Skip to content
Verified contractPartialMIT

Security

Address0xa90e64ba2e8ea61301999c489fc9c95e5069361f
Balance

0 ETH

 

Transactions

2

 

Compiler

solc 0.8.28

 

Same code

1 more contract

 

Details

Compiler
solc 0.8.28+commit.7893614a
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
License
MIT
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,434,949
Creation transaction
0x2e9127924c…c4eeef268c

Security.sol

// SPDX-License-Identifier: MIT
pragma solidity >=0.4.16 ^0.8.20 ^0.8.24 ^0.8.28;

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

// src/interfaces/IConfig.sol

/// @notice SPHToken 外部配置源(参数唯一权威)
interface IConfig {
    struct TradeParams {
        address keeper;
        address stakingContractAddress;
        address referralContract;
        address lpRewardAddress;
        address contributionRewardAddress;
        address autoLpManagerAddress;
        address fundWallet;
        uint256 buyFeeBps;
        uint256 sellFeeBps;
        uint256 extraSellTaxBps;
        uint16 buyTaxLpBps;
        uint16 buyTaxLpRewardBps;
        uint16 buyTaxContributionBps;
        uint16 buyTaxFundBps;
        uint16 buyTaxBurnBps;
        uint16 sellTaxLpRewardBps;
        uint16 sellTaxFundBps;
        uint16 sellTaxBurnBps;
        bool purchaseOpen;
        /// @notice true = 允许 claim / onBuy 建单
        bool claimOpen;
        bool burnEnabled;
        uint16 maxTxBpsOfPool;
        uint32 minBlocksBeforeSell;
        bool stopAll;
        bool enablePerBlockTradeLimit;
        uint256 perBlockMaxTradeCount;
        uint256 perBlockMaxTradeAmount;
        bool enableTxPoolTradeLimit;
        uint256 txPoolTradeLockSize;
        uint256 txPoolTradeAmountSize;
        bool enableMinBlocksBeforeSell;
        address sphToken;
        bool sellOpen;
        bool enableBuyTax;
        bool enableSellTax;
        bool enableAddLiquidityTax;
        bool enableRemoveLiquidityTax;
    }

    function tradeParams() external view returns (TradeParams memory);

    /// @notice Ethereum mainnet USDT
    function usdt() external view returns (address);

    /// @notice Uniswap V2 Router02(Ethereum mainnet)
    function uniswapV2RouterAddress() external view returns (address);

    function keeper() external view returns (address);

    function stakingContractAddress() external view returns (address);

    function referralContract() external view returns (address);

    function buyFeeBps() external view returns (uint256);

    function sellFeeBps() external view returns (uint256);

    function extraSellTaxBps() external view returns (uint256);

    /// @notice UTC 自然日基准价(sphToUsdt(1e18) 口径);keeper 写入,跨日未写则沿用
    function utcDayBaselinePrice() external view returns (uint256);

    /// @notice 历史字段:线性免跌宽度;阶梯卖税模式下不参与同步
    function extraTaxFreeBps() external view returns (uint256);

    /// @notice 仅 Security:按跌幅覆盖写入 extraSellTaxBps
    function syncExtraSellTaxBps(uint256 bps) external;

    function lpRewardAddress() external view returns (address);

    function contributionRewardAddress() external view returns (address);

    function autoLpManagerAddress() external view returns (address);

    function fundWallet() external view returns (address);

    function purchaseOpen() external view returns (bool);

    function claimOpen() external view returns (bool);

    function burnEnabled() external view returns (bool);

    function maxTxBpsOfPool() external view returns (uint16);

    /// @notice 买入 U 限额:本笔付出 U ≤ 底池 USDT reserve × bps/10000;0=关闭(Security 钩子)
    function maxTxBpsOfPoolBuy() external view returns (uint16);

    /// @notice 卖出 U 限额:本笔 SPH 税后估值 U ≤ 底池 USDT reserve × bps/10000;0=关闭(Security 钩子)
    function maxTxBpsOfPoolSell() external view returns (uint16);

    function minBlocksBeforeSell() external view returns (uint32);

    function isExcludedFromFees(address account) external view returns (bool);

    function isBlacklisted(address account) external view returns (bool);

    function isRecycleToAddressPermission(
        address to
    ) external view returns (bool);

    function securityContractAddress() external view returns (address);

    /// @notice 静态/动态出局倍数(默认 1)
    function exitMultiple() external view returns (uint256);

    /// @notice 出局计量模式:0=币数 1=U(默认 0=币本位)
    function exitMetricMode() external view returns (uint256);

    /// @notice 静态阶段累计产出阈值(index 0..2)
    function phaseThresholds(uint256 index) external view returns (uint256);

    /// @notice 静态阶段小时利率 bps(index 0..2;20 => 0.02%/h)
    function hourlyBps(uint256 index) external view returns (uint256);

    /// @notice 建单最低 USDT(18 位)
    function minOrderUsdt() external view returns (uint256);

    /// @notice 有效账户最低持币价值 USDT(18 位)
    function minHoldingUsdt() external view returns (uint256);

    /// @notice 单次 claim 实发上限(SPH,18 位)
    function maxClaimSph() external view returns (uint256);

    /// @notice 两次 claim 最小间隔(秒);0=不限制
    function minClaimInterval() external view returns (uint256);

    /// @notice 静态产出总开关(false 则 Staking 不计息)
    function productionEnabled() external view returns (bool);

    function enablePerBlockTradeLimit() external view returns (bool);

    function perBlockMaxTradeCount() external view returns (uint256);

    function perBlockMaxTradeAmount() external view returns (uint256);

    function enableTxPoolTradeLimit() external view returns (bool);

    function txPoolTradeLockSize() external view returns (uint256);

    function txPoolTradeAmountSize() external view returns (uint256);

    function enableMinBlocksBeforeSell() external view returns (bool);

    function sphToken() external view returns (address);

    function sellOpen() external view returns (bool);

    function enableBuyTax() external view returns (bool);

    function enableSellTax() external view returns (bool);

    function enableAddLiquidityTax() external view returns (bool);

    function enableRemoveLiquidityTax() external view returns (bool);

    /// @notice 系统日长度(秒)。上线一般为 86400,测试可压缩
    function dayLength() external view returns (uint256);

    /// @notice 系统起始时间戳,用于计算日期 index
    function systemStartTimestamp() external view returns (uint256);

    /// @notice 指定时间戳对应的系统日 index
    function getDayIndex(uint256 timestamp) external view returns (uint256);

    /// @notice 排队通道硬闸:false 时 join 与 pull / join 尾带匹配均不可执行(默认 false,首期启动时置 true)
    function enableQueue() external view returns (bool);

    /// @notice 暂停标志:true 时禁止一切匹配与自动开下一期;仍允许入队与判定
    function queuePaused() external view returns (bool);

    /// @notice 是否在 managePermission 名单内(owner 不必在名单内)
    function hasManagePermission(address account) external view returns (bool);

    /// @notice owner / managePermission / Queue 合约可调
    function setEnableQueue(bool enabled) external;

    /// @notice owner / managePermission / Queue 合约可调
    function setQueuePaused(bool paused) external;

    /// @notice 配置基准目标;owner / managePermission / Queue 合约可调
    function setQueueTargetAmount(uint256 amount) external;

    /// @notice 递增倍数;owner / managePermission / Queue 合约可调
    function setQueueTargetIncreaseRatio(uint256 ratio) external;

    /// @notice 排单周期,单位是 dayLength 的个数
    function queuePeriod() external view returns (uint256);

    /// @notice 配置基准目标(整枚 USDT);每次正式开期把该期实际目标写回,下一期 = 基准 × 倍数
    function queueTargetAmount() external view returns (uint256);

    /// @notice 排单额度乘数,分母 10000。13000 表示每期目标 × 1.3
    function queueTargetIncreaseRatio() external view returns (uint256);

    /// @notice 单地址最低入金,单位是整枚 USDT
    function queueMinEntryAmount() external view returns (uint256);

    /// @notice 单地址每个排单周期最高入金,单位是整枚 USDT
    function queueMaxEntryAmount() external view returns (uint256);

    /// @notice 排单静态收益比例,分母 10000
    function queueStaticRewardRatio() external view returns (uint256);

    /// @notice 排单静态收益提现手续费比例,分母 10000
    function queueFeeRatio() external view returns (uint256);

    /// @notice 排单收益分配:回购,分母 10000
    function specifiedAddress() external view returns (uint256);

    /// @notice 排单收益分配:保险池,分母 10000
    function insurancePoolAddress() external view returns (uint256);

    /// @notice 排单收益分配:生态,分母 10000
    function ecosystemAddress() external view returns (uint256);

    /// @notice 排单收益分配:风险池,分母 10000
    function riskPoolAddress() external view returns (uint256);

    /// @notice 强制复投时间,单位是 dayLength 的个数
    function queueForceRecycleTime() external view returns (uint256);

    /// @notice 排队合约地址(鉴权 pull→staking / machine sync)
    function queueContract() external view returns (address);

    /// @notice 提现手续费分配钱包
    function queueFeeBuybackWallet() external view returns (address);
    function queueFeeInsuranceWallet() external view returns (address);
    function queueFeeEcosystemWallet() external view returns (address);
    function queueFeeRiskWallet() external view returns (address);

    /// @notice 每满多少 USDT 一台矿机
    function machineSlotUsdt() external view returns (uint256);
    /// @notice 矿机管理费周期,单位 dayLength 个数
    function machineFeeDays() external view returns (uint256);
    /// @notice 默认单台算力(1e18=1.0)
    function machineDefaultPower() external view returns (uint256);
    /// @notice 全网未销毁矿机数(owner 维护,用于管理费档位)
    function machineAliveCount() external view returns (uint256);
    /// @notice 管理费档位数量(固定)
    function machineFeeTierCount() external pure returns (uint256);
    /// @notice 第 index 档上限(含):aliveCount <= 该值则命中此档;最后一档为 type(uint256).max
    function machineFeeTierMaxAlive(uint256 index) external view returns (uint256);
    /// @notice 第 index 档每台管理费(整枚 USDT)
    function machineFeeTierPrice(uint256 index) external view returns (uint256);
    /// @notice 按全网 alive 数量取当前档位单价(整枚 USDT)
    function machineFeePriceByAlive(uint256 alive) external view returns (uint256);
    /// @notice 日产上限(SPH wei),默认 5000e18
    function machineDailyOutputCap() external view returns (uint256);
    /// @notice 减产周期,单位 dayLength 个数,默认 90
    function machineReduceDays() external view returns (uint256);
    /// @notice 每次减产比例,分母 10000,默认 1000=10%
    function machineReduceRatio() external view returns (uint256);

    /// @notice 单地址名下矿机软上限(热列表),默认 50;超额不新建
    function machinePerUserSoftCap() external view returns (uint256);
    /// @notice true=结算/sync 不扫已销毁(归档)机,默认 true
    function machineSkipDestroyedInSettle() external view returns (bool);
    /// @notice claim 单次最多处理机台数,默认 50
    function machineClaimBatchSize() external view returns (uint256);
    /// @notice claim/pending 单次最多回溯系统日,默认 30;0=不限制
    function machinePendingLookbackDays() external view returns (uint256);
    /// @notice 结算全网算力地板:peak × 该 bps / 10000;默认 9000=90%;0=关闭
    function machinePowerFloorBps() external view returns (uint256);
    /// @notice 单次 pull 最多处理订单数,默认 10
    function queuePullMaxOrders() external view returns (uint256);
    /// @notice 单次从游标起最多扫描订单数,默认 32
    function queuePullScanLimit() external view returns (uint256);
    /// @notice true=匹配后延后 sync 矿机,默认 false(当场 sync)
    function queueDeferMachineSync() external view returns (bool);

    function enableCredentialPurchase() external view returns (bool);

    function onlyAllowWhiteListPurchase() external view returns (bool);

    /// @notice 凭证单价,单位是整枚 USDT
    function credentialPrice() external view returns (uint256);

    /// @notice 入队扣凭证百分比:扣量 = amount * 本值 / 100(整枚);取值 1–100,默认 100
    function queueCredentialBurnPercent() external view returns (uint256);

    /// @notice 白名单折扣比例,分母 10000
    function whiteListDiscountRatio() external view returns (uint256);

    function addsCouldCallCredentialBurn(
        address account
    ) external view returns (bool);

    /// @notice 购买凭证的 USDT 收款地址
    function credentialDepositAddress() external view returns (address);

    /// @notice 动态奖励(直推无资格 / 级差剩余)沉淀地址
    function dynamicRewardSinkAddress() external view returns (address);

    /// @notice 级差/团队业绩/升级刷新向上层数(默认 30)
    function dynamicRewardDepth() external view returns (uint256);

    /// @notice 清算合约
    function liquidationContract() external view returns (address);
    /// @notice 矿机合约(可 bump alive)
    function machineContract() external view returns (address);
    /// @notice 矿机产出线性释放合约
    function sphLinearRelease() external view returns (address);
    /// @notice true=claimMining 按价档拆锁仓入 SphLinearRelease
    function enableMiningLinearRelease() external view returns (bool);
    /// @notice 线性释放天数 N(入账重置),默认 100
    function linearReleaseDays() external view returns (uint256);
    /// @notice 价档 i 的最低价(USDT raw / 1e18 SPH),升序
    function miningLockMinPrice(uint256 index) external view returns (uint256);
    /// @notice 价档 i 的锁仓 bps
    function miningLockBps(uint256 index) external view returns (uint256);
    /// @notice 按瞬时价(USDT raw / 1e18 SPH)取锁仓 bps
    function miningLockBpsForPrice(uint256 priceUsdtPerSph) external view returns (uint256);
    /// @notice SPH 凭证合约
    function sphCredential() external view returns (address);
    /// @notice 损失额换台除数,默认 200
    function liquidationLossDivisor() external view returns (uint256);
    /// @notice 余数令牌:每枚凭证对应多少整枚 USDT,默认 1
    function liquidationTokenUsdt() external view returns (uint256);
    /// @notice 上两期本金返还比例,分母 10000,默认 5000=50%
    function liquidationRefundBps() external view returns (uint256);
    /// @notice 用户领取爆仓矿机时单笔最多铸造台数
    function liquidationBatchMachines() external view returns (uint256);
    /// @notice 是否可从凭证库存发放(爆仓余数令牌)
    function addsCouldCallCredentialGrant(address account) external view returns (bool);

    /// @notice 矿机合约调整活机数
    function bumpMachineAliveCount(int256 delta) external;
}

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

// OpenZeppelin Contracts (last updated v5.4.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);
}

// src/interfaces/ISPHToken.sol

interface ISPHToken {
    function recycle(
        uint256 amount,
        address pairAddress,
        address to
    ) external;

    function mint(address to, uint256 amount) external;

    function uniswapV2PairAddress() external view returns (address);

    function sphToUsdt(uint256 sphAmount) external view returns (uint256);

    function balanceOf(address account) external view returns (uint256);

    function config() external view returns (address);
}

// src/interfaces/IUniswapV2Pair.sol

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

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

// src/Security.sol

/// @title 交易风控:同块/同笔限制、买卖 U 限额、动态额外卖税
contract Security is Ownable {
    uint256 private constant BPS = 10_000;
    uint256 private constant MAX_EXTRA_SELL_TAX_BPS = 4500;

    IConfig public config;

    mapping(uint256 => mapping(address => uint256))
        public lastTradeBlockUserAddressCounts;
    mapping(uint256 => mapping(address => uint256))
        public lastTradeBlockUserAddressAmount;
    mapping(address => uint32) public lastBuyBlock;

    uint256 private transient _txPoolTradeLock;
    uint256 private transient _txOriginAmount;

    event ConfigSet(address indexed config);
    event ExtraSellTaxSynced(uint256 spot, uint256 baseline, uint256 extraBps);

    error ZeroAddress();
    error ConfigNotSet();
    error NotSPHTokenOrStaking();
    error NotSPHToken();
    error MaxTxUsdtExceeded();

    /// @dev 配置未齐一律拒绝,避免未接线时任意地址可写守卫状态。
    modifier onlySPHTokenOrStaking() {
        if (address(config) == address(0)) revert ConfigNotSet();
        address token = config.sphToken();
        if (token == address(0)) revert ConfigNotSet();
        if (
            msg.sender != token && msg.sender != config.stakingContractAddress()
        ) {
            revert NotSPHTokenOrStaking();
        }
        _;
    }

    modifier onlySPHToken() {
        if (address(config) == address(0)) revert ConfigNotSet();
        address token = config.sphToken();
        if (token == address(0) || msg.sender != token) revert NotSPHToken();
        _;
    }

    constructor() Ownable(msg.sender) {}

    function setConfig(address config_) external onlyOwner {
        if (config_ == address(0)) revert ZeroAddress();
        config = IConfig(config_);
        emit ConfigSet(config_);
    }

    /// @notice 由 SPHToken._update 调用
    function antiFlashloanGuard(
        address from,
        address to,
        bool isBuy,
        bool isSell,
        uint256 amount
    ) external onlySPHTokenOrStaking {
        _antiFlashloanGuard(from, to, isBuy, isSell, amount);
    }

    /// @notice Token 转账前:买卖 U 限额。买跳过撤池;卖跳过加池。
    function onTokenTransfer(
        address from,
        address to,
        bool isBuy,
        bool isSell,
        bool isAddLiquidity,
        bool isRemoveLiquidity,
        uint256 amount
    ) external onlySPHToken {
        if (!isBuy && !isSell) return;

        IConfig cfg = config;
        ISPHToken token = ISPHToken(msg.sender);

        if (isBuy && !isRemoveLiquidity) {
            _enforceMaxTxUsdtBuy(cfg, token, to, amount);
        } else if (isSell && !isAddLiquidity) {
            _enforceMaxTxUsdtSell(cfg, token, from, amount);
        }
    }

    /// @notice 成交后:相对日基准覆盖同步 extraSellTaxBps
    function onAfterTrade(
        address /* from */,
        address /* to */,
        bool isBuy,
        bool isSell,
        bool /* isAddLiquidity */,
        bool /* isRemoveLiquidity */,
        uint256 /* amount */
    ) external onlySPHToken {
        if (!isBuy && !isSell) return;
        _syncExtraSellTax(ISPHToken(msg.sender));
    }

    function _antiFlashloanGuard(
        address from,
        address to,
        bool isBuy,
        bool isSell,
        uint256 amount
    ) internal {
        if (address(config) == address(0)) return;

        IConfig cfg = config;
        IConfig.TradeParams memory p = cfg.tradeParams();
        address token = p.sphToken;
        if (token == address(0)) return;

        address staking_ = p.stakingContractAddress;
        bool exempt = from == staking_ ||
            from == token ||
            (isBuy && cfg.isExcludedFromFees(to)) ||
            cfg.isExcludedFromFees(from) ||
            cfg.isExcludedFromFees(tx.origin);

        if (p.enablePerBlockTradeLimit && !exempt) {
            lastTradeBlockUserAddressCounts[block.number][tx.origin]++;

            if (
                lastTradeBlockUserAddressCounts[block.number][tx.origin] >
                p.perBlockMaxTradeCount
            ) {
                revert("o1");
            }

            if (p.perBlockMaxTradeCount > 1) {
                lastTradeBlockUserAddressAmount[block.number][
                    tx.origin
                ] += amount;
                require(
                    lastTradeBlockUserAddressAmount[block.number][tx.origin] <
                        p.perBlockMaxTradeAmount,
                    "o2"
                );
            }
        }

        if (p.enableTxPoolTradeLimit && (isBuy || isSell) && !exempt) {
            unchecked {
                ++_txPoolTradeLock;
            }

            if (_txPoolTradeLock > p.txPoolTradeLockSize) {
                revert("t1");
            }

            if (p.txPoolTradeLockSize > 1) {
                _txOriginAmount += amount;
                require(_txOriginAmount < p.txPoolTradeAmountSize, "t2");
            }
        }

        if (p.enableMinBlocksBeforeSell) {
            if (isSell && !cfg.isExcludedFromFees(from)) {
                require(
                    block.number > lastBuyBlock[from] + p.minBlocksBeforeSell,
                    "s"
                );
            }

            if (isBuy && !cfg.isExcludedFromFees(to)) {
                lastBuyBlock[to] = uint32(block.number);
            }
        }
    }

    /// @dev 买入:tradeU 优先用 pair 上 USDT 超额;否则税后 SPH 倒推毛额再报价
    function _enforceMaxTxUsdtBuy(
        IConfig cfg,
        ISPHToken token,
        address buyer,
        uint256 amountNet
    ) internal view {
        uint16 bps = cfg.maxTxBpsOfPoolBuy();
        if (bps == 0 || cfg.isExcludedFromFees(buyer)) return;

        (uint256 poolUsdt, uint256 usdtBal, address usdt) = _poolUsdtState(token);
        if (poolUsdt == 0 || usdt == address(0)) return;

        uint256 tradeU;
        if (usdtBal > poolUsdt) {
            tradeU = usdtBal - poolUsdt;
        } else {
            uint256 gross = amountNet;
            if (cfg.enableBuyTax()) {
                uint256 feeBps = cfg.buyFeeBps();
                if (feeBps > 0 && feeBps < BPS) {
                    gross = (amountNet * BPS) / (BPS - feeBps);
                }
            }
            tradeU = token.sphToUsdt(gross);
        }
        if (tradeU == 0) return;
        if (tradeU > (poolUsdt * uint256(bps)) / BPS) revert MaxTxUsdtExceeded();
    }

    /// @dev 卖出:按税后进池 SPH 的 U 估值
    function _enforceMaxTxUsdtSell(
        IConfig cfg,
        ISPHToken token,
        address seller,
        uint256 amountNet
    ) internal view {
        uint16 bps = cfg.maxTxBpsOfPoolSell();
        if (bps == 0 || cfg.isExcludedFromFees(seller)) return;

        (uint256 poolUsdt, , ) = _poolUsdtState(token);
        if (poolUsdt == 0) return;

        uint256 tradeU = token.sphToUsdt(amountNet);
        if (tradeU == 0) return;
        if (tradeU > (poolUsdt * uint256(bps)) / BPS) revert MaxTxUsdtExceeded();
    }

    function _poolUsdtState(
        ISPHToken token
    ) internal view returns (uint256 poolUsdt, uint256 usdtBal, address usdt) {
        address pair = token.uniswapV2PairAddress();
        if (pair == address(0)) return (0, 0, address(0));

        IUniswapV2Pair p = IUniswapV2Pair(pair);
        address t0 = p.token0();
        address t1 = p.token1();
        address sph = address(token);
        if (t0 == sph) {
            usdt = t1;
        } else if (t1 == sph) {
            usdt = t0;
        } else {
            return (0, 0, address(0));
        }

        (uint112 r0, uint112 r1, ) = p.getReserves();
        poolUsdt = usdt == t0 ? uint256(r0) : uint256(r1);
        usdtBal = IERC20(usdt).balanceOf(pair);
    }

    /// @dev 相对 utcDayBaselinePrice 的跌幅阶梯 → extraSellTaxBps(总税=sellFee500+extra)。
    ///      <5%→0;[5,10)→1000;[10,15)→1500;[15,20)→2500;≥20%→4000。不读 extraTaxFreeBps。
    function _syncExtraSellTax(ISPHToken token) internal {
        IConfig cfg = config;
        uint256 baseline = cfg.utcDayBaselinePrice();
        if (baseline == 0) return;

        uint256 spot = token.sphToUsdt(1e18);
        if (spot == 0) return;

        uint256 extra;
        if (spot < baseline) {
            uint256 dropBps = ((baseline - spot) * BPS) / baseline;
            if (dropBps < 500) {
                extra = 0;
            } else if (dropBps < 1000) {
                extra = 1000;
            } else if (dropBps < 1500) {
                extra = 1500;
            } else if (dropBps < 2000) {
                extra = 2500;
            } else {
                extra = 4000;
            }
            if (extra > MAX_EXTRA_SELL_TAX_BPS) {
                extra = MAX_EXTRA_SELL_TAX_BPS;
            }
        }

        cfg.syncExtraSellTaxBps(extra);
        emit ExtraSellTaxSynced(spot, baseline, extra);
    }
}
Compiler settingsShow
{
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun"
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.