Skip to content
Verified contractExactMIT

UniversalEthereumCurveExecutor

Address0x434f6b64a4059f3b35181fe6edf912bb7a5cd0aa
Balance

0 ETH

 

Transactions

2

 

Compiler

solc 0.8.26

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.26+commit.8a97fa7a
Language
solidity
Optimization
Yes, 200 runs
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,493,779
Creation transaction
0xd4ac58986f…3dad7dfbd7

contracts/UniversalEthereumCurveExecutor.sol

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

import {FullMath} from "@uniswap/v4-core/src/libraries/FullMath.sol";

interface IERC20EthereumCurveExecutor {
    function balanceOf(address account) external view returns (uint256);
    function decimals() external view returns (uint8);
    function transfer(address to, uint256 amount) external returns (bool);
    function transferFrom(address from, address to, uint256 amount) external returns (bool);
    function approve(address spender, uint256 amount) external returns (bool);
}

/// @notice Exact-input executor for Curve pools on Ethereum mainnet.
/// @dev The hook owner chooses the adapter and coin indexes during pool registration.
///      Output is always measured from token balances; Curve return values are not trusted.
contract UniversalEthereumCurveExecutor {
    uint8 public constant ADAPTER_EXCHANGE_INT128 = 1;
    uint8 public constant ADAPTER_EXCHANGE_UINT256 = 2;
    uint8 public constant ADAPTER_UNDERLYING_INT128 = 3;
    uint8 public constant ADAPTER_UNDERLYING_UINT256 = 4;
    uint8 public constant ADAPTER_EXCHANGE_UINT256_USE_ETH = 5;
    uint8 public constant ADAPTER_EXCHANGE_UINT256_RECEIVER = 6;
    uint8 public constant ADAPTER_EXCHANGE_RECEIVED_INT128 = 7;
    uint8 public constant ADAPTER_EXCHANGE_INT128_RECEIVER = 8;
    uint8 public constant ADAPTER_UNDERLYING_INT128_RECEIVER = 9;

    uint256 private constant Q192 = 1 << 192;

    address public immutable owner;
    address public hook;
    uint256 private _locked = 1;

    event HookChanged(address indexed previousHook, address indexed newHook);
    event SwapExecuted(
        address indexed pool,
        uint8 indexed adapterType,
        address indexed tokenIn,
        address tokenOut,
        uint8 indexIn,
        uint8 indexOut,
        uint256 amountIn,
        uint256 amountOut
    );
    event TokenSwept(address indexed token, address indexed recipient, uint256 amount);

    error WrongChain();
    error NotOwner();
    error OnlyHook();
    error ZeroAddress();
    error Reentrancy();
    error InvalidAdapter();
    error InvalidPool();
    error InvalidToken();
    error InvalidIndexes();
    error QuoteFailed();
    error SwapFailed();
    error TransferFailed();
    error ApprovalFailed();
    error FeeOnTransferUnsupported();
    error OutputMismatch();

    modifier onlyOwner() {
        if (msg.sender != owner) revert NotOwner();
        _;
    }

    modifier onlyHook() {
        if (msg.sender != hook) revert OnlyHook();
        _;
    }

    modifier nonReentrant() {
        if (_locked != 1) revert Reentrancy();
        _locked = 2;
        _;
        _locked = 1;
    }

    constructor() {
        if (block.chainid != 1) revert WrongChain();
        owner = msg.sender;
    }

    function setHook(address newHook) external onlyOwner {
        if (newHook == address(0)) revert ZeroAddress();
        address old = hook;
        hook = newHook;
        emit HookChanged(old, newHook);
    }

    function validatePool(
        address pool,
        uint8 adapterType,
        uint8 index0,
        uint8 index1,
        address token0,
        address token1
    ) external view returns (bool) {
        if (pool.code.length == 0 || token0 == address(0) || token1 == address(0) || token0 == token1 || index0 == index1) {
            return false;
        }
        if (!_validAdapter(adapterType)) return false;
        bool underlying = adapterType == ADAPTER_UNDERLYING_INT128
            || adapterType == ADAPTER_UNDERLYING_UINT256
            || adapterType == ADAPTER_UNDERLYING_INT128_RECEIVER;
        (bool ok0, address coin0) = _readCoin(pool, underlying, index0);
        (bool ok1, address coin1) = _readCoin(pool, underlying, index1);
        if (!ok0 || !ok1 || coin0 != token0 || coin1 != token1) return false;

        uint256 probe = _probeAmount(token0);
        (bool quoted, uint256 amountOut) = _quote(pool, adapterType, index0, index1, probe);
        return quoted && amountOut != 0;
    }

    function quoteExactInput(
        address pool,
        uint8 adapterType,
        uint8 indexIn,
        uint8 indexOut,
        uint256 amountIn
    ) external view returns (uint256 amountOut) {
        (bool ok, uint256 quoted) = _quote(pool, adapterType, indexIn, indexOut, amountIn);
        if (!ok || quoted == 0) revert QuoteFailed();
        return quoted;
    }

    function backendSqrtPriceX96(
        address pool,
        uint8 adapterType,
        uint8 index0,
        uint8 index1,
        address token0,
        address token1
    ) external view returns (uint160 sqrtPriceX96) {
        uint256 amountIn = _probeAmount(token0);
        (bool ok, uint256 amountOut) = _quote(pool, adapterType, index0, index1, amountIn);
        if (!ok || amountOut == 0) revert QuoteFailed();
        uint256 ratioX192 = FullMath.mulDiv(amountOut, Q192, amountIn);
        uint256 root = _sqrt(ratioX192);
        if (root == 0 || root > type(uint160).max) revert QuoteFailed();
        // Reading decimals verifies both registered tokens are ERC-20 contracts.
        IERC20EthereumCurveExecutor(token1).decimals();
        sqrtPriceX96 = uint160(root);
    }

    function swapExactInput(
        address pool,
        uint8 adapterType,
        uint8 indexIn,
        uint8 indexOut,
        address tokenIn,
        address tokenOut,
        uint256 amountIn
    ) external onlyHook nonReentrant returns (uint256 amountOut) {
        if (amountIn == 0 || tokenIn == tokenOut || pool.code.length == 0 || !_validAdapter(adapterType)) revert InvalidPool();

        uint256 inputBefore = _balanceOf(tokenIn, address(this));
        _safeTransferFrom(tokenIn, msg.sender, address(this), amountIn);
        if (_balanceOf(tokenIn, address(this)) - inputBefore != amountIn) revert FeeOnTransferUnsupported();

        uint256 outputBefore = _balanceOf(tokenOut, address(this));
        if (adapterType == ADAPTER_EXCHANGE_RECEIVED_INT128) {
            // StableSwap-NG exchange_received reads tokens already transferred to the pool.
            _safeTransfer(tokenIn, pool, amountIn);
        } else {
            _forceApprove(tokenIn, pool, amountIn);
        }
        _callExchange(pool, adapterType, indexIn, indexOut, amountIn);
        if (adapterType != ADAPTER_EXCHANGE_RECEIVED_INT128) _forceApprove(tokenIn, pool, 0);

        amountOut = _balanceOf(tokenOut, address(this)) - outputBefore;
        if (amountOut == 0) revert OutputMismatch();
        _safeTransfer(tokenOut, msg.sender, amountOut);
        emit SwapExecuted(pool, adapterType, tokenIn, tokenOut, indexIn, indexOut, amountIn, amountOut);
    }

    function sweepToken(address token, address recipient, uint256 amount) external onlyOwner nonReentrant {
        if (recipient == address(0)) revert ZeroAddress();
        _safeTransfer(token, recipient, amount);
        emit TokenSwept(token, recipient, amount);
    }

    function _callExchange(address pool, uint8 adapterType, uint8 i, uint8 j, uint256 dx) internal {
        bytes memory data;
        if (adapterType == ADAPTER_EXCHANGE_INT128) {
            data = abi.encodeWithSignature("exchange(int128,int128,uint256,uint256)", int128(uint128(i)), int128(uint128(j)), dx, 1);
        } else if (adapterType == ADAPTER_EXCHANGE_UINT256) {
            data = abi.encodeWithSignature("exchange(uint256,uint256,uint256,uint256)", uint256(i), uint256(j), dx, 1);
        } else if (adapterType == ADAPTER_UNDERLYING_INT128) {
            data = abi.encodeWithSignature("exchange_underlying(int128,int128,uint256,uint256)", int128(uint128(i)), int128(uint128(j)), dx, 1);
        } else if (adapterType == ADAPTER_UNDERLYING_UINT256) {
            data = abi.encodeWithSignature("exchange_underlying(uint256,uint256,uint256,uint256)", uint256(i), uint256(j), dx, 1);
        } else if (adapterType == ADAPTER_EXCHANGE_UINT256_USE_ETH) {
            data = abi.encodeWithSignature("exchange(uint256,uint256,uint256,uint256,bool)", uint256(i), uint256(j), dx, 1, false);
        } else if (adapterType == ADAPTER_EXCHANGE_UINT256_RECEIVER) {
            data = abi.encodeWithSignature("exchange(uint256,uint256,uint256,uint256,address)", uint256(i), uint256(j), dx, 1, address(this));
        } else if (adapterType == ADAPTER_EXCHANGE_RECEIVED_INT128) {
            data = abi.encodeWithSignature("exchange_received(int128,int128,uint256,uint256,address)", int128(uint128(i)), int128(uint128(j)), dx, 1, address(this));
        } else if (adapterType == ADAPTER_EXCHANGE_INT128_RECEIVER) {
            data = abi.encodeWithSignature("exchange(int128,int128,uint256,uint256,address)", int128(uint128(i)), int128(uint128(j)), dx, 1, address(this));
        } else if (adapterType == ADAPTER_UNDERLYING_INT128_RECEIVER) {
            data = abi.encodeWithSignature("exchange_underlying(int128,int128,uint256,uint256,address)", int128(uint128(i)), int128(uint128(j)), dx, 1, address(this));
        } else {
            revert InvalidAdapter();
        }
        (bool ok, bytes memory reason) = pool.call(data);
        if (!ok) _revertWith(reason);
    }

    function _quote(address pool, uint8 adapterType, uint8 i, uint8 j, uint256 dx)
        internal view returns (bool ok, uint256 amountOut)
    {
        if (dx == 0 || !_validAdapter(adapterType)) return (false, 0);
        bytes memory data;
        if (
            adapterType == ADAPTER_EXCHANGE_INT128
                || adapterType == ADAPTER_UNDERLYING_INT128
                || adapterType == ADAPTER_EXCHANGE_RECEIVED_INT128
                || adapterType == ADAPTER_EXCHANGE_INT128_RECEIVER
                || adapterType == ADAPTER_UNDERLYING_INT128_RECEIVER
        ) {
            bool underlying = adapterType == ADAPTER_UNDERLYING_INT128
                || adapterType == ADAPTER_UNDERLYING_INT128_RECEIVER;
            string memory signature = underlying
                ? "get_dy_underlying(int128,int128,uint256)"
                : "get_dy(int128,int128,uint256)";
            data = abi.encodeWithSignature(signature, int128(uint128(i)), int128(uint128(j)), dx);
        } else {
            string memory signature = adapterType == ADAPTER_UNDERLYING_UINT256
                ? "get_dy_underlying(uint256,uint256,uint256)"
                : "get_dy(uint256,uint256,uint256)";
            data = abi.encodeWithSignature(signature, uint256(i), uint256(j), dx);
        }
        bytes memory result;
        (ok, result) = pool.staticcall(data);
        if (!ok || result.length < 32) return (false, 0);
        amountOut = abi.decode(result, (uint256));
    }

    function _readCoin(address pool, bool underlying, uint8 index) internal view returns (bool ok, address coin) {
        string memory fn = underlying ? "underlying_coins(uint256)" : "coins(uint256)";
        bytes memory result;
        (ok, result) = pool.staticcall(abi.encodeWithSignature(fn, uint256(index)));
        if (!ok || result.length < 32) {
            fn = underlying ? "underlying_coins(int128)" : "coins(int128)";
            (ok, result) = pool.staticcall(abi.encodeWithSignature(fn, int128(uint128(index))));
        }
        if (!ok || result.length < 32) return (false, address(0));
        coin = abi.decode(result, (address));
    }

    function _probeAmount(address token) internal view returns (uint256) {
        uint8 decimals = IERC20EthereumCurveExecutor(token).decimals();
        if (decimals > 36) revert InvalidToken();
        return 10 ** uint256(decimals);
    }

    function _validAdapter(uint8 adapterType) internal pure returns (bool) {
        return adapterType >= ADAPTER_EXCHANGE_INT128 && adapterType <= ADAPTER_UNDERLYING_INT128_RECEIVER;
    }

    function _sqrt(uint256 x) internal pure returns (uint256 z) {
        if (x == 0) return 0;
        z = 1 << ((256 - _clz(x)) >> 1);
        for (uint256 i; i < 7; ++i) z = (z + x / z) >> 1;
        uint256 z1 = x / z;
        if (z1 < z) z = z1;
    }

    function _clz(uint256 x) internal pure returns (uint256 n) {
        if (x >> 128 == 0) { n += 128; x <<= 128; }
        if (x >> 192 == 0) { n += 64; x <<= 64; }
        if (x >> 224 == 0) { n += 32; x <<= 32; }
        if (x >> 240 == 0) { n += 16; x <<= 16; }
        if (x >> 248 == 0) { n += 8; x <<= 8; }
        if (x >> 252 == 0) { n += 4; x <<= 4; }
        if (x >> 254 == 0) { n += 2; x <<= 2; }
        if (x >> 255 == 0) n += 1;
    }

    function _balanceOf(address token, address account) internal view returns (uint256 balance) {
        (bool ok, bytes memory data) = token.staticcall(
            abi.encodeWithSelector(IERC20EthereumCurveExecutor.balanceOf.selector, account)
        );
        if (!ok || data.length < 32) revert InvalidToken();
        balance = abi.decode(data, (uint256));
    }

    function _safeTransfer(address token, address to, uint256 amount) internal {
        (bool ok, bytes memory data) = token.call(
            abi.encodeWithSelector(IERC20EthereumCurveExecutor.transfer.selector, to, amount)
        );
        if (!ok || (data.length != 0 && !abi.decode(data, (bool)))) revert TransferFailed();
    }

    function _safeTransferFrom(address token, address from, address to, uint256 amount) internal {
        (bool ok, bytes memory data) = token.call(
            abi.encodeWithSelector(IERC20EthereumCurveExecutor.transferFrom.selector, from, to, amount)
        );
        if (!ok || (data.length != 0 && !abi.decode(data, (bool)))) revert TransferFailed();
    }

    function _forceApprove(address token, address spender, uint256 amount) internal {
        if (!_callApprove(token, spender, amount)) {
            if (!_callApprove(token, spender, 0)) revert ApprovalFailed();
            if (!_callApprove(token, spender, amount)) revert ApprovalFailed();
        }
    }

    function _callApprove(address token, address spender, uint256 amount) internal returns (bool) {
        (bool ok, bytes memory data) = token.call(
            abi.encodeWithSelector(IERC20EthereumCurveExecutor.approve.selector, spender, amount)
        );
        return ok && (data.length == 0 || (data.length >= 32 && abi.decode(data, (bool))));
    }

    function _revertWith(bytes memory reason) internal pure {
        if (reason.length == 0) revert SwapFailed();
        assembly ("memory-safe") { revert(add(reason, 32), mload(reason)) }
    }
}




@uniswap/v4-core/src/libraries/FullMath.sol

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

/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
    /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
    /// @param a The multiplicand
    /// @param b The multiplier
    /// @param denominator The divisor
    /// @return result The 256-bit result
    /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
    function mulDiv(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            // 512-bit multiply [prod1 prod0] = a * b
            // Compute the product mod 2**256 and mod 2**256 - 1
            // then use the Chinese Remainder Theorem to reconstruct
            // the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2**256 + prod0
            uint256 prod0 = a * b; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly ("memory-safe") {
                let mm := mulmod(a, b, not(0))
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

            // Make sure the result is less than 2**256.
            // Also prevents denominator == 0
            require(denominator > prod1);

            // Handle non-overflow cases, 256 by 256 division
            if (prod1 == 0) {
                assembly ("memory-safe") {
                    result := div(prod0, denominator)
                }
                return result;
            }

            ///////////////////////////////////////////////
            // 512 by 256 division.
            ///////////////////////////////////////////////

            // Make division exact by subtracting the remainder from [prod1 prod0]
            // Compute remainder using mulmod
            uint256 remainder;
            assembly ("memory-safe") {
                remainder := mulmod(a, b, denominator)
            }
            // Subtract 256 bit number from 512 bit number
            assembly ("memory-safe") {
                prod1 := sub(prod1, gt(remainder, prod0))
                prod0 := sub(prod0, remainder)
            }

            // Factor powers of two out of denominator
            // Compute largest power of two divisor of denominator.
            // Always >= 1.
            uint256 twos = (0 - denominator) & denominator;
            // Divide denominator by power of two
            assembly ("memory-safe") {
                denominator := div(denominator, twos)
            }

            // Divide [prod1 prod0] by the factors of two
            assembly ("memory-safe") {
                prod0 := div(prod0, twos)
            }
            // Shift in bits from prod1 into prod0. For this we need
            // to flip `twos` such that it is 2**256 / twos.
            // If twos is zero, then it becomes one
            assembly ("memory-safe") {
                twos := add(div(sub(0, twos), twos), 1)
            }
            prod0 |= prod1 * twos;

            // Invert denominator mod 2**256
            // Now that denominator is an odd number, it has an inverse
            // modulo 2**256 such that denominator * inv = 1 mod 2**256.
            // Compute the inverse by starting with a seed that is correct
            // correct for four bits. That is, denominator * inv = 1 mod 2**4
            uint256 inv = (3 * denominator) ^ 2;
            // Now use Newton-Raphson iteration to improve the precision.
            // Thanks to Hensel's lifting lemma, this also works in modular
            // arithmetic, doubling the correct bits in each step.
            inv *= 2 - denominator * inv; // inverse mod 2**8
            inv *= 2 - denominator * inv; // inverse mod 2**16
            inv *= 2 - denominator * inv; // inverse mod 2**32
            inv *= 2 - denominator * inv; // inverse mod 2**64
            inv *= 2 - denominator * inv; // inverse mod 2**128
            inv *= 2 - denominator * inv; // inverse mod 2**256

            // Because the division is now exact we can divide by multiplying
            // with the modular inverse of denominator. This will give us the
            // correct result modulo 2**256. Since the preconditions guarantee
            // that the outcome is less than 2**256, this is the final result.
            // We don't need to compute the high bits of the result and prod1
            // is no longer required.
            result = prod0 * inv;
            return result;
        }
    }

    /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
    /// @param a The multiplicand
    /// @param b The multiplier
    /// @param denominator The divisor
    /// @return result The 256-bit result
    function mulDivRoundingUp(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            result = mulDiv(a, b, denominator);
            if (mulmod(a, b, denominator) != 0) {
                require(++result > 0);
            }
        }
    }
}
Compiler settingsShow
{
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "remappings": []
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.