Skip to content
Verified contractExactMIT

RangeLp

Address0xa91e3fa0e3151f4097ed6d7369ec691a0b889efa
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.26

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.26+commit.8a97fa7a
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
Via IR
yes
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,412,271
Creation transaction
0x1294da5d5b…530d35abad

contracts/RangeLp.sol

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

/// 一つのプールの一つの範囲にだけ流動性を置く。
/// 受取先は owner 固定。呼び出し元が送付先を指定する引数はない。
/// 借入はしない。呼ぶ相手は PoolManager と二つのトークンだけで、為替のフィードは読むだけ。
/// 秘密鍵はこのコントラクトに存在しない。
interface IToken {
    function balanceOf(address account) external view returns (uint256);
    function allowance(address holder, address spender) 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);
}

interface IPriceFeed {
    function decimals() external view returns (uint8);
    function latestRoundData()
        external
        view
        returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);
}

struct PoolKey {
    address currency0;
    address currency1;
    uint24 fee;
    int24 tickSpacing;
    address hooks;
}

struct SwapParams {
    bool zeroForOne;
    int256 amountSpecified;
    uint160 sqrtPriceLimitX96;
}

struct ModifyLiquidityParams {
    int24 tickLower;
    int24 tickUpper;
    int256 liquidityDelta;
    bytes32 salt;
}

/// デプロイ時に決めて、あとから変えられない上限。
struct Limits {
    /// プールの価格と為替の差の上限(1 万分率)。
    uint256 bandBps;
    /// 為替のフィードの古さの上限(秒)。
    uint256 maxFeedAge;
    /// 一度に置ける yen の上限。approve の額にかかわらず、これを超えて受け取らない。
    uint256 maxAmountIn;
    /// 置いてから exit できるまでの秒数。これより前に戻すのは withdraw だけ。
    uint256 minHold;
    /// 置くときに usd へ替えてよい割合の上限(1 万分率)。
    uint256 maxSwapBps;
    /// 範囲の幅の下限と上限(ティック)。
    int24 minRangeTicks;
    int24 maxRangeTicks;
    /// 替えないまま owner へ戻してよい usd の上限。置くときの余りと、替えない exit の両方にかかる。
    uint256 maxLooseUsd;
}

interface IPoolManager {
    function unlock(bytes calldata data) external returns (bytes memory);
    function swap(PoolKey memory key, SwapParams memory params, bytes calldata hookData) external returns (int256);
    function modifyLiquidity(PoolKey memory key, ModifyLiquidityParams memory params, bytes calldata hookData)
        external
        returns (int256 callerDelta, int256 feesAccrued);
    function sync(address currency) external;
    function settle() external payable returns (uint256);
    function take(address currency, address to, uint256 amount) external;
    function mint(address to, uint256 id, uint256 amount) external;
    function burn(address from, uint256 id, uint256 amount) external;
    function balanceOf(address holder, uint256 id) external view returns (uint256);
    function extsload(bytes32 slot) external view returns (bytes32);
}

contract RangeLp {
    // 両替の価格の制限は端に置く。歯止めは、両替の前と後に行う為替との照合。
    uint160 private constant MIN_SQRT_PRICE_LIMIT = 4295128739 + 1;
    uint160 private constant MAX_SQRT_PRICE_LIMIT = 1461446703485210103287273052203988822378723970342 - 1;
    // PoolManager の pools の場所。
    uint256 private constant POOLS_SLOT = 6;
    uint8 private constant OP_ENTER = 1;
    uint8 private constant OP_EXIT = 2;
    uint8 private constant OP_WITHDRAW = 3;
    uint8 private constant OP_CLAIM = 4;

    address public immutable owner;
    IPoolManager public immutable manager;
    /// currency0。途中だけ持つ側。
    address public immutable usd;
    /// currency1。置き場のトークン。
    address public immutable yen;
    uint24 public immutable fee;
    int24 public immutable tickSpacing;
    bytes32 public immutable poolId;
    /// yen の 1 単位が usd のいくつかを返すフィード(JPY/USD)。
    IPriceFeed public immutable feed;
    uint256 public immutable feedScale;
    uint256 public immutable bandBps;
    uint256 public immutable maxFeedAge;
    uint256 public immutable maxAmountIn;
    uint256 public immutable minHold;
    uint256 public immutable maxSwapBps;
    int24 public immutable minRangeTicks;
    int24 public immutable maxRangeTicks;
    uint256 public immutable maxLooseUsd;

    int24 public tickLower;
    int24 public tickUpper;
    uint128 public liquidity;
    uint64 public enteredAt;
    bool private locked;

    /// 置いた・外したときの価格と為替を、取引の記録に残す。
    /// 人が結果を確かめるときに、見積もりプロセスが送る画面に頼らず、チェーンの記録だけで読めるようにする。
    /// sqrtPrice は両替の前と後。fxAnswer はそのとき照合に使った為替の値。照合をしなかったときは 0。
    event Entered(
        uint256 amountIn,
        uint256 swapAmountIn,
        uint256 usdOut,
        int24 lower,
        int24 upper,
        uint128 liquidity,
        uint256 sqrtPriceBefore,
        uint256 sqrtPriceAfter,
        int256 fxAnswer
    );
    event Exited(
        uint256 yenOut, uint256 usdOut, bool swapBack, uint256 sqrtPriceBefore, uint256 sqrtPriceAfter, int256 fxAnswer
    );
    event Withdrawn();
    event Claimed(address token, uint256 amount);

    error NotOwner();
    error NotManager();
    error Reentered();
    error Expired();
    error BadInput();
    error AlreadyEntered();
    error NotEntered();
    error TooEarly();
    error Slippage();
    error StaleFx();
    error OffFx();
    error OutOfRange();
    error LooseUsd();
    error AllowanceLeft();
    error TokenFailed();

    constructor(
        IPoolManager manager_,
        address usd_,
        address yen_,
        uint24 fee_,
        int24 tickSpacing_,
        IPriceFeed feed_,
        Limits memory limits
    ) {
        if (usd_ >= yen_ || tickSpacing_ <= 0) revert BadInput();
        if (limits.bandBps == 0 || limits.bandBps > 1000 || limits.maxFeedAge == 0) revert BadInput();
        if (limits.maxAmountIn == 0 || limits.maxAmountIn > type(uint128).max) revert BadInput();
        if (limits.minHold > 365 days || limits.maxSwapBps > 10000) revert BadInput();
        if (limits.minRangeTicks <= 0 || limits.maxRangeTicks < limits.minRangeTicks) revert BadInput();
        if (limits.maxLooseUsd > uint256(type(int256).max)) revert BadInput();
        uint256 up = uint256(feed_.decimals()) + IToken(yen_).decimals();
        uint256 down = IToken(usd_).decimals();
        if (up < down || up - down > 36) revert BadInput();
        owner = msg.sender;
        manager = manager_;
        usd = usd_;
        yen = yen_;
        fee = fee_;
        tickSpacing = tickSpacing_;
        feed = feed_;
        feedScale = 10 ** (up - down);
        bandBps = limits.bandBps;
        maxFeedAge = limits.maxFeedAge;
        maxAmountIn = limits.maxAmountIn;
        minHold = limits.minHold;
        maxSwapBps = limits.maxSwapBps;
        minRangeTicks = limits.minRangeTicks;
        maxRangeTicks = limits.maxRangeTicks;
        maxLooseUsd = limits.maxLooseUsd;
        poolId = keccak256(abi.encode(PoolKey(usd_, yen_, fee_, tickSpacing_, address(0))));
    }

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

    modifier nonReentrant() {
        if (locked) revert Reentered();
        locked = true;
        _;
        locked = false;
    }

    /// owner の yen を受け取り、一部を usd に替えて、範囲に流動性を置く。
    /// 替える量と流動性は呼び出し側が計算して渡す。置けなければ取引全体を取り消す。
    function enter(
        uint256 amountIn,
        uint256 swapAmountIn,
        uint256 minUsdOut,
        int24 lower,
        int24 upper,
        uint128 liquidityToAdd,
        uint256 deadline
    ) external onlyOwner nonReentrant {
        if (block.timestamp > deadline) revert Expired();
        if (liquidity != 0) revert AlreadyEntered();
        if (amountIn == 0 || amountIn > maxAmountIn) revert BadInput();
        if (swapAmountIn * 10000 > amountIn * maxSwapBps) revert BadInput();
        int256 width = int256(upper) - int256(lower);
        if (liquidityToAdd == 0 || width < minRangeTicks || width > maxRangeTicks) revert BadInput();
        tickLower = lower;
        tickUpper = upper;
        liquidity = liquidityToAdd;
        enteredAt = uint64(block.timestamp);
        _token(yen, abi.encodeWithSelector(IToken.transferFrom.selector, owner, address(this), amountIn));
        // 一度の approve で置けるのは一度だけ。許可を残して、人の確認を待たずに次を置かせない。
        if (IToken(yen).allowance(owner, address(this)) != 0) revert AllowanceLeft();
        bytes memory seen =
            manager.unlock(abi.encode(OP_ENTER, abi.encode(swapAmountIn, minUsdOut, lower, upper, liquidityToAdd)));
        (uint256 usdOut, uint256 priceBefore, uint256 priceAfter, int256 fxAnswer) =
            abi.decode(seen, (uint256, uint256, uint256, int256));
        emit Entered(amountIn, swapAmountIn, usdOut, lower, upper, liquidityToAdd, priceBefore, priceAfter, fxAnswer);
        _sweep(yen);
        _sweep(usd);
    }

    /// 流動性と手数料を全部外し、yen を owner へ送る。
    /// swapBack が真なら usd を yen に替えてから送る。偽なら替えずに、usd もそのまま owner へ送る。
    /// 替えないときは為替を見ない。全部が yen で、手数料の usd だけが少し残っているときに使う。
    /// 替えないまま戻せる usd は maxLooseUsd まで。それを超えるときは、替えるか、withdraw を使う。
    /// 置いてから minHold が過ぎるまでは通らない。往復を繰り返して減らされないための歯止め。
    function exit(uint256 minYenOut, bool swapBack, uint256 deadline) external onlyOwner nonReentrant {
        if (block.timestamp > deadline) revert Expired();
        uint128 held = liquidity;
        if (held == 0) revert NotEntered();
        if (block.timestamp < uint256(enteredAt) + minHold) revert TooEarly();
        int24 lower = tickLower;
        int24 upper = tickUpper;
        _clear();
        bytes memory seen = manager.unlock(abi.encode(OP_EXIT, abi.encode(lower, upper, held, swapBack)));
        (uint256 priceBefore, uint256 priceAfter, int256 fxAnswer) = abi.decode(seen, (uint256, uint256, int256));
        uint256 yenOut = IToken(yen).balanceOf(address(this));
        if (yenOut < minYenOut) revert Slippage();
        emit Exited(yenOut, IToken(usd).balanceOf(address(this)), swapBack, priceBefore, priceAfter, fxAnswer);
        _sweep(yen);
        _sweep(usd);
    }

    /// ルール付き Clef からは呼べない別セレクタ。両替をせずに全部を owner へ戻す。
    /// 為替も minHold も見ない。トークンが owner へ届かないときは、PoolManager 上の預かりにして claim を待つ。
    function withdraw() external onlyOwner nonReentrant {
        uint128 held = liquidity;
        if (held != 0) {
            int24 lower = tickLower;
            int24 upper = tickUpper;
            _clear();
            manager.unlock(abi.encode(OP_WITHDRAW, abi.encode(lower, upper, held)));
        }
        _trySweep(yen);
        _trySweep(usd);
        emit Withdrawn();
    }

    /// ルール付き Clef からは呼べない別セレクタ。withdraw で預かりになった分を owner へ出す。
    function claim(address token) external onlyOwner nonReentrant {
        if (token != usd && token != yen) revert BadInput();
        uint256 amount = manager.balanceOf(address(this), uint256(uint160(token)));
        if (amount == 0) return;
        manager.unlock(abi.encode(OP_CLAIM, abi.encode(token, amount)));
        emit Claimed(token, amount);
    }

    function unlockCallback(bytes calldata data) external returns (bytes memory) {
        // 自分が unlock を呼んでいる最中の PoolManager だけを受け付ける。
        if (msg.sender != address(manager) || !locked) revert NotManager();
        (uint8 op, bytes memory args) = abi.decode(data, (uint8, bytes));
        if (op == OP_ENTER) {
            return _enter(args);
        } else if (op == OP_EXIT) {
            return _exit(args);
        } else if (op == OP_WITHDRAW) {
            _withdraw(args);
        } else if (op == OP_CLAIM) {
            (address token, uint256 amount) = abi.decode(args, (address, uint256));
            manager.burn(address(this), uint256(uint160(token)), amount);
            manager.take(token, owner, amount);
        } else {
            revert BadInput();
        }
        return "";
    }

    function _enter(bytes memory args) private returns (bytes memory) {
        (uint256 swapAmountIn, uint256 minUsdOut, int24 lower, int24 upper, uint128 liquidityToAdd) =
            abi.decode(args, (uint256, uint256, int24, int24, uint128));
        // 置く価格も為替の帯の中に限る。両替が無いときもここで確かめる。
        (uint256 priceBefore, int256 fxAnswer) = _requireNearFx();
        uint256 priceAfter = priceBefore;
        uint256 usdOut;
        int256 d0;
        int256 d1;
        if (swapAmountIn > 0) {
            int256 swapped =
                manager.swap(_key(), SwapParams(false, -int256(swapAmountIn), MAX_SQRT_PRICE_LIMIT), "");
            d0 = _amount0(swapped);
            d1 = _amount1(swapped);
            if (d0 < 0 || uint256(d0) < minUsdOut) revert Slippage();
            usdOut = uint256(d0);
            // 両替の前と後がどちらも帯の中なら、約定の価格も帯の中に収まる。
            (priceAfter,) = _requireNearFx();
        }
        // 置く範囲は、両替のあとの今の価格を含むものに限る。片側だけに置かせない。
        (, int24 tick) = _slot0();
        if (tick < lower || tick >= upper) revert OutOfRange();
        (int256 added,) = manager.modifyLiquidity(
            _key(), ModifyLiquidityParams(lower, upper, int256(uint256(liquidityToAdd)), bytes32(0)), ""
        );
        d0 += _amount0(added);
        // 替えた usd は、ほぼ全部を流動性に入れる。余らせて owner に持たせない。
        if (d0 > int256(maxLooseUsd)) revert LooseUsd();
        _resolve(usd, d0);
        _resolve(yen, d1 + _amount1(added));
        return abi.encode(usdOut, priceBefore, priceAfter, fxAnswer);
    }

    function _exit(bytes memory args) private returns (bytes memory) {
        (int24 lower, int24 upper, uint128 held, bool swapBack) = abi.decode(args, (int24, int24, uint128, bool));
        (int256 d0, int256 d1) = _remove(lower, upper, held);
        if (!swapBack && d0 > int256(maxLooseUsd)) revert LooseUsd();
        (uint256 priceBefore,) = _slot0();
        uint256 priceAfter = priceBefore;
        int256 fxAnswer;
        // 為替を見るのは両替するときだけ。
        if (swapBack && d0 > 0) {
            (priceBefore, fxAnswer) = _requireNearFx();
            int256 swapped = manager.swap(_key(), SwapParams(true, -d0, MIN_SQRT_PRICE_LIMIT), "");
            d0 += _amount0(swapped);
            d1 += _amount1(swapped);
            (priceAfter,) = _requireNearFx();
        }
        _resolve(usd, d0);
        _resolve(yen, d1);
        return abi.encode(priceBefore, priceAfter, fxAnswer);
    }

    function _withdraw(bytes memory args) private {
        (int24 lower, int24 upper, uint128 held) = abi.decode(args, (int24, int24, uint128));
        (int256 d0, int256 d1) = _remove(lower, upper, held);
        _deliver(usd, d0);
        _deliver(yen, d1);
    }

    function _remove(int24 lower, int24 upper, uint128 held) private returns (int256 d0, int256 d1) {
        (int256 removed,) =
            manager.modifyLiquidity(_key(), ModifyLiquidityParams(lower, upper, -int256(uint256(held)), bytes32(0)), "");
        d0 = _amount0(removed);
        d1 = _amount1(removed);
    }

    /// プールの価格が、為替から bandBps 以内にあることを確かめる。
    function _requireNearFx() private view returns (uint256 sqrtPrice, int256 answer) {
        uint256 updatedAt;
        (, answer,, updatedAt,) = feed.latestRoundData();
        if (answer <= 0 || answer > int256(uint256(type(uint64).max))) revert StaleFx();
        if (updatedAt == 0 || block.timestamp > updatedAt + maxFeedAge) revert StaleFx();
        (sqrtPrice,) = _slot0();
        if (sqrtPrice == 0 || sqrtPrice >= (uint256(1) << 128)) revert OffFx();
        // 価格 = sqrtPrice^2 / 2^192 = yen の最小単位 / usd の最小単位。
        // 為替の側は feedScale / answer。両辺に answer と 2^96 を掛けて比べる。
        uint256 pool = ((sqrtPrice * sqrtPrice) >> 96) * uint256(answer);
        uint256 fx = feedScale << 96;
        if (pool * 10000 < fx * (10000 - bandBps) || pool * 10000 > fx * (10000 + bandBps)) revert OffFx();
    }

    /// slot0 の下位 160 ビットが sqrtPriceX96、その上の 24 ビットが今のティック。
    function _slot0() private view returns (uint256 sqrtPrice, int24 tick) {
        uint256 word = uint256(manager.extsload(keccak256(abi.encode(poolId, POOLS_SLOT))));
        sqrtPrice = uint256(uint160(word));
        tick = int24(uint24(word >> 160));
    }

    function _resolve(address token, int256 delta) private {
        if (delta < 0) {
            manager.sync(token);
            _token(token, abi.encodeWithSelector(IToken.transfer.selector, address(manager), uint256(-delta)));
            manager.settle();
        } else if (delta > 0) {
            manager.take(token, address(this), uint256(delta));
        }
    }

    /// PoolManager から owner へ直接出す。届かなければ、この契約の預かりとして残す。
    function _deliver(address token, int256 delta) private {
        if (delta <= 0) return;
        try manager.take(token, owner, uint256(delta)) {}
        catch {
            manager.mint(address(this), uint256(uint160(token)), uint256(delta));
        }
    }

    function _sweep(address token) private {
        uint256 left = IToken(token).balanceOf(address(this));
        if (left > 0) _token(token, abi.encodeWithSelector(IToken.transfer.selector, owner, left));
    }

    /// 片方のトークンが止まっていても、もう片方を戻せるようにする。
    /// 残高の読み取りが失敗しても、戻り値が読めない形でも、止めない。
    function _trySweep(address token) private {
        (bool read, bytes memory ret) = token.staticcall(abi.encodeWithSelector(IToken.balanceOf.selector, address(this)));
        if (!read || ret.length < 32) return;
        uint256 left = abi.decode(ret, (uint256));
        if (left == 0) return;
        (bool sent,) = token.call(abi.encodeWithSelector(IToken.transfer.selector, owner, left));
        sent;
    }

    function _clear() private {
        tickLower = 0;
        tickUpper = 0;
        liquidity = 0;
        enteredAt = 0;
    }

    function _key() private view returns (PoolKey memory) {
        return PoolKey(usd, yen, fee, tickSpacing, address(0));
    }

    function _amount0(int256 delta) private pure returns (int256) {
        return int256(int128(delta >> 128));
    }

    function _amount1(int256 delta) private pure returns (int256) {
        return int256(int128(delta));
    }

    function _token(address token, bytes memory data) private {
        (bool ok, bytes memory ret) = token.call(data);
        if (!ok || (ret.length != 0 && !abi.decode(ret, (bool)))) revert TokenFailed();
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": []
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.