uniswap_viewer.utils

utils.py - Utility functions and constants for the uniswap_viewer library.

This module provides common helpers used throughout the uniswap_viewer codebase, including:

  • A list of standard tick keys used in Uniswap V3 pools.
  • A helper function to filter out zero addresses.
  • A utility to load ABI definitions from local JSON files.

The module assumes ABI files are located under the uniswap_viewer/source package.

Typical use cases:

  • Filtering out empty Ethereum addresses before display or storage.
  • Loading ABI files to construct contract instances via web3.py.
  • Interpreting tick data retrieved from Uniswap V3 pools.

All functions are intended for internal use, but may also be helpful for developers extending or integrating the uniswap_viewer library.

  1"""
  2utils.py - Utility functions and constants for the uniswap_viewer library.
  3
  4This module provides common helpers used throughout the uniswap_viewer codebase,
  5including:
  6
  7- A list of standard tick keys used in Uniswap V3 pools.
  8- A helper function to filter out zero addresses.
  9- A utility to load ABI definitions from local JSON files.
 10
 11The module assumes ABI files are located under the `uniswap_viewer/source` 
 12package.
 13
 14Typical use cases:
 15- Filtering out empty Ethereum addresses before display or storage.
 16- Loading ABI files to construct contract instances via web3.py.
 17- Interpreting tick data retrieved from Uniswap V3 pools.
 18
 19All functions are intended for internal use, but may also be helpful for
 20developers extending or integrating the uniswap_viewer library.
 21"""
 22
 23import re
 24import json
 25import time
 26from importlib import resources
 27from typing import Optional
 28
 29
 30REGEX_ADDRESS = re.compile(r'^0x[0-9a-fA-F]{40}$')
 31"""
 32A compiled regular expression to match valid Ethereum addresses.
 33
 34Matches any string that starts with '0x' followed by exactly 40 hexadecimal 
 35characters (case-insensitive).
 36
 37Example:
 38    >>> REGEX_ADDRESS.match("0x1234567890abcdef1234567890abcdef12345678") is not None
 39    True
 40    >>> REGEX_ADDRESS.match("not-an-address") is None
 41    True
 42"""
 43
 44
 45TICKS_KEYS = [
 46    'liquidityGross',
 47    'liquidityNet',
 48    'feeGrowthOutside0X128',
 49    'feeGrowthOutside1X128',
 50    'tickCumulativeOutside',
 51    'secondsPerLiquidityOutsideX128',
 52    'secondsOutside',
 53    'initialized',
 54]
 55"""
 56Keys used in Uniswap V3 tick structure.
 57"""
 58
 59
 60TOKEN_MAP = {
 61    "WETH": "0xC02aaA39b223FE8D0A0E5C4F27eAD9083C756Cc2",
 62    "USDT": "0xdAC17F958D2ee523a2206206994597C13D831ec7",
 63    "USDC": "0xA0b86991C6218B36c1d19D4a2e9Eb0cE3606eB48",
 64    "DAI": "0x6B175474E89094C44Da98b954EedeAC495271d0F",
 65    "WBTC": "0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599",
 66    "UNI": "0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984",
 67    "LINK": "0x514910771AF9Ca656af840dff83E8264EcF986CA",
 68    "AAVE": "0x7Fc66500c84A76Ad7e9c93437bFc5Ac33E2DDaE9",
 69    "COMP": "0xc00e94Cb662C3520282E6f5717214004A7f26888",
 70    "MKR": "0x9f8F72aA9304c8B593d555F12eF6589cC3A579A2",
 71    "SNX": "0xC011A72400E58ecD99Ee497CF89E3775d4bd732F",
 72    "YFI": "0x0bc529c00C6401aEF6D220BE8C6Ea1667F6Ad93e",
 73    "BAT": "0x0D8775F648430679A709E98d2b0Cb6250d2887EF",
 74    "ZRX": "0xE41d2489571d322189246DaFA5ebDe1F4699F498",
 75    "MANA": "0x0f5D2fB29fb7d3CFeE444a200298f468908cC942",
 76}
 77"""
 78List of the most liquid tokens on Uniswap V3.
 79"""
 80
 81
 82def address_checked(address: str) -> Optional[str]:
 83    """
 84    Returns the address if it's not the zero address, otherwise returns None.
 85
 86    This function is used to filter out null Ethereum addresses typically
 87    represented as "0x0000000000000000000000000000000000000000".
 88
 89    Args:
 90        address (str): The Ethereum address to check.
 91
 92    Returns:
 93        str or None: The original address if valid, otherwise None.
 94
 95    Example:
 96        >>> address_checked("0x0000000000000000000000000000000000000000")
 97        None
 98        >>> address_checked("0x1234567890abcdef1234567890abcdef12345678")
 99        '0x1234567890abcdef1234567890abcdef12345678'
100    """
101    if address != "0x0000000000000000000000000000000000000000":
102        return address
103    else:
104        return None
105
106
107def get_abi(abi: str) -> str:
108    """
109    Loads a JSON ABI file from the `uniswap_viewer.source` package.
110
111    The function expects the ABI file to be named `<abi>.json` and
112    located in the `uniswap_viewer/source` package directory.
113
114    Args:
115        abi (str): The name of the ABI file (without `.json` extension).
116
117    Returns:
118        dict: The parsed JSON ABI object.
119
120    Raises:
121        FileNotFoundError: If the ABI file does not exist.
122        json.JSONDecodeError: If the file content is not valid JSON.
123
124    Example:
125        >>> pool_abi = get_abi("pool-api")
126    """
127    file = resources.files("uniswap_viewer.source").joinpath(f"{abi}.json")
128    with file.open(mode='r') as f:
129        return json.load(f)
130
131
132def get_token_address(symbol: str) -> str:
133    """
134    Returns the Ethereum address of a commonly used token on Uniswap V3 by its 
135    symbol.
136
137    Looks up the token symbol in a predefined dictionary of liquid tokens 
138    supported by the `uniswap-viewer` library. The symbol matching is 
139    case-insensitive.
140
141    Args:
142        symbol (str): The token symbol (e.g., "USDC", "WETH", "DAI").
143
144    Returns:
145        str: The Ethereum address of the corresponding token.
146
147    Raises:
148        KeyError: If the symbol is not found in the internal token map.
149
150    Example:
151        >>> get_token_address("usdc")
152        '0xA0b86991C6218B36c1d19D4a2e9Eb0cE3606eB48'
153    """
154    try:
155        return TOKEN_MAP[symbol.upper()]
156    except KeyError as exc:
157        raise KeyError(
158            f"Could not find address {str(exc)} within uniswap-viewer library"
159        )
160
161
162def prepare_token_address(token_or_symbol: str) -> str:
163    """
164    Resolves either a token symbol or an Ethereum address to a valid address 
165    string.
166
167    If the input matches the standard Ethereum address format (via 
168    REGEX_ADDRESS), it is returned as-is. Otherwise, the function looks up the 
169    symbol in the internal token map using `get_token_address`.
170
171    Args:
172        token_or_symbol (str): Either a token symbol (e.g. "DAI", "USDC")
173                               or a full Ethereum address.
174
175    Returns:
176        str: A valid Ethereum address.
177
178    Raises:
179        KeyError: If a non-address string is provided and not found in the token 
180                  map.
181
182    Example:
183        >>> prepare_token_address("DAI")
184        '0x6B175474E89094C44Da98b954EedeAC495271d0F'
185        >>> prepare_token_address("0x1234567890abcdef1234567890abcdef12345678")
186        '0x1234567890abcdef1234567890abcdef12345678'
187    """
188    if REGEX_ADDRESS.match(token_or_symbol):
189        return token_or_symbol
190    else:
191        return get_token_address(token_or_symbol)
REGEX_ADDRESS = re.compile('^0x[0-9a-fA-F]{40}$')

A compiled regular expression to match valid Ethereum addresses.

Matches any string that starts with '0x' followed by exactly 40 hexadecimal characters (case-insensitive).

Example:

REGEX_ADDRESS.match("0x1234567890abcdef1234567890abcdef12345678") is not None True REGEX_ADDRESS.match("not-an-address") is None True

TICKS_KEYS = ['liquidityGross', 'liquidityNet', 'feeGrowthOutside0X128', 'feeGrowthOutside1X128', 'tickCumulativeOutside', 'secondsPerLiquidityOutsideX128', 'secondsOutside', 'initialized']

Keys used in Uniswap V3 tick structure.

TOKEN_MAP = {'WETH': '0xC02aaA39b223FE8D0A0E5C4F27eAD9083C756Cc2', 'USDT': '0xdAC17F958D2ee523a2206206994597C13D831ec7', 'USDC': '0xA0b86991C6218B36c1d19D4a2e9Eb0cE3606eB48', 'DAI': '0x6B175474E89094C44Da98b954EedeAC495271d0F', 'WBTC': '0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599', 'UNI': '0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984', 'LINK': '0x514910771AF9Ca656af840dff83E8264EcF986CA', 'AAVE': '0x7Fc66500c84A76Ad7e9c93437bFc5Ac33E2DDaE9', 'COMP': '0xc00e94Cb662C3520282E6f5717214004A7f26888', 'MKR': '0x9f8F72aA9304c8B593d555F12eF6589cC3A579A2', 'SNX': '0xC011A72400E58ecD99Ee497CF89E3775d4bd732F', 'YFI': '0x0bc529c00C6401aEF6D220BE8C6Ea1667F6Ad93e', 'BAT': '0x0D8775F648430679A709E98d2b0Cb6250d2887EF', 'ZRX': '0xE41d2489571d322189246DaFA5ebDe1F4699F498', 'MANA': '0x0f5D2fB29fb7d3CFeE444a200298f468908cC942'}

List of the most liquid tokens on Uniswap V3.

def address_checked(address: str) -> Optional[str]:
 83def address_checked(address: str) -> Optional[str]:
 84    """
 85    Returns the address if it's not the zero address, otherwise returns None.
 86
 87    This function is used to filter out null Ethereum addresses typically
 88    represented as "0x0000000000000000000000000000000000000000".
 89
 90    Args:
 91        address (str): The Ethereum address to check.
 92
 93    Returns:
 94        str or None: The original address if valid, otherwise None.
 95
 96    Example:
 97        >>> address_checked("0x0000000000000000000000000000000000000000")
 98        None
 99        >>> address_checked("0x1234567890abcdef1234567890abcdef12345678")
100        '0x1234567890abcdef1234567890abcdef12345678'
101    """
102    if address != "0x0000000000000000000000000000000000000000":
103        return address
104    else:
105        return None

Returns the address if it's not the zero address, otherwise returns None.

This function is used to filter out null Ethereum addresses typically represented as "0x0000000000000000000000000000000000000000".

Args: address (str): The Ethereum address to check.

Returns: str or None: The original address if valid, otherwise None.

Example:

address_checked("0x0000000000000000000000000000000000000000") None address_checked("0x1234567890abcdef1234567890abcdef12345678") '0x1234567890abcdef1234567890abcdef12345678'

def get_abi(abi: str) -> str:
108def get_abi(abi: str) -> str:
109    """
110    Loads a JSON ABI file from the `uniswap_viewer.source` package.
111
112    The function expects the ABI file to be named `<abi>.json` and
113    located in the `uniswap_viewer/source` package directory.
114
115    Args:
116        abi (str): The name of the ABI file (without `.json` extension).
117
118    Returns:
119        dict: The parsed JSON ABI object.
120
121    Raises:
122        FileNotFoundError: If the ABI file does not exist.
123        json.JSONDecodeError: If the file content is not valid JSON.
124
125    Example:
126        >>> pool_abi = get_abi("pool-api")
127    """
128    file = resources.files("uniswap_viewer.source").joinpath(f"{abi}.json")
129    with file.open(mode='r') as f:
130        return json.load(f)

Loads a JSON ABI file from the uniswap_viewer.source package.

The function expects the ABI file to be named <abi>.json and located in the uniswap_viewer/source package directory.

Args: abi (str): The name of the ABI file (without .json extension).

Returns: dict: The parsed JSON ABI object.

Raises: FileNotFoundError: If the ABI file does not exist. json.JSONDecodeError: If the file content is not valid JSON.

Example:

pool_abi = get_abi("pool-api")

def get_token_address(symbol: str) -> str:
133def get_token_address(symbol: str) -> str:
134    """
135    Returns the Ethereum address of a commonly used token on Uniswap V3 by its 
136    symbol.
137
138    Looks up the token symbol in a predefined dictionary of liquid tokens 
139    supported by the `uniswap-viewer` library. The symbol matching is 
140    case-insensitive.
141
142    Args:
143        symbol (str): The token symbol (e.g., "USDC", "WETH", "DAI").
144
145    Returns:
146        str: The Ethereum address of the corresponding token.
147
148    Raises:
149        KeyError: If the symbol is not found in the internal token map.
150
151    Example:
152        >>> get_token_address("usdc")
153        '0xA0b86991C6218B36c1d19D4a2e9Eb0cE3606eB48'
154    """
155    try:
156        return TOKEN_MAP[symbol.upper()]
157    except KeyError as exc:
158        raise KeyError(
159            f"Could not find address {str(exc)} within uniswap-viewer library"
160        )

Returns the Ethereum address of a commonly used token on Uniswap V3 by its symbol.

Looks up the token symbol in a predefined dictionary of liquid tokens supported by the uniswap-viewer library. The symbol matching is case-insensitive.

Args: symbol (str): The token symbol (e.g., "USDC", "WETH", "DAI").

Returns: str: The Ethereum address of the corresponding token.

Raises: KeyError: If the symbol is not found in the internal token map.

Example:

get_token_address("usdc") '0xA0b86991C6218B36c1d19D4a2e9Eb0cE3606eB48'

def prepare_token_address(token_or_symbol: str) -> str:
163def prepare_token_address(token_or_symbol: str) -> str:
164    """
165    Resolves either a token symbol or an Ethereum address to a valid address 
166    string.
167
168    If the input matches the standard Ethereum address format (via 
169    REGEX_ADDRESS), it is returned as-is. Otherwise, the function looks up the 
170    symbol in the internal token map using `get_token_address`.
171
172    Args:
173        token_or_symbol (str): Either a token symbol (e.g. "DAI", "USDC")
174                               or a full Ethereum address.
175
176    Returns:
177        str: A valid Ethereum address.
178
179    Raises:
180        KeyError: If a non-address string is provided and not found in the token 
181                  map.
182
183    Example:
184        >>> prepare_token_address("DAI")
185        '0x6B175474E89094C44Da98b954EedeAC495271d0F'
186        >>> prepare_token_address("0x1234567890abcdef1234567890abcdef12345678")
187        '0x1234567890abcdef1234567890abcdef12345678'
188    """
189    if REGEX_ADDRESS.match(token_or_symbol):
190        return token_or_symbol
191    else:
192        return get_token_address(token_or_symbol)

Resolves either a token symbol or an Ethereum address to a valid address string.

If the input matches the standard Ethereum address format (via REGEX_ADDRESS), it is returned as-is. Otherwise, the function looks up the symbol in the internal token map using get_token_address.

Args: token_or_symbol (str): Either a token symbol (e.g. "DAI", "USDC") or a full Ethereum address.

Returns: str: A valid Ethereum address.

Raises: KeyError: If a non-address string is provided and not found in the token map.

Example:

prepare_token_address("DAI") '0x6B175474E89094C44Da98b954EedeAC495271d0F' prepare_token_address("0x1234567890abcdef1234567890abcdef12345678") '0x1234567890abcdef1234567890abcdef12345678'