API Reference

Contents

API Reference#

Uniswap class#

class uniswap.Uniswap(address: Address | ChecksumAddress | str | None, private_key: str | None, provider: str | None = None, web3: Web3 | None = None, version: int = 1, default_slippage: float = 0.01, use_estimate_gas: bool = True, factory_contract_addr: str | None = None, router_contract_addr: str | None = None, enable_caching: bool = False)#

Wrapper around Uniswap contracts.

Parameters:
  • address – The public address of the ETH wallet to use.

  • private_key – The private key of the ETH wallet to use.

  • provider – Can be optionally set to a Web3 provider URI. If none set, will fall back to the PROVIDER environment variable, or web3 if set.

  • web3 – Can be optionally set to a custom Web3 instance.

  • version – Which version of the Uniswap contracts to use.

  • default_slippage – Default slippage for a trade, as a float (0.01 is 1%). WARNING: slippage is untested.

  • factory_contract_addr – Can be optionally set to override the address of the factory contract.

  • router_contract_addr – Can be optionally set to override the address of the router contract (v2 only).

  • enable_caching – Optionally enables middleware caching RPC method calls.

get_price_input(token0: Address | ChecksumAddress, token1: Address | ChecksumAddress, qty: int, fee: int | None = None, route: List[Address | ChecksumAddress] | None = None) int#

Given qty amount of the input token0, returns the maximum output amount of output token1.

get_price_output(token0: Address | ChecksumAddress, token1: Address | ChecksumAddress, qty: int, fee: int | None = None, route: List[Address | ChecksumAddress] | None = None) int#

Returns the minimum amount of token0 required to buy qty amount of token1.

make_trade(input_token: Address | ChecksumAddress, output_token: Address | ChecksumAddress, qty: int | Wei, recipient: Address | ChecksumAddress | None = None, fee: int | None = None, slippage: float | None = None, fee_on_transfer: bool = False) HexBytes#

Make a trade by defining the qty of the input token.

make_trade_output(input_token: Address | ChecksumAddress, output_token: Address | ChecksumAddress, qty: int | Wei, recipient: Address | ChecksumAddress | None = None, fee: int | None = None, slippage: float | None = None) HexBytes#

Make a trade by defining the qty of the output token.

get_eth_balance() Wei#

Get the balance of ETH for your address.

get_token_balance(token: Address | ChecksumAddress) int#

Get the balance of a token for your address.

get_ex_eth_balance(token: Address | ChecksumAddress) int#

Get the balance of ETH in an exchange contract.

Supports Uniswap v1

get_ex_token_balance(token: Address | ChecksumAddress) int#

Get the balance of a token in an exchange contract.

Supports Uniswap v1

get_exchange_rate(token: Address | ChecksumAddress) float#

Get the current ETH/token exchange rate of the token.

Supports Uniswap v1

add_liquidity(token: Address | ChecksumAddress, max_eth: Wei, min_liquidity: int = 1) HexBytes#

Add liquidity to the pool.

Supports Uniswap v1

remove_liquidity(token: str, max_token: int) HexBytes#

Remove liquidity from the pool.

Supports Uniswap v1

mint_liquidity(pool: Contract, amount_0: int, amount_1: int, tick_lower: int, tick_upper: int, deadline: int = 18446744073709551616) TxReceipt#

add liquidity to pool and mint position nft

Supports Uniswap v3

close_position(tokenId: int, amount0Min: int = 0, amount1Min: int = 0, deadline: int | None = None) TxReceipt#

remove all liquidity from the position associated w/ tokenId, collect fees, and burn token.

Supports Uniswap v3

get_tvl_in_pool(pool: Contract) Tuple[float, float]#

Iterate through each tick in a pool and calculate the TVL on-chain

Note: the output of this function may differ from what is returned by the UniswapV3 subgraph api (Uniswap/v3-subgraph#74)

Params#

pool: Contract

pool contract instance to find TVL

approve(token: Address | ChecksumAddress, max_approval: int | None = None) None#

Give an exchange/router max approval of a token.

multicall(encoded_functions: Sequence[Tuple[ChecksumAddress, bytes]], output_types: Sequence[str]) List[Any]#

Calls aggregate() on Uniswap Multicall2 contract

Params#

encoded_functionsSequence[Tuple[ChecksumAddress, bytes]]

array of tuples containing address of contract and byte-encoded transaction data

output_types: Sequence[str]

array of solidity output types for decoding (e.g. uint256, bool, etc.)

returns decoded results

get_token(address: Address | ChecksumAddress, abi_name: str = 'erc20') ERC20Token#

Retrieves metadata from the ERC20 contract of a given token, like its name, symbol, and decimals.

get_weth_address() ChecksumAddress#

Retrieves the WETH address from the contracts (which may vary between chains).

Supports Uniswap v2, v3

get_pool_instance(token_0: Address | ChecksumAddress, token_1: Address | ChecksumAddress, fee: int = 3000) Contract#

Returns an instance of a pool contract for a given token pair and fee. Requires pair [token_in, token_out, fee] has a direct pool. Will return 0x0 address if pool does not exist.

Supports Uniswap v3

create_pool_instance(token_0: Address | ChecksumAddress, token_1: Address | ChecksumAddress, fee: int = 3000) Contract#

Creates and returns UniswapV3 Pool instance. Requires that fee is valid and no similar pool already exists.

Supports Uniswap v3

get_pool_immutables(pool: Contract) Dict#

Fetch on-chain pool data.

Supports Uniswap v3

get_pool_state(pool: Contract) Dict#

Fetch on-chain pool state.

Supports Uniswap v3

get_liquidity_positions() List[int]#

Enumerates liquidity position tokens owned by address. Returns array of token IDs.

Supports Uniswap v3

mint_position(pool: Contract, amount0: int, amount1: int) HexBytes#

Supports Uniswap v3

get_raw_price(token_in: Address | ChecksumAddress, token_out: Address | ChecksumAddress, fee: int | None = None) float#

Returns current price for pair of tokens [token_in, token_out] regrading liquidity that is being locked in the pool Parameter fee is required for V3 only, can be omitted for V2 Requires pair [token_in, token_out] having direct pool

Supports Uniswap v2, v3

estimate_price_impact(token_in: Address | ChecksumAddress, token_out: Address | ChecksumAddress, amount_in: int, fee: int, route: List[Address | ChecksumAddress] | None = None) float#

Returns the estimated price impact as a positive float (0.01 = 1%).

NOTE: Work-in-progress.

See examples/price_impact.py for an example which uses this.

get_fee_maker() float#

Get the maker fee.

Supports Uniswap v1, v2

get_fee_taker() float#

Get the taker fee.

Supports Uniswap v1, v2

Uniswap4 class#

class uniswap.uniswap4.Uniswap4(address: str | Address | ChecksumAddress, private_key: str | None = None, provider: str | None = None, web3: Web3 | None = None, max_slippage: float = 0.01, gas_limit: float = 250000.0, gas_price: float = 1.8, priority_fee: float = 1.0, post_merge: bool = True)#

Wrapper around Uniswap v4 contracts.

Parameters:
  • address – The public address of the ETH wallet to use.

  • private_key – The private key of the ETH wallet to use.

  • provider – Can be optionally set to a Web3 provider URI. If none set, will fall back to the PROVIDER environment variable, or web3 if set.

  • web3 – Can be optionally set to a custom Web3 instance.

  • max_slippage – Maximum slippage for a trade, as a float (0.01 is 1%).

  • gas_limit – Maximum gas amount allocated for transactions.

  • gas_price – Cost per unit of gas, in GWei.

  • priority_fee – Amount of ETH to pay to the block producers, in GWei. Affects tx position in the block, the bigger value, the higher position is.

  • post_merge – True is for post-Merge transations, False for legacy ones.

approve(token: Address | ChecksumAddress, max_approval: int | None = None, delay_interval: int | None = 7, approve_position_manager: bool = False) HexBytes#

Approve the router to spend a token on the user’s behalf, or set up a permit for the position manager to pull the token from the user’s wallet. For ETH, the router can pull from the user’s wallet directly, so no approval is necessary.

Parameters:
  • token – The address of the token to approve.

  • max_approval – Optional. The maximum amount to approve. If not set, will approve a maximum possible amount.

  • delay_interval – Optional. Seconds to wait between two approval transactions. Defaults to 7. Values less than 1 are treated as default.

  • approve_position_manager – Optional. Whether to approve the position manager to spend the token. Defaults to False.

approval(token: Address | ChecksumAddress) int#

Returns the current allowance for the router to spend a token on the user’s behalf. Note that this is not the allowance of the token itself, but the allowance set in the Permit2 contract for the router to spend the token.

get_gas_limit() float#

Returns the current gas limit for transactions.

set_gas_limit(gas_limit: float) None#

Sets the gas limit for transactions.

get_gas_price() float#

Returns the current gas price in GWei.

set_gas_price(gas_price: float) None#

Sets the gas price in GWei.

get_gas_priorityfee() float#

Returns the current priority fee in GWei.

set_gas_priorityfee(priority_fee: float) None#

Sets the priority fee in GWei.

get_max_slippage() float#

Returns the current maximum slippage as a float (0.01 is 1%).

set_max_slippage(max_slippage: float) None#

Sets the maximum slippage as a float (0.01 is 1%).

update_last_nonce() None#

Updates the last nonce to the current nonce of the wallet. This can be used to resync the nonce if transactions have been sent outside of this class or custom nonce is used.

stateview_get_fee_growth_globals(token0: str, token1: str, fee: int, tick_spacing: int, hooks: str) Dict#

Retrieves the global fee growth of a pool.

stateview_get_fee_growth_inside(token0: str, token1: str, fee: int, tick_spacing: int, hooks: str, tick_lower: int, tick_upper: int) Dict#

Calculates the fee growth inside a tick range of a pool

stateview_get_liquidity(token0: str, token1: str, fee: int, tick_spacing: int, hooks: str) int#

Retrieves the total liquidity of a pool.

stateview_get_position_info(token0: str, token1: str, fee: int, tick_spacing: int, hooks: str, owner: str, tick_lower: int, tick_upper: int, token_id: int) Dict#

Retrieves position info in a pool.

Parameters:

token_id – TokenID of the correspoding NFT

stateview_get_slot0(token0: str, token1: str, fee: int, tick_spacing: int, hooks: str) Dict#

Returns current state of the pool.

stateview_get_tick_bitmap(token0: str, token1: str, fee: int, tick_spacing: int, hooks: str, tick: int) int#

Retrieves the tick bitmap of a pool at a specific tick.

Parameters:

tick – MUST be int16

stateview_get_tick_fee_growth_outside(token0: str, token1: str, fee: int, tick_spacing: int, hooks: str, tick: int) Dict#

Retrieves the fee growth outside a tick range of a pool

stateview_get_tick_pool_info(token0: str, token1: str, fee: int, tick_spacing: int, hooks: str, tick: int) Dict#

Retrieves the tick information of a pool at a specific tick.

reserves_lens_get_pool_tvl(pool_key: PoolKey, custom_provider: str = '') Dict#

Retrieves the total value locked (TVL) of a pool. See Uniswap/v4-periphery for more details.

Parameters:
  • pool_key – The PoolKey object representing the pool.

  • custom_provider – The custom provider address, empty string for default.

Returns:

A dictionary containing the reserves of the pool.

reserves_lens_get_pool_tvl_batch(pool_keys: List[PoolKey], custom_provider: List[str] | None = None) List[Dict]#

Retrieves the total value locked (TVL) of multiple pools in a batch. See Uniswap/v4-periphery for more details.

Parameters:
  • pool_keys – A list of PoolKey objects representing the pools.

  • custom_provider – The custom provider addresses for each pool. If None, will use default for all pools.

Returns:

A list of dictionaries containing the reserves of each pool.

reserves_lens_get_tvl_paged(pool_key: PoolKey, cursor: bytes, custom_provider: str = '', max_reads: int = 0) Tuple[Dict, bytes, bool]#

Retrieves the total value locked (TVL) of multiple pools in a paged manner. See Uniswap/v4-periphery for more details.

Parameters:
  • pool_key – A list of PoolKey objects representing the pools.

  • cursor – The cursor for paged retrieval.

  • custom_provider – The custom provider address, empty string for default.

  • max_reads – The maximum number of reads to perform using custom provider.

Returns:

A tuple containing the reserves dictionary, the next cursor, and a boolean indicating if the paged retrieval is done.

reserves_lens_get_populated_ticks_in_word(pool_key: PoolKey, word_position: int) List[Dict]#

Retrieves the populated ticks in a specific word of a pool. See Uniswap/v4-periphery for more details.

Parameters:
  • pool_key – The PoolKey object representing the pool.

  • word_position – The position of the word to retrieve.

Returns:

A list of dictionaries containing the populated ticks.

position_descriptor_get_currency_ratio_priority(currency: str) int#

For certain currencies on mainnet, the smaller the currency, the higher the priority. And those with the higher priority values (more positive values) will be in the numerator of the price ratio

Returns:

The priority of a currency.

position_descriptor_get_flip_ratio(currency0: str, currency1: str) bool#
Returns:

True if currency0 has higher priority than currency1

position_descriptor_get_native_currency_label() str#
Returns:

The label for the native currency as a string

position_descriptor_get_pool_manager() str#
Returns:

PoolManager address as a string

position_descriptor_get_token_uri(pos_manager: str, token_id: int) str#

Produces the URI describing a particular token ID Note this URI may be a data: URI with the JSON contents directly inlined

Returns:

The URI of the ERC721-compliant metadata

position_descriptor_get_wrapped_native_address() str#
Returns:

The wrapped native currency address as a string

position_manager_get_domain_separator() bytes#
Returns:

The domain separator for the current chain; bytes32

position_manager_get_weth9() str#
Returns:

The wrapped native token address

position_manager_get_balance_of(address: str) int#
Returns:

The number of tokens in owner’s address.

position_manager_get_approved(token_id: int) str#
Returns:

The account approved for a token.

position_manager_get_pool_and_position_info(token_id: int) Dict#
Returns:

The PoolKey class object and position info of a position

position_manager_get_position_liquidity(token_id: int) int#
Returns:

The liquidity of a position

position_manager_get_is_approved_for_all(owner: str, operator: str) bool#
Returns:

True if the operator is allowed to manage all of the assets of owner

position_manager_get_msg_sender() str#
Returns:

address considered executor of the actions

The other context functions, _msgData and _msgValue, are not supported by this contract. In many contracts this will be the address that calls the initial entry point that calls _executeActions msg.sender shouldn’t be used, as this will be the v4 pool manager contract that calls unlockCallback If using ReentrancyLock.sol, this function can return _getLocker()

position_manager_get_name() str#
Returns:

The name of the PositionManager token

position_manager_get_next_token_id() int#
Returns:

The ID that will be used for the next minted liquidity position

position_manager_get_nonces(owner: str, word: int) int#
Returns:

Mapping of nonces consumed by each address, where a nonce is a single bit on the 256-bit bitmap

position_manager_get_owner_of(token_id: int) str#
Returns:

The owner of the position for a given token ID

position_manager_get_permit2() str#
Returns:

The Permit2 contract to forward approvals

position_manager_get_pool_keys(pool_id_trunc: bytes) PoolKey#
Parameters:

pool_id_trunc – The truncated ID of the pool, first 25 bytes of common pool_id

Returns:

The PoolKey class object for a given token ID

position_manager_get_position_info(token_id: int) int#
Returns:

The position info for a given token ID

position_manager_get_subscriber(token_id: int) str#
Returns:

The subscriber of the position for a given token ID

position_manager_get_is_support_interface(interface_id: bytes) bool#
Parameters:

interface_id – The interface ID to check; should be ‘bytes4’

Returns:

True if specifeid interface is supported by the PositionManager contract

position_manager_get_symbol() str#
Returns:

The symbol of the PositionManager token

position_manager_get_token_descriptor() str#
Returns:

The address of the PositionDescriptor contract as a string

position_manager_get_position_uri(token_id: int) str#
Returns:

The URI of the position manager’s ERC721-compliant metadata for a given token ID

position_manager_get_unsubscribe_gas_limit() int#
Returns:

The gas limit used when unsubscribing from a position.

position_manager_approve(spender: str, token_id: int) HexBytes#

Change or reaffirm the approved address for an NFT Zero address removes existing approval.

position_manager_initialize_pool(pool_key: PoolKey, sqrt_price_x96: int, payable_amount: int) HexBytes#

Initialize a Uniswap v4 Pool with the given parameters.

position_manager_modify_liquidities(unlock_data: bytes, deadline: int, payable_amount: int) HexBytes#

Unlocks Uniswap v4 PoolManager and batches actions for modifying liquidity

position_manager_modify_liquidities_without_unlock(actions: bytes, params: List[bytes], payable_amount: int) HexBytes#

Batches actions for modifying liquidity without unlocking v4 PoolManager

This must be called by a contract that has already unlocked the v4 PoolManager

position_manager_multicall(data: List[bytes], payable_amount: int) HexBytes#

Call multiple functions in the current contract in a single transaction, with the possibility of sending ETH along with the calls.

position_manager_permit(spender: str, token_id: int, deadline: int, nonce: int, signature: bytes, payable_amount: int) HexBytes#

Approve of a specific token ID for spending by spender via signature

position_manager_permit2_single(owner: str, permit_single: PermitSingle, signature: bytes, payable_amount: int) HexBytes#

Allows forwarding a single permit to permit2

position_manager_permit2_batch(owner: str, permit_batch: PermitBatch, signature: bytes, payable_amount: int) HexBytes#

Allows forwarding batch permits to permit2

position_manager_permit_for_all(owner: str, operator: str, approved: bool, deadline: int, nonce: int, signature: bytes, payable_amount: int) HexBytes#

Set an operator with full permission to an owner’s tokens via signature

position_manager_revoke_nonce(nonce: int, payable_amount: int) HexBytes#

Revoke a nonce by spending it, preventing it from being used again

position_manager_safe_transfer_from(from_addr: str, to_addr: str, token_id: int, payable_amount: int) HexBytes#

Transfer a position from one address to another

position_manager_safe_transfer_from_with_data(from_addr: str, to_addr: str, token_id: int, data: bytes, payable_amount: int) HexBytes#

Transfer a position from one address to another with additional data

position_manager_set_approval_for_all(operator: str, approved: bool, payable_amount: int) HexBytes#

Enable or disable approval for a third party (“operator”) to manage all of msg.sender’s assets

position_manager_subscribe(token_id: int, new_subscriber: str, data: bytes, payable_amount: int) HexBytes#

Enables the subscriber to receive notifications for a respective position

position_manager_transfer_from(from_addr: str, to_addr: str, token_id: int, payable_amount: int) HexBytes#

Overrides solmate transferFrom in case a notification to subscribers is needed

position_manager_unsubscribe(token_id: int, payable_amount: int) HexBytes#

Removes the subscriber from receiving notifications for a respective position

pool_manager_get_allowance(owner: str, spender: str, token_id: int) int#

Spender allowance of an id.

pool_manager_get_balance_of(address: str, token_id: int) int#

The number of tokens in owner’s address.

pool_manager_get_extsload(slot: bytes) bytes#

Called by external contracts to access granular pool state

pool_manager_get_extsload_sequence(start_slot: bytes, slots_count: int) List[bytes]#

Called by external contracts to access a sequence of storage slots

pool_manager_get_extsload_sparse(slots: List[bytes]) List[bytes]#

Called by external contracts to access a sparse set of storage slots

pool_manager_get_exttload_sparse(slots: List[bytes]) List[bytes]#

Called by external contracts to access sparse transient pool state

pool_manager_get_exttload(slot: bytes) bytes#

Called by external contracts to access transient storage of the contract

pool_manager_get_is_operator(owner: str, operator: str) bool#

Checks if a spender is approved by an owner as an operator

pool_manager_get_owner() str#

Retrieve the contract owner.

pool_manager_get_protocol_fee_controller() str#

Returns the current protocol fee controller address

pool_manager_get_protocol_fees_accrued(address: str) int#

Given a currency address, returns the protocol fees accrued in that currency.

pool_manager_get_supports_interface(interface_id: bytes) bool#

Checks if a given interface ID is supported by the contract

Parameters:

interface_id – The interface ID to check; should be bytes4

Returns:

True if specifeid interface is supported by the PoolManager contract

pool_manager_approve(spender: str, token_id: int, amount: int) HexBytes#

Approves an amount of an id to a spender.

pool_manager_burn(from_addr: str, token_id: int, amount: int) HexBytes#

Called by the user to move value from ERC6909 balance.

pool_manager_clear(currency: str, amount: int) HexBytes#

!!!WARNING!!! - Any currency that is cleared, will be non-retrievable, and locked in the contract permanently. A call to clear will zero out a positive balance WITHOUT a corresponding transfer. This could be used to clear a balance that is considered dust. Additionally, the amount must be the exact positive balance. This is to enforce that the caller is aware of the amount being cleared.

pool_manager_collect_protocol_fees(recipient: str, currency: str, amount: int) HexBytes#

Collects the protocol fees for a given recipient and currency, returning the amount collected This will revert if the contract is unlocked

pool_manager_donate(pool_key: PoolKey, amount0: int, amount1: int, hook_data: bytes) HexBytes#

Donate the given currency amounts to the in-range liquidity providers of a pool

pool_manager_initialize(pool_key: PoolKey, sqrt_price_x96: int) HexBytes#

Initialize the state for a given pool ID.

pool_manager_mint(to_addr: str, token_id: int, amount: int) HexBytes#

Called by the user to move value into ERC6909 balance.

pool_manager_modify_liquidity(pool_key: PoolKey, liquidity_params: ModifyLiquidityParams, hook_data: bytes) HexBytes#

Modify the liquidity for the given pool.

pool_manager_set_operator(operator: str, approved: bool) HexBytes#

Sets or removes an operator for the caller.

pool_manager_set_protocol_fee(pool_key: PoolKey, new_protocol_fee: int) HexBytes#

Sets the protocol fee for the given pool.

pool_manager_set_protocol_fee_controller(controller: str) HexBytes#

Sets a new protocol fee controller.

pool_manager_settle(payable_amount: int) HexBytes#

Called by the user to pay what is owed.

pool_manager_settle_for(recipient: str, payable_amount: int) HexBytes#

Called by the user to pay on behalf of another address.

pool_manager_swap(pool_key: PoolKey, params: SwapParams, hook_data: bytes) HexBytes#

Swap against the given pool.

pool_manager_sync(currency: str) HexBytes#

Writes the current ERC20 balance of the specified currency to transient storage. This is used to checkpoint balances for the manager and derive deltas for the caller. This MUST be called before any ERC20 tokens are sent into the contract, see documentation for more details.

pool_manager_take(currency: str, to_addr: str, amount: int) HexBytes#

Called by the user to net out some value owed to the user.

pool_manager_transfer(to_addr: str, token_id: int, amount: int) HexBytes#

Transfers an amount of an id from the caller to a receiver.

pool_manager_transfer_from(sender: str, receiver: str, token_id: int, amount: int) HexBytes#

Transfers an amount of an id from a sender to a receiver.

pool_manager_transfer_ownership(new_owner: str) HexBytes#

Transfers ownership of the contract to a new owner.

pool_manager_unlock(data: bytes) HexBytes#

All interactions on the contract that account deltas require unlocking. A caller that calls unlock must implement IUnlockCallback(msg.sender).unlockCallback(data), where they interact with the remaining functions on this contract.

pool_manager_update_dynamic_lp_fee(pool_key: PoolKey, new_dynamic_lp_fee: int) HexBytes#

Updates the pools lp fees for the a pool that has enabled dynamic lp fees.

get_token_token_spot_price(token0: str, token1: str, fee: int = 500, tick_spacing: int = 10, hooks: str = '0x0000000000000000000000000000000000000000') float#
Parameters:
  • token0 – The first token in the pair.

  • token1 – The second token in the pair.

  • fee – The fee tier for the swap.

  • tick_spacing – The tick spacing for the swap.

  • hooks – The hooks for the swap.

Returns:

The current spot price for token to token trades.

estimate_price_impact(token0: str, token1: str, qty: int, fee: int = 500, tick_spacing: int = 10, hooks: str = '0x0000000000000000000000000000000000000000', hook_data: bytes = b'') float#
Parameters:
  • token0 – The token to be sold.

  • token1 – The token to be bought.

  • qty – The amount of token0 to be sold.

  • fee – The fee tier for the swap.

  • tick_spacing – The tick spacing for the swap.

  • hooks – The hooks for the swap.

  • hook_data – The hook data for the swap.

Returns:

the estimated price impact as a positive float (0.01 = 1%).

See examples/v4_examples.py for an example which uses this.

NOTE: Does not support multi-hop swaps, should be used for single-hop swaps only.

get_quote_exact_input_single(token0: str, token1: str, qty: int, fee: int, tick_spacing: int, hooks: str = '0x0000000000000000000000000000000000000000', hook_data: bytes = b'') int#
Parameters:
  • token0 – The token to be sold.

  • token1 – The token to be bought.

  • qty – The amount of token0 to be sold.

  • fee – The fee tier for the swap.

  • tick_spacing – The tick spacing for the swap.

  • hooks – The hooks for the swap.

  • hook_data – The hook data for the swap.

Returns:

Quote for token to token single hop trades with an exact input.

get_quote_exact_input(token_exact: str, qty: int, route: List[PoolKey]) int#
Parameters:
  • token_exact – The token for which the qty parameter is specified.

  • qty – The amount of the token_exact to be swapped.

  • route – The list of PoolKeys representing the path of the swap, starting with the pool containing the input token and ending with the pool containing the output token.

Returns:

Quote for token to token multi-hop trades with an exact input.

get_quote_exact_output_single(token0: str, token1: str, qty: int, fee: int, tick_spacing: int, hooks: str = '0x0000000000000000000000000000000000000000', hook_data: bytes = b'') int#
Parameters:
  • token0 – The token to be sold.

  • token1 – The token to be bought.

  • qty – The amount of token1 to be bought.

  • fee – The fee tier for the swap.

  • tick_spacing – The tick spacing for the swap.

  • hooks – The hooks for the swap.

  • hook_data – The hook data for the swap.

Returns:

Quote for token to token single hop trades with an exact output.

get_quote_exact_output(token_exact: str, qty: int, route: List[PoolKey]) int#
Parameters:
  • token_exact – The token for which the qty parameter is specified, either the input or output token depending on the quote type.

  • qty – The amount of the token_exact to be swapped. For an exact output quote, this is the amount of output token desired.

  • route – The list of PoolKeys representing the path of the swap in reverse order, starting with the pool containing the output token and ending with the pool containing the input token.

Returns:

Quote for token to token multi-hop trades with an exact output.

get_price_input(token0: str, token1: str, qty: int, fee: int | None = None, tick_spacing: int | None = None, hooks: str | None = '0x0000000000000000000000000000000000000000', hook_data: bytes | None = b'', route: List[PoolKey] | None = None) int#
Parameters:
  • token0 – The token to be sold.

  • token1 – The token to be bought.

  • qty – The amount of token0 to be sold.

  • fee – Optional. The fee tier for the swap.

  • tick_spacing – Optional. The tick spacing for the swap.

  • hooks – Optional. The hooks for the swap.

  • hook_data – Optional. The hook data for the swap.

  • route – Optional. The route for the swap. The first element should be the pool containing token0 and the last element should be the pool containing token1.

Returns:

Returns the exact amount of token1 that can be received for qty amount of token0 at the current price.

If route is provided, it will be used for the quote. Otherwise, fee and tick_spacing must be provided for a single hop quote.

get_price_output(token0: str, token1: str, qty: int, fee: int | None = None, tick_spacing: int | None = None, hooks: str | None = '0x0000000000000000000000000000000000000000', hook_data: bytes | None = b'', route: List[PoolKey] | None = None) int#
Parameters:
  • token0 – The token to be sold.

  • token1 – The token to be bought.

  • qty – The amount of token1 to be bought.

  • fee – Optional. The fee tier for the swap.

  • tick_spacing – Optional. The tick spacing for the swap.

  • hooks – Optional. The hooks for the swap.

  • hook_data – Optional. The hook data for the swap.

  • route – Optional. The route for the swap in reverse order. The first element should be the pool containing token1 and the last element should be the pool containing token0.

Returns:

Returns the exact amount of token0 required to buy qty amount of token1 at the current price.

If route is provided, it will be used for the quote. Otherwise, fee and tick_spacing must be provided for a single hop quote.

token_to_token_swap_exact_input(input_token: str, qty: int, qtycap: int, output_token: str, fee: int, tick_spacing: int, hooks: str, hook_data: bytes = b'', min_hop_price_x_36: int = 0, custom_nonce: Nonce | None = None) HexBytes#
Parameters:
  • input_token – The token to be sold.

  • qty – The amount of input_token to be sold.

  • qtycap – The minimum amount of output_token that must be bought for the swap to succeed.

  • output_token – The token to be bought.

  • fee – The fee for the swap.

  • tick_spacing – The tick spacing for the swap.

  • hooks – The hooks for the swap.

  • hook_data – The hook data for the swap.

  • min_hop_price_x_36 – Optional. The minimum price for each hop in the route, expressed as an integer.

  • custom_nonce – Optional. The nonce to use for the transaction.

Swaps an exact amount of input_token for a minimum amount of output_token, reverting if the amount of output_token received is less than qtycap.

token_to_token_swap_input(input_token: str, qty: int, qtycap: int, route: List[PoolKey], min_hop_price_x_36: List[int] = [], custom_nonce: Nonce | None = None) HexBytes#
Parameters:
  • input_token – The token to be sold.

  • qty – The amount of input_token to be sold.

  • qtycap – The minimum amount of output_token that must be bought for the swap to succeed.

  • route – The list of PoolKeys representing the path of the swap. The first element should be the pool containing the input_token and the last element should be the pool containing the output_token.

  • min_hop_price_x_36 – Optional. A list of minimum prices for each hop in the route, expressed as a list of integers.

  • custom_nonce – Optional. The nonce to use for the transaction.

Swaps an exact amount of input_token for a minimum amount of output_token through a specified multi-hop route, reverting if the amount of output_token received is less than qtycap.

token_to_token_swap_exact_output(input_token: str, qty: int, qtycap: int, output_token: str, fee: int, tick_spacing: int, hooks: str, hook_data: bytes = b'', min_hop_price_x_36: int = 0, custom_nonce: Nonce | None = None) HexBytes#
Parameters:
  • input_token – The token to be sold.

  • qty – The amount of output_token to be bought.

  • qtycap – The maximum amount of input_token that can be sold for the trade to proceed.

  • output_token – The token to be bought.

  • fee – The fee for the swap.

  • tick_spacing – The tick spacing for the swap.

  • hooks – The hooks for the swap.

  • hook_data – The hook data for the swap.

  • min_hop_price_x_36 – Optional. The minimum price for each hop in the route, expressed as an integer.

  • custom_nonce – Optional. The nonce for the transaction.

token_to_token_swap_output(output_token: str, qty: int, qtycap: int, route: List[PoolKey], min_hop_price_x_36: List[int] = [], custom_nonce: Nonce | None = None) HexBytes#
Parameters:
  • output_token – The token to be bought.

  • qty – The amount of output_token to be bought.

  • qtycap – The maximum amount of input_token that can be sold for the trade to proceed.

  • route – The route for the swap in reverse order. The first element should be the pool containing output_token and the last element should be the pool containing input_token.

  • min_hop_price_x_36 – Optional. The minimum price for each hop in the route, expressed as a list of integers.

  • custom_nonce – Optional. The nonce for the transaction.

Swaps a maximum amount of input_token for an exact amount of output_token through a specified multi-hop route, reverting if the amount of input_token required is more than qtycap.

drop_txn(address_to: Address | ChecksumAddress, gas_price: float, priority_fee: int = 10, custom_nonce: Nonce | None = None) HexBytes#

Replaces pending transaction with zero-value ETH transfer

Parameters:

address_to – Zero address or any other valid address to which the zero-value transaction will be sent

Params gas_price and priority_fee are Gas Price and Max Priority Fee respectively; MUST be at least 20% higher than values the original transaction has.

make_swap_input(input_token: str, output_token: str, qty: int, qtycap: int, swap_pool_key: PoolKey | None = None, hook_data: bytes | None = b'', route: List[PoolKey] | None = None, custom_nonce: Nonce | None = None) HexBytes#
Parameters:
  • input_token – The token to be sold.

  • output_token – The token to be bought.

  • qty – The amount of input_token to be sold.

  • qtycap – The minimum amount of output_token that must be bought for the trade to proceed.

  • swap_pool_key – Optional. The PoolKey for the swap, required if route is not provided.

  • hook_data – Optional. The hook data for the swap. This is only used for single hop swaps and will be ignored if route is provided.

  • route – Optional. The route for the swap. The first element should be the pool containing input_token and the last element should be the pool containing output_token. If route is provided, it will be used for the swap instead of swap_pool_key.

  • custom_nonce – Optional. The nonce for the transaction.

Make a trade by defining the qty of the input token.

If route is provided, it will be used for the swap. Otherwise, swap_pool_key must be provided for a single hop swap.

make_swap_output(input_token: str, output_token: str, qty: int, qtycap: int, swap_pool_key: PoolKey | None = None, hook_data: bytes | None = b'', route: List[PoolKey] | None = None, custom_nonce: Nonce | None = None) HexBytes#
Parameters:
  • input_token – The token to be sold.

  • output_token – The token to be bought.

  • qty – The amount of output_token to be bought.

  • qtycap – The maximum amount of input_token that can be sold for the trade to proceed.

  • swap_pool_key – Optional. The PoolKey for the swap, required if route is not provided.

  • hook_data – Optional. The hook data for the swap.

  • route – Optional. The route for the swap in reverse order. The first element should be the pool containing output_token and the last element should be the pool containing input_token.

Make a trade by defining the qty of the output token. If route is provided, it will be used for the swap. Otherwise, swap_pool_key must be provided for a single hop swap.

get_position_info(token_id: int) Dict#

Get information about a liquidity position given its token ID. :return: A dictionary with the following keys:

  • currency0: The address of the first token in the pool

  • currency1: The address of the second token in the pool

  • fee: The fee tier of the pool

  • tickSpacing: The tick spacing of the pool

  • hooks: The hooks address of the pool

  • poolID: The truncated pool ID of the position, which is the first 25 bytes of the full pool ID

  • tickLower: The lower tick of the position

  • tickUpper: The upper tick of the position

  • hasSubscriber: A boolean indicating whether the position has a subscriber

  • owner: The address of the owner of the position

get_position_value(token_id: int, token0_decimals: int, token1_decimals: int) Dict#

Get the value of a liquidity position given its token ID.

create_pool(pool_key: PoolKey, sqrt_price_x96: int, custom_nonce: Nonce | None = None) HexBytes#

Creates a new liquidity pool without initial liquidity with the specified parameters and a starting price.

mint_position(pool_key: PoolKey, tick_lower: int, tick_upper: int, liquidity: int, amount0: int, amount1: int, recipient: str | None = None, hook_data: bytes | None = b'', custom_nonce: Nonce | None = None) HexBytes#

Mints a new liquidity position with the specified parameters.

Parameters:
  • pool_key – The parameters of the pool for which the position is being minted.

  • tick_lower – The lower tick of the position.

  • tick_upper – The upper tick of the position.

  • liquidity – The amount of liquidity to mint.

  • amount0 – The amount of token0 to provide as liquidity.

  • amount1 – The amount of token1 to provide as liquidity.

  • recipient – The address that will receive excessive ETH amounts. If None, it defaults to the caller’s address.

  • hook_data – Optional bytes that can be passed to the hooks during the minting.

Returns:

The transaction hash of the minting transaction.

increase_liquidity(pool_key: PoolKey, token_id: int, amount0_max: int, amount1_max: int, liquidity: int, recipient: str | None = None, hook_data: bytes | None = b'', custom_nonce: Nonce | None = None) HexBytes#

Increases the liquidity of an existing position.

Parameters:
  • pool_key – The parameters of the pool for which the position is being increased.

  • token_id – The token ID of the position to increase liquidity for.

  • amount0_max – The maximum amount of token0 to provide as liquidity.

  • amount1_max – The maximum amount of token1 to provide as liquidity.

  • liquidity – The amount of liquidity to add to the position.

  • recipient – The address that will receive excessive ETH amounts. If None, it defaults to the caller’s address.

  • hook_data – Optional bytes that can be passed to the hooks during the liquidity increase.

Returns:

The transaction hash of the liquidity increase transaction.

decrease_liquidity(pool_key: PoolKey, token_id: int, amount0_min: int, amount1_min: int, liquidity: int, recipient: str | None = None, hook_data: bytes | None = b'', custom_nonce: Nonce | None = None) HexBytes#

Decreases the liquidity of an existing position.

Parameters:
  • pool_key – The parameters of the pool for which the position is being decreased.

  • token_id – The token ID of the position to decrease liquidity for.

  • amount0_min – The minimum amount of token0 to receive from the liquidity decrease.

  • amount1_min – The minimum amount of token1 to receive from the liquidity decrease.

  • liquidity – The amount of liquidity to remove from the position.

  • recipient – The address that will receive the withdrawn liquidity. If None, it defaults to the caller’s address.

  • hook_data – Optional bytes that can be passed to the hooks during the liquidity decrease.

Returns:

The transaction hash of the liquidity decrease transaction.

collect_fees(pool_key: PoolKey, token_id: int, recipient: str | None = None, hook_data: bytes | None = b'', custom_nonce: Nonce | None = None) HexBytes#

Collects the fees accrued by an existing position.

Parameters:
  • pool_key – The parameters of the pool for which the position is collecting fees.

  • token_id – The token ID of the position for which to collect fees.

  • recipient – The address that will receive the collected fees. If None, it defaults to the caller’s address.

  • hook_data – Optional bytes that can be passed to the hooks during the fee collection.

Returns:

The transaction hash of the fee collection transaction.

burn_position(pool_key: PoolKey, token_id: int, amount0_min: int, amount1_min: int, recipient: str | None = None, hook_data: bytes | None = b'', custom_nonce: Nonce | None = None) HexBytes#

Burns an existing liquidity position.

Parameters:
  • pool_key – The parameters of the pool for which the position is being burned.

  • token_id – The token ID of the position to burn.

  • amount0_min – The minimum amount of token0 to receive from burning the position.

  • amount1_min – The minimum amount of token1 to receive from burning the position.

  • recipient – The address that will receive the withdrawn liquidity. If None, it defaults to the caller’s address.

  • hook_data – Optional bytes that can be passed to the hooks during the position burn.

Returns:

The transaction hash of the position burn transaction.

universal_router_execute(commands: List[int], actions: List[List[int]], params: List[List[List]], ether_amount: int = 0, custom_nonce: Nonce | None = None) HexBytes#

Executes a transaction with the Universal Router with the specified commands, actions, and parameters.

Parameters:
  • commands – A list of command integers corresponding to the commands to execute.

  • actions – A list of lists of action integers, where each sublist corresponds to the actions for the respective command in the commands list.

  • params – A list of lists of lists of parameters, where each sublist corresponds to the parameters for the respective actions in the actions list. The structure of the parameters should match the expected input for each action as defined in the Universal Router documentation.

  • ether_amount – The amount of ether to send with the transaction, if any.

  • custom_nonce – Optional. The nonce for the transaction.

See tests/test_uniswap4.py for an example which uses this, test_universal_router_execute_multiaction() specific test.

NOTE: This function does not perform checks on the validity of the commands SWAP_EXACT_IN* and SWAP_EXACT_OUT*. It is the caller’s responsibility to ensure that they are correct and will not cause the transaction to revert.

static get_liquidity_for_amount0(sqrt_ratio_a_x96: int, sqrt_ratio_b_x96: int, amount0: int) int#

Helper function to calculate the amount of liquidity that can be provided for a given amount of token0 and price range defined by sqrt_ ratio_a_x96 and sqrt_ratio_b_x96.

static get_liquidity_for_amount1(sqrt_ratio_a_x96: int, sqrt_ratio_b_x96: int, amount1: int) int#

Helper function to calculate the amount of liquidity that can be provided for a given amount of token1 and price range defined by sqrt_ratio_a_x96 and sqrt_ratio_b_x96.

get_liquidity_for_amounts(sqrt_ratio_a_x96: int, sqrt_ratio_b_x96: int, sqrt_ratio_current_x96: int, amount0: int, amount1: int) int#

Helper function to calculate the amount of liquidity that can be provided for given amounts of token0 and token1 and price range defined by sqrt_ratio_a_x96 and sqrt_ratio_b_x96.

static get_amount0_for_liquidity(sqrt_ratio_a_x96: int, sqrt_ratio_b_x96: int, liquidity: int) int#

Helper function to calculate the amount of token0 that can be provided for a given amount of liquidity and price range defined by sqrt_ratio_a_x96 and sqrt_ratio_b_x96.

static get_amount1_for_liquidity(sqrt_ratio_a_x96: int, sqrt_ratio_b_x96: int, liquidity: int) int#

Helper function to calculate the amount of token1 that can be provided for a given amount of liquidity and price range defined by sqrt_ratio_a_x96 and sqrt_ratio_b_x96.

get_amounts_for_liquidity(sqrt_ratio_a_x96: int, sqrt_ratio_b_x96: int, sqrt_ratio_current_x96: int, liquidity: int) Dict#

Helper function to calculate the amounts of token0 and token1 that can be provided for a given amount of liquidity and price range defined by sqrt_ratio_a_x96 and sqrt_ratio_b_x96.

get_minted_token_id(tx_hash: str) List[int]#

Helper function to extract the token ID of a newly minted position from the transaction receipt of the minting transaction.

Returns:

A list of token IDs of the newly minted positions; empty list if none can be extracted. In most cases, this list will contain only one token ID, but in some cases (e.g., if multiple positions are minted in a single transaction), it may contain multiple token IDs.

static decode_position_info(position_info: int) Dict#
return:

A dictionary with the following keys: - tickLower: The lower tick of the position. - tickUpper: The upper tick of the position. - poolID: The truncated pool ID of the position, which is the first 25 bytes of the full pool ID. - hasSubscriber: A boolean indicating whether the position has a subscriber.

static encode_path_keys_input(path: List[PoolKey], currency_in: str, hook_data_list: List[bytes] | None = None) List[PathKey]#

Encodes a list of PoolKeys into the format expected by the quoter for multi-hop ExactInput quotes.

static encode_path_keys_output(path: List[PoolKey], currency_out: str, hook_data_list: List[bytes] | None = None) List[PathKey]#

Encodes a list of PoolKeys into the format expected by the quoter for multi-hop ExactOutput quotes.

static get_pool_id(pool: PoolKey) HexBytes#

Computes the pool ID for a given PoolKey by hashing its parameters.

get_token(address: Address | ChecksumAddress, abi_name: str = 'erc20') ERC20Token#

Retrieves metadata from the ERC20 contract of a given token, like its name, symbol, and decimals.

get_token_balance(erc20: Address | ChecksumAddress) Decimal#

Get the balance of an ERC20 token for your address.

get_balance() Decimal#

Get the balance of ETH for your address.

Pools cache class#

class uniswap.util.V4pools(web3: Web3)#

Uniswap V4 pools handler

Parameters:

web3 – Web3 instance connected to the network for which pool data is being fetched.

get_last_block() int#

Returns last block number processed by fetch_poolkey_data() method.

set_last_block(value: int) None#

Sets last block number processed by fetch_poolkey_data() method.

fetch_poolkey_data(first_block: int, chunk_size: int = 500, clear_list: bool = True, retry_attempts: int = 3, minutes_between_retries: int = 3, last_block: int | None = None) int#
Parameters:
  • first_block – Starting block for scanning process

  • chunk_size – Defines amount of blocks per single log request

  • clear_list – When True, clears pool list before log scanning, when False - new entries will be added to the end of the list.

  • retry_attempts – Number of attempts to retry and resume log retrieval in case of RPC returns errors like 500 etc.

  • minutes_between_retries – Minutes to wait between retry attempts.

  • last_block – Optional parameter defining the last block for scanning process. If None, current block number will be used.

Returns:

0 if logs were successfully processed, -1 if logs retrieval failed (e.g. due to wrong chunk size or RPC endpoint failure).

save_poolkeys_list(poolkey_data_filename: str) None#

Saves poolKey list to specified file (XML format)

load_poolkeys_list(poolkey_data_filename: str) None#

Loads poolKey list from specified file (XML format)

get_poolkeys_sublist(currency0: str, currency1: str) List[PoolKey]#

Returns all pools for the (currency0, currency1) pair

Token class#

class uniswap.token.BaseToken(symbol: str, address: Address | ChecksumAddress)#

Base for tokens of all kinds

symbol: str#

Symbol such as ETH, DAI, etc.

address: Address | ChecksumAddress#

Address of the token contract.

class uniswap.token.ERC20Token(symbol: str, address: Address | ChecksumAddress, name: str, decimals: int)#

Represents an ERC20 token

name: str#

Name of the token, as specified in the contract.

symbol: str#

Symbol such as ETH, DAI, etc.

address: Address | ChecksumAddress#

Address of the token contract.

decimals: int#

Decimals used to denominate the token.

Exceptions#

exception uniswap.exceptions.InvalidToken(address: Any)#

Raised when an invalid token address is used.

exception uniswap.exceptions.InsufficientBalance(had: int, needed: int)#

Raised when the account has insufficient balance for a transaction.