### Setup Viem Client for Uniswap v4 Interaction (TypeScript) Source: https://docs.uniswap.org/sdk/v4/guides/liquidity/position-fetching Initializes a viem public client configured for the Unichain, essential for interacting with Uniswap v4 smart contracts. It imports necessary components from 'viem' and defines the Position Manager contract address. ```typescript import { createPublicClient, http, Address, zeroAddress } from 'viem' import { unichain } from 'viem/chains' import request from 'graphql-request' const POSITION_MANAGER_ADDRESS = '0x4529a01c7a0410167c5740c487a8de60232617bf' //unichain const publicClient = createPublicClient({ chain: unichain, transport: http(), }) ``` -------------------------------- ### Define Example Configuration - TypeScript Source: https://docs.uniswap.org/sdk/v4/guides/advanced/pool-data Sets up an example configuration object 'CurrentConfig' for interacting with a Uniswap v4 pool. This includes environment, RPC endpoints, and pool key details like currency, fee, tick spacing, and hooks. Ensure a pool exists for the specified configuration. ```typescript export const CurrentConfig: ExampleConfig = { env: Environment.MAINNET, rpc: { local: 'http://localhost:8545', mainnet: 'https://mainnet.infura.io/v3/YOUR_API_KEY', }, ... poolKey: { currency0: USDC_TOKEN.address, currency1: ETH_TOKEN.address, fee: FEE_AMOUNT_LOW, tickSpacing: TICK_SPACING_TEN, hooks: EMPTY_HOOK, }, } ``` -------------------------------- ### Call PoolManager.initialize Function Source: https://docs.uniswap.org/sdk/v4/guides/advanced/create-pool Executes the initialization of a new Uniswap v4 pool by calling the `initialize` function on the PoolManager contract instance. This function requires the pool's unique key and the desired starting price, expressed as sqrtPriceX96. ```javascript const result = await poolManager.initialize( CurrentConfig.poolKey, startingPrice ) ``` -------------------------------- ### Construct SwapExactInSingle Configuration - TypeScript Source: https://docs.uniswap.org/sdk/v4/guides/swaps/quoting Defines the configuration for a `SwapExactInSingle` operation, including pool details, swap direction, and amounts. Requires `@uniswap/v4-sdk` and `@uniswap/sdk-core` packages. Inputs are a `PoolKey` object, `zeroForOne` boolean, `amountIn` string, and `hookData` string. ```typescript import { SwapExactInSingle } from '@uniswap/v4-sdk' import { USDC_TOKEN, ETH_TOKEN } from './constants' import { parseUnits, JsonRpcProvider, formatUnits } from 'ethers' export const CurrentConfig: SwapExactInSingle = { poolKey: { currency0: ETH_TOKEN.address, currency1: USDC_TOKEN.address, fee: 500, tickSpacing: 10, hooks: "0x0000000000000000000000000000000000000000", }, zeroForOne: true, amountIn: parseUnits('1', ETH_TOKEN.decimals).toString(), amountOutMinimum: "0", hookData: '0x00' } ``` -------------------------------- ### Fetch User Positions with Uniswap v4 SDK (TypeScript) Source: https://docs.uniswap.org/sdk/v4/guides/liquidity/position-fetching An example TypeScript function demonstrating how to fetch user positions on Unichain using the Uniswap v4 SDK. It retrieves position IDs from a subgraph and then fetches detailed information for each position, including token details, fee, range, liquidity, and hooks. It includes error handling for the asynchronous operations. ```typescript async function fetchUserPositions(userAddress: Address) { try { // Get position IDs from subgraph const tokenIds = await getPositionIds(userAddress) console.log(`Found ${tokenIds.length} positions on Unichain`) // Fetch details for each position for (const tokenId of tokenIds) { const details = await getPositionDetails(tokenId) console.log(`Position ${tokenId}:`) console.log(` Token0: ${details.poolKey.currency0}`) console.log(` Token1: ${details.poolKey.currency1}`) console.log(` Fee: ${details.poolKey.fee / 10000}%`) console.log(` Range: ${details.tickLower} to ${details.tickUpper}`) console.log(` Liquidity: ${details.liquidity.toString()}`) console.log(` Hooks: ${details.poolKey.hooks}`) console.log('---') } } catch (error) { console.error('Error:', error) } } // Example usage fetchUserPositions('0xYourAddress' as Address) ``` -------------------------------- ### Uniswap v4 Position Manager Contract ABI (TypeScript) Source: https://docs.uniswap.org/sdk/v4/guides/liquidity/position-fetching Defines the contract interface (ABI) for the Uniswap v4 Position Manager, specifying the 'getPoolAndPositionInfo' and 'getPositionLiquidity' functions. This ABI is used by viem to interact with the contract. ```typescript const POSITION_MANAGER_ABI = [ { name: 'getPoolAndPositionInfo', type: 'function', inputs: [{ name: 'tokenId', type: 'uint256' }], outputs: [ { name: 'poolKey', type: 'tuple', components: [ { name: 'currency0', type: 'address' }, { name: 'currency1', type: 'address' }, { name: 'fee', type: 'uint24' }, { name: 'tickSpacing', type: 'int24' }, { name: 'hooks', type: 'address' }, ], }, { name: 'info', type: 'uint256' }, ], }, { name: 'getPositionLiquidity', type: 'function', inputs: [{ name: 'tokenId', type: 'uint256' }], outputs: [{ name: 'liquidity', type: 'uint128' }], }, ] as const ``` -------------------------------- ### Instantiate Uniswap Quoter Contract using ethers.js Source: https://docs.uniswap.org/sdk/v4/guides/swaps/quoting Constructs an ethers.js Contract instance for the Uniswap Quoter contract. Requires the contract address, ABI, and an RPC provider for the target chain. This instance is used to interact with the Quoter contract's functionalities. ```javascript const quoterContract = new ethers.Contract( QUOTER_CONTRACT_ADDRESS, QUOTER_ABI, // Import or define the ABI for Quoter contract new JsonRpcProvider("RPC") // Provide the right RPC address for the chain ) ``` -------------------------------- ### Complete Add/Remove Liquidity Workflow (TypeScript) Source: https://docs.uniswap.org/sdk/v4/guides/liquidity/add-remove-liquidity Demonstrates a full workflow involving adding and then removing liquidity from a Uniswap v4 position. It includes fetching position details, adding liquidity, waiting, and then removing a specified percentage of liquidity with configurable slippage tolerance and burn token option. This example relies on external functions like `getPositionDetails`, `addLiquidityToPosition`, and assumes the presence of `walletClient`, `POSITION_MANAGER_ADDRESS`, `unichain`, and `POSITION_MANAGER_ABI`. ```typescript async function completeAddRemoveWorkflow() { const tokenId = 123456n // 1. Fetch position details const positionDetails = await getPositionDetails(tokenId) console.log(`Position: ${positionDetails.token0.symbol}/${positionDetails.token1.symbol}`) // 2. Add liquidity const addResult = await addLiquidityToPosition( positionDetails, '1000000000000000', // 0.001 ETH '1000000', // 1 USDC 0.05 // 5% slippage ) console.log(`Added liquidity: ${addResult.txHash}`) // 3. Wait and verify await new Promise((resolve) => setTimeout(resolve, 5000)) const updatedPosition = await getPositionDetails(tokenId) // 4. Remove 50% of liquidity const removeResult = await removeLiquidityFromPosition( updatedPosition, 0.5, // 50% 0.05, // 5% slippage false // don't burn token ) console.log(`Removed 50% liquidity: ${removeResult.txHash}`) return { addResult, removeResult } } ``` -------------------------------- ### Fetch Tick Bitmaps using Multicall (TypeScript) Source: https://docs.uniswap.org/sdk/v4/guides/advanced/pool-data This example shows how to prepare and execute multicall requests to fetch tick bitmaps. It iterates through all possible word positions, adds a `getTickBitmap` call for each, and then sends all calls in a single RPC request. ```typescript let calls: any[] = []; let wordPosIndices: number[] = []; const poolId = 'POOL_ID'; // Replace with the Pool ID for (let i = minWord; i <= maxWord; i++) { wordPosIndices.push(i); calls.push(stateViewContract.getTickBitmap(poolId, i)); } const results: bigint[] = (await multicallProvider.all(calls)).map( (ethersResponse) => { return BigInt(ethersResponse.toString()); } ); ``` -------------------------------- ### Define ETH and USDC Tokens - TypeScript Source: https://docs.uniswap.org/sdk/v4/guides/swaps/quoting Defines `Token` objects for ETH and USDC, including their chain ID, address, decimals, symbol, and name. Requires `@uniswap/sdk-core`. This is used for constructing `PoolKey` objects. ```typescript import { Token, ChainId } from '@uniswap/sdk-core' export const ETH_TOKEN = new Token( ChainId.MAINNET, '0x0000000000000000000000000000000000000000', 18, 'ETH', 'Ether' ) export const USDC_TOKEN = new Token( ChainId.MAINNET, '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', 6, 'USDC', 'USDC' ) ``` -------------------------------- ### Configure Uniswap v4 MintOptions in TypeScript Source: https://docs.uniswap.org/sdk/v4/guides/liquidity/position-minting This example demonstrates how to construct `MintOptions` for Uniswap v4 in TypeScript. It covers setting required parameters like `recipient`, `slippageTolerance`, and `deadline`, as well as optional parameters such as `useNative`, `hookData`, and configurations for creating new pools or migrating from v3. ```typescript import { Percent } from '@uniswap/sdk-core'; import { MintOptions } from '@uniswap/v4-sdk'; // Placeholder for publicClient and ETH_TOKEN/USDC_TOKEN, assumed to be defined elsewhere. // const publicClient = ...; // const ETH_TOKEN = ...; // const USDC_TOKEN = ...; // Example code showing how to set up MintOptions // These parameters typically come from user input or application state // 1. slippageTolerance (required): Maximum allowed price movement // Convert from a percentage (e.g., 0.5%) to a Percent object // Here, 50 out of 10000 = 0.5% const slippageTolerance = 0.5; // 0.5% slippage tolerance const slippagePct = new Percent(Math.floor(slippageTolerance * 100), 10000); // 2. deadline (required): Transaction expiry timestamp in seconds // Usually current time + some buffer (e.g., 20 minutes) const deadlineSeconds = 20 * 60; // 20 minutes // Assuming publicClient.getBlock() returns a promise with a timestamp // const currentBlock = await publicClient.getBlock(); // const currentBlockTimestamp = Number(currentBlock.timestamp); const mockCurrentTimestamp = Math.floor(Date.now() / 1000); const deadline = mockCurrentTimestamp + deadlineSeconds; // 3. recipient (required): Address to receive the position NFT // Typically the user's wallet address const userAddress = '0xYourAddressHere'; // Replace with actual user address // Create the basic MintOptions object with required fields const mintOptions: MintOptions = { recipient: userAddress, slippageTolerance: slippagePct, deadline: deadline.toString(), // 4. useNative (optional): Use native ETH // Placeholder logic for determining useNative useNative: undefined, // Set based on actual token properties if available // 5. batchPermit (optional): For gasless approvals via Permit2 // batchPermit: { ... }, // Set if needed // 6. hookData (optional): Data for pool hooks hookData: '0x', // Default empty bytes // 7-8. For new pools only: // createPool: true, // Uncomment if creating a new pool // sqrtPriceX96: '1234567890123456789', // Initial price, required if createPool is true // 9. For migrations only: // migrate: false, // Normally omitted unless migrating from v3 }; console.log(mintOptions); ``` -------------------------------- ### Simulate Exact Input Swap with Uniswap Quoter using ethers.js callStatic Source: https://docs.uniswap.org/sdk/v4/guides/swaps/quoting Obtains a quote for an exact input amount using the Quoter contract's `quoteExactInputSingle` method via `callStatic`. This simulates a state-changing transaction without executing it on-chain, returning the expected output amount. Requires `poolKey`, `zeroForOne`, `exactAmount`, and `hookData` from `CurrentConfig`. ```javascript const quotedAmountOut = await quoterContract.callStatic.quoteExactInputSingle({ poolKey: CurrentConfig.poolKey, zeroForOne: CurrentConfig.zeroForOne, exactAmount: CurrentConfig.amountIn, hookData: CurrentConfig.hookData, }) console.log(formatUnits(quotedAmountOut.amountOut, USDC_TOKEN.decimals)); ``` -------------------------------- ### V4Planner Constructor Source: https://docs.uniswap.org/sdk/v4/reference/classes/V4Planner Initializes a new V4Planner instance. ```APIDOC ## V4Planner Constructor ### Description Initializes a new instance of the V4Planner class. ### Method `new V4Planner()` ### Endpoint N/A (Class Constructor) ### Parameters None ### Request Example ```javascript const planner = new V4Planner(); ``` ### Response #### Success Response - **planner** (`V4Planner`) - A new instance of V4Planner. #### Response Example ```json // No direct JSON response for constructor, returns an object instance ``` ``` -------------------------------- ### V4Planner Methods Source: https://docs.uniswap.org/sdk/v4/reference/classes/V4Planner Documentation for the methods available on the V4Planner class. ```APIDOC ## V4Planner Methods ### addAction() #### Description Adds an action to the planner. #### Method `addAction(type: Actions, parameters: any[])` #### Endpoint N/A #### Parameters - **type** (`Actions`) - The type of action to add. - **parameters** (`any[]`) - An array of parameters for the action. #### Returns - `V4Planner` - The V4Planner instance for chaining. ### addSettle() #### Description Adds a settlement instruction to the planner. #### Method `addSettle(currency: Currency, payerIsUser: boolean, amount?: BigNumber)` #### Endpoint N/A #### Parameters - **currency** (`Currency`) - The currency to settle. - **payerIsUser** (`boolean`) - Whether the payer is the user. - **amount** (`BigNumber`, Optional) - The amount to settle. #### Returns - `V4Planner` - The V4Planner instance for chaining. ### addTake() #### Description Adds a take instruction to the planner. #### Method `addTake(currency: Currency, recipient: string, amount?: BigNumber)` #### Endpoint N/A #### Parameters - **currency** (`Currency`) - The currency to take. - **recipient** (`string`) - The address of the recipient. - **amount** (`BigNumber`, Optional) - The amount to take. #### Returns - `V4Planner` - The V4Planner instance for chaining. ### addTrade() #### Description Adds a trade to the planner. #### Method `addTrade(trade: Trade, slippageTolerance?: Percent)` #### Endpoint N/A #### Parameters - **trade** (`Trade`) - The trade object to add. - **slippageTolerance** (`Percent`, Optional) - The slippage tolerance for the trade. #### Returns - `V4Planner` - The V4Planner instance for chaining. ### finalize() #### Description Finalizes the plan and returns a string representation. #### Method `finalize(): string` #### Endpoint N/A #### Parameters None #### Returns - `string` - A string representing the finalized plan. ``` -------------------------------- ### getPoolKey() Source: https://docs.uniswap.org/sdk/v4/reference/classes/Pool Static method to get the pool key, which uniquely identifies a pool. ```APIDOC ## GET /getPoolKey ### Description Generates a unique key for a pool based on its currencies, fee, tick spacing, and hooks. ### Method GET ### Endpoint /getPoolKey ### Parameters #### Query Parameters - **currencyA** (Currency) - Required - The first currency in the pool. - **currencyB** (Currency) - Required - The second currency in the pool. - **fee** (number) - Required - The fee tier for the pool. - **tickSpacing** (number) - Required - The tick spacing for the pool. - **hooks** (string) - Required - The hooks associated with the pool. ### Request Example ```json { "currencyA": "USDC", "currencyB": "WETH", "fee": 0.05, "tickSpacing": 60, "hooks": "0x..." } ``` ### Response #### Success Response (200) - **poolKey** (PoolKey) - The unique key identifying the pool. #### Response Example ```json { "poolKey": { "currencyA": "USDC", "currencyB": "WETH", "fee": 0.05, "tickSpacing": 60, "hooks": "0x..." } } ``` ``` -------------------------------- ### getPoolId() Source: https://docs.uniswap.org/sdk/v4/reference/classes/Pool Static method to get the unique pool ID based on currency, fee, tick spacing, and hooks. ```APIDOC ## GET /getPoolId ### Description Retrieves the unique identifier for a pool given its constituent currencies, fee, tick spacing, and hooks. ### Method GET ### Endpoint /getPoolId ### Parameters #### Query Parameters - **currencyA** (Currency) - Required - The first currency in the pool. - **currencyB** (Currency) - Required - The second currency in the pool. - **fee** (number) - Required - The fee tier for the pool. - **tickSpacing** (number) - Required - The tick spacing for the pool. - **hooks** (string) - Required - The hooks associated with the pool. ### Request Example ```json { "currencyA": "USDC", "currencyB": "WETH", "fee": 0.05, "tickSpacing": 60, "hooks": "0x..." } ``` ### Response #### Success Response (200) - **poolId** (string) - The unique identifier for the pool. #### Response Example ```json { "poolId": "0xabc123..." } ``` ``` -------------------------------- ### V4Planner Properties Source: https://docs.uniswap.org/sdk/v4/reference/classes/V4Planner Details about the properties of the V4Planner class. ```APIDOC ## V4Planner Properties ### Description Properties available on the V4Planner instance. ### Properties #### actions - **actions** (`string`) - Represents the actions to be performed. #### params - **params** (`string[]`) - An array of parameters for the planner. ``` -------------------------------- ### Get Path Currency (TypeScript) Source: https://docs.uniswap.org/sdk/v4/reference/overview Retrieves the currency associated with a specific path and pool. This utility helps in identifying the correct currency within a trading path. ```typescript function getPathCurrency(currency: Currency, pool: Pool): Currency ``` -------------------------------- ### V4PositionPlanner Methods Source: https://docs.uniswap.org/sdk/v4/reference/classes/V4PositionPlanner This section details the various methods provided by the V4PositionPlanner class for interacting with Uniswap v4 liquidity pools. ```APIDOC ## V4PositionPlanner Class Methods ### addMint() Adds a mint action to the planner. #### Method POST #### Endpoint /v4/positionplanner/mint #### Parameters ##### Path Parameters None ##### Query Parameters None ##### Request Body - **pool** (Pool) - Required - The pool details. - **tickLower** (number) - Required - The lower tick. - **tickUpper** (number) - Required - The upper tick. - **liquidity** (BigintIsh) - Required - The amount of liquidity to mint. - **amount0Max** (BigintIsh) - Required - The maximum amount of token0. - **amount1Max** (BigintIsh) - Required - The maximum amount of token1. - **owner** (string) - Required - The owner of the position. - **hookData** (string) - Optional - Hook data, defaults to EMPTY_BYTES. ### Request Example ```json { "pool": "...", "tickLower": 100, "tickUpper": 200, "liquidity": "1000000000000000000", "amount0Max": "1000000000000000000", "amount1Max": "1000000000000000000", "owner": "0x...", "hookData": "0x..." } ``` #### Response Example (This method returns void, indicating success if no error is thrown) --- ### addIncrease() Adds an increase liquidity action to the planner. #### Method POST #### Endpoint /v4/positionplanner/increase #### Parameters ##### Path Parameters None ##### Query Parameters None ##### Request Body - **tokenId** (BigintIsh) - Required - The ID of the token. - **liquidity** (BigintIsh) - Required - The amount of liquidity to add. - **amount0Max** (BigintIsh) - Required - The maximum amount of token0. - **amount1Max** (BigintIsh) - Required - The maximum amount of token1. - **hookData** (string) - Optional - Hook data, defaults to EMPTY_BYTES. #### Response Example (This method returns void, indicating success if no error is thrown) --- ### addDecrease() Adds a decrease liquidity action to the planner. #### Method POST #### Endpoint /v4/positionplanner/decrease #### Parameters ##### Path Parameters None ##### Query Parameters None ##### Request Body - **tokenId** (BigintIsh) - Required - The ID of the token. - **liquidity** (BigintIsh) - Required - The amount of liquidity to decrease. - **amount0Min** (BigintIsh) - Required - The minimum amount of token0. - **amount1Min** (BigintIsh) - Required - The minimum amount of token1. - **hookData** (string) - Optional - Hook data, defaults to EMPTY_BYTES. #### Response Example (This method returns void, indicating success if no error is thrown) --- ### addBurn() Adds a burn action to the planner. This is typically used for removing all liquidity associated with a position. #### Method POST #### Endpoint /v4/positionplanner/burn #### Parameters ##### Path Parameters None ##### Query Parameters None ##### Request Body - **tokenId** (BigintIsh) - Required - The ID of the token. - **amount0Min** (BigintIsh) - Required - The minimum amount of token0 to receive. - **amount1Min** (BigintIsh) - Required - The minimum amount of token1 to receive. - **hookData** (string) - Optional - Hook data, defaults to EMPTY_BYTES. #### Response Example (This method returns void, indicating success if no error is thrown) --- ### addSettlePair() Adds a settle pair action to the planner. #### Method POST #### Endpoint /v4/positionplanner/settle_pair #### Parameters ##### Path Parameters None ##### Query Parameters None ##### Request Body - **currency0** (Currency) - Required - The first currency. - **currency1** (Currency) - Required - The second currency. #### Response Example (This method returns void, indicating success if no error is thrown) --- ### addSweep() Adds a sweep action to the planner. #### Method POST #### Endpoint /v4/positionplanner/sweep #### Parameters ##### Path Parameters None ##### Query Parameters None ##### Request Body - **currency** (Currency) - Required - The currency to sweep. - **to** (string) - Required - The recipient address. #### Response Example (This method returns void, indicating success if no error is thrown) --- ### addTakePair() Adds a take pair action to the planner. #### Method POST #### Endpoint /v4/positionplanner/take_pair #### Parameters ##### Path Parameters None ##### Query Parameters None ##### Request Body - **currency0** (Currency) - Required - The first currency. - **currency1** (Currency) - Required - The second currency. - **recipient** (string) - Required - The recipient address. #### Response Example (This method returns void, indicating success if no error is thrown) --- ### addSweep() Adds a sweep action to the planner. (This appears to be a duplicate description, check source) #### Method POST #### Endpoint /v4/positionplanner/sweep #### Parameters ##### Path Parameters None ##### Query Parameters None ##### Request Body - **currency** (Currency) - Required - The currency to sweep. - **to** (string) - Required - The recipient address. #### Response Example (This method returns void, indicating success if no error is thrown) --- ### addAction() Adds a generic action to the planner. #### Method POST #### Endpoint /v4/positionplanner/action #### Parameters ##### Path Parameters None ##### Query Parameters None ##### Request Body - **type** (Actions) - Required - The type of action. - **parameters** (any[]) - Required - An array of parameters for the action. #### Response Example (This method returns V4Planner, indicating the planner instance for chaining) --- ### addSettle() Adds a settle action to the planner. #### Method POST #### Endpoint /v4/positionplanner/settle #### Parameters ##### Path Parameters None ##### Query Parameters None ##### Request Body - **currency** (Currency) - Required - The currency to settle. - **payerIsUser** (boolean) - Required - Whether the payer is the user. - **amount** (BigNumber) - Optional - The amount to settle. #### Response Example (This method returns V4Planner, indicating the planner instance for chaining) --- ### addTake() Adds a take action to the planner. #### Method POST #### Endpoint /v4/positionplanner/take #### Parameters ##### Path Parameters None ##### Query Parameters None ##### Request Body - **currency** (Currency) - Required - The currency to take. - **recipient** (string) - Required - The recipient address. - **amount** (BigNumber) - Optional - The amount to take. #### Response Example (This method returns V4Planner, indicating the planner instance for chaining) --- ### addTrade() Adds a trade action to the planner. #### Method POST #### Endpoint /v4/positionplanner/trade #### Parameters ##### Path Parameters None ##### Query Parameters None ##### Request Body - **trade** (Trade) - Required - The trade object. - **slippageTolerance** (Percent) - Optional - The slippage tolerance. #### Response Example (This method returns V4Planner, indicating the planner instance for chaining) --- ### finalize() Finalizes the plan and returns the encoded transaction data. #### Method GET #### Endpoint /v4/positionplanner/finalize #### Parameters None #### Response Example ```json { "transactionData": "0x..." } ``` ``` -------------------------------- ### Get Chain ID from Route - TypeScript Source: https://docs.uniswap.org/sdk/v4/reference/classes/Route Retrieves the chain ID associated with the Route. This is determined by the chain ID of the pools within the route, ensuring consistency in network operations. ```typescript const chainId: number = route.chainId; ``` -------------------------------- ### Initialize Uniswap v4 Contracts and ABIs (JavaScript) Source: https://docs.uniswap.org/sdk/v4/guides/swaps/multi-hop-swapping This snippet shows how to define the contract addresses and ABIs for the Universal Router and Permit2, which are essential for interacting with Uniswap v4. These constants are prerequisites for executing swaps. ```javascript const UNIVERSAL_ROUTER_ADDRESS = "0x66a9893cC07D91D95644AEDD05D03f95e1dBA8Af" const PERMIT2_ADDRESS = "0x000000000022D473030F116dDEE9F6B43aC78BA3" // ABIs remain the same as in single-hop guide const UNIVERSAL_ROUTER_ABI = [/* ... */] const ERC20_ABI = [/* ... */] const PERMIT2_ABI = [/* ... */] ``` -------------------------------- ### Get Price Boundaries - Uniswap V4 SDK Source: https://docs.uniswap.org/sdk/v4/reference/classes/Position Retrieves the price of token0 at the lower and upper tick boundaries of the position. These accessors provide insights into the price range sensitivity of the position. ```typescript import { Position } from "@uniswap/v4-sdk" const lowerPrice = position.token0PriceLower const upperPrice = position.token0PriceUpper ``` -------------------------------- ### Get NFT Permit Data - V4PositionManager Source: https://docs.uniswap.org/sdk/v4/reference/classes/V4PositionManager Retrieves data necessary for an NFT permit, which is used for authorizing actions on NFT-based positions. It requires permit values, the position manager's address, and the chain ID. ```typescript static getPermitData( permit: NFTPermitValues, positionManagerAddress: string, chainId: number ): NFTPermitData ``` -------------------------------- ### Execute Multi-Hop Swap with Uniswap SDK v4 (JavaScript) Source: https://docs.uniswap.org/sdk/v4/guides/swaps/multi-hop-swapping This code demonstrates the core logic for executing a multi-hop swap using the Uniswap SDK v4. It involves creating planners, adding swap actions, encoding them, and sending the transaction via the Universal Router. It handles native ETH input with `txOptions`. ```javascript import { Actions, V4Planner } from '@uniswap/v4-sdk' import { CommandType, RoutePlanner } from '@uniswap/universal-router-sdk' const v4Planner = new V4Planner() const routePlanner = new RoutePlanner() const deadline = Math.floor(Date.now() / 1000) + 3600 v4Planner.addAction(Actions.SWAP_EXACT_IN, [CurrentConfig]); v4Planner.addAction(Actions.SETTLE_ALL, [ETH_USDC_POOL_KEY.currency0, CurrentConfig.amountIn]); v4Planner.addAction(Actions.TAKE_ALL, [USDC_USDT_POOL_KEY.currency1, CurrentConfig.amountOutMinimum]); const encodedActions = v4Planner.finalize() routePlanner.addCommand(CommandType.V4_SWAP, [v4Planner.actions, v4Planner.params]) // Only needed for native ETH as input currency swaps const txOptions: any = { value: CurrentConfig.amountIn } const tx = await universalRouter.execute( routePlanner.commands, [encodedActions], deadline, txOptions ) const receipt = await tx.wait() console.log('Multi-hop swap completed! Transaction hash:', receipt.transactionHash) ``` -------------------------------- ### Trade Construction from Routes Source: https://docs.uniswap.org/sdk/v4/reference/classes/Trade This section describes the `fromRoutes` static method used to construct a trade by simulating swaps through provided routes. It outlines the type parameters, required parameters, and the expected return type. ```APIDOC ## static fromRoutes() ### Description Constructs a trade from routes by simulating swaps. ### Method `static` ### Endpoint `entities/trade.ts:272` ### Type Parameters - **`TInput`** (_extends `Currency`) - The input currency, either Ether or an ERC-20. - **`TOutput`** (_extends `Currency`) - The output currency, either Ether or an ERC-20. - **`TTradeType`** (_extends `TradeType`) - The type of the trade, either exact in or exact out. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "routes": [ { "route": ">", "amount": " : CurrencyAmount>" } ], "tradeType": "" } ``` ### Response #### Success Response (200) - **Trade** (`Trade`) - The constructed trade object. #### Response Example ```json { "trade": "" } ``` ``` -------------------------------- ### Get Mid Price of Route - TypeScript Source: https://docs.uniswap.org/sdk/v4/reference/classes/Route Calculates the mid-price for a given Route, representing the exchange rate between the input and output currencies considering the specified pools. This is useful for understanding the current market price before a swap. ```typescript import { Price } from "@uniswap/v4-sdk"; const midPrice: Price = route.midPrice; ``` -------------------------------- ### Get Token Amounts At Current Price - Uniswap V4 SDK Source: https://docs.uniswap.org/sdk/v4/reference/classes/Position Calculates the amount of token0 or token1 that the position's liquidity could be burned for at the current pool price. These accessors are crucial for understanding the potential value of a position. ```typescript import { Position } from "@uniswap/v4-sdk" const amount0 = position.amount0 const amount1 = position.amount1 ``` -------------------------------- ### Configure Pool Initialization Parameters Source: https://docs.uniswap.org/sdk/v4/guides/advanced/create-pool Defines the configuration object for initializing a Uniswap v4 pool. It includes environment settings, RPC endpoints, and the unique pool key comprising currencies, fee, tick spacing, and hook contract address. Ensure currencies are sorted and the fee is expressed in pips. ```typescript export const CurrentConfig: ExampleConfig = { env: Environment.MAINNET, rpc: { local: 'http://localhost:8545', mainnet: 'https://mainnet.infura.io/v3/YOUR_API_KEY', }, ... poolKey: { currency0: currency0, currency1: currency1, fee: lpFee, tickSpacing: tickSpacing, hooks: HOOK_CONTRACT_ADDRESS, }, } ``` -------------------------------- ### Trade Creation and Simulation Source: https://docs.uniswap.org/sdk/v4/reference/classes/Trade Methods for creating and simulating trades, including exact input, exact output, and unchecked trade creation. ```APIDOC ## POST /trades/exactIn ### Description Constructs an exact in trade with the given amount in and route. ### Method POST ### Endpoint /trades/exactIn ### Parameters #### Query Parameters - **route** (Route) - Required - The route of the exact in trade. - **amountIn** (CurrencyAmount) - Required - The amount being passed in. ### Request Example ```json { "route": { "pools": [], "tokenPath": [], "blockNumber": 1234567 }, "amountIn": { "numerator": "1000000000000000000", "denominator": "1", "currency": { "decimals": 18, "symbol": "WETH", "name": "Wrapped Ether" } } } ``` ### Response #### Success Response (200) - **Trade** - The exact in trade. #### Response Example ```json { "route": { "pools": [], "tokenPath": [], "blockNumber": 1234567 }, "inputAmount": { "numerator": "1000000000000000000", "denominator": "1", "currency": { "decimals": 18, "symbol": "WETH", "name": "Wrapped Ether" } }, "outputAmount": { "numerator": "990000000000000000", "denominator": "1", "currency": { "decimals": 6, "symbol": "USDC", "name": "USD Coin" } }, "tradeType": "EXACT_INPUT" } ``` ``` ```APIDOC ## POST /trades/exactOut ### Description Constructs an exact out trade with the given amount out and route. ### Method POST ### Endpoint /trades/exactOut ### Parameters #### Query Parameters - **route** (Route) - Required - The route of the exact out trade. - **amountOut** (CurrencyAmount) - Required - The amount returned by the trade. ### Request Example ```json { "route": { "pools": [], "tokenPath": [], "blockNumber": 1234567 }, "amountOut": { "numerator": "990000000000000000", "denominator": "1", "currency": { "decimals": 6, "symbol": "USDC", "name": "USD Coin" } } } ``` ### Response #### Success Response (200) - **Trade** - The exact out trade. #### Response Example ```json { "route": { "pools": [], "tokenPath": [], "blockNumber": 1234567 }, "inputAmount": { "numerator": "1000000000000000000", "denominator": "1", "currency": { "decimals": 18, "symbol": "WETH", "name": "Wrapped Ether" } }, "outputAmount": { "numerator": "990000000000000000", "denominator": "1", "currency": { "decimals": 6, "symbol": "USDC", "name": "USD Coin" } }, "tradeType": "EXACT_OUTPUT" } ``` ``` ```APIDOC ## POST /trades/unchecked ### Description Creates a trade without computing the result of swapping through the route. Useful when you have simulated the trade elsewhere and do not have any tick data. ### Method POST ### Endpoint /trades/unchecked ### Parameters #### Request Body - **constructorArguments** (object) - Required - The arguments passed to the trade constructor. - **inputAmount** (CurrencyAmount) - Required - The input amount. - **outputAmount** (CurrencyAmount) - Required - The output amount. - **route** (Route) - Required - The route. - **tradeType** (TTradeType) - Required - The type of the trade. ### Request Example ```json { "constructorArguments": { "inputAmount": { "numerator": "1000000000000000000", "denominator": "1", "currency": { "decimals": 18, "symbol": "WETH", "name": "Wrapped Ether" } }, "outputAmount": { "numerator": "990000000000000000", "denominator": "1", "currency": { "decimals": 6, "symbol": "USDC", "name": "USD Coin" } }, "route": { "pools": [], "tokenPath": [], "blockNumber": 1234567 }, "tradeType": "EXACT_INPUT" } } ``` ### Response #### Success Response (200) - **Trade** - The unchecked trade. #### Response Example ```json { "route": { "pools": [], "tokenPath": [], "blockNumber": 1234567 }, "inputAmount": { "numerator": "1000000000000000000", "denominator": "1", "currency": { "decimals": 18, "symbol": "WETH", "name": "Wrapped Ether" } }, "outputAmount": { "numerator": "990000000000000000", "denominator": "1", "currency": { "decimals": 6, "symbol": "USDC", "name": "USD Coin" } }, "tradeType": "EXACT_INPUT" } ``` ``` ```APIDOC ## POST /trades/unchecked/multiple ### Description Creates a trade without computing the result of swapping through the routes. Useful when you have simulated the trade elsewhere and do not have any tick data. ### Method POST ### Endpoint /trades/unchecked/multiple ### Parameters #### Request Body - **constructorArguments** (object) - Required - The arguments passed to the trade constructor. - **routes** (object[]) - Required - The routes. - **tradeType** (TTradeType) - Required - The type of the trade. ### Request Example ```json { "constructorArguments": { "routes": [ { "pools": [], "tokenPath": [], "blockNumber": 1234567 } ], "tradeType": "EXACT_INPUT" } } ``` ### Response #### Success Response (200) - **Trade** - The unchecked trade. #### Response Example ```json { "route": { "pools": [], "tokenPath": [], "blockNumber": 1234567 }, "inputAmount": { "numerator": "1000000000000000000", "denominator": "1", "currency": { "decimals": 18, "symbol": "WETH", "name": "Wrapped Ether" } }, "outputAmount": { "numerator": "990000000000000000", "denominator": "1", "currency": { "decimals": 6, "symbol": "USDC", "name": "USD Coin" } }, "tradeType": "EXACT_INPUT" } ``` ``` ```APIDOC ## POST /trades/fromRoute ### Description Constructs a trade by simulating swaps through the given route. ### Method POST ### Endpoint /trades/fromRoute ### Parameters #### Request Body - **route** (Route) - Required - The route. - **amount** (CurrencyAmount) - Required - The amount. - **tradeType** (TTradeType) - Required - The type of trade. ### Request Example ```json { "route": { "pools": [], "tokenPath": [], "blockNumber": 1234567 }, "amount": { "numerator": "1000000000000000000", "denominator": "1", "currency": { "decimals": 18, "symbol": "WETH", "name": "Wrapped Ether" } }, "tradeType": "EXACT_INPUT" } ``` ### Response #### Success Response (200) - **Trade** - The constructed trade. #### Response Example ```json { "route": { "pools": [], "tokenPath": [], "blockNumber": 1234567 }, "inputAmount": { "numerator": "1000000000000000000", "denominator": "1", "currency": { "decimals": 18, "symbol": "WETH", "name": "Wrapped Ether" } }, "outputAmount": { "numerator": "990000000000000000", "denominator": "1", "currency": { "decimals": 6, "symbol": "USDC", "name": "USD Coin" } }, "tradeType": "EXACT_INPUT" } ``` ``` -------------------------------- ### Get Position Amounts - Uniswap V4 SDK Source: https://docs.uniswap.org/sdk/v4/reference/classes/Position Retrieves the minimum amounts of token0 and token1 that must be provided to mint the liquidity held by the position at the current pool price. This accessor is useful for understanding the capital required to establish a position. ```typescript import { Position } from "@uniswap/v4-sdk" const mintAmounts = position.mintAmounts ```