### Install Documentation Tooling Source: https://github.com/apeworx/ape/blob/main/CONTRIBUTING.md Install the necessary tooling for building and serving the project documentation. ```bash pip install -e .[doc] ``` -------------------------------- ### Install Plugins Individually Source: https://github.com/apeworx/ape/blob/main/docs/userguides/installing_plugins.md Install specific plugins and their versions directly from the command line. ```bash ape plugins install vyper "solidity>=0.6,<0.7" ``` -------------------------------- ### Install Ape with Docker Source: https://github.com/apeworx/ape/blob/main/README.md Pull the latest Ape Docker image which includes recommended plugins. This is a good starting point for containerized environments. ```bash $ docker pull ghcr.io/apeworx/ape:latest # installs with recommended-plugins ``` -------------------------------- ### Install Plugins from Project Configuration Source: https://github.com/apeworx/ape/blob/main/docs/userguides/installing_plugins.md Run this command in your project's root directory to install all plugins listed in ape-config.yaml. ```bash ape plugins install . ``` -------------------------------- ### Install All Project Dependencies Source: https://github.com/apeworx/ape/blob/main/docs/userguides/dependencies.md Install all dependencies defined in your project's configuration. Use the --force flag to re-install even if dependencies are already cached. ```shell ape pm install ``` ```shell ape pm install --force ``` -------------------------------- ### List Installed Dependencies Source: https://github.com/apeworx/ape/blob/main/docs/userguides/dependencies.md View information about installed dependencies, including their name, version, installation status, and compilation status. ```shell ape pm list ``` -------------------------------- ### Install Ape Hardware Wallet Plugin Source: https://github.com/apeworx/ape/blob/main/docs/userguides/accounts.md Install hardware wallet plugins like `ape-ledger` or `ape-trezor` using the `ape plugins install` command to enable support for hardware accounts. ```bash ape plugins install ledger ``` -------------------------------- ### List All Plugins Source: https://github.com/apeworx/ape/blob/main/docs/userguides/installing_plugins.md Use this command to view all installed core plugins and available plugins. ```bash ape plugins list --all ``` -------------------------------- ### Install Forking Plugin Source: https://github.com/apeworx/ape/blob/main/docs/userguides/forking_networks.md Install a provider plugin that supports forking, such as `ape-foundry` or `ape-hardhat`, to enable local network forking. ```shell ape plugins install ``` -------------------------------- ### Install Pre-Commit Hooks Source: https://github.com/apeworx/ape/blob/main/CONTRIBUTING.md Install and configure pre-commit hooks to ensure code quality and consistent formatting. ```bash pip install pre-commit pre-commit install ``` -------------------------------- ### Install L2 Network Plugins Source: https://github.com/apeworx/ape/blob/main/docs/userguides/networks.md Install plugins for common L2 networks to enable ecosystem-specific customizations and default overrides. This command installs plugins for Arbitrum, Polygon, Optimism, Fantom, and Base. ```bash ape plugins install arbitrum polygon optimism fantom base ``` -------------------------------- ### Launch Default Console Source: https://github.com/apeworx/ape/blob/main/docs/userguides/console.md Start the Ape console with default settings. ```bash ape console ``` -------------------------------- ### Install L2 Forking Plugins Source: https://github.com/apeworx/ape/blob/main/docs/userguides/forking_networks.md Install plugins for L2 networks like Optimism or Arbitrum to enable forking of these Layer 2 solutions. ```shell ape plugins install optimism ape plugins install arbitrum ``` -------------------------------- ### Install Specific Dependency by ID or Name Source: https://github.com/apeworx/ape/blob/main/docs/userguides/dependencies.md Install a specific dependency using its ID or name as listed in your configuration file. ```shell ape pm install OpenZeppelin/openzeppelin-contracts ``` -------------------------------- ### Install Hardhat Plugin Source: https://github.com/apeworx/ape/blob/main/docs/userguides/testing.md Install the ape-hardhat plugin to use Hardhat as a testing provider. This can be done via configuration or manual installation. ```bash ape plugins install hardhat ``` -------------------------------- ### Ape Configuration Example Source: https://github.com/apeworx/ape/blob/main/docs/userguides/brownie-migration.md Example of an `ape-config.yaml` file, demonstrating how dependencies and compiler settings are structured in Ape. Wallet management is done via `ape accounts import`. ```yaml name: migrated-ape-project plugins: - name: solidity solidity: version: 0.8.20 import_remapping: - "@chainlink=smartcontractkit/chainlink-brownie-contracts@1.1.1" hereum: default_network: local ``` -------------------------------- ### Clone Repository and Setup Environment Source: https://github.com/apeworx/ape/blob/main/CONTRIBUTING.md Clone the GitHub repository and set up a local Python virtual environment for development. ```bash git clone https://github.com/ApeWorX/ape.git cd ape python3 -m venv venv source venv/bin/activate pip install -e .[dev] ``` -------------------------------- ### Brownie Configuration Example Source: https://github.com/apeworx/ape/blob/main/docs/userguides/brownie-migration.md Example of a typical `brownie-config.yaml` file. Note that private keys are handled via environment variables and wallet imports. ```yaml dependencies: - smartcontractkit/chainlink-brownie-contracts@1.1.1 compiler: solc: remappings: - "@chainlink=smartcontractkit/chainlink-brownie-contracts@1.1.1" wallets: from_key: ${PRIVATE_KEY} networks: development: verify: false ``` -------------------------------- ### Install Dependency with Config Override Source: https://github.com/apeworx/ape/blob/main/docs/userguides/dependencies.md Install a dependency and override its configuration settings during installation using the '--config-override' option. This allows specifying compiler versions or other settings. ```shell ape pm install gh:OpenZeppelin/openzeppelin-contracts \ --name openzeppelin \ --version "4.6.0" \ --config-override '{"solidity": {"version": "0.8.12"}}' ``` -------------------------------- ### Launch Console with Specific Network Source: https://github.com/apeworx/ape/blob/main/docs/userguides/console.md Start the Ape console and connect to a specific network, such as Ethereum's mainnet. ```bash ape console --network ethereum:mainnet ``` -------------------------------- ### Install Plugin from Git Branch (YAML) Source: https://github.com/apeworx/ape/blob/main/docs/userguides/installing_plugins.md Configure a plugin to be installed from a specific Git branch using a git+ prefix in the version field within ape-config.yaml. ```yaml plugins: - name: foobar version: git+https://github.com//ape-foobar.git@ ``` -------------------------------- ### Use Installed Site-Package as Dependency Source: https://github.com/apeworx/ape/blob/main/docs/userguides/dependencies.md Reference a Python package already installed in your environment using `site_package:`. This is useful for dependencies not available on PyPI or when you prefer managing installations via `pip`. Note that `contracts_folder` may need to be specified. ```yaml dependencies: - site_package: snekmate config_override: contracts_folder: . ``` -------------------------------- ### Solidity Import Remapping Source: https://github.com/apeworx/ape/blob/main/docs/userguides/dependencies.md Map import paths to local installations of dependencies in `ape-config.yaml` when they are not installed via Ape. ```yaml solidity: import_remapping: - "@openzeppelin=path/to/openzeppelin" ``` -------------------------------- ### Run Ape Command from Docker Container Source: https://github.com/apeworx/ape/blob/main/README.md Example of executing an Ape command, such as 'compile', from within a Docker container. Ensure volumes are correctly mapped for persistent data and project access. This command assumes the full install with recommended plugins. ```bash docker run \ --volume $HOME/.ape:/home/harambe/.ape \ --volume $HOME/.vvm:/home/harambe/.vvm \ --volume $HOME/.solcx:/home/harambe/.solcx \ --volume $PWD:/home/harambe/project \ apeworx/ape compile ``` -------------------------------- ### Install Plugin from Git Branch (CLI) Source: https://github.com/apeworx/ape/blob/main/docs/userguides/installing_plugins.md Install a plugin directly from a Git branch using the CLI. Ape can deduce the plugin name if the prefix is omitted. ```shell ape plugins install "foobar@git+https://github.com//ape-foobar.git@" ``` ```shell ape plugins install "git+https://github.com//ape-foobar.git@" ``` -------------------------------- ### Launch Ape Console for Contract Deployment Source: https://github.com/apeworx/ape/blob/main/docs/userguides/transactions.md Start the Ape console connected to a specific network, allowing for interactive contract deployment and interaction. ```bash ape console --network ethereum:sepolia:alchemy ``` -------------------------------- ### Install Dependency Directly with GitHub Prefix Source: https://github.com/apeworx/ape/blob/main/docs/userguides/dependencies.md Install a dependency directly from GitHub by specifying the repository and optionally its name and version. The 'gh:' prefix indicates a GitHub source. ```shell ape pm install gh:OpenZeppelin/openzeppelin-contracts --name openzeppelin --version "4.6.0" ``` -------------------------------- ### Install Dependency using Python API Source: https://github.com/apeworx/ape/blob/main/docs/userguides/dependencies.md Install dependencies programmatically using the Ape Python API. Pass dependency details as keyword arguments, mirroring the configuration file format. ```python from ape import project project.dependencies.install( github="OpenZeppelin/openzeppelin-contracts", name="openzeppelin", version="4.9.6" ) ``` -------------------------------- ### Invoke Account Selection CLI Commands Source: https://github.com/apeworx/ape/blob/main/docs/userguides/clis.md Examples of how to invoke the CLI command with the account option, demonstrating different ways to specify the desired account. ```shell cmd # Use the default account. cmd --account 0 # Use first account that would show up in `select_account()`. cmd --account metamask # Use account with alias "metamask". cmd --account TEST::0 # Use the test account at index 0. ``` -------------------------------- ### Install Slim Ape Docker Image Source: https://github.com/apeworx/ape/blob/main/README.md Pull the slim Ape Docker image which is built without any installed plugins. This image is suitable for production and requires further configuration if plugins are needed. ```bash $ docker pull ghcr.io/apeworx/ape:latest-slim # installs ape with required packages ``` -------------------------------- ### Short-hand Network Selection Source: https://github.com/apeworx/ape/blob/main/docs/userguides/networks.md Omit ecosystem and network names to use defaults when specifying only the provider. This example uses the default 'ethereum:local' with the 'foundry' provider. ```bash ape run --network ::foundry ``` -------------------------------- ### Run Tests with Local Node Source: https://github.com/apeworx/ape/blob/main/docs/userguides/testing.md Execute tests using the local Ethereum node provider. Ensure you have Ethereum node software installed and configured. ```bash ape test --network ethereum:local:node ``` -------------------------------- ### Install GitHub Dependency by Git Reference Source: https://github.com/apeworx/ape/blob/main/docs/userguides/dependencies.md Use the `ref` key to install a dependency from a specific Git reference (tag or branch) when an official release or tag is not available. The `v` prefix may be required for tags. ```yaml dependencies: - name: Uniswap github: Uniswap/v3-core ref: v1.0.0 ``` -------------------------------- ### Define Project Configuration with Environment Variables Source: https://github.com/apeworx/ape/blob/main/docs/userguides/config.md An example demonstrating how to override a full YAML configuration using environment variables. Note the use of plugin-specific prefixes like `APE_COMPILE` and `APE_TEST`, and the general `APE_` prefix for non-plugin settings. Complex types like lists require careful quoting. ```yaml contracts_folder: src/qwe test: number_of_accounts: 3 show_internal: True compile: exclude: - "one" - "two" - "three" include_dependencies: true ``` ```shell APE_CONTRACTS_FOLDER=src/contracts APE_TEST_NUMBER_OF_ACCOUNTS=3 APE_TEST_SHOW_INTERNAL=true APE_COMPILE_EXCLUDE='["one", "two", "three"]' APE_COMPILE_INCLUDE_DEPENDENCIES=true ``` -------------------------------- ### Deploy Contract from Ape Console Source: https://github.com/apeworx/ape/blob/main/docs/userguides/transactions.md Deploy a contract directly within the Ape console. This example assumes a contract named 'Token' is available in the project. ```python In [1]: dev = accounts.load("dev") In [2]: token = dev.deploy(project.Token) In [3]: token.contract_method_defined_in_contract() ``` -------------------------------- ### Change Version for All Plugins Source: https://github.com/apeworx/ape/blob/main/docs/userguides/installing_plugins.md Install a specific version of Ape and all plugins at once using the 'change-version' command. ```shell ape plugins change-version 0.6.0 ``` -------------------------------- ### Compile and Use Dependency Contract Types Source: https://github.com/apeworx/ape/blob/main/docs/userguides/dependencies.md Access and deploy contract types from installed dependencies using the `project.dependencies` object. ```python from ape import accounts, project # NOTE: This will compile the dependency dependency_project = project.dependencies["my_dependency"]["1.0.0"] dependency_contract = dependency_project.DependencyContractType my_account = accounts.load("alias") deployed_contract = my_account.deploy(dependency_contract, "argument") print(deployed_contract.address) ``` -------------------------------- ### Serve Documentation with Auto-Open Source: https://github.com/apeworx/ape/blob/main/CONTRIBUTING.md Serve the project documentation locally and automatically open it in the default web browser. ```bash sphinx-ape serve . --open ``` -------------------------------- ### Example Test Function Source: https://github.com/apeworx/ape/blob/main/docs/userguides/testing.md A sample test function demonstrating contract interaction, including minting an NFT and checking balances. Assumes 'project', 'owner', 'receiver', and 'nft' fixtures are available. ```python def test_account_balance(project, owner, receiver, nft): quantity = 1 nft.mint(receiver, quantity, ["0"], value=nft.PRICE() * quantity, sender=owner) actual = project.balanceOf(receiver) expect = quantity assert actual == expect ``` -------------------------------- ### Serve Documentation Locally Source: https://github.com/apeworx/ape/blob/main/CONTRIBUTING.md Serve the project documentation locally for viewing in a web browser. ```bash sphinx-ape serve . ``` -------------------------------- ### Configure Ape-Solidity Plugin Source: https://github.com/apeworx/ape/blob/main/docs/userguides/config.md Set plugin-specific options by referencing the plugin name in your configuration file. This example shows how to set the EVM version for the `ape-solidity` plugin. ```yaml solidity: evm_version: paris # Or any other setting defined in `ape-solidity`. ``` -------------------------------- ### Logging Failed Transactions Source: https://github.com/apeworx/ape/blob/main/docs/userguides/reverts.md Provides an example of using `raise_on_revert=False` to log transaction failures and perform fallback actions without interrupting the script's flow. ```python try: # Try to execute a risky transaction receipt = contract.riskFunction(sender=account, raise_on_revert=False) if receipt.failed: logger.warning(f"Transaction failed: {receipt.error}") # Perform some fallback action else: logger.info("Transaction succeeded!") except Exception as e: logger.error(f"Unexpected error: {e}") ``` -------------------------------- ### Pytest Fixtures and Contract Testing Source: https://github.com/apeworx/ape/blob/main/docs/userguides/testing.md Example of pytest fixtures for setting up accounts and deploying contracts, followed by a test function that invokes contract methods and asserts outcomes. This demonstrates the setup-invocation-assertion pattern. It includes testing for reverts with string messages, custom error types, and regex patterns. ```python import ape import pytest import re # SETUP PHASE # NOTE: More on fixtures is discussed in later sections of this guide! @pytest.fixture def owner(accounts): return accounts[0] @pytest.pytest.fixture def not_owner(accounts): return accounts[1] @pytest.fixture def my_contract(owner, project): return owner.deploy(project.MyContract) def test_authorization(my_contract, owner, not_owner): # INVOCATION PHASE my_contract.set_owner(sender=owner) assert owner == my_contract.owner() # ASSERTION PHASE with ape.reverts("!authorized"): my_contract.authorized_method(sender=not_owner) # You can also test against custom error types with ape.reverts(my_contract.Unauthorized): my_contract.authorized_method(sender=not_owner) # Or match error patterns with regex with ape.reverts(re.compile(r"^!auth.*")): my_contract.authorized_method(sender=not_owner) ``` -------------------------------- ### Instantiate a Project Source: https://github.com/apeworx/ape/blob/main/docs/methoddocs/ape.md Use this to instantiate other projects by providing the path to the project. ```python project = ape.Project(path) ``` -------------------------------- ### Initialize Ape Project Source: https://github.com/apeworx/ape/blob/main/docs/userguides/projects.md Use 'ape init' to create a new Ape project. The standard project structure includes directories for contracts, tests, scripts, and a configuration file. ```bash ape init ``` -------------------------------- ### Configure Compiler Settings in Python Source: https://github.com/apeworx/ape/blob/main/docs/userguides/compile.md Programmatically set compiler versions and other settings for Vyper and Solidity using the `compilers` module. You can compile specific files or get compiler instances. ```python from pathlib import Path from ape import compilers settings = {"vyper": {"version": "0.3.7"}, "solidity": {"version": "0.8.0"}} compilers.compile( ["path/to/contract.vy", "path/to/contract.sol"], settings=settings ) # Or, more explicitly: vyper = compilers.get_compiler("vyper", settings=settings["vyper"]) vyper.compile([Path("path/to/contract.vy")]) solidity = compilers.get_compiler("solidity", settings=settings["solidity"]) solidity.compile([Path("path/to/contract.sol")]) ``` -------------------------------- ### Build Documentation Locally Source: https://github.com/apeworx/ape/blob/main/CONTRIBUTING.md Build the project documentation using sphinx-ape. ```bash sphinx-ape build . ``` -------------------------------- ### Define Custom Console Extras Source: https://github.com/apeworx/ape/blob/main/docs/userguides/console.md Create a Python file (`ape_console_extras.py`) in your project root to add custom functions and variables to the console namespace. Non-internal symbols (not starting with '_') will be available. ```python from ape import networks from eth_utils import encode_hex, decode_hex def latest(key): return getattr(networks.active_provider.get_block("latest"), key) ``` -------------------------------- ### Main Method Script with Network Info Source: https://github.com/apeworx/ape/blob/main/docs/userguides/scripts.md Demonstrates accessing network details within a `main()` script. This script runs connected by default and can be run with specific network configurations. ```python from ape import networks import click def main(): ecosystem_name = networks.provider.network.ecosystem.name network_name = networks.provider.network.name provider_name = networks.provider.name click.echo(f"You are connected to network '{ecosystem_name}:{network_name}:{provider_name}'.") ``` -------------------------------- ### Select Network in Ape CLI Source: https://github.com/apeworx/ape/blob/main/docs/userguides/networks.md Use the `--network` option with Ape CLI commands to select a specific network. This example shows selecting a local Foundry network for testing. ```bash ape test --network ethereum:local:foundry ``` ```bash ape console --network arbitrum:testnet:alchemy ``` -------------------------------- ### Launch Local Development Networks Source: https://github.com/apeworx/ape/blob/main/docs/userguides/networks.md Use these commands to launch local development networks for testing. '--network ::test' uses an in-process Ethereum Tester, while '--network ::node' launches a local development node process (e.g., Geth). ```bash ape test --network ::test ``` ```bash ape test --network ::node ``` -------------------------------- ### Get Previous Deployment via project.ContractName.deployments Source: https://github.com/apeworx/ape/blob/main/docs/userguides/contracts.md Access the deployment history of a contract type directly through `project.ContractName.deployments` to get the last deployment. ```python from ape import project def main(): my_contract = project.MyContract.deployments[-1] ``` -------------------------------- ### Reference NPM Dependency Source: https://github.com/apeworx/ape/blob/main/docs/userguides/dependencies.md Use dependencies from NPM. Ensure the package is installed locally via 'npm install' before adding it to your Ape configuration. ```yaml dependencies: - name: MyDependency npm: "@myorg/mydependency" version: v1.3.0 ``` -------------------------------- ### Connect to Custom Network via CLI with URI Source: https://github.com/apeworx/ape/blob/main/docs/userguides/networks.md Connect to a custom network on-the-fly using a URI with an existing ecosystem plugin. Specify the ecosystem, network, and provider URI. ```bash ape run script --network ::https://foo.bar ``` -------------------------------- ### Uninstall Specific Versions of a Dependency Source: https://github.com/apeworx/ape/blob/main/docs/userguides/dependencies.md Remove specific versions of a dependency if multiple versions are installed. You can also use 'all' to remove all installed versions. ```shell ape pm uninstall OpenZeppelin 4.5.0 4.6.0 ``` ```shell ape pm uninstall OpenZeppelin all --yes ``` -------------------------------- ### Reference Installed Python Projects Source: https://github.com/apeworx/ape/blob/main/docs/userguides/projects.md Use the 'Project.from_python_library()' class method to reference Ape projects installed via pip or other Python package managers. ```python from ape import Project snekmate = Project.from_python_library("snekmate", config_override={"contracts_folder": "."}) ``` -------------------------------- ### Basic CLI Script with Click Source: https://github.com/apeworx/ape/blob/main/docs/userguides/scripts.md Create a simple command-line interface script using the `click` library. Define a `cli` object that prints 'Hello world!'. This script can be executed using `ape run `. ```python import click @click.command() def cli(): print("Hello world!") ``` -------------------------------- ### Multi-Network Script with Context Manager Source: https://github.com/apeworx/ape/blob/main/docs/userguides/scripts.md Demonstrates how to use the `network_option` decorator and context managers (`use_provider`) to interact with multiple networks sequentially within a single script. This is useful for cross-chain operations. ```python import click from ape import networks, chain, accounts from ape.cli import network_option @click.command() @network_option() def cli(): """Connect to multiple networks in one command.""" # Uses the provider from network_option account = accounts.load("my-account") balance1 = account.balance network1 = chain.provider.network.name print(f"Balance on {network1}: {balance1}") # Temporarily use a different provider than was selected originally with networks.ethereum.sepolia.use_provider("alchemy"): balance2 = account.balance # Balance on Sepolia network2 = chain.provider.network.name print(f"Balance on {network2}: {balance2}") # Can even do a third network with networks.arbitrum.mainnet.use_provider("infura"): balance3 = account.balance # Balance on Arbitrum network3 = chain.provider.network.name print(f"Balance on {network3}: {balance3}") # Back to the original network print(f"Back to {network1}") ``` -------------------------------- ### Instantiate Contract from ABI (JSON File Path) Source: https://github.com/apeworx/ape/blob/main/docs/userguides/contracts.md Load a contract instance using its address and ABI from a JSON file path. ```python from ape import Contract address = "0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45" # Using a JSON file path: contract = Contract(address, abi="abi.json") ``` -------------------------------- ### Uninstall Dependency by Name Source: https://github.com/apeworx/ape/blob/main/docs/userguides/dependencies.md Remove a previously installed dependency using its name. ```shell ape pm uninstall OpenZeppelin ``` -------------------------------- ### Configure Console Plugins Source: https://github.com/apeworx/ape/blob/main/docs/userguides/console.md Enable IPython extensions for the console by listing them under the 'console.plugins' key in your `ape-config.yaml` file. ```yaml console: plugins: # A plugin that lets you modify Python modules without having close/reopen your console. - autoreload ``` -------------------------------- ### Update All Plugins Source: https://github.com/apeworx/ape/blob/main/docs/userguides/installing_plugins.md Use this command to update Ape and all installed plugins to their latest compatible versions. ```shell ape plugins update ``` -------------------------------- ### Register Plugin with Entry Points Source: https://github.com/apeworx/ape/blob/main/docs/userguides/developing_plugins.md Register your plugin's CLI group using the 'ape_cli_subcommands' entry point in your setup.py file. ```python entry_points={ "ape_cli_subcommands": [ "ape_myplugin=ape_myplugin._cli:cli", ], }, ``` -------------------------------- ### Uninstall Dependency by Package ID Source: https://github.com/apeworx/ape/blob/main/docs/userguides/dependencies.md Remove a previously installed dependency using its full package ID. ```shell ape pm uninstall OpenZeppelin/openzeppelin-contracts ``` -------------------------------- ### Instantiate Contract with ENS Domain Source: https://github.com/apeworx/ape/blob/main/docs/userguides/contracts.md Use an ENS domain name to instantiate a contract if the ape-ens plugin is installed. ```python from ape import Contract contract = Contract("v2.registry.ychad.eth") ``` -------------------------------- ### ape.Project(path) Source: https://github.com/apeworx/ape/blob/main/docs/methoddocs/ape.md Instantiates other projects given a path. ```APIDOC ## ape.Project(path) ### Description Instantiate other projects. See the `ProjectManager <../methoddocs/managers.html#ape.managers.project.ProjectManager>`__ for more info. ### Parameters #### Path Parameters - **path** (type) - Required - The path to the project. ### Method Function Call ### Endpoint N/A (Python function) ``` -------------------------------- ### Connect to Unknown Ecosystem/Network via CLI Source: https://github.com/apeworx/ape/blob/main/docs/userguides/networks.md Connect to an unknown ecosystem or network using only a URI. This defaults to the Ethereum ecosystem class. ```bash ape run script --network https://foo.bar ``` -------------------------------- ### List Available Networks Source: https://github.com/apeworx/ape/blob/main/docs/userguides/networks.md Run this command to see all networks that are compatible with the `--network` flag, excluding those only defined in evmchains. ```bash ape networks list ``` -------------------------------- ### Solidity Custom Error Example Source: https://github.com/apeworx/ape/blob/main/docs/userguides/reverts.md Defines a custom error `Unauthorized` in Solidity and demonstrates its usage within a contract function. ```solidity // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.4; error Unauthorized(address unauth_address); contract MyContract { address payable owner = payable(msg.sender); function withdraw() public { if (msg.sender != owner) revert Unauthorized(msg.sender); owner.transfer(address(this).balance); } } ``` -------------------------------- ### Create Project from Manifest Source: https://github.com/apeworx/ape/blob/main/docs/userguides/projects.md Instantiate a Project object directly from an EthPM package manifest by providing the manifest object, dictionary, or a path to its JSON file. ```python from ape import Project # Pass in a manifest (object or dictionary), or a path to a manifest's JSON file. project = Project.from_manifest("path/to/manifest.json") _ = project.MyContract # Do anything you can do to the root-level project. ``` -------------------------------- ### Convert Value Source: https://github.com/apeworx/ape/blob/main/docs/methoddocs/ape.md Use the conversion utility to convert values between types. For example, convert a string representation of Ether to an integer. ```python result = ape.convert("1 ETH", int) ``` -------------------------------- ### Get Previous Deployment via chain.contracts Source: https://github.com/apeworx/ape/blob/main/docs/userguides/contracts.md Retrieve the last deployment of a specific contract type from the deployment history using `chain.contracts.get_deployments`. ```python from ape import project, chain def main(): my_contract = chain.contracts.get_deployments(project.MyContract)[-1] ``` -------------------------------- ### Instantiate Contract from ABI (Python Dictionary) Source: https://github.com/apeworx/ape/blob/main/docs/userguides/contracts.md Load a contract instance using its address and ABI provided as a Python dictionary. ```python from ape import Contract address = "0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45" # Using a Python dictionary from JSON: contract = Contract( address, abi=[{"name":"foo","type":"fallback", "stateMutability":"nonpayable"}] ) ``` -------------------------------- ### Override Dependency Configuration via CLI Source: https://github.com/apeworx/ape/blob/main/docs/userguides/dependencies.md Use the `--config-override` flag with `ape pm install` for ad hoc configuration overrides. ```shell ape pm install --config-override '{"solidity": {"evm_version": "paris"}}' ``` -------------------------------- ### Use Default Provider from Configuration Source: https://github.com/apeworx/ape/blob/main/docs/userguides/networks.md Leverage the `use_default_provider` context manager to connect to the provider specified as the default in your `ape-config.yaml` for a given network. This simplifies configuration management. ```yaml arbitrum: mainnet: default_provider: alchemy ``` ```python import ape # Use the provider configured as the default for the arbitrum::mainnet network. # In this case, it will use the "alchemy" provider. with ape.networks.arbitrum.mainnet.use_default_provider(): ... ``` -------------------------------- ### Instantiate Contract from ABI (JSON String) Source: https://github.com/apeworx/ape/blob/main/docs/userguides/contracts.md Load a contract instance using its address and ABI provided as a JSON string. ```python from ape import Contract address = "0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45" # Using a JSON str: contract = Contract( address, abi='[{"name":"foo","type":"fallback", "stateMutability":"nonpayable"}]' ) ``` -------------------------------- ### Sign EIP-712 Structured Message Source: https://github.com/apeworx/ape/blob/main/docs/userguides/accounts.md Sign EIP-712 compliant structured messages using custom Pydantic models. Ensure `eip712` and `eth_pydantic_types` are installed. ```python from ape import accounts from eip712.messages import EIP712Message, EIP712Domain from eth_pydantic_types import abi from pydantic import BaseModel class Person(BaseModel): name: abi.string wallet: abi.address class Mail(EIP712Message): eip712_domain = EIP712Domain( name="Ether Mail", version="1", verifyingContract="0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC", chainId=1, ) sender: Person receivers: list[Person] alice = Person(name="Alice", wallet="0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826") bob = Person("Bob", "0xB0B0b0b0b0b0B000000000000000000000000000") charlie = Person("Charlie", "0xC0C0c0c0c0c0C000000000000000000000000000") message = Mail(sender=alice, receivers=[bob, charlie]) account = accounts.load("") account.sign_message(message) ``` -------------------------------- ### Initialize Deployed Contract using at() Source: https://github.com/apeworx/ape/blob/main/docs/userguides/contracts.md Initialize an instance of an already-deployed contract using its address. Ape automatically handles proxy detection. ```python from ape import project contract = project.MyContract.at("0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45") ``` -------------------------------- ### Configure Compiler Settings in YAML Source: https://github.com/apeworx/ape/blob/main/docs/userguides/compile.md Set compiler-specific settings, such as the version, under the respective compiler's key in `ape-config.yaml`. For example, configure the `vyper` plugin. ```yaml vyper: version: 0.3.10 ``` -------------------------------- ### Set CLI Command Description with short_help Source: https://github.com/apeworx/ape/blob/main/docs/userguides/developing_plugins.md Provide a short help description for a Click command using the 'short_help' keyword argument. ```python import click @click.command(short_help="Utilities for my plugin") def cli(): pass ``` -------------------------------- ### Creating Contract Instances with Contract Fixture Source: https://github.com/apeworx/ape/blob/main/docs/userguides/testing.md Instantiate contract objects using the 'Contract' fixture, providing the contract's address. ```python @pytest.fixture def my_contract(Contract): return Contract(
) ``` -------------------------------- ### Get Raw Return Data from Call Source: https://github.com/apeworx/ape/blob/main/docs/userguides/contracts.md Use `decode=False` to retrieve raw return data bytes from a contract call instead of decoded Python types. ```python from ape import accounts, Contract from eth_pydantic_types import HexBytes account = accounts.load("") contract = Contract("0x...") assert contract.get_static_list() == HexBytes( "0x0000000000000000000000000000000000000000000000000000000000000001" "0000000000000000000000000000000000000000000000000000000000000002" "0000000000000000000000000000000000000000000000000000000000000003" ) ``` -------------------------------- ### Import Existing Account with Alias Source: https://github.com/apeworx/ape/blob/main/docs/userguides/accounts.md Imports an existing account using its alias. You will be prompted for the private key. ```bash ape accounts import ``` -------------------------------- ### Run a Network Process Source: https://github.com/apeworx/ape/blob/main/docs/userguides/networks.md Launch a development node using the `ape networks run` command. Use flags like `--background` to run in the background or `--network` to specify a different node type (e.g., Foundry). ```shell ape networks run ``` ```shell ape networks run --background ``` ```shell ape networks run --network ethereum:local:foundry ``` ```shell ape networks run --network ethereum:local:foundry --block-time 10 ``` -------------------------------- ### Instantiate Contract from ABI Source: https://github.com/apeworx/ape/blob/main/docs/userguides/compile.md Create a contract wrapper using an ABI from a JSON file. This is useful for interacting with existing contracts by address. ```python from ape import project # Comes from a file named `MyInterface.json` in the contracts/ folder. my_interface = project.MyInterface address = "0x1234556b5Ed9202110D7Ecd637A4581db8b9879F" # Instantiate a deployed contract using the local interface. contract = my_interface.at(address) # Call a method named `my_method` found in the local contract ABI. contract.my_method() ``` -------------------------------- ### Retrieving Specific Events from a Receipt Source: https://github.com/apeworx/ape/blob/main/docs/userguides/transactions.md The `ContractEvent.from_receipt()` method can be used to directly get logs for a specific event type from a transaction receipt. This simplifies filtering for a single event. ```python receipt = contract.fooMethod(value="1 gwei", type="0x0", sender=sender) for log in contract.FooEvent.from_receipt(receipt): print(log.amount) # Assuming 'amount' is a property on the event. ``` -------------------------------- ### Instantiate a Contract Source: https://github.com/apeworx/ape/blob/main/docs/methoddocs/ape.md Instantiate contract classes at a given address. Optionally provide ABI or contract type data. ```python contract = ape.Contract(address, contract_type) ``` -------------------------------- ### Get Contract Container using get_contract() Source: https://github.com/apeworx/ape/blob/main/docs/userguides/contracts.md Retrieve a contract container from the project manager using its name. This is an alternative to accessing contracts directly via the project object. ```python from ape import project contract = project.get_contract("MyContract") # Same as `project.MyContract`. ``` -------------------------------- ### Handle FallbackNotDefinedError in Python Source: https://github.com/apeworx/ape/blob/main/docs/userguides/reverts.md Demonstrates how to catch a specific built-in error, FallbackNotDefinedError, when interacting with a contract. Ensure the relevant compiler plugin (e.g., ape_vyper) is installed and its exceptions are imported. ```python from ape import accounts, Contract from ape_vyper.exceptions import FallbackNotDefinedError my_contract = Contract("0x...") account = accounts.load("test-account") try: my_contract(sender=account) except FallbackNotDefinedError: print("fallback not defined") ``` -------------------------------- ### Compile All Project Dependencies Source: https://github.com/apeworx/ape/blob/main/docs/userguides/dependencies.md Recompile all dependencies for your local project by running the compile command without arguments. ```shell ape pm compile ``` -------------------------------- ### Connect to Network with Ape Console Source: https://github.com/apeworx/ape/blob/main/docs/userguides/data.md Use `ape console` to connect to a specific network and version. This is the entry point for interactive querying. ```bash ape console --network ethereum:mainnet:infura ``` -------------------------------- ### Get Account Balance with %bal Source: https://github.com/apeworx/ape/blob/main/docs/userguides/console.md The %bal magic command displays the human-readable balance for an account, contract, address, or alias. It can accept an account object, alias, or raw address. ```shell In [1]: account = accounts.load("metamask0") In [2]: %bal account Out[2]: '0.00040634 ETH' ``` ```shell In [3]: %bal metamask0 Out[3]: '0.00040634 ETH' ``` ```shell In [4]: %bal 0xE3747e6341E0d3430e6Ea9e2346cdDCc2F8a4b5b Out[4]: '0.00040634 ETH' ``` -------------------------------- ### Fixture with Disabled Chain Isolation Source: https://github.com/apeworx/ape/blob/main/docs/userguides/testing.md Example of an Ape fixture with `chain_isolation=False` and `params`. This fixture is session-scoped and does not alter chain isolation, potentially improving performance for specific use cases. ```python import ape from ape_tokens import tokens @ape.fixture(scope="session", chain_isolation=False, params=("WETH", "DAI", "BAT")) def token_addresses(request): return tokens[request].address ``` -------------------------------- ### Configure Custom Network within Custom Ecosystem Source: https://github.com/apeworx/ape/blob/main/docs/userguides/networks.md Define a custom network within a custom ecosystem in ape-config.yaml. This example sets static-fee transactions for Shibarium's 'mainnet'. ```yaml networks: custom: - name: mainnet ecosystem: shibarium base_ecosystem_plugin: polygon chain_id: 109 shibarium: mainnet: default_transaction_type: 0 ``` -------------------------------- ### Configure Default Transaction Type for Custom Network Source: https://github.com/apeworx/ape/blob/main/docs/userguides/networks.md Set network configuration properties like `default_transaction_type` for custom networks in ape-config.yaml. This example sets static-fee transactions for 'apenet'. ```yaml ethereum: apenet: default_transaction_type: 0 ``` -------------------------------- ### Set CLI Command Description with Docstring Source: https://github.com/apeworx/ape/blob/main/docs/userguides/developing_plugins.md Alternatively, set the short help description for a Click command using its docstring. ```python import click @click.command() def cli(): """Utilities for my plugin""" ``` -------------------------------- ### Compile Specific Dependency Version Source: https://github.com/apeworx/ape/blob/main/docs/userguides/dependencies.md Recompile a specific version of a dependency. Use the '--force' flag to recompile even if it has already been compiled. Specify the version only if multiple versions are installed. ```shell ape pm compile OpenZeppelin --version 4.6.0 --force ``` -------------------------------- ### Update Contract JSON from Source Source: https://github.com/apeworx/ape/blob/main/tests/functional/data/README.md Run this script from the data directory to update a contract's JSON representation after editing its source file. Ensure ape-solidity and/or ape-vyper are installed. ```shell ape run update ``` -------------------------------- ### Build Ape Docker Image Locally Source: https://github.com/apeworx/ape/blob/main/README.md Build the Ape Docker image locally from source. Use this if you need to customize the build or are developing Ape itself. ```bash $ docker build -t ape:latest-slim -f Dockerfile.slim . ``` ```bash $ docker build -t ape:latest . ``` -------------------------------- ### Manual Proxy Configuration with ContractContainer.at() Source: https://github.com/apeworx/ape/blob/main/docs/userguides/proxy.md Manually specify proxy information when creating contract instances using `ContractContainer.at()`. This is useful if automatic detection fails or if you need to force a specific implementation. ```python from ape import project from ape.api.networks import ProxyInfoAPI from ape_ethereum.proxies import ProxyInfo, ProxyType # Create proxy info with implementation address proxy_info = ProxyInfo(target="0x1234567890123456789012345678901234567890", type=ProxyType.STANDARD) # Create contract instance with manual proxy configuration contract = project.MyImplementation.at( "0xProxyAddress", # Provide proxy information manually proxy_info=proxy_info, ) ``` ```python # Or disable proxy detection entirely if you know it's not a proxy contract = project.MyContract.at( "0xAddress", detect_proxy=False ) ``` -------------------------------- ### Launch Ape Console for Transactions Source: https://github.com/apeworx/ape/blob/main/docs/userguides/transactions.md Use this command to launch the Ape console connected to a specific network, enabling interactive transaction making. ```bash ape console --network ethereum:mainnet:node ``` -------------------------------- ### Configure RPC URL for Custom Network Source: https://github.com/apeworx/ape/blob/main/docs/userguides/networks.md Set the RPC URL for a custom network by configuring the provider. This example shows how to set the URI for the 'mainnet' network within the 'shibarium' ecosystem. ```yaml default_ecosystem: shibarium networks: custom: - name: mainnet ecosystem: shibarium base_ecosystem_plugin: polygon # Closest base class. chain_id: 109 # This must be correct or txns will fail. node: shibarium: mainnet: uri: https://www.shibrpc.com ``` -------------------------------- ### Load Account in Ape Console Source: https://github.com/apeworx/ape/blob/main/docs/userguides/transactions.md Load an existing account from your Ape configuration to use for making transactions. ```bash account = accounts.load("") ``` -------------------------------- ### Define Network-Specific Fixtures Source: https://github.com/apeworx/ape/blob/main/docs/userguides/testing.md Create pytest fixtures that operate within a specific network context using `parse_network_choice`. This ensures that contract deployments or other setup logic run on the intended network. ```python import pytest @pytest.fixture def stark_contract(networks, project): with networks.parse_network_choice("starknet:local"): yield project.MyStarknetContract.deploy() def test_starknet_thing(stark_contract, stark_account): # Uses the starknet connection via the stark_contract fixture receipt = stark_contract.my_method(sender=stark_account) assert not receipt.failed ``` -------------------------------- ### Get Transaction Trace Directly Source: https://github.com/apeworx/ape/blob/main/docs/userguides/trace.md Retrieve a transaction trace directly from the provider, allowing for modification of trace parameters like `enableMemory`. The trace object can then be printed or used to access raw frames. ```python from ape import chain # Change the `debug_traceTransaction` parameter dictionary trace = chain.provider.get_transaction_trace( "0x...", debug_trace_transaction_parameters={"enableMemory": False} ) # You can still print the pretty call-trace (as we did in the example above) print(trace) # Interact with low-level logs for deeper analysis. struct_logs = trace.get_raw_frames() ``` -------------------------------- ### Configure Test Accounts in YAML Source: https://github.com/apeworx/ape/blob/main/docs/userguides/config.md Set up test accounts for Ape testing by providing a mnemonic phrase and the desired number of accounts in YAML format. ```yaml test: mnemonic: test test test test test test test test test test test junk number_of_accounts: 5 ``` -------------------------------- ### Expand Environment Variables in Plugin Config Source: https://github.com/apeworx/ape/blob/main/docs/userguides/config.md Use environment variables prefixed with `$` to dynamically set configuration values, keeping secrets out of config files. This example shows setting a secret RPC endpoint. ```toml [tool.ape.plugin] secret_rpc = "$MY_SECRET_RPC" ``` ```yaml plugin: secret_rpc: $MY_SECRET_RPC ``` -------------------------------- ### Set Project Base Path Source: https://github.com/apeworx/ape/blob/main/docs/userguides/config.md Configure the `base_path` to change Ape's root directory for project files. This is useful if your project structure differs from the standard, for example, placing source files in a `src/` directory. ```toml [tool.ape] base_path = "src" ``` ```yaml base_path: src ``` -------------------------------- ### Deploy Contract using AccountAPI Source: https://github.com/apeworx/ape/blob/main/docs/userguides/contracts.md Deploy a contract using an account and the project object. Ensure the contract is compiled before deployment. The constructor arguments are passed directly. ```python from ape import accounts, project # You need an account to deploy, as it requires a transaction. account = accounts.load("") # NOTE: refers to your account alias! contract = project.MyContract.deploy(1, account, sender=account) # NOTE: You can also do it this way: contract2 = account.deploy(project.MyContract, 1, account) ``` -------------------------------- ### Specify Network with Triplet Source: https://github.com/apeworx/ape/blob/main/docs/userguides/networks.md Use this format to specify an ecosystem, network, and provider. The ecosystem defaults to 'ethereum' and the network to 'local' if omitted. ```python "::" ``` -------------------------------- ### Access Project Configuration Source: https://github.com/apeworx/ape/blob/main/docs/userguides/config.md Retrieve custom or plugin settings from the project configuration object in Python. Ensure the settings are defined in your `ape-config.yaml`. ```python from ape import project my_str = project.config.my_project_key.my_string # "my_value" my_int = project.config.my_project_key.my_int # 123 my_bool = project.config.my_project_key.my_bool # True ``` -------------------------------- ### Compile Project Source: https://github.com/apeworx/ape/blob/main/docs/userguides/compile.md Use this command to compile all contracts within your Ape project. ```bash ape compile ``` -------------------------------- ### Jump Between Networks with Context Managers Source: https://github.com/apeworx/ape/blob/main/docs/userguides/networks.md Simulate multi-chain behavior by using separate context managers for different networks. This allows you to execute operations on Polygon and then Ethereum within the same script. ```python import click from ape import networks @click.command() def cli(): with networks.polygon.mainnet.use_provider("node"): ... with networks.ethereum.mainnet.use_provider("node"): ... ``` -------------------------------- ### Basic Main Method Script Source: https://github.com/apeworx/ape/blob/main/docs/userguides/scripts.md A simple script defining a `main()` function. These scripts automatically run in a connected context and are best for single-network workflows. ```python def main(): print("Hello world!") ``` -------------------------------- ### Use Fork Context Manager Source: https://github.com/apeworx/ape/blob/main/docs/userguides/forking_networks.md Temporarily fork a live network using the `networks.fork()` context manager. You can specify the provider and block number for the fork. ```python from ape import networks with networks.ethereum.mainnet.use_provider("alchemy") as alchemy: # Connect to live network print(f"Connected to: {alchemy.name}") # Create a fork of the current network using the specified fork provider with networks.fork(provider_name="foundry") as fork: print(f"Now using fork: {fork.name}") # You can specify a block number (using the configured default fork provider) with networks.fork(provider_name="foundry", block_number=17000000) as fork: print(f"Using fork at block {fork.chain.blocks.height}") ``` -------------------------------- ### Instantiate Contract by Address (No Explorer Fetch) Source: https://github.com/apeworx/ape/blob/main/docs/userguides/contracts.md Instantiate a contract by address without fetching from an explorer. This forces Ape to use only cached ABI/code. ```python from ape import Contract contract = Contract("0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45", fetch_from_explorer=False) ``` -------------------------------- ### Load Ape Console Extension Manually Source: https://github.com/apeworx/ape/blob/main/docs/userguides/console.md Manually load the `ape_console.plugin` extension in any IPython environment if the console magics are not automatically available. ```shell In [1]: %load_ext ape_console.plugin ``` -------------------------------- ### Fork Custom Network with Ape Foundry Source: https://github.com/apeworx/ape/blob/main/docs/userguides/networks.md Use this command to fork a custom network with Ape Foundry. Ensure the custom network is already set up and accessible. ```bash ape --network shibarium:puppynet-fork:foundry ``` -------------------------------- ### Programmatically Import Account from Private Key Source: https://github.com/apeworx/ape/blob/main/docs/userguides/accounts.md Imports an account using a raw private key, passphrase, and alias. Returns the account object. ```python import os from ape_accounts import import_account_from_private_key alias = "my-account" passphrase = "my SecurePassphrase" private_key = os.urandom(32).hex() account = import_account_from_private_key(alias, passphrase, private_key) print(f'Your imported account address is: {account.address}') ``` -------------------------------- ### Configure Default Network and Providers in TOML Source: https://github.com/apeworx/ape/blob/main/docs/userguides/config.md Set the default network for an Ethereum chain and specify the default provider for a specific network in TOML format. ```toml [tool.ape.ethereum] default_network = "mainnet-fork" [tool.ape.ethereum.mainnet_fork] default_provider = "hardhat" ``` -------------------------------- ### CLI Script with Network Connection Source: https://github.com/apeworx/ape/blob/main/docs/userguides/scripts.md This script uses `ConnectedProviderCommand` to automatically connect to a network. It provides access to ecosystem, network, and provider objects, and allows direct use of Ape's managers like `chain`. ```python import click from ape.cli import ConnectedProviderCommand @click.command(cls=ConnectedProviderCommand) def cli(ecosystem, network, provider): click.echo(f"Connected to {ecosystem.name}:{network.name} using provider '{provider.name}'.") # Access chain and other managers automatically from ape import chain click.echo(f"Current block: {chain.blocks.height}") ``` ```python import click from ape.cli import ConnectedProviderCommand @click.command(cls=ConnectedProviderCommand) def cli(network, provider): click.echo(f"You are connected to network '{network.name}'.") click.echo(provider.chain_id) ``` -------------------------------- ### Manual Proxy Configuration with Contract Factory Source: https://github.com/apeworx/ape/blob/main/docs/userguides/proxy.md Use the `Contract` factory with proxy parameters to disable detection or provide custom proxy information. This offers flexibility when automatic detection is insufficient. ```python from ape import Contract # Disable proxy detection contract = Contract("0xAddress", detect_proxy=False) ``` ```python # Provide custom proxy info contract = Contract( "0xProxyAddress", proxy_info=ProxyInfoAPI( target="0xImplementationAddress", type_name=ProxyType.STANDARD ) ) ``` -------------------------------- ### Configure Plugins in ape-config.yaml Source: https://github.com/apeworx/ape/blob/main/docs/userguides/installing_plugins.md Specify plugins and their versions in your project's ape-config.yaml file. The 'name' field is required, and 'version' is optional with constraint support. ```yaml plugins: - name: solidity version: 0.6.0 - name: hardhat - name: ens - name: etherscan version: ">=0.6.2,<0.7" ```