Skip to content
Verified contractExactMIT

RewardManager

Address0xb7df8ca194adcd6a0068ca2dc51d3b1bd03ade12
Balance

0 ETH

 

Transactions

20

 

Compiler

solc 0.8.34

 

Same code

1 more contract

 

Details

Compiler
solc 0.8.34+commit.80d5c536
Language
solidity
Optimization
Yes, 20 runs
Via IR
yes
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
24,563,187
Creation transaction
0xf57045d160…2cba44fd54

contracts/RewardManager.sol

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

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {AccessControl} from "@openzeppelin/contracts/access/AccessControl.sol";

/**
 * @title  IUniversalRouter
 * @notice Minimal interface for DSF UniversalRouter used by RewardManager
 */
interface IUniversalRouter {
    /**
     * @notice Returns output amounts for the given path
     * @dev    In your router, the last value is NET (fees already applied)
     */
    function getAmountsOut(uint amountIn, address[] calldata path)
            external
            view
            returns (uint[] memory amountsNet);
        
    /**
     * @notice Swaps exact input tokens for output tokens along a simple path (V2-style)
     */
    function swapExactTokensForTokens(
        uint256 amountIn,
        uint256 amountOutMin,
        address[] calldata path,
        address to,
        uint256 deadline
    ) external returns (uint256[] memory amounts);

    /**
     * @notice Executes a single route encoded in payload
     */
    function swapRoute(
        bytes calldata payload,
        address to,
        uint256 minAmountOut,
        bool useOracleGuard,
        uint16 maxDevBps
    ) external returns (uint256 netOut);

    /**
     * @notice Executes a split route: payloadA/payloadB with percentA (1..99)
     */
    function swapSplit(
        bytes calldata payloadA,
        bytes calldata payloadB,
        uint16 percentA,          // 1..99
        uint256 minAmountOut,
        address to,
        bool useOracleGuard,
        uint16 maxDevBps
    ) external returns (uint256 netOut);

    /**
     * @notice Returns best routes and a suggested split for a given pair and amount
     */
    function getBestRoute(
        address tokenIn,
        address tokenOut,
        uint256 amountIn
    ) external view returns (
        bytes memory best1HopRouteTop1, uint256 amountOut1HopTop1,
        bytes memory best2HopRouteTop1, uint256 amountOut2HopTop1,
        bytes memory best1HopRouteTop2, uint256 amountOut1HopTop2,
        bytes memory best2HopRouteTop2, uint256 amountOut2HopTop2,
        uint256 splitAmountOut, uint16 splitPercentA
    );
}

/**
 * @title  IDSF
 * @notice Minimal interface to DSF core contract used by RewardManager
 */
interface IDSF {
    /**
     * @notice Pool snapshot stored in DSF.
     * @dev    Strategy is address to keep RM simple.
     */
    struct PoolInfo {
        address strategy; // IStrategy, but address is enough for RM
        uint256 startTime;
        uint256 lpShares;
    }

    /**
     * @notice Triggers compounding logic on all strategies (claim/unwrap/push rewards)
     */
    function autoCompoundAll() external;

    /**
     * @notice Computes management fee for a given USDT amount (in USDT native decimals)
     */
    function calcManagementFee(uint256 amount) external view returns (uint256);

    function poolCount() external view returns (uint256);
    function poolInfo(uint256 pid) external view returns (PoolInfo memory);

    function defaultDepositPid() external view returns (uint256);
    function defaultWithdrawPid() external view returns (uint256);

    /**
     * @notice Total holdings of DSF across all strategies (scaled to 1e18 in DSF implementation)
     */
    function totalHoldings() external view returns (uint256);
    
    /**
     * @notice Total supply of DSF LP token (same scale as DSF accounting; typically 1e18)
     */
    function totalSupply() external view returns (uint256);
}

/**
 * @title  IStrategy
 * @notice Minimal strategy interface for RewardManager.
 */
interface IStrategy {
    /**
     * @notice Strategy pulls USDT from RewardManager (RewardManager must approve first)
     * @param  amountUSDT Amount in USDT native decimals (1e6)
     */
    function managerCompound(uint256 amountUSDT) external;

    /**
     * @notice Strategy total holdings in USDT terms (1e18 scale in your codebase)
     */
    function totalHoldings() external view returns (uint256);
}

/**
 * @notice Snapshot for analytics: DSF pool + strategy pricing.
 */
struct PoolSnapshot {
    uint256 pid;
    address strategy;
    uint256 lpShares;          // DSF pool shares allocated
    uint256 totalHolding;  // strategy holdings (USDT terms, 1e18)
    uint256 LPprice;    // totalHolding * 1e18 / lpShares
}

/**
 * @title  RewardManager
 * @author Andrei Averin — CTO dsf.finance
 * @notice Aggregates rewards from DSF strategies, swaps them to USDT via UniversalRouter,
 *         pays DSF management fee to feeDistributor, and re-deploys USDT into selected pools
 *         using strategy.managerCompound()
 *
 * @dev    Important assumptions:
 *         - DSF.autoCompoundAll() makes strategies push reward tokens to this contract (RewardManager)
 *         - Router.getAmountsOut() returns NET out amount (fees included) for the final token in path
 *         - USDT uses 6 decimals; internal "pricing" uses 1e18 scale where needed
 */
contract RewardManager is Ownable, ReentrancyGuard, AccessControl {
    using SafeERC20 for IERC20;

    /// @notice Role for automated operations (bots/keepers)
    bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR_ROLE");

    /// @notice Basis points denominator (100% = 10_000)
    uint256 public constant BPS_DENOMINATOR = 10_000;

    /* ───────────────────────────── Roles ───────────────────────────── */

    /// @notice Restricts to DEFAULT_ADMIN_ROLE
    modifier onlyAdmin() {
        require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "RM: not admin");
        _;
    }

    /// @notice Restricts to OPERATOR_ROLE or DEFAULT_ADMIN_ROLE
    modifier onlyOperator() {
        require(
            hasRole(OPERATOR_ROLE, msg.sender) || hasRole(DEFAULT_ADMIN_ROLE, msg.sender),
            "RM: not operator"
        );
        _;
    }

    /* ───────────────────────────── Storage ───────────────────────────── */

    /// @notice UniversalRouter used for swaps
    IUniversalRouter public router;

    /// @notice DSF core contract
    IDSF public dsf;

    /// @notice Recipient of DSF management fee (currently Gnosis Safe)
    address public feeDistributor;

    /// @dev    token => swap path to USDT (token ... USDT)
    mapping(address => address[]) private _pathToUsdt;

    /// @dev Swap deadline offset in seconds (33m20s)
    uint256 private constant TRADE_DEADLINE = 2000;

    /**
     * @notice  Default slippage for auto-swaps (bps).
     * @dev     minOut = quoteNet * (10_000 - bps) / 10_000
     */
    uint16 public defaultSlippageBps = 50; // 0.50%

    /// @notice Whitelist of tokens eligible for auto-swap
    address[] public autoSwapTokens;

    /// @notice Quick membership check for autoSwapTokens
    mapping(address => bool) public isAutoSwapToken;

    /// @notice Pool blacklist (pid => disabled)
    mapping(uint256 => bool) public isPoolBlacklisted;

    /// @notice Scale used for 1e18 math
    uint256 public constant PRICE_SCALE = 1e18;

    /// @dev USDT (1e6) -> 1e18 multiplier
    uint256 private constant USDT_DECIMALS_SCALE = 1e12;

    /// @dev Mainnet token addresses used for default routing configuration
    address private constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
    address private constant CRV  = 0xD533a949740bb3306d119CC777fa900bA034cd52;
    address private constant CVX  = 0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B;
    address private constant USDT = 0xdAC17F958D2ee523a2206206994597C13D831ec7;

    /* ───────────────────────────── Events ───────────────────────────── */

    event RouterUpdated(address indexed oldRouter, address indexed newRouter);
    event DSFUpdated(address indexed oldDsf, address indexed newDsf);
    event FeeDistributorUpdated(address indexed oldFeeDistributor, address indexed newFeeDistributor);
    event DefaultSlippageUpdated(uint16 oldBps, uint16 newBps);

    event PathToUsdtUpdated(address indexed token, address[] path);
    event AutoSwapTokenRemoved(address indexed token);
    event PoolBlacklistUpdated(uint256 indexed pid, bool blacklisted);

    event AutoSwapExecuted(address indexed tokenIn, uint256 amountIn, uint256 minOut, uint256 usdtOut);

    event ManualRouteSwapExecuted(bytes32 indexed payloadHash, uint256 netOut);
    event ManualSplitSwapExecuted(bytes32 indexed payloadHashA, bytes32 indexed payloadHashB, uint16 percentA, uint256 netOut);

    event DsfAutoCompoundAllCalled(address indexed caller);
    event ManagementFeePaid(address indexed feeDistributor, uint256 feeAmountUSDT);
    event ManagerCompoundExecuted(uint256 indexed pid, address indexed strategy, uint256 usdtIn);

    event ManagerCompoundAllToDepositPool(address indexed caller, uint256 usdtIn, uint256 fee, uint256 net, uint256 pid);
    event ManagerCompoundAllToWithdrawPool(address indexed caller, uint256 usdtIn, uint256 fee, uint256 net, uint256 pid);

    event RebalancePlanned(uint256 targetPrice1e18, uint256 netUSDT, uint256 sumNeed, uint256 leftover);
    event RebalanceAllocated(uint256 indexed pid, uint256 amountUSDT);

    /**
     * @param router_ UniversalRouter address
     * @param dsf_ DSF core address
     * @param feeDistributor_ Fee recipient address
     */
    constructor(address router_, address dsf_, address feeDistributor_) Ownable(msg.sender) {
        require(router_ != address(0) && router_.code.length > 0, "RM: bad router");
        require(dsf_   != address(0) && dsf_.code.length > 0, "RM: bad DSF");
        require(feeDistributor_ != address(0), "RM: feeDistributor=0");

        dsf = IDSF(dsf_);
        router = IUniversalRouter(router_);
        feeDistributor = feeDistributor_;
        
        _grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
        _grantRole(OPERATOR_ROLE, msg.sender);

        _setPathToUsdtInternal(CVX, _make3(CVX, WETH, USDT));
        _setPathToUsdtInternal(CRV, _make3(CRV, WETH, USDT));
    }

    /* ─────────────────────────────────── Roles admin ──────────────────────────────────── */

    /**
     * @notice Grants OPERATOR_ROLE to an address
     * @dev Only callable by DEFAULT_ADMIN_ROLE
     * @param op Address to grant operator permissions
     */
    function addOperator(address op) external onlyAdmin {
        require(op != address(0), "RM: op=0");
        _grantRole(OPERATOR_ROLE, op);
    }

    /**
     * @notice Revokes OPERATOR_ROLE from an address
     * @dev Only callable by DEFAULT_ADMIN_ROLE
     * @param op Address to revoke operator permissions from
     */
    function removeOperator(address op) external onlyAdmin {
        _revokeRole(OPERATOR_ROLE, op);
    }

    /**
     * @notice Returns whether an address has OPERATOR_ROLE.
     * @param op Address to check
     * @return True if address has operator role
     */
    function isOperator(address op) external view returns (bool) {
        return hasRole(OPERATOR_ROLE, op);
    }

    /* ───────────────────────────────────── Admin config ────────────────────────────────── */

    /**
     * @notice Updates the UniversalRouter address
     * @dev    newRouter must be a deployed contract
     * @param  newRouter Address of the new router
     */
    function setRouter(address newRouter) external onlyAdmin {
        require(newRouter != address(0) && newRouter.code.length > 0, "RM: bad router");
        address old = address(router);
        router = IUniversalRouter(newRouter);
        emit RouterUpdated(old, newRouter);
    }

    /**
     * @notice Updates the DSF core contract address
     * @dev    newDsf must be a deployed contract
     * @param  newDsf Address of the new DSF contract
     */
    function setDSF(address newDsf) external onlyAdmin {
        require(newDsf != address(0) && newDsf.code.length > 0, "RM: bad DSF");
        address old = address(dsf);
        dsf = IDSF(newDsf);
        emit DSFUpdated(old, newDsf);
    }

    /**
     * @notice Updates the management fee recipient
     * @dev newFD must be a deployed contract
     * @param newFD Address of the new fee distributor
     */
    function setFeeDistributor(address newFD) external onlyAdmin {
        require(newFD != address(0), "RM: bad feeDistributor");
        address old = feeDistributor;
        feeDistributor = newFD;
        emit FeeDistributorUpdated(old, newFD);
    }

    /**
     * @notice Updates default slippage (in basis points) used for auto-swaps
     * @dev bps must be <= 10_000
     * @param bps Slippage in basis points (100% = 10_000)
     */
    function setDefaultSlippageBps(uint16 bps) external onlyAdmin {
        require(bps <= 10_000, "RM: bad bps");
        uint16 old = defaultSlippageBps;
        defaultSlippageBps = bps;
        emit DefaultSlippageUpdated(old, bps);
    }

    /**
     * @notice Sets swap path from `token` to USDT and enables it for auto-swap
     * @dev    Requirements:
     *         - token must be a deployed contract
     *         - path length >= 2
     *         - path[0] == token
     *         - path[last] == USDT
     *
     *         Replaces any previously stored path.
     *         Adds token to autoSwapTokens if not already present
     * @param  token Reward token address
     * @param  path Swap path (token ... USDT)
     */
    function setPathToUsdt(address token, address[] calldata path) external onlyAdmin {
        require(token != address(0) && token.code.length > 0, "RM: bad token");
        require(path.length >= 2, "RM: path short");
        require(path[0] == token, "RM: path[0]!=token");
        require(path[path.length - 1] == USDT, "RM: last!=USDT");

        if (!isAutoSwapToken[token]) {
            autoSwapTokens.push(token);
            isAutoSwapToken[token] = true;
        }

        // store
        delete _pathToUsdt[token];
        for (uint256 i = 0; i < path.length; i++) {
            _pathToUsdt[token].push(path[i]);
        }

        emit PathToUsdtUpdated(token, path);
    }
    
    /**
     * @notice Removes token from auto-swap whitelist and clears its stored path
     * @dev    Uses swap-pop to remove token from autoSwapTokens array
     * @param  token Token address to remove
     */
    function removeAutoSwapToken(address token) external onlyAdmin {
        if (!isAutoSwapToken[token]) return;

        // delete path
        delete _pathToUsdt[token];

        // remove from array (swap-pop)
        uint256 n = autoSwapTokens.length;
        for (uint256 i = 0; i < n; i++) {
            if (autoSwapTokens[i] == token) {
                if (i != n - 1) autoSwapTokens[i] = autoSwapTokens[n - 1];
                autoSwapTokens.pop();
                break;
            }
        }

        isAutoSwapToken[token] = false;
        emit AutoSwapTokenRemoved(token);
    }

    /**
     * @notice Enables or disables a DSF pool for RewardManager allocations
     * @dev    Reverts if `pid` is out of DSF pool range
     * @param  pid DSF pool id
     * @param  v   True to blacklist, false to unblacklist
     */
    function setPoolBlacklisted(uint256 pid, bool v) external onlyAdmin {
        require(pid < dsf.poolCount(), "RM: pid out of range");
        isPoolBlacklisted[pid] = v;
        emit PoolBlacklistUpdated(pid, v);
    }

    /**
     * @notice Batch update blacklist flag for multiple pids (same value).
     * @dev    Reverts if any pid is out of range.
     * @param  pids Array of DSF pool ids
     * @param  v    True to blacklist, false to unblacklist
     */
    function batchSetPoolBlacklisted(uint256[] calldata pids, bool v) external onlyAdmin {
        uint256 nPools = dsf.poolCount();
        for (uint256 i = 0; i < pids.length; i++) {
            uint256 pid = pids[i];
            require(pid < nPools, "RM: pid out of range");
            isPoolBlacklisted[pid] = v;
            emit PoolBlacklistUpdated(pid, v);
        }
    }

    /**
     * @notice Returns stored swap path from token to USDT
     * @param  token Input token address
     * @return Swap path (token ... USDT)
     */
    function getPathToUsdt(address token) external view returns (address[] memory) {
        return _pathToUsdt[token];
    }

    /**
     * @notice Returns list of tokens enabled for auto-swap
     * @return Array of whitelisted reward tokens
     */
    function getAutoSwapTokens() external view returns (address[] memory) {
        return autoSwapTokens;
    }

    /* ───────────────────────────── Operator: DSF compounding ───────────────────────────── */

    /**
     * @notice Triggers DSF.autoCompoundAll()
     * @dev Intended to claim/push rewards from all strategies to RewardManager
     *      Only callable by OPERATOR_ROLE
     */
    function DSFAutoCompoundAll() external onlyOperator nonReentrant {
        dsf.autoCompoundAll();
        emit DsfAutoCompoundAllCalled(msg.sender);
    }

    /* ───────────────────────────── AUTO swap (balance -> USDT) ─────────────────────────── */

    /**
     * @notice Swaps all whitelisted reward tokens into USDT using an internal deadline
     * @dev    Public entrypoint for operators/keepers
     *         Computes a single deadline as `block.timestamp + TRADE_DEADLINE`
     *         and executes `_swapAllAuto(deadline)` to swap all eligible tokens
     *
     *         Tokens with zero balance or missing swap path are skipped
     */
    function swapAllAuto() external onlyOperator nonReentrant {
        uint256 deadline = block.timestamp + TRADE_DEADLINE;
        _swapAllAuto(deadline);
    }

    /* ─────────────────────────────── MANUAL swap (payload) ─────────────────────────────── */

    /**
     * @notice Executes a manual swap via router.swapRoute()
     * @dev    Requirements:
     *         - payload must encode (module,index,quotedOut,tokenIn,tokenOut,amountIn,route)
     *         - tokenIn must be a valid contract
     *         - amountIn > 0
     *         Reads tokenIn and amountIn directly from payload,
     *         approves router for amountIn, and forwards execution
     * @param  payload        ABI-encoded route payload
     * @param  minAmountOut   Minimum output required
     * @param  useOracleGuard Whether oracle guard is enabled
     * @param  maxDevBps      Max allowed deviation (bps) for oracle guard
     *
     * @return netOut         Output amount returned by router
     */
    function swapManualRoute(
        bytes calldata payload,
        uint256 minAmountOut,
        bool useOracleGuard,
        uint16 maxDevBps
    )
        external
        onlyAdmin
        nonReentrant
        returns (uint256 netOut)
    {
        // We must approve tokenIn for router BEFORE calling swapRoute.
        // tokenIn is inside payload; we read it from the ABI header slots like your router does.
        // Layout in payload = abi.encode(module,index,quotedOut,tokenIn,tokenOut,amountIn,bytes[]route)
        address tokenIn = _loadAddressFromPayload(payload, 3);
        uint256 amountIn = _loadUint256FromPayload(payload, 5);

        require(tokenIn != address(0) && tokenIn.code.length > 0, "RM: bad tokenIn");
        require(amountIn > 0, "RM: zero amountIn");

        _smartApprove(tokenIn, address(router), amountIn);

        netOut = router.swapRoute(
            payload,
            address(this),     // keep result inside RM
            minAmountOut,
            useOracleGuard,
            maxDevBps
        );

        emit ManualRouteSwapExecuted(keccak256(payload), netOut);
    }

    /**
     * @notice Executes a manual split swap via router.swapSplit()
     * @dev    Requirements:
     *         - percentA must be in range 1..99
     *         - tokenIn in both payloads must match
     *         - amountIn encoded in both payloads must match and be > 0
     *         Approves router once for totalIn and forwards parameters
     * @param  payloadA       First encoded route
     * @param  payloadB       Second encoded route
     * @param  percentA       Percentage allocated to payloadA (1..99)
     * @param  minAmountOut   Minimum total output expected
     * @param  useOracleGuard Whether oracle guard is enabled
     * @param  maxDevBps      Max deviation (bps) for oracle guard
     * @return netOut         Total output received
     */
    function swapManualSplit(
        bytes calldata payloadA,
        bytes calldata payloadB,
        uint16 percentA,        // 1..99
        uint256 minAmountOut,
        bool useOracleGuard,
        uint16 maxDevBps
    )
        external
        onlyAdmin
        nonReentrant
        returns (uint256 netOut)
    {
        require(percentA >= 1 && percentA <= 99, "RM: bad percentA");

        address tokenInA = _loadAddressFromPayload(payloadA, 3);
        uint256 totalInA = _loadUint256FromPayload(payloadA, 5);

        address tokenInB = _loadAddressFromPayload(payloadB, 3);
        uint256 totalInB = _loadUint256FromPayload(payloadB, 5);

        require(tokenInA != address(0) && tokenInA.code.length > 0, "RM: bad tokenInA");
        require(tokenInB != address(0) && tokenInB.code.length > 0, "RM: bad tokenInB");
        require(tokenInA == tokenInB, "RM: tokenIn mismatch");

        require(totalInA > 0 && totalInB > 0, "RM: zero in");
        require(totalInA == totalInB, "RM: payload amountIn mismatch");

        uint256 totalIn = totalInA;

        // Router will transferFrom(RM) exactly once for totalIn
        _smartApprove(tokenInA, address(router), totalIn);

        netOut = router.swapSplit(
            payloadA,
            payloadB,
            percentA,
            minAmountOut,
            address(this),
            useOracleGuard,
            maxDevBps
        );

        emit ManualSplitSwapExecuted(keccak256(payloadA), keccak256(payloadB), percentA, netOut);
    }

    /* ───────────────────────────── Manager compound ───────────────────────────── */

    /**
     * @notice Sends USDT to DSF default deposit pool strategy via managerCompound()
     * @param  amountUSDT 0 = use entire USDT balance of RewardManager
     */
    function managerCompoundToDepositPool(uint256 amountUSDT) external onlyOperator nonReentrant {
        uint256 pid = dsf.defaultDepositPid();
        _managerCompoundSinglePid(pid, amountUSDT);
    }

    /**
     * @notice Sends USDT to DSF default withdraw pool strategy via managerCompound()
     * @param  amountUSDT 0 = use entire USDT balance of RewardManager
     */
    function managerCompoundToWithdrawPool(uint256 amountUSDT) external onlyOperator nonReentrant {
        uint256 pid = dsf.defaultWithdrawPid();
        _managerCompoundSinglePid(pid, amountUSDT);
    }

    /**
     * @notice Manual allocation: list of pids + bps weights (sum must be 10_000)
     * @param  pids DSF pool ids
     * @param  bps Weights in bps (sum = 10_000)
     * @param  amountUSDT 0 = use entire USDT balance of RewardManager
     */
    function managerCompoundManual(
        uint256[] calldata pids,
        uint16[] calldata bps,
        uint256 amountUSDT
    ) external onlyOperator nonReentrant {
        require(pids.length > 0, "RM: empty pids");
        require(pids.length == bps.length, "RM: len mismatch");

        uint256 sum;
        for (uint256 i = 0; i < bps.length; i++) sum += bps[i];
        require(sum == BPS_DENOMINATOR, "RM: bps sum != 10000");

        uint256 bal = IERC20(USDT).balanceOf(address(this));
        uint256 amount = amountUSDT == 0 ? bal : amountUSDT;
        require(amount > 0, "RM: zero amount");
        require(amount <= bal, "RM: insufficient USDT");

        uint256 fee = dsf.calcManagementFee(amount);
        if (fee > 0) {
            IERC20(USDT).safeTransfer(feeDistributor, fee);
            emit ManagementFeePaid(feeDistributor, fee);
        }

        uint256 net = amount - fee;
        require(net > 0, "RM: net=0");

        uint256 left = net;

        for (uint256 i = 0; i < pids.length; i++) {
            require(pids[i] < dsf.poolCount(), "RM: pid out of range");
            uint256 part = (i + 1 == pids.length) ? left : (net * bps[i]) / BPS_DENOMINATOR;
            if (part == 0) continue;

            left -= part;
            _callStrategyManagerCompound(pids[i], part);
        }
    }

    /**
     * @notice Full pipeline: DSF.autoCompoundAll() -> auto-swap whitelist tokens -> pay fee -> deposit net into default deposit pid
     * @param  amountUSDT 0 = use entire USDT balance after swaps
     */
    function managerCompoundAllToDepositPool(uint256 amountUSDT)
        external
        onlyOperator
        nonReentrant
    {
        uint256 deadline = block.timestamp + TRADE_DEADLINE;

        dsf.autoCompoundAll();
        emit DsfAutoCompoundAllCalled(msg.sender);

        // swap whitelist reward tokens -> USDT
        _swapAllAuto(deadline);

        uint256 pid = dsf.defaultDepositPid();

        uint256 bal = IERC20(USDT).balanceOf(address(this));
        uint256 amount = amountUSDT == 0 ? bal : amountUSDT;
        require(amount > 0, "RM: zero amount");
        require(amount <= bal, "RM: insufficient USDT");

        uint256 fee = dsf.calcManagementFee(amount);
        if (fee > 0) {
            IERC20(USDT).safeTransfer(feeDistributor, fee);
            emit ManagementFeePaid(feeDistributor, fee);
        }

        uint256 net = amount - fee;
        require(net > 0, "RM: net=0");

        _callStrategyManagerCompound(pid, net);

        emit ManagerCompoundAllToDepositPool(msg.sender, amount, fee, net, pid);
    }

    /**
     * @notice Full pipeline: DSF.autoCompoundAll() -> auto-swap whitelist tokens -> pay fee -> deposit net into default withdraw pid
     * @param  amountUSDT 0 = use entire USDT balance after swaps
     */
    function managerCompoundAllToWithdrawPool(uint256 amountUSDT)
        external
        onlyOperator
        nonReentrant
    {
        uint256 deadline = block.timestamp + TRADE_DEADLINE;

        dsf.autoCompoundAll();
        emit DsfAutoCompoundAllCalled(msg.sender);

        _swapAllAuto(deadline);

        uint256 pid = dsf.defaultWithdrawPid();

        uint256 bal = IERC20(USDT).balanceOf(address(this));
        uint256 amount = amountUSDT == 0 ? bal : amountUSDT;
        require(amount > 0, "RM: zero amount");
        require(amount <= bal, "RM: insufficient USDT");

        uint256 fee = dsf.calcManagementFee(amount);
        if (fee > 0) {
            IERC20(USDT).safeTransfer(feeDistributor, fee);
            emit ManagementFeePaid(feeDistributor, fee);
        }

        uint256 net = amount - fee;
        require(net > 0, "RM: net=0");

        _callStrategyManagerCompound(pid, net);

        emit ManagerCompoundAllToWithdrawPool(msg.sender, amount, fee, net, pid);
    }

    /**
     * @notice Rebalance allocations to move pool share prices toward DSF global price (totalHoldings/totalSupply)
     * @dev    Logic:
     *         1) autoCompoundAll + auto-swap rewards -> USDT
     *         2) pay management fee
     *         3) compute targetPrice = dsf.totalHoldings / dsf.totalSupply
     *         4) allocate net USDT to pools below target proportionally to their deficits
     *         5) leftover (rounding) goes to last allocated pool, otherwise to min-price pool
     * @param  amountUSDT 0 = use entire USDT balance after swaps
     * @param  maxPoolsToScan 0 = scan all pools, otherwise scan first N for gas control
     */
    function managerCompoundRebalanceToTarget(
        uint256 amountUSDT,      // 0 = entire USDT balance of RM after swap
        uint256 maxPoolsToScan   // gas protection (0 = scan all)
    ) external onlyOperator nonReentrant {

        uint256 deadline = block.timestamp + TRADE_DEADLINE;

        // 1) claim / push rewards from strategies -> RM
        dsf.autoCompoundAll();
        emit DsfAutoCompoundAllCalled(msg.sender);

        // 2) swap whitelist reward tokens -> USDT
        _swapAllAuto(deadline);

        // 3) take USDT and pay management fee
        uint256 bal1e6 = IERC20(USDT).balanceOf(address(this));
        uint256 amount1e6 = amountUSDT == 0 ? bal1e6 : amountUSDT;
        require(amount1e6 > 0, "RM: zero amount");
        require(amount1e6 <= bal1e6, "RM: insufficient USDT");

        uint256 fee1e6 = dsf.calcManagementFee(amount1e6);
        if (fee1e6 > 0) {
            IERC20(USDT).safeTransfer(feeDistributor, fee1e6);
            emit ManagementFeePaid(feeDistributor, fee1e6);
        }

        uint256 net1e6 = amount1e6 - fee1e6;
        require(net1e6 > 0, "RM: net=0");

        // 4) compute target price
        uint256 net1e18 = _to1e18(net1e6); // 1e18

        uint256 ts = dsf.totalSupply();
        require(ts > 0, "RM: totalSupply=0");

        // targetPrice1e18 = dsf.totalHoldings(1e18) * 1e18 / totalSupply(1e18) => 1e18
        uint256 targetPrice1e18 = (dsf.totalHoldings() * PRICE_SCALE) / ts;

        // 5) scan pools, collect deficits in 1e18; also find minPrice pool
        uint256 n = dsf.poolCount();
        uint256 limit = maxPoolsToScan == 0 ? n : (maxPoolsToScan < n ? maxPoolsToScan : n);

        // first pass: compute sumNeed, and track min price pool for leftover
        uint256 sumNeed1e18 = 0;
        uint256 minPrice1e18 = type(uint256).max;
        uint256 minPricePid = dsf.defaultDepositPid();

        for (uint256 pid = 0; pid < limit; pid++) {
            if (isPoolBlacklisted[pid]) continue;

            IDSF.PoolInfo memory p = dsf.poolInfo(pid);
            if (p.lpShares == 0) continue;

            address strat = p.strategy;
            if (strat == address(0) || strat.code.length == 0) continue;
            if (strat == address(this)) continue; // ✅ RM-pid

            uint256 h1e18 = _safeStrategyHoldings(strat);
            uint256 price1e18 = (h1e18 * PRICE_SCALE) / p.lpShares; // 1e18

            if (price1e18 < minPrice1e18) {
                minPrice1e18 = price1e18;
                minPricePid = pid;
            }

            // desired holdings to reach target
            uint256 desired1e18 = (targetPrice1e18 * p.lpShares) / PRICE_SCALE;

            if (desired1e18 > h1e18) {
                sumNeed1e18 += (desired1e18 - h1e18);
            }
        }

        require(minPrice1e18 != type(uint256).max, "RM: no active pools");
        emit RebalancePlanned(
            targetPrice1e18,
            net1e6,
            sumNeed1e18,
            (sumNeed1e18 == 0 || net1e18 > sumNeed1e18) ? _to1e6(net1e18 - (sumNeed1e18 == 0 ? 0 : sumNeed1e18)) : 0
        );

        // If no deficits: put all net to minPricePid (or defaultDepositPid)
        if (sumNeed1e18 == 0) {
            _callStrategyManagerCompound(minPricePid, net1e6);
            emit RebalanceAllocated(minPricePid, net1e6);
            return;
        }

        // 6) allocate
        uint256 left1e18 = net1e18;

        // last pid where we actually allocated > 0
        uint256 lastAllocatedPid = type(uint256).max;

        for (uint256 pid = 0; pid < limit; pid++) {
            if (left1e18 == 0) break;
            if (isPoolBlacklisted[pid]) continue;

            IDSF.PoolInfo memory p = dsf.poolInfo(pid);
            if (p.lpShares == 0) continue;

            address strat = p.strategy;
            if (strat == address(0) || strat.code.length == 0) continue;
            if (strat == address(this)) continue; // ✅ RM-pid

            uint256 h1e18 = _safeStrategyHoldings(strat);
            uint256 desired1e18 = (targetPrice1e18 * p.lpShares) / PRICE_SCALE;
            if (desired1e18 <= h1e18) continue;

            uint256 need1e18 = desired1e18 - h1e18;

            uint256 part1e18 = (net1e18 * need1e18) / sumNeed1e18;
            if (part1e18 > left1e18) part1e18 = left1e18;
            if (part1e18 == 0) continue;

            left1e18 -= part1e18;

            uint256 part1e6 = _to1e6(part1e18);

            if (part1e6 > 0) {
                _callStrategyManagerCompound(pid, part1e6);
                emit RebalanceAllocated(pid, part1e6);
                lastAllocatedPid = pid;
            }

            if (left1e18 == 0) break;
        }

        // rounding leftover -> lastAllocatedPid; if none -> minPricePid
        if (left1e18 > 0) {
            uint256 leftover1e6 = _to1e6(left1e18);

            if (leftover1e6 > 0) {
                uint256 targetPid = (lastAllocatedPid != type(uint256).max) ? lastAllocatedPid : minPricePid;
                _callStrategyManagerCompound(targetPid, leftover1e6);
                emit RebalanceAllocated(targetPid, leftover1e6);
            }
        }
    }

    /* ───────────────────────────── Analitics ───────────────────────────── */

    /**
     * @notice Returns best swap routes for a given token pair and amount
     * @dev    Simple proxy to router.getBestRoute()
     *         Provides:
     *         - Top1 1-hop route
     *         - Top1 2-hop route
     *         - Top2 1-hop route
     *         - Top2 2-hop route
     *         - Suggested split configuration
     * @param  tokenIn           Input token address
     * @param  tokenOut          Output token address
     * @param  amountIn          Input amount
     * @return best1HopRouteTop1 Encoded best 1-hop route (rank 1)
     * @return amountOut1HopTop1 Output for best 1-hop route (rank 1)
     * @return best2HopRouteTop1 Encoded best 2-hop route (rank 1)
     * @return amountOut2HopTop1 Output for best 2-hop route (rank 1)
     * @return best1HopRouteTop2 Encoded best 1-hop route (rank 2)
     * @return amountOut1HopTop2 Output for best 1-hop route (rank 2)
     * @return best2HopRouteTop2 Encoded best 2-hop route (rank 2)
     * @return amountOut2HopTop2 Output for best 2-hop route (rank 2)
     * @return splitAmountOut    Estimated output using suggested split
     * @return splitPercentA     Suggested percent allocation to route A (1..99)
     */
    function getBestRoute(
        address tokenIn,
        address tokenOut,
        uint256 amountIn
    ) external view returns (
        bytes memory best1HopRouteTop1, uint256 amountOut1HopTop1,
        bytes memory best2HopRouteTop1, uint256 amountOut2HopTop1,
        bytes memory best1HopRouteTop2, uint256 amountOut1HopTop2,
        bytes memory best2HopRouteTop2, uint256 amountOut2HopTop2,
        uint256 splitAmountOut, uint16 splitPercentA
    ) {
        return router.getBestRoute(tokenIn, tokenOut, amountIn);
    }

    /**
     * @notice Returns a snapshot of all active DSF pools
     * @dev    Returns multiple arrays (tuple of arrays) instead of an array of structs
     *         to ensure compatibility with all UI/Analytics tools and avoid ABI-decoding issues.
     *         Iterates over all DSF pools and includes only:
     *         - Pools not blacklisted
     *         - Pools with a valid deployed strategy
     *         - Pools not pointing to this RewardManager (self-pid guard)
     * @return pids         Array of pool IDs
     * @return strategies   Array of strategy addresses
     * @return lpShares     Array of total LP shares per pool
     * @return totalHolding Array of total holdings in USDT (1e18 precision)
     * @return LPprice      Array of computed share prices (1e18 precision)
     */
    function getPoolsInfo()
        external
        view
        returns (
            uint256[] memory pids,
            address[] memory strategies,
            uint256[] memory lpShares,
            uint256[] memory totalHolding,
            uint256[] memory LPprice
        ) 
    {
        uint256 n = dsf.poolCount(); 
        
        uint256 activeCount = 0;
        for (uint256 i = 0; i < n; i++) {
            if (isPoolBlacklisted[i]) continue;
            address strat = dsf.poolInfo(i).strategy; 
            if (strat == address(0) || strat.code.length == 0 || strat == address(this)) continue;
            activeCount++;
        }

        pids = new uint256[](activeCount);
        strategies = new address[](activeCount);
        lpShares = new uint256[](activeCount);
        totalHolding = new uint256[](activeCount);
        LPprice = new uint256[](activeCount);

        uint256 j = 0;
        for (uint256 i = 0; i < n; i++) {
            if (isPoolBlacklisted[i]) continue;

            IDSF.PoolInfo memory p = dsf.poolInfo(i);
            address strat = p.strategy;

            if (strat == address(0) || strat.code.length == 0 || strat == address(this)) continue;

            uint256 holdings = _safeStrategyHoldings(strat);
            uint256 price = (p.lpShares > 0) ? (holdings * PRICE_SCALE) / p.lpShares : 0;

            pids[j] = i;
            strategies[j] = strat;
            lpShares[j] = p.lpShares;
            totalHolding[j] = holdings;
            LPprice[j] = price;
            j++;
        }
    }

    /**
     * @notice Returns RewardManager net holdings denominated in USDT (1e18 scale)
     * @dev    Calculation:
     *         1. Reads native USDT balance held by RewardManager (1e6 decimals)
     *         2. Iterates over whitelisted autoSwapTokens:
     *            - For each token, reads balance
     *            - Quotes NET USDT value via router.getAmountsOut()
     *            - Adds quoted NET amount to grossUSDT
     *         3. Computes DSF management fee on grossUSDT
     *         4. Returns (grossUSDT - fee) scaled to 1e18 precision
     *         Important:
     *         - Router is assumed to return NET output already
     *         - All intermediate accounting is done in native USDT decimals (1e6)
     *         - Final result is converted to 1e18 precision
     * @return netUSDT_1e18 Net holdings expressed in USDT terms (1e18 precision)
     */
    function totalHoldings() external view returns (uint256 netUSDT_1e18) {
        uint256 grossUSDT = IERC20(USDT).balanceOf(address(this)); // native USDT decimals

        uint256 n = autoSwapTokens.length;
        for (uint256 i = 0; i < n; i++) {
            address tokenIn = autoSwapTokens[i];
            uint256 bal = IERC20(tokenIn).balanceOf(address(this));
            if (bal == 0) continue;

            address[] memory path = _pathToUsdt[tokenIn];
            if (path.length < 2) continue;

            // router.getAmountsOut returns NET already, in USDT native decimals (because last token is USDT)
            uint256 quotedNetUSDT = _quoteNet(bal, path);
            if (quotedNetUSDT == 0) continue;

            grossUSDT += quotedNetUSDT;
        }

        uint256 fee = dsf.calcManagementFee(grossUSDT); // fee in native USDT decimals
        uint256 netUSDT = (grossUSDT > fee) ? (grossUSDT - fee) : 0;

        // scale native USDT -> 1e18
        netUSDT_1e18 = netUSDT * USDT_DECIMALS_SCALE;
    }

    /* ───────────────────────────── Internal helpers ───────────────────────────── */

    /**
     * @notice Swaps the entire balance of `tokenIn` held by RewardManager into USDT using the stored path
     * @dev    Flow:
     *         1. Reads `tokenIn` balance on this contract; returns 0 if balance is zero
     *         2. Loads stored `_pathToUsdt[tokenIn]` and requires length >= 2
     *         3. Quotes NET output via `_quoteNet()` (router.getAmountsOut())
     *         4. Applies `defaultSlippageBps` on top of the NET quote to compute `minOut`
     *         5. Approves router to pull `tokenIn` (reset-then-max via `_smartApprove`)
     *         6. Calls `router.swapExactTokensForTokens(...)`, keeping USDT in this contract
     *         7. Computes actual USDT received as postBalance - preBalance and emits {AutoSwapExecuted}
     * @param  tokenIn  Input token to be swapped into USDT
     * @param  deadline Swap deadline forwarded to the router
     * @return usdtOut  Actual USDT received (native decimals, 1e6)
     */ 
     function _swapSingle(address tokenIn, uint256 deadline)
        internal
        returns (uint256 usdtOut)
    {
        uint256 amountIn = IERC20(tokenIn).balanceOf(address(this));
        if (amountIn == 0) return 0;

        address[] memory path = _pathToUsdt[tokenIn];

        // quote net via router.getAmountsOut (it returns NET already in your router)
        uint256 quotedOutNet = _quoteNet(amountIn, path);
        if (quotedOutNet == 0) return 0;
        
        // apply RM slippage on top of router net quote
        uint256 minOut = (quotedOutNet * (10_000 - defaultSlippageBps)) / 10_000;

        uint256 usdtBefore = IERC20(USDT).balanceOf(address(this));

        // approve router to pull tokenIn from RewardManager (msg.sender = RewardManager)
        _smartApprove(tokenIn, address(router), amountIn);

        router.swapExactTokensForTokens(
            amountIn,
            minOut,
            path,
            address(this), // keep USDT in RM
            deadline
        );

        uint256 usdtAfter = IERC20(USDT).balanceOf(address(this));
        usdtOut = (usdtAfter > usdtBefore) ? (usdtAfter - usdtBefore) : 0;

        emit AutoSwapExecuted(tokenIn, amountIn, minOut, usdtOut);
    }

    /**
     * @notice Quotes NET output amount for a swap path via router.getAmountsOut()
     * @dev    Assumes router returns amounts with the last element already NET
     *         (i.e., after internal fee logic)
     *         Reverts if returned array length is less than 2
     * @param  amountIn Input token amount
     * @param  path Swap path (tokenIn ... tokenOut)
     * @return outNet NET output amount for the final token in the path
     */
    function _quoteNet(uint256 amountIn, address[] memory path) internal view returns (uint256 outNet) {
        if (amountIn == 0) return 0;
        if (path.length < 2) return 0;

        if (path[0] == address(0) || path[path.length - 1] != USDT) return 0;

        try router.getAmountsOut(amountIn, path) returns (uint[] memory amounts) {
            if (amounts.length < 2) return 0;
            return amounts[amounts.length - 1];
        } catch {
            return 0;
        }
    }

    /**
     * @notice Ensures sufficient allowance using a reset-then-max approval pattern
     * @dev    Designed for non-standard ERC20 tokens (e.g., USDT) that require
     *         allowance to be set to zero before being increased
     * @param  token   ERC20 token address
     * @param  spender Address that will spend tokens
     * @param  amount  Minimum required allowance
     */
    function _smartApprove(address token, address spender, uint256 amount) internal {
        uint256 cur = IERC20(token).allowance(address(this), spender);
        if (cur < amount) {
            // OZ v5 SafeERC20.forceApprove handles USDT-style approve quirks
            IERC20(token).forceApprove(spender, 0);
            IERC20(token).forceApprove(spender, type(uint256).max);
        }
    }

    /**
     * @notice Reads an address from a specific slot inside an ABI-encoded payload
     * @dev    Reads 32 bytes at:
     *             payload.offset + slot * 32
     *         Then right-shifts by 96 bits to convert to address (20 bytes)
     *         No bounds checks are performed
     *         Caller must guarantee correct payload layout
     * @param  payload ABI-encoded calldata blob
     * @param  slot Zero-based 32-byte slot index
     * @return a Address stored in the specified slot
     */
    function _loadAddressFromPayload(bytes calldata payload, uint256 slot) internal pure returns (address a) {
        assembly ("memory-safe") {
            a := shr(96, calldataload(add(payload.offset, mul(slot, 32))))
        }
    }

    /**
     * @notice Reads a uint256 value from a specific slot inside an ABI-encoded payload.
     * @dev    Assumes the payload is ABI-encoded in fixed 32-byte slots.
     *         The function reads raw calldata at:
     *             payload.offset + slot * 32
     *         No bounds checks are performed — caller must ensure that:
     *         - `slot` points to a valid 32-byte word
     *         - The payload layout matches the expected encoding
     * @param  payload ABI-encoded calldata blob
     * @param  slot Zero-based 32-byte slot index inside the payload
     * @return v The uint256 value stored at the specified slot
     */
    function _loadUint256FromPayload(bytes calldata payload, uint256 slot) internal pure returns (uint256 v) {
        assembly ("memory-safe") {
            v := calldataload(add(payload.offset, mul(slot, 32)))
        }
    }

    /**
     * @notice Converts USDT amount from native decimals (1e6) to 1e18 scale
     * @dev    Multiplies by 1e12 to normalize USDT (6 decimals) to internal 1e18 math
     *         Safe from overflow for realistic USDT supply ranges
     * @param  usdt1e6 Amount in USDT native decimals (1e6)
     * @return Amount scaled to 1e18 precision
     */
    function _to1e18(uint256 usdt1e6) internal pure returns (uint256) {
        return usdt1e6 * USDT_DECIMALS_SCALE;  // *1e12
    }

    /**
     * @notice Converts USDT value from 1e18 scale back to native decimals (1e6)
     * @dev    Divides by 1e12 using integer division (rounds down / floors)
     *         Any remainder below 1e6 precision is truncated
     * @param  usdt1e18 Amount in 1e18 precision
     * @return Amount in USDT native decimals (1e6)
     */
    function _to1e6(uint256 usdt1e18) internal pure returns (uint256) {
        return usdt1e18 / USDT_DECIMALS_SCALE; // floor
    }

    /**
     * @notice Allocates USDT to a single DSF pool after deducting management fee
     * @dev    Flow:
     *         1. Determines effective amount:
     *            - If `amountUSDT == 0`, uses full USDT balance of RewardManager
     *         2. Validates balance sufficiency
     *         3. Calculates DSF management fee via dsf.calcManagementFee()
     *         4. Transfers fee to `feeDistributor`
     *         5. Sends remaining net USDT to the strategy via `_callStrategyManagerCompound`
     *         All amounts are in USDT native decimals (1e6)
     * @param  pid DSF pool id
     * @param  amountUSDT Amount of USDT to allocate (0 = use full balance)
     */
    function _managerCompoundSinglePid(uint256 pid, uint256 amountUSDT) internal {
        uint256 bal = IERC20(USDT).balanceOf(address(this));
        uint256 amount = amountUSDT == 0 ? bal : amountUSDT;
        require(amount > 0, "RM: zero amount");
        require(amount <= bal, "RM: insufficient USDT");

        uint256 fee = dsf.calcManagementFee(amount);
        if (fee > 0) {
            IERC20(USDT).safeTransfer(feeDistributor, fee);
            emit ManagementFeePaid(feeDistributor, fee);
        }

        uint256 net = amount - fee;
        require(net > 0, "RM: net=0");

        _callStrategyManagerCompound(pid, net);
    }

    /**
     * @notice Transfers USDT into a DSF strategy via managerCompound().
     * @dev    Flow:
     *         1. Ensures pool is not blacklisted.
     *         2. Loads strategy address from DSF poolInfo
     *         3. Validates that strategy is a deployed contract
     *         4. Approves USDT to strategy (using safe force-approve pattern)
     *         5. Calls strategy.managerCompound(usdtAmount)
     *         The strategy is expected to pull USDT via transferFrom()
     * @param  pid DSF pool id
     * @param  usdtAmount Amount of USDT (native decimals, 1e6) to allocate
     */
    function _callStrategyManagerCompound(uint256 pid, uint256 usdtAmount) internal {
        require(!isPoolBlacklisted[pid], "RM: pid blacklisted");

        IDSF.PoolInfo memory p = dsf.poolInfo(pid);
        address strat = p.strategy;
        require(strat != address(0) && strat.code.length > 0, "RM: bad strategy");
        
        _smartApprove(USDT, strat, usdtAmount);

        IStrategy(strat).managerCompound(usdtAmount);

        emit ManagerCompoundExecuted(pid, strat, usdtAmount);
    }

    /**
     * @notice Safely fetches strategy total holdings
     * @dev    Performs a defensive external call to `IStrategy(strat).totalHoldings()`.
     *         Returns 0 if:
     *         - `strat` is zero address
     *         - `strat` has no code (not a contract)
     *         - The external call reverts for any reason
     * @param  strat Strategy contract address
     * @return h     Strategy total holdings (USDT-denominated, 1e18 scale),
     *               or 0 if the call fails
     */
    function _safeStrategyHoldings(address strat) internal view returns (uint256 h) {
        if (strat == address(0) || strat.code.length == 0) return 0;
        try IStrategy(strat).totalHoldings() returns (uint256 v) {
            return v;
        } catch {
            return 0;
        }
    }

    /**
     * @notice Builds a 3-hop swap path `[a, b, c]`
     * @dev    Convenience helper for initializing routes like `TOKEN -> WETH -> USDT`
     * @param  a    First token in the path (tokenIn)
     * @param  b    Middle token (intermediate hop)
     * @param  c    Last token in the path (tokenOut)
     * @return path A freshly allocated memory array of length 3
     */
    function _make3(address a, address b, address c) internal pure returns (address[] memory path) {
        path = new address[](3);
        path[0] = a;
        path[1] = b;
        path[2] = c;
    }

    /**
     * @notice Stores `token -> USDT` swap path in storage and ensures token is whitelisted for auto-swap
     * @dev    Internal variant used in constructor / internal setup to avoid repeating array copy logic
     *         This function:
     *         - Adds `token` to `autoSwapTokens` if not present (sets `isAutoSwapToken[token]=true`)
     *         - Replaces any previously stored `_pathToUsdt[token]` with the provided `path`
     *         - Emits {PathToUsdtUpdated}
     * @param  token Reward token address (tokenIn for swaps)
     * @param  path  Swap path starting with `token` and ending with `USDT`
     */
    function _setPathToUsdtInternal(address token, address[] memory path) internal {
        // enable autoswap if not enabled
        if (!isAutoSwapToken[token]) {
            autoSwapTokens.push(token);
            isAutoSwapToken[token] = true;
        }

        delete _pathToUsdt[token];
        for (uint256 i = 0; i < path.length; i++) {
            _pathToUsdt[token].push(path[i]);
        }

        emit PathToUsdtUpdated(token, path);
    }

    /**
     * @notice Swaps all whitelisted reward tokens held by RewardManager into USDT
     * @dev    Internal worker for auto-swaps
     *         Iterates over `autoSwapTokens` and for each token:
     *         - skips if RewardManager balance is zero
     *         - skips if no path to USDT is configured (`_pathToUsdt[token].length < 2`)
     *         - otherwise swaps the full token balance to USDT via `_swapSingle(token, deadline)`
     *
     *         `deadline` is expected to be computed by the caller (usually `block.timestamp + TRADE_DEADLINE`)
     *         and is forwarded unchanged to the router call
     * @param  deadline Swap deadline timestamp passed to the router
     */
    function _swapAllAuto(uint256 deadline) internal {
        for (uint256 i = 0; i < autoSwapTokens.length; i++) {
            address tokenIn = autoSwapTokens[i];

            if (IERC20(tokenIn).balanceOf(address(this)) == 0) continue;

            address[] storage pathS = _pathToUsdt[tokenIn];
            if (pathS.length < 2) continue;

            _swapSingle(tokenIn, deadline);
        }
    }
}

@openzeppelin/contracts/access/AccessControl.sol

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

pragma solidity ^0.8.20;

import {IAccessControl} from "./IAccessControl.sol";
import {Context} from "../utils/Context.sol";
import {IERC165, ERC165} from "../utils/introspection/ERC165.sol";

/**
 * @dev Contract module that allows children to implement role-based access
 * control mechanisms. This is a lightweight version that doesn't allow enumerating role
 * members except through off-chain means by accessing the contract event logs. Some
 * applications may benefit from on-chain enumerability, for those cases see
 * {AccessControlEnumerable}.
 *
 * Roles are referred to by their `bytes32` identifier. These should be exposed
 * in the external API and be unique. The best way to achieve this is by
 * using `public constant` hash digests:
 *
 * ```solidity
 * bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
 * ```
 *
 * Roles can be used to represent a set of permissions. To restrict access to a
 * function call, use {hasRole}:
 *
 * ```solidity
 * function foo() public {
 *     require(hasRole(MY_ROLE, msg.sender));
 *     ...
 * }
 * ```
 *
 * Roles can be granted and revoked dynamically via the {grantRole} and
 * {revokeRole} functions. Each role has an associated admin role, and only
 * accounts that have a role's admin role can call {grantRole} and {revokeRole}.
 *
 * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
 * that only accounts with this role will be able to grant or revoke other
 * roles. More complex role relationships can be created by using
 * {_setRoleAdmin}.
 *
 * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
 * grant and revoke this role. Extra precautions should be taken to secure
 * accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
 * to enforce additional security measures for this role.
 */
abstract contract AccessControl is Context, IAccessControl, ERC165 {
    struct RoleData {
        mapping(address account => bool) hasRole;
        bytes32 adminRole;
    }

    mapping(bytes32 role => RoleData) private _roles;

    bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;

    /**
     * @dev Modifier that checks that an account has a specific role. Reverts
     * with an {AccessControlUnauthorizedAccount} error including the required role.
     */
    modifier onlyRole(bytes32 role) {
        _checkRole(role);
        _;
    }

    /// @inheritdoc IERC165
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
    }

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) public view virtual returns (bool) {
        return _roles[role].hasRole[account];
    }

    /**
     * @dev Reverts with an {AccessControlUnauthorizedAccount} error if `_msgSender()`
     * is missing `role`. Overriding this function changes the behavior of the {onlyRole} modifier.
     */
    function _checkRole(bytes32 role) internal view virtual {
        _checkRole(role, _msgSender());
    }

    /**
     * @dev Reverts with an {AccessControlUnauthorizedAccount} error if `account`
     * is missing `role`.
     */
    function _checkRole(bytes32 role, address account) internal view virtual {
        if (!hasRole(role, account)) {
            revert AccessControlUnauthorizedAccount(account, role);
        }
    }

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) public view virtual returns (bytes32) {
        return _roles[role].adminRole;
    }

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     *
     * May emit a {RoleGranted} event.
     */
    function grantRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
        _grantRole(role, account);
    }

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     *
     * May emit a {RoleRevoked} event.
     */
    function revokeRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
        _revokeRole(role, account);
    }

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been revoked `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `callerConfirmation`.
     *
     * May emit a {RoleRevoked} event.
     */
    function renounceRole(bytes32 role, address callerConfirmation) public virtual {
        if (callerConfirmation != _msgSender()) {
            revert AccessControlBadConfirmation();
        }

        _revokeRole(role, callerConfirmation);
    }

    /**
     * @dev Sets `adminRole` as ``role``'s admin role.
     *
     * Emits a {RoleAdminChanged} event.
     */
    function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
        bytes32 previousAdminRole = getRoleAdmin(role);
        _roles[role].adminRole = adminRole;
        emit RoleAdminChanged(role, previousAdminRole, adminRole);
    }

    /**
     * @dev Attempts to grant `role` to `account` and returns a boolean indicating if `role` was granted.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleGranted} event.
     */
    function _grantRole(bytes32 role, address account) internal virtual returns (bool) {
        if (!hasRole(role, account)) {
            _roles[role].hasRole[account] = true;
            emit RoleGranted(role, account, _msgSender());
            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Attempts to revoke `role` from `account` and returns a boolean indicating if `role` was revoked.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleRevoked} event.
     */
    function _revokeRole(bytes32 role, address account) internal virtual returns (bool) {
        if (hasRole(role, account)) {
            _roles[role].hasRole[account] = false;
            emit RoleRevoked(role, account, _msgSender());
            return true;
        } else {
            return false;
        }
    }
}

@openzeppelin/contracts/access/IAccessControl.sol

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

pragma solidity >=0.8.4;

/**
 * @dev External interface of AccessControl declared to support ERC-165 detection.
 */
interface IAccessControl {
    /**
     * @dev The `account` is missing a role.
     */
    error AccessControlUnauthorizedAccount(address account, bytes32 neededRole);

    /**
     * @dev The caller of a function is not the expected one.
     *
     * NOTE: Don't confuse with {AccessControlUnauthorizedAccount}.
     */
    error AccessControlBadConfirmation();

    /**
     * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
     *
     * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
     * {RoleAdminChanged} not being emitted to signal this.
     */
    event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);

    /**
     * @dev Emitted when `account` is granted `role`.
     *
     * `sender` is the account that originated the contract call. This account bears the admin role (for the granted role).
     * Expected in cases where the role was granted using the internal {AccessControl-_grantRole}.
     */
    event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Emitted when `account` is revoked `role`.
     *
     * `sender` is the account that originated the contract call:
     *   - if using `revokeRole`, it is the admin role bearer
     *   - if using `renounceRole`, it is the role bearer (i.e. `account`)
     */
    event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) external view returns (bool);

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {AccessControl-_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) external view returns (bytes32);

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function grantRole(bytes32 role, address account) external;

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function revokeRole(bytes32 role, address account) external;

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been granted `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `callerConfirmation`.
     */
    function renounceRole(bytes32 role, address callerConfirmation) external;
}

@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/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/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/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/ERC165.sol

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

pragma solidity ^0.8.20;

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

/**
 * @dev Implementation of the {IERC165} interface.
 *
 * Contracts that want to implement ERC-165 should inherit from this contract and override {supportsInterface} to check
 * for the additional interface id that will be supported. For example:
 *
 * ```solidity
 * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
 *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
 * }
 * ```
 */
abstract contract ERC165 is IERC165 {
    /// @inheritdoc IERC165
    function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
        return interfaceId == type(IERC165).interfaceId;
    }
}

@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,
  "libraries": {},
  "optimizer": {
    "runs": 20,
    "enabled": true
  }
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.