// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity =0.7.6; pragma abicoder v2;…
- User
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity =0.7.6; pragma abicoder v2;
import '@uniswap/v3-periphery/contracts/base/PeripheryImmutableState.sol'; import '@uniswap/v3-core/contracts/libraries/SafeCast.sol'; import '@uniswap/v3-core/contracts/libraries/TickMath.sol'; import '@uniswap/v3-core/contracts/libraries/TickBitmap.sol'; import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol'; import '@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol'; import '@uniswap/v3-periphery/contracts/libraries/Path.sol'; import '@uniswap/v3-periphery/contracts/libraries/PoolAddress.sol'; import '@uniswap/v3-periphery/contracts/libraries/CallbackValidation.sol';
import '../interfaces/IQuoterV2.sol'; import '../libraries/PoolTicksCounter.sol';
/// @title Provides quotes for swaps /// @notice Allows getting the expected amount out or amount in for a given swap without executing the swap /// @dev These functions are not gas efficient and should not be called on chain. Instead, optimistically execute /// the swap and check the amounts in the callback. contract QuoterV2 is IQuoterV2, IUniswapV3SwapCallback, PeripheryImmutableState { using Path for bytes; using SafeCast for uint256; using PoolTicksCounter for IUniswapV3Pool;
/// @dev Transient storage variable used to check a safety condition in exact output swaps. uint256 private amountOutCached; constructor(address _factory, address _WETH9) PeripheryImmutableState(_factory, _WETH9) {} function getPool( address tokenA, address tokenB, uint24 fee ) private view returns (IUniswapV3Pool) { return IUniswapV3Pool(PoolAddress.computeAddress(factory, PoolAddress.getPoolKey(tokenA, tokenB, fee))); } /// @inheritdoc IUniswapV3SwapCallback function uniswapV3SwapCallback( int256 amount0Delta, int256 amount1Delta, bytes memory path ) external view override { require(amount0Delta > 0 || amount1Delta > 0); // swaps entirely within 0-liquidity regions are not supported (address tokenIn, address tokenOut, uint24 fee) = path.decodeFirstPool(); CallbackValidation.verifyCallback(factory, tokenIn, tokenOut, fee); (bool isExactInput, uint256 amountToPay, uint256 amountReceived) = amount0Delta > 0 ? (tokenIn < tokenOut, uint256(amount0Delta), uint256(-amount1Delta)) : (tokenOut < tokenIn, uint256(amount1Delta), uint256(-amount0Delta)); IUniswapV3Pool pool = getPool(tokenIn, tokenOut, fee); (uint160 sqrtPriceX96After, int24 tickAfter, , , , , ) = pool.slot0(); if (isExactInput) { assembly { let ptr := mload(0x40) mstore(ptr, amountReceived) mstore(add(ptr, 0x20), sqrtPriceX96After) mstore(add(ptr, 0x40), tickAfter) revert(ptr, 96) } } else { // if the cache has been populated, ensure that the full output amount has been received if (amountOutCached != 0) require(amountReceived == amountOutCached); assembly { let ptr := mload(0x40) mstore(ptr, amountToPay) mstore(add(ptr, 0x20), sqrtPriceX96After) mstore(add(ptr, 0x40), tickAfter) revert(ptr, 96) } } } /// @dev Parses a revert reason that should contain the numeric quote function parseRevertReason(bytes memory reason) private pure returns ( uint256 amount, uint160 sqrtPriceX96After, int24 tickAfter ) { if (reason.length != 96) { if (reason.length < 68) revert('Unexpected error'); assembly { reason := add(reason, 0x04) } revert(abi.decode(reason, (string))); } return abi.decode(reason, (uint256, uint160, int24)); } function handleRevert( bytes memory reason, IUniswapV3Pool pool, uint256 gasEstimate ) private view returns ( uint256 amount, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 ) { int24 tickBefore; int24 tickAfter; (, tickBefore, , , , , ) = pool.slot0(); (amount, sqrtPriceX96After, tickAfter) = parseRevertReason(reason); initializedTicksCrossed = pool.countInitializedTicksCrossed(tickBefore, tickAfter); return (amount, sqrtPriceX96After, initializedTicksCrossed, gasEstimate); } function quoteExactInputSingle(QuoteExactInputSingleParams memory params) public override returns ( uint256 amountOut, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate ) { bool zeroForOne = params.tokenIn < params.tokenOut; IUniswapV3Pool pool = getPool(params.tokenIn, params.tokenOut, params.fee); uint256 gasBefore = gasleft(); try pool.swap( address(this), // address(0) might cause issues with some tokens zeroForOne, params.amountIn.toInt256(), params.sqrtPriceLimitX96 == 0 ? (zeroForOne ? TickMath.MIN_SQRT_RATIO + 1 : TickMath.MAX_SQRT_RATIO - 1) : params.sqrtPriceLimitX96, abi.encodePacked(params.tokenIn, params.fee, params.tokenOut) ) {} catch (bytes memory reason) { gasEstimate = gasBefore - gasleft(); return handleRevert(reason, pool, gasEstimate); } } function quoteExactInput(bytes memory path, uint256 amountIn) public override returns ( uint256 amountOut, uint160[] memory sqrtPriceX96AfterList, uint32[] memory initializedTicksCrossedList, uint256 gasEstimate ) { sqrtPriceX96AfterList = new uint160[](path.numPools()); initializedTicksCrossedList = new uint32[](path.numPools()); uint256 i = 0; while (true) { (address tokenIn, address tokenOut, uint24 fee) = path.decodeFirstPool(); // the outputs of prior swaps become the inputs to subsequent ones (uint256 _amountOut, uint160 _sqrtPriceX96After, uint32 _initializedTicksCrossed, uint256 _gasEstimate) = quoteExactInputSingle( QuoteExactInputSingleParams({ tokenIn: tokenIn, tokenOut: tokenOut, fee: fee, amountIn: amountIn, sqrtPriceLimitX96: 0 }) ); sqrtPriceX96AfterList[i] = _sqrtPriceX96After; initializedTicksCrossedList[i] = _initializedTicksCrossed; amountIn = _amountOut; gasEstimate += _gasEstimate; i++; // decide whether to continue or terminate if (path.hasMultiplePools()) { path = path.skipToken(); } else { return (amountIn, sqrtPriceX96AfterList, initializedTicksCrossedList, gasEstimate); } } } function quoteExactOutputSingle(QuoteExactOutputSingleParams memory params) public override returns ( uint256 amountIn, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate ) { bool zeroForOne = params.tokenIn < params.tokenOut; IUniswapV3Pool pool = getPool(params.tokenIn, params.tokenOut, params.fee); // if no price limit has been specified, cache the output amount for comparison in the swap callback if (params.sqrtPriceLimitX96 == 0) amountOutCached = params.amount; uint256 gasBefore = gasleft(); try pool.swap( address(this), // address(0) might cause issues with some tokens zeroForOne, -params.amount.toInt256(), params.sqrtPriceLimitX96 == 0 ? (zeroForOne ? TickMath.MIN_SQRT_RATIO + 1 : TickMath.MAX_SQRT_RATIO - 1) : params.sqrtPriceLimitX96, abi.encodePacked(params.tokenOut, params.fee, params.tokenIn) ) {} catch (bytes memory reason) { gasEstimate = gasBefore - gasleft(); if (params.sqrtPriceLimitX96 == 0) delete amountOutCached; // clear cache return handleRevert(reason, pool, gasEstimate); } } function quoteExactOutput(bytes memory path, uint256 amountOut) public override returns ( uint256 amountIn, uint160[] memory sqrtPriceX96AfterList, uint32[] memory initializedTicksCrossedList, uint256 gasEstimate ) { sqrtPriceX96AfterList = new uint160[](path.numPools()); initializedTicksCrossedList = new uint32[](path.numPools()); uint256 i = 0; while (true) { (address tokenOut, address tokenIn, uint24 fee) = path.decodeFirstPool(); // the inputs of prior swaps become the outputs of subsequent ones (uint256 _amountIn, uint160 _sqrtPriceX96After, uint32 _initializedTicksCrossed, uint256 _gasEstimate) = quoteExactOutputSingle( QuoteExactOutputSingleParams({ tokenIn: tokenIn, tokenOut: tokenOut, amount: amountOut, fee: fee, sqrtPriceLimitX96: 0 }) ); sqrtPriceX96AfterList[i] = _sqrtPriceX96After; initializedTicksCrossedList[i] = _initializedTicksCrossed; amountOut = _amountIn; gasEstimate += _gasEstimate; i++; // decide whether to continue or terminate if (path.hasMultiplePools()) { path = path.skipToken(); } else { return (amountOut, sqrtPriceX96AfterList, initializedTicksCrossedList, gasEstimate); } } }}
im trying to make a utility that quotes using uniswaps QuoterV2 Contract:
This is the code i have so far:
- This should take in a hop not just a direct quote.
- It needs the actual logic to perform the quote:
import { Logger } from '@ethersproject/logger'; import { flags } from '@oclif/command'; import { Currency, QUOTER_ADDRESSES, V2_FACTORY_ADDRESSES, V2_FACTORY_INIT_HASH } from '@uniswap/sdk-core'; import dotenv from 'dotenv'; import _, { chain } from 'lodash';
import { ID_TO_CHAIN_ID, nativeOnChain, } from '../../src'; import { NATIVE_NAMES_BY_ID } from '../../src/util'; import { BaseCommand } from '../base-command'; import { computePairAddress } from '@uniswap/v2-sdk'; import { IQuoterV2__factory } from '../../src/types/v3/factories/IQuoterV2__factory';
dotenv.config();
Logger.globalLogger(); Logger.setLogLevel(Logger.levels.DEBUG);
export class QuoterUtils extends BaseCommand { static description = 'Uniswap Smart Order Router CLI';
static flags = { ...BaseCommand.flags, version: flags.version({ char: 'v' }), help: flags.help({ char: 'h' }), tokenIn: flags.string({ char: 'i', required: true }), tokenOut: flags.string({ char: 'o', required: true }), //protocols: flags.string({ required: false }), }; async run() { const { flags } = this.parse(QuoterUtils); const { tokenIn: tokenInStr, tokenOut: tokenOutStr, chainId: chainIdNumb, //protocols: protocolsStr, } = flags; const chainId = ID_TO_CHAIN_ID(chainIdNumb); const quoterAddress = QUOTER_ADDRESSES[chainId]; const tokenProvider = this.tokenProvider; // if the tokenIn str is 'ETH' or 'MATIC' or in NATIVE_NAMES_BY_ID const tokenIn: Currency = NATIVE_NAMES_BY_ID[chainId]!.includes(tokenInStr) ? nativeOnChain(chainId) : (await tokenProvider.getTokens([tokenInStr])).getTokenByAddress( tokenInStr )!; const tokenOut: Currency = NATIVE_NAMES_BY_ID[chainId]!.includes( tokenOutStr ) ? nativeOnChain(chainId) : (await tokenProvider.getTokens([tokenOutStr])).getTokenByAddress( tokenOutStr )!; var quoterInterface = IQuoterV2__factory.createInterface() }}
- Assistant
You're on the right path for building a CLI tool to use Uniswap's
QuoterV2contract to get swap quotes, including multi-hop routes. Below, I will walk you through:- 🧠 Understanding what's needed to quote with
QuoterV2 - 🔧 Building the path for multi-hop
- 📦 Encoding the call to
quoteExactInput(...) - 🖨️ Returning the quote result
✅ 1. Understanding
QuoterV2ABI BehaviorYou are using Uniswap V3’s
QuoterV2, which allows:- quoteExactInput(path, amountIn) – provides output amount for given input path and amount.
- quoteExactOutput(path, amountOut) – provides input amount needed to receive given output.
The input format for multi-hop is via encoded bytes path like:
path = [tokenIn (20 bytes)] + [fee (3 bytes)] + [tokenOut (20 bytes)] + [fee (3 bytes)] + ...You need to pack this off-chain using something like
utils.solidityPack.
🔧 2. Construct the Swap Path for Multi-hop
You can define a helper to encode the swap path in the correct format – a
bytessequence made oftoken + fee + token + ....import { utils } from 'ethers'; // Path encoding helper for multi-hop function encodePath(tokens: string[], fees: number[]): string { if (tokens.length !== fees.length + 1) { throw new Error('Path: invalid path length'); } let path = '0x'; for (let i = 0; i < fees.length; i++) { path += tokens[i].slice(2); // Remove '0x' path += utils.hexZeroPad(utils.hexlify(fees[i]), 3).slice(2); // fee: 3 bytes } path += tokens[tokens.length - 1].slice(2); // Final token return path; }
🧪 3. Call
quoteExactInputonQuoterV2Assuming users pass:
- Tokens:
tokenIn,tokenMiddle1,tokenOut - Fees:
[500, 3000](for 0.05%, then 0.3%)
Example steps:
import { ethers } from 'ethers'; import { IQuoterV2__factory } from '../../src/types/v3/factories/IQuoterV2__factory'; const provider = new ethers.providers.JsonRpcProvider(YOUR_RPC_URL); const quoter = IQuoterV2__factory.connect(quoterAddress, provider); // Tokens and fees const tokenAddrs = [tokenIn.address, middleToken.address, tokenOut.address]; const fees = [500, 3000]; // Example Uniswap fee tiers const path = encodePath(tokenAddrs, fees); const amountIn = utils.parseUnits('1', tokenIn.decimals); // e.g., quote for 1 tokenIn const quote = await quoter.quoteExactInput(path, amountIn);The return from
quoteExactInput()is a tuple:[ amountOut: BigNumber, sqrtPriceX96AfterList: BigNumber[], initializedTicksCrossedList: number[], gasEstimate: BigNumber ]
✍️ Complete It in
QuoterUtilsCommandHere’s how you would add this logic in your
async run():// Assume middleToken is optional (for single-hop, users just pass tokenIn/tokenOut) const tokenAddrs = [tokenIn.address, tokenOut.address]; const fees = [500]; // Single-hop 0.05% fee - realistic default or ask user to pass it const pathEncoded = encodePath(tokenAddrs, fees); const provider = new ethers.providers.JsonRpcProvider(process.env.RPC_URL;); const quoter = IQuoterV2__factory.connect(quoterAddress, provider); const amountIn = utils.parseUnits('1', tokenIn.decimals); // or take user input const [amountOut, sqrtPrices, ticksCrossed, gasEst] = await quoter.quoteExactInput( pathEncoded, amountIn ); this.log(`Amount In: ${utils.formatUnits(amountIn, tokenIn.decimals)} ${tokenIn.symbol}`); this.log(`Amount Out: ${utils.formatUnits(amountOut, tokenOut.decimals)} ${tokenOut.symbol}`); this.log(`Estimated Gas Used: ${gasEst.toString()}`);
📜 Optional: Take Fee Tiers and Hops from CLI
Add additional CLI input flags if you want to support:
- Multi-hop tokens like
--route WETH,USDC,UNI - Fees like
--fees 500,3000
Parsing those:
const route = flags.route.split(','); const fees = flags.fees.split(',').map(f => parseInt(f)); // Validate inputs if (route.length !== fees.length + 1) throw new Error('Route must have fees.length + 1 tokens'); // Fetch all tokens, including intermediate ones const tokens = await tokenProvider.getTokens(route); const addresses = route.map(r => tokens.getTokenBySymbolOrAddress(r).address);
🧼 Wrap-up
✅ Your final steps are:
- Build the path as encoded bytes for
quoteExactInput(...). - Handle CLI inputs dynamically for hops + fees.
- Format output decimals using token metadata.
- Add logging/CLI output.
Let me know if you'd like a complete boilerplate CLI implementation for single/multi-hop quoting or support for
quoteExactOutput. - 🧠 Understanding what's needed to quote with
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.