Skip to content
Verified contractExactMIT

UniswapV3Retargetor

Address0xcf4c5cc6fce4c16fc5526f65f242f66dd6819dd2
Balance

0 ETH

 

Transactions

365

 

Compiler

solc 0.8.20

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.20+commit.a1b79de6
Language
solidity
Optimization
Yes, 400 runs
Via IR
yes
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
24,232,063
Creation transaction
0x318168be27…c578513a22

contracts/UniswapV3Retargetorv2.sol

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

/* ============================================================
   Minimal interfaces
   ============================================================ */

interface IERC20 {
    function balanceOf(address) external view returns (uint256);
    function allowance(address owner, address spender) external view returns (uint256);
    function approve(address spender, uint256 value) external returns (bool);
    function transfer(address to, uint256 value) external returns (bool);
    function transferFrom(address src, address dst, uint256 value) external returns (bool);
    function decimals() external view returns (uint8);
}

interface ISwapRouter {
    struct ExactInputSingleParams {
        address tokenIn;
        address tokenOut;
        uint24  fee;
        address recipient;
        uint256 deadline;
        uint256 amountIn;
        uint256 amountOutMinimum;
        uint160 sqrtPriceLimitX96;
    }

    function exactInputSingle(ExactInputSingleParams calldata params)
        external
        payable
        returns (uint256 amountOut);
}

interface IQuoterV2 {
    function quoteExactInputSingle(
        address tokenIn,
        address tokenOut,
        uint24 fee,
        uint256 amountIn,
        uint160 sqrtPriceLimitX96
    ) external returns (uint256 amountOut);
}

interface INonfungiblePositionManager {
    struct DecreaseLiquidityParams {
        uint256 tokenId;
        uint128 liquidity;
        uint256 amount0Min;
        uint256 amount1Min;
        uint256 deadline;
    }
    struct CollectParams {
        uint256 tokenId;
        address recipient;
        uint128 amount0Max;
        uint128 amount1Max;
    }
    struct MintParams {
        address token0;
        address token1;
        uint24  fee;
        int24   tickLower;
        int24   tickUpper;
        uint256 amount0Desired;
        uint256 amount1Desired;
        uint256 amount0Min;
        uint256 amount1Min;
        address recipient;
        uint256 deadline;
    }

    function positions(uint256 tokenId)
        external view
        returns (
            uint96 nonce,
            address operator,
            address token0,
            address token1,
            uint24  fee,
            int24   tickLower,
            int24   tickUpper,
            uint128 liquidity,
            uint256 feeGrowthInside0LastX128,
            uint256 feeGrowthInside1LastX128,
            uint128 tokensOwed0,
            uint128 tokensOwed1
        );

    function decreaseLiquidity(DecreaseLiquidityParams calldata params)
        external payable
        returns (uint256 amount0, uint256 amount1);

    function collect(CollectParams calldata params)
        external payable
        returns (uint256 amount0, uint256 amount1);

    function burn(uint256 tokenId) external payable;

    function mint(MintParams calldata params)
        external payable
        returns (uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1);

    function ownerOf(uint256 tokenId) external view returns (address);
    function getApproved(uint256 tokenId) external view returns (address);
    function isApprovedForAll(address owner, address operator) external view returns (bool);
}

/* ============================================================
   Orchestrator (ABI-compatible upgrade)
   ============================================================ */

contract UniswapV3Retargetor {
    // ========= Errors =========
    error DeadlinePassed();
    error TokenOrder();
    error CallerNotOwnerOrOperator();
    error OrchestratorNotApproved();
    error BadBps();

    error PullNotAllowed();              // pull requested but maxPull == 0
    error PullInsufficientAllowance();   // allowance < needed
    error PullInsufficientBalance();     // balance < needed
    error ERC20CallFailed(address token);

    // ========= Events =========
    event Retargeted(
        uint256 oldTokenId,
        int24 oldLower,
        int24 oldUpper,
        uint128 oldLiquidity,
        uint256 collected0,
        uint256 collected1,
        uint256 newTokenId,
        int24 newLower,
        int24 newUpper,
        uint256 used0,
        uint256 used1,
        uint256 leftover0,
        uint256 leftover1
    );

    event Rebalanced(
        address tokenIn,
        address tokenOut,
        uint256 amountIn,
        uint256 amountOutMin,
        uint256 amountOutActual
    );

    event Pulled(address token, uint256 amount);

    // ========= Immutables =========
    INonfungiblePositionManager public immutable positionManager;
    ISwapRouter public immutable router;
    IQuoterV2 public immutable quoter;

    address public immutable token0; // USDC
    address public immutable token1; // WETH
    uint24  public immutable poolFee;

    uint8   public immutable dec0;
    uint8   public immutable dec1;
    uint256 public immutable one0;
    uint256 public immutable one1;

    constructor(
        address _positionManager,
        address _router,
        address _quoter,
        address _token0,
        address _token1,
        uint24  _poolFee
    ) {
        if (_token0 >= _token1) revert TokenOrder();

        positionManager = INonfungiblePositionManager(_positionManager);
        router          = ISwapRouter(_router);
        quoter          = IQuoterV2(_quoter);

        token0  = _token0;
        token1  = _token1;
        poolFee = _poolFee;

        dec0 = IERC20(_token0).decimals();
        dec1 = IERC20(_token1).decimals();
        one0 = 10 ** uint256(dec0);
        one1 = 10 ** uint256(dec1);
    }

    // ========= Params =========
    struct RetargetParams {
        uint256 oldTokenId;

        int24 newTickLower;
        int24 newTickUpper;

        uint256 amount0Min;
        uint256 amount1Min;

        uint16  targetRatioBps; // token0 value share
        uint16  slippageBps;
        uint256 maxSwapIn;

        uint256 deadline;

        address recipient;

        bool    pullFromSenderIfDeficit;

        uint256 maxPull0;
        uint256 maxPull1;

        uint256 pullTarget0;
        uint256 pullTarget1;

        uint16  mintHaircutBps;
    }

    function retarget(RetargetParams calldata p) external payable returns (uint256 newTokenId) {
        if (block.timestamp > p.deadline) revert DeadlinePassed();

        if (p.targetRatioBps == 0 || p.targetRatioBps >= 10000) revert BadBps();
        if (p.slippageBps >= 10_000) revert BadBps();
        if (p.mintHaircutBps == 0 || p.mintHaircutBps > 10_000) revert BadBps();

        // --- 1) Remove/collect/burn old position (if any)
        int24 oldLower; int24 oldUpper; uint128 oldLiquidity;
        uint256 collected0; uint256 collected1;
        address owner;

        if (p.oldTokenId != 0) {
            owner = positionManager.ownerOf(p.oldTokenId);

            bool callerOk = (msg.sender == owner)
                || (positionManager.getApproved(p.oldTokenId) == msg.sender)
                || (positionManager.isApprovedForAll(owner, msg.sender));
            if (!callerOk) revert CallerNotOwnerOrOperator();

            bool orchOk = (positionManager.getApproved(p.oldTokenId) == address(this))
                || (positionManager.isApprovedForAll(owner, address(this)));
            if (!orchOk) revert OrchestratorNotApproved();

            (oldLower, oldUpper, oldLiquidity, collected0, collected1) =
                _removeCollectBurn(p.oldTokenId, p.deadline);
        }

        // --- 2) Pull tokens from sender (new semantics):
        // If pullTarget == type(uint256).max => pull "as much as allowed", capped by maxPull + balance + allowance.
        if (p.pullFromSenderIfDeficit) {
            if (p.pullTarget0 > 0) _pullSmart(token0, p.pullTarget0, p.maxPull0);
            if (p.pullTarget1 > 0) _pullSmart(token1, p.pullTarget1, p.maxPull1);
        }

        // --- 3) Rebalance to ratio (one swap)
        _rebalanceToRatioBps(p.targetRatioBps, p.slippageBps, p.deadline, p.maxSwapIn);

        // --- 4) Mint using post-swap balances + refund leftovers
        address finalRecipient = (p.oldTokenId != 0) ? owner : p.recipient;
        uint256 used0; uint256 used1; uint256 left0; uint256 left1;

        (newTokenId, used0, used1, left0, left1) = _mintUsingBalancesAndRefund(
            p.newTickLower,
            p.newTickUpper,
            p.amount0Min,
            p.amount1Min,
            p.mintHaircutBps,
            finalRecipient,
            p.deadline
        );

        emit Retargeted(
            p.oldTokenId, oldLower, oldUpper, oldLiquidity,
            collected0, collected1,
            newTokenId, p.newTickLower, p.newTickUpper,
            used0, used1, left0, left1
        );
    }

    function _removeCollectBurn(
        uint256 tokenId,
        uint256 deadline
    ) internal returns (
        int24 oldLower,
        int24 oldUpper,
        uint128 oldLiquidity,
        uint256 collected0,
        uint256 collected1
    ) {
        ( , , , , , oldLower, oldUpper, oldLiquidity, , , , ) =
            positionManager.positions(tokenId);

        positionManager.decreaseLiquidity(INonfungiblePositionManager.DecreaseLiquidityParams({
            tokenId: tokenId,
            liquidity: oldLiquidity,
            amount0Min: 0,
            amount1Min: 0,
            deadline: deadline
        }));

        (collected0, collected1) = positionManager.collect(INonfungiblePositionManager.CollectParams({
            tokenId: tokenId,
            recipient: address(this),
            amount0Max: type(uint128).max,
            amount1Max: type(uint128).max
        }));

        positionManager.burn(tokenId);
    }

    function _rebalanceToRatioBps(
        uint16 target0Bps,
        uint16 slippageBps,
        uint256 deadline,
        uint256 maxSwapIn
    ) internal {
        uint256 b0 = IERC20(token0).balanceOf(address(this));
        uint256 b1 = IERC20(token1).balanceOf(address(this));
        if (b0 == 0 && b1 == 0) return;

        // price proxy: 1 token1 -> token0 (raw)
        uint256 p10 = quoter.quoteExactInputSingle(token1, token0, poolFee, one1, 0);

        uint256 v1in0 = (b1 * p10) / one1;
        uint256 totalIn0 = b0 + v1in0;
        uint256 target0Val = (totalIn0 * target0Bps) / 10_000;

        bool swap0For1 = (b0 > target0Val);

        uint256 amountIn = _solveAmountInForTarget(
            swap0For1,
            target0Bps,
            p10,
            b0,
            b1,
            maxSwapIn
        );
        if (amountIn == 0) return;

        address tokenIn  = swap0For1 ? token0 : token1;
        address tokenOut = swap0For1 ? token1 : token0;

        uint256 qOut = quoter.quoteExactInputSingle(tokenIn, tokenOut, poolFee, amountIn, 0);
        if (qOut == 0) return;

        uint256 minOut = (qOut * (10_000 - slippageBps)) / 10_000;

        _approveIfNeeded(tokenIn, address(router), amountIn);

        uint256 outActual = router.exactInputSingle(ISwapRouter.ExactInputSingleParams({
            tokenIn: tokenIn,
            tokenOut: tokenOut,
            fee: poolFee,
            recipient: address(this),
            deadline: deadline,
            amountIn: amountIn,
            amountOutMinimum: minOut,
            sqrtPriceLimitX96: 0
        }));

        emit Rebalanced(tokenIn, tokenOut, amountIn, minOut, outActual);
    }

    function _solveAmountInForTarget(
        bool swap0For1,
        uint16 target0Bps,
        uint256 p10,
        uint256 b0,
        uint256 b1,
        uint256 maxSwapIn
    ) internal returns (uint256) {
        uint256 upper = swap0For1 ? b0 : b1;
        if (upper == 0) return 0;

        if (maxSwapIn > 0 && maxSwapIn < upper) upper = maxSwapIn;
        if (upper == 0) return 0;

        uint256 lo = 0;
        uint256 hi = upper;

        uint256 best = 0;
        uint256 bestErr = type(uint256).max;

        for (uint256 i = 0; i < 12; i++) {
            uint256 mid = (lo + hi) / 2;
            if (mid == 0) { lo = 1; continue; }

            uint256 out = quoter.quoteExactInputSingle(
                swap0For1 ? token0 : token1,
                swap0For1 ? token1 : token0,
                poolFee,
                mid,
                0
            );

            uint256 nb0;
            uint256 nb1;

            if (swap0For1) {
                if (mid > b0) break;
                nb0 = b0 - mid;
                nb1 = b1 + out;
            } else {
                if (mid > b1) break;
                nb1 = b1 - mid;
                nb0 = b0 + out;
            }

            uint256 v1in0 = (nb1 * p10) / one1;
            uint256 totalIn0 = nb0 + v1in0;
            uint256 want0 = (totalIn0 * target0Bps) / 10_000;

            uint256 err = nb0 > want0 ? (nb0 - want0) : (want0 - nb0);
            if (err < bestErr) {
                bestErr = err;
                best = mid;
            }

            if (nb0 > want0) {
                if (swap0For1) lo = mid + 1;
                else hi = (mid == 0) ? 0 : (mid - 1);
            } else {
                if (swap0For1) hi = (mid == 0) ? 0 : (mid - 1);
                else lo = mid + 1;
            }
        }

        return best;
    }

    function _mintUsingBalancesAndRefund(
        int24 lower,
        int24 upper,
        uint256 min0,
        uint256 min1,
        uint16 haircutBps,
        address recipient,
        uint256 deadline
    ) internal returns (
        uint256 newTokenId,
        uint256 used0,
        uint256 used1,
        uint256 left0,
        uint256 left1
    ) {
        uint256 b0 = IERC20(token0).balanceOf(address(this));
        uint256 b1 = IERC20(token1).balanceOf(address(this));

        uint256 use0 = (b0 * haircutBps) / 10_000;
        uint256 use1 = (b1 * haircutBps) / 10_000;

        _approveIfNeeded(token0, address(positionManager), use0);
        _approveIfNeeded(token1, address(positionManager), use1);

        (newTokenId, , used0, used1) = positionManager.mint(INonfungiblePositionManager.MintParams({
            token0: token0,
            token1: token1,
            fee: poolFee,
            tickLower: lower,
            tickUpper: upper,
            amount0Desired: use0,
            amount1Desired: use1,
            amount0Min: min0,
            amount1Min: min1,
            recipient: recipient,
            deadline: deadline
        }));

        left0 = IERC20(token0).balanceOf(address(this));
        left1 = IERC20(token1).balanceOf(address(this));

        if (left0 > 0) _safeTransfer(token0, recipient, left0);
        if (left1 > 0) _safeTransfer(token1, recipient, left1);
    }

    /* ============================================================
       Pull logic (ABI compatible improvement)
       ============================================================ */

    function _pullSmart(address tok, uint256 want, uint256 maxPull) internal {
        if (maxPull == 0) revert PullNotAllowed();

        // Special mode used by your bot:
        // pullTarget == UINT256_MAX => "pull as much as possible up to maxPull"
        if (want == type(uint256).max) {
            uint256 bal = IERC20(tok).balanceOf(msg.sender);
            uint256 allow = IERC20(tok).allowance(msg.sender, address(this));
            uint256 amt = maxPull;

            if (amt > bal) amt = bal;
            if (amt > allow) amt = allow;

            if (amt == 0) {
                // Make failure obvious (rather than a silent 0 pull that later causes weird behaviour)
                if (allow == 0) revert PullInsufficientAllowance();
                revert PullInsufficientBalance();
            }

            _safeTransferFrom(tok, msg.sender, address(this), amt);
            emit Pulled(tok, amt);
            return;
        }

        // Original behaviour: pull only if deficit below "want"
        uint256 b = IERC20(tok).balanceOf(address(this));
        if (b >= want) return;

        uint256 need = want - b;
        if (need > maxPull) need = maxPull;

        uint256 senderBal = IERC20(tok).balanceOf(msg.sender);
        if (need > senderBal) revert PullInsufficientBalance();

        uint256 senderAllow = IERC20(tok).allowance(msg.sender, address(this));
        if (need > senderAllow) revert PullInsufficientAllowance();

        _safeTransferFrom(tok, msg.sender, address(this), need);
        emit Pulled(tok, need);
    }

    /* ============================================================
       Safe ERC20 wrappers (handles non-standard tokens)
       ============================================================ */

    function _safeTransfer(address tok, address to, uint256 amt) internal {
        (bool ok, bytes memory data) = tok.call(abi.encodeWithSelector(IERC20.transfer.selector, to, amt));
        if (!ok) revert ERC20CallFailed(tok);
        if (data.length > 0 && !abi.decode(data, (bool))) revert ERC20CallFailed(tok);
    }

    function _safeTransferFrom(address tok, address from, address to, uint256 amt) internal {
        (bool ok, bytes memory data) = tok.call(abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, amt));
        if (!ok) revert ERC20CallFailed(tok);
        if (data.length > 0 && !abi.decode(data, (bool))) revert ERC20CallFailed(tok);
    }

    function _approveIfNeeded(address tok, address spender, uint256 amt) internal {
        if (amt == 0) return;
        if (IERC20(tok).allowance(address(this), spender) < amt) {
            // reset then max (covers USDT-like tokens too)
            (bool ok0, ) = tok.call(abi.encodeWithSelector(IERC20.approve.selector, spender, 0));
            if (!ok0) revert ERC20CallFailed(tok);
            (bool ok1, ) = tok.call(abi.encodeWithSelector(IERC20.approve.selector, spender, type(uint256).max));
            if (!ok1) revert ERC20CallFailed(tok);
        }
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "optimizer": {
    "runs": 400,
    "enabled": true
  },
  "remappings": []
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.