### Import Uniswap V4 SDK Prelude in Rust Source: https://github.com/shuhuiluo/uniswap-v4-sdk-rs/blob/main/README.md This Rust code demonstrates how to import the prelude of the uniswap-v4-sdk crate. Using the prelude provides easy access to commonly used types and traits, simplifying the process of interacting with the SDK in your applications. This is the recommended way to start using the SDK for common tasks. ```rust use uniswap_v4_sdk::prelude::*; ``` -------------------------------- ### Find Best Trade Routes using Uniswap V4 SDK Source: https://context7.com/shuhuiluo/uniswap-v4-sdk-rs/llms.txt Provides an example of how to find the best possible trade routes for an exact input amount across multiple pools, considering a maximum number of results and hops. This function is essential for optimizing trade execution. Dependencies include `uniswap_v4_sdk` and `uniswap_sdk_core`. ```rust use uniswap_v4_sdk::prelude::*; // Find best routes for exact input let pools = vec![ pool_token0_token1.clone(), pool_token0_token2.clone(), pool_token1_token2.clone(), ]; let currency_amount_in = CurrencyAmount::from_raw_amount(token0.clone(), 10_000)?; let currency_out = &token2; let mut best_trades = vec![]; let options = BestTradeOptions { max_num_results: Some(3), max_hops: Some(3), }; Trade::best_trade_exact_in( pools.clone(), ¤cy_amount_in, currency_out, options, vec![], None, &mut best_trades, ).await?; // Iterate through best trades for (i, trade) in best_trades.iter().enumerate() { println!("Trade {}: {} -> {}", i + 1, trade.input_amount()?.to_significant(6, None)?, trade.output_amount()?.to_significant(6, None)? ); println!(" Price Impact: {}%", trade.price_impact()?.to_significant(2, None)?); } ``` -------------------------------- ### Run Rust Linting with Clippy Source: https://github.com/shuhuiluo/uniswap-v4-sdk-rs/blob/main/README.md This command runs the clippy linter on all targets and features of your Rust project, with a strict setting to treat warnings as errors. It helps enforce code quality, style, and potential common mistakes. Ensure clippy is installed and configured for your project. ```shell cargo clippy --all-targets --all-features -- -D warnings ``` -------------------------------- ### Removing Liquidity from Uniswap V4 Position Source: https://context7.com/shuhuiluo/uniswap-v4-sdk-rs/llms.txt Provides an example of encoding a transaction to remove liquidity from an existing position in Uniswap V4. Users can specify the percentage of liquidity to remove and whether to burn the NFT upon full removal. ```rust use uniswap_v4_sdk::prelude::*; let position = Position::new(pool.clone(), 1_000_000, -60, 60); // Remove 50% of liquidity let options = RemoveLiquidityOptions { common_opts: CommonOptions { slippage_tolerance: Percent::new(5, 1000), deadline: U256::from(1234567890), hook_data: Bytes::default(), }, token_id: U256::from(42), liquidity_percentage: Percent::new(50, 100), // 50% burn_token: false, // set true to burn NFT when removing 100% permit: None, }; let method_params = remove_call_parameters(&position, options)?; println!("Remove liquidity calldata: {:?}", method_params.calldata); ``` -------------------------------- ### Create Exact Output Trades using Uniswap V4 SDK Source: https://context7.com/shuhuiluo/uniswap-v4-sdk-rs/llms.txt Demonstrates how to create an exact output trade, specifying the desired amount of a token to receive and calculating the maximum input required. This snippet also shows how to determine the maximum input considering slippage and the worst-case execution price. Dependencies include `uniswap_v4_sdk`. ```rust use uniswap_v4_sdk::prelude::*; // Create exact output trade let output_amount = CurrencyAmount::from_raw_amount(weth.clone(), 1_000_000_000_000_000_000)?; // 1 WETH let trade = Trade::exact_out(route, output_amount).await?; // Get maximum input needed with slippage let slippage = Percent::new(5, 1000); // 0.5% let max_input = trade.maximum_amount_in(slippage.clone(), None)?; println!("Maximum Input: {} USDC", max_input.to_significant(6, None)?); // Get worst case execution price let worst_price = trade.worst_execution_price(slippage)?; println!("Worst Price: {}", worst_price.to_significant(6, None)?); ``` -------------------------------- ### Create and Manage a V4 Pool in Rust Source: https://context7.com/shuhuiluo/uniswap-v4-sdk-rs/llms.txt Demonstrates how to create a Uniswap V4 pool with specified currencies, fee, tick spacing, and initial liquidity. It also shows how to access pool properties like ID, currencies, tick, and fee, and how to calculate the price and check currency involvement. ```rust use uniswap_v4_sdk::prelude::*; use alloy_primitives::{Address, uint, U160}; use uniswap_sdk_core::prelude::*; // Define currencies for the pool let currency0 = Currency::Token(Token::new( 1, "0x6B175474E89094C44Da98b954EedeAC495271d0F", // DAI 18, Some("DAI".to_string()), Some("Dai Stablecoin".to_string()), )); let currency1 = Currency::Token(Token::new( 1, "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", // USDC 6, Some("USDC".to_string()), Some("USD Coin".to_string()), )); // Create a pool with specific parameters let pool = Pool::new( currency0.clone(), currency1.clone(), uint!(3000_U24), // 0.3% fee 60, // tick spacing Address::ZERO, // no hook uint!(79228162514264337593543950336_U160), // sqrt price 1:1 1_000_000_000_000_000_000_u128, // liquidity )?; // Access pool properties println!("Pool ID: {:?}", pool.pool_id); println!("Currency0: {:?}", pool.currency0); println!("Currency1: {:?}", pool.currency1); println!("Current Tick: {}", pool.tick_current); println!("Fee: {}", pool.fee); // Get pool price let price = pool.currency0_price(); println!("Currency0 Price: {}", price.to_significant(5, None)?); // Check if pool involves a specific currency assert!(pool.involves_currency(¤cy0)); ``` -------------------------------- ### Create Exact Input Trades using Uniswap V4 SDK Source: https://context7.com/shuhuiluo/uniswap-v4-sdk-rs/llms.txt Shows how to construct an exact input trade, specifying the exact amount of a token to send and calculating the expected output. This involves defining a route through one or more pools and considering slippage. Dependencies include `uniswap_v4_sdk` and `uniswap_sdk_core`. ```rust use uniswap_v4_sdk::prelude::*; use uniswap_sdk_core::prelude::{TradeType, CurrencyAmount}; // Create a route through pools let pools = vec![pool_usdc_dai.clone(), pool_dai_weth.clone()]; let route = Route::new( pools, usdc.clone(), weth.clone(), )?; // Create exact input trade let input_amount = CurrencyAmount::from_raw_amount(usdc.clone(), 1_000_000)?; // 1 USDC let trade = Trade::exact_in(route, input_amount).await?; // Access trade details let output = trade.output_amount()?; println!("Input: {} USDC", trade.input_amount()?.to_significant(6, None)?); println!("Output: {} WETH", output.to_significant(6, None)?); println!("Execution Price: {}", trade.execution_price()?.to_significant(6, None)?); println!("Price Impact: {}%", trade.price_impact()?.to_significant(2, None)?); // Calculate minimum output with slippage let slippage = Percent::new(5, 1000); // 0.5% let min_output = trade.minimum_amount_out(slippage.clone(), None)?; println!("Minimum Output: {} WETH", min_output.to_significant(6, None)?); ``` -------------------------------- ### Use V4PositionPlanner for Liquidity Operations (Rust) Source: https://context7.com/shuhuiluo/uniswap-v4-sdk-rs/llms.txt Demonstrates managing liquidity positions using `V4PositionPlanner`. This includes adding a `mint` position action, settling the pair of currencies involved, and potentially adding `sweep` actions for native tokens. The `finalize()` method returns unlock data which is then encoded into calldata. ```rust use uniswap_v4_sdk::prelude::*; let mut planner = V4PositionPlanner::default(); // Add mint position action planner.add_mint( &pool, tick_lower, tick_upper, U256::from(liquidity), amount0_max, amount1_max, recipient_address, Bytes::default(), // hook data ); // Add settle pair (pay both tokens) planner.add_settle_pair(&pool.currency0, &pool.currency1); // For native ETH pools, add sweep if pool.currency0.is_native() { planner.add_sweep(&pool.currency0, recipient_address); } // Finalize the actions let unlock_data = planner.0.finalize(); let calldata = encode_modify_liquidities(unlock_data, deadline); ``` -------------------------------- ### Build Swap Transactions with V4Planner in Rust Source: https://context7.com/shuhuiluo/uniswap-v4-sdk-rs/llms.txt Shows how to construct complex swap transactions using the `V4Planner`. This involves adding swap actions, settle actions (for user payment), and take actions (for receiving output). The `finalize()` method generates the transaction calldata. ```rust use uniswap_v4_sdk::prelude::*; use alloy_primitives::Bytes; // Create a planner to build complex transaction sequences let mut planner = V4Planner::default(); // Add a swap action planner.add_action(&Actions::SWAP_EXACT_IN(SwapExactInParams { currencyIn: token0.address(), path: encode_route_to_path(&route, false), maxHopSlippage: vec![], amountIn: 1_000_000, amountOutMinimum: 950_000, })); // Add settle action (user pays) planner.add_settle(&token0, true, None); // Add take action (receive output) planner.add_take(&token1, recipient_address, None); // Finalize and get calldata let calldata: Bytes = planner.finalize(); println!("Transaction calldata: {:?}", calldata); ``` -------------------------------- ### Testing the Rust Uniswap V4 SDK Source: https://github.com/shuhuiluo/uniswap-v4-sdk-rs/blob/main/CLAUDE.md Commands for running various types of tests for the Uniswap V4 SDK, including core, std feature, extension, doc tests, and specific tests or modules. ```bash # Run core tests cargo test # Run tests with std feature cargo test --features std # Run extension tests (must be single-threaded due to RPC state) cargo test --features extensions --lib extensions -- --test-threads=1 # Run doc tests cargo test --doc --all-features # Run a specific test cargo test test_name # Run tests in a specific module cargo test module_name:: ``` -------------------------------- ### Compute Position from Token Amounts using Uniswap V4 SDK Source: https://context7.com/shuhuiluo/uniswap-v4-sdk-rs/llms.txt Demonstrates how to create a liquidity position object from specific token amounts and tick ranges using the Uniswap V4 SDK. It also shows how to derive positions from a single token amount. Dependencies include the `uniswap_v4_sdk` and `alloy_primitives` crates. Outputs include the calculated liquidity. ```rust use uniswap_v4_sdk::prelude::*; use alloy_primitives::uint; // Create position from specific token amounts let amount0 = uint!(1000000_U256); // 1 USDC let amount1 = uint!(1000000000000000000_U256); // 1 DAI let tick_lower = -60; let tick_upper = 60; let position = Position::from_amounts( pool.clone(), tick_lower, tick_upper, amount0, amount1, true, // use full precision )?; println!("Calculated Liquidity: {}", position.liquidity); // Or create from single token amount let position_from_token0 = Position::from_amount0( pool.clone(), tick_lower, tick_upper, amount0, true, )?; let position_from_token1 = Position::from_amount1( pool.clone(), tick_lower, tick_upper, amount1, )?; ``` -------------------------------- ### Creating Multi-Hop Trades with Uniswap V4 SDK Source: https://context7.com/shuhuiluo/uniswap-v4-sdk-rs/llms.txt Demonstrates how to create a trade that utilizes multiple routes, enabling split routing for potentially better execution prices. This involves defining individual routes and then combining them into a single trade object. ```rust use uniswap_v4_sdk::prelude::*; // Create trade with multiple routes (for split routing) let amount1 = CurrencyAmount::from_raw_amount(token0.clone(), 5_000)?; let amount2 = CurrencyAmount::from_raw_amount(token0.clone(), 5_000)?; let route1 = Route::new(vec![pool_0_2.clone()], token0.clone(), token2.clone())?; let route2 = Route::new(vec![pool_0_1.clone(), pool_1_2.clone()], token0.clone(), token2.clone())?; let trade = Trade::from_routes( vec![ (amount1, route1), (amount2, route2), ], TradeType::ExactInput, ).await?; println!("Split trade output: {}", trade.output_amount()?.to_significant(6, None)?); ``` -------------------------------- ### Compute Mint/Burn Amounts with Slippage using Uniswap V4 SDK Source: https://context7.com/shuhuiluo/uniswap-v4-sdk-rs/llms.txt Illustrates how to calculate the required token amounts for minting a position and the minimum amounts to receive when burning liquidity, incorporating slippage tolerance. This function is crucial for mitigating price impact during liquidity operations. Dependencies include `uniswap_v4_sdk` and `uniswap_sdk_core`. ```rust use uniswap_v4_sdk::prelude::*; use uniswap_sdk_core::prelude::Percent; // Calculate amounts needed to mint position let mut position = Position::new(pool.clone(), 1_000_000, -60, 60); // Get mint amounts at current price let mint_amounts = position.mint_amounts()?; println!("Amount0: {}", mint_amounts.amount0); println!("Amount1: {}", mint_amounts.amount1); // Get mint amounts with slippage protection let slippage_tolerance = Percent::new(5, 1000); // 0.5% let mint_amounts_with_slippage = position.mint_amounts_with_slippage(&slippage_tolerance)?; println!("Max Amount0: {}", mint_amounts_with_slippage.amount0); println!("Max Amount1: {}", mint_amounts_with_slippage.amount1); // Get burn amounts with slippage for removing liquidity let (min_amount0, min_amount1) = position.burn_amounts_with_slippage(&slippage_tolerance)?; println!("Min Amount0 to receive: {}", min_amount0); println!("Min Amount1 to receive: {}", min_amount1); ``` -------------------------------- ### Fetch Tick Data using SimpleTickDataProvider (Rust) Source: https://context7.com/shuhuiluo/uniswap-v4-sdk-rs/llms.txt Explains how to fetch tick data from Uniswap V4 using `SimpleTickDataProvider`, which requires a provider, pool manager address, and pool key. It demonstrates fetching individual tick data including gross and net liquidity, and how to integrate this provider with a `Pool` object for accurate swap calculations. ```rust #[cfg(feature = "extensions")] use uniswap_v4_sdk::prelude::*; // Create tick data provider from RPC let tick_provider = SimpleTickDataProvider::new( provider.clone(), pool_manager_address, pool_key.clone(), ); // Fetch specific tick let tick_data = tick_provider.get_tick(tick_index).await?; println!("Liquidity Gross: {}", tick_data.liquidity_gross); println!("Liquidity Net: {}", tick_data.liquidity_net); // Use with pool for accurate swap calculations let pool_with_ticks = Pool::new_with_tick_data_provider( currency0, currency1, fee, tick_spacing, hooks, sqrt_price_x96, liquidity, tick_provider, )?; ``` -------------------------------- ### Linting and Formatting the Rust Uniswap V4 SDK Source: https://github.com/shuhuiluo/uniswap-v4-sdk-rs/blob/main/CLAUDE.md Commands to lint code using clippy and check/apply formatting using cargo fmt for the Uniswap V4 SDK project. Ensures code quality and consistency. ```bash # Run clippy (must pass with no warnings) cargo clippy --all-targets --all-features -- -D warnings # Check formatting cargo fmt --all -- --check # Apply formatting cargo fmt --all ``` -------------------------------- ### Query Pool Manager State using Pool Manager Lens (Rust) Source: https://context7.com/shuhuiluo/uniswap-v4-sdk-rs/llms.txt Demonstrates querying Uniswap V4 pool manager state, similar to Solidity's `StateView`, using the `extensions` feature. It involves constructing a `PoolKey` and then using `get_pool_state` for a single pool or `get_pool_states` for multiple pools. The results include liquidity, square root price, and tick. ```rust #[cfg(feature = "extensions")] use uniswap_v4_sdk::prelude::*; // Query pool manager state (similar to StateView in Solidity) let pool_key = Pool::get_pool_key(¤cy0, ¤cy1, fee, tick_spacing, hooks)?; let state = get_pool_state(provider, pool_manager_address, pool_key).await?; println!("Liquidity: {}", state.liquidity); println!("Sqrt Price X96: {}", state.sqrtPriceX96); println!("Tick: {}", state.tick); // Get multiple pool states at once let pool_keys = vec![pool_key1, pool_key2, pool_key3]; let states = get_pool_states(provider, pool_manager_address, pool_keys).await?; for (i, state) in states.iter().enumerate() { println!("Pool {} liquidity: {}", i, state.liquidity); } ``` -------------------------------- ### Create a Liquidity Position in Rust Source: https://context7.com/shuhuiluo/uniswap-v4-sdk-rs/llms.txt Shows how to create a liquidity position within a Uniswap V4 pool, defining the liquidity amount and the tick range (lower and upper). It also demonstrates how to calculate the amounts of token0 and token1 corresponding to this liquidity and the price range. ```rust use uniswap_v4_sdk::prelude::*; use uniswap_v3_sdk::prelude::{nearest_usable_tick, MIN_TICK_I32, MAX_TICK_I32}; // Placeholder for a created pool (from previous example or elsewhere) let currency0 = Currency::Token(Token::new(1, "0x6B175474E89094C44Da98b954EedeAC495271d0F".to_string(), 18, None, None)); let currency1 = Currency::Token(Token::new(1, "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48".to_string(), 6, None, None)); let pool = Pool::new( currency0.clone(), currency1.clone(), uint!(3000_U24), // 0.3% fee 60, // tick spacing Address::ZERO, // no hook uint!(79228162514264337593543950336_U160), // sqrt price 1:1 1_000_000_000_000_000_000_u128, // liquidity )?; // Create a position with specific liquidity amount let liquidity = 1_000_000_u128; let tick_spacing = 60; let tick_lower = nearest_usable_tick(-887220, tick_spacing); let tick_upper = nearest_usable_tick(887220, tick_spacing); let position = Position::new( pool.clone(), liquidity, tick_lower, tick_upper, ); // Get amounts of tokens in the position let amount0 = position.amount0()?; let amount1 = position.amount1()?; println!("Token0 Amount: {}", amount0.to_significant(6, None)?); println!("Token1 Amount: {}", amount1.to_significant(6, None)?); // Get prices at tick boundaries let price_lower = position.token0_price_lower()?; let price_upper = position.token0_price_upper()?; println!("Lower Price: {}", price_lower.to_significant(5, None)?); println!("Upper Price: {}", price_upper.to_significant(5, None)?); ``` -------------------------------- ### Building the Rust Uniswap V4 SDK Source: https://github.com/shuhuiluo/uniswap-v4-sdk-rs/blob/main/CLAUDE.md Commands to build the core library and extensions of the Uniswap V4 SDK using Cargo. Supports no_std, std, and all features including RPC interactions via alloy. ```bash # Build core library (no_std by default) cargo build # Build with std feature cargo build --features std # Build with extensions (includes alloy for RPC interactions) cargo build --features extensions # Build with all features cargo build --all-features ``` -------------------------------- ### Run Rust Tests Source: https://github.com/shuhuiluo/uniswap-v4-sdk-rs/blob/main/README.md This command executes all the tests within your Rust project, including those for the uniswap-v4-sdk if integrated. It's a standard way to verify the correctness of your code and ensure that changes haven't introduced regressions. ```shell cargo test ``` -------------------------------- ### Minting a Uniswap V4 Position with Basic Parameters Source: https://context7.com/shuhuiluo/uniswap-v4-sdk-rs/llms.txt Shows how to encode a transaction for minting a new liquidity position in Uniswap V4 using basic parameters. This includes setting the position details and defining common transaction options like slippage tolerance and deadline. ```rust use uniswap_v4_sdk::prelude::*; use alloy_primitives::{Address, Bytes, U256}; // Create position let mut position = Position::new(pool.clone(), 1_000_000, -60, 60); // Set up mint options let options = AddLiquidityOptions { common_opts: CommonOptions { slippage_tolerance: Percent::new(5, 1000), // 0.5% deadline: U256::from(1234567890), hook_data: Bytes::default(), }, use_native: None, // or Some(ether) for ETH pools batch_permit: None, specific_opts: MintSpecificOptions { recipient: "0x1234...".parse()?, create_pool: false, sqrt_price_x96: None, migrate: false, }.into(), }; // Generate transaction calldata let method_params = add_call_parameters(&mut position, options)?; // Use in transaction println!("Calldata: {:?}", method_params.calldata); println!("Value: {}", method_params.value); ``` -------------------------------- ### Minting Uniswap V4 Position with Permit2 Source: https://context7.com/shuhuiluo/uniswap-v4-sdk-rs/llms.txt Illustrates minting a liquidity position using Permit2 for token approvals, which allows for gasless approvals. This involves constructing a permit batch and signing it before including it in the minting options. ```rust use uniswap_v4_sdk::prelude::*; use alloy_primitives::{uint, U48, U160, U256}; // Create permit batch for token approvals let permit_batch = AllowanceTransferPermitBatch { details: vec![ IAllowanceTransfer::PermitDetails { token: position.pool.currency0.wrapped().address(), amount: U160::from(amount0_max), expiration: U48::from(deadline), nonce: U48::from(nonce), }, IAllowanceTransfer::PermitDetails { token: position.pool.currency1.wrapped().address(), amount: U160::from(amount1_max), expiration: U48::from(deadline), nonce: U48::from(nonce), }, ], spender: position_manager_address, sigDeadline: U256::from(deadline), }; // Sign the permit (use your signing logic) let signature = Bytes::from(signed_permit_data); let options = AddLiquidityOptions { common_opts: CommonOptions { slippage_tolerance: Percent::new(5, 1000), deadline: U256::from(deadline), hook_data: Bytes::default(), }, use_native: None, batch_permit: Some(BatchPermitOptions { owner: user_address, permit_batch, signature, }), specific_opts: MintSpecificOptions { recipient: user_address, create_pool: false, sqrt_price_x96: None, migrate: false, }.into(), }; let method_params = add_call_parameters(&mut position, options)?; ``` -------------------------------- ### Add Trade to Planner with Slippage Protection (Rust) Source: https://context7.com/shuhuiluo/uniswap-v4-sdk-rs/llms.txt Illustrates adding a pre-calculated trade to a `V4Planner` with optional slippage protection. It also includes adding settlement and take actions for the input and output currencies of the trade. The function returns the finalized transaction calldata. ```rust use uniswap_v4_sdk::prelude::*; // Create a trade let trade = Trade::exact_in(route, input_amount).await?; // Add trade to planner with slippage protection let mut planner = V4Planner::default(); let slippage = Percent::new(5, 1000); // 0.5% planner.add_trade(&trade, Some(slippage), None)?; // Add settlement for paying input token planner.add_settle(trade.input_currency(), true, None); // Add take for receiving output token planner.add_take(trade.output_currency(), recipient_address, None); let calldata = planner.finalize(); ``` -------------------------------- ### Fetch Pool State from On-Chain Data using Extensions (Rust) Source: https://context7.com/shuhuiluo/uniswap-v4-sdk-rs/llms.txt Shows how to fetch Uniswap V4 pool state directly from on-chain data using the `extensions` feature. This requires a blockchain provider and the pool manager address. It returns a `Pool` object containing liquidity, current tick, and square root price. ```rust #[cfg(feature = "extensions")] use uniswap_v4_sdk::prelude::*; use alloy::providers::Provider; // Fetch pool state from blockchain let provider = ...; // your provider let pool_manager_address = "0x...".parse()?; let pool = get_pool( provider, pool_manager_address, currency0, currency1, fee, tick_spacing, hooks_address, ).await?; println!("Pool liquidity: {}", pool.liquidity); println!("Current tick: {}", pool.tick_current); println!("Sqrt price: {}", pool.sqrt_price_x96); ``` -------------------------------- ### Compute V4 Pool ID and Pool Key in Rust Source: https://context7.com/shuhuiluo/uniswap-v4-sdk-rs/llms.txt Illustrates how to compute the unique identifier (pool ID) and the pool key for a Uniswap V4 pool using its parameters like currencies, fee, tick spacing, and hooks address. The pool key is essential for contract interactions. ```rust use uniswap_v4_sdk::prelude::*; use alloy_primitives::{Address, uint, B256}; // Placeholder currencies and fee for demonstration let currency_a = Currency::Token(Token::new(1, "0x123...".to_string(), 18, None, None)); let currency_b = Currency::Token(Token::new(1, "0x456...".to_string(), 6, None, None)); // Compute pool ID from parameters let pool_id: B256 = Pool::get_pool_id( ¤cy_a, ¤cy_b, uint!(3000_U24), // fee 60, // tick_spacing Address::ZERO, // hooks address )?; println!("Pool ID: {:?}", pool_id); // Get pool key (used for contract calls) let pool_key: PoolKey = Pool::get_pool_key( ¤cy_a, ¤cy_b, uint!(3000_U24), 60, Address::ZERO, )?; println!("Pool Key: {:?}", pool_key); // Pool key contains sorted currencies // Note: In a real scenario, currency_a and currency_b would be properly ordered based on their addresses // assert_eq!(pool_key.currency0, currency_a.address()); // assert_eq!(pool_key.tickSpacing, 60); ``` -------------------------------- ### Sign NFT Permit Source: https://context7.com/shuhuiluo/uniswap-v4-sdk-rs/llms.txt Generates a signed permit for NFT-based positions, enabling off-chain authorization for transactions. This involves preparing permit data, obtaining the EIP-712 signing hash, and signing it with a private key. ```rust use uniswap_v4_sdk::prelude::*; use alloy::signers::{local::PrivateKeySigner, SignerSync}; use alloy_sol_types::SolStruct; // Prepare permit data let permit = NFTPermitValues { spender: spender_address, tokenId: U256::from(1), nonce: U256::from(0), deadline: U256::from(deadline), }; // Get EIP-712 domain and signing hash let permit_data = get_permit_data( permit, position_manager_address, chain_id, ); let signing_hash = permit_data.eip712_signing_hash(); // Sign with private key let signer = PrivateKeySigner::from_bytes(&private_key)?; let signature = signer.sign_hash_sync(&signing_hash)?; // Use in transaction let permit_options = NFTPermitOptions { values: permit, signature, }; ``` -------------------------------- ### Check Rust Code Formatting Source: https://github.com/shuhuiluo/uniswap-v4-sdk-rs/blob/main/README.md This command checks the formatting of all files in your Rust project using rustfmt, ensuring compliance with standard Rust code style. It will report any files that are not correctly formatted without making changes. Use `cargo fmt --all` to automatically format the code. ```shell cargo fmt --all -- --check ``` -------------------------------- ### Encode Routes to Paths Source: https://context7.com/shuhuiluo/uniswap-v4-sdk-rs/llms.txt Encodes a liquidity route into a path format suitable for exact input or exact output swaps. This utility function takes a route object and a boolean indicating whether to encode for exact output (reversed) swaps. ```rust use uniswap_v4_sdk::prelude::*; // Create a route let route = Route::new( vec![pool1.clone(), pool2.clone()], token_in.clone(), token_out.clone(), )?; // Encode route to path for exact input swaps let path = encode_route_to_path(&route, false); println!("Encoded path: {:?}", path); // Encode for exact output (reversed) let path_reversed = encode_route_to_path(&route, true); ``` -------------------------------- ### Collect Fees from a Position using Uniswap V4 SDK Source: https://context7.com/shuhuiluo/uniswap-v4-sdk-rs/llms.txt Demonstrates how to collect fees from a specific position in Uniswap V4. It requires a `Position` object, `CollectOptions` including slippage tolerance, deadline, and recipient address. The output is the calldata for the collect transaction. ```rust use uniswap_v4_sdk::prelude::*; let position = Position::new(pool.clone(), 1_000_000, -60, 60); let options = CollectOptions { common_opts: CommonOptions { slippage_tolerance: Percent::new(0, 100), // no slippage for collect deadline: U256::from(1234567890), hook_data: Bytes::default(), }, token_id: U256::from(42), recipient: user_address, }; let method_params = collect_call_parameters(&position, options); println!("Collect fees calldata: {:?}", method_params.calldata); ``` -------------------------------- ### Convert Price and Tick Source: https://context7.com/shuhuiluo/uniswap-v4-sdk-rs/llms.txt Performs conversions between price and tick values using Uniswap V3 SDK utilities. It includes functions to convert a tick to its corresponding price and to convert a square root price (in X96 format) to a tick. ```rust use uniswap_v4_sdk::prelude::*; use uniswap_v3_sdk::prelude::{get_tick_at_sqrt_ratio, get_sqrt_ratio_at_tick}; // Convert tick to price let tick = 100; let price = tick_to_price(currency0.clone(), currency1.clone(), tick)?; println!("Price at tick {}: {}", tick, price.to_significant(5, None)?); // Convert sqrt price to tick let sqrt_price_x96 = uint!(79228162514264337593543950336_U160); let tick = get_tick_at_sqrt_ratio(sqrt_price_x96)?; println!("Tick at sqrt price: {}", tick); // Convert tick to sqrt price let sqrt_price = get_sqrt_ratio_at_tick(tick)?; println!("Sqrt price at tick {}: {}", tick, sqrt_price); ``` -------------------------------- ### Check Hook Permissions Source: https://context7.com/shuhuiluo/uniswap-v4-sdk-rs/llms.txt Verifies if a given hook address has the necessary permissions to interact with Uniswap V4 swap functions. It supports checking for general swap permissions as well as specific before/after swap permissions, and validates the hook address format. ```rust use uniswap_v4_sdk::prelude::*; use alloy_primitives::Address; let hook_address: Address = "0x1100000000000000000000000000000000002401".parse()?; // Check if hook has before/after swap permissions if has_swap_permissions(hook_address) { println!("Hook modifies swap behavior"); } // Check specific permissions if has_permission(hook_address, HOOKS_BEFORE_SWAP_FLAG) { println!("Hook has beforeSwap permission"); } if has_permission(hook_address, HOOKS_AFTER_SWAP_FLAG) { println!("Hook has afterSwap permission"); } // Validate hook address format assert!(validate_hook_address(hook_address, HOOKS_BEFORE_SWAP_FLAG)); ``` -------------------------------- ### Fetch Position Data from NFT Source: https://context7.com/shuhuiluo/uniswap-v4-sdk-rs/llms.txt Retrieves detailed information about a liquidity position using its NFT token ID. This function requires a provider, the position manager's address, and the token ID as input. It returns the pool key, tick boundaries, and liquidity amount. ```rust #[cfg(feature = "extensions")] use uniswap_v4_sdk::prelude::*; // Fetch position details from NFT token ID let token_id = U256::from(42); let position_info = get_position_info( provider, position_manager_address, token_id, ).await?; println!("Pool Key: {:?}", position_info.poolKey); println!("Tick Lower: {}", position_info.tickLower); println!("Tick Upper: {}", position_info.tickUpper); println!("Liquidity: {}", position_info.liquidity); // Parse position events from transaction receipt let receipt = provider.get_transaction_receipt(tx_hash).await?.unwrap(); let token_id = get_first_token_id_from_transaction( position_manager_address, &receipt, )?; println!("Minted position token ID: {}", token_id); ``` -------------------------------- ### Increasing Liquidity on Existing Uniswap V4 Position Source: https://context7.com/shuhuiluo/uniswap-v4-sdk-rs/llms.txt Demonstrates how to encode a transaction to increase liquidity on an existing position in Uniswap V4. This is achieved by specifying the NFT token ID of the existing position and the additional liquidity to add. ```rust use uniswap_v4_sdk::prelude::*; // Create position with additional liquidity to add let mut position = Position::new(pool.clone(), 500_000, -60, 60); let options = AddLiquidityOptions { common_opts: CommonOptions { slippage_tolerance: Percent::new(5, 1000), deadline: U256::from(1234567890), hook_data: Bytes::default(), }, use_native: None, batch_permit: None, specific_opts: ModifyPositionSpecificOptions { token_id: U256::from(42), // existing NFT token ID }.into(), }; let method_params = add_call_parameters(&mut position, options)?; ``` -------------------------------- ### Add Uniswap V4 SDK Dependency to Cargo.toml Source: https://github.com/shuhuiluo/uniswap-v4-sdk-rs/blob/main/README.md This code snippet shows how to add the uniswap-v4-sdk crate as a dependency in your Rust project's Cargo.toml file. It includes the 'extensions' and 'std' features, which enable additional functionalities and standard library support respectively. Ensure you specify the desired version. ```toml uniswap-v4-sdk = { version = "0.13.0", features = ["extensions", "std"] } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.