Skip to content
Verified contractExactUNLICENSED

CurveStableSwapHandlerV3

Address0xc740e2ab60a18f5d2d2db0e8658cb2f89cfa46b8
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.20

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.20+commit.a1b79de6
Language
solidity
Optimization
Yes, 200 runs
EVM version
paris
Via IR
yes
License
UNLICENSED
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,266,041
Creation transaction
0xb35d5ca2a0…add2029102

contracts/router/modules/CurveStableSwapHandlerV3.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.20;

import "@uniswap/lib/contracts/libraries/TransferHelper.sol";
import "../interfaces/ISwapHandler.sol";
import "../../shared/interfaces/IERC20.sol";
import "../../shared/interfaces/IWETH.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import "../libraries/HandlerGas.sol";

/// @title CurveStableSwapHandlerV3 — liquidityType 10 (pool types
///        curve_stable, curve_stable_meta and curve_stable_native)
/// @notice Router-side handler for Curve stableswap pools. It replaces
///         CurveStableSwapHandlerV2 in NonLinearSwapModule slot 10
///         (setCurveStableSwapHandler). It keeps the two V2 step kinds and
///         adds the pools that hold native ETH (coin 0xEeee...).
///
/// Step kinds, told apart by path.data:
///
///   empty data   exchange(i, j, dx, 0) on the pool. The handler finds i and j
///                in coins(). A step token that the pool does not hold, but
///                that is the wrapped native, takes the index of the native
///                coin 0xEeee (curve_stable_native: stETH/ETH, rETH/ETH, ...):
///                  WETH in:  WETH.withdraw(dx), exchange{value: dx}
///                  WETH out: the ETH balance delta, WETH.deposit, transfer
///                The route moves WETH only, so the module, the backend step
///                (srcToken/dstToken = WETH, empty data) and the next step do
///                not change. An exact coin match always wins, so a pool that
///                holds WETH (Curve WETH/stETH 0x828b1540) keeps the ERC-20
///                path, as in V2.
///   64 bytes     abi.encode(int128 i, int128 j): exchange_underlying(i, j,
///                dx, 0) on a metapool, unchanged from V2 (ERC-20 coins only).
///
/// Every path uses a raw call and the output balance delta: pre-NG pools
/// declare exchange and exchange_underlying without a return value. A wrong
/// index pair cannot move funds that the step did not bring: the pool pulls
/// at most the approved srcToken amount (or gets exactly the step's ETH), and
/// a swap into another token gives a zero delta, so the module's minimum-output
/// check reverts the route.
///
/// Balances: the native path approves nothing and keeps no ETH. It unwraps
/// exactly the step input and wraps exactly the ETH that the pool sent, so
/// the WETH balance (the HandlerGas dust, if seeded) and the ETH balance are
/// the same before and after a swap. A share-rounding coin (stETH) can leave
/// 1-2 wei in the handler, as with every other handler.
///
/// supportsExchangeUnderlying() and supportsNativeEth() let the quoter
/// router-handler gate and the backend venue gate tell this handler from the
/// older ones (V1 has neither function, V2 has only the first).
contract CurveStableSwapHandlerV3 is ISwapHandler, Ownable {
    /// abi.encode(int128 i, int128 j)
    uint256 private constant UNDERLYING_DATA_LENGTH = 64;
    /// The native-coin placeholder of Curve pools.
    address private constant NATIVE_COIN = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
    uint256 private constant MAX_COINS = 8;

    /// The wrapped native token that the routes carry (WETH on Ethereum).
    address public immutable wrappedNative;

    constructor(address wrappedNative_) Ownable(msg.sender) {
        require(wrappedNative_ != address(0), "Curve: wrapped native is zero");
        wrappedNative = wrappedNative_;
    }

    /// ETH from WETH.withdraw and from the pools that pay out native ETH.
    receive() external payable {}

    /// @notice Marker for the off-chain gates: this handler executes
    ///         exchange_underlying steps of curve_stable_meta pools.
    function supportsExchangeUnderlying() external pure returns (bool) {
        return true;
    }

    /// @notice Marker for the off-chain gates: this handler executes the
    ///         WETH steps of curve_stable_native pools (native ETH coin).
    function supportsNativeEth() external pure returns (bool) {
        return true;
    }

    function executeSwap(
        PathDescription memory path,
        uint256 amount,
        address, /* from */
        address to
    ) external override returns (uint256 amountOut) {
        uint256 amountIn = HandlerGas.inputAmount(path.srcToken, amount);
        if (path.data.length != 0) return _swapUnderlying(path, amountIn, to);

        (uint256 i, bool nativeIn) = _coinIndex(path.pairAddr, path.srcToken);
        (uint256 j, bool nativeOut) = _coinIndex(path.pairAddr, path.dstToken);

        uint256 value;
        if (nativeIn) {
            IWETH(wrappedNative).withdraw(amountIn);
            value = amountIn;
        } else {
            // Oku gas upgrade: the allowance rests at 1 unit (1 -> x -> 1), see HandlerGas.
            HandlerGas.approveResting(path.srcToken, path.pairAddr, amountIn);
        }

        uint256 balBefore = nativeOut ? address(this).balance : IERC20(path.dstToken).balanceOf(address(this));
        (bool ok, ) = path.pairAddr.call{value: value}(abi.encodeWithSignature(
            "exchange(int128,int128,uint256,uint256)",
            int128(int256(i)), int128(int256(j)), amountIn, uint256(0)
        ));
        require(ok, "Curve stable swap failed");
        if (!nativeIn) HandlerGas.settleAllowance(path.srcToken, path.pairAddr);

        if (nativeOut) {
            amountOut = address(this).balance - balBefore;
            if (amountOut > 0) IWETH(wrappedNative).deposit{value: amountOut}();
        } else {
            amountOut = IERC20(path.dstToken).balanceOf(address(this)) - balBefore;
        }

        if (amountOut > 0) {
            TransferHelper.safeTransfer(path.dstToken, to, amountOut);
        }
        return amountOut;
    }

    /// exchange_underlying(i, j, dx, 0) of a metapool (the V2 path).
    function _swapUnderlying(PathDescription memory path, uint256 amountIn, address to)
        private
        returns (uint256 amountOut)
    {
        require(path.data.length == UNDERLYING_DATA_LENGTH, "Curve underlying: bad data");
        (int128 ui, int128 uj) = abi.decode(path.data, (int128, int128));
        require(ui >= 0 && uj >= 0 && ui != uj, "Curve underlying: bad index");

        HandlerGas.approveResting(path.srcToken, path.pairAddr, amountIn);
        uint256 balBefore = IERC20(path.dstToken).balanceOf(address(this));
        (bool ok, ) = path.pairAddr.call(abi.encodeWithSignature(
            "exchange_underlying(int128,int128,uint256,uint256)",
            ui, uj, amountIn, uint256(0)
        ));
        require(ok, "Curve underlying swap failed");
        HandlerGas.settleAllowance(path.srcToken, path.pairAddr);
        amountOut = IERC20(path.dstToken).balanceOf(address(this)) - balBefore;

        if (amountOut > 0) {
            TransferHelper.safeTransfer(path.dstToken, to, amountOut);
        }
    }

    /// The coin index of `token` in `pool`, as CurveLibrary._tokenIndex finds
    /// it (raw coins(uint256) probes, then coins(int128) for pre-2020 pools).
    /// When no coin is `token` and `token` is the wrapped native, the index of
    /// the native coin 0xEeee (isNative = true). Raw staticcalls with a
    /// returndata-length check: old-Vyper pools return empty success for an
    /// unknown selector (see CurveLibrary).
    function _coinIndex(address pool, address token) private view returns (uint256 index, bool isNative) {
        bool wantNative = token == wrappedNative;
        uint256 nativeIndex = type(uint256).max;
        bool anyUint256;
        for (uint256 k = 0; k < MAX_COINS; k++) {
            (bool ok, bytes memory ret) = pool.staticcall(abi.encodeWithSignature("coins(uint256)", k));
            if (!ok || ret.length < 32) break;
            anyUint256 = true;
            address coin = abi.decode(ret, (address));
            if (coin == token) return (k, false);
            if (wantNative && coin == NATIVE_COIN && nativeIndex == type(uint256).max) nativeIndex = k;
        }
        if (!anyUint256) {
            for (uint256 k = 0; k < MAX_COINS; k++) {
                (bool ok, bytes memory ret) = pool.staticcall(abi.encodeWithSignature("coins(int128)", int128(int256(k))));
                if (!ok || ret.length < 32) break;
                address coin = abi.decode(ret, (address));
                if (coin == token) return (k, false);
                if (wantNative && coin == NATIVE_COIN && nativeIndex == type(uint256).max) nativeIndex = k;
            }
        }
        if (nativeIndex != type(uint256).max) return (nativeIndex, true);
        revert("Token not found in pool");
    }
}

@openzeppelin/contracts/access/Ownable.sol

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

@openzeppelin/contracts/utils/Context.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)

pragma solidity ^0.8.20;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}

@uniswap/lib/contracts/libraries/TransferHelper.sol

// SPDX-License-Identifier: GPL-3.0-or-later

pragma solidity >=0.6.0;

// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
    function safeApprove(
        address token,
        address to,
        uint256 value
    ) internal {
        // bytes4(keccak256(bytes('approve(address,uint256)')));
        (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
        require(
            success && (data.length == 0 || abi.decode(data, (bool))),
            'TransferHelper::safeApprove: approve failed'
        );
    }

    function safeTransfer(
        address token,
        address to,
        uint256 value
    ) internal {
        // bytes4(keccak256(bytes('transfer(address,uint256)')));
        (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
        require(
            success && (data.length == 0 || abi.decode(data, (bool))),
            'TransferHelper::safeTransfer: transfer failed'
        );
    }

    function safeTransferFrom(
        address token,
        address from,
        address to,
        uint256 value
    ) internal {
        // bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
        (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
        require(
            success && (data.length == 0 || abi.decode(data, (bool))),
            'TransferHelper::transferFrom: transferFrom failed'
        );
    }

    function safeTransferETH(address to, uint256 value) internal {
        (bool success, ) = to.call{value: value}(new bytes(0));
        require(success, 'TransferHelper::safeTransferETH: ETH transfer failed');
    }
}

contracts/router/interfaces/ISwapHandler.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.20;

interface ISwapHandler {
    struct PathDescription {
        address srcToken;
        address dstToken;
        address pairAddr;
        uint256 fee;
        uint256 srcAmount;
        uint256 dstMinAmount;
        uint256 feeSrc;
        uint256 feeDst;
        uint256 liquidityType;
        bytes data;
    }

    function executeSwap(
        PathDescription memory path,
        uint256 amount,
        address from,
        address to
    ) external returns (uint256 amountOut);
}

contracts/router/libraries/HandlerGas.sol

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

import "@uniswap/lib/contracts/libraries/TransferHelper.sol";
import "../../shared/interfaces/IERC20.sol";

/// Oku gas upgrade (review items 1-3): handler helpers so that a swap never
/// moves a storage slot 0 -> x -> 0. Such a slot costs 20,000 gas up front
/// and is refunded only at the end of the transaction, and eth_estimateGas
/// (what meta-aggregators rank by) counts the gas before the refund.
///   - allowances rest at 1 unit between swaps (1 -> x -> 1)
///   - balances keep 1 unit (the "dust") when the handler sweeps a token out
library HandlerGas {
    uint256 internal constant RESTING_ALLOWANCE = 1;
    uint256 internal constant DUST = 1;

    /// Lets `spender` pull `amount`, plus the resting unit that stays after
    /// an exact pull.
    function approveResting(address token, address spender, uint256 amount) internal {
        _approve(token, spender, amount + RESTING_ALLOWANCE);
    }

    /// Brings any allowance other than the resting unit back to it (a
    /// partial pull, a spender that does not decrement), so no allowance
    /// above 1 unit outlives the swap.
    function settleAllowance(address token, address spender) internal {
        if (IERC20(token).allowance(address(this), spender) != RESTING_ALLOWANCE) {
            _approve(token, spender, RESTING_ALLOWANCE);
        }
    }

    /// This contract's balance of `token` minus the 1-unit dust it keeps
    /// (0 when it holds only the dust or less).
    function spendable(address token) internal view returns (uint256 amount) {
        amount = IERC20(token).balanceOf(address(this));
        unchecked {
            amount = amount > DUST ? amount - DUST : 0;
        }
    }

    /// The input to spend: `amount`, capped at this contract's balance;
    /// `amount == 0` means the balance minus the dust. The module passes the
    /// exact amount it sent, but a share-rounding token (eETH, aTokens,
    /// cUSDCv3) delivers 1-2 wei less. Spending the full `amount` then took
    /// the shortfall from the dust and, once the dust was gone, reverted every
    /// later swap of that token. Capped, such a swap spends what it holds (the
    /// dust once, then what arrived).
    function inputAmount(address token, uint256 amount) internal view returns (uint256 amountIn) {
        if (amount == 0) return spendable(token);
        amountIn = IERC20(token).balanceOf(address(this));
        if (amount < amountIn) amountIn = amount;
    }

    /// approve(value); for tokens that refuse a nonzero -> nonzero approve
    /// (USDT-style), approve(0) first and retry.
    function _approve(address token, address spender, uint256 value) private {
        (bool ok, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.approve.selector, spender, value));
        if (ok && (data.length == 0 || abi.decode(data, (bool)))) return;
        TransferHelper.safeApprove(token, spender, 0);
        TransferHelper.safeApprove(token, spender, value);
    }
}

contracts/shared/interfaces/IERC20.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

interface IERC20 {
    event Approval(address indexed owner, address indexed spender, uint value);
    event Transfer(address indexed from, address indexed to, uint value);

    function name() external view returns (string memory);
    function symbol() external view returns (string memory);
    function decimals() external view returns (uint8);
    function totalSupply() external view returns (uint);
    function balanceOf(address owner) external view returns (uint);
    function allowance(address owner, address spender) external view returns (uint);

    function approve(address spender, uint value) external returns (bool);
    function transfer(address to, uint value) external returns (bool);
    function transferFrom(address from, address to, uint value) external returns (bool);
}

contracts/shared/interfaces/IWETH.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

interface IWETH {
    function deposit() external payable;
    function transfer(address to, uint value) external returns (bool);
    function withdraw(uint) external;
}
Compiler settingsShow
{
  "viaIR": true,
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "paris"
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.