### Install Uniswap SDK via Setuptools Source: https://github.com/apeworx/uniswap-sdk/blob/main/README.md Installs the most up-to-date version of the Uniswap SDK by cloning the repository and using setuptools. This method is suitable for developers who need the latest features. ```bash git clone https://github.com/SilverBackLtd/uniswap-sdk.git cd uniswap-sdk python3 setup.py install ``` -------------------------------- ### Integrate Uniswap SDK with Silverback Bot (Python) Source: https://github.com/apeworx/uniswap-sdk/blob/main/README.md Shows how to integrate the Uniswap SDK with a Silverback Bot for real-time processing and reduced overhead. This example demonstrates installing the SDK into the bot and using cron jobs for background index updates, leading to faster price lookups. ```python from ape_tokens import tokens from silverback import SilverbackBot from uniswap_sdk import Uniswap bot = SilverbackBot() uni = Uniswap() uni.install(bot) @bot.cron("* * * * *") async def weth_price(t): return uni.price("WETH", "USDC") ``` -------------------------------- ### Install Uniswap SDK via pip Source: https://github.com/apeworx/uniswap-sdk/blob/main/README.md Installs the latest release of the Uniswap SDK using pip, the Python package installer. Ensure you have Python 3.10 or greater installed. ```bash pip install uniswap_sdk ``` -------------------------------- ### Uniswap SDK Scripting Examples (Python) Source: https://github.com/apeworx/uniswap-sdk/blob/main/README.md Demonstrates basic scripting tasks using the Uniswap SDK in Python. This includes initializing the SDK, indexing tokens, fetching real-time prices, and performing token swaps with various parameters like slippage and deadline. ```python from ape_tokens import tokens from uniswap_sdk import Uniswap uni = Uniswap(use_v3=False) list(uni.index(tokens=tokens)) uni.price("UNI", "USDC") usdc = tokens["USDC"] tx = uni.swap( "UNI", usdc, amount_in="12 UNI", slippage=0.3, deadline=timedelta(minutes=2), sender=trader, ) ``` ```python uni.swap(want="UNI", sender=trader, value="1 ether") uni.swap(want="UNI", amount_out="10 UNI", sender=trader, value="1 ether") uni.swap(have="UNI", amount_in="10 UNI", native_out=True, ...) ``` -------------------------------- ### Get Token Price with Uniswap SDK Source: https://context7.com/apeworx/uniswap-sdk/llms.txt Shows how to query liquidity-weighted prices for a token pair using the Uniswap SDK. It covers fetching the price of one token in terms of another and applying a minimum liquidity filter for more reliable price data. ```python from uniswap_sdk import Uniswap from ape_tokens import tokens from decimal import Decimal uni = Uniswap() list(uni.index(tokens=[tokens["UNI"], tokens["USDC"], tokens["WETH"]])) # Get price of UNI in terms of USDC price = uni.price("UNI", "USDC") print(f"UNI price: {price} USDC") # Returns Decimal("4.75") # Get price with minimum liquidity filter price_filtered = uni.price( base=tokens["WETH"], quote=tokens["USDC"], min_liquidity=Decimal(10) # Require at least 10 tokens liquidity ) print(f"WETH price: {price_filtered} USDC") ``` -------------------------------- ### Define a Custom Uniswap Solver (Python) Source: https://github.com/apeworx/uniswap-sdk/blob/main/README.md Provides an interface definition and an example class for creating a custom solver for the Uniswap SDK. Custom solvers allow users to optimize swap actions by defining their own logic for routing and amount calculations, overriding the default solver. ```python from uniswap_sdk import Order Route = tuple[PairType, ...] Solution = dict[Route, Decimal] SolverType = Callable[[Order, Iterable[Route]], Solution] class Solver: def __call__(self, order: Order, routes: Iterable[Route]) -> Solution: # This function must match `SolverType` to work pass my_solver = Solver(...) uni = Uniswap(use_solver=my_solver) uni.solve(...) ``` -------------------------------- ### Initialize Uniswap SDK Source: https://context7.com/apeworx/uniswap-sdk/llms.txt Demonstrates basic initialization of the Uniswap SDK, allowing selection of V2 and V3 protocols and setting a default slippage tolerance. It also shows how to index token pairs for faster price queries, which can be time-consuming. ```python from uniswap_sdk import Uniswap from ape_tokens import tokens # Initialize with both V2 and V3 (default) uni = Uniswap() # Initialize with only V2 uni_v2_only = Uniswap(use_v2=True, use_v3=False) # Initialize with custom default slippage (0.5% default) uni_custom = Uniswap(default_slippage=0.01) # 1% slippage # Index pairs for faster price queries (takes significant time) list(uni.index(tokens=tokens)) ``` -------------------------------- ### Uniswap SDK CLI Usage Source: https://github.com/apeworx/uniswap-sdk/blob/main/README.md Illustrates the usage of the `uni` command-line interface (CLI) that comes with the SDK. The CLI provides a convenient way to perform common tasks like finding prices and executing swaps directly from the terminal. ```bash uni --help ``` -------------------------------- ### Inspect Solution Source: https://context7.com/apeworx/uniswap-sdk/llms.txt Iterates through a solution dictionary to print the ratio and description of each route. This is useful for visualizing the output of a routing algorithm. ```python for route, ratio in solution.items(): route_desc = " -> ".join(p.describe() for p in route) print(f"{ratio * 100:.2f}% via {route_desc}") ``` -------------------------------- ### Create UniversalRouter Execution Plan Source: https://context7.com/apeworx/uniswap-sdk/llms.txt Builds a custom execution plan for the UniversalRouter, enabling multiple commands like wrapping ETH and executing V3 swaps. It utilizes the Plan and UniversalRouter classes, requiring Ape accounts for sender addresses. The output is a transaction receipt. ```python from uniswap_sdk import Plan, UniversalRouter from uniswap_sdk.universal_router import Constants from ape import accounts router = UniversalRouter() me = accounts.load("my-account") # Build plan using builder pattern plan = ( Plan() .wrap_eth(Constants.ADDRESS_THIS, int(1e18)) # Wrap 1 ETH .v3_swap_exact_in( recipient=me.address, amountIn=int(1e18), amountOutMin=int(1000e6), # Expect at least 1000 USDC path=( "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2", # WETH 3000, # 0.3% fee "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48" # USDC ), payerIsUser=False ) ) # Execute plan receipt = router.execute(plan, sender=me, value="1 ether") print(f"Executed: {receipt.txn_hash}") ``` -------------------------------- ### Execute Token Swap with Uniswap SDK Source: https://context7.com/apeworx/uniswap-sdk/llms.txt Details how to perform token swaps using the Uniswap SDK, including support for both exact input and exact output amounts. It allows specifying slippage tolerance and a transaction deadline to protect against price fluctuations. ```python from uniswap_sdk import Uniswap from ape_tokens import tokens from ape import accounts from datetime import timedelta uni = Uniswap() trader = accounts.load("my-account") # Swap exact input amount tx = uni.swap( have="UNI", want=tokens["USDC"], amount_in="12 UNI", slippage=0.005, # 0.5% slippage deadline=timedelta(minutes=2), sender=trader ) print(f"Swap executed: {tx.txn_hash}") # Swap for exact output amount tx = uni.swap( have="UNI", want="USDC", amount_out="100 USDC", slippage=0.01, # 1% slippage sender=trader ) ``` -------------------------------- ### Swap with Native ETH using Uniswap SDK Source: https://context7.com/apeworx/uniswap-sdk/llms.txt Illustrates how to perform swaps involving native Ether (ETH) directly, eliminating the need for manual wrapping and unwrapping. This includes buying tokens with ETH and selling tokens for native ETH, specifying amounts as exact input or output. ```python from uniswap_sdk import Uniswap from ape import accounts uni = Uniswap() trader = accounts.load("my-account") # Buy UNI with ETH (exact input) tx = uni.swap( want="UNI", sender=trader, value="1 ether" ) # Buy UNI with ETH (exact output) tx = uni.swap( want="UNI", amount_out="10 UNI", sender=trader, value="1 ether" # Acts as max_amount_in ) # Sell UNI for native ETH tx = uni.swap( have="UNI", amount_in="10 UNI", native_out=True, sender=trader ) ``` -------------------------------- ### Create and Solve Swap Order Source: https://context7.com/apeworx/uniswap-sdk/llms.txt Creates a swap order with specified input/output tokens, amount, and slippage tolerance, then solves for the optimal route using indexed pools. It returns a description of the order and the optimal solution. ```python from uniswap_sdk import Uniswap from ape_tokens import tokens from decimal import Decimal uni = Uniswap() list(uni.index(tokens=[tokens["UNI"], tokens["USDC"], tokens["WETH"]])) # Create exact input order order = uni.create_order( have="UNI", want="USDC", amount_in=Decimal("10"), # 10 UNI slippage=0.005 # 0.5% ) print(order.describe()) # Solve for optimal routes solution = uni.solve(order=order) ``` -------------------------------- ### Build Arbitrage Bot using Silverback Integration Source: https://context7.com/apeworx/uniswap-sdk/llms.txt Creates a production-ready arbitrage trading bot by integrating Uniswap SDK with Silverback Bot. It loads token inventory, monitors price differences, and executes trades when arbitrage opportunities exceed a defined threshold. ```python from decimal import Decimal from ape_tokens import tokens from silverback import SilverbackBot from uniswap_sdk import Uniswap from ape.exceptions import ContractLogicError bot = SilverbackBot(signer_required=True) uni = Uniswap() TOKENA = tokens["USDT"] TOKENB = tokens["USDC"] REFERENCE_PRICE = Decimal("1.0") ARB_THRESHOLD = Decimal("0.0025") # 0.25% uni.install(bot, tokens=[TOKENA, TOKENB]) @bot.on_startup() async def load_inventory(_): bot.state.inventory = { TOKENA: Decimal(TOKENA.balanceOf(bot.signer)) / Decimal(10 ** TOKENA.decimals()), TOKENB: Decimal(TOKENB.balanceOf(bot.signer)) / Decimal(10 ** TOKENB.decimals()) } return bot.state.inventory @bot.cron("*/5 * * * *") # Every 5 minutes async def price(_): return uni.price(TOKENA, TOKENB) @bot.on_metric("price") def price_delta(price: Decimal): return price - REFERENCE_PRICE @bot.on_metric("price_delta", lt=-ARB_THRESHOLD) def buy_opportunity(_): if bot.state.inventory[TOKENB] > 0: try: uni.swap( have=TOKENB, want=TOKENA, amount_in=bot.state.inventory[TOKENB], sender=bot.signer ) except ContractLogicError: pass # Trade failed, skip ``` -------------------------------- ### Index V2 Factory Pairs with Uniswap SDK Source: https://context7.com/apeworx/uniswap-sdk/llms.txt Explains how to index all trading pairs from a Uniswap V2 factory contract, which significantly speeds up routing. It also shows how to index only specific token pairs or retrieve individual pair information. ```python from uniswap_sdk import v2 from ape_tokens import tokens factory = v2.Factory() # Index all pairs (very slow, can take hours) all_pairs = list(factory.index()) print(f"Indexed {len(factory)} pairs") # Index only specific token pairs selected_pairs = list(factory.index(tokens=[ tokens["UNI"], tokens["USDC"], tokens["WETH"] ])) # Get specific pair pair = factory.get_pair("YFI", "USDC") if pair: print(f"Pair address: {pair.address}") print(f"YFI price: {pair.price('YFI')} USDC") print(f"YFI liquidity: {pair.liquidity['YFI']}") ``` -------------------------------- ### Find Optimal Swap Routes Source: https://context7.com/apeworx/uniswap-sdk/llms.txt Finds all possible swap routes between token pairs, supporting multiple hops and different Uniswap versions (V2/V3). It indexes tokens and then uses `find_routes` to identify potential paths. The output is a list of route descriptions. ```python from uniswap_sdk import Uniswap from ape_tokens import tokens uni = Uniswap() list(uni.index(tokens=[ tokens["UNI"], tokens["USDC"], tokens["WETH"], tokens["DAI"] ])) # Find all routes between UNI and USDC (up to depth 2) routes = list(uni.find_routes( have="UNI", want="USDC", )) for route in routes: print(f"Route: {' -> '.join(p.describe() for p in route)}") # Find longer routes (more hops) from uniswap_sdk import v2 factory = v2.Factory() long_routes = list(factory.find_routes( start_token="UNI", end_token="DAI", depth=3 # Allow up to 3 hops )) ``` -------------------------------- ### Query V2 Pair Information with Uniswap SDK Source: https://context7.com/apeworx/uniswap-sdk/llms.txt Demonstrates how to query detailed information from Uniswap V2 trading pools, including token reserves, current prices, and liquidity data. It also covers calculating the maximum swap size for a given slippage and the price impact of a specific trade. ```python from uniswap_sdk import v2 from decimal import Decimal # Initialize pair directly by address pair = v2.Pair(address="0xdE37cD310c70e7Fa9d7eD3261515B107D5Fe1F2d") # Get reserves for a token yfi_liquidity = pair.liquidity["YFI"] print(f"YFI reserves: {yfi_liquidity}") # Get price yfi_price = pair.price("YFI") print(f"Price: {yfi_price} {pair.other('YFI').symbol()}/YFI") # Calculate depth (max swap size for given slippage) max_swap = pair.depth("YFI", slippage=Decimal("0.05")) # 5% slippage print(f"Max swap before 5% slippage: {max_swap} YFI") # Calculate reflexivity (price impact for given swap size) impact = pair.reflexivity("YFI", size=Decimal("1.0")) print(f"Price impact for 1 YFI swap: {impact * 100}%") ``` -------------------------------- ### Sign Permit2 for Gasless Approvals Source: https://context7.com/apeworx/uniswap-sdk/llms.txt Creates Permit2 signatures for gasless token approvals, enabling the UniversalRouter to spend tokens without direct user transaction confirmation. It requires Ape accounts, token definitions, and the UniversalRouter address. The output is a signed permit command. ```python from uniswap_sdk import Permit2 from uniswap_sdk.permit2 import PermitDetails from ape import accounts from ape_tokens import tokens from datetime import datetime, timedelta, timezone permit2 = Permit2() signer = accounts.load("my-account") uni_router_address = "0x3fC91A3afd70395Cd496C647d5a6CC9D4B2b7FAD" # Create permit details expiration = datetime.now(timezone.utc) + timedelta(hours=1) permit = PermitDetails( token=tokens["UNI"].address, amount=int(100e18), # 100 UNI expiration=int(expiration.timestamp()), nonce=permit2.get_nonce(signer, tokens["UNI"], uni_router_address) ) # Sign permit permit_command = permit2.sign_permit( spender=uni_router_address, permit=permit, signer=signer ) # Use in swap from uniswap_sdk import Uniswap uni = Uniswap() # Permit command will be included automatically if allowance exists ``` -------------------------------- ### Integrate with Silverback Bot for Real-time Event Processing Source: https://context7.com/apeworx/uniswap-sdk/llms.txt Integrates the Uniswap SDK with Silverback Bot for real-time event processing and automated index updates. This allows for faster price queries using cached data and reacting to price changes. ```python from ape_tokens import tokens from silverback import SilverbackBot from uniswap_sdk import Uniswap bot = SilverbackBot() uni = Uniswap() # Install replaces manual indexing - tracks events in background uni.install(bot, tokens=[ tokens["WETH"], tokens["USDC"], tokens["UNI"] ]) # Price queries use cached data (much faster) @bot.cron("* * * * *") # Every minute async def check_price(timestamp): price = uni.price("WETH", "USDC") return {"weth_usdc_price": float(price)} # React to price changes @bot.on_metric("weth_usdc_price") async def on_price_change(price): if price > 2000: print(f"WETH price is high: {price}") ``` -------------------------------- ### Implement Custom Solver for Optimized Route Finding Source: https://context7.com/apeworx/uniswap-sdk/llms.txt Implements a custom solver for the Uniswap SDK that prioritizes routes with the lowest gas cost. This involves sorting available routes by their length (number of hops) and selecting the shortest one for execution. ```python from decimal import Decimal from typing import Iterable from uniswap_sdk import Uniswap, Order from uniswap_sdk.types import Route from uniswap_sdk.solver import Solution class CustomSolver: def __call__(self, order: Order, routes: Iterable[Route]) -> Solution: """Custom solver that prioritizes lowest gas cost routes""" solution = {} # Sort routes by length (fewer hops = less gas) sorted_routes = sorted(routes, key=len) if sorted_routes: # Use only the shortest route best_route = tuple(sorted_routes[0]) solution[best_route] = Decimal("1.0") # 100% of flow return solution # Use custom solver my_solver = CustomSolver() uni = Uniswap(use_solver=my_solver) # Swaps will now use custom solver logic uni.swap( have="UNI", want="USDC", amount_in="10 UNI", sender=trader ) ``` -------------------------------- ### Index V3 Factory Pools Source: https://context7.com/apeworx/uniswap-sdk/llms.txt Indexes Uniswap V3 pools, allowing for the retrieval of all pools or pools for specific token pairs across different fee tiers. It utilizes the v3.Factory class and requires access to token definitions. ```python from uniswap_sdk import v3 from ape_tokens import tokens from uniswap_sdk.types import Fee factory = v3.Factory() # Index all pools from PoolCreated events all_pools = list(factory.index()) # Index specific tokens across all fee tiers pools = list(factory.index(tokens=[ tokens["USDC"], tokens["WETH"], tokens["UNI"] ])) # Get specific pool with fee tier pool = factory.get_pool("USDC", "WETH", fee=Fee.MEDIUM) # 0.3% fee if pool: print(f"Pool: {pool.token0.symbol()}/{pool.token1.symbol()}") print(f"Fee: {pool.fee.to_decimal() * 100}%") print(f"Current price: {pool.price('USDC')}") ``` -------------------------------- ### Approve Token for Permit2 Source: https://context7.com/apeworx/uniswap-sdk/llms.txt Grants the Permit2 contract approval to spend tokens on behalf of a user, either for an unlimited amount or a specific allowance. It uses the Uniswap class and requires Ape accounts and token definitions. The output is a transaction receipt. ```python from uniswap_sdk import Uniswap from ape import accounts from ape_tokens import tokens uni = Uniswap() trader = accounts.load("my-account") # Approve unlimited amount (default) receipt = uni.approve_permit2( token=tokens["UNI"], sender=trader ) # Approve specific amount receipt = uni.approve_permit2( token="USDC", allowance="1000 USDC", sender=trader ) print(f"Approval transaction: {receipt.txn_hash}") ``` -------------------------------- ### Decode UniversalRouter Transaction Calldata Source: https://context7.com/apeworx/uniswap-sdk/llms.txt Decodes and inspects transaction calldata for the UniversalRouter, allowing examination of executed commands and their arguments. It requires a transaction hash and returns the decoded plan object. ```python from uniswap_sdk import UniversalRouter router = UniversalRouter() # Decode from transaction hash txn_hash = "0x1234..." plan = router.decode_plan_from_transaction(txn_hash) # Inspect commands in plan for cmd in plan.commands: print(f"Command: {cmd.__class__.__name__}") print(f" Args: {cmd.args}") # Access specific command attributes if hasattr(plan.commands[0], 'amountIn'): print(f"Amount In: {plan.commands[0].amountIn}") ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.