Перейти к содержимому
Проверенный контрактТочноеGPL-2.0-or-later

UniswapSpotAdapter

Адрес0xfe2e7a50eb696acee24c6664cd10fc3d9333bf71
Баланс

0 ETH

 

Транзакций

1

 

Компилятор

solc 0.8.20

 

Тот же код

Только этот контракт

 

Подробности

Компилятор
solc 0.8.20+commit.a1b79de6
Язык
solidity
Оптимизация
Да, 200 прогонов
Версия EVM
shanghai
Лицензия
GPL-2.0-or-later
Совпадение
Точноекод создания: да, код в сети: да
Проверен на Sourcify
Создан в блоке
26 493 947
Транзакция создания
0xf81491331f…b8a78c1602

src/UniswapSpotAdapter.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.20;

import {ISpotToken, ISpotV3Pool, IUniswapV3SwapCallback} from "./uniswap/IUniswapV3.sol";
import {TickMath} from "./uniswap/vendor/TickMath.sol";

/// @notice Executes ENA/USDT swaps for one Safe through the fixed Route ENA/WETH then WETH/USDT.
/// @dev The Safe retains custody. It calls swaps and grants this adapter ERC-20 allowances for callback settlement.
/// WETH exists only inside a swap: the first Hop pays it to this adapter and the second Hop spends all of it.
contract UniswapSpotAdapter is IUniswapV3SwapCallback {
    uint24 public constant ENA_WETH_FEE = 3000;
    uint24 public constant WETH_USDT_FEE = 100;

    /// @dev The second Hop runs inside the first Hop's callback, so the second Hop is paid before the first.
    enum Stage {
        Idle,
        AwaitingFirstHopCallback,
        AwaitingSecondHopCallback,
        SecondHopPaid,
        FirstHopPaid
    }

    struct Balances {
        uint256 safeEna;
        uint256 safeWeth;
        uint256 safeUsdt;
        uint256 adapterEna;
        uint256 adapterWeth;
        uint256 adapterUsdt;
    }

    address public immutable safe;
    address public immutable ena;
    address public immutable weth;
    address public immutable usdt;
    ISpotV3Pool public immutable enaWethPool;
    ISpotV3Pool public immutable wethUsdtPool;
    bool private immutable _enaIsToken0;
    bool private immutable _wethIsToken0;

    uint256 public maxSwapSize;
    /// @notice The USDT ceiling, in USDT base units, that no single buy may spend.
    uint256 public maxUsdtInPerSwap;
    mapping(bytes32 => bool) public usedIntents;

    Stage private _stage;
    bool private _buying;
    uint256 private _enaAmount;
    uint256 private _wethAmount;
    uint256 private _usdtAmount;

    error InvalidDeployment();
    error OnlySafe();
    error ReentrantCall();
    error InvalidAmount();
    error ExceedsMaxSwapSize();
    error ExceedsMaxUsdtInPerSwap();
    error InvalidDeadline();
    error InvalidIntent();
    error InvalidOutputBounds();
    error OutputOutOfBounds();
    error InvalidInputBound();
    error InputOutOfBounds();
    error InvalidSwapCallback();
    error UnexpectedBalanceChange();
    error TokenCallFailed();

    event SwapExecuted(
        bytes32 indexed intentId, address indexed tokenIn, address indexed tokenOut, uint256 amountIn, uint256 amountOut
    );

    event MaxSwapSizeUpdated(uint256 previous, uint256 current);

    event MaxUsdtInPerSwapUpdated(uint256 previous, uint256 current);

    event TokensSwept(address indexed token, uint256 amount);

    modifier onlySafe() {
        if (msg.sender != safe) revert OnlySafe();
        _;
    }

    constructor(
        address safe_,
        address ena_,
        address weth_,
        address usdt_,
        address enaWethPool_,
        address wethUsdtPool_,
        uint256 maxSwapSize_,
        uint256 maxUsdtInPerSwap_
    ) {
        if (
            safe_.code.length == 0 || ena_.code.length == 0 || weth_.code.length == 0 || usdt_.code.length == 0
                || ena_ == weth_ || weth_ == usdt_ || ena_ == usdt_ || maxSwapSize_ == 0 || maxUsdtInPerSwap_ == 0
        ) revert InvalidDeployment();
        _checkPool(enaWethPool_, ena_, weth_, ENA_WETH_FEE);
        _checkPool(wethUsdtPool_, weth_, usdt_, WETH_USDT_FEE);
        safe = safe_;
        ena = ena_;
        weth = weth_;
        usdt = usdt_;
        enaWethPool = ISpotV3Pool(enaWethPool_);
        wethUsdtPool = ISpotV3Pool(wethUsdtPool_);
        _enaIsToken0 = ena_ < weth_;
        _wethIsToken0 = weth_ < usdt_;
        maxSwapSize = maxSwapSize_;
        maxUsdtInPerSwap = maxUsdtInPerSwap_;
    }

    function _checkPool(address pool, address tokenA, address tokenB, uint24 fee) private view {
        (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
        if (
            pool.code.length == 0 || ISpotV3Pool(pool).token0() != token0 || ISpotV3Pool(pool).token1() != token1
                || ISpotV3Pool(pool).fee() != fee
        ) revert InvalidDeployment();
    }

    /// @notice Sets the ENA ceiling no single swap may exceed. The Safe may grant this selector to the Operator.
    function setMaxSwapSize(uint256 newMaxSwapSize) external onlySafe {
        if (newMaxSwapSize == 0) revert InvalidAmount();
        emit MaxSwapSizeUpdated(maxSwapSize, newMaxSwapSize);
        maxSwapSize = newMaxSwapSize;
    }

    /// @notice Sets the USDT ceiling no single buy may spend. Meant for Safe owners only: the prepare script never
    /// grants this selector to the Operator.
    function setMaxUsdtInPerSwap(uint256 newMaxUsdtInPerSwap) external onlySafe {
        if (newMaxUsdtInPerSwap == 0) revert InvalidAmount();
        emit MaxUsdtInPerSwapUpdated(maxUsdtInPerSwap, newMaxUsdtInPerSwap);
        maxUsdtInPerSwap = newMaxUsdtInPerSwap;
    }

    /// @notice Sends this adapter's whole balance of `token` to the Safe.
    function sweep(address token) external onlySafe {
        if (_stage != Stage.Idle) revert ReentrantCall();
        uint256 amount = ISpotToken(token).balanceOf(address(this));
        if (amount == 0) revert InvalidAmount();
        _callToken(token, abi.encodeCall(ISpotToken.transfer, (safe, amount)));
        emit TokensSwept(token, amount);
    }

    /// @notice Sells an exact ENA amount for USDT through both Hops.
    function sellExactInput(bytes32 intentId, uint256 enaIn, uint256 minUsdtOut, uint256 maxUsdtOut, uint256 deadline)
        external
        onlySafe
        returns (uint256 usdtOut)
    {
        if (_stage != Stage.Idle) revert ReentrantCall();
        if (intentId == bytes32(0) || usedIntents[intentId]) revert InvalidIntent();
        if (deadline < block.timestamp) revert InvalidDeadline();
        if (enaIn == 0 || enaIn > type(uint128).max) revert InvalidAmount();
        if (enaIn > maxSwapSize) revert ExceedsMaxSwapSize();
        if (minUsdtOut == 0 || maxUsdtOut < minUsdtOut) revert InvalidOutputBounds();
        Balances memory before = _balances();
        if (before.safeEna < enaIn) revert InvalidAmount();

        usedIntents[intentId] = true;
        usdtOut = _sell(enaIn);
        _checkSellBalances(before, enaIn, usdtOut);
        if (usdtOut < minUsdtOut || usdtOut > maxUsdtOut) revert OutputOutOfBounds();
        emit SwapExecuted(intentId, ena, usdt, enaIn, usdtOut);
    }

    /// @notice Buys an exact ENA amount with USDT through both Hops; `maxUsdtIn` may not exceed `maxUsdtInPerSwap`.
    function buyExactOutput(bytes32 intentId, uint256 enaOut, uint256 maxUsdtIn, uint256 deadline)
        external
        onlySafe
        returns (uint256 usdtIn)
    {
        if (_stage != Stage.Idle) revert ReentrantCall();
        if (intentId == bytes32(0) || usedIntents[intentId]) revert InvalidIntent();
        if (deadline < block.timestamp) revert InvalidDeadline();
        if (enaOut == 0 || enaOut > type(uint128).max) revert InvalidAmount();
        if (enaOut > maxSwapSize) revert ExceedsMaxSwapSize();
        if (maxUsdtIn == 0) revert InvalidInputBound();
        if (maxUsdtIn > maxUsdtInPerSwap) revert ExceedsMaxUsdtInPerSwap();
        Balances memory before = _balances();

        usedIntents[intentId] = true;
        usdtIn = _buy(enaOut);
        _checkBuyBalances(before, enaOut, usdtIn);
        if (usdtIn > maxUsdtIn) revert InputOutOfBounds();
        emit SwapExecuted(intentId, usdt, ena, usdtIn, enaOut);
    }

    function _buy(uint256 enaOut) private returns (uint256 usdtIn) {
        _stage = Stage.AwaitingFirstHopCallback;
        _buying = true;
        _enaAmount = enaOut;
        (int256 amount0, int256 amount1) =
            enaWethPool.swap(safe, !_enaIsToken0, -int256(enaOut), _priceLimit(!_enaIsToken0), bytes(""));
        (int256 enaDelta, int256 wethDelta) = _enaIsToken0 ? (amount0, amount1) : (amount1, amount0);
        if (_stage != Stage.FirstHopPaid || enaDelta != -int256(enaOut) || wethDelta != int256(_wethAmount)) {
            revert UnexpectedBalanceChange();
        }
        usdtIn = _usdtAmount;
        _stage = Stage.Idle;
        delete _buying;
        delete _enaAmount;
        delete _wethAmount;
        delete _usdtAmount;
    }

    /// @dev The Safe gains exactly the ENA output and loses exactly the USDT input. WETH is net zero for the Safe and
    /// this adapter, and this adapter retains nothing.
    function _checkBuyBalances(Balances memory before, uint256 enaOut, uint256 usdtIn) private view {
        Balances memory afterSwap = _balances();
        if (
            afterSwap.safeEna < before.safeEna || afterSwap.safeEna - before.safeEna != enaOut
                || afterSwap.safeUsdt > before.safeUsdt || before.safeUsdt - afterSwap.safeUsdt != usdtIn
                || afterSwap.safeWeth != before.safeWeth || afterSwap.adapterEna != before.adapterEna
                || afterSwap.adapterWeth != before.adapterWeth || afterSwap.adapterUsdt != before.adapterUsdt
        ) revert UnexpectedBalanceChange();
    }

    /// @dev The first pool has paid ENA to the Safe and wants WETH. The second Hop pays exactly that WETH to the
    /// first pool, then the second pool's callback pulls its USDT from the Safe.
    function _settleBuyFirstHop(int256 amount0Delta, int256 amount1Delta) private {
        (int256 enaDelta, int256 wethDelta) = _enaIsToken0 ? (amount0Delta, amount1Delta) : (amount1Delta, amount0Delta);
        if (enaDelta != -int256(_enaAmount) || wethDelta <= 0) revert InvalidSwapCallback();
        uint256 wethIn = uint256(wethDelta);
        _wethAmount = wethIn;
        _stage = Stage.AwaitingSecondHopCallback;
        (int256 amount0, int256 amount1) = wethUsdtPool.swap(
            address(enaWethPool), !_wethIsToken0, -int256(wethIn), _priceLimit(!_wethIsToken0), bytes("")
        );
        (int256 wethPaid, int256 usdtDelta) = _wethIsToken0 ? (amount0, amount1) : (amount1, amount0);
        if (_stage != Stage.SecondHopPaid || wethPaid != -int256(wethIn) || usdtDelta != int256(_usdtAmount)) {
            revert UnexpectedBalanceChange();
        }
        _stage = Stage.FirstHopPaid;
    }

    /// @dev Pulls the second pool's USDT debt from the Safe.
    function _settleBuySecondHop(int256 amount0Delta, int256 amount1Delta) private {
        (int256 wethDelta, int256 usdtDelta) =
            _wethIsToken0 ? (amount0Delta, amount1Delta) : (amount1Delta, amount0Delta);
        if (wethDelta != -int256(_wethAmount) || usdtDelta <= 0) revert InvalidSwapCallback();
        uint256 usdtIn = uint256(usdtDelta);
        _usdtAmount = usdtIn;
        _stage = Stage.SecondHopPaid;
        _callToken(usdt, abi.encodeCall(ISpotToken.transferFrom, (safe, address(wethUsdtPool), usdtIn)));
    }

    function _sell(uint256 enaIn) private returns (uint256 usdtOut) {
        _stage = Stage.AwaitingFirstHopCallback;
        _enaAmount = enaIn;
        (int256 amount0, int256 amount1) =
            enaWethPool.swap(address(this), _enaIsToken0, int256(enaIn), _priceLimit(_enaIsToken0), bytes(""));
        (int256 enaDelta, int256 wethDelta) = _enaIsToken0 ? (amount0, amount1) : (amount1, amount0);
        if (_stage != Stage.FirstHopPaid || enaDelta != int256(enaIn) || wethDelta != -int256(_wethAmount)) {
            revert UnexpectedBalanceChange();
        }
        usdtOut = _usdtAmount;
        _stage = Stage.Idle;
        delete _enaAmount;
        delete _wethAmount;
        delete _usdtAmount;
    }

    function _balances() private view returns (Balances memory b) {
        b.safeEna = ISpotToken(ena).balanceOf(safe);
        b.safeWeth = ISpotToken(weth).balanceOf(safe);
        b.safeUsdt = ISpotToken(usdt).balanceOf(safe);
        b.adapterEna = ISpotToken(ena).balanceOf(address(this));
        b.adapterWeth = ISpotToken(weth).balanceOf(address(this));
        b.adapterUsdt = ISpotToken(usdt).balanceOf(address(this));
    }

    /// @dev The Safe loses exactly the ENA input and gains exactly the pool-reported USDT. WETH is net zero for the
    /// Safe and this adapter, and this adapter retains nothing. Balances are compared before and after rather than
    /// against zero, so tokens donated to this adapter can neither block swaps nor pay a Hop.
    function _checkSellBalances(Balances memory before, uint256 enaIn, uint256 usdtOut) private view {
        Balances memory afterSwap = _balances();
        if (
            afterSwap.safeEna > before.safeEna || before.safeEna - afterSwap.safeEna != enaIn
                || afterSwap.safeUsdt < before.safeUsdt || afterSwap.safeUsdt - before.safeUsdt != usdtOut
                || afterSwap.safeWeth != before.safeWeth || afterSwap.adapterEna != before.adapterEna
                || afterSwap.adapterWeth != before.adapterWeth || afterSwap.adapterUsdt != before.adapterUsdt
        ) revert UnexpectedBalanceChange();
    }

    /// @dev Settles only the active Hop, and only from that Hop's pool.
    function uniswapV3SwapCallback(int256 amount0Delta, int256 amount1Delta, bytes calldata data) external override {
        Stage stage = _stage;
        if (data.length != 0) revert InvalidSwapCallback();
        if (stage == Stage.AwaitingFirstHopCallback && msg.sender == address(enaWethPool)) {
            if (_buying) _settleBuyFirstHop(amount0Delta, amount1Delta);
            else _settleFirstHop(amount0Delta, amount1Delta);
        } else if (stage == Stage.AwaitingSecondHopCallback && msg.sender == address(wethUsdtPool)) {
            if (_buying) _settleBuySecondHop(amount0Delta, amount1Delta);
            else _settleSecondHop(amount0Delta, amount1Delta);
        } else {
            revert InvalidSwapCallback();
        }
    }

    /// @dev The first pool has paid WETH to this adapter. Swaps all of it to the Safe, then pays ENA from the Safe.
    function _settleFirstHop(int256 amount0Delta, int256 amount1Delta) private {
        (int256 enaDelta, int256 wethDelta) = _enaIsToken0 ? (amount0Delta, amount1Delta) : (amount1Delta, amount0Delta);
        uint256 enaIn = _enaAmount;
        if (enaDelta != int256(enaIn) || wethDelta >= 0 || wethDelta == type(int256).min) {
            revert InvalidSwapCallback();
        }
        uint256 wethOut = uint256(-wethDelta);
        _wethAmount = wethOut;
        _stage = Stage.AwaitingSecondHopCallback;
        (int256 amount0, int256 amount1) =
            wethUsdtPool.swap(safe, _wethIsToken0, int256(wethOut), _priceLimit(_wethIsToken0), bytes(""));
        (int256 wethIn, int256 usdtDelta) = _wethIsToken0 ? (amount0, amount1) : (amount1, amount0);
        if (_stage != Stage.SecondHopPaid || wethIn != int256(wethOut) || usdtDelta != -int256(_usdtAmount)) {
            revert UnexpectedBalanceChange();
        }
        _stage = Stage.FirstHopPaid;
        _callToken(ena, abi.encodeCall(ISpotToken.transferFrom, (safe, address(enaWethPool), enaIn)));
    }

    /// @dev Pays the second pool exactly the WETH the first Hop produced.
    function _settleSecondHop(int256 amount0Delta, int256 amount1Delta) private {
        (int256 wethDelta, int256 usdtDelta) =
            _wethIsToken0 ? (amount0Delta, amount1Delta) : (amount1Delta, amount0Delta);
        uint256 wethOut = _wethAmount;
        if (wethDelta != int256(wethOut) || usdtDelta >= 0 || usdtDelta == type(int256).min) {
            revert InvalidSwapCallback();
        }
        _usdtAmount = uint256(-usdtDelta);
        _stage = Stage.SecondHopPaid;
        _callToken(weth, abi.encodeCall(ISpotToken.transfer, (address(wethUsdtPool), wethOut)));
    }

    function _priceLimit(bool zeroForOne) private pure returns (uint160) {
        return zeroForOne ? TickMath.MIN_SQRT_RATIO + 1 : TickMath.MAX_SQRT_RATIO - 1;
    }

    function _callToken(address token, bytes memory data) private {
        (bool ok, bytes memory result) = token.call(data);
        if (!ok || (result.length != 0 && (result.length != 32 || !abi.decode(result, (bool))))) {
            revert TokenCallFailed();
        }
    }
}

src/uniswap/IUniswapV3.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.20;

interface ISpotToken {
    function balanceOf(address account) external view returns (uint256);
    function transfer(address to, uint256 amount) external returns (bool);
    function transferFrom(address from, address to, uint256 amount) external returns (bool);
}

interface ISpotV3Pool {
    function token0() external view returns (address);
    function token1() external view returns (address);
    function fee() external view returns (uint24);
    function swap(
        address recipient,
        bool zeroForOne,
        int256 amountSpecified,
        uint160 sqrtPriceLimitX96,
        bytes calldata data
    ) external returns (int256 amount0, int256 amount1);
}

/// @dev Canonical v3 callback ABI; only the configured pool may settle an active adapter swap.
interface IUniswapV3SwapCallback {
    function uniswapV3SwapCallback(int256 amount0Delta, int256 amount1Delta, bytes calldata data) external;
}

src/uniswap/vendor/TickMath.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.20;

/// @dev Only the v3 protocol price bounds are needed for direct swaps. See PROVENANCE.md.
library TickMath {
    uint160 internal constant MIN_SQRT_RATIO = 4295128739;
    uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;
}
Настройки компилятораПоказать
{
  "viaIR": false,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "shanghai",
  "remappings": [
    "lib/openzeppelin-contracts/:forge-std/=lib/openzeppelin-contracts/lib/forge-std/src/",
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
    "forge-std/=lib/forge-std/src/",
    "halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/"
  ]
}

Исходный код и метаданные: Sourcify.

Исходный код принадлежит авторам контракта.