Skip to main content
PulseScanner.io

Address

0xc2e73bb4064130f39cb9daa32a4d5699e2b0fb71
Current Holdings
$0.00
TXs sent
not counted
First Active
2026-08-10
block 27,253,002
Last Active
37 days ago
block 27,254,549
Funded By
not identified

Net worth historyi

No net-worth snapshots recorded yet
partial matchTokenTaxV3solc 0.8.34+commit.80d5c536runtime partial · creation partial
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import "./interfaces/TokenTypes.sol";
import {TokenTaxSwapLib} from "./TokenTaxSwapLib.sol";

interface IWETH_0 {
    function deposit() external payable;
    function withdraw(uint256 wad) external;
}

interface ISmartTokenFactory {
    function FEE() external view returns (uint256);
    function WALLET() external view returns (address);
    function STAKING_VAULT() external view returns (address);
    function NEON_LP_FEE() external view returns (uint256);
    function NEON_LP_RECEIVER() external view returns (address);
}
interface IERC20Burnable {
    function burn(uint256 amount) external;
}
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);
}

// lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol

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

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

// lib/openzeppelin-contracts/contracts/utils/Context.sol

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

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

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

    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
        if (_status == ENTERED) {
            revert ReentrancyGuardReentrantCall();
        }

        // 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;
    }
}
interface IUniswapV2Factory {
    event PairCreated(
        address indexed token0,
        address indexed token1,
        address pair,
        uint
    );

    function feeTo() external view returns (address);
    function feeToSetter() external view returns (address);

    function getPair(
        address tokenA,
        address tokenB
    ) external view returns (address pair);
    function allPairs(uint) external view returns (address pair);
    function allPairsLength() external view returns (uint);

    function createPair(
        address tokenA,
        address tokenB
    ) external returns (address pair);

    function setFeeTo(address) external;
    function setFeeToSetter(address) external;
}
interface IUniswapV2Pair {
    event Approval(address indexed owner, address indexed spender, uint value);
    event Transfer(address indexed from, address indexed to, uint value);

    function name() external pure returns (string memory);
    function symbol() external pure returns (string memory);
    function decimals() external pure returns (uint8);
    function totalSupply() external view returns (uint);
    function balanceOf(address owner) external view returns (uint);
    function allowance(
        address owner,
        address spender
    ) external view returns (uint);

    function approve(address spender, uint value) external returns (bool);
    function transfer(address to, uint value) external returns (bool);
    function transferFrom(
        address from,
        address to,
        uint value
    ) external returns (bool);

    function DOMAIN_SEPARATOR() external view returns (bytes32);
    function PERMIT_TYPEHASH() external pure returns (bytes32);
    function nonces(address owner) external view returns (uint);

    function permit(
        address owner,
        address spender,
        uint value,
        uint deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

    event Mint(address indexed sender, uint amount0, uint amount1);
    event Burn(
        address indexed sender,
        uint amount0,
        uint amount1,
        address indexed to
    );
    event Swap(
        address indexed sender,
        uint amount0In,
        uint amount1In,
        uint amount0Out,
        uint amount1Out,
        address indexed to
    );
    event Sync(uint112 reserve0, uint112 reserve1);

    function MINIMUM_LIQUIDITY() external pure returns (uint);
    function factory() external view returns (address);
    function token0() external view returns (address);
    function token1() external view returns (address);
    function getReserves()
        external
        view
        returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
    function price0CumulativeLast() external view returns (uint);
    function price1CumulativeLast() external view returns (uint);
    function kLast() external view returns (uint);

    function mint(address to) external returns (uint liquidity);
    function burn(address to) external returns (uint amount0, uint amount1);
    function swap(
        uint amount0Out,
        uint amount1Out,
        address to,
        bytes calldata data
    ) external;
    function skim(address to) external;
    function sync() external;

    function initialize(address, address) external;
}

interface IUniswapV2Router01 {
    function factory() external pure returns (address);
    function WETH() external pure returns (address);

    function addLiquidity(
        address tokenA,
        address tokenB,
        uint amountADesired,
        uint amountBDesired,
        uint amountAMin,
        uint amountBMin,
        address to,
        uint deadline
    ) external returns (uint amountA, uint amountB, uint liquidity);
    function addLiquidityETH(
        address token,
        uint amountTokenDesired,
        uint amountTokenMin,
        uint amountETHMin,
        address to,
        uint deadline
    )
        external
        payable
        returns (uint amountToken, uint amountETH, uint liquidity);
    function removeLiquidity(
        address tokenA,
        address tokenB,
        uint liquidity,
        uint amountAMin,
        uint amountBMin,
        address to,
        uint deadline
    ) external returns (uint amountA, uint amountB);
    function removeLiquidityETH(
        address token,
        uint liquidity,
        uint amountTokenMin,
        uint amountETHMin,
        address to,
        uint deadline
    ) external returns (uint amountToken, uint amountETH);
    function removeLiquidityWithPermit(
        address tokenA,
        address tokenB,
        uint liquidity,
        uint amountAMin,
        uint amountBMin,
        address to,
        uint deadline,
        bool approveMax,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external returns (uint amountA, uint amountB);
    function removeLiquidityETHWithPermit(
        address token,
        uint liquidity,
        uint amountTokenMin,
        uint amountETHMin,
        address to,
        uint deadline,
        bool approveMax,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external returns (uint amountToken, uint amountETH);
    function swapExactTokensForTokens(
        uint amountIn,
        uint amountOutMin,
        address[] calldata path,
        address to,
        uint deadline
    ) external returns (uint[] memory amounts);
    function swapTokensForExactTokens(
        uint amountOut,
        uint amountInMax,
        address[] calldata path,
        address to,
        uint deadline
    ) external returns (uint[] memory amounts);
    function swapExactETHForTokens(
        uint amountOutMin,
        address[] calldata path,
        address to,
        uint deadline
    ) external payable returns (uint[] memory amounts);
    function swapTokensForExactETH(
        uint amountOut,
        uint amountInMax,
        address[] calldata path,
        address to,
        uint deadline
    ) external returns (uint[] memory amounts);
    function swapExactTokensForETH(
        uint amountIn,
        uint amountOutMin,
        address[] calldata path,
        address to,
        uint deadline
    ) external returns (uint[] memory amounts);
    function swapETHForExactTokens(
        uint amountOut,
        address[] calldata path,
        address to,
        uint deadline
    ) external payable returns (uint[] memory amounts);

    function quote(
        uint amountA,
        uint reserveA,
        uint reserveB
    ) external pure returns (uint amountB);
    function getAmountOut(
        uint amountIn,
        uint reserveIn,
        uint reserveOut
    ) external pure returns (uint amountOut);
    function getAmountIn(
        uint amountOut,
        uint reserveIn,
        uint reserveOut
    ) external pure returns (uint amountIn);
    function getAmountsOut(
        uint amountIn,
        address[] calldata path
    ) external view returns (uint[] memory amounts);
    function getAmountsIn(
        uint amountOut,
        address[] calldata path
    ) external view returns (uint[] memory amounts);
}

// lib/openzeppelin-contracts/contracts/access/Ownable.sol

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

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * The initial owner is set to the address provided by the deployer. This can
 * later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract 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);
    }
}

// lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol

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

/**
 * @dev Interface for the optional metadata functions from the ERC-20 standard.
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the symbol of the token.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
}

// lib/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol
interface IUniswapV2Router02 is IUniswapV2Router01 {
    function removeLiquidityETHSupportingFeeOnTransferTokens(
        address token,
        uint liquidity,
        uint amountTokenMin,
        uint amountETHMin,
        address to,
        uint deadline
    ) external returns (uint amountETH);
    function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
        address token,
        uint liquidity,
        uint amountTokenMin,
        uint amountETHMin,
        address to,
        uint deadline,
        bool approveMax,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external returns (uint amountETH);

    function swapExactTokensForTokensSupportingFeeOnTransferTokens(
        uint amountIn,
        uint amountOutMin,
        address[] calldata path,
        address to,
        uint deadline
    ) external;
    function swapExactETHForTokensSupportingFeeOnTransferTokens(
        uint amountOutMin,
        address[] calldata path,
        address to,
        uint deadline
    ) external payable;
    function swapExactTokensForETHSupportingFeeOnTransferTokens(
        uint amountIn,
        uint amountOutMin,
        address[] calldata path,
        address to,
        uint deadline
    ) external;
}

// contracts/Tokens/Manager.sol
contract Manager {
    // For yield tax tokens
    struct UserYield {
        uint256 reflectionDebt;
    }
    struct YieldToken {
        address tokenAddress;
        uint256 reflectionsPerShareAmount;
    }
    YieldToken[] internal yieldTokens;

    // Default used only when older deploy params pass helpers = address(0).
    uint256 internal constant PRECISION = 10 ** 28;
    uint256 internal reflectionsPerShareAmount;
    uint256 internal wethYieldBalance;
    address internal constant DEFAULT_HELPERS = 0xd3397b405A2272F5C27fc673BE20579f22f59D6C;
    address internal constant wethAddress = 0xA1077a294dDE1B09bB078844df40758a5D0f9a27; // WPLS on PulseChain
    address internal immutable helpers;

    mapping(address => uint256) internal reflectionDebt;
    mapping(address => bool) public isReflectionExcluded;
    mapping(address => mapping(address => UserYield)) internal userYields;
    mapping(address => uint256[]) internal yieldTokenReflectionDebts;

    bool internal inSwap;

    modifier lockSwap() {
        inSwap = true;
        _;
        inSwap = false;
    }

    constructor(address helpers_) {
        helpers = helpers_ == address(0) ? DEFAULT_HELPERS : helpers_;
    }

    // ------------------------------------------ REFLECTIONS -------------------------------------------------//
    function getCurrentReflectionsPerShareAmount()
        external
        view
        returns (uint256)
    {
        return reflectionsPerShareAmount;
    }

    function isExcludedFromReflections(
        address account
    ) public view returns (bool) {
        return isReflectionExcluded[account];
    }

    function pendingReflections(address account) public view returns (uint256) {
        if (isExcludedFromReflections(account)) {
            return 0;
        }
        return cleanPendingReflections(account);
    }

    function cleanPendingReflections(
        address account
    ) internal view returns (uint256) {
        return
            Helpers(helpers).cleanPendingReflections(
                account,
                address(this),
                reflectionsPerShareAmount,
                reflectionDebt[account],
                PRECISION
            );
    }

    function updateAndClaimReflections(
        address from,
        address to,
        address deployer
    )
        internal
        returns (uint256 fromAmount, uint256 toAmount, uint256 deployerAmount)
    {
        if (from == to) {
            fromAmount = isExcludedFromReflections(from)
                ? 0
                : pendingReflections(from);
            toAmount = 0; // Set to zero to avoid double claiming
        } else {
            fromAmount = isExcludedFromReflections(from)
                ? 0
                : pendingReflections(from);
            toAmount = isExcludedFromReflections(to)
                ? 0
                : pendingReflections(to);
        }
        // (REFL-02) Respect the reflection-exclusion flag for the deployer leg
        // too. cleanPendingReflections() bypasses the isExcludedFromReflections
        // check, so an excluded deployer would otherwise still accrue/claim.
        deployerAmount = (deployer == from ||
            deployer == to ||
            isExcludedFromReflections(deployer))
            ? 0
            : cleanPendingReflections(deployer);
        reflectionDebt[deployer] = reflectionsPerShareAmount;
        reflectionDebt[from] = reflectionsPerShareAmount;
        reflectionDebt[to] = reflectionsPerShareAmount;
    }

    // function tokenPendingReflections() public view returns (uint256) {
    //     uint256 currentBalance = IERC20(address(this)).balanceOf(address(this));
    //     uint256 newReflectionDebt = reflectionsPerShareAmount;
    //     if (newReflectionDebt <= reflectionDebt[address(this)]) {
    //         return 0;
    //     }
    //     return (newReflectionDebt - reflectionDebt[address(this)]) * currentBalance / PRECISION;
    // }

    // ------------------------------------------ YIELD TOKENS REFLECTIONS -------------------------------------------------//

    function addYieldToken(
        address tokenAddress
    ) internal returns (uint256 tokenIndex) {
        for (uint256 i = 0; i < yieldTokens.length; i++) {
            if (yieldTokens[i].tokenAddress == tokenAddress) {
                return i;
            }
        }

        yieldTokens.push(
            YieldToken({
                tokenAddress: tokenAddress,
                reflectionsPerShareAmount: 0
            })
        );

        return yieldTokens.length - 1;
    }

    function pendingYields(
        address account,
        uint256 tokenIndex
    ) public view returns (uint256) {
        if (tokenIndex >= yieldTokenReflectionDebts[account].length) {
            return 0;
        }
        return
            Helpers(helpers).pendingYields(
                account,
                address(this),
                yieldTokens[tokenIndex].reflectionsPerShareAmount,
                yieldTokenReflectionDebts[account][tokenIndex],
                PRECISION
            );
    }

    function updateAndClaimYield(
        address from,
        address to,
        address deployer
    ) internal {
        for (uint256 i = 0; i < yieldTokens.length; i++) {
            while (yieldTokenReflectionDebts[from].length <= i) {
                yieldTokenReflectionDebts[from].push(
                    yieldTokens[i].reflectionsPerShareAmount
                );
            }
            while (yieldTokenReflectionDebts[to].length <= i) {
                yieldTokenReflectionDebts[to].push(
                    yieldTokens[i].reflectionsPerShareAmount
                );
            }
            while (yieldTokenReflectionDebts[deployer].length <= i) {
                yieldTokenReflectionDebts[deployer].push(
                    yieldTokens[i].reflectionsPerShareAmount
                );
            }

            uint256 fromAmount = isExcludedFromReflections(from)
                ? 0
                : pendingYields(from, i);
            uint256 toAmount = 0; // Initialize to 0

            if (from != to) {
                toAmount = isExcludedFromReflections(to)
                    ? 0
                    : pendingYields(to, i);
            }

            uint256[] memory transferAmounts = new uint256[](2);
            address[] memory recipients = new address[](2);
            uint256 recipientCount = 0;
            if (fromAmount > 0) {
                transferAmounts[recipientCount] = fromAmount;
                recipients[recipientCount] = from;
                recipientCount++;
            }
            if (toAmount > 0) {
                transferAmounts[recipientCount] = toAmount;
                recipients[recipientCount] = to;
                recipientCount++;
            }

            for (uint256 j = 0; j < recipientCount; j++) {
                if (transferAmounts[j] > 0) {
                    // (INC-04) Checks-Effects-Interactions: checkpoint the debt BEFORE the
                    // external token transfer so a hooked (ERC777-style) yield token cannot
                    // re-enter claimYield() and be paid the same pending twice. On re-entry
                    // pendingYields() reads the already-advanced debt and returns 0.
                    uint256 prevDebt = yieldTokenReflectionDebts[recipients[j]][i];
                    yieldTokenReflectionDebts[recipients[j]][
                        i
                    ] = yieldTokens[i].reflectionsPerShareAmount;
                    try
                        IERC20(yieldTokens[i].tokenAddress).transfer(
                            recipients[j],
                            transferAmounts[j]
                        )
                    {
                        if (yieldTokens[i].tokenAddress == wethAddress) {
                            wethYieldBalance -= transferAmounts[j];
                        }
                    } catch {
                        // Payout genuinely failed: roll the checkpoint back so the pending
                        // stays claimable next time.
                        yieldTokenReflectionDebts[recipients[j]][i] = prevDebt;
                    }
                }
            }
        }
    }

    function getYieldTokens() public view returns (YieldToken[] memory) {
        return yieldTokens;
    }

    function getYieldTokenReflectionDebts(
        address account
    ) public view returns (uint256[] memory) {
        return yieldTokenReflectionDebts[account];
    }
}

// contracts/Tokens/ERC20.sol

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

/**
 * @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}.
     *
     * All two of these 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;
    }

    /**
     * @dev See {IERC20-totalSupply}.
     */
    function totalSupply() public view virtual returns (uint256) {
        return _totalSupply;
    }

    /**
     * @dev See {IERC20-balanceOf}.
     */
    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;
    }

    /**
     * @dev See {IERC20-allowance}.
     */
    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 virtual {
        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);
            }
        }
    }
}

// contracts/Tokens/SmartTrader.sol
contract SmartTrader is Ownable {
    constructor() Ownable(msg.sender) {}

    function swapExactTokensForTokensSupportingFeeOnTransferTokens(
        address _router,
        address _receiver,
        uint256 amountIn,
        address[] memory path
    ) public {
        // INC-08: forward only the freshly-swapped delta, not the whole balance,
        // so any tokens already sitting in this helper aren't leaked to _receiver.
        IERC20 outToken = IERC20(path[path.length - 1]);
        uint256 beforeBal = outToken.balanceOf(address(this));
        IERC20(path[0]).transferFrom(msg.sender, address(this), amountIn);
        IERC20(path[0]).approve(_router, amountIn);

        IUniswapV2Router02(_router)
            .swapExactTokensForTokensSupportingFeeOnTransferTokens(
                amountIn,
                0,
                path,
                address(this),
                block.timestamp + 30
            );

        uint256 receivedAmount = outToken.balanceOf(address(this)) - beforeBal;
        outToken.transfer(_receiver, receivedAmount);
    }

    function swapExactTokensForETHSupportingFeeOnTransferTokens(
        address _router,
        address _receiver,
        uint256 amountIn,
        address[] calldata path
    ) public {
        IERC20(path[0]).transferFrom(msg.sender, address(this), amountIn);
        IERC20(path[0]).approve(_router, amountIn);

        IUniswapV2Router02(_router)
            .swapExactTokensForETHSupportingFeeOnTransferTokens(
                amountIn,
                0,
                path,
                _receiver,
                block.timestamp + 30
            );

        payable(_receiver).transfer(address(this).balance);
    }

    function buyToken(
        address _router,
        address _receiver,
        uint256 amountIn,
        address[] memory path
    ) public {
        IERC20(path[0]).transferFrom(msg.sender, address(this), amountIn);
        IERC20(path[0]).approve(_router, amountIn);
        IUniswapV2Router02(_router)
            .swapExactTokensForTokensSupportingFeeOnTransferTokens(
                amountIn,
                0,
                path,
                _receiver,
                block.timestamp + 30
            );
    }

    function addLiquidity(
        address _router,
        address tokenA,
        address tokenB,
        uint256 amountA,
        uint256 amountB,
        address lpReceiver
    ) public {
        IERC20(tokenA).transferFrom(msg.sender, address(this), amountA);
        IERC20(tokenB).transferFrom(msg.sender, address(this), amountB);
        IERC20(tokenA).approve(_router, amountA);
        IERC20(tokenB).approve(_router, amountB);
        IUniswapV2Router02(_router).addLiquidity(
            tokenA, tokenB, amountA, amountB, 0, 0, lpReceiver, block.timestamp + 30
        );
        // Return any dust
        uint256 dustA = IERC20(tokenA).balanceOf(address(this));
        if (dustA > 0) IERC20(tokenA).transfer(msg.sender, dustA);
        uint256 dustB = IERC20(tokenB).balanceOf(address(this));
        if (dustB > 0) IERC20(tokenB).transfer(msg.sender, dustB);
    }

    function withdrawPLS() external onlyOwner {
        uint256 balance = address(this).balance;
        require(balance > 0, "No PLS to withdraw");
        payable(owner()).transfer(balance);
    }

    function withdrawToken(address tokenAddress) external onlyOwner {
        IERC20 token = IERC20(tokenAddress);
        uint256 balance = token.balanceOf(address(this));
        require(balance > 0, "No tokens to withdraw");
        token.transfer(owner(), balance);
    }

    receive() external payable {}
}
interface IWETH_1 {
    function deposit() external payable;
    function withdraw(uint256 wad) external;
}
contract TokenTaxV3 is ERC20, Ownable, Manager {
    //
    //       ███╗   ██╗███████╗██╗  ██╗██╗ ██████╗ ███╗   ██╗
    //       ████╗  ██║██╔════╝╚██╗██╔╝██║██╔═══██╗████╗  ██║
    //       ██╔██╗ ██║█████╗   ╚███╔╝ ██║██║   ██║██╔██╗ ██║
    //       ██║╚██╗██║██╔══╝   ██╔██╗ ██║██║   ██║██║╚██╗██║
    //       ██║ ╚████║███████╗██╔╝ ██╗██║╚██████╔╝██║ ╚████║
    //       ╚═╝  ╚═══╝╚══════╝╚═╝  ╚═╝╚═╝ ╚═════╝ ╚═╝  ╚═══╝
    //
    //            * .    *       *    .      * .      *
    //     .   *         *              .        .  *
    //                    .                *         .
    //    .    *     *         *    .   *          .  *
    //         _____                         _____
    //       .|     |.    *     .   *     .|     |.
    //       ||     ||        .          *||     ||
    //       || ___ ||  *         .       || ___ ||
    //  *    |:_____:|        *           |:_____:|
    //       |_______|    .   *      *    |_______|. *
    //  .    | .   . |              .     | .   . |
    //       | .   . |   *    .           | .   . |    *
    //       '._____.'.       *     *    .'._____.'.
    //
    // Revolutionary Hyper-Deflationary and Bonded Liquidity Ecosystem
    //
    // Telegram: https://t.me/NexionPulse
    // Website: https://nexionpulse.com/
    // X: https://x.com/nexionpulse
    // Contract: 0xF2Da3942616880E52e841E5C504B5A9Fba23FFF0
    //

    string public constant VERSION = "2.8";

    uint256 public initialSupply;
    bool public tradingEnabled;
    uint64 public enableTradingAt; // timestamp for auto-enable (0 = manual only)

    error TradingDisabled();
    error AlreadyEnabled();
    error InvalidArg();
    // Size: shared custom errors replacing revert strings (each string is raw
    // runtime bytecode; a custom error is a 4-byte selector). Reused broadly.
    error Unauthorized();
    error NothingToWithdraw();
    error TaxTooHigh();
    error TransferFailed();
    event TradingEnabled();

    address payable private smartTrader;
    address private deployer;
    address private factory;

    // Routers scanned by Helpers.getBestPair() to find the deepest TOKEN/WPLS pair
    // when swapping rewardInPls / Liquify tax legs to native PLS. MUST include every
    // DEX a token from this launchpad can graduate to — otherwise getBestPair returns
    // address(0), emits noRouter(), and the tax accrues forever instead of reaching
    // its receiver (e.g. a staking vault). TrenchDex is the launchpad's own graduation
    // venue, so it leads the list; PulseX V1/V2 + others stay as fallbacks.
    address[] private routers = [
        0xB75Cb05eCEf509df852270aC572cc1bde48F9e7E, // TrenchDex router (launchpad graduation target)
        0x98bf93ebf5c380C0e6Ae8e192A7e2AE08edAcc02, // PulseX V2 router
        0x165C3410fC91EF562C50559f7d2289fEbed552d9, // PulseX V1 router
        0xcC73b59F8D7b7c532703bDfea2808a28a488cF47,
        0xeB45a3c4aedd0F47F345fB4c8A1802BB5740d725
    ];
    mapping(address => bool) isTaxExcluded;
    /// @dev (G2) Deprecated storage slot — must remain to preserve UUPS layout.
    ///      Previously written on every taxed transfer; now passed as a function
    ///      parameter through processAccumulatedTaxes / Helpers.getProcessingAmount.
    ///      Reads still happen via the legacy internal getProcessingAmount(uint256)
    ///      helper below, but no on-path code writes to this slot anymore.
    uint256 private __deprecated_currentSwapAmount;
    uint256 private accumulatedFee;
    // Parallel platform-style bucket for the Neon LP autoBuy/autoLP feed.
    // Funded the same way as `accumulatedFee` (bps of each user tax) but
    // routed to NEON_LP_RECEIVER instead of getWallet() during processAccumulatedTaxes.
    // Never cannibalises the creator's tax bucket.
    uint256 private accumulatedNeonFee;

    bool private shouldAccumulateFee;
    bool private reflectionsEnabled;
    bool private yieldEnabled;
    bool private firstPairInteractionHappened;
    bool private processedTaxesInTx;

    /// @notice When non-zero, this is the bonding curve that minted the supply AND
    ///         curve-phase trades against it are taxed (creator opt-in at create time).
    ///         Zero => curve trades are untaxed and tax only starts at the DEX pair,
    ///         which is the pre-existing behaviour for every already-launched token.
    /// @dev    Repurposed from the former `launchpad` field. The old one-way
    ///         `activateTax()` flow was provably dead — both factory call sites passed
    ///         `launchpad: address(0)`, so `taxLive` was always true from construction.
    ///         Reusing the slot keeps `DeployTokenParams` byte-identical, which means no
    ///         new TokenDeployer and no change to the deployer's `abi.encode(p)` layout.
    address public immutable curveTaxVenue;
    /// @dev Tax is live from construction. Kept as a constant (not storage) so existing
    ///      off-chain readers of `taxLive()` keep working while freeing runtime bytes —
    ///      this contract sits ~11 bytes under the EIP-170 cap, so every byte is paid for.
    bool public constant taxLive = true;

    // Add all the events for tax tracking
    event TaxCollected(
        uint256 indexed taxId,
        Helpers.TaxType taxType,
        Helpers.TaxMoment taxMoment,
        address from,
        address to,
        uint256 amount,
        uint256 timestamp
    );
    event noRouter();

    event BurnTaxProcessed(uint256 amount, uint256 timestamp);

    event ExternalBurnProcessed(
        uint256 tokenAmount,
        uint256 taxid,
        uint256 wethAmount,
        address receiver,
        address tokenToBurn,
        uint256 timestamp
    );

    event ReflectionTaxProcessed(
        uint256 amount,
        uint256 newReflectionsPerShareAmount,
        uint256 timestamp
    );

    event ReflectionDistributed(
        address from,
        address to,
        uint256 fromAmount,
        uint256 toAmount,
        uint256 deployerAmount,
        uint256 reflectionsPerShareAmount,
        uint256 timestamp
    );

    event YieldTaxProcessed(
        uint256 tokenAmount,
        uint256 wethAmount,
        address yieldTokenAddress,
        uint256 timestamp
    );

    event YieldDistributed(
        address tokenAddress,
        address recipient,
        uint256 amount,
        uint256 reflectionsPerShareAmount,
        uint256 timestamp
    );
    event YieldSwapFailed(
        address tokenAddress,
        uint256 wplsAmount,
        uint256 timestamp
    );

    // (V3 byte budget) `private`, not `public`: the auto-generated `taxes(uint256)` getter
    // cost ~70 runtime bytes on a contract that is 24 bytes from the EIP-170 cap, and it has
    // no consumer — nothing in cabal declares `function taxes(`, and the frontend reads the
    // whole array through `getTaxes()` (which is unchanged and still public). Removing an
    // indexed getter nobody calls is the cheapest byte on the table.
    Helpers.Tax[] private taxes;
    error ZeroTaxPercentage();

    uint256 public totalSupport; // Track external burn taxes
    uint256 public totalReflection; // Track reflection taxes
    uint256 public totalYield; // Track yield taxes
    uint256 public totalLiquify; // Track liquify taxes

    address internal constant deadAddress = 0x000000000000000000000000000000000000dEaD;

    constructor(
        DeployTokenParams memory p
    ) ERC20(p.name_, p.symbol_) Ownable(p.owner_) Manager(p.helpers) {
        tradingEnabled = p.tradingEnabled;
        enableTradingAt = p.enableTradingAt;
        _mint(p.mintTo, p.initialSupply);

        deployer = p.mintTo;
        initialSupply = p.initialSupply;
        smartTrader = payable(p.smartTrader);
        factory = p.factory;

        // Non-zero only when the creator opted into curve-phase taxes; the value is the
        // curve that mints and holds the supply (`p.mintTo`).
        curveTaxVenue = p.launchpad;

        // Inline taxesInitialize (can't rely on deployed Helpers for Liquify enum)
        // (G4) Zero-percentage check now lives inside _initializeTaxes; the
        // duplicate post-loop has been removed.
        _initializeTaxes(p.taxes);

        inititlizeTaxExclusions();

        if (reflectionsEnabled || yieldEnabled) {
            initializeReflectionExclusions();
            // (D2) The curve holds the entire unsold supply, so if it were a reflection /
            // yield participant it would absorb the overwhelming majority of every
            // curve-phase payout and strand it: `_claimReflections` ships the share
            // straight back into the curve's balance, while the curve's own accounting
            // only ever moves `virtualReserveToken`. Everything above that is
            // unrecoverable once the token graduates. Same guard covers the yield leg,
            // which gates payouts on `isExcludedFromReflections`.
            // Reads `p.launchpad`, not the immutable: reading an immutable inside the
            // constructor only became legal in solc 0.8.21.
            if (p.launchpad != address(0))
                isReflectionExcluded[p.launchpad] = true;
        }

        // (INC-01) No standing allowance to smartTrader. Each swap-back / buyback / liquify
        // grants an EXACT, single-operation allowance and resets to 0 on failure (fully
        // consumed by transferFrom on success), so a caller-supplied smartTrader can never
        // drain accrued reserves.
    }

    function _initializeTaxes(Helpers.Tax[] memory _taxes) internal {
        uint256 totalTaxPct;

        for (uint256 i; i < _taxes.length; i++) {
            taxes.push(_taxes[i]);
            taxes[i].id = i;

            // (G4) Hoisted from the second constructor loop
            if (_taxes[i].percentage == 0) revert ZeroTaxPercentage();
            if (_taxes[i].percentage > 5000) revert TaxTooHigh();

            if (_taxes[i].taxMoment == Helpers.TaxMoment.Both) {
                totalTaxPct += _taxes[i].percentage * 2;
            } else {
                totalTaxPct += _taxes[i].percentage;
            }

            if (_taxes[i].taxType == Helpers.TaxType.Reflection) {
                reflectionsEnabled = true;
            }

            if (_taxes[i].taxType == Helpers.TaxType.Yield) {
                yieldEnabled = true;
                if (_taxes[i].tokenAddress != address(0)) {
                    addYieldToken(_taxes[i].tokenAddress);
                }
            }

            if (_taxes[i].taxType == Helpers.TaxType.ExternalBurn) {
                if (_taxes[i].receiver == address(0)) revert InvalidArg();
                if (_taxes[i].tokenAddress == address(0)) revert InvalidArg();
                shouldAccumulateFee = true;
            } else if (_taxes[i].taxType == Helpers.TaxType.Dev) {
                if (_taxes[i].receiver == address(0)) revert InvalidArg();
                if (_taxes[i].rewardInPls) {
                    shouldAccumulateFee = true;
                }
            } else if (_taxes[i].taxType == Helpers.TaxType.Yield) {
                if (_taxes[i].tokenAddress == address(0)) revert InvalidArg();
                shouldAccumulateFee = true;
            } else if (_taxes[i].taxType == Helpers.TaxType.Liquify) {
                shouldAccumulateFee = true;
            }
        }

        if (totalTaxPct > 8000) revert TaxTooHigh();
    }

    function _transfer(
        address from,
        address to,
        uint256 value
    ) internal override {
        processedTaxesInTx = false;

        // (gas #7) Cache `tradingEnabled` and `isTaxExcluded[from]` once —
        // both are touched multiple times below, and caching saves 2 SLOADs
        // per transfer on the common taxed path.
        bool _trading = tradingEnabled;
        bool _fromExcluded = isTaxExcluded[from];

        // Auto-enable trading if timer has passed
        if (!_trading && enableTradingAt > 0 && block.timestamp >= enableTradingAt) {
            tradingEnabled = true;
            _trading = true;
            emit TradingEnabled();
        }

        if (isDeadAddress(to)) {
            // (REFL-01) The DEAD-burn shortcut mutates `from`'s balance without
            // running _claimReflections. Settle `from`'s reflection debt first
            // (credit pending against the pre-burn balance, then checkpoint) so
            // it cannot over-claim later. `to` is a dead address (always
            // reflection-excluded / not a holder), so no settle is needed there.
            _settleReflections(from);
            super._burn(from, value);
            return;
        }

        // Block non-excluded transfers when trading is disabled
        if (!_trading && !_fromExcluded) revert TradingDisabled();

        bool _isPairTo = isPair(to);

        // Curve-phase trade leg. Buys are curve->trader, sells are trader->curve.
        // Four carve-outs matter here:
        //  • `curveTaxVenue == 0` (every existing token, and any new token that did not
        //    opt in) leaves `_curveLeg` false, so the gate below is bit-for-bit the old one.
        //  • curve->pair is the graduation LP seed, NOT a trade — `_isPairTo` excludes it,
        //    otherwise graduation would tax its own seeding transfer and under-fill the pool.
        //  • the curve is `deployer` and therefore permanently tax-excluded, so a curve leg
        //    has to bypass BOTH the exclusion checks and `firstPairInteractionHappened`
        //    (which stays false until the DEX pair exists) or no tax could ever fire.
        //  • (D1) but ONLY for real traders: the curve also pays out to tax-excluded
        //    infrastructure (graduation fee harvester, creator-fee splitter, smartTrader,
        //    this contract, the factory) and receives from it. Those legs are internal
        //    plumbing, not trades, so `!isTaxExcluded[to]` / `!_fromExcluded` keep them
        //    untaxed exactly as they are today.
        address _curve = curveTaxVenue;
        bool _curveLeg = _curve != address(0) &&
            ((from == _curve && !_isPairTo && !isTaxExcluded[to]) ||
                (to == _curve && !_fromExcluded));

        if (
            taxes.length == 0 ||
            inSwap ||
            (!_curveLeg &&
                (!firstPairInteractionHappened || _fromExcluded || isTaxExcluded[to]))
        ) {
            if (!firstPairInteractionHappened && _isPairTo)
                firstPairInteractionHappened = true;

            _claimYield(from, to);
            // (REFL-01) This early-return path (tax-excluded sender/receiver,
            // pre-first-pair, or inSwap) mutates balances WITHOUT running
            // _claimReflections. Settle BOTH endpoints' reflection debt before
            // the transfer so a receiver from a tax-excluded wallet cannot
            // over-claim reflections on the newly-received balance and drain
            // the contract's shared self-balance. Settling before the mutation
            // credits pending against the correct (pre-transfer) balances.
            if (from != to) {
                _settleReflections(from);
                _settleReflections(to);
            } else {
                _settleReflections(from);
            }
            super._transfer(from, to, value);
            return;
        }

        if (_isPairTo && !isReflectionExcluded[to])
            isReflectionExcluded[to] = true;

        // (gas #3A) Compute isBuy/isSell ONCE here and thread them through
        // processTaxes + the post-tax gating block. Prior code called
        // Helpers.isBuy twice per taxed transfer (once inside processTaxes,
        // once after). Now it's a single STATICCALL, with isSell only
        // evaluated when isBuy is false (preserves the G3 short-circuit).
        // On a curve leg the venue is the curve, not a pair, so Helpers' pair-only
        // classification would score the trade as a plain transfer (0% for most tokens).
        // Classify inline instead — this also avoids redeploying HelpersV2, whose
        // constructor `routers` list is stale.
        bool _isBuy  = _curveLeg ? from == _curve : isBuy(from, to);
        bool _isSell = _isBuy
            ? false
            : (_curveLeg ? to == _curve : isSell(from, to));

        // (G2) `value` is plumbed directly through processAccumulatedTaxes
        // instead of via the deprecated currentSwapAmount storage slot.
        uint256 amountAfterTaxs = processTaxes(from, to, value, _isBuy, _isSell);

        // (gas #6) `hasAccumulatedTaxes()` was provably dead: it only returned
        // true when some tax.amountAccumulated > 0, and amountAccumulated is
        // only written by the four processors (ExternalBurn / Yield / Liquify
        // / Dev+rewardInPls) that set `shouldAccumulateFee = true` in the
        // constructor. `firstPairInteractionHappened` and `!inSwap` are also
        // already guaranteed by the early-return guard above. Collapsed to a
        // single boolean check.
        // `processAccumulatedTaxes` swaps the accrued balance out through a TOKEN/WPLS
        // pair. During the curve phase no such pair exists yet, so a flush here would
        // find no router, emit noRouter() and waste gas at best. Let the Liquify / Yield /
        // ExternalBurn / rewardInPls legs ACCRUE on the curve and flush on the first
        // post-graduation sell instead. Burn / Reflect / in-token Dev legs are
        // self-contained and settle immediately, so they are unaffected.
        if (shouldAccumulateFee && !processedTaxesInTx && !_isBuy && !_curveLeg) {
            processAccumulatedTaxes(value);
            processedTaxesInTx = true;
        }

        _claimYield(from, to);
        _claimReflections(from, to);

        super._transfer(from, to, amountAfterTaxs);
    }

    /// @dev Bundle of loop-invariant context for _processOneTaxLeg. Passed
    ///      as a single memory struct to keep the per-call argument count
    ///      under the non-via-ir stack-too-deep ceiling.
    struct TaxLegCtx {
        address from;
        address to;
        uint256 amount;
        bool isBuy;
        bool isSell;
        uint256 neonFeeBps;
        uint256 fee;
    }

    function processTaxes(
        address from,
        address to,
        uint256 amount,
        bool _isBuy,
        bool _isSell
    ) internal returns (uint256) {
        uint256 totalTaxAmount;
        uint256 totalFee;
        uint256 totalNeonFee;

        TaxLegCtx memory ctx;
        ctx.from = from;
        ctx.to = to;
        ctx.amount = amount;

        // (gas #3A) isBuy/isSell are now computed once by the caller and
        // passed in, eliminating a duplicate Helpers.isBuy STATICCALL.
        // The G3 short-circuit is preserved at the caller.
        ctx.isBuy = _isBuy;
        ctx.isSell = _isSell;

        // Parallel Neon LP fee, taken in bps of each user-tax slice (NOT volume,
        // NOT from the platform Fee bucket, NOT from creator's leftover WPLS).
        // Only fires when shouldAccumulateFee is true — i.e. the token has a
        // tax type that requires the WPLS swap pipeline. Otherwise the neon
        // tokens would have no path out and would just sit in the contract.
        if (shouldAccumulateFee && getNeonLpReceiver() != address(0)) {
            ctx.neonFeeBps = getNeonLpFee();
        }

        // (G1) Read the platform FEE once per transfer instead of once per
        //      tax leg. Saves N-1 STATICCALLs to the factory per taxed trade.
        // (#4) Cache the taxes array to memory once. processTaxes only reads
        //      immutable fields (taxType/taxMoment/percentage/receiver/etc.);
        //      writes to amountAccumulated still go through storage in
        //      processTaxType via taxes[tax.id], so accounting is unaffected.
        ctx.fee = getFee();
        Helpers.Tax[] memory _cachedTaxes = taxes;
        uint256 len = _cachedTaxes.length;

        for (uint256 i; i < len; i++) {
            (uint256 _taxAmount, uint256 _Fee, uint256 _neonFee) = _processOneTaxLeg(
                ctx, _cachedTaxes[i]
            );
            totalTaxAmount += _taxAmount;
            totalFee       += _Fee;
            totalNeonFee   += _neonFee;
        }

        if (totalFee > 0) {
            if (shouldAccumulateFee) {
                super._transfer(from, address(this), totalFee);
                accumulatedFee += totalFee;
            } else {
                _transferPlatformFee(from, totalFee);
            }
        }

        if (totalNeonFee > 0) {
            // Neon fee always accumulates for the swap pipeline (gated above
            // on shouldAccumulateFee, so we know the swap path will run).
            super._transfer(from, address(this), totalNeonFee);
            accumulatedNeonFee += totalNeonFee;
        }

        return amount - totalTaxAmount - totalFee - totalNeonFee;
    }

    /// @dev Per-tax-leg helper extracted from processTaxes() to keep that
    ///      frame under the stack-too-deep limit. Computes the user-tax /
    ///      dev-fee / neon-fee triple, routes the user-tax portion to its
    ///      destination, and returns the three amounts so the caller can
    ///      accumulate totals. Loop-invariant context (from/to/amount/
    ///      isBuy/isSell/neonFeeBps/fee) is bundled into TaxLegCtx to keep
    ///      the argument count below the non-via-ir stack ceiling.
    function _processOneTaxLeg(
        TaxLegCtx memory ctx,
        Helpers.Tax memory tax
    ) internal returns (uint256 taxAmount, uint256 Fee, uint256 neonFee) {
        bool fired;
        if (tax.taxMoment == Helpers.TaxMoment.Both) {
            (taxAmount, Fee) = calculateTaxAmount(ctx.amount, tax, ctx.fee);
            fired = true;
        } else if (tax.taxMoment == Helpers.TaxMoment.Buy && ctx.isBuy) {
            (taxAmount, Fee) = calculateTaxAmount(ctx.amount, tax, ctx.fee);
            fired = true;
        } else if (tax.taxMoment == Helpers.TaxMoment.Sell && ctx.isSell) {
            (taxAmount, Fee) = calculateTaxAmount(ctx.amount, tax, ctx.fee);
            fired = true;
        }
        if (!fired) return (0, 0, 0);

        // Slice neon out of the user-tax portion (NOT out of dev Fee).
        if (ctx.neonFeeBps > 0 && taxAmount > 0) {
            neonFee = (taxAmount * ctx.neonFeeBps) / 10000;
            taxAmount -= neonFee;
        }

        processTaxType(ctx.from, ctx.to, taxAmount, tax);
    }

    /// @dev (G1) Now takes the cached platform fee as a parameter rather than
    ///      reading it via an external call to the factory on every call.
    function calculateTaxAmount(
        uint256 originalAmount,
        Helpers.Tax memory tax,
        uint256 fee_
    ) internal view returns (uint256 taxAmount, uint256 Fee) {
        return
            Helpers(helpers).calculateTaxAmount(
                originalAmount,
                tax.percentage,
                fee_,
                true,
                10000
            );
    }

    /// @param to (#2) Real transfer recipient — used as the TaxCollected.to
    ///           field instead of msg.sender. Off-chain indexers reading the
    ///           previous (broken) field were always seeing the router on
    ///           swaps. New deployments emit the correct counterparty.
    function processTaxType(
        address from,
        address to,
        uint256 taxAmount,
        Helpers.Tax memory tax
    ) internal {
        // Emit tax collection event for all types
        emit TaxCollected(
            tax.id,
            tax.taxType,
            tax.taxMoment,
            from,
            to,
            taxAmount,
            block.timestamp
        );

        if (tax.taxType == Helpers.TaxType.Burn) {
            processBurnTax(from, taxAmount);
        } else if (tax.taxType == Helpers.TaxType.Reflection) {
            processReflectionTax(from, taxAmount);
        } else if (tax.taxType == Helpers.TaxType.Dev) {
            processTreasuryTax(from, taxAmount, tax);
        } else if (tax.taxType == Helpers.TaxType.ExternalBurn) {
            processSupportTax(from, taxAmount, tax);
        } else if (tax.taxType == Helpers.TaxType.Yield) {
            processYieldTax(from, taxAmount, tax);
        } else if (tax.taxType == Helpers.TaxType.Liquify) {
            processLiquifyTax(from, taxAmount, tax);
        }
    }

    function burn(uint256 amount) public {
        emit BurnTaxProcessed(amount, block.timestamp);
        super._burn(msg.sender, amount);
    }

    function processBurnTax(address from, uint256 taxAmount) internal {
        emit BurnTaxProcessed(taxAmount, block.timestamp);
        super._burn(from, taxAmount);
    }

    function processTreasuryTax(
        address from,
        uint256 taxAmount,
        Helpers.Tax memory tax
    ) internal {
        if (!isTaxExcluded[tax.receiver]) isTaxExcluded[tax.receiver] = true;
        if (tax.rewardInPls) {
            super._transfer(from, address(this), taxAmount);
            taxes[tax.id].amountAccumulated += taxAmount;
        } else {
            // (INC-03) The Dev receiver gets tokens via checkpoint-bypassing super._transfer.
            // Reflection-exclude it and checkpoint its debt BEFORE the mutation so it can
            // never over-claim the reflection pool on a later transfer.
            _excludeReflectionReceiver(tax.receiver);
            super._transfer(from, tax.receiver, taxAmount);
        }
    }

    /// @dev (INC-03) Idempotently reflection-exclude an address that receives tokens through
    ///      a checkpoint-bypassing super._transfer (fee / dev receivers), checkpointing its
    ///      debt to the current index so it does not accrue retroactive reflections on the
    ///      incoming balance.
    function _excludeReflectionReceiver(address account) internal {
        if (!reflectionsEnabled) return;
        if (account == address(0) || account == address(this)) return;
        if (!isReflectionExcluded[account]) {
            isReflectionExcluded[account] = true;
            reflectionDebt[account] = reflectionsPerShareAmount;
        }
    }

    function processReflectionTax(address from, uint256 taxAmount) internal {
        super._transfer(from, address(this), taxAmount);
        // (D4) The curve is reflection-EXCLUDED (see the constructor), so it must also
        // leave the reflection DENOMINATOR. During the curve phase the curve holds the
        // overwhelming majority of the supply; leaving it in `supply` apportions ~99% of
        // every curve-phase reflection to a holder that can never claim it, and that
        // share stays locked in this contract forever. Legacy-safe by construction:
        // `curveTaxVenue` is address(0) on every non-opt-in token and `balanceOf` of the
        // zero address is always 0 (mints/burns adjust `_totalSupply`, never that slot),
        // and after graduation the curve's balance is 0 — so this is a no-op subtraction
        // on both paths. Cannot underflow: both terms are balances of distinct accounts.
        // Keyed off the LIVE exclusion flag, not off `curveTaxVenue != 0`: the owner can
        // re-include the curve through setReflectionExclusion, and a denominator that
        // dropped the curve while the curve was still accruing would let it claim against
        // an index it was never counted in — draining this contract's shared self-balance
        // and the reflections owed to real holders. Tying the two together keeps them in
        // lockstep in both directions.
        address _c = curveTaxVenue;
        uint256 supply = totalSupply() - balanceOf(address(this));
        if (isReflectionExcluded[_c]) supply -= balanceOf(_c);

        if (supply > 0) {
            reflectionsPerShareAmount += (taxAmount * PRECISION) / supply;
            totalReflection += taxAmount;
        }

        emit ReflectionTaxProcessed(
            taxAmount,
            reflectionsPerShareAmount,
            block.timestamp
        );
    }

    function processSupportTax(
        address from,
        uint256 taxAmount,
        Helpers.Tax memory tax
    ) internal lockSwap {
        super._transfer(from, address(this), taxAmount);
        taxes[tax.id].amountAccumulated += taxAmount;
        totalSupport += taxAmount;
        emit ExternalBurnProcessed(
            taxAmount,
            tax.id,
            0,
            tax.receiver,
            tax.tokenAddress,
            block.timestamp
        );
    }

    function processYieldTax(
        address from,
        uint256 taxAmount,
        Helpers.Tax memory tax
    ) internal lockSwap {
        super._transfer(from, address(this), taxAmount);
        taxes[tax.id].amountAccumulated += taxAmount;
        totalYield += taxAmount;
        emit YieldTaxProcessed(
            taxAmount,
            0, // wethAmount (will be updated when processed)
            tax.tokenAddress,
            block.timestamp
        );
    }

    function processLiquifyTax(
        address from,
        uint256 taxAmount,
        Helpers.Tax memory tax
    ) internal lockSwap {
        super._transfer(from, address(this), taxAmount);
        taxes[tax.id].amountAccumulated += taxAmount;
        totalLiquify += taxAmount;
    }

    function processAccumulatedTaxes(uint256 swapAmount) internal lockSwap {
        uint256 totalToSwap = 0;
        uint256 totalTokenTypes = 0;
        uint256 tl = taxes.length;
        bool[] memory taxesToProcess = new bool[](tl);
        uint256[] memory taxAmounts = new uint256[](tl);

        for (uint256 i; i < tl; i++) {
            Helpers.Tax storage tax = taxes[i];
            if (tax.amountAccumulated == 0) continue;
            if (
                tax.taxType == Helpers.TaxType.ExternalBurn ||
                (tax.taxType == Helpers.TaxType.Dev && tax.rewardInPls) ||
                tax.taxType == Helpers.TaxType.Yield ||
                tax.taxType == Helpers.TaxType.Liquify
            ) {
                (uint256 swapAmount, uint256 _newAccumulatedAmount) = Helpers(
                    helpers
                ).getProcessingAmount(tax.amountAccumulated, swapAmount);
                if (swapAmount > 0) {
                    uint256 amountToSwap = swapAmount;
                    uint256 finalAccumulatedAmount = _newAccumulatedAmount;

                    // For Liquify, only swap half — keep other half for liquidity
                    if (tax.taxType == Helpers.TaxType.Liquify) {
                        amountToSwap = swapAmount / 2;
                        finalAccumulatedAmount = _newAccumulatedAmount + (swapAmount - amountToSwap);
                    }

                    taxesToProcess[i] = true;
                    taxAmounts[i] = amountToSwap;
                    totalToSwap += amountToSwap;
                    totalTokenTypes++;
                    taxes[i].amountAccumulated = finalAccumulatedAmount;
                } else {
                    taxes[i].amountAccumulated = _newAccumulatedAmount;
                }
            }
        }

        (, /*address bestPair*/ address bestRouter) = Helpers(helpers)
            .getBestPair(address(this), wethAddress, routers);
        if (bestRouter == address(0)) {
            // The per-leg buckets were already zeroed above. Returning without restoring
            // them permanently destroys the accounting for tax already sitting at
            // address(this): rescueToken refuses address(this) and
            // forceProcessAccumulatedTaxes only drains amountAccumulated, so the tokens
            // become unrecoverable. Mirror the swap-failure branch below and put them back.
            for (uint256 i; i < tl; i++) {
                if (taxesToProcess[i]) {
                    taxes[i].amountAccumulated += taxAmounts[i];
                }
            }
            emit noRouter();
            return;
        }

        // Pull both platform buckets from storage. Scoped block so the
        // `newAcc*` temporaries don't pollute the outer stack frame.
        uint256 ToProcess;
        uint256 NeonToProcess;
        {
            uint256 newAcc;
            uint256 newAccNeon;
            (ToProcess, newAcc) = Helpers(helpers).getProcessingAmount(
                accumulatedFee, swapAmount
            );
            (NeonToProcess, newAccNeon) = Helpers(helpers).getProcessingAmount(
                accumulatedNeonFee, swapAmount
            );
            accumulatedFee     = newAcc;
            accumulatedNeonFee = newAccNeon;
        }

        totalToSwap += ToProcess;
        totalToSwap += NeonToProcess;
        if (totalToSwap == 0) return;

        // (INC-01) Exact single-op allowance instead of a standing max grant.
        _approve(address(this), smartTrader, totalToSwap);
        try
            SmartTrader(smartTrader)
                .swapExactTokensForTokensSupportingFeeOnTransferTokens(
                    bestRouter,
                    address(this),
                    totalToSwap,
                    getTokenWETHPath(address(this))
                )
        {} catch {
            _approve(address(this), smartTrader, 0); // reset residual on failure
            for (uint256 i; i < tl; i++) {
                if (taxesToProcess[i]) {
                    taxes[i].amountAccumulated += taxAmounts[i];
                }
            }
            accumulatedFee     += ToProcess;
            accumulatedNeonFee += NeonToProcess;
            return;
        }
        uint256 totalWethReceived = IERC20(wethAddress).balanceOf(
            address(this)
        ) - wethYieldBalance;

        // Pay platform FEE bps through the deployer/staking-vault split, then
        // any Neon LP receiver slice, and shrink WPLS down to the creator share.
        // Helper extracted to keep this frame under the stack-too-deep limit.
        totalWethReceived -= _distributeFeesAndNeon(
            totalWethReceived, ToProcess, NeonToProcess, totalToSwap
        );

        totalToSwap -= ToProcess;
        totalToSwap -= NeonToProcess;
        if (totalWethReceived == 0) return;

        _groupedSwapDistribute(
            taxesToProcess, taxAmounts, totalWethReceived, totalToSwap
        );
    }

    /// @dev Groups Yield + ExternalBurn taxes by target tokenAddress, executes
    ///      one swap per unique target, then distributes bought tokens pro-rata.
    ///      Dev+PLS and Liquify taxes are handled individually (unchanged logic).
    ///      Split across three internal functions to stay under the stack-depth
    ///      limit without --via-ir.
    function _groupedSwapDistribute(
        bool[] memory taxesToProcess,
        uint256[] memory taxAmounts,
        uint256 totalWethReceived,
        uint256 totalToSwap
    ) internal {
        uint256 tl = taxes.length;

        // Scratch arrays shared across passes.
        address[] memory grpToken = new address[](tl);
        uint256[] memory grpWpls  = new uint256[](tl);
        uint256[] memory taxGroup = new uint256[](tl);
        uint256[] memory taxWpls  = new uint256[](tl);

        // Pass 1: handle Dev+PLS/Liquify/WPLS-target individually,
        // accumulate the rest into swap groups.
        uint256 grpCount = _buildSwapGroups(
            taxesToProcess, taxAmounts, totalWethReceived, totalToSwap,
            grpToken, grpWpls, taxGroup, taxWpls
        );
        if (grpCount == 0) return;

        // Pass 2: one swap per unique target token.
        uint256[] memory grpReceived = _executeGroupedSwaps(
            grpToken, grpWpls, grpCount
        );

        // Pass 3: distribute bought tokens pro-rata per tax.
        _distributeGroupedTokens(
            taxesToProcess, taxAmounts,
            grpToken, grpWpls, grpReceived, grpCount,
            taxGroup, taxWpls
        );
    }

    /// @dev Pass 1 — handle individual taxes and build swap groups.
    ///      Returns the number of unique swap groups created.
    function _buildSwapGroups(
        bool[] memory taxesToProcess,
        uint256[] memory taxAmounts,
        uint256 totalWethReceived,
        uint256 totalToSwap,
        address[] memory grpToken,
        uint256[] memory grpWpls,
        uint256[] memory taxGroup,
        uint256[] memory taxWpls
    ) internal returns (uint256 grpCount) {
        uint256 tl = taxes.length;

        for (uint256 i; i < tl; i++) {
            if (!taxesToProcess[i] || taxAmounts[i] == 0) continue;

            uint256 wethPortion = (taxAmounts[i] * totalWethReceived) /
                totalToSwap;
            Helpers.Tax storage tax = taxes[i];

            if (tax.taxType == Helpers.TaxType.Dev && tax.rewardInPls) {
                sendWETH(wethPortion, tax.receiver);
                continue;
            }
            if (tax.taxType == Helpers.TaxType.Liquify) {
                processLiquifyWeth(wethPortion, tax);
                continue;
            }

            // WPLS-target shortcut (no swap needed).
            if (tax.tokenAddress == wethAddress) {
                _handleWplsTarget(i, taxAmounts[i], wethPortion, tax);
                continue;
            }

            // Find or create group (1-based so default 0 = unassigned).
            uint256 gIdx1 = 0; // 0 = not found
            for (uint256 g; g < grpCount; g++) {
                if (grpToken[g] == tax.tokenAddress) { gIdx1 = g + 1; break; }
            }
            if (gIdx1 == 0) {
                grpToken[grpCount] = tax.tokenAddress;
                gIdx1 = grpCount + 1;
                grpCount++;
            }
            grpWpls[gIdx1 - 1] += wethPortion;
            taxGroup[i] = gIdx1; // 1-based
            taxWpls[i]  = wethPortion;
        }
    }

    /// @dev Handles Yield/ExternalBurn taxes whose target is WPLS (no swap).
    function _handleWplsTarget(
        uint256 i,
        uint256 taxAmount,
        uint256 wethPortion,
        Helpers.Tax storage tax
    ) internal {
        if (tax.taxType == Helpers.TaxType.Yield) {
            emit YieldTaxProcessed(
                taxAmount, wethPortion, tax.tokenAddress, block.timestamp
            );
            processYieldWeth(wethPortion, tax);
        } else {
            emit ExternalBurnProcessed(
                taxAmount, tax.id, wethPortion, tax.receiver,
                tax.tokenAddress, block.timestamp
            );
            _burnOrTransfer(wethAddress, tax.receiver, wethPortion);
        }
    }

    /// @dev Pass 2 — execute one grouped swap per unique target token.
    /// @dev (EIP-170) Body extracted to TokenTaxSwapLib (delegatecall library).
    ///      Behaviour-identical: only external swaps, no storage writes.
    function _executeGroupedSwaps(
        address[] memory grpToken,
        uint256[] memory grpWpls,
        uint256 grpCount
    ) internal returns (uint256[] memory grpReceived) {
        return TokenTaxSwapLib.executeGroupedSwaps(
            _libCfg(), grpToken, grpWpls, grpCount
        );
    }

    /// @dev Build the static config struct the swap library needs.
    function _libCfg() internal view returns (TokenTaxSwapLib.Config memory) {
        return TokenTaxSwapLib.Config({
            helpers: helpers,
            smartTrader: smartTrader,
            factory: factory,
            deployer: deployer,
            routers: routers
        });
    }

    /// @dev Pass 3 — distribute bought tokens pro-rata across grouped taxes.
    function _distributeGroupedTokens(
        bool[] memory taxesToProcess,
        uint256[] memory taxAmounts,
        address[] memory grpToken,
        uint256[] memory grpWpls,
        uint256[] memory grpReceived,
        uint256 grpCount,
        uint256[] memory taxGroup,
        uint256[] memory taxWpls
    ) internal {
        uint256 tl = taxes.length;
        uint256[] memory grpDistributed = new uint256[](grpCount);

        for (uint256 i; i < tl; i++) {
            if (!taxesToProcess[i] || taxAmounts[i] == 0) continue;

            Helpers.Tax storage tax = taxes[i];

            // Skip taxes handled in Pass 1.
            if ((tax.taxType == Helpers.TaxType.Dev && tax.rewardInPls) ||
                tax.taxType == Helpers.TaxType.Liquify ||
                tax.tokenAddress == wethAddress) continue;

            // taxGroup is 1-based; 0 = unassigned (should never reach here).
            uint256 g1 = taxGroup[i];
            if (g1 == 0) continue;
            uint256 g = g1 - 1;

            if (grpReceived[g] == 0) {
                _handleFailedGroupTax(i, taxAmounts[i], taxWpls[i], tax);
                continue;
            }

            uint256 share = (grpReceived[g] * taxWpls[i]) / grpWpls[g];
            grpDistributed[g] += share;
            if (grpDistributed[g] > grpReceived[g]) {
                share -= (grpDistributed[g] - grpReceived[g]);
                grpDistributed[g] = grpReceived[g];
            }

            _creditTaxShare(i, taxAmounts[i], taxWpls[i], share, tax);
        }
    }

    /// @dev Fallback when a grouped swap failed — send WPLS to ExtBurn receiver,
    ///      or leave in contract for Yield (matching current per-tax behavior).
    function _handleFailedGroupTax(
        uint256 i,
        uint256 taxAmount,
        uint256 wethPortion,
        Helpers.Tax storage tax
    ) internal {
        if (tax.taxType == Helpers.TaxType.ExternalBurn) {
            emit ExternalBurnProcessed(
                taxAmount, tax.id, wethPortion, tax.receiver,
                tax.tokenAddress, block.timestamp
            );
            // try/catch so a reverting receiver cannot brick the token.
            // On failure WPLS stays at address(this), recoverable via rescueToken.
            _burnOrTransfer(wethAddress, tax.receiver, wethPortion);
        } else if (tax.taxType == Helpers.TaxType.Yield) {
            emit YieldSwapFailed(tax.tokenAddress, wethPortion, block.timestamp);
        }
    }

    /// @dev Credits a single tax its pro-rata share of a grouped swap.
    function _creditTaxShare(
        uint256 i,
        uint256 taxAmount,
        uint256 wethPortion,
        uint256 share,
        Helpers.Tax storage tax
    ) internal {
        if (tax.taxType == Helpers.TaxType.Yield) {
            emit YieldTaxProcessed(
                taxAmount, wethPortion, tax.tokenAddress, block.timestamp
            );
            if (share > 0) {
                uint256 tokenIndex = addYieldToken(tax.tokenAddress);
                uint256 supply = totalSupply() - balanceOf(address(this));
                if (supply > 0) {
                    yieldTokens[tokenIndex].reflectionsPerShareAmount +=
                        (share * PRECISION) / supply;
                    emit YieldDistributed(
                        tax.tokenAddress, address(this), share,
                        yieldTokens[tokenIndex].reflectionsPerShareAmount,
                        block.timestamp
                    );
                }
            }
        } else if (tax.taxType == Helpers.TaxType.ExternalBurn) {
            emit ExternalBurnProcessed(
                taxAmount, tax.id, wethPortion, tax.receiver,
                tax.tokenAddress, block.timestamp
            );
            if (share > 0) {
                // try/catch so a reverting receiver (blacklist, pause, etc.)
                // cannot brick every future transfer of this token.
                // On failure tokens stay at address(this), recoverable via rescueToken.
                _burnOrTransfer(tax.tokenAddress, tax.receiver, share);
            }
        }
    }

    /// @dev If receiver is a dead address, try burn() first (real totalSupply
    ///      reduction) and fall back to transfer. Otherwise just transfer.
    ///      Balance check guards against no-op burn() (e.g. HEX's burn is a
    ///      staking function that doesn't reduce supply).
    /// @dev (EIP-170) Body extracted to TokenTaxSwapLib. Behaviour-identical.
    function _burnOrTransfer(address token, address receiver, uint256 amount) internal {
        TokenTaxSwapLib.burnOrTransfer(token, receiver, amount);
    }

    /// @dev Pays the deployer/staking vault split + the Neon LP share out of the
    ///      just-swapped WPLS pool. (EIP-170) Body extracted to TokenTaxSwapLib.
    function _distributeFeesAndNeon(
        uint256 totalWethReceived,
        uint256 toProcess,
        uint256 neonToProcess,
        uint256 totalToSwap_
    ) internal returns (uint256 spent) {
        return TokenTaxSwapLib.distributeFeesAndNeon(
            _libCfg(), totalWethReceived, toProcess, neonToProcess, totalToSwap_
        );
    }

    function _platformFeeWallet() internal view returns (address wallet) {
        wallet = getWallet();
        if (wallet == address(0)) wallet = deployer;
    }

    function _transferPlatformFee(address from, uint256 amount) internal {
        address wallet = _platformFeeWallet();
        address stakingVault = getStakingVault();
        if (stakingVault == address(0)) {
            // (INC-03) exclude+checkpoint the fee receiver before crediting it
            _excludeReflectionReceiver(wallet);
            super._transfer(from, wallet, amount);
            return;
        }

        uint256 vaultAmount = amount / 2;
        uint256 walletAmount = amount - vaultAmount;
        if (walletAmount > 0) {
            _excludeReflectionReceiver(wallet);
            super._transfer(from, wallet, walletAmount);
        }
        if (vaultAmount > 0) {
            _excludeReflectionReceiver(stakingVault);
            super._transfer(from, stakingVault, vaultAmount);
        }
    }

    /// @dev KNOWN BUG (mitigated off-chain in the deployment UI):
    ///      On the success path of `withdraw`, the WPLS has already been
    ///      unwrapped to native PLS. If the subsequent `.call` fails (receiver
    ///      is a contract that rejects PLS — Safe with no `receive()`,
    ///      blacklist-bound contract, etc.), the fallback `transfer` of WETH
    ///      operates on a balance that no longer exists for this slice.
    ///      Two failure modes:
    ///        1. Hard revert if the contract holds no other WETH → bricks
    ///           every subsequent user transfer (processAccumulatedTaxes runs
    ///           inside _transfer with no try/catch wrapping it).
    ///        2. Silent dip into `wethYieldBalance` if yield reserves exist →
    ///           the next processAccumulatedTaxes computes
    ///           `weth.balanceOf(this) - wethYieldBalance` and underflows
    ///           (panic), permanently bricking tax processing for this token.
    ///      Trigger surfaces the UI cannot fully cover:
    ///        (a) factory `WALLET` (set by factory owner via setWallet)
    ///        (b) `NEON_LP_RECEIVER` (set by factory owner via setNeonLpReceiver)
    ///        (c) any receiver contract that becomes PLS-rejecting AFTER
    ///            deployment (multisig reconfig, paused flag, etc.)
    ///      The deployment UI validates per-token dev receivers can accept
    ///      PLS at create time, which mitigates the most common surface
    ///      (the dev receiver picked at create) but does NOT cover (a)/(b)/(c).
    ///      Long-term fix: re-wrap PLS via `IWETH(wethAddress).deposit{value: wethAmount}()`
    ///      before the fallback transfer, OR never unwrap and always send WETH.
    /// @dev (EIP-170) Body extracted to TokenTaxSwapLib. Behaviour-identical.
    function sendWETH(uint256 wethAmount, address receiver) internal {
        TokenTaxSwapLib.sendWETH(wethAmount, receiver);
    }

    function processYieldWeth(
        uint256 wethAmount,
        Helpers.Tax memory tax
    ) internal {
        if (wethAmount == 0) return;

        if (tax.tokenAddress == wethAddress) {
            wethYieldBalance += wethAmount;
            uint256 tokenIndex = addYieldToken(tax.tokenAddress);
            uint256 supply = totalSupply() - balanceOf(address(this));
            if (supply > 0) {
                yieldTokens[tokenIndex].reflectionsPerShareAmount +=
                    (wethAmount * PRECISION) /
                    supply;

                emit YieldDistributed(
                    tax.tokenAddress,
                    address(this),
                    wethAmount,
                    yieldTokens[tokenIndex].reflectionsPerShareAmount,
                    block.timestamp
                );
            }
            return;
        }

        (, /*address bestTargetPair*/ address bestTargetRouter) = Helpers(
            helpers
        ).getBestPair(wethAddress, tax.tokenAddress, routers);

        uint256 initialTokenBalance = IERC20(tax.tokenAddress).balanceOf(
            address(this)
        );

        // (INC-01) Exact single-op WPLS allowance instead of a standing max grant.
        IERC20(wethAddress).approve(smartTrader, wethAmount);
        try
            SmartTrader(smartTrader).buyToken(
                bestTargetRouter,
                address(this),
                wethAmount,
                getWETHBuyBurnPath(tax.tokenAddress)
            )
        {
            uint256 finalTokenBalance = IERC20(tax.tokenAddress).balanceOf(
                address(this)
            );
            uint256 boughtAmount = finalTokenBalance - initialTokenBalance;

            if (boughtAmount > 0) {
                uint256 tokenIndex = addYieldToken(tax.tokenAddress);
                uint256 supply = totalSupply() - balanceOf(address(this));
                if (supply > 0) {
                    yieldTokens[tokenIndex].reflectionsPerShareAmount +=
                        (boughtAmount * PRECISION) /
                        supply;

                    emit YieldDistributed(
                        tax.tokenAddress,
                        address(this),
                        boughtAmount,
                        yieldTokens[tokenIndex].reflectionsPerShareAmount,
                        block.timestamp
                    );
                }
            }
        } catch {
            IERC20(wethAddress).approve(smartTrader, 0); // (INC-01) reset residual on failure
        }
    }

    /// @dev (EIP-170) Heavy add-liquidity body extracted to TokenTaxSwapLib.
    ///      The library performs the WPLS→pair swap (if any), the addLiquidity,
    ///      and computes the consumed amount, but the AUTHORITATIVE storage write
    ///      to `taxes[tax.id].amountAccumulated` stays here on the token so all
    ///      accounting / storage layout is byte-for-byte unchanged.
    function processLiquifyWeth(
        uint256 wethAmount,
        Helpers.Tax storage tax
    ) internal {
        (bool updated, uint256 newAcc) =
            TokenTaxSwapLib.processLiquifyWeth(_libCfg(), tax, wethAmount);
        if (updated) {
            taxes[tax.id].amountAccumulated = newAcc;
        }
    }

    function _claimReflections(address from, address to) internal {
        if (!reflectionsEnabled) return;
        (
            uint256 fromAmount,
            uint256 toAmount,
            uint256 deployerAmount
        ) = updateAndClaimReflections(from, to, deployer);

        emit ReflectionDistributed(
            from,
            to,
            fromAmount,
            toAmount,
            deployerAmount,
            reflectionsPerShareAmount,
            block.timestamp
        );

        if (fromAmount != 0) {
            if (!isPair(from)) {
                super._transfer(address(this), from, fromAmount);
            }
        }
        if (toAmount != 0) {
            if (!isPair(to)) {
                super._transfer(address(this), to, toAmount);
            }
        }
        if (deployerAmount != 0) {
            super._transfer(address(this), deployer, deployerAmount);
        }
    }

    /// @dev (REFL-01) Settle one account's reflection position: credit any
    ///      pending reflections out of the contract's shared self-balance and
    ///      checkpoint its debt to the current per-share index. MUST be called
    ///      on BOTH endpoints of every balance change that does NOT already run
    ///      through _claimReflections (the DEAD-burn shortcut and the
    ///      excluded/no-tax early-return path), otherwise a holder receiving
    ///      tokens without a debt checkpoint accrues reflections retroactively
    ///      on the larger balance and can drain the contract's self-balance.
    ///
    ///      Pending is computed against the account's CURRENT (pre-mutation)
    ///      balance via Helpers.cleanPendingReflections, so this must be invoked
    ///      BEFORE the underlying ERC20 balance mutation. The payout itself is a
    ///      plain super._transfer from address(this) (reflection-excluded), so
    ///      it cannot recurse into reflection settlement.
    function _settleReflections(address account) internal {
        if (!reflectionsEnabled) return;
        if (isExcludedFromReflections(account)) {
            // Excluded accounts earn nothing; still checkpoint debt so they
            // never accrue retroactively if later re-included.
            reflectionDebt[account] = reflectionsPerShareAmount;
            return;
        }
        uint256 pending = cleanPendingReflections(account);
        reflectionDebt[account] = reflectionsPerShareAmount;
        if (pending != 0 && !isPair(account)) {
            super._transfer(address(this), account, pending);
        }
    }

    function initializeReflectionExclusions() internal {
        isReflectionExcluded[address(0)] = true;
        isReflectionExcluded[address(this)] = true;
        for (uint256 i; i < routers.length; ) {
            isReflectionExcluded[routers[i]] = true;
            unchecked {
                i++;
            }
        }
    }
    function isDeadAddress(address _address) internal pure returns (bool) {
        return
            _address == address(0) ||
            _address == 0x0000000000000000000000000000000000000369 ||
            _address == 0x000000000000000000000000000000000000dEaD;
    }

    function isPair(address _address) internal view returns (bool) {
        return Helpers(helpers).isPair(_address, address(this));
    }

    function isBuy(address from, address to) internal view returns (bool) {
        return Helpers(helpers).isBuy(from, to, address(this));
    }

    function isSell(address from, address to) internal view returns (bool) {
        // Pair→pair (arb bot routing) is treated as a sell so the sell-tax fires.
        if (isPair(from) && isPair(to)) return true;
        return Helpers(helpers).isSell(from, to, address(this));
    }

    /// @dev (G2) Removed the internal `getProcessingAmount(uint256)` helper —
    ///      it was dead code and was the only remaining reader of the
    ///      deprecated `currentSwapAmount` storage slot. Active swap amounts
    ///      now flow through processAccumulatedTaxes(uint256 swapAmount).

    function getTokenWETHPath(
        address tokenAddress
    ) internal view returns (address[] memory) {
        return Helpers(helpers).getTokenWPLSPath(tokenAddress);
    }

    function getWETHBuyBurnPath(
        address tokenAddress
    ) internal view returns (address[] memory) {
        return Helpers(helpers).getWPLSBuyBurnPath(tokenAddress);
    }

    function getTaxes() public view returns (Helpers.Tax[] memory) {
        return taxes;
    }

    function getFee() public view returns (uint256) {
        return ISmartTokenFactory(factory).FEE();
    }

    function getWallet() public view returns (address) {
        return ISmartTokenFactory(factory).WALLET();
    }

    function getStakingVault() public view returns (address) {
        try ISmartTokenFactory(factory).STAKING_VAULT() returns (address vault) {
            return vault;
        } catch {
            return address(0);
        }
    }

    // (gas #8) Factory is the live TokenFactoryTax proxy whose ABI is pinned
    // at token-deploy time, so these getters are guaranteed to exist. Drop
    // the try/catch wrapper — saves ~200-500 gas per taxed transfer.
    //
    // (V3 byte budget) Demoted from `public` to `internal`. NEON is a retired product:
    // the live factory 0x3315a2fA12c7645260a430aC0a5053a17FBE746B holds NEON_LP_FEE = 0
    // (slot 3) and NEON_LP_RECEIVER = address(0) (slot 4) permanently, and its setters
    // were removed by the factory upgrade — so on any V3 token these return constants and
    // the NEON branch in _handleTaxes never fires. Nothing reads the TOKEN-side getters:
    // no caller in cabal src/ or script/, no entry in the frontend's tokenTaxAbi /
    // tokenTaxManageAbi, and TokenTaxSwapLib does not call back into them. The FACTORY's
    // NEON_LP_FEE()/NEON_LP_RECEIVER() getters are untouched — those ARE load-bearing,
    // because every already-deployed TokenTaxV2 STATICCALLs them without try/catch.
    // The internal callers and the NEON code path below are unchanged.
    function getNeonLpFee() internal view returns (uint256) {
        return ISmartTokenFactory(factory).NEON_LP_FEE();
    }

    function getNeonLpReceiver() internal view returns (address) {
        return ISmartTokenFactory(factory).NEON_LP_RECEIVER();
    }

    function getaccumulatedFee() external view returns (uint256) {
        return accumulatedFee;
    }

    // (V3 byte budget) `getaccumulatedNeonFee()` deleted. NEON is fully retired: the
    // factory's NEON_LP_FEE / NEON_LP_RECEIVER are permanently 0 / address(0), so the
    // guard at `getNeonLpReceiver() != address(0)` in _handleTaxes never fires and
    // `accumulatedNeonFee` is structurally always 0 on a V3 token. The getter had zero
    // readers anywhere — no caller in cabal src/ or script/, and no reference in the
    // frontend (it is absent from tokenTaxAbi / tokenTaxManageAbi). The storage var and
    // the NEON code path itself are left intact so the layout and the tax pipeline stay
    // identical to V2. NOTE: `getTotalTaxs()` below is deliberately KEPT — the manage
    // page reads it (trench-trader-hub src/routes/ttrnch_.manage.$address.tsx).
    function getTotalTaxs() external view returns (uint256 total) {
        for (uint256 i; i < taxes.length; i++) {
            total += taxes[i].percentage;
        }
    }

    function forceProcessAccumulatedTaxes() external onlyOwner {
        // (G2) Manual flush — pass max as the swap-budget so Helpers.getProcessingAmount
        // does not artificially cap how much accumulated tax we drain.
        processAccumulatedTaxes(type(uint256).max);
    }

    // (INC-01) reapproveSmartTrader removed — there is no longer any standing smartTrader
    // allowance to maintain; each swap grants its own exact amount and resets on failure.

    function enableTrading() external onlyOwner {
        if (tradingEnabled) revert AlreadyEnabled();
        tradingEnabled = true;
        emit TradingEnabled();
    }

    function _claimYield(address from, address to) internal {
        if (yieldEnabled) {
            updateAndClaimYield(from, to, deployer);
        }
    }

    function claimYield() external returns (bool) {
        _claimYield(msg.sender, msg.sender);
        return true;
    }

function updateTaxReceiver(uint256 taxId, address newReceiver) external onlyOwner {
        if (taxId >= taxes.length) revert InvalidArg();
        if (newReceiver == address(0)) revert InvalidArg();
        taxes[taxId].receiver = newReceiver;
    }

    function updateTaxTokenAddress(uint256 taxId, address newTokenAddress) external onlyOwner {
        if (taxId >= taxes.length) revert InvalidArg();
        if (newTokenAddress == address(0)) revert InvalidArg();
        taxes[taxId].tokenAddress = newTokenAddress;
    }

    function isExcludedFromTax(address _address) external view returns (bool) {
        return isTaxExcluded[_address];
    }

    function addTaxExclusion(address _address) external onlyOwner {
        isTaxExcluded[_address] = true;
    }

    function removeTaxExclusion(address _address) external onlyOwner {
        isTaxExcluded[_address] = false;
    }

    /// @notice Excludes an address from tax, callable ONLY by the deploying factory.
    ///         Exists so the launchpad can exclude this token's graduation fee-harvester
    ///         — which is deployed AT graduation, after ownership already moved to the
    ///         creator, so the factory's mint-time exclusion could not cover it. Without
    ///         it the harvester's sell of accrued fees into the pair is taxed (and any
    ///         burn leg fires), bleeding the creator fee. Only ever ADDS an exclusion.
    function excludeFromTaxByFactory(address _address) external {
        if (msg.sender != factory) revert Unauthorized();
        isTaxExcluded[_address] = true;
    }

    /// @notice Add or remove an address from reflection rewards.
    ///         Excluded addresses earn zero reflections; their share
    ///         remains in the contract (effectively locked).
    /// @param _address The address to toggle.
    /// @param excluded true = exclude from reflections, false = re-include.
    function setReflectionExclusion(address _address, bool excluded) external onlyOwner {
        // (D2) The curve's constructor-set exclusion is PERMANENT. Re-including it would
        // hand the curve — holder of the entire unsold supply — the overwhelming majority
        // of every reflection payout, which `_claimReflections` writes into the curve's
        // balance while the curve's own accounting only tracks `virtualReserveToken`. The
        // excess is unrecoverable, so the owner must not be able to point the reflection
        // pot at the raise. Folded into the single revert site (and checked before the
        // `isPair` STATICCALL) to stay inside the EIP-170 byte budget.
        if (
            _address == address(0) ||
            _address == address(this) ||
            (!excluded && (_address == curveTaxVenue || isPair(_address)))
        ) revert InvalidArg();
        isReflectionExcluded[_address] = excluded;
        // Reset debt so the address doesn't collect retroactive reflections
        // from the period it was excluded when re-included.
        reflectionDebt[_address] = reflectionsPerShareAmount;
    }

    function inititlizeTaxExclusions() internal {
        isTaxExcluded[deployer] = true;
        isTaxExcluded[address(this)] = true;
        isTaxExcluded[smartTrader] = true;
        isTaxExcluded[factory] = true;
        // NOTE: the TrenchDex FeeBurner is excluded per-token by the factory at mint
        // (TokenFactoryTax.OMEGA_FEE_BURNER) rather than hardcoded here — keeps this
        // contract under the EIP-170 runtime limit while still excluding the burner.
        // Airdrop contract — TODO: replace with deployed address
        // isTaxExcluded[0x_AIRDROP_CONTRACT_ADDRESS_HERE] = true;
    }

    /// @notice Rescue stuck tokens — only factory owner can call
    /// @dev For when users accidentally send tokens to the token contract
    function rescueToken(address token, address to, uint256 amount) external {
        if (msg.sender != Ownable(factory).owner()) revert Unauthorized();
        if (to == address(0)) revert InvalidArg();
        if (token == address(this)) revert InvalidArg();
        // (RESCUE-01) Forbid pulling tokens that this contract accumulates as
        // part of its tax pipeline. Rescuing a configured Yield/ExternalBurn
        // target token would steal already-bought yield/burn balances owed to
        // holders/receivers and break pending tax processing. Only truly
        // foreign tokens (accidental sends) may be rescued.
        if (isTaxAccumulatorToken(token)) revert InvalidArg();
        if (token == wethAddress) {
            uint256 bal = IERC20(token).balanceOf(address(this));
            if (bal < wethYieldBalance + amount) revert InvalidArg();
        }
        IERC20(token).transfer(to, amount);
    }

    /// @dev (RESCUE-01) True if `token` is a token this contract accumulates
    ///      through its tax pipeline (a configured Yield or ExternalBurn target
    ///      token). Such balances are owed to holders / configured receivers and
    ///      must not be drained via rescueToken. WPLS is intentionally NOT
    ///      flagged here: it keeps its existing reserved-balance guard in
    ///      rescueToken (only the creator's leftover WPLS share above
    ///      wethYieldBalance stays rescuable), preserving prior behavior.
    function isTaxAccumulatorToken(address token) internal view returns (bool) {
        uint256 len = taxes.length;
        for (uint256 i; i < len; i++) {
            Helpers.Tax memory t = taxes[i];
            if (
                (t.taxType == Helpers.TaxType.Yield ||
                    t.taxType == Helpers.TaxType.ExternalBurn) &&
                t.tokenAddress == token
            ) {
                return true;
            }
        }
        // Also protect any yield tokens registered post-deploy (e.g. via a
        // grouped-swap addYieldToken) that may not appear in `taxes`.
        for (uint256 i; i < yieldTokens.length; i++) {
            if (yieldTokens[i].tokenAddress == token) return true;
        }
        return false;
    }

    /// @notice Rescue stuck PLS — only factory owner can call
    function rescuePLS(address payable to, uint256 amount) external {
        if (msg.sender != Ownable(factory).owner()) revert Unauthorized();
        (bool ok,) = to.call{value: amount}("");
        if (!ok) revert TransferFailed();
    }

    receive() external payable {}
}