Skip to content
Verified contractExactMIT

PaymentRouterV3

Address0xb1e22c577e79dc2a08bfd7c5792eda20d78f04a7
Balance

0 ETH

 

Transactions

2

 

Compiler

solc 0.8.20

 

Same code

8 more contracts

 

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
26,401,809
Creation transaction
0xef74ef69aa…71f4d3072a
Main copy (most transactions)
0xdf1f22a0…d8f247d8

contracts/PaymentRouterV3_2.sol

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

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";

/**
 * @title PaymentRouterV3
 * @dev FINAL PRODUCTION-READY (V3.2.9): Automatic token routing + FOT + reflection/rebasing + malicious token protection
 *
 * @notice This contract is immutable - configuration set at deployment
 * @notice All percentages must sum to exactly 100%
 * @notice Events emit amounts moved out of contract (may differ from recipient net with FOT)
 * @notice Supported tokens: ERC-20, FOT/deflationary, reflection/rebasing (best-effort)
 * @notice Recommend allowlisting tokens for production use
 * @notice V3.2.9: Added distributeExistingTokens() for automatic token routing when sent directly
 */
contract PaymentRouterV3 is ReentrancyGuard {
    using SafeERC20 for IERC20;

    // Custom errors for gas efficiency and clearer monitoring
    error ERC20OverDebit(address token, uint256 requested, uint256 moved);
    error ZeroMoveButSignalled(address token, address recipient, uint256 requested);

    // Additional custom errors for gas efficiency and consistency
    error InvalidTokenAddress();
    error NoPendingETH();
    error NoPendingTokens();
    error TokenTransferReverted();
    error ETHTransferReverted();
    error OnlyContractWallet();
    error NoETHToSweep();
    error NoTokensToSweep();

    struct Route {
        address payable wallet;
        uint256 percentage; // In basis points (10000 = 100%)
    }

    Route[] public routes;

    uint256 private constant BASIS_POINTS = 10000; // 100.00%
    uint256 private constant MAX_ROUTES = 50; // Gas safety limit

    // Gas caps for DoS protection (S-1 fix) - public for monitoring/ops visibility
    // V3.2.10: Increased ETH_SEND_GAS to support cascading routers (router → router with multiple recipients)
    // A child router with 9 recipients needs ~650,000 gas to complete distribution
    uint256 public constant ETH_SEND_GAS = 700000; // Gas limit for ETH sends (supports cascading routers)
    uint256 public constant TOKEN_CALL_GAS = 120000; // Gas limit for token calls (prevents DoS via gas exhaustion)

    // Pull payment pattern
    mapping(address => uint256) public pendingETHWithdrawals;
    mapping(address => mapping(address => uint256)) public pendingTokenWithdrawals;

    // Failed transfer tracking
    uint256 public failedETHTransfers;
    mapping(address => uint256) public failedTokenTransfers;

    // Pending distribution
    uint256 public pendingDistribution;

    // Reentrancy telemetry flag
    bool private _inETHRoute;

    event PaymentReceived(address indexed from, uint256 amount);
    event PaymentReceivedDuringRoute(address indexed from, uint256 amount);
    event ETHRouted(address indexed to, uint256 amount);
    event ETHRetainedInContract(uint256 amount);
    event TokenRouted(address indexed token, address indexed to, uint256 amount);
    event TokenTransferAnomaly(address indexed token, address indexed to, uint256 attempted);

    /// @notice Emitted when tokens remain in contract after distribution
    /// @dev Reports TOTAL on-hand balance (includes locked collateral for pending withdrawals)
    /// @param token Token address
    /// @param amount Total balance remaining in contract (locked + unlocked)
    event TokenRetainedInContract(address indexed token, uint256 amount); // ✅ V2 FIX

    /// @notice Emitted when unlocked (sweepable) dust remains in contract after distribution
    /// @dev Reports only dust available for sweeping (excludes locked collateral)
    /// @param token Token address
    /// @param amount Sweepable balance (balance - failedTokenTransfers[token])
    event TokenUnlockedDust(address indexed token, uint256 amount);

    event ETHWithdrawn(address indexed to, uint256 amount);
    event TokenWithdrawn(address indexed token, address indexed to, uint256 amount);
    event TransferFailed(address indexed recipient, uint256 amount);
    event TokenTransferFailed(address indexed token, address indexed recipient, uint256 amount);
    event DistributionTriggered(uint256 amount);
    event ETHSwept(uint256 amount); // ✅ V2 FIX
    event TokenSwept(address indexed token, uint256 amount); // ✅ V2 FIX

    address public immutable contractWallet; // ✅ V2 FIX: For sweep functions

    /**
     * @dev Constructor sets up routing configuration
     * @param _routes Array of route configurations
     *
     * @notice Total percentages must equal exactly 100%
     *
     */
    constructor(Route[] memory _routes) {
        require(_routes.length > 0, "Must have at least one route");
        require(_routes.length <= MAX_ROUTES, "Too many routes");

        // CRITICAL: msg.sender becomes the immutable contractWallet
        // Verify this is the intended treasury address before deployment
        contractWallet = payable(msg.sender); // ✅ V2 FIX

        uint256 totalPercentage = 0;

        for (uint256 i = 0; i < _routes.length; i++) {
            for (uint256 j = 0; j < i; j++) {
                require(_routes[i].wallet != _routes[j].wallet, "Duplicate route wallet");
            }
            require(_routes[i].wallet != address(0), "Invalid wallet address");
            require(_routes[i].wallet != address(this), "Cannot route to self");
            require(_routes[i].wallet != contractWallet, "contractWallet cannot also be a route");
            require(_routes[i].percentage > 0, "Percentage must be greater than 0");

            totalPercentage += _routes[i].percentage;
            routes.push(_routes[i]);
        }

        require(totalPercentage == BASIS_POINTS, "Total percentage must equal exactly 100%");
    }

    /**
     * @notice Receive ETH and AUTOMATICALLY route to all recipients
     * @dev ETH is instantly distributed on every payment (automatic routing)
     * @dev FORCED ETH (S-2): ETH sent via SELFDESTRUCT bypasses receive/fallback and won't update pendingDistribution.
     *      Such forced ETH becomes sweepable via getSweepableETH (balance - pendingDistribution - failedETHTransfers).
     *      POLICY: Forced ETH is treated as treasury sweepable funds (not distributed to recipients).
     *      To include forced ETH in distributions, treasury can manually call distributeETH after reconciliation.
     */
    receive() external payable nonReentrant {
        if (_inETHRoute) {
            // Already routing - accumulate for next batch to prevent infinite recursion
            pendingDistribution += msg.value;
            emit PaymentReceivedDuringRoute(msg.sender, msg.value);
        } else {
            // V3.2.10: Check if we have enough gas to complete distribution
            // Each recipient needs ~50k gas, plus overhead. If insufficient, defer to pendingDistribution.
            uint256 gasNeeded = (routes.length * 60000) + 50000;

            if (gasleft() < gasNeeded) {
                // Not enough gas - store for later distribution via distributeETH()
                pendingDistribution += msg.value;
                emit PaymentReceived(msg.sender, msg.value);
                emit ETHRetainedInContract(msg.value);
            } else {
                // Enough gas - distribute immediately
                emit PaymentReceived(msg.sender, msg.value);
                _routeETH(msg.value);
            }
        }
    }

    /**
     * @dev Fallback function - AUTOMATICALLY routes incoming ETH
     */
    fallback() external payable nonReentrant {
        if (_inETHRoute) {
            // Already routing - accumulate for next batch to prevent infinite recursion
            pendingDistribution += msg.value;
            emit PaymentReceivedDuringRoute(msg.sender, msg.value);
        } else {
            // V3.2.10: Check if we have enough gas to complete distribution
            uint256 gasNeeded = (routes.length * 60000) + 50000;

            if (gasleft() < gasNeeded) {
                // Not enough gas - store for later distribution via distributeETH()
                pendingDistribution += msg.value;
                emit PaymentReceived(msg.sender, msg.value);
                emit ETHRetainedInContract(msg.value);
            } else {
                // Enough gas - distribute immediately
                emit PaymentReceived(msg.sender, msg.value);
                _routeETH(msg.value);
            }
        }
    }

    /**
     * @dev Manually trigger ETH distribution
     * @notice Anyone can call this to distribute accumulated ETH
     *
     */
    function distributeETH() external nonReentrant {
        uint256 amount = pendingDistribution;
        require(amount > 0, "No ETH to distribute");

        _routeETH(amount);

        // Defer-decrement: only subtract processed amount (protects against future reverts)
        // If new ETH arrived during routing (reentrancy), don't erase it
        // V3.2.7: Removed unchecked for safer future-proofing (checked math prevents mistakes)
        pendingDistribution -= amount;

        emit DistributionTriggered(amount);
    }

    /**
     * @dev Route ERC20 tokens to recipients
     * @param token The ERC20 token address
     * @param amount The amount of tokens to route
     *
     * @notice Non-standard tokens may route to pending withdrawals
     * @notice Fee-on-transfer tokens will have dust remainder
     * @notice V3.2.1 FIX: Measures actual received tokens to handle FOT on incoming transfers
     */
    function routeTokens(address token, uint256 amount) external nonReentrant {
        if (token == address(0)) revert InvalidTokenAddress();
        require(amount > 0, "Amount must be greater than 0");

        IERC20 t = IERC20(token);
        uint256 beforeBal = t.balanceOf(address(this));
        t.safeTransferFrom(msg.sender, address(this), amount);
        uint256 received = t.balanceOf(address(this)) - beforeBal;
        require(received > 0, "No tokens received");

        _routeTokens(token, received);
    }

    /**
     * @dev Distribute tokens that are already in the contract (AUTOMATIC ROUTING)
     * @param token The ERC20 token address
     *
     * @notice This function enables AUTOMATIC token routing for tokens sent directly to contract
     * @notice Anyone can call this to trigger distribution of existing token balance
     * @notice Protects locked collateral - only distributes sweepable balance
     * @notice V3.2.9: Automatic token routing support
     */
    function distributeExistingTokens(address token) external nonReentrant {
        if (token == address(0)) revert InvalidTokenAddress();

        IERC20 t = IERC20(token);
        uint256 balance = t.balanceOf(address(this));

        // Don't distribute locked collateral (pending withdrawals)
        uint256 locked = failedTokenTransfers[token];

        if (balance <= locked) revert NoPendingTokens();

        uint256 distributable = balance - locked;
        require(distributable > 0, "No tokens to distribute");

        _routeTokens(token, distributable);
    }

    /**
     * @dev Internal ETH routing logic
     * @param amount Amount to route
     *
     */
    function _routeETH(uint256 amount) private {
        if (amount == 0) return;

        _inETHRoute = true;

        uint256 remaining = amount;
        uint256 lastIndex = routes.length - 1;

        // Process all routes except last
        for (uint256 i = 0; i < lastIndex; i++) {
            uint256 share = (amount * routes[i].percentage) / BASIS_POINTS;

            if (share > 0) {
                // Reserve the share BEFORE transfer to prevent over-allocation on failure
                remaining -= share;

                (bool success, ) = routes[i].wallet.call{value: share, gas: ETH_SEND_GAS}("");

                if (success) {
                    emit ETHRouted(routes[i].wallet, share);
                } else {
                    pendingETHWithdrawals[routes[i].wallet] += share;
                    failedETHTransfers += share;
                    emit TransferFailed(routes[i].wallet, share);
                }
            }
        }

        // Send remaining to last route (handles rounding)
        if (remaining > 0) {
            (bool success, ) = routes[lastIndex].wallet.call{value: remaining, gas: ETH_SEND_GAS}("");

            if (success) {
                emit ETHRouted(routes[lastIndex].wallet, remaining);
            } else {
                pendingETHWithdrawals[routes[lastIndex].wallet] += remaining;
                failedETHTransfers += remaining;
                emit TransferFailed(routes[lastIndex].wallet, remaining);
            }
        }

        // CRITICAL: Always reset flag before exit (even though current code doesn't revert,
        // future changes must maintain this guarantee to prevent stuck state)
        _inETHRoute = false;

        // Defensive assertion: If we reach here, the function completed without revert.
        // This assertion documents the invariant and will catch future bugs if someone
        // introduces a revert path after flag set (e.g., via compiler optimizations or refactoring).
        assert(!_inETHRoute); // Should always pass since we just reset it
    }

    /**
     * @dev Internal token routing logic with FOT support
     * @param token Token address
     * @param amount Amount to route (actual received amount)
     *
     */
    function _routeTokens(address token, uint256 amount) private {
        IERC20 t = IERC20(token);
        uint256 remaining = amount;
        uint256 movedTotal = 0; // Track total actual outflow to prevent locked-collateral drain
        uint256 lastIndex = routes.length - 1;

        // Process all routes except last
        for (uint256 i = 0; i < lastIndex; i++) {
            uint256 share = (amount * routes[i].percentage) / BASIS_POINTS;
            if (share == 0) { continue; }

            // Reserve BEFORE transfer to prevent over-allocation on failure
            remaining -= share;

            uint256 beforeBal = t.balanceOf(address(this));
            (bool ok, bytes memory data) = address(t).call{gas: TOKEN_CALL_GAS}(
                abi.encodeWithSelector(t.transfer.selector, routes[i].wallet, share)
            );
            bool success = ok && (data.length == 0 || abi.decode(data, (bool)));
            uint256 afterBal = t.balanceOf(address(this));
            // Guard against malicious/rebasing tokens that could cause underflow
            uint256 moved = beforeBal > afterBal ? beforeBal - afterBal : 0;

            // Balance-delta-dominant success logic (prevents double-pay with malicious tokens)
            if (moved > 0) {
                // CRITICAL V3.2.8: Prevent adversarial over-debit
                if (moved > share) revert ERC20OverDebit(token, share, moved);

                movedTotal += moved; // Track actual outflow
                // Movement occurred: treat as success regardless of return flag
                emit TokenRouted(token, routes[i].wallet, moved);

                // Handle partial move (enqueue shortfall for pro-rata guarantee)
                if (moved < share) {
                    pendingTokenWithdrawals[routes[i].wallet][token] += (share - moved);
                    failedTokenTransfers[token] += (share - moved);
                    emit TokenTransferFailed(token, routes[i].wallet, (share - moved));
                }

                if (!success) {
                    // Token moved but signalled failure → telemetry for malicious token
                    emit TokenTransferAnomaly(token, routes[i].wallet, share);
                }
            } else if (success) {
                // Signalled success but moved 0 → reflection/rebasing anomaly, no enqueue
                emit TokenTransferAnomaly(token, routes[i].wallet, share);
            } else {
                // True failure: nothing moved and signalled failure → enqueue
                pendingTokenWithdrawals[routes[i].wallet][token] += share;
                failedTokenTransfers[token] += share;
                emit TokenTransferFailed(token, routes[i].wallet, share);
            }
        }

        if (remaining > 0) {
            uint256 toAttempt = remaining;
            uint256 beforeBal2 = t.balanceOf(address(this));
            (bool ok2, bytes memory data2) = address(t).call{gas: TOKEN_CALL_GAS}(
                abi.encodeWithSelector(t.transfer.selector, routes[lastIndex].wallet, toAttempt)
            );
            bool success2 = ok2 && (data2.length == 0 || abi.decode(data2, (bool)));
            uint256 afterBal2 = t.balanceOf(address(this));
            // Guard against malicious/rebasing tokens that could cause underflow
            uint256 moved2 = beforeBal2 > afterBal2 ? beforeBal2 - afterBal2 : 0;

            // Balance-delta-dominant success logic (prevents double-pay with malicious tokens)
            if (moved2 > 0) {
                // CRITICAL V3.2.8: Prevent adversarial over-debit
                if (moved2 > toAttempt) revert ERC20OverDebit(token, toAttempt, moved2);

                movedTotal += moved2; // Track actual outflow
                // Movement occurred: treat as success regardless of return flag
                emit TokenRouted(token, routes[lastIndex].wallet, moved2);

                // Handle partial move (enqueue shortfall for pro-rata guarantee)
                if (moved2 < toAttempt) {
                    pendingTokenWithdrawals[routes[lastIndex].wallet][token] += (toAttempt - moved2);
                    failedTokenTransfers[token] += (toAttempt - moved2);
                    emit TokenTransferFailed(token, routes[lastIndex].wallet, (toAttempt - moved2));
                }

                if (!success2 || moved2 != toAttempt) {
                    // Token moved but signalled failure OR partial move → telemetry
                    emit TokenTransferAnomaly(token, routes[lastIndex].wallet, toAttempt);
                }
            } else if (success2) {
                // Signalled success but moved 0 → reflection/rebasing anomaly, no enqueue
                emit TokenTransferAnomaly(token, routes[lastIndex].wallet, toAttempt);
            } else {
                // True failure: nothing moved and signalled failure → enqueue
                pendingTokenWithdrawals[routes[lastIndex].wallet][token] += toAttempt;
                failedTokenTransfers[token] += toAttempt;
                emit TokenTransferFailed(token, routes[lastIndex].wallet, toAttempt);
            }
        }

        // After all transfers, emit retained event if dust remains
        // (Can happen with broken tokens that return true but move 0)
        uint256 dust = t.balanceOf(address(this));
        if (dust > 0) {
            emit TokenRetainedInContract(token, dust);
        }

        // Emit unlocked dust separately for operational clarity
        // (Prevents confusion between "retained" which includes locked queues vs "sweepable")
        uint256 locked = failedTokenTransfers[token];
        uint256 unlocked = dust > locked ? (dust - locked) : 0;
        if (unlocked > 0) {
            emit TokenUnlockedDust(token, unlocked);
        }
    }

    /**
     * @dev Withdraw pending ETH (pull payment)
     */
    function withdrawPendingETH() external nonReentrant {
        uint256 amount = pendingETHWithdrawals[msg.sender];
        if (amount == 0) revert NoPendingETH();

        pendingETHWithdrawals[msg.sender] = 0;
        failedETHTransfers -= amount;

        (bool success, ) = payable(msg.sender).call{value: amount}("");
        if (!success) revert ETHTransferReverted();

        emit ETHWithdrawn(msg.sender, amount);
    }

    /**
     * @dev Withdraw pending tokens (pull payment)
     */
    function withdrawPendingTokens(address token) external nonReentrant {
        if (token == address(0)) revert InvalidTokenAddress();
        uint256 amount = pendingTokenWithdrawals[msg.sender][token];
        if (amount == 0) revert NoPendingTokens();

        IERC20 t = IERC20(token);
        uint256 beforeBal = t.balanceOf(address(this));

        (bool ok, bytes memory data) = address(t).call{gas: TOKEN_CALL_GAS}(
            abi.encodeWithSelector(t.transfer.selector, msg.sender, amount)
        );
        bool signalled = ok && (data.length == 0 || abi.decode(data, (bool)));
        uint256 afterBal = t.balanceOf(address(this));
        uint256 moved = beforeBal > afterBal ? beforeBal - afterBal : 0;

        if (moved > 0) {
            // CRITICAL V3.2.8: Prevent adversarial over-debit
            if (moved > amount) revert ERC20OverDebit(token, amount, moved);

            // Compute residual and update bookkeeping precisely
            uint256 residual = amount - moved;

            // Update per-recipient queue (keeps residual for partial pays)
            pendingTokenWithdrawals[msg.sender][token] = residual;

            // Update global failure pool by actual movement only
            failedTokenTransfers[token] -= moved;

            emit TokenWithdrawn(token, msg.sender, moved);

            // Telemetry for anomalies (success flag mismatch or partial move)
            if (!signalled || moved != amount) {
                emit TokenTransferAnomaly(token, msg.sender, amount);
            }
        } else if (signalled) {
            // Claimed success but moved 0: keep claim intact
            emit TokenTransferAnomaly(token, msg.sender, amount);
            revert ZeroMoveButSignalled(token, msg.sender, amount);
        } else {
            revert TokenTransferReverted();
        }
    }

    /**
     * @dev Sweep retained ETH to contract wallet
     *
     * @notice Only contract wallet can call
     * @notice Sweeps ETH not allocated to distributions or pending withdrawals
     */
    function sweepETH() external nonReentrant {
        if (msg.sender != contractWallet) revert OnlyContractWallet();

        uint256 balance = address(this).balance;
        uint256 locked = pendingDistribution + failedETHTransfers;

        if (balance <= locked) revert NoETHToSweep();

        uint256 sweepable = balance - locked;

        (bool success, ) = contractWallet.call{value: sweepable, gas: ETH_SEND_GAS}("");
        if (!success) revert ETHTransferReverted();

        emit ETHSwept(sweepable);
    }

    /**
     * @dev Sweep retained tokens to contract wallet
     * ✅ V2 CRITICAL FIX: Prevents permanent fund lockup
     *
     * @param token Token address to sweep
     * @notice Only contract wallet can call
     * @notice Sweeps tokens not allocated to pending withdrawals
     */
    function sweepTokens(address token) external nonReentrant {
        if (msg.sender != contractWallet) revert OnlyContractWallet();
        if (token == address(0)) revert InvalidTokenAddress();

        IERC20 t = IERC20(token);
        uint256 balance = t.balanceOf(address(this));
        uint256 locked = failedTokenTransfers[token];

        if (balance <= locked) revert NoTokensToSweep();

        uint256 sweepable = balance - locked;

        uint256 beforeBal = t.balanceOf(address(this));
        (bool ok, bytes memory data) = address(t).call{gas: TOKEN_CALL_GAS}(
            abi.encodeWithSelector(t.transfer.selector, contractWallet, sweepable)
        );
        bool signalled = ok && (data.length == 0 || abi.decode(data, (bool)));
        uint256 afterBal = t.balanceOf(address(this));
        uint256 moved = beforeBal > afterBal ? beforeBal - afterBal : 0;

        if (moved > 0) {
            // CRITICAL V3.2.8: Prevent adversarial over-debit
            if (moved > sweepable) revert ERC20OverDebit(token, sweepable, moved);

            emit TokenSwept(token, moved);
            if (!signalled || moved != sweepable) {
                emit TokenTransferAnomaly(token, contractWallet, sweepable);
            }
        } else if (signalled) {
            emit TokenTransferAnomaly(token, contractWallet, sweepable);
            revert ZeroMoveButSignalled(token, contractWallet, sweepable);
        } else {
            revert TokenTransferReverted();
        }
    }

    /**
     * @dev Get route count
     */
    function getRoutesCount() external view returns (uint256) {
        return routes.length;
    }

    /**
     * @dev Get route details
     */
    function getRoute(uint256 index) external view returns (
        address wallet,
        uint256 percentage
    ) {
        require(index < routes.length, "Index out of bounds");
        Route memory route = routes[index];
        return (route.wallet, route.percentage);
    }

    /**
     * @dev Get all routes
     */
    function getAllRoutes() external view returns (Route[] memory) {
        return routes;
    }

    /**
     * @dev Check pending ETH for address
     */
    function getPendingETH(address account) external view returns (uint256) {
        return pendingETHWithdrawals[account];
    }

    /**
     * @dev Check pending tokens for address
     */
    function getPendingTokens(address account, address token) external view returns (uint256) {
        return pendingTokenWithdrawals[account][token];
    }

    /**
     * @dev Get pending distribution amount
     */
    function getPendingDistribution() external view returns (uint256) {
        return pendingDistribution;
    }

    /**
     * @dev Get sweepable ETH amount
     * @notice Amount that can be swept (retained funds)
     */
    function getSweepableETH() external view returns (uint256) {
        uint256 balance = address(this).balance;
        uint256 locked = pendingDistribution + failedETHTransfers;
        return balance > locked ? balance - locked : 0;
    }

    /**
     * @dev Get sweepable token amount
     * @param token Token address
     * @notice Amount that can be swept (retained funds)
     */
    function getSweepableTokens(address token) external view returns (uint256) {
        if (token == address(0)) revert InvalidTokenAddress();
        uint256 balance = IERC20(token).balanceOf(address(this));
        uint256 locked = failedTokenTransfers[token];
        return balance > locked ? balance - locked : 0;
    }

    /**
     * @dev Get unlocked token balance (operational monitoring helper)
     * @param token Token address
     * @return amount Tokens not locked in pull-payment queue (same as getSweepableTokens)
     *
     */
    function getUnlockedTokenBalance(address token) external view returns (uint256) {
        if (token == address(0)) revert InvalidTokenAddress();
        uint256 balance = IERC20(token).balanceOf(address(this));
        uint256 locked = failedTokenTransfers[token];
        return balance > locked ? balance - locked : 0;
    }

    /**
     * @dev DEBUG/AUDIT HELPER: Verify Token Queue Consistency Invariant
     * @param token Token address to check
     * @param accounts Array of all route addresses that may have pending tokens
     * @return totalPending Sum of all individual pending token withdrawals
     * @return globalPool Value of failedTokenTransfers[token]
     * @return consistent True if totalPending == globalPool (invariant holds)
     *
     */
    function verifyTokenQueueInvariant(address token, address[] calldata accounts)
        external
        view
        returns (uint256 totalPending, uint256 globalPool, bool consistent)
    {
        if (token == address(0)) revert InvalidTokenAddress();

        totalPending = 0;
        for (uint256 i = 0; i < accounts.length; i++) {
            totalPending += pendingTokenWithdrawals[accounts[i]][token];
        }

        globalPool = failedTokenTransfers[token];
        consistent = (totalPending == globalPool);

        return (totalPending, globalPool, consistent);
    }

    /**
     * @dev DEBUG/AUDIT HELPER: Verify ETH Queue Consistency Invariant
     * @param accounts Array of all route addresses that may have pending ETH
     * @return totalPending Sum of all individual pending ETH withdrawals
     * @return globalPool Value of failedETHTransfers
     * @return consistent True if totalPending == globalPool (invariant holds)
     *
     */
    function verifyETHQueueInvariant(address[] calldata accounts)
        external
        view
        returns (uint256 totalPending, uint256 globalPool, bool consistent)
    {
        totalPending = 0;
        for (uint256 i = 0; i < accounts.length; i++) {
            totalPending += pendingETHWithdrawals[accounts[i]];
        }

        globalPool = failedETHTransfers;
        consistent = (totalPending == globalPool);

        return (totalPending, globalPool, consistent);
    }
}

@openzeppelin/contracts/interfaces/IERC1363.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1363.sol)

pragma solidity >=0.6.2;

import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";

/**
 * @title IERC1363
 * @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
 *
 * Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
 * after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
 */
interface IERC1363 is IERC20, IERC165 {
    /*
     * Note: the ERC-165 identifier for this interface is 0xb0202a11.
     * 0xb0202a11 ===
     *   bytes4(keccak256('transferAndCall(address,uint256)')) ^
     *   bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
     */

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @param data Additional data with no specified format, sent in call to `spender`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}

@openzeppelin/contracts/interfaces/IERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC165.sol)

pragma solidity >=0.4.16;

import {IERC165} from "../utils/introspection/IERC165.sol";

@openzeppelin/contracts/interfaces/IERC20.sol

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

pragma solidity >=0.4.16;

import {IERC20} from "../token/ERC20/IERC20.sol";

@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/token/ERC20/utils/SafeERC20.sol

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

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC-20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20 {
    /**
     * @dev An operation with an ERC-20 token failed.
     */
    error SafeERC20FailedOperation(address token);

    /**
     * @dev Indicates a failed `decreaseAllowance` request.
     */
    error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
    }

    /**
     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
     */
    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
    }

    /**
     * @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
        return _callOptionalReturnBool(token, abi.encodeCall(token.transfer, (to, value)));
    }

    /**
     * @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
        return _callOptionalReturnBool(token, abi.encodeCall(token.transferFrom, (from, to, value)));
    }

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        forceApprove(token, spender, oldAllowance + value);
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
     * value, non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
        unchecked {
            uint256 currentAllowance = token.allowance(address(this), spender);
            if (currentAllowance < requestedDecrease) {
                revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
            }
            forceApprove(token, spender, currentAllowance - requestedDecrease);
        }
    }

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
     * to be set to zero before setting it to a non-zero value, such as USDT.
     *
     * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
     * only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
     * set here.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));

        if (!_callOptionalReturnBool(token, approvalCall)) {
            _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
            _callOptionalReturn(token, approvalCall);
        }
    }

    /**
     * @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            safeTransfer(token, to, value);
        } else if (!token.transferAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
     * has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferFromAndCallRelaxed(
        IERC1363 token,
        address from,
        address to,
        uint256 value,
        bytes memory data
    ) internal {
        if (to.code.length == 0) {
            safeTransferFrom(token, from, to, value);
        } else if (!token.transferFromAndCall(from, to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
     * Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
     * once without retrying, and relies on the returned value to be true.
     *
     * Reverts if the returned value is other than `true`.
     */
    function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            forceApprove(token, to, value);
        } else if (!token.approveAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            // bubble errors
            if iszero(success) {
                let ptr := mload(0x40)
                returndatacopy(ptr, 0, returndatasize())
                revert(ptr, returndatasize())
            }
            returnSize := returndatasize()
            returnValue := mload(0)
        }

        if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        bool success;
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            returnSize := returndatasize()
            returnValue := mload(0)
        }
        return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
    }
}

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

@openzeppelin/contracts/utils/introspection/IERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)

pragma solidity >=0.4.16;

/**
 * @dev Interface of the ERC-165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[ERC].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
Compiler settingsShow
{
  "viaIR": true,
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "paris"
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.