UniversalRouter

Description:

Multi-signature wallet contract requiring multiple confirmations for transaction execution.

Blockchain: Ethereum

Source Code: View Code On The Blockchain

Solidity Source Code:

{{
  "language": "Solidity",
  "sources": {
    "contracts/swap/UniversalRouter.sol": {
      "content": "// SPDX-License-Identifier: MIT\r
pragma solidity ^0.8.30;\r
\r
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";\r
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";\r
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";\r
import {ReentrancyGuard} from "@openzeppelin/contracts/security/ReentrancyGuard.sol";\r
\r
/**\r
 * @title  DSF UniversalRouter\r
 * @notice Универсальный роутер, объединяющий DEX-модули (Curve, UniswapV2, SushiSwap, UniswapV3 и другие).\r
 * @dev    Роутер:\r
 * - Запрашивает у каждого модуля лучший маршрут и amountOut;\r
 * - Выбирает модуль с максимальным amountOut;\r
 * - Тянет токены у пользователя (user -> router), даёт approve модулю (router -> module),\r
 *   модуль уже сам делает swap и отправляет результат обратно на роутер;\r
 * - Начисляет, при необходимости, комиссию (feeBps) и отправляет остаток получателю.\r
 *\r
 * ВАЖНО: Модули имеют разный тип Quote, поэтому здесь используется low-level staticcall\r
 * к функции getBestRoute(address,address,uint256) и парсинг только двух вещей:\r
 * (DexRoute route, uint256 amountOut). Это совместимо со всеми модулями.\r
 */\r
\r
/* ─────────────────────────────── Interfaces / Types ─────────────────────────────── */\r
\r
struct DexRoute { bytes[] data; }\r
\r
struct Quote {\r
    address pool;\r
    int128  i;\r
    int128  j;\r
    bool    useUnderlying;\r
    uint256 amountOut;\r
}\r
\r
struct BestAgg {\r
    bytes payload;\r
    uint256 amount;\r
    address module;\r
    uint256 idx;\r
}\r
\r
struct RouteInfo {\r
    address module;\r
    uint256 index;\r
    bytes   payload;  // тот же формат, что в getBestRoute/decodeRoute\r
    uint256 amount;   // quotedOut\r
}\r
\r
struct QuoteArgs {\r
    address tokenIn;\r
    address tokenOut;\r
    uint256 amountIn;\r
}\r
\r
struct LegDecoded {\r
    address module;\r
    uint256 index;\r
    uint256 quoted;     // quotedOut из payload\r
    address tokenIn;\r
    address tokenOut;\r
    uint256 amountIn;\r
    bytes[] route;\r
}\r
\r
struct SplitResult {\r
    address moduleA;\r
    address moduleB;\r
    address tokenIn;\r
    address tokenOut;\r
    uint256 totalIn;\r
    uint256 amountInA;\r
    uint256 amountInB;\r
    uint256 outA;\r
    uint256 outB;\r
    uint256 totalOut;\r
}\r
\r
struct TrackedRoute {\r
    bytes payload;\r
    uint256 amountOut;\r
    address module;\r
    uint256 moduleIndex;\r
}\r
\r
struct BestQuotes {\r
    TrackedRoute top1Hop;\r
    TrackedRoute second1Hop;\r
    TrackedRoute top2Hop;\r
    TrackedRoute second2Hop;\r
}\r
\r
struct ModuleQuotes {\r
    address module;\r
    uint256 moduleIndex;\r
    bytes payload1Hop;\r
    uint256 amountOut1Hop;\r
    bytes payload2Hop;\r
    uint256 amountOut2Hop;\r
}\r
\r
/// 24 Единый минимальный интерфейс для ваших модулей:\r
\r
interface IDexModule {\r
    /**\r
     * @notice  Compute the best 1-hop and 2-hop routes.\r
     * @param   tokenIn    Input token\r
     * @param   tokenOut   Output token\r
     * @param   amountIn   Input amount\r
     * @return  best1HopRoute Serialized 1-hop route\r
     * @return  amountOut1Hop Quoted 1-hop output\r
     * @return  best2HopRoute Serialized 2-hop route\r
     * @return  amountOut2Hop Quoted 2-hop output\r
     */\r
    function getBestRoute(\r
        address tokenIn,\r
        address tokenOut,\r
        uint256 amountIn\r
    ) external view returns (\r
        DexRoute memory best1HopRoute,\r
        uint256 amountOut1Hop,\r
        DexRoute memory best2HopRoute,\r
        uint256 amountOut2Hop\r
    );\r
\r
    /**\r
     * @notice  Execute a previously returned route with a slippage check based on a percentage.\r
     * @param   route     Serialized route\r
     * @param   to        Recipient of the final tokens\r
     * @param   percent   Percentage (0-100) of amountIn from the route to be swapped. 100 = 100%.\r
     * @return  amountOut Actual output received\r
     */\r
    function swapRoute(\r
        DexRoute calldata route,\r
        address to,\r
        uint256 percent\r
    ) external returns (uint256 amountOut);\r
\r
    /**\r
     * @notice  Simulate a route (1–2 hops) encoded as {DexRoute}.\r
     * @param   route Serialized route\r
     * @param   percent   Percentage (0-100)\r
     * @return  amountOut Quoted total output amount\r
     */\r
    function simulateRoute(\r
        DexRoute calldata route,\r
        uint256 percent\r
    ) external view returns (uint256 amountOut);\r
}\r
\r
contract UniversalRouter is Ownable, ReentrancyGuard {\r
    using SafeERC20 for IERC20;\r
\r
    /* ─────────────────────────────── Storage ─────────────────────────────── */\r
\r
    address[] public modules;                     // список модулей (Curve, UniV2, Sushi, UniV3)\r
    mapping(address => bool)     public isModule;\r
    mapping(address => uint256)  private moduleIndexPlusOne; // 1-based для O(1) remove\r
\r
    address public feeRecipient;                  // получатель комиссии\r
    uint16  public feeBps;                        // комиссия в bps (макс 10000 = 100%)\r
\r
    /* ─────────────────────────────── Events ─────────────────────────────── */\r
\r
    event ModuleAdded(address indexed module);\r
    event ModuleRemoved(address indexed module);\r
    event ModulesReset(uint256 newCount);\r
    event FeeUpdated(address recipient, uint16 bps);\r
\r
    event SwapExecuted(\r
        address indexed module,\r
        address indexed user,\r
        address indexed to,\r
        address tokenIn,\r
        address tokenOut,\r
        uint256 amountIn,\r
        uint256 amountOut,\r
        uint256 quotedOut\r
    );\r
\r
    event Swapped(\r
        address indexed module,\r
        address indexed tokenIn,\r
        address indexed tokenOut,\r
        uint256 amountIn,\r
        uint256 amountOut,\r
        address to\r
    );\r
\r
    event SwapSplitExecuted(\r
        address indexed moduleA,\r
        address indexed moduleB,\r
        address indexed user,\r
        address to,\r
        address tokenIn,\r
        address tokenOut,\r
        uint256 totalIn,\r
        uint256 amountInA,\r
        uint256 amountInB,\r
        uint256 outA,\r
        uint256 outB,\r
        uint256 totalOut,\r
        uint16  bpsA\r
    );\r
\r
    /* ─────────────────────────────── Errors ─────────────────────────────── */\r
\r
    error ZeroAddress();\r
    error DuplicateModule();\r
    error NotAModule();\r
    error InvalidFee();\r
    error NoRouteFound();\r
\r
\r
    /* ─────────────────────────────── Modifiers ─────────────────────────────── */\r
\r
    modifier onlyERC20(address token) {\r
        require(token != address(0) && token.code.length > 0, "not ERC20");\r
        _;\r
    }\r
\r
    /* ─────────────────────────────── Constructor ─────────────────────────────── */\r
\r
    constructor(address[] memory _modules, address _feeRecipient, uint16 _feeBps) Ownable(msg.sender) {\r
        _setModules(_modules);     // теперь можно [] — см. _setModules\r
        _setFee(_feeRecipient, _feeBps);\r
    }\r
\r
    // ───────────────────────── Admin: modules mgmt ─────────────────────────\r
\r
    function setModules(address[] calldata _modules) external onlyOwner {\r
        _clearModules();\r
        _addModules(_modules);\r
        emit ModulesReset(_modules.length);\r
    }\r
\r
    function addModule(address module) external onlyOwner {\r
        _addModule(module);\r
    }\r
\r
    function removeModule(address module) external onlyOwner {\r
        _removeModule(module);\r
    }\r
\r
    function modulesLength() external view returns (uint256) {\r
        return modules.length;\r
    }\r
\r
    function getModules() external view returns (address[] memory) {\r
        return modules;\r
    }\r
\r
    /* ─────────── Admin: fee (если понадобится в исполнителе) ─────────── */\r
\r
\r
    function setFee(address recipient, uint16 bps) external onlyOwner { _setFee(recipient, bps); }\r
\r
    function _setFee(address recipient, uint16 bps) internal {\r
        if (bps > 10_000) revert InvalidFee();\r
        feeRecipient = recipient; // может быть 0x0 => комиссия отключена\r
        feeBps = bps;\r
        emit FeeUpdated(recipient, bps);\r
    }\r
\r
    function _setModules(address[] memory _modules) internal {\r
        _clearModules();\r
        uint256 n = _modules.length;\r
        for (uint256 i; i < n; ) {\r
            _addModule(_modules[i]);\r
            unchecked { ++i; }\r
        }\r
        emit ModulesReset(n);\r
    }\r
\r
    function _clearModules() internal {\r
        uint256 n = modules.length;\r
        for (uint256 i; i < n; ) {\r
            address m = modules[i];\r
            isModule[m] = false;\r
            moduleIndexPlusOne[m] = 0;\r
            unchecked { ++i; }\r
        }\r
        delete modules;\r
    }\r
\r
    function _addModules(address[] calldata _modules) internal {\r
        uint256 n = _modules.length;\r
        for (uint256 i; i < n; ) {\r
            _addModule(_modules[i]);\r
            unchecked { ++i; }\r
        }\r
    }\r
\r
    function _addModule(address module) internal {\r
        if (module == address(0)) revert ZeroAddress();\r
        if (isModule[module]) revert DuplicateModule();\r
\r
        // (опционально) минимальная проверка кода\r
        uint256 size;\r
        assembly { size := extcodesize(module) }\r
        if (size == 0) revert ZeroAddress(); // «пустой» адрес\r
\r
        isModule[module] = true;\r
        modules.push(module);\r
        moduleIndexPlusOne[module] = modules.length; // 1-based\r
        emit ModuleAdded(module);\r
    }\r
\r
    function _removeModule(address module) internal {\r
        uint256 idxPlusOne = moduleIndexPlusOne[module];\r
        if (idxPlusOne == 0) revert NotAModule();\r
\r
        uint256 idx = idxPlusOne - 1;\r
        uint256 lastIdx = modules.length - 1;\r
\r
        if (idx != lastIdx) {\r
            address last = modules[lastIdx];\r
            modules[idx] = last;\r
            moduleIndexPlusOne[last] = idx + 1;\r
        }\r
        modules.pop();\r
\r
        isModule[module] = false;\r
        moduleIndexPlusOne[module] = 0;\r
        emit ModuleRemoved(module);\r
    }\r
\r
    // ───────────────────────── core: best route (internal) ─────────────────────────\r
\r
    function _updateBestQuotes(BestQuotes memory currentBest, TrackedRoute memory newRoute, bool is1Hop) private pure {\r
        if (is1Hop) {\r
            if (newRoute.amountOut > currentBest.top1Hop.amountOut) {\r
                currentBest.second1Hop = currentBest.top1Hop;\r
                currentBest.top1Hop = newRoute;\r
            } else if (newRoute.amountOut > currentBest.second1Hop.amountOut) {\r
                currentBest.second1Hop = newRoute;\r
            }\r
        } else { // 2-hop\r
            if (newRoute.amountOut > currentBest.top2Hop.amountOut) {\r
                currentBest.second2Hop = currentBest.top2Hop;\r
                currentBest.top2Hop = newRoute;\r
            } else if (newRoute.amountOut > currentBest.second2Hop.amountOut) {\r
                currentBest.second2Hop = newRoute;\r
            }\r
        }\r
    }\r
\r
    function _getModuleQuotes(\r
        address m,\r
        uint256 idx,\r
        QuoteArgs memory a\r
    ) internal view returns (ModuleQuotes memory quotes) {\r
        quotes.module = m;\r
        quotes.moduleIndex = idx;\r
        \r
        if (!isModule[m]) return quotes;\r
\r
        bytes memory cd = abi.encodeWithSelector(\r
            IDexModule.getBestRoute.selector,\r
            a.tokenIn,\r
            a.tokenOut,\r
            a.amountIn\r
        );\r
\r
        (bool success, bytes memory ret) = m.staticcall(cd);\r
        if (!success || ret.length == 0) return quotes;\r
\r
        (\r
            DexRoute memory route1, uint256 out1,\r
            DexRoute memory route2, uint256 out2\r
        ) = abi.decode(ret, (DexRoute, uint256, DexRoute, uint256));\r
\r
        // Helper to create payload\r
        // Payload format: abi.encode(module, index, quotedOut, tokenIn, tokenOut, amountIn, route.data)\r
        if (out1 > 0 && route1.data.length > 0) {\r
            quotes.amountOut1Hop = out1;\r
            quotes.payload1Hop = abi.encode(\r
                m, idx, out1, a.tokenIn, a.tokenOut, a.amountIn, route1.data\r
            );\r
        }\r
        \r
        if (out2 > 0 && route2.data.length > 0) {\r
            quotes.amountOut2Hop = out2;\r
            quotes.payload2Hop = abi.encode(\r
                m, idx, out2, a.tokenIn, a.tokenOut, a.amountIn, route2.data\r
            );\r
        }\r
    }\r
\r
    /**\r
     * @notice Возвращает 4 лучших маршрута по категориям (Топ-1 / Топ-2 | 1-hop / 2-hop).\r
     * @param tokenIn Адрес входящего токена.\r
     * @param tokenOut Адрес исходящего токена.\r
     * @param amountIn Количество входящего токена.\r
     * @return best1HopRouteTop1 Сериализованный маршрут (payload) с лучшей котировкой среди 1-hop.\r
     * @return amountOut1HopTop1 Количество токенов на выходе для лучшего 1-hop маршрута.\r
     * @return best2HopRouteTop1 Сериализованный маршрут (payload) с лучшей котировкой среди 2-hop.\r
     * @return amountOut2HopTop1 Количество токенов на выходе для лучшего 2-hop маршрута.\r
     * @return best1HopRouteTop2 Сериализованный маршрут (payload) со второй лучшей котировкой среди 1-hop.\r
     * @return amountOut1HopTop2 Количество токенов на выходе для второго лучшего 1-hop маршрута.\r
     * @return best2HopRouteTop2 Сериализованный маршрут (payload) со второй лучшей котировкой среди 2-hop.\r
     * @return amountOut2HopTop2 Количество токенов на выходе для второго лучшего 2-hop маршрута.\r
     */\r
    function getBestRoute(\r
        address tokenIn,\r
        address tokenOut,\r
        uint256 amountIn\r
    ) external view returns (\r
        bytes memory best1HopRouteTop1, uint256 amountOut1HopTop1,\r
        bytes memory best2HopRouteTop1, uint256 amountOut2HopTop1,\r
        bytes memory best1HopRouteTop2, uint256 amountOut1HopTop2,\r
        bytes memory best2HopRouteTop2, uint256 amountOut2HopTop2\r
    ) {\r
        QuoteArgs memory qa = QuoteArgs({\r
            tokenIn: tokenIn,\r
            tokenOut: tokenOut,\r
            amountIn: amountIn\r
        });\r
\r
        BestQuotes memory best; // все поля zero/empty по умолчанию\r
\r
        for (uint256 i = 0; i < modules.length; ) {\r
            ModuleQuotes memory quotes = _getModuleQuotes(modules[i], i, qa);\r
\r
            if (quotes.amountOut1Hop > 0) {\r
                TrackedRoute memory r1 = TrackedRoute({\r
                    payload: quotes.payload1Hop,\r
                    amountOut: quotes.amountOut1Hop,\r
                    module: quotes.module,\r
                    moduleIndex: quotes.moduleIndex\r
                });\r
                _updateBestQuotes(best, r1, true); // true for 1-hop\r
            }\r
\r
            if (quotes.amountOut2Hop > 0) {\r
                TrackedRoute memory r2 = TrackedRoute({\r
                    payload: quotes.payload2Hop,\r
                    amountOut: quotes.amountOut2Hop,\r
                    module: quotes.module,\r
                    moduleIndex: quotes.moduleIndex\r
                });\r
                _updateBestQuotes(best, r2, false); // false for 2-hop\r
            }\r
\r
            unchecked { ++i; }\r
        }\r
\r
        if (best.top1Hop.amountOut == 0 && best.top2Hop.amountOut == 0) {\r
            revert NoRouteFound();\r
        }\r
\r
        // 1-hop, Top 1\r
        best1HopRouteTop1 = best.top1Hop.payload; amountOut1HopTop1 = best.top1Hop.amountOut;\r
        // 2-hop, Top 1\r
        best2HopRouteTop1 = best.top2Hop.payload; amountOut2HopTop1 = best.top2Hop.amountOut;\r
        // 1-hop, Top 2\r
        best1HopRouteTop2 = best.second1Hop.payload; amountOut1HopTop2 = best.second1Hop.amountOut;\r
        // 2-hop, Top 2\r
        best2HopRouteTop2 = best.second2Hop.payload; amountOut2HopTop2 = best.second2Hop.amountOut;\r
    }\r
\r
    /**\r
     * @notice Возвращает лучший маршрут в формате getBestRoute, а также ВСЕ успешные маршруты по модулям.\r
     * @dev Формат каждого payload совпадает с getBestRoute/decodeRoute:\r
     *      abi.encode(module, moduleIndex, quotedOut, tokenIn, tokenOut, amountIn, route.data)\r
     */\r
    /**\r
     * @notice Возвращает лучший маршрут (среди 1-hop и 2-hop) в формате getBestRoute, а также ВСЕ успешные маршруты по модулям.\r
     * @dev Формат каждого payload совпадает с getBestRoute/decodeRoute:\r
     *      abi.encode(module, moduleIndex, quotedOut, tokenIn, tokenOut, amountIn, route.data)\r
     */\r
    function getBestRouteAndAll(\r
        address tokenIn,\r
        address tokenOut,\r
        uint256 amountIn\r
    )\r
        external\r
        view\r
        returns (\r
            bytes memory,        // bestPayload (overall best)\r
            uint256,             // bestAmountOut\r
            address,             // bestModule\r
            uint256,             // bestModuleIndex\r
            RouteInfo[] memory   // routes (все успешные маршруты, включая лучший)\r
        )\r
    {\r
        // Максимум модулей * 2 (1-hop + 2-hop) маршрутов\r
        RouteInfo[] memory allRoutes = new RouteInfo[](modules.length * 2);\r
\r
        BestAgg memory best;\r
        QuoteArgs memory qa = QuoteArgs({tokenIn: tokenIn, tokenOut: tokenOut, amountIn: amountIn});\r
        uint256 k = 0; // Счетчик успешных маршрутов\r
\r
        for (uint256 i = 0; i < modules.length; ) {\r
            ModuleQuotes memory quotes = _getModuleQuotes(modules[i], i, qa);\r
\r
            // 1-hop\r
            if (quotes.amountOut1Hop > 0) {\r
                allRoutes[k] = RouteInfo({\r
                    module: quotes.module,\r
                    index: i,\r
                    payload: quotes.payload1Hop,\r
                    amount: quotes.amountOut1Hop\r
                });\r
                if (quotes.amountOut1Hop > best.amount) {\r
                    best.amount  = quotes.amountOut1Hop;\r
                    best.payload = quotes.payload1Hop;\r
                    best.module  = quotes.module;\r
                    best.idx     = i;\r
                }\r
                unchecked { ++k; }\r
            }\r
            \r
            // 2-hop\r
            if (quotes.amountOut2Hop > 0) {\r
                allRoutes[k] = RouteInfo({\r
                    module: quotes.module,\r
                    index: i,\r
                    payload: quotes.payload2Hop,\r
                    amount: quotes.amountOut2Hop\r
                });\r
                if (quotes.amountOut2Hop > best.amount) {\r
                    best.amount  = quotes.amountOut2Hop;\r
                    best.payload = quotes.payload2Hop;\r
                    best.module  = quotes.module;\r
                    best.idx     = i;\r
                }\r
                unchecked { ++k; }\r
            }\r
\r
            unchecked { ++i; }\r
        }\r
\r
        if (k == 0) revert NoRouteFound();\r
\r
        assembly { mstore(allRoutes, k) } // Уменьшаем размер массива до k\r
\r
        return (best.payload, best.amount, best.module, best.idx, allRoutes);\r
    }\r
\r
    /**\r
     * @dev Приватная вспомогательная функция для расчета общей суммы на выходе.\r
     * @param percentA Процент от amountIn для Маршрута A (0-100).\r
     */\r
    function _calculateTotalOut(\r
        address moduleA,\r
        bytes[] memory routeA,\r
        address moduleB,\r
        bytes[] memory routeB,\r
        uint16 percentA // Теперь 0-100\r
    ) internal view returns (uint256 totalOut) {\r
        uint16 percentB = 100 - percentA;\r
        \r
        // Вызов simulateRoute для A (используем 0-100 Percent)\r
        uint256 outA = IDexModule(moduleA).simulateRoute(DexRoute({ data: routeA }), percentA);\r
        \r
        // Вызов simulateRoute для B (используем 0-100 Percent)\r
        uint256 outB = IDexModule(moduleB).simulateRoute(DexRoute({ data: routeB }), percentB);\r
        \r
        return outA + outB;\r
    }\r
\r
    /**\r
     * @notice Находит оптимальное соотношение разделения (split ratio) между двумя маршрутами.\r
     * @dev Использует simulateRoute для поиска лучшего percentA.\r
     * Эвристика: Сначала проверяются ключевые точки (10%-90%), затем локальное уточнение\r
     * вокруг лучшей точки для экономии запросов.\r
     * @param payloadA Сериализованный маршрут A.\r
     * @param payloadB Сериализованный маршрут B.\r
     * @return bestAmountOut Максимальное количество токенов на выходе.\r
     * @return bestPercentA Оптимальное соотношение для маршрута A в процентах (0-100).\r
     */\r
    function findBestSplit(\r
        bytes calldata payloadA,\r
        bytes calldata payloadB\r
    )\r
        external\r
        view\r
        returns (\r
            uint256 bestAmountOut,\r
            uint16 bestPercentA // Изменено с bestBpsA\r
        )\r
    {\r
        // 1. Декодируем и проверяем\r
        LegDecoded memory A = _decodeRouteStruct(payloadA);\r
        LegDecoded memory B = _decodeRouteStruct(payloadB);\r
\r
        require(A.amountIn > 0 && B.amountIn > 0, "UR: zero amounts");\r
        require(A.tokenIn == B.tokenIn, "UR: in mismatch");\r
        require(A.tokenOut == B.tokenOut, "UR: out mismatch");\r
        require(A.amountIn == B.amountIn, "UR: totalIn mismatch"); \r
\r
        address moduleA = A.module;\r
        address moduleB = B.module;\r
        \r
        // --- Шаг 1: Инициализация (50%) ---\r
        uint16 initialPercent = 50; // 50%\r
        \r
        uint256 currentMaxOut = _calculateTotalOut(\r
            moduleA, A.route, moduleB, B.route, initialPercent\r
        );\r
        uint16 currentBestPercent = initialPercent;\r
\r
        // --- Шаг 2: Основной разреженный поиск: 10% до 90% с шагом 10% ---\r
        // Проверяем 10, 20, 30, 40, 60, 70, 80, 90. (50% уже проверено).\r
        for (uint16 percent = 10; percent <= 90; percent += 10) {\r
            if (percent == 50) continue; \r
\r
            uint256 totalOut = _calculateTotalOut(\r
                moduleA, A.route, moduleB, B.route, percent\r
            );\r
\r
            if (totalOut > currentMaxOut) {\r
                currentMaxOut = totalOut;\r
                currentBestPercent = percent;\r
            }\r
        }\r
        \r
        // --- Шаг 3: Уточнение (Локальный поиск, +/- 5% шаг) ---\r
        \r
        uint16 bestPercentFound = currentBestPercent;\r
        \r
        // Массив смещений для уточнения: [-5, +5] Percent\r
        int16[] memory offsets = new int16[](2);\r
        offsets[0] = -5; // Проверяем -5% от лучшей точки\r
        offsets[1] = 5;  // Проверяем +5% от лучшей точки\r
\r
        for (uint256 i = 0; i < offsets.length; ) {\r
            int16 offset = offsets[i];\r
            \r
            // Защита от выхода за крайние значения (например, ниже 1% или выше 99%)\r
            // Условие: bestPercentFound <= 5 (для -5) или bestPercentFound >= 95 (для +5)\r
            if (\r
                (offset < 0 && bestPercentFound <= uint16(-offset)) || \r
                (offset > 0 && bestPercentFound >= 100 - uint16(offset))\r
            ) {\r
                 unchecked { ++i; }\r
                 continue;\r
            }\r
            \r
            uint16 checkPercent;\r
            if (offset < 0) {\r
                checkPercent = bestPercentFound - uint16(-offset);\r
            } else {\r
                checkPercent = bestPercentFound + uint16(offset);\r
            }\r
            \r
            // Проверка, что точка находится в разумном диапазоне для свопа [1, 99]\r
            if (checkPercent >= 1 && checkPercent <= 99) { \r
                uint256 totalOut = _calculateTotalOut(\r
                    moduleA, A.route, moduleB, B.route, checkPercent\r
                );\r
\r
                if (totalOut > currentMaxOut) {\r
                    currentMaxOut = totalOut;\r
                    currentBestPercent = checkPercent;\r
                }\r
            }\r
            unchecked { ++i; }\r
        }\r
        \r
        // 4. Возврат результата\r
        bestAmountOut = currentMaxOut;\r
        bestPercentA = currentBestPercent;\r
    }\r
\r
    function decodeRoute(bytes calldata payload)\r
        public\r
        pure\r
        returns (\r
            address module,\r
            uint256 moduleIndex,\r
            uint256 quotedOut,\r
            address tokenIn,\r
            address tokenOut,\r
            uint256 amountIn,\r
            bytes[] memory routeData\r
        )\r
    {\r
        (module, moduleIndex, quotedOut, tokenIn, tokenOut, amountIn, routeData) =\r
            abi.decode(payload, (address, uint256, uint256, address, address, uint256, bytes[]));\r
    }\r
\r
    // Быстро достаём 3-е поле (amountOut) из payload: \r
    // payload = abi.encode(module, index, amountOut, tokenIn, tokenOut, amountIn, bytes[] route)\r
    function _extractQuotedOut(bytes memory payload) internal pure returns (uint256 out_) {\r
        assembly {\r
            // payload: [len][module][index][amountOut]...\r
            let data := add(payload, 32)\r
            out_ := mload(add(data, 64)) // 64 = 2 * 32\r
        }\r
    }\r
\r
    /// @notice Декодирует payload и возвращает готовую структуру Best (+ DexRoute внутри).\r
    // function decodeBestPayload(bytes memory payload)\r
    //     public\r
    //     pure\r
    //     returns (address module, uint256 moduleIndex, uint256 amountOut, bytes[] memory routeData)\r
    // {\r
    //     (module, moduleIndex, amountOut, routeData) =\r
    //         abi.decode(payload, (address, uint256, uint256, bytes[]));\r
    // }\r
\r
    function _smartApprove(address token, address spender, uint256 amount) internal {\r
        uint256 cur = IERC20(token).allowance(address(this), spender);\r
        if (cur < amount) {\r
            if (cur > 0) IERC20(token).forceApprove(spender, 0);\r
            IERC20(token).forceApprove(spender, type(uint256).max);\r
        }\r
    }\r
    \r
\r
    // ───────────────────────── свопы ─────────────────────────\r
\r
    error FotNotSupported();\r
    error SlippageExceeded();\r
\r
    /**\r
     * @notice Выполнить своп по уже подготовленному payload (из off-chain/кеша).\r
     */\r
    function swapRoute(bytes calldata payload, address to, uint256 minAmountOut)\r
        external\r
        nonReentrant\r
        returns (uint256 amountOut)\r
    {\r
        require(to != address(0), "UR: bad to");\r
\r
        (\r
            address module, , uint256 quotedOut,\r
            address tokenIn, address tokenOut, uint256 amountIn,\r
            bytes[] memory routeData\r
        ) = decodeRoute(payload);\r
\r
        require(isModule[module], "UR: unknown module");\r
        require(amountIn > 0, "UR: zero amountIn");\r
        require(routeData.length > 0, "UR: empty route");\r
\r
        IERC20(tokenIn).safeTransferFrom(msg.sender, address(this), amountIn);\r
        _smartApprove(tokenIn, module, amountIn);\r
\r
        amountOut = IDexModule(module).swapRoute(DexRoute({ data: routeData }), to, 100);\r
        require(amountOut >= minAmountOut, "UR: slippage");\r
\r
        emit SwapExecuted(module, msg.sender, to, tokenIn, tokenOut, amountIn, amountOut, quotedOut);\r
    }\r
\r
    function swapSplit(\r
        bytes calldata payloadA,\r
        bytes calldata payloadB,\r
        uint16 bpsA,\r
        address to,\r
        uint256 minTotalOut\r
    ) external nonReentrant returns (uint256) {\r
        require(to != address(0), "UR: bad to");\r
        require(bpsA <= 10_000,   "UR: bps");\r
\r
        SplitResult memory R;\r
\r
        // Держим A/B только внутри блока, чтобы они «умерли» до emit\r
        {\r
            LegDecoded memory A = _decodeRouteStruct(payloadA);\r
            LegDecoded memory B = _decodeRouteStruct(payloadB);\r
\r
            require(isModule[A.module] && isModule[B.module], "UR: unknown module");\r
            require(A.amountIn > 0 || B.amountIn > 0, "UR: zero amounts");\r
            require(A.tokenIn  == B.tokenIn,  "UR: in mismatch");\r
            require(A.tokenOut == B.tokenOut, "UR: out mismatch");\r
\r
            R.tokenIn   = A.tokenIn;\r
            R.tokenOut  = A.tokenOut;\r
            R.moduleA   = A.module;\r
            R.moduleB   = B.module;\r
            R.amountInA = A.amountIn;\r
            R.amountInB = B.amountIn;\r
            R.totalIn   = A.amountIn + B.amountIn;\r
\r
            if (R.totalIn > 0) {\r
                uint256 calcA = (R.totalIn * bpsA) / 10_000;\r
                uint256 diff  = calcA > R.amountInA ? (calcA - R.amountInA) : (R.amountInA - calcA);\r
                require(diff <= 1, "UR: percent/payload mismatch");\r
            }\r
\r
            // Тянем всю сумму один раз\r
            IERC20(R.tokenIn).safeTransferFrom(msg.sender, address(this), R.totalIn);\r
\r
            // В модуле `swapRoute` теперь требуется `percent` (10000 bps = 100%)\r
            if (R.amountInA > 0) {\r
                _smartApprove(R.tokenIn, R.moduleA, R.amountInA);\r
                R.outA = IDexModule(R.moduleA).swapRoute(DexRoute({ data: A.route }), address(this), 10_000);\r
            }\r
\r
            if (R.amountInB > 0) {\r
                _smartApprove(R.tokenIn, R.moduleB, R.amountInB);\r
                R.outB = IDexModule(R.moduleB).swapRoute(DexRoute({ data: B.route }), address(this), 10_000);\r
            }\r
        } // <-- A и B вышли из скоупа, тяжёлые локалки освобождены\r
\r
        R.totalOut = R.outA + R.outB;\r
        require(R.totalOut >= minTotalOut, "UR: slippage");\r
\r
        _payoutWithFee(R.tokenOut, to, R.totalOut);\r
        _emitSwapSplit(R, msg.sender, to, bpsA);\r
\r
        return R.totalOut;\r
    }\r
\r
    function _emitSwapSplit(SplitResult memory r, address user, address to, uint16 bpsA) internal {\r
        emit SwapSplitExecuted(\r
            r.moduleA, r.moduleB, user, to,\r
            r.tokenIn, r.tokenOut,\r
            r.totalIn, r.amountInA, r.amountInB,\r
            r.outA, r.outB, r.totalOut, bpsA\r
        );\r
    }\r
\r
    function _decodeRouteStruct(bytes calldata payload)\r
        internal\r
        pure\r
        returns (LegDecoded memory d)\r
    {\r
        (d.module, d.index, d.quoted, d.tokenIn, d.tokenOut, d.amountIn, d.route) =\r
            abi.decode(payload, (address, uint256, uint256, address, address, uint256, bytes[]));\r
    }\r
\r
    /**\r
     * @dev Универсально парсим bytes-энкод первого (или любого) хопа:\r
     *      все модули кодируют: (address tokenIn, address tokenOut, ... , uint256 amountIn)\r
     */\r
    function _peekInOutAmt(bytes memory hop)\r
        internal\r
        pure\r
        returns (address tokenIn, address tokenOut, uint256 amountIn)\r
    {\r
        assembly {\r
            let p := add(hop, 32)             // pointer to data\r
            tokenIn  := shr(96, mload(p))     // first address\r
            tokenOut := shr(96, mload(add(p, 32))) // second address\r
            let len := mload(hop)\r
            amountIn := mload(add(p, sub(len, 32))) // last 32 bytes\r
        }\r
    }\r
\r
    /** отправка с учётом комиссии */\r
    function _payoutWithFee(address tokenOut, address to, uint256 grossOut) internal {\r
        uint256 fee = (feeRecipient != address(0) && feeBps > 0)\r
            ? (grossOut * feeBps) / 10_000\r
            : 0;\r
\r
        if (fee > 0) IERC20(tokenOut).safeTransfer(feeRecipient, fee);\r
        IERC20(tokenOut).safeTransfer(to, grossOut - fee);\r
    }\r
}\r
"
    },
    "@openzeppelin/contracts/security/ReentrancyGuard.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)

pragma solidity ^0.8.0;

/**
 * @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 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;

    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
        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");

        // 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/access/Ownable.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * The initial owner is set to the address provided by the deployer. This can
 * later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

    /**
     * @dev The caller account is not authorized to perform an operation.
     */
    error OwnableUnauthorizedAccount(address account);

    /**
     * @dev The owner is not a valid owner account. (eg. `address(0)`)
     */
    error OwnableInvalidOwner(address owner);

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.
     */
    constructor(address initialOwner) {
        if (initialOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(initialOwner);
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        if (owner() != _msgSender()) {
            revert OwnableUnauthorizedAccount(_msgSender());
        }
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby disabling any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        if (newOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}
"
    },
    "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol": {
      "content": "// 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/token/ERC20/IERC20.sol": {
      "content": "// 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/interfaces/IERC1363.sol": {
      "content": "// 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/utils/Context.sol": {
      "content": "// 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/interfaces/IERC165.sol": {
      "content": "// 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": {
      "content": "// 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/utils/introspection/IERC165.sol": {
      "content": "// 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);
}
"
    }
  },
  "settings": {
    "optimizer": {
      "enabled": true,
      "runs": 200
    },
    "outputSelection": {
      "*": {
        "*": [
          "evm.bytecode",
          "evm.deployedBytecode",
          "abi"
        ]
      }
    },
    "remappings": []
  }
}}

Tags:
ERC20, ERC165, Multisig, Swap, Upgradeable, Multi-Signature, Factory|addr:0x5a91de0ded9f92a3e5346c1106bc43bfbc4ce95e|verified:true|block:23546602|tx:0xfad9cfd1f166fe0845dce5007eaec5da05822e14bd11c5ce74e3520b6cbc3ff0|first_check:1760094171

Submitted on: 2025-10-10 13:02:52

Comments

Log in to comment.

No comments yet.