ape.api

Accounts

class ape.api.accounts.AccountAPI

Bases: ape.utils.basemodel.BaseInterfaceModel, ape.api.address.BaseAddress

An API class representing an account.

__dir__() List[str]

Display methods to IPython on a.[TAB] tab completion.

Returns

Method names that IPython uses for tab completion.

Return type

List[str]

__hash__ = None
property alias: Optional[str]

A shortened-name for quicker access to the account.

call(txn: ape.api.transactions.TransactionAPI, send_everything: bool = False) ape.api.transactions.ReceiptAPI

Make a transaction call.

Raises
  • AccountsError – When the nonce is invalid or the sender does not have enough funds.

  • TransactionError – When the required confirmations are negative.

  • SignatureError – When the user does not sign the transaction.

Parameters
  • txn (TransactionAPI) – An invoke-transaction.

  • send_everything (bool) – True will send the difference from balance and fee. Defaults to False.

Returns

ReceiptAPI

check_signature(data: Union[eth_account.messages.SignableMessage, ape.api.transactions.TransactionAPI], signature: Optional[ape.types.signatures._Signature] = None) bool

Verify a message or transaction was signed by this account.

Parameters
Returns

True if the data was signed by this account. False otherwise.

Return type

bool

deploy(contract: ContractContainer, *args, publish: bool = False, **kwargs) ContractInstance

Create a smart contract on the blockchain. The smart contract must compile before deploying and a provider must be active.

Parameters
  • contract (ContractContainer) – The type of contract to deploy.

  • publish (bool) – Set to True to attempt explorer contract verification. Defaults to False.

Returns

An instance of the deployed contract.

Return type

ContractInstance

prepare_transaction(txn: ape.api.transactions.TransactionAPI) ape.api.transactions.TransactionAPI

Set default values on a transaction.

Raises
  • AccountsError – When the account cannot afford the transaction or the nonce is invalid.

  • TransactionError – When given negative required confirmations.

Parameters

txn (TransactionAPI) – The transaction to prepare.

Returns

TransactionAPI

abstract sign_message(msg: eth_account.messages.SignableMessage) Optional[ape.types.signatures.MessageSignature]

Sign a message.

Parameters

msg (SignableMessage) – The message to sign. See these docs # noqa: E501 for more type information on this type.

Returns

The signed message.

Return type

MessageSignature (optional)

abstract sign_transaction(txn: ape.api.transactions.TransactionAPI) Optional[ape.types.signatures.TransactionSignature]

Sign a transaction.

Parameters

txn (TransactionAPI) – The transaction to sign.

Returns

The signed transaction.

Return type

TransactionSignature (optional)

transfer(account: Union[str, ChecksumAddress, ape.api.address.BaseAddress], value: Optional[Union[str, int]] = None, data: Optional[Union[bytes, str]] = None, **kwargs) ape.api.transactions.ReceiptAPI

Send funds to an account.

Parameters
  • account (str) – The account to send funds to.

  • value (str) – The amount to send.

  • data (str) – Extra data to include in the transaction.

Returns

ReceiptAPI

class ape.api.accounts.AccountContainerAPI(*, data_folder: pathlib.Path, account_type: Type[ape.api.accounts.AccountAPI])

Bases: ape.utils.basemodel.BaseInterfaceModel

An API class representing a collection of AccountAPI instances.

__contains__(address: ChecksumAddress) bool

Check if the address is an existing account in ape.

Raises

IndexError – When the given account address is not in this container.

Parameters

address (AddressType) – An account address.

Returns

True if ape manages the account with the given address.

Return type

bool

__delitem__(address: ChecksumAddress)

Delete an account.

Raises

NotImplementError – When not overridden within a plugin.

Parameters

address (AddressType) – The address of the account to delete.

__getitem__(address: ChecksumAddress) ape.api.accounts.AccountAPI

Get an account by address.

Parameters

address (AddressType) – The address to get. The type is an alias to ChecksumAddress. # noqa: E501

Raises

IndexError – When there is no local account with the given address.

Returns

AccountAPI

__hash__ = None
abstract __len__() int

Number of accounts.

abstract property accounts: Iterator[ape.api.accounts.AccountAPI]

Iterate over all accounts.

Returns

Iterator[AccountAPI]

abstract property aliases: Iterator[str]

Iterate over all available aliases.

Returns

Iterator[str]

append(account: ape.api.accounts.AccountAPI)

Add an account to the container.

Raises

AccountsError – When the account is already in the container.

Parameters

account (AccountAPI) – The account to add.

remove(account: ape.api.accounts.AccountAPI)

Delete an account.

Raises

AccountsError – When the account is not known to ape.

Parameters

account (AccountAPI) – The account to remove.

class ape.api.accounts.ImpersonatedAccount(*, raw_address: ChecksumAddress)

Bases: ape.api.accounts.AccountAPI

An account to use that does not require signing.

__hash__ = None
property address: ChecksumAddress

The address of this account. Subclasses must override and provide this value.

call(txn: ape.api.transactions.TransactionAPI, send_everything: bool = False) ape.api.transactions.ReceiptAPI

Make a transaction call.

Raises
  • AccountsError – When the nonce is invalid or the sender does not have enough funds.

  • TransactionError – When the required confirmations are negative.

  • SignatureError – When the user does not sign the transaction.

Parameters
  • txn (TransactionAPI) – An invoke-transaction.

  • send_everything (bool) – True will send the difference from balance and fee. Defaults to False.

Returns

ReceiptAPI

sign_message(msg: eth_account.messages.SignableMessage) Optional[ape.types.signatures.MessageSignature]

Sign a message.

Parameters

msg (SignableMessage) – The message to sign. See these docs # noqa: E501 for more type information on this type.

Returns

The signed message.

Return type

MessageSignature (optional)

sign_transaction(txn: ape.api.transactions.TransactionAPI) Optional[ape.types.signatures.TransactionSignature]

Sign a transaction.

Parameters

txn (TransactionAPI) – The transaction to sign.

Returns

The signed transaction.

Return type

TransactionSignature (optional)

class ape.api.accounts.TestAccountAPI

Bases: ape.api.accounts.AccountAPI

Test accounts for ape test (such accounts that use GeneratedDevAccounts) should implement this API instead of AccountAPI directly. This is how they show up in the accounts test fixture.

__hash__ = None
class ape.api.accounts.TestAccountContainerAPI(*, data_folder: pathlib.Path, account_type: Type[ape.api.accounts.AccountAPI])

Bases: ape.api.accounts.AccountContainerAPI

Test account containers for ape test (such containers that generate accounts using GeneratedDevAccounts) should implement this API instead of AccountContainerAPI directly. This is how they show up in the accounts test fixture.

__hash__ = None

Address

class ape.api.address.Address(address: ChecksumAddress)

Bases: ape.api.address.BaseAddress

A generic blockchain address.

Typically, this is used when we do not know the contract type at a given address, or to refer to an EOA the user doesn’t personally control.

property address: ChecksumAddress

The raw address type.

Returns

An alias to ChecksumAddress. # noqa: E501

Return type

AddressType

class ape.api.address.BaseAddress

Bases: ape.utils.basemodel.BaseInterface

A base address API class. All account-types subclass this type.

abstract property address: ChecksumAddress

The address of this account. Subclasses must override and provide this value.

property balance: int

The total balance of the account.

property code: Union[str, bytes, hexbytes.main.HexBytes]

The raw bytes of the smart-contract code at the address.

property codesize: int

The number of bytes in the smart contract.

property is_contract: bool

True when there is code associated with the address.

property nonce: int

The number of transactions associated with the address.

Compiler

class ape.api.compiler.CompilerAPI

Bases: ape.utils.basemodel.BaseInterfaceModel

Compiler plugins, such as for languages like Solidity or Vyper, implement this API.

See the repository for the ape-solidity plugin or the ape-vyper plugin as example implementations of this API.

abstract compile(contract_filepaths: List[pathlib.Path], base_path: Optional[pathlib.Path]) List[ethpm_types.contract_type.ContractType]

Compile the given source files. All compiler plugins must implement this function.

Parameters
  • contract_filepaths (List[pathlib.Path]) – A list of source file paths to compile.

  • base_path (Optional[pathlib.Path]) – Optionally provide the base path, such as the project contracts/ directory. Defaults to None. When using in a project via ape compile, gets set to the project’s contracts/ directory.

Returns

List[ContractType]

abstract get_versions(all_paths: List[pathlib.Path]) Set[str]

Retrieve the set of available compiler versions for this plugin to compile all_paths.

Parameters

all_paths (List[pathlib.Path]) – The list of paths.

Returns

A set of available compiler versions.

Return type

Set[str]

Config

class ape.api.config.ConfigEnum(value)

Bases: str, enum.Enum

A configuration Enum type. Use this to limit the values of a config item, such as colors "RED", "BLUE", "GREEN", rather than any arbitrary str.

class ape.api.config.GenericConfig(_env_file: Optional[Union[str, os.PathLike, List[Union[str, os.PathLike]], Tuple[Union[str, os.PathLike], ...]]] = '<object object>', _env_file_encoding: Optional[str] = None, _env_nested_delimiter: Optional[str] = None, _secrets_dir: Optional[Union[str, os.PathLike]] = None, *, __root__: dict = {})

Bases: ape.api.config.PluginConfig

The default class used when no specialized class is used.

__hash__ = None
class ape.api.config.PluginConfig(_env_file: Optional[Union[str, os.PathLike, List[Union[str, os.PathLike]], Tuple[Union[str, os.PathLike], ...]]] = '<object object>', _env_file_encoding: Optional[str] = None, _env_nested_delimiter: Optional[str] = None, _secrets_dir: Optional[Union[str, os.PathLike]] = None)

Bases: pydantic.env_settings.BaseSettings

A base plugin configuration class. Each plugin that includes a config API must register a subclass of this class.

__hash__ = None

Convert

class ape.api.convert.ConverterAPI

Bases: Generic[ape.api.convert.ConvertedType], ape.utils.basemodel.BaseInterfaceModel

abstract convert(value: Any) ape.api.convert.ConvertedType

Convert the given value to the type specified as the generic for this class. Implementations of this API must throw a ConversionError when the item fails to convert properly.

abstract is_convertible(value: Any) bool

Returns True if string value provided by value is convertible using ape.api.convert.ConverterAPI.convert().

Parameters

value (str) – The value to check.

Returns

True when the given value can be converted.

Return type

bool

Explorers

class ape.api.explorers.ExplorerAPI(*, name: str, network: ape.api.networks.NetworkAPI)

Bases: ape.utils.basemodel.BaseInterfaceModel

An API class representing a blockchain explorer for a particular network in a particular ecosystem.

abstract get_account_transactions(address: ChecksumAddress) Iterator[ReceiptAPI]

Get a list of list of transactions performed by an address.

Parameters

address (AddressType) – The account address.

Returns

Iterator[ReceiptAPI]

abstract get_address_url(address: ChecksumAddress) str

Get an address URL, such as for a transaction.

Parameters

address (AddressType) – The address to get the URL for.

Returns

str

abstract get_contract_type(address: ChecksumAddress) Optional[ethpm_types.contract_type.ContractType]

Get the contract type for a given address if it has been published in an explorer.

Parameters

address (AddressType) – The contract address.

Returns

If not published, returns None.

Return type

Optional[ContractType]

abstract get_transaction_url(transaction_hash: str) str

Get the transaction URL for the given transaction.

Parameters

transaction_hash (str) – The transaction hash.

Returns

str

abstract publish_contract(address: ChecksumAddress)

Publish a contract to the explorer.

Parameters

address (AddressType) – The address of the deployed contract.

Networks

class ape.api.networks.EcosystemAPI(*, name: str, data_folder: pathlib.Path, request_header: dict)

Bases: ape.utils.basemodel.BaseInterfaceModel

A set of related networks, such as Ethereum.

__getattr__(network_name: str) ape.api.networks.NetworkAPI

Get a network by name using . access.

Usage example:

from ape import networks
mainnet = networks.ecosystem.mainnet
Raises

NetworkNotFoundError – When there is no network with the given name.

Parameters

network_name (str) – The name of the network to retrieve.

Returns

NetworkAPI

__getitem__(network_name: str) ape.api.networks.NetworkAPI

Get a network by name.

Raises

NetworkNotFoundError – When there is no network with the given name.

Parameters

network_name (str) – The name of the network to retrieve.

Returns

NetworkAPI

__hash__ = None
add_network(network_name: str, network: ape.api.networks.NetworkAPI)

Attach a new network to an ecosystem (e.g. L2 networks like Optimism).

Raises

ape.exceptions.NetworkError – When the network already exists.

Parameters

network_name (str) – The name of the network to add.

Returns

NetworkAPI

property config: ape.api.config.PluginConfig

The configuration of the ecosystem. See ape.managers.config.ConfigManager for more information on plugin configurations.

Returns

ape.api.config.PluginConfig

abstract create_transaction(**kwargs) TransactionAPI

Create a transaction using key-value arguments.

Parameters

**kwargs – Everything the transaction needs initialize.

Returns

~ape.api.transactions.TransactionAPI

Return type

class

data_folder: pathlib.Path

The path to the .ape directory.

abstract classmethod decode_address(raw_address: Union[str, int, hexbytes.main.HexBytes]) ChecksumAddress

Convert a raw address to the ecosystem’s native address type.

Parameters

raw_address (Union[str, int]) – The address to convert.

Returns

AddressType

abstract decode_block(data: dict) BlockAPI

Decode data to a BlockAPI.

Parameters

data (dict) – A dictionary of data to decode.

Returns

BlockAPI

abstract decode_logs(logs: List[Dict], *events: ethpm_types.abi.EventABI) Iterator[ape.types.ContractLog]

Decode any contract logs that match the given event ABI from the raw log data.

Parameters
  • logs (List[Dict]) – A list of raw log data from the chain.

  • *events (EventABI) – Event definitions to decode.

Returns

Iterator[ContractLog]

abstract decode_receipt(data: dict) ReceiptAPI

Convert data to ReceiptAPI.

Parameters

data (dict) – A dictionary of Receipt properties.

Returns

ReceiptAPI

abstract decode_returndata(abi: ethpm_types.abi.MethodABI, raw_data: bytes) Any

Get the result of a contract call.

Arg:

abi (MethodABI): The method called. raw_data (bytes): Raw returned data.

Returns

All of the values returned from the contract function.

Return type

Any

property default_network: str

The name of the default network in this ecosystem.

Returns

str

abstract classmethod encode_address(address: ChecksumAddress) Union[str, int, hexbytes.main.HexBytes]

Convert the ecosystem’s native address type to a raw integer or str address.

Parameters

address (Union[str, int]) – The address to convert.

Returns

Union[str, int]

abstract encode_deployment(deployment_bytecode: hexbytes.main.HexBytes, abi: ethpm_types.abi.ConstructorABI, *args, **kwargs) TransactionAPI

Create a deployment transaction in the given ecosystem. This may require connecting to other networks.

Parameters
  • deployment_bytecode (HexBytes) – The bytecode to deploy.

  • abi (ConstructorABI) – The constructor interface of the contract.

  • *args – Constructor arguments.

  • **kwargs – Transaction arguments.

Returns

~ape.api.transactions.TransactionAPI

Return type

class

abstract encode_transaction(address: ChecksumAddress, abi: ethpm_types.abi.MethodABI, *args, **kwargs) TransactionAPI

Encode a transaction object from a contract function’s abi and call arguments. Update the transaction arguments with the overrides in kwargs as well.

Parameters
  • address (AddressType) – The address of the contract.

  • abi (MethodABI) – The function to call on the contract.

  • *args – Function arguments.

  • **kwargs – Transaction arguments.

Returns

~ape.api.transactions.TransactionAPI

Return type

class

get_network(network_name: str) ape.api.networks.NetworkAPI

Get the network for the given name.

Parameters

network_name (str) – The name of the network to get.

Raises

NetworkNotFoundError – When the network is not present.

Returns

NetworkAPI

get_network_data(network_name: str) Dict

Get a dictionary of data about providers in the network.

NOTE: The keys are added in an opinionated order for nicely translating into yaml.

Parameters

network_name (str) – The name of the network to get provider data from.

Returns

A dictionary containing the providers in a network.

Return type

dict

get_proxy_info(address: ChecksumAddress) Optional[ape.api.networks.ProxyInfoAPI]

Information about a proxy contract such as proxy type and implementation address.

Parameters

address (str) – The address of the contract.

Returns

Returns None if the contract does not use any known proxy pattern.

Return type

Optional[ProxyInfoAPI]

name: str

The name of the ecosystem. This should be set the same name as the plugin.

property networks: Dict[str, ape.api.networks.NetworkAPI]

A dictionary of network names mapped to their API implementation.

Returns

Dict[str, NetworkAPI]

request_header: dict

A shareable HTTP header for network requests.

serialize_transaction(transaction: TransactionAPI) bytes

Serialize a transaction to bytes.

Parameters

transaction (TransactionAPI) – The transaction to encode.

Returns

bytes

set_default_network(network_name: str)

Change the default network.

Raises

NetworkError – When the network does not exist.

Parameters

network_name (str) – The name of the default network to switch to.

class ape.api.networks.NetworkAPI(*, name: str, ecosystem: ape.api.networks.EcosystemAPI, data_folder: pathlib.Path, request_header: Dict)

Bases: ape.utils.basemodel.BaseInterfaceModel

A wrapper around a provider for a specific ecosystem.

__hash__ = None
property block_time: int

The approximate amount of time it takes for a new block to get mined to the chain. Configure in your ape-config.yaml file.

Config example:

ethereum:
  mainnet:
    block_time: 15
property chain_id: int

The ID of the blockchain.

NOTE: Unless overridden, returns same as ape.api.providers.ProviderAPI.chain_id.

property config: ape.api.config.PluginConfig

The configuration of the network. See ConfigManager for more information on plugin configurations.

data_folder: pathlib.Path

The path to the .ape directory.

property default_provider: Optional[str]

The name of the default provider or None.

Returns

Optional[str]

ecosystem: ape.api.networks.EcosystemAPI

The ecosystem of the network.

property explorer: Optional[ExplorerAPI]

The block-explorer for the given network.

Returns

ape.api.explorers.ExplorerAPI, optional

get_provider(provider_name: Optional[str] = None, provider_settings: Optional[Dict] = None)

Get a provider for the given name. If given None, returns the default provider.

Parameters
  • provider_name (str, optional) – The name of the provider to get. Defaults to None. When None, returns the default provider.

  • provider_settings (dict, optional) – Settings to apply to the provider. Defaults to None.

Returns

ProviderAPI

name: str

The name of the network.

property network_id: int

The ID of the network.

NOTE: Unless overridden, returns same as chain_id.

property providers

The providers of the network, such as Infura, Alchemy, or Geth.

Returns

Dict[str, partial[ProviderAPI]]

publish_contract(address: ChecksumAddress)

A convenience method to publish a contract to the explorer.

Raises

NetworkError – When there is no explorer for this network.

Parameters

address (AddressType) – The address of the contract.

request_header: Dict

A shareable network HTTP header.

property required_confirmations: int

The default amount of confirmations recommended to wait before considering a transaction “confirmed”. Confirmations refer to the number of blocks that have been added since the transaction’s block.

set_default_provider(provider_name: str)

Change the default provider.

Raises

NetworkError – When the given provider is not found.

Parameters

provider_name (str) – The name of the provider to switch to.

property transaction_acceptance_timeout: int

The amount of time to wait for a transaction to be accepted on the network. Does not include waiting for block-confirmations. Defaults to two minutes. Local networks use smaller timeouts.

use_default_provider(provider_settings: Optional[Dict] = None) ape.api.networks.ProviderContextManager

Temporarily connect and use the default provider. When entering the context, it calls method ape.api.providers.ProviderAPI.connect() and when exiting, it calls method ape.api.providers.ProviderAPI.disconnect().

NOTE: If multiple providers exist, uses whatever was “first” registered.

Usage example:

from ape import networks
mainnet = networks.ethereum.mainnet  # An instance of NetworkAPI
with mainnet.use_default_provider():
    ...
Parameters

provider_settings (dict, optional) – Settings to override the provider.

Returns

ProviderContextManager

use_provider(provider_name: str, provider_settings: Optional[Dict] = None) ape.api.networks.ProviderContextManager

Use and connect to a provider in a temporary context. When entering the context, it calls method ape.api.providers.ProviderAPI.connect() and when exiting, it calls method ape.api.providers.ProviderAPI.disconnect().

Usage example:

from ape import networks

mainnet = networks.ethereum.mainnet  # An instance of NetworkAPI
with mainnet.use_provider("infura"):
    ...
Parameters
  • provider_name (str) – The name of the provider to use.

  • provider_settings (dict, optional) – Settings to apply to the provider. Defaults to None.

Returns

ape.api.networks.ProviderContextManager

verify_chain_id(chain_id: int)

Verify a chain ID for this network.

Parameters

chain_id (int) – The chain ID to verify.

Raises

NetworkMismatchError – When the network is not local or adhoc and has a different hardcoded chain ID than the given one.

class ape.api.networks.ProviderContextManager(provider: ProviderAPI)

Bases: ape.utils.basemodel.ManagerAccessMixin

A context manager for temporarily connecting to a network. When entering the context, calls the ape.api.providers.ProviderAPI.connect() method. And conversely, when exiting, calls the ape.api.providers.ProviderPAI.disconnect() method.

The method ape.api.networks.NetworkAPI.use_provider() returns an instance of this context manager.

Usage example:

from ape import networks

mainnet = networks.ethereum.mainnet  # An instance of NetworkAPI
with mainnet.use_provider("infura"):
    ...
class ape.api.networks.ProxyInfoAPI(*, target: ChecksumAddress)

Bases: pydantic.main.BaseModel

Information about a proxy contract.

__hash__ = None
target: ChecksumAddress

The address of the implementation contract.

ape.api.networks.create_network_type(chain_id: int, network_id: int) Type[ape.api.networks.NetworkAPI]

Easily create a ape.api.networks.NetworkAPI subclass.

Projects

class ape.api.projects.DependencyAPI(*, name: str, version: Optional[str] = None, contracts_folder: str = 'contracts', exclude: List[str] = ['package.json', 'package-lock.json'])

Bases: ape.utils.basemodel.BaseInterfaceModel

A base-class for dependency sources, such as GitHub or IPFS.

property cached_manifest: Optional[ethpm_types.manifest.PackageManifest]

The manifest from the .ape/packages/<dependency-name>/<version-id> if it exists and is valid.

contracts_folder: str

The name of the dependency’s contracts/ directory. This is where ape will look for source files when compiling the manifest for this dependency. NOTE: This must be the name of a directory in the project.

exclude: List[str]

A list of glob-patterns for excluding files in dependency projects.

abstract extract_manifest() ethpm_types.manifest.PackageManifest

Create a PackageManifest definition, presumably by downloading and compiling the dependency.

Implementations may use self.project_manager to call method get_project() to dynamically get the correct ProjectAPI. based on the project’s structure.

Returns

PackageManifest

name: str

The name of the dependency.

version: Optional[str]

The version of the dependency. Omit to use the latest.

abstract property version_id: str

The ID to use as the sub-directory in the download cache. Most often, this is either a version number or a branch name.

class ape.api.projects.ProjectAPI(*, path: pathlib.Path, contracts_folder: pathlib.Path, name: Optional[str] = None, version: Optional[str] = None)

Bases: ape.utils.basemodel.BaseInterfaceModel

An abstract base-class for working with projects. This class can also be extended to a plugin for supporting non-ape projects.

property cached_manifest: Optional[ethpm_types.manifest.PackageManifest]

The PackageManifest at manifest_cachefile if it exists and is valid.

contracts_folder: pathlib.Path

The path to the contracts in the project.

abstract create_manifest(file_paths: Optional[List[pathlib.Path]] = None, use_cache: bool = True) ethpm_types.manifest.PackageManifest

Create a manifest from the project.

Parameters
  • file_paths (Optional[List[Path]]) – An optional list of paths to compile from this project.

  • use_cache (bool) – Set to False to clear caches and force a re-compile.

Returns

PackageManifest

abstract property is_valid: bool

True if the project at the given path matches this project type. Useful for figuring out the best ProjectAPI to use when compiling a project.

property manifest_cachefile: pathlib.Path

The path to the project’s cached manifest. The manifest is a cached file representing the project and is useful for sharing, such as uploading to IPFS.

Returns

pathlib.Path

name: Optional[str]

The name of this project when another project uses it as a dependency.

path: pathlib.Path

The project path.

version: Optional[str]

The version of the project whe another project uses it as a dependency.

Providers

class ape.api.providers.BlockAPI(*, num_transactions: int = 0, hash: Optional[Any] = None, number: Optional[int] = None, parentHash: Any = HexBytes('0x0000000000000000000000000000000000000000000000000000000000000000'), size: int, timestamp: int)

Bases: ape.utils.basemodel.BaseInterfaceModel

An abstract class representing a block and its attributes.

class ape.api.providers.ProviderAPI(*, name: str, network: ape.api.networks.NetworkAPI, provider_settings: dict, data_folder: pathlib.Path, request_header: dict, cached_chain_id: Optional[int] = None, block_page_size: int = 100, concurrency: int = 4)

Bases: ape.utils.basemodel.BaseInterfaceModel

An abstraction of a connection to a network in an ecosystem. Example ProviderAPI implementations include the ape-infura plugin or the ape-hardhat plugin.

property base_fee: int

The minimum value required to get your transaction included on the next block. Only providers that implement EIP-1559 will use this property.

Raises

NotImplementedError – When this provider does not implement EIP-1559.

block_page_size: int

The amount of blocks to fetch in a response, as a default. This is particularly useful for querying logs across a block range.

cached_chain_id: Optional[int]

Implementation providers may use this to cache and re-use chain ID.

abstract property chain_id: int

The blockchain ID. See ChainList for a comprehensive list of IDs.

concurrency: int

How many parallel threads to use when fetching logs.

property config: ape.api.config.PluginConfig

The provider’s configuration.

abstract connect()

Connect a to a provider, such as start-up a process or create an HTTP connection.

data_folder: pathlib.Path

The path to the .ape directory.

abstract disconnect()

Disconnect from a provider, such as tear-down a process or quit an HTTP session.

abstract estimate_gas_cost(txn: ape.api.transactions.TransactionAPI) int

Estimate the cost of gas for a transaction.

Parameters

txn (TransactionAPI) – The transaction to estimate the gas for.

Returns

The estimated cost of gas to execute the transaction reported in the fee-currency’s smallest unit, e.g. Wei.

Return type

int

abstract property gas_price: int

The price for what it costs to transact (pre-EIP-1559).

abstract get_balance(address: str) int

Get the balance of an account.

Parameters

address (str) – The address of the account.

Returns

The account balance.

Return type

int

abstract get_block(block_id: Union[int, HexStr, hexbytes.main.HexBytes, Literal['earliest', 'latest', 'pending']]) ape.api.providers.BlockAPI

Get a block.

Parameters

block_id (BlockID) – The ID of the block to get. Can be "latest", "earliest", "pending", a block hash or a block number.

Raises

BlockNotFoundError – Likely the exception raised when a block is not found (depends on implementation).

Returns

The block for the given ID.

Return type

BlockID

abstract get_code(address: ChecksumAddress) Union[str, bytes, hexbytes.main.HexBytes]

Get the bytes a contract.

Parameters

address (AddressType) – The address of the contract.

Returns

The contract bytecode.

Return type

ContractCode

abstract get_contract_logs(log_filter: ape.types.LogFilter) Iterator[ape.types.ContractLog]

Get logs from contracts.

Parameters

log_filter (LogFilter) – A mapping of event ABIs to topic filters. Defaults to getting all events.

Returns

Iterator[ContractLog]

abstract get_nonce(address: ChecksumAddress) int

Get the number of times an account has transacted.

Parameters

address (AddressType) – The address of the account.

Returns

int

abstract get_receipt(txn_hash: str) ape.api.transactions.ReceiptAPI

Get the information about a transaction from a transaction hash.

Parameters

txn_hash (str) – The hash of the transaction to retrieve.

Returns

The receipt of the transaction with the given hash.

Return type

ReceiptAPI

abstract get_transactions_by_block(block_id: Union[int, HexStr, hexbytes.main.HexBytes, Literal['earliest', 'latest', 'pending']]) Iterator[ape.api.transactions.TransactionAPI]

Get the information about a set of transactions from a block.

Parameters

block_id (BlockID) – The ID of the block.

Returns

class: ~ape.api.transactions.TransactionAPI]

Return type

Iterator[

get_virtual_machine_error(exception: Exception) ape.exceptions.VirtualMachineError

Get a virtual machine error from an error returned from your RPC. If from a contract revert / assert statement, you will be given a special ContractLogicError that can be checked in ape.reverts() tests.

NOTE: The default implementation is based on geth output. ProviderAPI implementations override when needed.

Parameters

exception (Exception) – The error returned from your RPC client.

Returns

An error representing what

went wrong in the call.

Return type

VirtualMachineError

abstract property is_connected: bool

True if currently connected to the provider. False otherwise.

property max_gas: int

The max gas limit value you can use.

name: str

The name of the provider (should be the plugin name).

network: ape.api.networks.NetworkAPI

A reference to the network this provider provides.

prepare_transaction(txn: ape.api.transactions.TransactionAPI) ape.api.transactions.TransactionAPI

Set default values on the transaction.

Raises

TransactionError – When given negative required confirmations.

Parameters

txn (TransactionAPI) – The transaction to prepare.

Returns

TransactionAPI

property priority_fee: int

A miner tip to incentivize them to include your transaction in a block.

Raises

NotImplementedError – When the provider does not implement EIP-1559 typed transactions.

provider_settings: dict

The settings for the provider, as overrides to the configuration.

request_header: dict

A header to set on HTTP/RPC requests.

abstract send_call(txn: ape.api.transactions.TransactionAPI, **kwargs) bytes

Execute a new transaction call immediately without creating a transaction on the blockchain.

Parameters

txn (TransactionAPI) – The transaction to send as a call.

Returns

The result of the transaction call.

Return type

str

abstract send_transaction(txn: ape.api.transactions.TransactionAPI) ape.api.transactions.ReceiptAPI

Send a transaction to the network.

Parameters

txn (TransactionAPI) – The transaction to send.

Returns

ReceiptAPI

property supports_tracing: bool

True when the provider can provide transaction traces.

abstract update_settings(new_settings: dict)

Change a provider’s setting, such as configure a new port to run on. May require a reconnect.

Parameters

new_settings (dict) – The new provider settings.

class ape.api.providers.SubprocessProvider(*, name: str, network: ape.api.networks.NetworkAPI, provider_settings: dict, data_folder: pathlib.Path, request_header: dict, cached_chain_id: Optional[int] = None, block_page_size: int = 100, concurrency: int = 4, process: Optional[subprocess.Popen] = None, is_stopping: bool = False, stdout_queue: Optional[ape.utils.process.JoinableQueue] = None, stderr_queue: Optional[ape.utils.process.JoinableQueue] = None, PROCESS_WAIT_TIMEOUT: int = 15)

Bases: ape.api.providers.ProviderAPI

A provider that manages a process, such as for ganache.

abstract build_command() List[str]

Get the command as a list of str. Subclasses should override and add command arguments if needed.

Returns

The command to pass to subprocess.Popen.

Return type

List[str]

connect()

Start the process and connect to it. Subclasses handle the connection-related tasks.

disconnect()

Stop the process if it exists. Subclasses override this method to do provider-specific disconnection tasks.

abstract property process_name: str

The name of the process, such as Hardhat node.

start(timeout: int = 20)

Start the process and wait for its RPC to be ready.

stop()

Kill the process.

class ape.api.providers.TestProviderAPI(*, name: str, network: ape.api.networks.NetworkAPI, provider_settings: dict, data_folder: pathlib.Path, request_header: dict, cached_chain_id: Optional[int] = None, block_page_size: int = 100, concurrency: int = 4)

Bases: ape.api.providers.ProviderAPI

An API for providers that have development functionality, such as snapshotting.

abstract mine(num_blocks: int = 1)

Advance by the given number of blocks.

Parameters

num_blocks (int) – The number of blocks allotted to mine. Defaults to 1.

abstract revert(snapshot_id: Union[str, int, bytes])

Regress the current call using the given snapshot ID. Allows developers to go back to a previous state.

Parameters

snapshot_id (str) – The snapshot ID.

abstract set_timestamp(new_timestamp: int)

Change the pending timestamp.

Parameters

new_timestamp (int) – The timestamp to set.

Returns

The new timestamp.

Return type

int

abstract snapshot() Union[str, int, bytes]

Record the current state of the blockchain with intent to later call the method revert() to go back to this point. This method is for local networks only.

Returns

The snapshot ID.

Return type

SnapshotID

class ape.api.providers.UpstreamProvider(*, name: str, network: ape.api.networks.NetworkAPI, provider_settings: dict, data_folder: pathlib.Path, request_header: dict, cached_chain_id: Optional[int] = None, block_page_size: int = 100, concurrency: int = 4)

Bases: ape.api.providers.ProviderAPI

A provider that can also be set as another provider’s upstream.

abstract property connection_str: str

The str used by downstream providers to connect to this one. For example, the URL for HTTP-based providers.

class ape.api.providers.Web3Provider(*, name: str, network: ape.api.networks.NetworkAPI, provider_settings: dict, data_folder: pathlib.Path, request_header: dict, cached_chain_id: Optional[int] = None, block_page_size: int = 100, concurrency: int = 4)

Bases: ape.api.providers.ProviderAPI, abc.ABC

A base provider mixin class that uses the web3.py python package.

property base_fee: int

The minimum value required to get your transaction included on the next block. Only providers that implement EIP-1559 will use this property.

Raises

NotImplementedError – When this provider does not implement EIP-1559.

property chain_id: int

The blockchain ID. See ChainList for a comprehensive list of IDs.

estimate_gas_cost(txn: ape.api.transactions.TransactionAPI, **kwargs) int

Estimate the cost of gas for a transaction.

Parameters
  • txn (TransactionAPI) – The transaction to estimate the gas for.

  • kwargs

    • block_identifier (BlockID): The block ID to use when estimating the transaction. Useful for checking a past estimation cost of a transaction.

    • state_overrides (Dict): Modify the state of the blockchain prior to estimation.

Returns

The estimated cost of gas to execute the transaction reported in the fee-currency’s smallest unit, e.g. Wei. If the provider’s network has been configured with a gas limit override, it will be returned. If the gas limit configuration is “max” this will return the block maximum gas limit.

Return type

int

property gas_price: int

The price for what it costs to transact (pre-EIP-1559).

get_balance(address: str) int

Get the balance of an account.

Parameters

address (str) – The address of the account.

Returns

The account balance.

Return type

int

get_block(block_id: Union[int, HexStr, hexbytes.main.HexBytes, Literal['earliest', 'latest', 'pending']]) ape.api.providers.BlockAPI

Get a block.

Parameters

block_id (BlockID) – The ID of the block to get. Can be "latest", "earliest", "pending", a block hash or a block number.

Raises

BlockNotFoundError – Likely the exception raised when a block is not found (depends on implementation).

Returns

The block for the given ID.

Return type

BlockID

get_code(address: ChecksumAddress) Union[str, bytes, hexbytes.main.HexBytes]

Get the bytes a contract.

Parameters

address (AddressType) – The address of the contract.

Returns

The contract bytecode.

Return type

ContractCode

get_contract_logs(log_filter: ape.types.LogFilter) Iterator[ape.types.ContractLog]

Get logs from contracts.

Parameters

log_filter (LogFilter) – A mapping of event ABIs to topic filters. Defaults to getting all events.

Returns

Iterator[ContractLog]

get_nonce(address: str, **kwargs) int

Get the number of times an account has transacted.

Parameters
  • address (str) – The address of the account.

  • kwargs

    • block_identifier (BlockID): The block ID for checking a previous account nonce.

Returns

int

get_receipt(txn_hash: str, required_confirmations: int = 0, timeout: Optional[int] = None) ape.api.transactions.ReceiptAPI

Get the information about a transaction from a transaction hash.

Parameters
  • txn_hash (str) – The hash of the transaction to retrieve.

  • required_confirmations (int) – The amount of block confirmations to wait before returning the receipt. Defaults to 0.

  • timeout (Optional[int]) – The amount of time to wait for a receipt before timing out. Defaults None.

Raises

TransactionNotFoundError – Likely the exception raised when the transaction receipt is not found (depends on implementation).

Returns

The receipt of the transaction with the given hash.

Return type

ReceiptAPI

get_storage_at(address: str, slot: int, **kwargs) bytes

Gets the raw value of a storage slot of a contract.

Parameters
  • address (str) – The address of the contract.

  • slot (int) – Storage slot to read the value of.

  • kwargs

    • block_identifier (BlockID): The block ID for checking previous contract storage values.

Returns

The value of the storage slot.

Return type

bytes

get_transactions_by_block(block_id: Union[int, HexStr, hexbytes.main.HexBytes, Literal['earliest', 'latest', 'pending']]) Iterator

Get the information about a set of transactions from a block.

Parameters

block_id (BlockID) – The ID of the block.

Returns

class: ~ape.api.transactions.TransactionAPI]

Return type

Iterator[

property is_connected: bool

True if currently connected to the provider. False otherwise.

property max_gas: int

The max gas limit value you can use.

property priority_fee: int

A miner tip to incentivize them to include your transaction in a block.

Raises

NotImplementedError – When the provider does not implement EIP-1559 typed transactions.

send_call(txn: ape.api.transactions.TransactionAPI, **kwargs) bytes

Execute a new transaction call immediately without creating a transaction on the block chain.

Parameters
  • txnTransactionAPI

  • kwargs

    • block_identifier (BlockID): The block ID to use to send a call at a historical point of a contract. checking a past estimation cost of a transaction.

    • state_overrides (Dict): Modify the state of the blockchain prior to sending the call, for testing purposes.

    • show_trace (bool): Set to True to display the call’s trace. Defaults to False.

    • show_gas_report (bool): Set to ``True to display the call’s gas report. Defaults to False.

    • skip_trace (bool): Set to True to skip the trace no matter what. This is useful if you are making a more background contract call of some sort, such as proxy-checking, and you are running a global call-tracer such as using the --gas flag in tests.

Returns

The result of the transaction call.

Return type

str

send_transaction(txn: ape.api.transactions.TransactionAPI) ape.api.transactions.ReceiptAPI

Send a transaction to the network.

Parameters

txn (TransactionAPI) – The transaction to send.

Returns

ReceiptAPI

property supports_tracing: bool

True when the provider can provide transaction traces.

update_settings(new_settings: dict)

Change a provider’s setting, such as configure a new port to run on. May require a reconnect.

Parameters

new_settings (dict) – The new provider settings.

property web3: web3.main.Web3

Access to the web3 object as if you did Web3(HTTPProvider(uri)).

Transactions

class ape.api.transactions.ReceiptAPI(*, contract_address: Optional[ChecksumAddress] = None, block_number: int, gas_used: int, logs: List[dict] = [], status: int, txn_hash: str, transaction: ape.api.transactions.TransactionAPI)

Bases: ape.utils.basemodel.BaseInterfaceModel

An abstract class to represent a transaction receipt. The receipt contains information about the transaction, such as the status and required confirmations.

NOTE: Use a required_confirmations of 0 in your transaction to not wait for confirmations.

Get a receipt by making transactions in ape, such as interacting with a ape.contracts.base.ContractInstance.

await_confirmations() ape.api.transactions.ReceiptAPI

Wait for a transaction to be considered confirmed.

Returns

The receipt that is now confirmed.

Return type

ReceiptAPI

abstract decode_logs(abi: Optional[Union[List[Union[ethpm_types.abi.EventABI, ContractEvent]], ethpm_types.abi.EventABI, ContractEvent]] = None) Iterator[ape.types.ContractLog]

Decode the logs on the receipt.

Parameters

abi (EventABI) – The ABI of the event to decode into logs.

Returns

Iterator[ContractLog]

property failed: bool

Whether the receipt represents a failing transaction. Ecosystem plugins override this property when their receipts are able to be failing.

property method_called: Optional[ethpm_types.abi.MethodABI]

The method ABI of the method called to produce this receipt. Requires both that the user is using a provider that supports traces as well as for this to have been a contract invocation.

raise_for_status()

Handle provider-specific errors regarding a non-successful TransactionStatusEnum.

abstract property ran_out_of_gas: bool

Check if a transaction ran out of gas and failed.

Returns

True when the transaction failed and used the same amount of gas as the given gas_limit.

Return type

bool

property return_value: Any

Obtain the final return value of the call. Requires tracing to function, since this is not available from the receipt object.

abstract property total_fees_paid: int

The total amount of fees paid for the transaction.

property trace: Iterator[evm_trace.base.TraceFrame]

The trace of the transaction, if available from your provider.

track_gas()

Track this receipt’s gas in the on-going sessional gas-report. Requires using a provider that support transaction traces. This gets called when running tests with the --gas flag.

class ape.api.transactions.TransactionAPI(*, chainId: int = 0, to: Optional[ChecksumAddress] = None, sender: Optional[ChecksumAddress] = None, gas: Optional[Union[Literal['auto', 'max'], int, str]] = None, nonce: Optional[int] = None, value: int = 0, data: bytes = b'', type: Union[int, bytes, str], max_fee: Optional[int] = None, max_priority_fee: Optional[int] = None, required_confirmations: Optional[int] = None, signature: Optional[ape.types.signatures.TransactionSignature] = None)

Bases: ape.utils.basemodel.BaseInterfaceModel

An API class representing a transaction. Ecosystem plugins implement one or more of transaction APIs depending on which schemas they permit, such as typed-transactions from EIP-1559.

abstract serialize_transaction() bytes

Serialize the transaction

property total_transfer_value: int

The total amount of WEI that a transaction could use. Useful for determining if an account balance can afford to submit the transaction.

abstract property txn_hash: ethpm_types.utils.HexBytes

The calculated hash of the transaction.

Query

class ape.api.query.AccountTransactionQuery(*, columns: List[str], account: ChecksumAddress, start_nonce: pydantic.types.NonNegativeInt = 0, stop_nonce: pydantic.types.NonNegativeInt)

Bases: ape.api.query._BaseQuery

A QueryType that collects properties of TransactionAPI over a range of transactions made by account between start_nonce and stop_nonce.

__hash__ = None
class ape.api.query.BlockQuery(*, columns: List[str], start_block: pydantic.types.NonNegativeInt = 0, stop_block: pydantic.types.NonNegativeInt, step: pydantic.types.PositiveInt = 1)

Bases: ape.api.query._BaseBlockQuery

A QueryType that collects properties of BlockAPI over a range of blocks between start_block and stop_block.

__hash__ = None
class ape.api.query.BlockTransactionQuery(*, columns: List[str], block_id: Any = None)

Bases: ape.api.query._BaseQuery

A QueryType that collects properties of TransactionAPI over a range of transactions collected inside the BlockAPI` object represented by ``block_id.

__hash__ = None
class ape.api.query.ContractEventQuery(*, columns: List[str], start_block: pydantic.types.NonNegativeInt = 0, stop_block: pydantic.types.NonNegativeInt, step: pydantic.types.PositiveInt = 1, contract: Union[ChecksumAddress, List[ChecksumAddress]], event: ethpm_types.abi.EventABI, search_topics: Optional[Dict[str, Any]] = None)

Bases: ape.api.query._BaseBlockQuery

A QueryType that collects members from event over a range of logs emitted by contract between start_block and stop_block.

__hash__ = None
class ape.api.query.ContractMethodQuery(*, columns: List[str], start_block: pydantic.types.NonNegativeInt = 0, stop_block: pydantic.types.NonNegativeInt, step: pydantic.types.PositiveInt = 1, contract: ChecksumAddress, method: ethpm_types.abi.MethodABI, method_args: Dict[str, Any])

Bases: ape.api.query._BaseBlockQuery

A QueryType that collects return values from calling method in contract over a range of blocks between start_block and stop_block.

__hash__ = None
class ape.api.query.QueryAPI

Bases: ape.utils.basemodel.BaseInterfaceModel

__hash__ = None
abstract estimate_query(query: Union[ape.api.query.BlockQuery, ape.api.query.BlockTransactionQuery, ape.api.query.AccountTransactionQuery, ape.api.query.ContractEventQuery, ape.api.query.ContractMethodQuery]) Optional[int]

Estimation of time needed to complete the query. The estimation is returned as an int representing milliseconds. A value of None indicates that the query engine is not available for use or is unable to complete the query.

Parameters

query (QueryType) – Query to estimate.

Returns

Represents milliseconds, returns None if unable to execute.

Return type

Optional[int]

abstract perform_query(query: Union[ape.api.query.BlockQuery, ape.api.query.BlockTransactionQuery, ape.api.query.AccountTransactionQuery, ape.api.query.ContractEventQuery, ape.api.query.ContractMethodQuery]) Iterator

Executes the query using best performing estimate_query query engine.

Parameters

query (QueryType) – query to execute

Returns

Iterator

update_cache(query: Union[ape.api.query.BlockQuery, ape.api.query.BlockTransactionQuery, ape.api.query.AccountTransactionQuery, ape.api.query.ContractEventQuery, ape.api.query.ContractMethodQuery], result: Iterator[ape.utils.basemodel.BaseInterfaceModel])

Allows a query plugin the chance to update any cache using the results obtained from other query plugins. Defaults to doing nothing, override to store cache data.

Parameters
  • query (QueryType) – query that was executed

  • result (Iterator) – the result of the query