Skip to content
Verified contractExactMIT

AutoTradeTokenV4Flash

Address0xc905702ebc36b501ae3debd25f3d015b7c9ce418
Balance

0 ETH

 

Transactions

9

 

Compiler

solc 0.8.38

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.38+commit.1835d247
Language
solidity
Optimization
Yes, 200 runs
EVM version
paris
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,457,154
Creation transaction
0xe1192af416…a76c206c69

AutoTradeTokenV4Flash.sol

// SPDX-License-Identifier: MIT
// AutoTradeTokenV4Flash.sol — "Tech" (TECH), flash-loan edition
// --------------------------------------------------------------------------------
// V4 = V3 + AAVE FLASH-LOAN ENGINE. Everything from v3 is kept (the v3
// documentation below still applies in full): the $1 peg, deposit/redeem at
// the current redeem value, the 70/20/10 profit share, the growing redeem
// rate, the 7-price ring buffer, the thresholds, the thresholdUpdater, and
// the v3 spot auto-trader (autoTrade) — unchanged.
//
// WHAT V4 ADDS — the flash engine (see FLASHLOAN_REBUILD_DESIGN.md):
//  - flashTrade(): borrow stable from Aave V3, run a two-leg swap across
//    TWO routers (buy on one venue, sell on another — a same-pool round
//    trip can never profit), repay loan + premium in the same transaction.
//    Flash profit is realized stable, so it goes straight to pendingProfit
//    and is split 70/20/10 by distributeProfits(), exactly like spot profit.
//  - THE APPROVAL GATE: flashTrade() requires surplus() > 0. Surplus only
//    exists because users APPROVED this contract to pull their stable and
//    deposited it. No approved capital in the contract -> no flash trade.
//    The deposit approval IS Tech's trading approval.
//  - THE PROFIT GATE: a flash trade must clear loan + Aave premium +
//    minNetProfit (owner-set, in stable units) or the whole transaction
//    reverts and only gas is lost. Gas is paid by the caller, so the
//    off-chain watcher must simulate NET profit (after premium AND gas)
//    before calling; the on-chain gate is the last line of defence.
//  - The borrowed asset MUST be the stable token (profit has to land in
//    stable to feed pendingProfit). The middle token is normally WETH.
//  - The 9% rule stays with the SPOT engine (autoTrade) — it is a
//    directional rule and does not apply to same-block flash arbitrage.
//    The flash engine's gate is minNetProfit, not the 9% rule.
//  - Two routers per trade (routerOut, routerBack). Each must be the
//    configured router or an owner-allowlisted flash router.
//  - maxFlashLoan defaults to 0: flash trading is OFF until the owner
//    sets a limit. Flash trading is blocked while paused; redeem is
//    never blocked by pause, same as v3.
//  - REENTRANCY NOTE: flashTrade() deliberately has NO nonReentrant guard:
//    it calls the Aave Pool, which calls back into executeOperation() in
//    the SAME transaction — if flashTrade held the guard, the callback
//    would revert. executeOperation() HAS the guard (shared with v3's
//    guarded functions) and is additionally callable ONLY by the Pool,
//    ONLY when this contract started the loan. A re-entrant call from a
//    router into any guarded function reverts on the guard; into any
//    unguarded trading function it reverts on the caller check.
//  - UNAUDITED, LOCAL-TEST ONLY. Not deployed anywhere. A professional
//    audit is REQUIRED before any mainnet use with real money.
// --------------------------------------------------------------------------------
// V3 DOCUMENTATION (still applies — v4 changes nothing below except where
// the v4 preamble above says so):
// AutoTradeTokenV3.sol — "Tech" (TECH)
// --------------------------------------------------------------------------------
// V3 = AutoTradeTokenV2 + PROFIT SHARE. Everything from v2 is kept
// (transferOwnership included); the only changes are the profit-share
// mechanism described below. Same constructor arguments as v2.
//
// PROFIT SHARE — holders earn a cut of the trading profits
//  In v2, trading profit just sat in the surplus: holders got nothing from
//  it and the owner could withdraw all of it. In v3, realized trading
//  profit is split 70% holders / 20% trading capital / 10% treasury, and
//  the holders' share stays in the contract as extra backing (profitPool),
//  so each Tech slowly becomes redeemable for MORE than $1:
//      redeemValue = techAmount x (backingRequired + profitPool) / totalSupply
//  With no profit yet, profitPool is 0 and redeem pays exactly $1 per Tech
//  — v3 behaves exactly like v2. As profits are distributed, the redeem
//  value grows. Holders do nothing: no claiming, no staking. Holding Tech
//  is enough.
//
//  HOW PROFIT IS MEASURED (cost basis, realized only)
//  - wethCostBasis tracks the stable spent acquiring the WETH the contract
//    holds. Buying adds to it; selling compares the stable received with
//    the pro-rata cost of the WETH sold. Proceeds above cost = realized
//    profit (added to pendingProfit). Proceeds below cost = realized loss,
//    which absorbs pendingProfit first (floored at zero) and otherwise just
//    shrinks the surplus. Losses NEVER touch the backing or the profitPool.
//  - Unrealized WETH gains are not profit until sold. Direct stable
//    donations are trading capital, not profit (seed money is never
//    scattered as "profit").
//
//  WHEN PROFITS ARE SHARED (periodic distribution)
//  - Realized profit accumulates in pendingProfit. distributeProfits()
//    (owner or tradingBot) splits it: holders' share -> profitPool,
//    treasury share -> sent to the treasury address, trading share stays
//    in the surplus to compound. The runner calls it after trades or on a
//    schedule. Distribution is deliberately NOT per-trade (gas + noise).
//
//  WHY DEPOSIT MINTS AT THE CURRENT REDEEM RATE
//  - depositStable mints Tech at the current redeem value: exactly 1:1
//    while no profit has accrued, and at the grown rate after profits
//    (e.g. $1.05 buys 1 Tech when 1 Tech redeems for $1.05). The premium
//    over the $1 backing flows into the profitPool, so existing holders
//    are never diluted. If deposit stayed literally 1:1 while redeem paid
//    $1.05, anyone could deposit $1,000,000 and immediately redeem
//    $1,050,000, draining every holder's profit in one transaction.
//    Minting at the current rate makes a deposit-then-redeem round trip
//    value-neutral. Redeem symmetrically pays out the holder's share of
//    the profitPool and reduces it by that amount.
//
//  THE SPLIT (owner-adjustable within guards)
//  - Default 70% holders / 20% trading capital / 10% treasury. Holders
//    get the clear majority because "buy into the wallet and earn" is the
//    pitch; trading capital compounds so the engine grows; treasury is a
//    modest operator cut. setProfitShares enforces: holder share >= 50%,
//    treasury share <= 25%, and the three shares must sum to 100%.
//
//  Full design, alternatives, and edge cases: PROFIT_SHARE_DESIGN.md.
//
// WHAT THIS IS
//  Tech is a STABLE token: 1 Tech = $1, backed 1:1 by a stable token held in
//  this contract (USDT on mainnet, a test stable token on Sepolia).
//
// HOW THE PEG WORKS (plain language)
//  - depositStable(amount): you send stable tokens to the contract and it
//    mints Tech at the current redeem value. While no profit has accrued
//    that is 1:1 (1 stable unit ($1) = 1 Tech); after profits, the mint
//    rate tracks the grown redeem value so new depositors neither dilute
//    past profit nor steal it (see PROFIT SHARE above). Tech has 18
//    decimals and the stable token usually has 6, so the contract converts
//    between them (1e6 stable units = 1e18 Tech at the $1 rate).
//  - redeem(amount): you burn Tech and the contract sends you the same
//    USD value of stable tokens back — $1 per Tech plus your share of the
//    profitPool once profits have been distributed. Redeem ALWAYS works —
//    even while the contract is paused — as long as the contract holds
//    enough stable.
//  - The contract must always hold at least `totalSupply` worth of stable
//    tokens. That is the backing. It is never traded and never withdrawn.
//    On top of the backing sits the profitPool (holders' share of realized
//    profits), which is also never traded and never withdrawn — it is
//    paid out only through redeem.
//  - AUTO-TRADE USES ONLY THE SURPLUS: the stable balance ABOVE the
//    backing. Surplus appears when trades profit, or when someone sends
//    stable to the contract directly without depositing. Buy-low swaps 50%
//    of surplus stable -> WETH; sell-high swaps 50% of WETH -> stable.
//    If surplus is zero, autoTrade does nothing. Trading can never break
//    the peg, because it can never touch backing.
//
//  The price comes from a Chainlink AggregatorV3 feed (constructor argument,
//  owner-updatable — no network is hardcoded). Swaps go through a configured
//  Uniswap V2 router (also a constructor argument, owner-updatable).
//
//  A keeper must call autoTrade(). The contract cannot wake itself up and
//  cannot change its own code. See "HONEST LIMITS" below.
//
// ONE SYSTEM — Tech + analyst + runner (see TECH_SYSTEM_GUIDE.md)
//  This contract is one piece of a single system:
//   - ON-CHAIN (this contract): the stable token, the peg, the surplus
//     trader, and a small trend check — a ring buffer of the last 7
//     Chainlink prices with their moving average. A contract cannot read
//     the internet, so the full analyst (30 days of candles, RSI,
//     momentum) cannot live on-chain; the on-chain check is deliberately
//     small: once the buffer is full, a buy also requires the price to
//     be below its recent average, and a sell also requires it to be
//     above it. Until the buffer fills, trades use the thresholds alone.
//   - OFF-CHAIN BRAIN (marketAnalyst.js): reads public market data,
//     scores every token, and suggests the buyBelow/sellAbove levels.
//   - OFF-CHAIN RUNNER (techSystem.js): runs the analyst, sets the
//     suggested thresholds through the thresholdUpdater role (which can
//     ONLY set thresholds — it holds no owner power), pokes the latest
//     price into the buffer, and calls autoTrade() when one would fire.
//     The owner key is never needed for the loop to run.
//
// HOW IT IS CALLED
//  depositStable(amount) — anyone, needs prior approval of the stable token.
//  redeem(amount)        — anyone holding Tech. Never blocked by pause.
//  distributeProfits()   — owner OR tradingBot. Splits accumulated realized
//                          profit 70/20/10 (holders / trading capital /
//                          treasury). Not blocked by pause.
//  pokePrice()           — owner OR tradingBot. Records the current
//                          Chainlink price into the 7-price ring buffer.
//                          Not blocked by pause (recording a price moves
//                          no funds and cannot break the peg).
//  autoTrade()           — owner OR the tradingBot (set by owner, revoke with
//                          setTradingBot(0)). Blocked while paused, and
//                          blocked when there is no surplus to trade.
//  setBuyBelow / setSellAbove — owner OR the thresholdUpdater (set by
//                          owner, revoke with setThresholdUpdater(0)).
//                          The updater can ONLY set thresholds — it cannot
//                          withdraw, pause, set the bot, or change any
//                          other setting.
//
// HONEST LIMITS — read before deploying anywhere with real money
//  - NO SELF-UPDATING CODE. A deployed contract is immutable. "Automatically
//    updated" here means the owner can update SETTINGS (thresholds, router,
//    price feed, bot, slippage, staleness) — the code itself never changes.
//    Anyone promising a contract that rewrites itself is selling you a story.
//  - NO SELF-TRIGGERING. Nothing on-chain calls autoTrade() for you. A
//    keeper (the watcher script, Chainlink Automation, or a human) must send
//    the transaction. Without a keeper, the contract never trades.
//  - THIS IS NOT A BATTLE-TESTED STABLECOIN. There is no liquidation
//    engine, no oracle fallback, and no circuit breaker on the peg — and the
//    peg is only as good as the stable token backing it: if the backing
//    stable token itself loses its peg, Tech loses its peg too. If a bug or
//    a bad trade ever left the contract holding less stable than the Tech in
//    circulation, later redeemers would be short: redeem reverts instead of
//    paying a partial amount, so check backingRatio() before trusting the peg.
//    A redeem always pays from the stable balance only — WETH holdings do
//    not count as backing.
//  - BUY LOW / SELL HIGH IS NOT A PROFIT GUARANTEE. It is only as good as
//    the thresholds the owner sets and the oracle price it reads. A price can
//    keep falling after a "buy low" and keep rising after a "sell high".
//    Gas and slippage eat returns on every trade, and a 50% trade size means
//    the surplus is never fully in or fully out. The profit share only
//    divides profit that actually exists — in a flat or losing market
//    there may be nothing to share, and the redeem value simply stays $1.
//  - THE ON-CHAIN AVERAGE IS A 7-SAMPLE TREND CHECK, NOT THE ANALYST.
//    The ring buffer holds only the last 7 recorded prices — it cannot see
//    RSI, momentum, or a 30-day range. It only stops the obvious mistakes
//    (buying into a price that is still above its own recent average).
//    The real judgement lives off-chain in the analyst; the contract is
//    the last safety net, not the brain.
//  - UNAUDITED, SEPOLIA-FIRST TEST TEMPLATE. Do not put real funds in it and
//    do not deploy it on mainnet without a full review. Start tiny, verify
//    every step, and never deploy more than you can afford to lose.
//
// SAFETY BUILT IN
//  - Backing is sacred: autoTrade only ever spends surplus stable, the owner
//    can only withdraw surplus stable, and redeem reverts instead of paying
//    out more stable than the contract holds. The profitPool is sacred too:
//    it is never traded, never withdrawn, and only leaves through redeem.
//  - Undistributed profit is ring-fenced: the owner's stable withdrawal is
//    capped at surplus minus pendingProfit, so profit that has not been
//    distributed yet cannot be taken. The treasury share is paid by the
//    distribution rules, not by withdrawal.
//  - Redeem is never blocked by pause: users can always exit, at the grown
//    redeem value. Deposit is blocked while paused (no new money into a
//    troubled contract). Plain Tech transfers are never blocked by pause.
//  - Exact approvals only: the contract approves the router for exactly the
//    swap amount, per trade. No unlimited approvals.
//  - minOut is computed from getAmountsOut minus owner-set slippage (default
//    1%). A worse-than-expected price reverts the swap.
//  - Price must be > 0 and fresh (updatedAt within maxStaleness, default
//    1 hour). A stale or dead feed blocks trading instead of trading blind.
//  - buyBelow must be < sellAbove, enforced on every threshold change.
//  - The stable token cannot be changed while any Tech exists: swapping the
//    backing token under live holders would break the peg math.
//  - Reentrancy guard on deposit, redeem, autoTrade, and withdrawals.
//  - Only the configured router is ever used; owner and bot are the only
//    callers of autoTrade(); only the owner can change settings, except
//    the two thresholds, which the thresholdUpdater may also set (and
//    nothing else). The bot and the updater can NEVER withdraw funds.
// --------------------------------------------------------------------------------

pragma solidity ^0.8.20;

interface IERC20 {
    function balanceOf(address account) external view returns (uint256);
    function decimals() external view returns (uint8);
    function approve(address spender, uint256 amount) external returns (bool);
    function transfer(address to, uint256 amount) external returns (bool);
    function transferFrom(address from, address to, uint256 amount) external returns (bool);
}

interface IUniswapV2Router {
    function getAmountsOut(uint256 amountIn, address[] calldata path)
        external view returns (uint256[] memory amounts);
    function swapExactTokensForTokens(
        uint256 amountIn,
        uint256 amountOutMin,
        address[] calldata path,
        address to,
        uint256 deadline
    ) external returns (uint256[] memory amounts);
}

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

// Aave V3 flash-loan interfaces (minimal, same as FlashLoanBot.sol).
interface IPoolAddressesProvider {
    function getPool() external view returns (address);
}

interface IPool {
    function flashLoanSimple(
        address receiverAddress,
        address asset,
        uint256 amount,
        bytes calldata params,
        uint16 referralCode
    ) external;
}

interface IFlashLoanSimpleReceiver {
    function executeOperation(
        address asset,
        uint256 amount,
        uint256 premium,
        address initiator,
        bytes calldata params
    ) external returns (bool);
}

contract AutoTradeTokenV4Flash is IFlashLoanSimpleReceiver {
    // --- ERC20 state ---
    string public constant name = "Tech";
    string public constant symbol = "TECH";
    uint8 public constant decimals = 18;
    uint256 public totalSupply;
    mapping(address => uint256) public balanceOf;
    mapping(address => mapping(address => uint256)) public allowance;

    event Transfer(address indexed from, address indexed to, uint256 value);
    event Approval(address indexed owner, address indexed spender, uint256 value);

    // --- Trading state ---
    address public owner;
    address public tradingBot;
    address public thresholdUpdater; // may ONLY set buyBelow / sellAbove
    address public stableToken; // e.g. USDT on mainnet, a test token on Sepolia
    address public weth;
    address public router; // Uniswap V2 router
    address public priceFeed; // Chainlink ETH/USD AggregatorV3
    uint256 public buyBelow; // 8-decimal USD: trade BUY when price <= this
    uint256 public sellAbove; // 8-decimal USD: trade SELL when price >= this
    uint256 public slippageBps = 100; // 1% default
    uint256 public maxStaleness = 3600; // 1 hour default
    uint8 public stableDecimals;
    bool public paused;

    // --- Profit share state (v3) ---
    // profitPool: stable earmarked for Tech holders from realized trading
    // profit. Part of the stable balance, counted as holder backing.
    // It only grows via distributeProfits() and deposit premiums, and only
    // shrinks via redeem (holders taking their share out).
    uint256 public profitPool;
    // pendingProfit: realized trading profit not yet distributed. A
    // sub-account of the surplus — the stable is already in the contract;
    // this is just the amount owed to the next distribution.
    uint256 public pendingProfit;
    // wethCostBasis: stable spent acquiring the WETH the contract holds.
    // The sell leg compares proceeds against the pro-rata cost to measure
    // realized profit or loss.
    uint256 public wethCostBasis;
    // treasury: receives the treasury share of every distribution.
    address public treasury;
    // The profit split in basis points (sum must always be 10000).
    // Defaults 70% holders / 20% trading capital / 10% treasury.
    uint256 public holderShareBps = 7000;
    uint256 public tradingShareBps = 2000;
    uint256 public treasuryShareBps = 1000;
    // Running totals for transparency (stable raw units).
    uint256 public totalProfitDistributed;
    uint256 public totalProfitToHolders;

    // --- On-chain trend check: ring buffer of the last 7 recorded
    //     Chainlink prices (8-decimal USD) and their moving average.
    //     The full analyst cannot live on-chain (a contract cannot read
    //     the internet), so this is a small, cheap sanity check: once
    //     the buffer is full, a buy also needs price < average and a
    //     sell also needs price > average. Until it fills, the average
    //     condition is skipped and trades use the thresholds alone.
    uint256 public constant PRICE_WINDOW = 7;
    int256[7] public priceHistory;
    uint256 public priceCount; // how many prices recorded (max 7)
    uint256 public priceHead; // next slot to overwrite once full
    int256 public priceSum; // running sum of the prices in the buffer

    // --- Flash-loan engine state (v4) ---
    // Aave V3 Pool, resolved from the PoolAddressesProvider at deploy.
    address public immutable POOL;
    // Max single flash loan (stable raw units). Defaults to 0: flash
    // trading is OFF until the owner sets a limit.
    uint256 public maxFlashLoan;
    // Minimum net profit a flash trade must clear, in stable raw units,
    // ABOVE loan + Aave premium. Owner-set; covers the expected gas cost
    // plus the minimum profit worth taking. Defaults to 0.
    uint256 public minNetProfit;
    // Extra routers the flash engine may use, besides the configured
    // `router` (which is always allowed). Owner-set. A flash trade needs
    // two venues to capture a price gap; both legs must use an allowed
    // router.
    mapping(address => bool) public allowedFlashRouters;

    // --- Events ---
    event Deposit(address indexed user, uint256 stableIn, uint256 techOut);
    event Redeem(address indexed user, uint256 techIn, uint256 stableOut);
    event Trade(
        bool indexed isBuy,
        int256 price,
        address indexed tokenIn,
        address indexed tokenOut,
        uint256 amountIn,
        uint256 amountOut
    );
    event ThresholdsUpdated(uint256 buyBelow, uint256 sellAbove);
    event ThresholdUpdaterUpdated(address thresholdUpdater);
    event PriceRecorded(int256 price, int256 average, uint256 count);
    event SlippageUpdated(uint256 slippageBps);
    event MaxStalenessUpdated(uint256 maxStaleness);
    event RouterUpdated(address router);
    event StableTokenUpdated(address stableToken);
    event WethUpdated(address weth);
    event PriceFeedUpdated(address priceFeed);
    event TradingBotUpdated(address tradingBot);
    event PausedUpdated(bool paused);
    event OwnershipTransferred(address indexed oldOwner, address indexed newOwner);
    event ProfitsDistributed(
        uint256 profit,
        uint256 holderShare,
        uint256 tradingShare,
        uint256 treasuryShare,
        uint256 newProfitPool
    );
    event ProfitSharesUpdated(uint256 holderShareBps, uint256 tradingShareBps, uint256 treasuryShareBps);
    event TreasuryUpdated(address treasury);
    // --- Flash-loan events (v4) ---
    event FlashTradeRequested(address indexed asset, uint256 amount);
    event FlashTradeExecuted(
        address indexed asset,
        uint256 amount,
        uint256 premium,
        uint256 amountOwed,
        uint256 profit
    );
    event MaxFlashLoanUpdated(uint256 maxFlashLoan);
    event MinNetProfitUpdated(uint256 minNetProfit);
    event FlashRouterAllowed(address indexed router, bool allowed);

    // --- Errors ---
    error NotOwner();
    error NotAuthorized();
    error IsPaused();
    error PriceInRange(int256 price, uint256 buyBelow, uint256 sellAbove);
    error NotBelowAverage(int256 price, int256 average);
    error NotAboveAverage(int256 price, int256 average);
    error StalePrice(uint256 updatedAt, uint256 now_);
    error InvalidPrice(int256 price);
    error InvalidThreshold();
    error ZeroAddress();
    error ZeroAmount();
    error NoSurplus();
    error NoWethBalance();
    error InsufficientBacking(uint256 needed, uint256 available);
    error InsufficientSurplus(uint256 requested, uint256 available);
    error StableTokenLocked();
    error SlippageTooHigh();
    error Reentrancy();
    error NoProfitToDistribute();
    error InvalidProfitShares();
    // --- Flash-loan errors (v4) ---
    error NotPool();
    error NotInitiator();
    error NotStableAsset();
    error LoanTooLarge();
    error RouterNotAllowed();
    error InsufficientToRepay();
    error ProfitBelowMinimum(uint256 profit, uint256 minNetProfit);
    error TokenCallFailed();
    error TokenCallReturnedFalse();


    bool private _locked;

    modifier onlyOwner() {
        if (msg.sender != owner) revert NotOwner();
        _;
    }

    modifier nonReentrant() {
        if (_locked) revert Reentrancy();
        _locked = true;
        _;
        _locked = false;
    }

    constructor(
        address _stableToken,
        address _weth,
        address _router,
        address _priceFeed,
        uint256 _buyBelow,
        uint256 _sellAbove,
        address _poolAddressesProvider
    ) {
        if (
            _stableToken == address(0) ||
            _weth == address(0) ||
            _router == address(0) ||
            _priceFeed == address(0) ||
            _poolAddressesProvider == address(0)
        ) revert ZeroAddress();
        if (_buyBelow == 0 || _sellAbove == 0 || _buyBelow >= _sellAbove) {
            revert InvalidThreshold();
        }
        owner = msg.sender;
        treasury = msg.sender; // default treasury is the owner; owner can change it
        stableToken = _stableToken;
        weth = _weth;
        router = _router;
        priceFeed = _priceFeed;
        buyBelow = _buyBelow;
        sellAbove = _sellAbove;
        stableDecimals = IERC20(_stableToken).decimals();
        POOL = IPoolAddressesProvider(_poolAddressesProvider).getPool();
        // maxFlashLoan starts at 0: flash trading is OFF until the owner
        // sets a limit. minNetProfit starts at 0.
        // No premint: Tech is minted only when stable is deposited.
    }


    // --- SafeERC20-style token calls (no imports, self-contained) ---
    /// @dev Low-level ERC20 call that accepts EITHER a bool `true` return
    ///      OR empty returndata. Real USDT returns NOTHING from transfer /
    ///      transferFrom / approve — proven on a mainnet fork (its
    ///      transferFrom succeeds but returns 0x), which reverts a
    ///      standard `returns (bool)` ABI decode. This is the SafeERC20
    ///      pattern, inlined so the file stays self-contained.
    function _callOptionalReturn(address token, bytes memory data) internal {
        (bool success, bytes memory ret) = token.call(data);
        if (!success) revert TokenCallFailed();
        if (ret.length > 0) {
            if (!abi.decode(ret, (bool))) revert TokenCallReturnedFalse();
        }
    }

    function _safeTransfer(address token, address to, uint256 amount) internal {
        _callOptionalReturn(token, abi.encodeCall(IERC20.transfer, (to, amount)));
    }

    function _safeTransferFrom(address token, address from, address to, uint256 amount) internal {
        _callOptionalReturn(token, abi.encodeCall(IERC20.transferFrom, (from, to, amount)));
    }

    function _safeApprove(address token, address spender, uint256 amount) internal {
        _callOptionalReturn(token, abi.encodeCall(IERC20.approve, (spender, amount)));
    }

    // --- ERC20 ---
    function transfer(address to, uint256 amount) external returns (bool) {
        require(balanceOf[msg.sender] >= amount, "insufficient balance");
        balanceOf[msg.sender] -= amount;
        balanceOf[to] += amount;
        emit Transfer(msg.sender, to, amount);
        return true;
    }

    function approve(address spender, uint256 amount) external returns (bool) {
        allowance[msg.sender][spender] = amount;
        emit Approval(msg.sender, spender, amount);
        return true;
    }

    function transferFrom(address from, address to, uint256 amount) external returns (bool) {
        require(balanceOf[from] >= amount, "insufficient balance");
        require(allowance[from][msg.sender] >= amount, "allowance exceeded");
        allowance[from][msg.sender] -= amount;
        balanceOf[from] -= amount;
        balanceOf[to] += amount;
        emit Transfer(from, to, amount);
        return true;
    }

    // --- Peg: deposit / redeem ---
    /// @notice Deposit stable tokens, mint Tech at the current redeem
    ///         value. While no profit has accrued the mint is exactly 1:1
    ///         (same as v2); after profits, the mint rate tracks the grown
    ///         redeem value, so a new depositor neither dilutes past profit
    ///         nor steals it — a deposit-then-redeem round trip returns
    ///         exactly what was deposited. The premium over the $1 backing
    ///         flows into the profitPool, which is what keeps the redeem
    ///         rate unchanged by the deposit. Caller must approve this
    ///         contract for `amount` first. Blocked while paused (no new
    ///         money into a troubled contract).
    function depositStable(uint256 amount) external nonReentrant {
        if (paused) revert IsPaused();
        if (amount == 0) revert ZeroAmount();
        uint256 techOut;
        if (totalSupply == 0) {
            // First deposit: the rate is $1.00 by definition.
            techOut = _toTechUnits(amount);
        } else {
            // Fair-value mint at the current redeem rate. Capped at the
            // plain 1:1 mint: when no profit has accrued and the supply
            // is not a whole multiple of the stable decimals, rounding in
            // holderBacking() could otherwise mint a dust amount above
            // 1:1. The cap never binds once any profit exists.
            techOut = (amount * totalSupply) / holderBacking();
            uint256 maxTech = _toTechUnits(amount);
            if (techOut > maxTech) techOut = maxTech;
        }
        if (techOut == 0) revert ZeroAmount();
        _safeTransferFrom(stableToken, msg.sender, address(this), amount);
        // The premium over the $1 backing compensates existing holders
        // for sharing their profit pool with the new depositor. It is 0
        // while no profit has accrued. (The cap above guarantees
        // _toStableUnits(techOut) <= amount, so this cannot underflow.)
        uint256 premium = amount - _toStableUnits(techOut);
        if (premium > 0) profitPool += premium;
        totalSupply += techOut;
        balanceOf[msg.sender] += techOut;
        emit Transfer(address(0), msg.sender, techOut);
        emit Deposit(msg.sender, amount, techOut);
    }

    /// @notice Burn Tech, receive stable tokens back at the current redeem
    ///         value — $1 per Tech plus your share of the profitPool once
    ///         profits have been distributed. The profit portion of the
    ///         payout comes out of the profitPool, so the redeem rate for
    ///         remaining holders is unchanged. Deliberately NEVER blocked
    ///         by pause — users must always exit. Reverts instead of
    ///         paying out more stable than the contract holds, so a
    ///         shortfall is visible instead of silently partial.
    function redeem(uint256 techAmount) external nonReentrant {
        if (techAmount == 0) revert ZeroAmount();
        uint256 stableOut = redeemValue(techAmount);
        if (stableOut == 0) revert ZeroAmount();
        require(balanceOf[msg.sender] >= techAmount, "insufficient balance");
        uint256 stableBal = IERC20(stableToken).balanceOf(address(this));
        if (stableOut > stableBal) revert InsufficientBacking(stableOut, stableBal);
        // The profit portion of this payout leaves the profitPool. It is
        // the redeemer's pro-rata share of distributed profit. The
        // ternary guards a 1-unit rounding edge: when no profit has
        // accrued and the supply is not a whole multiple of the stable
        // decimals, stableOut can round to 1 unit below the $1 value, in
        // which case the profit portion is simply 0. The clamp guards
        // the mirror edge when redeeming nearly all of the supply.
        uint256 baseOut = _toStableUnits(techAmount);
        uint256 profitPortion = stableOut > baseOut ? stableOut - baseOut : 0;
        if (profitPortion > profitPool) profitPortion = profitPool;
        if (profitPortion > 0) profitPool -= profitPortion;
        balanceOf[msg.sender] -= techAmount;
        totalSupply -= techAmount;
        emit Transfer(msg.sender, address(0), techAmount);
        _safeTransfer(stableToken, msg.sender, stableOut);
        emit Redeem(msg.sender, techAmount, stableOut);
    }

    // --- Peg views ---
    /// @notice Stable tokens required to back all Tech in circulation.
    function backingRequired() public view returns (uint256) {
        return _toStableUnits(totalSupply);
    }

    /// @notice Total stable owed to Tech holders: the $1 backing plus the
    ///         profitPool (holders' share of distributed profit).
    function holderBacking() public view returns (uint256) {
        return backingRequired() + profitPool;
    }

    /// @notice Stable a holder receives for `techAmount` Tech at the
    ///         current redeem value. Exactly $1 per Tech while no profit
    ///         has been distributed; more once the profitPool has grown.
    ///         Rounds down — dust favours remaining holders.
    function redeemValue(uint256 techAmount) public view returns (uint256) {
        if (totalSupply == 0) return 0;
        return (techAmount * holderBacking()) / totalSupply;
    }

    /// @notice Current redeem rate: stable raw units for 1 whole Tech
    ///         (1e18). $1.00 while no profit has been distributed; grows
    ///         as profits are shared with holders. Returns the $1 rate
    ///         when no Tech exists.
    function redeemRate() public view returns (uint256) {
        if (totalSupply == 0) return _toStableUnits(1e18);
        return (holderBacking() * 1e18) / totalSupply;
    }

    /// @notice Stable balance ABOVE what holders are owed — the only
    ///         stable the contract may trade with, and the only stable
    ///         the owner may withdraw (minus undistributed profit, see
    ///         withdrawToken). The profitPool is holder money, so it is
    ///         NOT surplus. Zero when fully backed with no extra stable.
    function surplus() public view returns (uint256) {
        uint256 stableBal = IERC20(stableToken).balanceOf(address(this));
        uint256 owed = holderBacking();
        return stableBal > owed ? stableBal - owed : 0;
    }

    /// @notice Backing health in basis points: 10000 = fully backed at $1.
    ///         Above 10000 means surplus stable and/or holder profit is
    ///         held. Returns 10000 when no Tech exists (nothing to back).
    function backingRatio() public view returns (uint256) {
        uint256 required = backingRequired();
        if (required == 0) return 10000;
        uint256 stableBal = IERC20(stableToken).balanceOf(address(this));
        return (stableBal * 10000) / required;
    }

    /// @dev Stable raw units -> Tech raw units (18 decimals).
    ///      _toStableUnits rounds DOWN (dust favours remaining holders).
    function _toTechUnits(uint256 stableAmount) internal view returns (uint256) {
        if (stableDecimals >= 18) return stableAmount / (10 ** (stableDecimals - 18));
        return stableAmount * (10 ** (18 - stableDecimals));
    }

    /// @dev Tech raw units (18 decimals) -> stable raw units.
    function _toStableUnits(uint256 techAmount) internal view returns (uint256) {
        if (stableDecimals >= 18) return techAmount * (10 ** (stableDecimals - 18));
        return techAmount / (10 ** (18 - stableDecimals));
    }

    // --- Price ---
    /// @notice Latest ETH/USD price from the Chainlink feed (8 decimals).
    function getLatestPrice() public view returns (int256 price, uint256 updatedAt) {
        (, int256 answer, , uint256 _updatedAt, ) = IAggregatorV3(priceFeed).latestRoundData();
        return (answer, _updatedAt);
    }

    /// @notice Moving average of the recorded prices (8-decimal USD).
    ///         Returns 0 while nothing has been recorded yet.
    function priceAverage() public view returns (int256) {
        if (priceCount == 0) return 0;
        return priceSum / int256(priceCount);
    }

    /// @notice Record the current Chainlink price into the ring buffer.
    ///         Owner or tradingBot only. Deliberately NOT blocked by
    ///         pause: recording a price moves no funds and cannot break
    ///         the peg — a paused contract should still keep its trend
    ///         record fresh so trading can resume accurately. A stale or
    ///         invalid feed price is never recorded.
    function pokePrice() external {
        if (msg.sender != owner && msg.sender != tradingBot) revert NotAuthorized();
        (int256 price, uint256 updatedAt) = getLatestPrice();
        if (price <= 0) revert InvalidPrice(price);
        if (updatedAt == 0 || block.timestamp - updatedAt > maxStaleness) {
            revert StalePrice(updatedAt, block.timestamp);
        }
        if (priceCount < PRICE_WINDOW) {
            priceHistory[priceCount] = price;
            priceSum += price;
            priceCount++;
        } else {
            int256 old = priceHistory[priceHead];
            priceHistory[priceHead] = price;
            priceSum = priceSum - old + price;
            priceHead = (priceHead + 1) % PRICE_WINDOW;
        }
        emit PriceRecorded(price, priceAverage(), priceCount);
    }

    /// @notice Treasury balances plus the WETH leg valued in stable-token units.
    /// @return stableBal stable-token balance held by this contract
    /// @return wethBal WETH balance held by this contract
    /// @return wethValueInStable WETH balance converted to stable units at the
    ///         latest feed price (0 if the price is invalid/stale — callers
    ///         should check getLatestPrice() separately)
    function treasuryValue()
        external
        view
        returns (uint256 stableBal, uint256 wethBal, uint256 wethValueInStable)
    {
        stableBal = IERC20(stableToken).balanceOf(address(this));
        wethBal = IERC20(weth).balanceOf(address(this));
        (int256 price, uint256 updatedAt) = getLatestPrice();
        if (price <= 0 || updatedAt == 0 || block.timestamp - updatedAt > maxStaleness) {
            return (stableBal, wethBal, 0);
        }
        // price is USD/ETH with 8 decimals; wethBal is 18-decimal wei.
        // value in stable units = wethBal * price * 10^stableDecimals / 1e26
        wethValueInStable =
            (wethBal * uint256(price) * (10 ** uint256(stableDecimals))) / 1e26;
    }

    // --- Auto-trade (surplus only — backing is never touched) ---
    /// @notice Buy low (price <= buyBelow) or sell high (price >= sellAbove),
    ///         swapping exactly 50% of the SURPLUS stable balance (buy) or
    ///         50% of the WETH balance (sell). Once the 7-price buffer is
    ///         full, the buy leg also requires price < the moving average
    ///         and the sell leg also requires price > it; while the buffer
    ///         is still filling, the average condition is skipped and the
    ///         thresholds alone decide. Reverts with PriceInRange when the
    ///         price sits between the thresholds, NotBelowAverage /
    ///         NotAboveAverage when the trend gate blocks the trade,
    ///         NoSurplus when there is no surplus stable to buy with,
    ///         and StalePrice when the feed is too old.
    function autoTrade() external nonReentrant {
        if (paused) revert IsPaused();
        if (msg.sender != owner && msg.sender != tradingBot) revert NotAuthorized();

        (int256 price, uint256 updatedAt) = getLatestPrice();
        if (price <= 0) revert InvalidPrice(price);
        if (updatedAt == 0 || block.timestamp - updatedAt > maxStaleness) {
            revert StalePrice(updatedAt, block.timestamp);
        }

        if (price <= int256(buyBelow)) {
            // Trend gate (only once the buffer is full): the price must
            // actually have dipped BELOW its recent average to buy.
            if (priceCount >= PRICE_WINDOW && price >= priceAverage()) {
                revert NotBelowAverage(price, priceAverage());
            }
            uint256 surplusStable = surplus();
            if (surplusStable == 0) revert NoSurplus();
            uint256 amountIn = surplusStable / 2;
            if (amountIn == 0) revert ZeroAmount();
            uint256 amountOut = _swap(stableToken, weth, amountIn);
            // Buying is not profit or loss — it moves the cost basis.
            wethCostBasis += amountIn;
            emit Trade(true, price, stableToken, weth, amountIn, amountOut);
        } else if (price >= int256(sellAbove)) {
            // Trend gate (only once the buffer is full): the price must
            // actually have risen ABOVE its recent average to sell.
            if (priceCount >= PRICE_WINDOW && price <= priceAverage()) {
                revert NotAboveAverage(price, priceAverage());
            }
            uint256 wethBal = IERC20(weth).balanceOf(address(this));
            if (wethBal == 0) revert NoWethBalance();
            uint256 amountIn = wethBal / 2;
            if (amountIn == 0) revert ZeroAmount();
            uint256 amountOut = _swap(weth, stableToken, amountIn);
            // Realized P&L on the sold portion (cost-basis accounting):
            // proceeds above the pro-rata cost are profit; below cost is
            // a loss, absorbed by undistributed profit first (floored at
            // zero) and otherwise by the surplus. Losses never touch the
            // backing or the profitPool.
            uint256 costOfSold = (wethCostBasis * amountIn) / wethBal;
            wethCostBasis -= costOfSold;
            if (amountOut > costOfSold) {
                pendingProfit += amountOut - costOfSold;
            } else {
                uint256 loss = costOfSold - amountOut;
                if (loss >= pendingProfit) pendingProfit = 0;
                else pendingProfit -= loss;
            }
            emit Trade(false, price, weth, stableToken, amountIn, amountOut);
        } else {
            revert PriceInRange(price, buyBelow, sellAbove);
        }
    }

    // --- Flash-loan trading (v4) ---
    // Trade parameters for one flash loan, encoded into the loan's `params`
    // so executeOperation() can read them when Aave calls it back.
    struct FlashTradeParams {
        address routerOut; // venue for leg 1 (stable -> middle token)
        address routerBack; // venue for leg 2 (middle token -> stable)
        address[] pathOut; // stable -> middle token
        address[] pathBack; // middle token -> stable
        uint256 minOutFirstLeg;
        uint256 minOutSecondLeg;
    }

    /// @notice Start a flash-loan arbitrage trade. Owner or tradingBot only.
    ///         THE APPROVAL GATE: requires surplus() > 0 — surplus only
    ///         exists because users approved this contract to pull their
    ///         stable and deposited it. No approved capital -> no trade.
    ///         The borrowed asset MUST be the stable token (profit has to
    ///         land in stable to feed pendingProfit). Both routers must be
    ///         the configured router or an owner-allowlisted flash router.
    ///         Blocked while paused. Deliberately NOT nonReentrant: this
    ///         function calls the Aave Pool, which calls back into
    ///         executeOperation() in the SAME transaction — if this function
    ///         held the guard, the callback would revert. executeOperation()
    ///         holds the guard instead (see its comment).
    function flashTrade(
        address asset,
        uint256 amount,
        address routerOut,
        address routerBack,
        address[] calldata pathOut,
        address[] calldata pathBack,
        uint256 minOutFirstLeg,
        uint256 minOutSecondLeg
    ) external {
        if (paused) revert IsPaused();
        if (msg.sender != owner && msg.sender != tradingBot) revert NotAuthorized();
        if (asset != stableToken) revert NotStableAsset();
        if (amount == 0) revert ZeroAmount();
        if (amount > maxFlashLoan) revert LoanTooLarge();
        if (!_isFlashRouter(routerOut) || !_isFlashRouter(routerBack)) revert RouterNotAllowed();
        // THE APPROVAL GATE: no approved capital in the contract, no trade.
        if (surplus() == 0) revert NoSurplus();

        FlashTradeParams memory trade = FlashTradeParams({
            routerOut: routerOut,
            routerBack: routerBack,
            pathOut: pathOut,
            pathBack: pathBack,
            minOutFirstLeg: minOutFirstLeg,
            minOutSecondLeg: minOutSecondLeg
        });

        emit FlashTradeRequested(asset, amount);

        IPool(POOL).flashLoanSimple(
            address(this),
            asset,
            amount,
            abi.encode(trade),
            0
        );
    }

    /// @notice Called by the Aave Pool only, in the same transaction as the
    ///         loan. Runs the two-leg swap, checks repayment + the profit
    ///         gate, repays exactly what is owed, and books the profit into
    ///         pendingProfit (the same realized-profit bucket the spot
    ///         engine feeds — distributeProfits() splits it 70/20/10).
    ///         If the trade cannot cover loan + premium + minNetProfit, it
    ///         reverts and the whole flash loan reverts: only gas is lost.
    ///         Holds the reentrancy guard (flashTrade does not — see above).
    function executeOperation(
        address asset,
        uint256 amount,
        uint256 premium,
        address initiator,
        bytes calldata params
    ) external override nonReentrant returns (bool) {
        if (msg.sender != POOL) revert NotPool();
        if (initiator != address(this)) revert NotInitiator();

        FlashTradeParams memory trade = abi.decode(params, (FlashTradeParams));
        uint256 amountOwed = amount + premium;

        // Balance when the loan arrives: pre-existing stable (backing +
        // surplus + profitPool) PLUS the loan. The trade is measured
        // against THIS, not against the loan alone — otherwise a losing
        // trade could silently eat the contract's own stable (including
        // the BACKING) and still pass a naive "final >= amountOwed"
        // check. Measuring against balanceBefore guarantees the trade
        // pays its own way: after Aave pulls amount + premium, the
        // contract holds at least what it held before the loan, plus
        // the profit. The peg can never subsidise a flash trade.
        uint256 balanceBefore = IERC20(asset).balanceOf(address(this));

        // STAKE-SWEEP FIX (2026-11-17): record the middle-token balance
        // BEFORE leg 1. Leg 2 must swap ONLY what leg 1 produced — the
        // old code swapped the whole middle-token balance, which would
        // have liquidated Tech's open spot WETH position (the middle
        // token here is WETH) AND corrupted the cost-basis accounting,
        // since that sale would bypass autoTrade's wethCostBasis update.
        // The same bug was found live on Sepolia in DollarV3 and
        // SmartWalletV3, where leg 2 sold the whole TST stake.
        // Pre-existing balances of the middle token are never traded.
        address middleToken = trade.pathOut[trade.pathOut.length - 1];
        uint256 middleBalanceBefore = IERC20(middleToken).balanceOf(address(this));

        // Leg 1: stable -> middle token, on routerOut.
        _swapExact(trade.routerOut, asset, trade.minOutFirstLeg, trade.pathOut, amount);

        // Leg 2: ONLY leg 1's output -> stable, on routerBack.
        uint256 middleOut = IERC20(middleToken).balanceOf(address(this)) - middleBalanceBefore;
        _swapExact(trade.routerBack, middleToken, trade.minOutSecondLeg, trade.pathBack, middleOut);

        // Repay + profit gates: the trade's own P&L must cover the Aave
        // premium AND the owner's minimum net profit — otherwise the
        // whole transaction reverts and nothing is lost but gas.
        uint256 finalBalance = IERC20(asset).balanceOf(address(this));
        if (finalBalance < balanceBefore + premium) revert InsufficientToRepay();
        uint256 profit = finalBalance - balanceBefore - premium;
        if (profit < minNetProfit) revert ProfitBelowMinimum(profit, minNetProfit);

        // Repay exactly what is owed — no unlimited approval to the Pool.
        _safeApprove(asset, POOL, amountOwed);

        // Flash profit is realized stable: straight into pendingProfit,
        // to be split 70/20/10 by distributeProfits(). No cost basis is
        // involved — the loan is repaid in full in this transaction.
        pendingProfit += profit;

        emit FlashTradeExecuted(asset, amount, premium, amountOwed, profit);
        return true;
    }

    /// @dev Swap an exact amount through a given router with a caller-set
    ///      minimum output (the watcher simulates and sets it). Approves
    ///      exactly amountIn and nothing more.
    function _swapExact(
        address routerAddr,
        address tokenIn,
        uint256 amountOutMin,
        address[] memory path,
        uint256 amountIn
    ) internal {
        _safeApprove(tokenIn, routerAddr, amountIn);
        IUniswapV2Router(routerAddr).swapExactTokensForTokens(
            amountIn,
            amountOutMin,
            path,
            address(this),
            block.timestamp + 300 // 5-minute deadline
        );
    }

    /// @dev The configured router is always a valid flash router; extras
    ///      are owner-allowlisted.
    function _isFlashRouter(address routerAddr) internal view returns (bool) {
        return routerAddr == router || allowedFlashRouters[routerAddr];
    }

    // --- Flash-loan settings (v4, owner-only) ---
    function setMaxFlashLoan(uint256 _maxFlashLoan) external onlyOwner {
        maxFlashLoan = _maxFlashLoan;
        emit MaxFlashLoanUpdated(_maxFlashLoan);
    }

    function setMinNetProfit(uint256 _minNetProfit) external onlyOwner {
        minNetProfit = _minNetProfit;
        emit MinNetProfitUpdated(_minNetProfit);
    }

    function setFlashRouter(address routerAddr, bool allowed) external onlyOwner {
        if (routerAddr == address(0)) revert ZeroAddress();
        allowedFlashRouters[routerAddr] = allowed;
        emit FlashRouterAllowed(routerAddr, allowed);
    }

    // --- Profit share: distribution ---
    /// @notice Split accumulated realized profit by the configured shares
    ///         (default 70% holders / 20% trading capital / 10% treasury).
    ///         The holders' share joins the profitPool, raising every
    ///         holder's redeem value immediately; the treasury share is
    ///         sent in stable to the treasury address; the trading share
    ///         stays in the surplus to compound. Owner or tradingBot, so
    ///         the runner can call it after trades or on a schedule.
    ///         Deliberately NOT blocked by pause: it moves already-
    ///         realized profit by fixed rules and cannot endanger the peg.
    ///         If no Tech exists, the holder share stays in the surplus as
    ///         trading capital (there are no holders to pay) — nothing is
    ///         lost. Reverts when there is no profit to distribute.
    function distributeProfits() external nonReentrant {
        if (msg.sender != owner && msg.sender != tradingBot) revert NotAuthorized();
        uint256 profit = pendingProfit;
        if (profit == 0) revert NoProfitToDistribute();
        uint256 holderShare = (profit * holderShareBps) / 10000;
        uint256 tradingShare = (profit * tradingShareBps) / 10000;
        // Treasury takes the remainder so rounding dust is never lost.
        uint256 treasuryShare = profit - holderShare - tradingShare;
        pendingProfit = 0;
        totalProfitDistributed += profit;
        if (totalSupply > 0) {
            profitPool += holderShare;
            totalProfitToHolders += holderShare;
        }
        // When totalSupply is 0 the holder share simply stays in the
        // surplus as trading capital.
        if (treasuryShare > 0) {
            _safeTransfer(stableToken, treasury, treasuryShare);
        }
        emit ProfitsDistributed(profit, holderShare, tradingShare, treasuryShare, profitPool);
    }

    /// @dev Swap an exact amount of tokenIn for tokenOut via the configured
    ///      router, approving exactly amountIn and nothing more.
    function _swap(address tokenIn, address tokenOut, uint256 amountIn)
        internal
        returns (uint256 amountOut)
    {
        address[] memory path = new address[](2);
        path[0] = tokenIn;
        path[1] = tokenOut;
        uint256[] memory amountsOut = IUniswapV2Router(router).getAmountsOut(amountIn, path);
        uint256 expectedOut = amountsOut[amountsOut.length - 1];
        uint256 amountOutMin = (expectedOut * (10000 - slippageBps)) / 10000;
        _safeApprove(tokenIn, router, amountIn);
        uint256[] memory amounts = IUniswapV2Router(router).swapExactTokensForTokens(
            amountIn,
            amountOutMin,
            path,
            address(this),
            block.timestamp + 300 // 5-minute deadline
        );
        amountOut = amounts[amounts.length - 1];
    }

    // --- Owner-only settings ---
    /// @dev Owner or the thresholdUpdater. The updater exists so the
    ///      off-chain analyst (techSystem.js) can keep the thresholds
    ///      current without holding the owner key — it can ONLY set
    ///      thresholds, nothing else.
    modifier onlyOwnerOrThresholdUpdater() {
        if (msg.sender != owner && msg.sender != thresholdUpdater) revert NotAuthorized();
        _;
    }

    function setBuyBelow(uint256 _buyBelow) external onlyOwnerOrThresholdUpdater {
        if (_buyBelow == 0 || _buyBelow >= sellAbove) revert InvalidThreshold();
        buyBelow = _buyBelow;
        emit ThresholdsUpdated(buyBelow, sellAbove);
    }

    function setSellAbove(uint256 _sellAbove) external onlyOwnerOrThresholdUpdater {
        if (_sellAbove == 0 || _sellAbove <= buyBelow) revert InvalidThreshold();
        sellAbove = _sellAbove;
        emit ThresholdsUpdated(buyBelow, sellAbove);
    }

    function setThresholdUpdater(address _thresholdUpdater) external onlyOwner {
        thresholdUpdater = _thresholdUpdater; // address(0) revokes the updater
        emit ThresholdUpdaterUpdated(_thresholdUpdater);
    }

    function setSlippageBps(uint256 _slippageBps) external onlyOwner {
        if (_slippageBps > 1000) revert SlippageTooHigh(); // max 10%
        slippageBps = _slippageBps;
        emit SlippageUpdated(_slippageBps);
    }

    function setMaxStaleness(uint256 _maxStaleness) external onlyOwner {
        maxStaleness = _maxStaleness;
        emit MaxStalenessUpdated(_maxStaleness);
    }

    function setRouter(address _router) external onlyOwner {
        if (_router == address(0)) revert ZeroAddress();
        router = _router;
        emit RouterUpdated(_router);
    }

    function setStableToken(address _stableToken) external onlyOwner {
        if (_stableToken == address(0)) revert ZeroAddress();
        // Swapping the backing token under live holders would break the peg
        // math (old Tech would be backed by a token the contract no longer
        // counts). Only allowed while no Tech exists.
        if (totalSupply > 0) revert StableTokenLocked();
        stableToken = _stableToken;
        stableDecimals = IERC20(_stableToken).decimals();
        emit StableTokenUpdated(_stableToken);
    }

    function setWeth(address _weth) external onlyOwner {
        if (_weth == address(0)) revert ZeroAddress();
        weth = _weth;
        emit WethUpdated(_weth);
    }

    function setPriceFeed(address _priceFeed) external onlyOwner {
        if (_priceFeed == address(0)) revert ZeroAddress();
        priceFeed = _priceFeed;
        emit PriceFeedUpdated(_priceFeed);
    }

    function setTradingBot(address _tradingBot) external onlyOwner {
        tradingBot = _tradingBot; // address(0) revokes the bot
        emit TradingBotUpdated(_tradingBot);
    }

    /// @notice Change the profit split. Guarded so it cannot be turned
    ///         against holders: the holder share can never drop below 50%,
    ///         the treasury share can never exceed 25%, and the three
    ///         shares must always sum to 100%.
    function setProfitShares(uint256 _holderBps, uint256 _tradingBps, uint256 _treasuryBps)
        external
        onlyOwner
    {
        if (_holderBps + _tradingBps + _treasuryBps != 10000) revert InvalidProfitShares();
        if (_holderBps < 5000 || _treasuryBps > 2500) revert InvalidProfitShares();
        holderShareBps = _holderBps;
        tradingShareBps = _tradingBps;
        treasuryShareBps = _treasuryBps;
        emit ProfitSharesUpdated(_holderBps, _tradingBps, _treasuryBps);
    }

    /// @notice Change the address that receives the treasury share of
    ///         each distribution. Cannot be the zero address.
    function setTreasury(address _treasury) external onlyOwner {
        if (_treasury == address(0)) revert ZeroAddress();
        treasury = _treasury;
        emit TreasuryUpdated(_treasury);
    }

    // V2/V3: hand ownership to a new address. Irreversible — after this call
    // the old owner has no control at all. Only the current owner can call it.
    function transferOwnership(address newOwner) external onlyOwner {
        if (newOwner == address(0)) revert ZeroAddress();
        address oldOwner = owner;
        owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }

    function setPaused(bool _paused) external onlyOwner {
        paused = _paused;
        emit PausedUpdated(_paused);
    }

    // --- Owner-only withdrawals (bot can NEVER withdraw) ---
    /// @notice Withdraw a token. Stable withdrawals are capped at the
    ///         surplus MINUS undistributed profit — backing can never be
    ///         withdrawn, and neither can profit that has not been
    ///         distributed yet (distribute first; the treasury share is
    ///         then sent by the rules). WETH withdrawals reduce the cost
    ///         basis pro-rata so later sells still measure profit
    ///         honestly. Other tokens are surplus by definition (backing
    ///         is stable only).
    function withdrawToken(address token, address to, uint256 amount)
        external
        onlyOwner
        nonReentrant
    {
        if (to == address(0)) revert ZeroAddress();
        if (token == stableToken) {
            uint256 s = surplus();
            uint256 withdrawable = s > pendingProfit ? s - pendingProfit : 0;
            if (amount > withdrawable) revert InsufficientSurplus(amount, withdrawable);
        } else if (token == weth) {
            uint256 wethBal = IERC20(weth).balanceOf(address(this));
            if (wethBal > 0) {
                uint256 costRemoved = (wethCostBasis * amount) / wethBal;
                if (costRemoved > wethCostBasis) costRemoved = wethCostBasis;
                wethCostBasis -= costRemoved;
            }
        }
        _safeTransfer(token, to, amount);
    }

    function withdrawETH(address to, uint256 amount) external onlyOwner nonReentrant {
        if (to == address(0)) revert ZeroAddress();
        (bool ok, ) = to.call{value: amount}("");
        require(ok, "ETH withdraw failed");
    }

    receive() external payable {}
}
Compiler settingsShow
{
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "paris"
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.