Skip to content
Verified contractExactMIT

NormieTool

Address0x52a2dab31218ba20dc82a0c2a29d8a3fc4ad714e
Balance

0 ETH

 

Transactions

631

 

Compiler

solc 0.8.20

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.20+commit.a1b79de6
Language
solidity
Optimization
Yes, 200 runs
EVM version
paris
Via IR
yes
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
24,360,840
Creation transaction
0x5f9912628e…87119e1407

contracts/NormieTool.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/Pausable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";

/**
 * @title NormieTool
 * @notice ETH <-> MK token swap wrapper with SSOT-driven referrer payouts + atomic fallback.
 * @dev Version 4.1.0 - Non-reverting fee paths for all recipients
 *
 * SSOT semantics:
 * - Backend supplies referrer address for EACH swap (buy and sell).
 * - Contract never locks/overrides referrer.
 * - Invalid referrer falls back to defaultReferrer (org wallet).
 *
 * Fees:
 * - BUY: fees computed on msg.value (ETH-in)
 * - SELL: fees computed on ETH received from swap (ETH-out)
 * - 4% to referrer, 1% to marketing/treasury, 95% to user
 *
 * Atomic payout fallback (hybrid):
 * - Try pay recipient in ETH
 * - Else wrap to WETH and try transfer
 * - Else credit in WETH (claim later)
 *
 * CRITICAL (v4.1): All fee paths use non-reverting fallback cascade:
 * - Referral fee (4%) → _payReferrer → ETH→WETH→credit
 * - Marketing fee (1%) → _paySink → ETH→WETH→credit
 * - Combined path → _paySink → ETH→WETH→credit
 * This ensures swaps NEVER revert due to fee recipient issues.
 *
 * Gas Optimizations (v4):
 * - Single-transfer optimization when defaultReferrer == marketingWallet
 * - Unchecked blocks for bounded operations (counters, totals)
 * - Custom errors throughout
 *
 * Observability:
 * - Keeps V3-style counters + getters for stats and expected outputs.
 * - ReferralPayout event for referrer payments
 * - ProtocolFeePayout event for sink payments (cleaner analytics)
 */
interface IUniswapV2Router02 {
    function swapExactETHForTokensSupportingFeeOnTransferTokens(
        uint256 amountOutMin,
        address[] calldata path,
        address to,
        uint256 deadline
    ) external payable;

    function swapExactTokensForETHSupportingFeeOnTransferTokens(
        uint256 amountIn,
        uint256 amountOutMin,
        address[] calldata path,
        address to,
        uint256 deadline
    ) external;

    function getAmountsOut(uint256 amountIn, address[] calldata path)
        external view returns (uint256[] memory amounts);

    function WETH() external pure returns (address);
}

interface IUniswapV2Factory {
    function getPair(address tokenA, address tokenB) external view returns (address pair);
}

/// @notice WETH interface for deposit/withdraw/transfer
interface IWETH {
    function deposit() external payable;
    function withdraw(uint256 wad) external;
    function transfer(address dst, uint256 wad) external returns (bool);
    function balanceOf(address who) external view returns (uint256);
}

contract NormieTool is ReentrancyGuard, Pausable, Ownable {
    // ============ Immutables ============

    /// @notice MemeLinked (MK) token address
    address public immutable mkToken;

    /// @notice Uniswap V2 Router
    IUniswapV2Router02 public immutable router;

    /// @notice Uniswap V2 Factory
    IUniswapV2Factory public immutable factory;

    /// @notice WETH address
    address public immutable weth;

    // ============ Fee Configuration ============

    /// @notice Referral fee in basis points (4% = 400 bps)
    uint256 public constant REFERRAL_FEE_BPS = 400;

    /// @notice Marketing/Treasury fee in basis points (1% = 100 bps)
    uint256 public constant MARKETING_FEE_BPS = 100;

    /// @notice Total fee in basis points (5% = 500 bps)
    uint256 public constant TOTAL_FEE_BPS = 500;

    /// @notice Basis points denominator
    uint256 public constant BPS_DENOMINATOR = 10_000;

    // ============ Payout Constants ============

    /// @notice Asset types for ReferralPayout event
    uint8 public constant ASSET_ETH = 0;
    uint8 public constant ASSET_WETH = 1;

    /// @notice Payout modes for ReferralPayout event
    uint8 public constant MODE_PUSH_ETH = 0;
    uint8 public constant MODE_PUSH_WETH = 1;
    uint8 public constant MODE_CREDIT = 2;

    // ============ Payout Wallets ============

    /// @notice Marketing/Treasury wallet address (1%)
    address public marketingWallet;

    /// @notice Default referrer (org-level fallback when referrer invalid)
    address public defaultReferrer;

    // ============ Statistics (V3-style) ============

    /// @notice Total ETH collected as referral fees (buys + sells)
    uint256 public totalReferralFeesCollected;

    /// @notice Total ETH collected as marketing fees (buys + sells)
    uint256 public totalMarketingFeesCollected;

    /// @notice Total ETH swapped for MK (buys only; 95% portion)
    uint256 public totalEthSwappedForMK;

    /// @notice Total MK tokens purchased
    uint256 public totalMKPurchased;

    /// @notice Total number of buy transactions
    uint256 public totalBuys;

    /// @notice Total MK tokens sold
    uint256 public totalMKSold;

    /// @notice Total ETH received from sells (gross, before fees)
    uint256 public totalEthFromSells;

    /// @notice Total number of sell transactions
    uint256 public totalSells;

    /// @notice Per-referrer earnings tracking (from buys + sells)
    mapping(address => uint256) public referrerEarnings;

    // ============ Credit System (Atomic Fallback) ============

    /// @notice Pending WETH credits for referrers who couldn't receive direct transfer
    mapping(address => uint256) public pendingCredits;

    /// @notice Total pending credits across all referrers
    uint256 public totalPendingCredits;

    // ============ Events ============

    event MKPurchased(
        address indexed buyer,
        uint256 ethIn,
        uint256 referralFee,
        uint256 marketingFee,
        uint256 swapEth,
        uint256 mkOut,
        bytes32 indexed referralCode,
        address indexed referrer
    );

    event MKSold(
        address indexed seller,
        uint256 mkIn,
        uint256 ethOut,
        uint256 referralFee,
        uint256 marketingFee,
        uint256 ethToSeller,
        address indexed referrer
    );

    event MarketingWalletUpdated(address indexed oldWallet, address indexed newWallet);
    event DefaultReferrerUpdated(address indexed oldReferrer, address indexed newReferrer);

    event ReferralPayout(
        address indexed referrer,
        uint8 asset,
        uint256 amount,
        uint8 mode
    );

    event CreditsClaimed(address indexed referrer, uint8 asset, uint256 amount);

    /**
     * @notice Emitted when protocol fees are combined into single transfer (optimization)
     * @dev Only emitted when effectiveReferrer == defaultReferrer == marketingWallet
     */
    event ProtocolFeesCombined(address indexed sink, uint256 amount);

    /**
     * @notice Emitted when protocol sink (marketing/treasury) receives payment
     * @dev Separate from ReferralPayout for cleaner analytics
     * @param sink The marketing/treasury wallet address
     * @param asset 0 = ETH, 1 = WETH
     * @param amount Amount paid
     * @param mode 0 = push ETH, 1 = push WETH, 2 = credit
     */
    event ProtocolFeePayout(
        address indexed sink,
        uint8 asset,
        uint256 amount,
        uint8 mode
    );

    // ============ Errors ============

    error ZeroETHSent();
    error ZeroMKAmount();
    error DeadlineExpired();
    error PairDoesNotExist();
    error TransferFailed();
    error InvalidAddress();
    error SlippageExceeded();
    error NoCreditsToClaim();
    error InvalidETHSender();

    // ============ Constructor ============

    constructor(
        address _mkToken,
        address _router,
        address _factory,
        address _marketingWallet,
        address _defaultReferrer
    ) Ownable(msg.sender) {
        if (_mkToken == address(0)) revert InvalidAddress();
        if (_router == address(0)) revert InvalidAddress();
        if (_factory == address(0)) revert InvalidAddress();
        if (_marketingWallet == address(0)) revert InvalidAddress();
        if (_defaultReferrer == address(0)) revert InvalidAddress();

        mkToken = _mkToken;
        router = IUniswapV2Router02(_router);
        factory = IUniswapV2Factory(_factory);
        weth = router.WETH();

        marketingWallet = _marketingWallet;
        defaultReferrer = _defaultReferrer;
    }

    // ============ Core Functions ============

    /**
     * @notice Purchase MK tokens with ETH (fees on input)
     * @param amountOutMin Minimum MK tokens to receive (slippage protection)
     * @param deadline Transaction deadline (MEV protection)
     * @param referralCode Off-chain referral code for analytics
     * @param referrer SSOT-resolved referrer address (4% payout). Invalid -> defaultReferrer.
     * @return mkOut Amount of MK tokens received
     */
    function buyMK(
        uint256 amountOutMin,
        uint256 deadline,
        bytes32 referralCode,
        address referrer
    ) external payable nonReentrant whenNotPaused returns (uint256 mkOut) {
        if (msg.value == 0) revert ZeroETHSent();
        if (deadline < block.timestamp) revert DeadlineExpired();

        // Cache immutables and storage reads for gas optimization
        address wethAddr = weth;
        address mkTokenAddr = mkToken;
        address defRef = defaultReferrer;
        address marketing = marketingWallet;

        address pair = factory.getPair(wethAddr, mkTokenAddr);
        if (pair == address(0)) revert PairDoesNotExist();

        address effectiveReferrer = _sanitizeReferrerCached(referrer, defRef);

        // Fees on ETH-in (safe: bounded by constants, never overflows)
        uint256 referralFee = (msg.value * REFERRAL_FEE_BPS) / BPS_DENOMINATOR;
        uint256 marketingFee = (msg.value * MARKETING_FEE_BPS) / BPS_DENOMINATOR;
        uint256 swapEth = msg.value - referralFee - marketingFee; // 95%

        // Swap path: WETH -> MK
        address[] memory path = new address[](2);
        path[0] = wethAddr;
        path[1] = mkTokenAddr;

        uint256 balanceBefore = _getMKBalance(msg.sender);

        router.swapExactETHForTokensSupportingFeeOnTransferTokens{value: swapEth}(
            amountOutMin,
            path,
            msg.sender,
            deadline
        );

        mkOut = _getMKBalance(msg.sender) - balanceBefore;

        // Payouts (optimized: single transfer when effectiveReferrer == defaultReferrer == marketingWallet)
        _payProtocolFeesCached(effectiveReferrer, referralFee, marketingFee, defRef, marketing);

        // Earnings tracking for the effective referrer identity
        unchecked { referrerEarnings[effectiveReferrer] += referralFee; }

        // Stats (unchecked: uint256 counters won't realistically overflow)
        unchecked {
            totalReferralFeesCollected += referralFee;
            totalMarketingFeesCollected += marketingFee;
            totalEthSwappedForMK += swapEth;
            totalMKPurchased += mkOut;
            totalBuys += 1;
        }

        emit MKPurchased(
            msg.sender,
            msg.value,
            referralFee,
            marketingFee,
            swapEth,
            mkOut,
            referralCode,
            effectiveReferrer
        );

        return mkOut;
    }

    /**
     * @notice Sell MK tokens for ETH (fees on output)
     * @dev Backend must supply SSOT referrer on sells as well.
     * @param mkAmount Amount of MK tokens to sell
     * @param amountOutMin Minimum ETH to receive AFTER FEES (seller receives 95%)
     * @param deadline Transaction deadline
     * @param referrer SSOT-resolved referrer address (4% payout). Invalid -> defaultReferrer.
     * @return ethToSeller Net ETH paid to seller (95% of ethReceived)
     */
    function sellMK(
        uint256 mkAmount,
        uint256 amountOutMin,
        uint256 deadline,
        address referrer
    ) external nonReentrant whenNotPaused returns (uint256 ethToSeller) {
        if (mkAmount == 0) revert ZeroMKAmount();
        if (deadline < block.timestamp) revert DeadlineExpired();

        // Cache immutables and storage reads for gas optimization
        address wethAddr = weth;
        address mkTokenAddr = mkToken;
        address defRef = defaultReferrer;
        address marketing = marketingWallet;

        address pair = factory.getPair(wethAddr, mkTokenAddr);
        if (pair == address(0)) revert PairDoesNotExist();

        address effectiveReferrer = _sanitizeReferrerCached(referrer, defRef);

        IERC20 mk = IERC20(mkTokenAddr);

        // Pull MK from seller
        bool transferred = mk.transferFrom(msg.sender, address(this), mkAmount);
        if (!transferred) revert TransferFailed();

        // Approve router (safe pattern)
        mk.approve(address(router), 0);
        mk.approve(address(router), mkAmount);

        uint256 ethBalanceBefore = address(this).balance;

        // Swap path: MK -> WETH (router outputs ETH in this function, WETH is used for pair)
        address[] memory path = new address[](2);
        path[0] = mkTokenAddr;
        path[1] = wethAddr;

        // Router slippage enforced by our post-fee check on ethToSeller
        router.swapExactTokensForETHSupportingFeeOnTransferTokens(
            mkAmount,
            0,
            path,
            address(this),
            deadline
        );

        uint256 ethReceived = address(this).balance - ethBalanceBefore;

        // Fees on ETH-out (gross) - safe: bounded by constants
        uint256 referralFee = (ethReceived * REFERRAL_FEE_BPS) / BPS_DENOMINATOR;
        uint256 marketingFee = (ethReceived * MARKETING_FEE_BPS) / BPS_DENOMINATOR;
        ethToSeller = ethReceived - referralFee - marketingFee;

        if (ethToSeller < amountOutMin) revert SlippageExceeded();

        // Payouts (optimized: single transfer when effectiveReferrer == defaultReferrer == marketingWallet)
        _payProtocolFeesCached(effectiveReferrer, referralFee, marketingFee, defRef, marketing);

        // Earnings tracking for the effective referrer identity
        unchecked { referrerEarnings[effectiveReferrer] += referralFee; }

        _safeTransferETH(msg.sender, ethToSeller);

        // Stats (unchecked: uint256 counters won't realistically overflow)
        unchecked {
            totalReferralFeesCollected += referralFee;
            totalMarketingFeesCollected += marketingFee;
            totalMKSold += mkAmount;
            totalEthFromSells += ethReceived;
            totalSells += 1;
        }

        emit MKSold(
            msg.sender,
            mkAmount,
            ethReceived,
            referralFee,
            marketingFee,
            ethToSeller,
            effectiveReferrer
        );

        return ethToSeller;
    }

    // ============ Credit Claim Functions (V3-style) ============

    function claimable(address referrer) external view returns (uint256 ethCredits, uint256 wethCredits) {
        // Credits stored as WETH only
        return (0, pendingCredits[referrer]);
    }

    function claimToETH() external nonReentrant returns (uint256 amount) {
        amount = pendingCredits[msg.sender];
        if (amount == 0) revert NoCreditsToClaim();

        pendingCredits[msg.sender] = 0;
        unchecked { totalPendingCredits -= amount; }

        IWETH(weth).withdraw(amount);

        (bool ok, ) = msg.sender.call{value: amount}("");
        if (!ok) revert TransferFailed();

        emit CreditsClaimed(msg.sender, ASSET_ETH, amount);
        return amount;
    }

    function claimToWETH() external nonReentrant returns (uint256 amount) {
        amount = pendingCredits[msg.sender];
        if (amount == 0) revert NoCreditsToClaim();

        pendingCredits[msg.sender] = 0;
        unchecked { totalPendingCredits -= amount; }

        bool ok = IWETH(weth).transfer(msg.sender, amount);
        if (!ok) revert TransferFailed();

        emit CreditsClaimed(msg.sender, ASSET_WETH, amount);
        return amount;
    }

    // ============ View Functions (V3-style) ============

    function getExpectedOutput(uint256 ethIn) external view returns (
        uint256 mkOut,
        uint256 referralFee,
        uint256 marketingFee,
        uint256 swapAmount
    ) {
        referralFee = (ethIn * REFERRAL_FEE_BPS) / BPS_DENOMINATOR;
        marketingFee = (ethIn * MARKETING_FEE_BPS) / BPS_DENOMINATOR;
        swapAmount = ethIn - referralFee - marketingFee;

        address[] memory path = new address[](2);
        path[0] = weth;
        path[1] = mkToken;

        try router.getAmountsOut(swapAmount, path) returns (uint256[] memory amounts) {
            mkOut = amounts[1];
        } catch {
            mkOut = 0;
        }

        return (mkOut, referralFee, marketingFee, swapAmount);
    }

    function getExpectedSellOutput(uint256 mkIn) external view returns (
        uint256 ethToSeller,
        uint256 referralFee,
        uint256 marketingFee,
        uint256 grossEth
    ) {
        address[] memory path = new address[](2);
        path[0] = mkToken;
        path[1] = weth;

        try router.getAmountsOut(mkIn, path) returns (uint256[] memory amounts) {
            grossEth = amounts[1];
        } catch {
            grossEth = 0;
        }

        referralFee = (grossEth * REFERRAL_FEE_BPS) / BPS_DENOMINATOR;
        marketingFee = (grossEth * MARKETING_FEE_BPS) / BPS_DENOMINATOR;
        ethToSeller = grossEth - referralFee - marketingFee;

        return (ethToSeller, referralFee, marketingFee, grossEth);
    }

    function getFeeConfig() external view returns (
        uint256 referralFeeBps,
        uint256 marketingFeeBps,
        uint256 totalFeeBps,
        address marketingWalletAddr
    ) {
        return (REFERRAL_FEE_BPS, MARKETING_FEE_BPS, TOTAL_FEE_BPS, marketingWallet);
    }

    function getStats() external view returns (
        uint256 _totalReferralFees,
        uint256 _totalMarketingFees,
        uint256 _totalEthSwappedForMK,
        uint256 _totalMKPurchased,
        uint256 _totalBuys,
        uint256 _totalMKSold,
        uint256 _totalEthFromSells,
        uint256 _totalSells
    ) {
        return (
            totalReferralFeesCollected,
            totalMarketingFeesCollected,
            totalEthSwappedForMK,
            totalMKPurchased,
            totalBuys,
            totalMKSold,
            totalEthFromSells,
            totalSells
        );
    }

    function getReferrerEarnings(address referrer) external view returns (uint256) {
        return referrerEarnings[referrer];
    }

    // ============ Admin Functions ============

    function setMarketingWallet(address newWallet) external onlyOwner {
        if (newWallet == address(0)) revert InvalidAddress();
        emit MarketingWalletUpdated(marketingWallet, newWallet);
        marketingWallet = newWallet;
    }

    function setDefaultReferrer(address newReferrer) external onlyOwner {
        if (newReferrer == address(0)) revert InvalidAddress();
        emit DefaultReferrerUpdated(defaultReferrer, newReferrer);
        defaultReferrer = newReferrer;
    }

    function pause() external onlyOwner { _pause(); }
    function unpause() external onlyOwner { _unpause(); }

    function rescueTokens(address token, address to, uint256 amount) external onlyOwner {
        if (to == address(0)) revert InvalidAddress();
        (bool ok, bytes memory data) = token.call(
            abi.encodeWithSignature("transfer(address,uint256)", to, amount)
        );
        require(ok && (data.length == 0 || abi.decode(data, (bool))), "Transfer failed");
    }

    function rescueETH(address to, uint256 amount) external onlyOwner {
        if (to == address(0)) revert InvalidAddress();
        _safeTransferETH(to, amount);
    }

    // ============ Internal Functions ============

    /**
     * @notice Sanitize referrer with cached defaultReferrer (gas optimization)
     */
    function _sanitizeReferrerCached(address referrer, address defRef) internal view returns (address) {
        if (referrer == address(0) || referrer == msg.sender || referrer == address(this)) {
            return defRef;
        }
        return referrer;
    }

    /**
     * @notice Legacy sanitizer (for external use or uncached paths)
     */
    function _sanitizeReferrer(address referrer) internal view returns (address) {
        if (referrer == address(0) || referrer == msg.sender || referrer == address(this)) {
            return defaultReferrer;
        }
        return referrer;
    }

    function _getMKBalance(address account) internal view returns (uint256) {
        (bool success, bytes memory data) = mkToken.staticcall(
            abi.encodeWithSignature("balanceOf(address)", account)
        );
        require(success && data.length >= 32, "Balance check failed");
        return abi.decode(data, (uint256));
    }

    /**
     * @notice Pay protocol fees with single-transfer optimization (cached version)
     * @dev If effectiveReferrer == defaultReferrer == marketingWallet (all same splitter),
     *      combine fees into one transfer. Otherwise, pay separately.
     *
     *      CRITICAL (v4.1): All fee paths use non-reverting fallback cascade to ensure
     *      swaps NEVER revert due to fee recipient issues. This applies to:
     *      - Combined path (when all sinks are same address)
     *      - Referral fee path (4% to referrer)
     *      - Marketing fee path (1% to sink)
     *
     * @param effectiveReferrer The resolved referrer address (4% payout)
     * @param referralFee 4% fee amount
     * @param marketingFee 1% fee amount
     * @param defRef Cached defaultReferrer (saves SLOAD)
     * @param marketing Cached marketingWallet (saves SLOAD)
     */
    function _payProtocolFeesCached(
        address effectiveReferrer,
        uint256 referralFee,
        uint256 marketingFee,
        address defRef,
        address marketing
    ) internal {
        // Gas optimization: If both sinks are the same splitter AND the referrer is the default,
        // combine the fees into one transfer so the splitter splits once (not twice).
        // Uses non-reverting _paySink to ensure swap never fails due to sink issues.
        if (effectiveReferrer == defRef && defRef == marketing) {
            uint256 combined = referralFee + marketingFee;
            _paySink(marketing, combined);
            emit ProtocolFeesCombined(marketing, combined);
            return;
        }

        // Normal case: 4% to referrer (could be splitter or real referrer), 1% to marketing sink
        // Both use non-reverting fallback cascade (ETH → WETH → credit)
        _payReferrer(effectiveReferrer, referralFee);
        _paySink(marketing, marketingFee);
    }

    /**
     * @notice Pay protocol fees (legacy uncached version for external use)
     */
    function _payProtocolFees(
        address effectiveReferrer,
        uint256 referralFee,
        uint256 marketingFee
    ) internal {
        _payProtocolFeesCached(effectiveReferrer, referralFee, marketingFee, defaultReferrer, marketingWallet);
    }

    /**
     * @notice Pay referrer with hybrid ETH→WETH→credit fallback
     * @dev 1) Try ETH, 2) Try WETH, 3) Credit WETH
     *      Emits ReferralPayout for analytics tracking of referrer payments.
     */
    function _payReferrer(address to, uint256 amount) internal {
        // 1) Try ETH
        (bool ethOk, ) = to.call{value: amount}("");
        if (ethOk) {
            emit ReferralPayout(to, ASSET_ETH, amount, MODE_PUSH_ETH);
            return;
        }

        // 2) Wrap to WETH and try transfer
        IWETH(weth).deposit{value: amount}();
        bool wethOk = IWETH(weth).transfer(to, amount);
        if (wethOk) {
            emit ReferralPayout(to, ASSET_WETH, amount, MODE_PUSH_WETH);
            return;
        }

        // 3) Credit in WETH
        unchecked {
            pendingCredits[to] += amount;
            totalPendingCredits += amount;
        }
        emit ReferralPayout(to, ASSET_WETH, amount, MODE_CREDIT);
    }

    /**
     * @notice Pay protocol sink (marketing/treasury) with ETH→credit fallback
     * @dev CRITICAL: Unlike _payReferrer, this does NOT attempt WETH transfer to sink.
     *
     *      Why? If sink is FeeSplitter80_20, WETH transfer bypasses its receive() function,
     *      so the 80/20 split logic never executes. WETH would get "stuck" unsplit.
     *
     *      Correct behavior:
     *      1) Try ETH push (ideal: FeeSplitter splits immediately in receive())
     *      2) If ETH fails: wrap to WETH and credit INSIDE NormieTool
     *      3) FeeSplitter can later call claimToETH() to pull and auto-split
     *
     *      This ensures swaps NEVER revert AND split semantics are preserved.
     */
    function _paySink(address to, uint256 amount) internal {
        // 1) Try ETH push (ideal for FeeSplitter: it splits immediately in receive())
        (bool ethOk, ) = to.call{value: amount}("");
        if (ethOk) {
            emit ProtocolFeePayout(to, ASSET_ETH, amount, MODE_PUSH_ETH);
            return;
        }

        // 2) If ETH fails: DO NOT attempt WETH transfer to sink.
        // Instead: wrap to WETH and credit INSIDE NormieTool.
        // FeeSplitter can later pull via claimToETH() which triggers its receive().
        IWETH(weth).deposit{value: amount}();

        unchecked {
            pendingCredits[to] += amount;      // WETH-denominated credits
            totalPendingCredits += amount;
        }

        emit ProtocolFeePayout(to, ASSET_WETH, amount, MODE_CREDIT);
    }

    function _safeTransferETH(address to, uint256 amount) internal {
        (bool ok, ) = to.call{value: amount}("");
        if (!ok) revert TransferFailed();
    }

    // ============ Receive ============

    receive() external payable {
        // Allow ETH from Uniswap router (sellMK) and from WETH (claimToETH)
        if (msg.sender != address(router) && msg.sender != weth) {
            revert InvalidETHSender();
        }
    }
}

@openzeppelin/contracts/access/Ownable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)

pragma solidity ^0.8.20;

import {Context} from "../utils/Context.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);
    }
}

@openzeppelin/contracts/token/ERC20/IERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)

pragma solidity >=0.4.16;

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

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

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

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

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

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

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

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

@openzeppelin/contracts/utils/Context.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)

pragma solidity ^0.8.20;

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

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

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

@openzeppelin/contracts/utils/Pausable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/Pausable.sol)

pragma solidity ^0.8.20;

import {Context} from "../utils/Context.sol";

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

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

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

    /**
     * @dev The operation failed because the contract is paused.
     */
    error EnforcedPause();

    /**
     * @dev The operation failed because the contract is not paused.
     */
    error ExpectedPause();

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

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

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

    /**
     * @dev Throws if the contract is paused.
     */
    function _requireNotPaused() internal view virtual {
        if (paused()) {
            revert EnforcedPause();
        }
    }

    /**
     * @dev Throws if the contract is not paused.
     */
    function _requirePaused() internal view virtual {
        if (!paused()) {
            revert ExpectedPause();
        }
    }

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

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

@openzeppelin/contracts/utils/ReentrancyGuard.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuard.sol)

pragma solidity ^0.8.20;

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
 * consider using {ReentrancyGuardTransient} instead.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuard {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant NOT_ENTERED = 1;
    uint256 private constant ENTERED = 2;

    uint256 private _status;

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

    constructor() {
        _status = NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be NOT_ENTERED
        if (_status == ENTERED) {
            revert ReentrancyGuardReentrantCall();
        }

        // Any calls to nonReentrant after this point will fail
        _status = ENTERED;
    }

    function _nonReentrantAfter() private {
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = NOT_ENTERED;
    }

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        return _status == ENTERED;
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "bytecodeHash": "ipfs"
  },
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "paris",
  "remappings": []
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.