### Manage tokens via CLI Source: https://github.com/apeworx/ape-tokens/blob/main/README.md Commands for installing, listing, and getting help for token management. ```bash ape tokens install tokens.1inch.eth ``` ```bash ape tokens list-tokens ``` ```bash ape tokens --help ``` -------------------------------- ### Install ape-tokens from source Source: https://github.com/apeworx/ape-tokens/blob/main/README.md Clone the repository and set up the development environment. ```bash git clone https://github.com/ApeWorX/ape-tokens.git cd ape-tokens uv sync --group dev uv run prek install ``` -------------------------------- ### ape tokens install Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/MODULES.md Installs a token list from a specified URI. ```APIDOC ## ape tokens install ### Description Installs a token list from the provided HTTP(S) URI. ### Parameters - **uri** (string) - Required - The URL to the token list JSON file. ``` -------------------------------- ### Initialize ListInfo Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/types.md Example of instantiating a ListInfo object for a token list. ```python from ape_tokens.config import ListInfo coingecko = ListInfo( name="CoinGecko", uri="https://tokens.coingecko.com/uniswap/all.json" ) ``` -------------------------------- ### Troubleshooting Token List Installation Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/configuration.md Commands and configuration snippets to verify and fix token list installation issues. ```bash ape tokens list-tokens ``` ```yaml tokens: required: - name: "MyList" uri: "https://..." # Verify URI is correct ``` ```bash ape tokens install ``` -------------------------------- ### Install ape-tokens via pip Source: https://github.com/apeworx/ape-tokens/blob/main/README.md Install the latest release of the plugin using pip. ```bash pip install ape-tokens ``` -------------------------------- ### Project-specific YAML configuration Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/configuration.md Example configuration tailored for a specific DeFi protocol project. ```yaml # ape-config.yaml for a DeFi protocol project tokens: default: "Protocol" required: - name: "Protocol" uri: "https://app.protocol.io/tokenlist.json" - name: "CoinGecko" uri: "https://tokens.coingecko.com/uniswap/all.json" ``` -------------------------------- ### Minimal YAML configuration Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/configuration.md A basic configuration example defining one default and one required token list. ```yaml # ape-config.yaml tokens: default: "CoinGecko" required: - name: "CoinGecko" uri: "https://tokens.coingecko.com/uniswap/all.json" ``` -------------------------------- ### Configure Tokens via YAML Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/types.md Example configuration for ape-config.yaml defining default and required token lists. ```yaml tokens: default: "CoinGecko" required: - name: "CoinGecko" uri: "https://tokens.coingecko.com/uniswap/all.json" - name: "1inch" uri: "https://tokens.1inch.eth/" ``` -------------------------------- ### ape tokens list-tokens Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/MODULES.md Lists all currently installed tokens. ```APIDOC ## ape tokens list-tokens ### Description Displays a list of all tokens currently installed in the environment. ``` -------------------------------- ### Retrieve tokens Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/api-reference/Converters.md Fetch all tokens from installed lists for the current chain. ```python def get_tokens(self) -> Iterator[TokenInfo] ``` -------------------------------- ### Convert Tokens using Ape Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/api-reference/Converters.md Demonstrates how to use the convert function to resolve token amounts and addresses after the plugin is installed. ```python from ape import convert # This uses TokenAmountConverter internally usdc_amount = convert("100.5 USDC", int) print(usdc_amount) # 100500000 # This uses TokenSymbolConverter internally usdc_address = convert("USDC", "address") print(usdc_address) # 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48 ``` -------------------------------- ### Cloud deployment script Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/configuration.md Example shell script for setting environment variables before running an Ape script. ```bash #!/bin/bash # deployment.sh export APE_TOKENS_DEFAULT="CoinGecko" export APE_TOKENS_REQUIRED='[ {"name":"CoinGecko","uri":"https://tokens.coingecko.com/uniswap/all.json"} ]' # Run your Ape script python my_script.py ``` -------------------------------- ### Safely Retrieve TokenBalances with get Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/api-reference/BalanceManager.md Use the get method to safely check for a token's presence in the manager without raising a KeyError. ```python from ape_tokens import BalanceManager manager = BalanceManager("USDC") if usdc_bal := manager.get("USDC"): print(f"USDC in manager") else: print("USDC not monitored") if weth_bal := manager.get("WETH"): print("WETH in manager") else: print("WETH not monitored") ``` -------------------------------- ### Multiple token lists configuration Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/configuration.md Example of defining multiple required token lists in a YAML configuration file. ```yaml # ape-config.yaml tokens: default: "Uniswap" required: - name: "Uniswap" uri: "https://uniswap.org/tokenlist.json" - name: "CoinGecko" uri: "https://tokens.coingecko.com/uniswap/all.json" - name: "1inch" uri: "https://tokens.1inch.eth/" ``` -------------------------------- ### Use tokens in transactions Source: https://github.com/apeworx/ape-tokens/blob/main/README.md Examples of using token strings in contract calls and conversions. ```python from ape import accounts, project my_account = accounts[0] contract = my_account.deploy(project.MyContract) tx = contract.provideLinkTokens("8.23 LINK", sender=me) ``` ```python from ape import convert convert("100.1234 BAT", int) ``` ```python tx = swapper.swap("BAT", "LINK", "10 BAT", sender=me) ``` -------------------------------- ### monitor(bot, *accounts) Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/api-reference/BalanceManager.md Installs balance monitoring on a Silverback bot, registering event handlers to track transfers and maintain an in-memory cache. ```APIDOC ## monitor(bot, *accounts) ### Description Install balance monitoring on a Silverback bot. Registers event handlers to track Transfer events for all configured tokens and maintains an in-memory cache of balances that updates in real-time. ### Parameters - **bot** (SilverbackBot) - Required - The Silverback bot instance to install monitoring on - **accounts** (BaseAddress | AddressType | str) - Optional - Additional accounts to monitor. Always includes bot.signer if configured ### Raises - **ValueError** - If no accounts are provided and bot.signer is not configured ``` -------------------------------- ### Define TokensConfig Configuration Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/MODULES.md Defines the plugin configuration settings including default lists and required installations. ```python class TokensConfig(PluginConfig): default: str | None = None required: list[ListInfo] = [] model_config = SettingsConfigDict(env_prefix="APE_TOKENS_") ``` -------------------------------- ### Symbol Resolution Examples Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/MODULES.md Demonstrates valid and invalid import patterns based on the module's lazy attribute resolution. ```python from ape_tokens import tokens # Uses __getattr__("tokens") from ape_tokens import TokenManager # AttributeError - must use ape_tokens.managers from ape_tokens.managers import TokenManager # Direct import - works ``` -------------------------------- ### Define TokenBalances get method Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/api-reference/BalanceManager.md Fetches the current balance of an account by querying the blockchain directly. ```python def get(self, acct: "BaseAddress | AddressType | str") -> Decimal ``` -------------------------------- ### Configuring Invalid Token List URI Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/errors.md Example of an invalid URI configuration in the ape-config.yaml file. ```yaml # ape-config.yaml tokens: required: - name: "BadList" uri: "https://invalid-uri-that-does-not-exist.example.com/" ``` -------------------------------- ### Token List Name Mismatch Warning Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/configuration.md Example of the warning message logged when the configured token list name differs from the metadata name in the JSON file. ```text WARNING: Installed list name 'ActualName' does not match requirement 'ExpectedName'. This could be problematic. ``` -------------------------------- ### Perform basic balance queries Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/api-reference/BalanceManager.md Demonstrates initializing the BalanceManager and fetching balances for multiple tokens. ```python from ape_tokens import BalanceManager from decimal import Decimal manager = BalanceManager("USDC", "WETH", "DAI") account = "0x742d35Cc6634C0532925a3b844Bc9e7595f7bEb" # Get balance for each token usdc_balance = manager.get_balance("USDC", account) weth_balance = manager.get_balance("WETH", account) dai_balance = manager.get_balance("DAI", account) print(f"USDC: {usdc_balance}") print(f"WETH: {weth_balance}") print(f"DAI: {dai_balance}") # Check if balance is above threshold if usdc_balance > Decimal("1000"): print("Good USDC balance") ``` -------------------------------- ### Catching Configuration Errors Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/errors.md Demonstrates how to catch exceptions that occur during plugin initialization due to invalid configuration. ```python from ape_tokens import tokens # If configuration has invalid URI, this fails during import: # ImportError: Token list installation failed try: from ape_tokens import TokenManager manager = TokenManager() except (ValueError, ImportError) as e: print(f"Configuration error: {e}") ``` -------------------------------- ### Test EIP-712 Permit with MockERC20 Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/api-reference/MockERC20.md Demonstrates how to set up a MockERC20 token and prepare for permit-based transactions in a test environment. ```python from ape_tokens.testing import MockERC20 from ape import accounts from eth_account.messages import encode_structured_data import time def test_permit(): owner = accounts[0] spender = accounts[1] user = accounts[2] usdc = MockERC20.deploy(owner, "USD Coin", "USDC", 6, sender=owner) # Mint to user usdc.mint(user, 1000 * (10 ** 6), sender=owner) # Create permit signature (example using eth-account) # This is a simplified example; actual permit signing is more complex deadline = int(time.time()) + 3600 # Permit allows spender to spend tokens without separate approve tx # Requires EIP-712 signature generation (handled by eth-account library) # After permit is signed and broadcast: # usdc.permit(user, spender, amount, deadline, v, r, s, sender=spender) # The spender can then transfer tokens # usdc.transferFrom(user, spender, amount, sender=spender) ``` -------------------------------- ### Generate Documentation Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/MODULES.md Build HTML documentation using sphinx-ape or mkdocs. ```bash # Using sphinx-ape (if installed) sphinx-build -b html . _build/html # Or using mkdocs (if configured) mkdocs build ``` -------------------------------- ### Deploy MockERC20 tokens Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/api-reference/MockERC20.md Demonstrates deploying mock ERC20 tokens with specific names, symbols, and decimal configurations. ```python from ape_tokens.testing import MockERC20 from ape import accounts def test_token_deployment(): owner = accounts[0] # Deploy test tokens usdc = MockERC20.deploy(owner, "USD Coin", "USDC", 6, sender=owner) weth = MockERC20.deploy(owner, "Wrapped Ether", "WETH", 18, sender=owner) # Verify deployment assert usdc.name() == "USD Coin" assert usdc.symbol() == "USDC" assert usdc.decimals() == 6 assert weth.decimals() == 18 ``` -------------------------------- ### Mint MockERC20 tokens Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/api-reference/MockERC20.md Shows how to mint tokens to a specific account and verify the resulting balances. ```python from ape_tokens.testing import MockERC20 from ape import accounts def test_token_minting(): owner = accounts[0] user1 = accounts[1] usdc = MockERC20.deploy(owner, "USD Coin", "USDC", 6, sender=owner) # Mint tokens to user amount = 1000 * (10 ** 6) # 1000 USDC usdc.mint(user1, amount, sender=owner) # Verify balance assert usdc.balanceOf(user1) == amount assert usdc.totalSupply() == amount ``` -------------------------------- ### Get BalanceManager representation Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/api-reference/BalanceManager.md Returns a string representation of the BalanceManager instance indicating the number of monitored tokens. ```python def __repr__(self) -> str ``` -------------------------------- ### Get the number of tokens Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/api-reference/TokenManager.md Returns the total count of tokens in the currently configured default token list. ```python from ape_tokens import tokens num_tokens = len(tokens) print(f"Token list contains {num_tokens} tokens") ``` -------------------------------- ### Query balances with BalanceManager Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/00-START-HERE.md Initialize a manager for specific tokens and retrieve account balances. ```python from ape_tokens import BalanceManager manager = BalanceManager("USDC", "WETH") usdc_balance = manager.get_balance("USDC", account) ``` -------------------------------- ### Initialize BalanceManager Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/api-reference/BalanceManager.md Initialize the manager with specific tokens or default to the configured token list. ```python from ape_tokens import BalanceManager, tokens # Monitor only specific tokens usdc = tokens["USDC"] manager = BalanceManager(usdc, "WETH", "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48") # Monitor all configured tokens (default tokenlist) manager_all = BalanceManager() ``` -------------------------------- ### Approve and transferFrom tokens Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/api-reference/MockERC20.md Demonstrates the approval workflow and using transferFrom to move tokens on behalf of another account. ```python from ape_tokens.testing import MockERC20 from ape import accounts def test_approve_and_transfer_from(): owner = accounts[0] user1 = accounts[1] spender = accounts[2] usdc = MockERC20.deploy(owner, "USD Coin", "USDC", 6, sender=owner) # Mint tokens amount = 1000 * (10 ** 6) usdc.mint(user1, amount, sender=owner) # Approve spender approval_amount = 500 * (10 ** 6) usdc.approve(spender, approval_amount, sender=user1) assert usdc.allowance(user1, spender) == approval_amount # Transfer from approved account transfer_amount = 100 * (10 ** 6) usdc.transferFrom(user1, spender, transfer_amount, sender=spender) # Verify balances and allowance assert usdc.balanceOf(user1) == amount - transfer_amount assert usdc.balanceOf(spender) == transfer_amount assert usdc.allowance(user1, spender) == approval_amount - transfer_amount ``` -------------------------------- ### Clearing Cached Token Lists Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/configuration.md Remove cached token lists to force a fresh installation from configured URIs. ```bash rm -rf ~/.ape/token-lists/ ``` -------------------------------- ### Load token by address Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/types.md Demonstrates loading a token contract instance using the Token singleton without requiring a token list configuration. ```python from ape_tokens import Token # Load token by address without requiring token list configuration usdc = Token.at("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48") print(usdc.symbol()) # "USDC" ``` -------------------------------- ### Access Underlying TokenListManager Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/api-reference/TokenManager.md Returns the internal manager instance, triggering automatic installation of required lists if necessary. ```python @cached_property def _manager(self) -> TokenListManager ``` -------------------------------- ### Import Package Modules Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/MODULES.md Demonstrates equivalent import paths and the lazy-loading mechanism for package components. ```python # All these work identically from ape_tokens import tokens from ape_tokens.main import tokens # Lazy loading example from ape_tokens import TokenInstance # Loads from ape_tokens.types ``` -------------------------------- ### Run the Balance Watcher Bot Source: https://github.com/apeworx/ape-tokens/blob/main/bots/README.md Executes the watcher bot on the Ethereum mainnet using the Silverback CLI. ```bash uvx --with ape-tokens silverback watcher --network :mainnet ``` -------------------------------- ### Deploy Test Tokens Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/00-START-HERE.md Deploy a mock ERC20 token for testing purposes and mint tokens to an account. ```python from ape_tokens.testing import MockERC20 from ape import accounts owner = accounts[0] usdc = MockERC20.deploy(owner, "USD Coin", "USDC", 6, sender=owner) usdc.mint(accounts[1], 1000 * (10 ** 6), sender=owner) ``` -------------------------------- ### Test multiple token balances Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/api-reference/MockERC20.md Shows how to manage and verify balances for multiple different token contracts simultaneously. ```python from ape_tokens.testing import MockERC20 from ape import accounts from decimal import Decimal def test_multiple_token_balances(): owner = accounts[0] user = accounts[1] # Deploy multiple test tokens usdc = MockERC20.deploy(owner, "USD Coin", "USDC", 6, sender=owner) usdt = MockERC20.deploy(owner, "Tether USD", "USDT", 6, sender=owner) weth = MockERC20.deploy(owner, "Wrapped Ether", "WETH", 18, sender=owner) # Mint different amounts usdc.mint(user, 1000 * (10 ** 6), sender=owner) # 1000 USDC usdt.mint(user, 500 * (10 ** 6), sender=owner) # 500 USDT weth.mint(user, 10 * (10 ** 18), sender=owner) # 10 WETH # Verify balances assert Decimal(usdc.balanceOf(user)) / (10 ** 6) == Decimal("1000") assert Decimal(usdt.balanceOf(user)) / (10 ** 6) == Decimal("500") assert Decimal(weth.balanceOf(user)) / (10 ** 18) == Decimal("10") ``` -------------------------------- ### Configuring token lists via environment variables Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/README.md Set token list defaults and requirements using shell environment variables. ```bash export APE_TOKENS_DEFAULT="CoinGecko" export APE_TOKENS_REQUIRED='[{"name":"CoinGecko","uri":"https://tokens.coingecko.com/uniswap/all.json"}]' ``` -------------------------------- ### Display Project File Structure Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/INDEX.md Visual representation of the project's documentation file hierarchy. ```text /workspace/home/output/ ├── INDEX.md (this file) ├── README.md (main overview) ├── MODULES.md (module structure) ├── types.md (type definitions) ├── configuration.md (configuration guide) ├── errors.md (error handling) └── api-reference/ ├── TokenManager.md (primary interface) ├── TokenInstance.md (ERC20 token) ├── BalanceManager.md (balance tracking) ├── Converters.md (type conversion) └── MockERC20.md (test utilities) ``` -------------------------------- ### Accessing Tokens Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/README.md Retrieve token objects by symbol or address using the tokens manager. Use the get method for safe access that returns None if the token is not found. ```python from ape_tokens import tokens # By symbol (if in token list) usdc = tokens["USDC"] # By address token = tokens["0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"] # Attribute access link = tokens.LINK # Safe access (returns None if not found) if dai := tokens.get("DAI"): print(dai.address) ``` -------------------------------- ### Initialize TokenManager Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/api-reference/TokenManager.md The class is instantiated as a singleton via the ape_tokens.main.tokens module. ```python def __init__(self) -> None ``` -------------------------------- ### Applying Type Annotations Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/types.md Demonstrates using ConvertsToToken and TokenInstance for type-safe token processing and balance retrieval. ```python from decimal import Decimal from ape_tokens import TokenInstance, BalanceManager, ConvertsToToken def process_token(token: ConvertsToToken) -> TokenInstance: """Accepts token symbol, address, or instance; returns TokenInstance.""" from ape_tokens import tokens if isinstance(token, TokenInstance): return token else: return tokens[token] def check_balance( token: TokenInstance, account: str, ) -> Decimal: """Get token balance as Decimal.""" balance_manager = BalanceManager(token) return balance_manager.get_balance(token, account) ``` -------------------------------- ### Create TokenInstance from TokenInfo Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/api-reference/TokenInstance.md Instantiate a TokenInstance using token list information to pre-populate immutable properties. ```python from ape_tokens.managers import TokenManager from ape_tokens.types import TokenInstance manager = TokenManager() token_info = manager._manager.get_token_info("USDC", chain_id=1) usdc = TokenInstance.from_tokeninfo(token_info) print(usdc.address) print(usdc.symbol()) # Does not require network call print(usdc.decimals()) # Does not require network call ``` -------------------------------- ### Configure ape-tokens Source: https://github.com/apeworx/ape-tokens/blob/main/README.md Configuration via YAML file or environment variables. ```yaml # ape-config.yaml tokens: default: "My Default List" required: - name: "My Default List" uri: "http://example.com/tokenlist.json" ``` ```sh APE_TOKENS_DEFAULT="My Default List" APE_TOKENS_REQUIRED='[{"name":"My Default List","uri":"http://example.com/tokenlist.json"}]' ``` -------------------------------- ### Deploy MockERC20 for Testing Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/SUMMARY.txt Deploy a mock ERC20 token for testing purposes using the testing module. ```python from ape_tokens.testing import MockERC20 token = MockERC20.deploy(owner, "Name", "SYM", 18, sender=owner) ``` -------------------------------- ### Monitor Real-Time Token Balances Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/SUMMARY.txt Use BalanceManager to track token balances in real-time via Silverback. ```python from ape_tokens import BalanceManager from silverback import SilverbackBot balances = BalanceManager("USDC") balances.monitor(bot, "0x...") ``` -------------------------------- ### Test ownership functions Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/api-reference/MockERC20.md Demonstrates transferring contract ownership and verifying access control restrictions. ```python from ape_tokens.testing import MockERC20 from ape import accounts def test_ownership(): owner = accounts[0] new_owner = accounts[1] non_owner = accounts[2] usdc = MockERC20.deploy(owner, "USD Coin", "USDC", 6, sender=owner) # Verify owner assert usdc.owner() == owner # Transfer ownership usdc.transferOwnership(new_owner, sender=owner) assert usdc.owner() == new_owner # Non-owner cannot mint with pytest.raises(Exception): # OwnableUnauthorizedAccount usdc.mint(non_owner, 1000 * (10 ** 6), sender=non_owner) # New owner can mint usdc.mint(non_owner, 1000 * (10 ** 6), sender=new_owner) assert usdc.balanceOf(non_owner) == 1000 * (10 ** 6) ``` -------------------------------- ### Dependency Graph Visualization Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/MODULES.md A tree representation of the module dependencies and internal class relationships. ```text ape_tokens ├── main.py │ └── managers.TokenManager │ ├── __init__.py │ ├── main.tokens │ ├── managers.BalanceManager │ ├── types.ConvertsToToken, TokenInstance, Token │ ├── converters.TokenAmountConverter, TokenSymbolConverter │ └── config.TokensConfig │ ├── types.py │ ├── ape.contracts (ContractInstance, ContractContainer, ContractType) │ ├── ape.types (AddressType) │ └── tokenlists (TokenInfo) │ ├── managers.py │ ├── types.TokenInstance, Token, ConvertsToToken │ ├── config.TokensConfig │ ├── tokenlists (TokenListManager) │ └── silverback (SilverbackBot) [optional] │ ├── converters.py │ ├── ape.api (ConverterAPI) │ ├── tokenlists (TokenListManager, TokenInfo) │ └── ape.types (AddressType) │ ├── config.py │ ├── ape.api (PluginConfig) │ └── pydantic │ ├── _cli.py │ └── tokenlists._cli (cli) │ └── testing.py └── ape.contracts (ContractContainer) ``` -------------------------------- ### Top-Level Import Paths Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/SUMMARY.txt Recommended imports for accessing core ape-tokens functionality. ```python from ape_tokens import ( tokens, TokenInstance, BalanceManager, TokenAmountConverter, TokenSymbolConverter, ConvertsToToken, ) ``` -------------------------------- ### Configuring token lists via YAML Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/README.md Define default and required token lists in the ape-config.yaml file. ```yaml tokens: default: "CoinGecko" required: - name: "CoinGecko" uri: "https://tokens.coingecko.com/uniswap/all.json" ``` -------------------------------- ### Transfer MockERC20 tokens Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/api-reference/MockERC20.md Illustrates transferring tokens between accounts and verifying the updated balances. ```python from ape_tokens.testing import MockERC20 from ape import accounts def test_token_transfer(): owner = accounts[0] user1 = accounts[1] user2 = accounts[2] usdc = MockERC20.deploy(owner, "USD Coin", "USDC", 6, sender=owner) # Mint tokens amount = 1000 * (10 ** 6) usdc.mint(user1, amount, sender=owner) # Transfer tokens transfer_amount = 100 * (10 ** 6) usdc.transfer(user2, transfer_amount, sender=user1) # Verify balances assert usdc.balanceOf(user1) == amount - transfer_amount assert usdc.balanceOf(user2) == transfer_amount assert usdc.totalSupply() == amount ``` -------------------------------- ### Import TokenListManager Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/types.md Import the TokenListManager class from the tokenlists library. ```python from tokenlists import TokenListManager ``` -------------------------------- ### Handle KeyError in BalanceManager Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/errors.md Demonstrates catching KeyError when accessing a token not initialized in the BalanceManager and using .get() as a safe alternative. ```python from ape_tokens import BalanceManager, tokens # Only monitor USDC manager = BalanceManager("USDC") # This raises KeyError try: weth_balances = manager["WETH"] except KeyError as e: print(f"WETH not being monitored: {e}") # Use .get() to avoid exception if weth_balances := manager.get("WETH"): print("WETH is monitored") else: print("WETH is not monitored") ``` -------------------------------- ### Check balances efficiently Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/api-reference/BalanceManager.md Compares network-based balance fetching with cached access for monitored tokens. ```python from ape_tokens import BalanceManager from ape.utils import ZERO_ADDRESS manager = BalanceManager("USDC", "WETH") # .get() performs network call current = manager.get_balance("USDC", "0x...") # If using monitor(), use direct access for speed if usdc_bal := manager.get("USDC"): cached = usdc_bal["0x..."] # No network call if monitored ``` -------------------------------- ### MockERC20 Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/00-START-HERE.md A testing utility for deploying mock ERC20 tokens in development environments. ```APIDOC ## MockERC20 ### Description A full-featured test token class used for testing token interactions in local environments. ### Usage ```python from ape_tokens.testing import MockERC20 # Deploy a new mock token test_token = MockERC20.deploy(owner, "Test", "TEST", 18, sender=owner) ``` ``` -------------------------------- ### Import TokenInfo Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/types.md Import the TokenInfo type from the tokenlists library. ```python from tokenlists import TokenInfo ``` -------------------------------- ### Handle ValueError in BalanceManager.monitor Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/errors.md Demonstrates how to catch a ValueError when monitoring without accounts or a configured signer, and how to resolve it by providing accounts explicitly. ```python from ape_tokens import BalanceManager from silverback import SilverbackBot bot = SilverbackBot() balances = BalanceManager("USDC") # This raises ValueError if bot.signer is not configured try: balances.monitor(bot) # No accounts provided except ValueError as e: print(f"Error: {e}") print("Provide accounts or configure bot.signer") # Solution: Provide accounts explicitly balances.monitor(bot, "0x742d35Cc6634C0532925a3b844Bc9e7595f7bEb") ``` -------------------------------- ### Deploy MockERC20 Token Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/MODULES.md Deploys a new instance of the MockERC20 contract with specified token parameters. ```python from ape_tokens.testing import MockERC20 from ape import accounts usdc = MockERC20.deploy( accounts[0], # initialOwner "USD Coin", # name "USDC", # symbol 6, # decimals sender=accounts[0] ) ``` -------------------------------- ### Default plugin configuration Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/configuration.md The default settings used when no configuration is provided. ```python default = None # First installed list will be used required = [] # No automatic installations ``` -------------------------------- ### TokenContainer.at() Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/MODULES.md Load an ERC20 token instance at a specific address. ```APIDOC ## TokenContainer.at(address) ### Description Loads an ERC20 token instance at the specified address. ### Parameters - **address** (str) - Required - The blockchain address of the token contract. ### Returns - **TokenInstance** - An instance representing the ERC20 token. ``` -------------------------------- ### TokenInstance ERC20 Methods Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/MODULES.md Standard ERC20 methods available on TokenInstance objects. ```APIDOC ## ERC20 Methods ### View Functions - **name()** -> string - **symbol()** -> string - **decimals()** -> uint8 - **totalSupply()** -> uint256 - **balanceOf(account: address)** -> uint256 - **allowance(owner: address, spender: address)** -> uint256 ### State Functions - **transfer(receiver: address, amount: uint256)** -> bool - **approve(spender: address, amount: uint256)** -> bool - **transferFrom(sender: address, receiver: address, amount: uint256)** -> bool ``` -------------------------------- ### Initialize MockERC20 Container Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/MODULES.md Instantiates the MockERC20 container using the pre-defined TEST_ERC20 contract type. ```python MockERC20 = ContractContainer(contract_type=TEST_ERC20) ``` -------------------------------- ### TokenInstance.__repr__ Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/api-reference/TokenInstance.md Returns a string representation of the token instance. ```APIDOC ## TokenInstance.__repr__() ### Description Returns a string representation of the token, including the symbol (if cached) and the contract address. ### Returns - **repr** (str) - Representation in format or <0x...> if symbol is not cached. ### Example ```python from ape_tokens import tokens usdc = tokens["USDC"] print(repr(usdc)) # ``` ``` -------------------------------- ### Integrate MockERC20 with Pytest Fixtures Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/api-reference/MockERC20.md Shows how to define reusable pytest fixtures for deploying MockERC20 tokens and using them in test functions. ```python import pytest from ape_tokens.testing import MockERC20 from ape import accounts @pytest.fixture def usdc(): """Deploy a test USDC token""" owner = accounts[0] return MockERC20.deploy( owner, "USD Coin", "USDC", 6, sender=owner ) @pytest.fixture def weth(): """Deploy a test WETH token""" owner = accounts[0] return MockERC20.deploy( owner, "Wrapped Ether", "WETH", 18, sender=owner ) def test_with_fixtures(usdc, weth): owner = accounts[0] user = accounts[1] # Use pre-deployed tokens usdc.mint(user, 1000 * (10 ** 6), sender=owner) weth.mint(user, 10 * (10 ** 18), sender=owner) assert usdc.balanceOf(user) == 1000 * (10 ** 6) assert weth.balanceOf(user) == 10 * (10 ** 18) ``` -------------------------------- ### Accessing Token Configuration Programmatically Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/configuration.md Retrieve and inspect the current token configuration settings using the tokens module. ```python from ape_tokens import tokens # Get config config = tokens.config print(f"Default list: {config.default}") print(f"Required lists: {config.required}") for list_info in config.required: print(f" - {list_info.name}: {list_info.uri}") ``` -------------------------------- ### Configure Mypy in pyproject.toml Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/MODULES.md Enable pydantic plugin support for type checking. ```toml [tool.mypy] plugins = ["pydantic.mypy"] ``` -------------------------------- ### Handle Conversion Errors Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/api-reference/Converters.md Shows how to catch ConversionError exceptions and verify convertibility before attempting a conversion. ```python from ape_tokens.converters import TokenAmountConverter, TokenSymbolConverter from ape.exceptions import ConversionError amount_conv = TokenAmountConverter() symbol_conv = TokenSymbolConverter() # Handle non-existent tokens try: amount = amount_conv.convert("100 NONEXISTENT") except ConversionError as e: print(f"Token not found: {e}") try: address = symbol_conv.convert("BADTOKEN") except ConversionError as e: print(f"Symbol not found: {e}") # Check convertibility to avoid exceptions if not amount_conv.is_convertible("invalid input"): print("Cannot convert this value") ``` -------------------------------- ### Configuration Validation Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/errors.md Verifies the availability of a list of token symbols within the tokens registry before proceeding. ```python from ape_tokens import tokens def validate_tokens_available(symbols: list[str]) -> bool: """Check if all symbols are available.""" for symbol in symbols: if symbol not in tokens: return False return True # Usage required_tokens = ["USDC", "WETH", "DAI"] if validate_tokens_available(required_tokens): print("All required tokens available") else: print("Some tokens are missing from token list") ``` -------------------------------- ### Configure default token list Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/configuration.md Set the default token list name using environment variables or YAML configuration. ```bash export APE_TOKENS_DEFAULT="CoinGecko" ``` ```yaml tokens: default: "CoinGecko" ``` -------------------------------- ### Define ListInfo Model Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/types.md Represents a single token list configuration entry. ```python class ListInfo(BaseModel): name: str uri: str ``` -------------------------------- ### Access tokens in the Ape console Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/configuration.md Import the tokens manager and retrieve token addresses directly from the console. ```python $ ape console In [1]: from ape_tokens import tokens In [2]: usdc = tokens["USDC"] In [3]: usdc.address '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48' ``` -------------------------------- ### TokenInstance.from_tokeninfo Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/api-reference/TokenInstance.md Creates a TokenInstance from a TokenInfo object, pre-populating immutable properties to avoid redundant network calls. ```APIDOC ## TokenInstance.from_tokeninfo(token_info) ### Description Creates a TokenInstance from a TokenInfo object (from the tokenlists library). This method pre-populates the name, symbol, and decimals properties with values from the token list to avoid unnecessary network calls. ### Parameters - **token_info** (TokenInfo) - Required - Token information object obtained from tokenlists.TokenListManager.get_token_info(). ### Returns - **instance** (TokenInstance) - A token instance with cached immutable properties. ### Example ```python from ape_tokens.managers import TokenManager from ape_tokens.types import TokenInstance manager = TokenManager() token_info = manager._manager.get_token_info("USDC", chain_id=1) usdc = TokenInstance.from_tokeninfo(token_info) print(usdc.address) print(usdc.symbol()) # Does not require network call print(usdc.decimals()) # Does not require network call ``` ``` -------------------------------- ### Configure automatic console imports Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/configuration.md Add the tokens manager to the console namespace automatically by placing this in the console extras file. ```python # ~/.ape/ape_console_extras.py try: from ape_tokens import tokens except ImportError: pass ``` -------------------------------- ### Test with MockERC20 Source: https://github.com/apeworx/ape-tokens/blob/main/README.md Deploy mock tokens for testing purposes within Ape tests. ```python from ape_tokens.testing import MockERC20 def test_deposit(accounts): owner = accounts[0] # Setup some test tokens. usdc = MockERC20.deploy(owner, "USD Coin", "USDC", 6, sender=owner) weth = MockERC20.deploy(owner, "Wrapped Ether", "WETH", 18, sender=owner) ... ``` -------------------------------- ### Iterate Over Configured Tokens Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/api-reference/TokenManager.md Loop through the tokens collection to perform operations like balance checks across all registered tokens. ```python from ape_tokens import tokens # Check balances for all tokens address = "0x..." for token in tokens: balance = token.balanceOf(address) / (10 ** token.decimals()) if balance > 0: print(f"{token.symbol()}: {balance}") ``` -------------------------------- ### Defining Per-Chain Token Configuration Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/configuration.md Use ape-config.yaml to specify different token lists for different blockchain networks. ```yaml # ape-config.yaml tokens: default: "CoinGecko" required: - name: "CoinGecko" uri: "https://tokens.coingecko.com/uniswap/all.json" ethereum: default_network: "mainnet" arbitrum: default_network: "arbitrum-one" ``` -------------------------------- ### Direct Token Contract Access Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/api-reference/TokenInstance.md Initialize a token instance directly from an address, bypassing the pre-populated token list. ```python from ape_tokens.types import Token from ape.types import AddressType # Access token by address directly (without token list) token = Token.at("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48") # Methods still cache, but values are loaded from contract name = token.name() symbol = token.symbol() decimals = token.decimals() ``` -------------------------------- ### Access TokenBalances via __getitem__ Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/api-reference/BalanceManager.md Retrieve a TokenBalances reader using a token symbol, address, or instance. ```python from ape_tokens import BalanceManager, tokens manager = BalanceManager("USDC", "WETH") # Access by symbol usdc_balances = manager["USDC"] # Or by TokenInstance usdc_balances = manager[tokens["USDC"]] # Or by address usdc_balances = manager["0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"] ``` -------------------------------- ### Retrieve token balances with get_balance Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/api-reference/BalanceManager.md Fetches the balance of a specified account for a given token, returning the value as a Decimal in natural units. ```python def get_balance( self, token: ConvertsToToken, account: "BaseAddress | AddressType | str", ) -> Decimal ``` ```python from ape_tokens import BalanceManager from decimal import Decimal manager = BalanceManager("USDC", "WETH") account = "0x742d35Cc6634C0532925a3b844Bc9e7595f7bEb" # Get balance as Decimal (already divided by decimals) usdc_balance = manager.get_balance("USDC", account) weth_balance = manager.get_balance("WETH", account) print(f"USDC: {usdc_balance}") # e.g., Decimal('123.456789') print(f"WETH: {weth_balance}") # e.g., Decimal('1.5') ``` -------------------------------- ### Accessing the TokenManager Singleton Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/MODULES.md Import the tokens singleton to access token data by symbol. ```python from ape_tokens.main import tokens from ape_tokens.main import tokens as tm # Access tokens usdc = tokens["USDC"] ``` -------------------------------- ### Monitor balance changes with monitor Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/api-reference/BalanceManager.md Registers event handlers on a Silverback bot to track token transfers and maintain an in-memory balance cache. Be mindful of RPC limits as each token-account pair creates two event log filters. ```python def monitor( self, bot: "SilverbackBot", *accounts: "BaseAddress | AddressType | str", ) ``` ```python from decimal import Decimal from ape_tokens import BalanceManager, tokens from silverback import SilverbackBot bot = SilverbackBot() usdc = tokens["USDC"] weth = tokens["WETH"] # Monitor specific tokens for specific accounts balances = BalanceManager(usdc, weth) balances.monitor(bot, "0x742d35Cc6634C0532925a3b844Bc9e7595f7bEb") # Or use bot.signer if configured # balances.monitor(bot) # React to balance changes @bot.on_metric("USDC/0x742d35Cc6634C0532925a3b844Bc9e7595f7bEb", lt=Decimal("100")) async def low_usdc_alert(balance: Decimal): print(f"USDC balance fell below 100: {balance}") # Access cached balance (no network call) current_balance = balances["USDC"]["0x742d35Cc6634C0532925a3b844Bc9e7595f7bEb"] print(f"Current USDC balance: {current_balance}") ``` -------------------------------- ### Balance Manager Error Handling Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/errors.md Safely retrieves account balances from a BalanceManager instance, handling missing token keys gracefully. ```python from ape_tokens import BalanceManager def get_balance_safely(manager, token, account): """Get balance with error handling.""" try: balances = manager[token] return balances.get(account) except KeyError: print(f"Token not being monitored") return None ``` -------------------------------- ### Catching Token List Errors Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/errors.md Demonstrates how to handle potential ValueErrors when retrieving tokens from a converter instance. ```python from ape_tokens import tokens from ape_tokens.converters import TokenAmountConverter # This logs a warning but doesn't raise converter = TokenAmountConverter() try: tokens_iter = converter.get_tokens() token_list = list(tokens_iter) if not token_list: print("No tokens available for current chain") except ValueError as e: print(f"Token list error: {e}") ``` -------------------------------- ### Perform Safe Token Lookup Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/api-reference/TokenManager.md Use the .get() method to retrieve a token safely, returning None if the token is not found. ```python from ape_tokens import tokens # Safe access that returns None if not found if usdt := tokens.get("USDT"): print(f"USDT found at {usdt.address}") else: print("USDT not configured") ``` -------------------------------- ### Access a Token Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/SUMMARY.txt Retrieve a token instance using the tokens singleton. ```python from ape_tokens import tokens usdc = tokens["USDC"] ``` -------------------------------- ### Monitor multiple tokens and addresses Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/api-reference/BalanceManager.md Configures the manager to track multiple tokens and addresses, then accesses cached values. ```python from ape_tokens import BalanceManager, tokens from silverback import SilverbackBot bot = SilverbackBot() # Monitor multiple tokens balances = BalanceManager( tokens["USDC"], "WETH", "0xdAC17F958D2ee523a2206206994597C13D831ec7", # USDT address ) # Monitor multiple addresses addresses = [ "0x742d35Cc6634C0532925a3b844Bc9e7595f7bEb", "0xc1c0c8D6f0311838f2376e541B95f25F5c4E7A34", ] balances.monitor(bot, *addresses) # Access cached balances (no RPC calls) for address in addresses: usdc_balance = balances["USDC"][address] print(f"USDC at {address}: {usdc_balance}") ``` -------------------------------- ### Convert token amounts in contract calls Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/api-reference/Converters.md Pass natural language strings like '8.23 LINK' directly into contract methods to handle decimal scaling automatically. ```python from ape import accounts, project from ape_tokens import tokens contract = accounts[0].deploy(project.MyContract) # Pass token amounts using natural syntax tx = contract.provideLinkTokens("8.23 LINK", sender=accounts[0]) tx.wait(1) # The converter automatically handles the math: # "8.23 LINK" → 8.23 * 10^18 (LINK has 18 decimals) ``` -------------------------------- ### Register Conversion Plugins Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/MODULES.md Registers TokenAmountConverter and TokenSymbolConverter with Ape's conversion system. ```python @plugins.register(plugins.ConversionPlugin) def converters(): # Registers converters with Ape's conversion system from .converters import TokenAmountConverter, TokenSymbolConverter yield int, TokenAmountConverter # For amount conversion yield AddressType, TokenSymbolConverter # For symbol→address ``` -------------------------------- ### Run Mypy Type Checking Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/MODULES.md Execute static type analysis on the project modules. ```bash mypy ape_tokens/ ``` -------------------------------- ### Test OwnableUnauthorizedAccount in MockERC20 Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/errors.md Shows how to verify that non-owner accounts are restricted from calling administrative functions like minting. ```python from ape_tokens.testing import MockERC20 from ape import accounts def test_mint_authorization(): owner = accounts[0] non_owner = accounts[1] usdc = MockERC20.deploy(owner, "USD Coin", "USDC", 6, sender=owner) # Owner can mint usdc.mint(non_owner, 1000 * (10 ** 6), sender=owner) # Non-owner cannot mint try: usdc.mint(non_owner, 1000 * (10 ** 6), sender=non_owner) assert False, "Should have raised OwnableUnauthorizedAccount" except Exception as e: # Specific exception type depends on testing framework print(f"Expected error: {e}") ``` -------------------------------- ### Register Ape Configuration Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/MODULES.md Registers the TokensConfig class with the Ape configuration system. ```python @plugins.register(plugins.Config) def config_class(): # Registers TokensConfig for Ape configuration system from .config import TokensConfig return TokensConfig ``` -------------------------------- ### Safely Retrieve Token Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/api-reference/TokenManager.md Returns None instead of raising an exception if the token is not found. ```python def get(self, val: str) -> TokenInstance | None ``` ```python from ape_tokens import tokens if bat := tokens.get("BAT"): print(f"Found BAT at {bat.address}") else: print("BAT not in token list") ``` -------------------------------- ### Check Balance Source: https://github.com/apeworx/ape-tokens/blob/main/_autodocs/SUMMARY.txt Use the BalanceManager to query token balances for a specific address. ```python from ape_tokens import BalanceManager manager = BalanceManager("USDC") balance = manager.get_balance("USDC", "0x...") ```