ape.api

Accounts

class ape.api.accounts.AccountAPI

Bases: BaseInterfaceModel, 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]

property alias: str | None

A shortened-name for quicker access to the account.

call(txn: TransactionAPI, send_everything: bool = False, private: bool = False, **signer_options) 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.

  • APINotImplementedError – When setting private=True and using a provider that does not support private transactions.

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

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

  • private (bool) – True will use the send_private_transaction() method.

  • **signer_options – Additional kwargs given to the signer to modify the signing operation.

Returns:

ReceiptAPI

check_signature(data: SignableMessage | TransactionAPI | str | EIP712Message | int | bytes, signature: MessageSignature | None = None, recover_using_eip191: bool = True) bool

Verify a message or transaction was signed by this account.

Parameters:
  • data (Union[SignableMessage, TransactionAPI]) – # noqa: E501 The message or transaction to verify.

  • signature (Optional[MessageSignature]) – The signature to check. Defaults to None and is not needed when the first argument is a transaction class.

  • recover_using_eip191 (bool) – Perform recovery using EIP-191 signed message check. If set False, then will attempt recovery as raw hash. data` must be a 32 byte hash if this is set False. Defaults to True.

Returns:

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

Return type:

bool

declare(contract: ContractContainer, *args, **kwargs) ReceiptAPI

Deploy the “blueprint” of a contract type. For EVM providers, this likely means using EIP-5202, which is implemented in the core ape-ethereum plugin.

Parameters:

contract (ContractContainer) – The contract container to declare.

Returns:

The receipt of the declare transaction.

Return type:

ReceiptAPI

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

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

prepare_transaction(txn: TransactionAPI) 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: Any, **signer_options) MessageSignature | None

Sign a message.

Parameters:
  • msg (Any) – The message to sign. Account plugins can handle various types of messages. For example, KeyfileAccount can handle SignableMessage, str, int, and bytes. See these docs # noqa: E501 for more type information on the SignableMessage type.

  • **signer_options – Additional kwargs given to the signer to modify the signing operation.

Returns:

The signature corresponding to the message.

Return type:

MessageSignature (optional)

sign_raw_msghash(msghash: HexBytes) MessageSignature | None

Sign a raw message hash.

Parameters:

msghash (HexBytes) – The message hash to sign. Plugins may or may not support this operation. Default implementation is to raise NotImplementedError.

Returns:

The signature corresponding to the message.

Return type:

MessageSignature (optional)

abstract sign_transaction(txn: TransactionAPI, **signer_options) TransactionAPI | None

Sign a transaction.

Parameters:
  • txn (TransactionAPI) – The transaction to sign.

  • **signer_options – Additional kwargs given to the signer to modify the signing operation.

Returns:

A signed transaction.

The TransactionAPI returned by this method may not correspond to txn given as input, however returning a properly-formatted transaction here is meant to be executed. Returns None if the account does not have a transaction it wishes to execute.

Return type:

TransactionAPI (optional)

transfer(account: str | ChecksumAddress | BaseAddress, value: str | int | None = None, data: bytes | str | None = None, private: bool = False, **kwargs) ReceiptAPI

Send funds to an account.

Raises:

APINotImplementedError – When setting private=True and using a provider that does not support private transactions.

Parameters:
  • account (Union[str, AddressType, BaseAddress]) – The receiver of the funds.

  • value (Optional[Union[str, int]]) – The amount to send.

  • data (Optional[Union[bytes, str]]) – Extra data to include in the transaction.

  • private (bool) – True asks the provider to make the transaction private. For example, EVM providers typically use the RPC eth_sendPrivateTransaction to achieve this. Local providers may ignore this value.

Returns:

ReceiptAPI

class ape.api.accounts.AccountContainerAPI(*, name: str, account_type: type[ape.api.accounts.AccountAPI])

Bases: 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) AccountAPI

Get an account by address.

Parameters:

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

Raises:

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

Returns:

AccountAPI

abstract __len__() int

Number of accounts.

account_type: type[ape.api.accounts.AccountAPI]

The type of account in this container. See AccountAPI.

abstract property accounts: Iterator[AccountAPI]

All accounts.

Returns:

Iterator[AccountAPI]

abstract property aliases: Iterator[str]

All available aliases.

Returns:

Iterator[str]

append(account: AccountAPI)

Add an account to the container.

Raises:

AccountsError – When the account is already in the container.

Parameters:

account (AccountAPI) – The account to add.

property data_folder: Path

The path to the account data files. Defaults to $HOME/.ape/<plugin_name> unless overriden.

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

name: str

The name of the account container. For example, the ape-ledger plugin uses "ledger" as its name.

remove(account: 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: AccountAPI

An account to use that does not require signing.

property address: ChecksumAddress

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

call(txn: TransactionAPI, send_everything: bool = False, private: bool = False, **kwargs) 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.

  • APINotImplementedError – When setting private=True and using a provider that does not support private transactions.

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

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

  • private (bool) – True will use the send_private_transaction() method.

  • **signer_options – Additional kwargs given to the signer to modify the signing operation.

Returns:

ReceiptAPI

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

sign_message(msg: Any, **signer_options) MessageSignature | None

Sign a message.

Parameters:
  • msg (Any) – The message to sign. Account plugins can handle various types of messages. For example, KeyfileAccount can handle SignableMessage, str, int, and bytes. See these docs # noqa: E501 for more type information on the SignableMessage type.

  • **signer_options – Additional kwargs given to the signer to modify the signing operation.

Returns:

The signature corresponding to the message.

Return type:

MessageSignature (optional)

sign_transaction(txn: TransactionAPI, **signer_options) TransactionAPI | None

Sign a transaction.

Parameters:
  • txn (TransactionAPI) – The transaction to sign.

  • **signer_options – Additional kwargs given to the signer to modify the signing operation.

Returns:

A signed transaction.

The TransactionAPI returned by this method may not correspond to txn given as input, however returning a properly-formatted transaction here is meant to be executed. Returns None if the account does not have a transaction it wishes to execute.

Return type:

TransactionAPI (optional)

class ape.api.accounts.TestAccountAPI

Bases: AccountAPI

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

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class ape.api.accounts.TestAccountContainerAPI(*, name: str, account_type: type[ape.api.accounts.AccountAPI])

Bases: AccountContainerAPI

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

property data_folder: Path

Test account containers do not touch persistant data. By default and unless overriden, this property returns the path to /dev/null and it is not used for anything.

Type:

NOTE

abstract generate_account() TestAccountAPI

Generate a new test account.

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

Address

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

Bases: 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: 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: str | bytes | HexBytes

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

property codesize: int

The number of bytes in the smart contract.

property history: AccountHistory

The list of transactions that this account has made on the current chain.

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(*, compiler_settings: dict = {})

Bases: 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: Iterable[Path], project: ProjectManager | None, settings: dict | None = None) Iterator[ContractType]

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

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

  • project (Optional[ProjectManager]) – Optionally provide the project containing the base paths and full source set. Defaults to the local project. Dependencies will change this value to their respective projects.

  • settings (Optional[dict]) – Adhoc compiler settings.

Returns:

list[ContractType]

compile_code(**kwargs)

Compile a program.

Parameters:
  • code (str) – The code to compile.

  • project (Optional[ProjectManager]) – Optionally provide the project containing the base paths and full source set. Defaults to the local project. Dependencies will change this value to their respective projects.

  • settings (Optional[Dict]) – Adhoc compiler settings.

  • **kwargs – Additional overrides for the ethpm_types.ContractType model.

Returns:

A compiled contract artifact.

Return type:

ContractType

compiler_settings: dict

Adhoc compiler settings.

enrich_error(err: ContractLogicError) ContractLogicError

Enrich a contract logic error using compiler information, such as known PC locations for compiler runtime errors.

Parameters:

err (ContractLogicError) – The exception to enrich.

Returns:

The enriched exception.

Return type:

ContractLogicError

flatten_contract(**kwargs)

Get the content of a flattened contract via its source path. Plugin implementations handle import resolution, SPDX de-duplication, and anything else needed.

Parameters:
  • path (pathlib.Path) – The source path of the contract.

  • project (Optional[ProjectManager]) – Optionally provide the project containing the base paths and full source set. Defaults to the local project. Dependencies will change this value to their respective projects.

  • **kwargs (Any) – Additional compiler-specific settings. See specific compiler plugins when applicable.

Returns:

The flattened contract content.

Return type:

ethpm_types.source.Content

get_compiler_settings(**kwargs)

Get a mapping of the settings that would be used to compile each of the sources by the compiler version number.

Parameters:
  • contract_filepaths (Iterable[pathlib.Path]) – The list of paths.

  • project (Optional[ProjectManager]) – Optionally provide the project containing the base paths and full source set. Defaults to the local project. Dependencies will change this value to their respective projects.

  • **overrides – Settings overrides.

Returns:

A dict of compiler settings by compiler version.

Return type:

dict[Version, dict]

get_config(project: ProjectManager | None = None) PluginConfig

The combination of settings from ape-config.yaml and .compiler_settings.

Parameters:

project (Optional[ProjectManager]) – Optionally provide the project containing the base paths and full source set. Defaults to the local project. Dependencies will change this value to their respective projects.

Returns:

PluginConfig

get_imports(**kwargs)

Returns a list of imports as source_ids for each contract’s source_id in a given compiler.

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

  • project (Optional[ProjectManager]) – Optionally provide the project containing the base paths and full source set. Defaults to the local project. Dependencies will change this value to their respective projects.

Returns:

A dictionary like {source_id: [import_source_id, ...], ...}

Return type:

dict[str, list[str]]

get_version_map(**kwargs)

Get a map of versions to source paths.

Parameters:
  • contract_filepaths (Iterable[Path]) – Input source paths. Defaults to all source paths per compiler.

  • project (Optional[ProjectManager]) – Optionally provide the project containing the base paths and full source set. Defaults to the local project. Dependencies will change this value to their respective projects.

Returns:

dict[Version, set[Path]]

get_versions(**kwargs)

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

Parameters:

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

Returns:

A set of available compiler versions.

Return type:

set[str]

init_coverage_profile(**kwargs)

Initialize an empty report for the given source ID. Modifies the given source coverage in-place.

Parameters:
  • source_coverage (SourceCoverage) – The source to generate an empty coverage profile for.

  • contract_source (ethpm_types.source.ContractSource) – The contract with source content.

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

abstract property name: str

The name of the compiler.

property supports_source_tracing: bool

Returns True if this compiler is able to provider a source traceback for a given trace.

trace_source(**kwargs)

Get a source-traceback for the given contract type. The source traceback object contains all the control paths taken in the transaction. When available, source-code location information is accessible from the object.

Parameters:
  • contract_source (ContractSource) – A contract type with a local-source that was compiled by this compiler.

  • trace (TraceAPI]) – The resulting trace from executing a function defined in the given contract type.

  • calldata (HexBytes) – Calldata passed to the top-level call.

Returns:

SourceTraceback

Config

class ape.api.config.ApeConfig(*args, contracts_folder: str | None = None, default_ecosystem: str = 'ethereum', dependencies: list[dict] = [], deployments: dict[str, dict[str, list[ape.api.config.DeploymentConfig]]] = {}, interfaces_folder: str = 'interfaces', meta: PackageMeta = PackageMeta(authors=None, license=None, description=None, keywords=None, links=None), name: str = '', version: str = '', **kwargs)

Bases: ExtraAttributesMixin, BaseSettings, ManagerAccessMixin

The top-level config.

contracts_folder: str | None

The path to the folder containing the contract source files. NOTE: Non-absolute paths are relative to the project-root. If not set, defaults to deducing the contracts folder. When deducing, Ape first tries "contracts", but if that folder does not exist, Ape tries to find a folder with contracts.

default_ecosystem: str

The default ecosystem to use in Ape.

dependencies: list[dict]

Project dependency declarations. Note: The actual dependency classes are decoded later.

deployment_data: dict[str, dict[str, list[ape.api.config.DeploymentConfig]]]

Data for deployed contracts from the project.

interfaces_folder: str

The path to the project’s interfaces.

meta: PackageMeta

Metadata about the active project as per EIP https://eips.ethereum.org/EIPS/eip-2678#the-package-meta-object

model_config: ClassVar[SettingsConfigDict] = {'arbitrary_types_allowed': True, 'case_sensitive': False, 'cli_avoid_json': False, 'cli_enforce_required': False, 'cli_hide_none_type': False, 'cli_parse_args': None, 'cli_parse_none_str': None, 'cli_prefix': '', 'cli_prog_name': None, 'cli_settings_source': None, 'cli_use_class_docs_for_groups': False, 'env_file': None, 'env_file_encoding': None, 'env_ignore_empty': False, 'env_nested_delimiter': None, 'env_parse_enums': None, 'env_parse_none_str': None, 'env_prefix': '', 'extra': 'allow', 'json_file': None, 'json_file_encoding': None, 'protected_namespaces': ('model_', 'settings_'), 'secrets_dir': None, 'toml_file': None, 'validate_default': True, 'yaml_file': None, 'yaml_file_encoding': None}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

model_dump(*args, **kwargs)

Usage docs: https://docs.pydantic.dev/2.8/concepts/serialization/#modelmodel_dump

Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.

Parameters:
  • mode – The mode in which to_python should run. If mode is ‘json’, the output will only contain JSON serializable types. If mode is ‘python’, the output may contain non-JSON-serializable Python objects.

  • include – A set of fields to include in the output.

  • exclude – A set of fields to exclude from the output.

  • context – Additional context to pass to the serializer.

  • by_alias – Whether to use the field’s alias in the dictionary key if defined.

  • exclude_unset – Whether to exclude fields that have not been explicitly set.

  • exclude_defaults – Whether to exclude fields that are set to their default value.

  • exclude_none – Whether to exclude fields that have a value of None.

  • round_trip – If True, dumped values should be valid as input for non-idempotent types such as Json[T].

  • warnings – How to handle serialization errors. False/”none” ignores them, True/”warn” logs errors, “error” raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].

  • serialize_as_any – Whether to serialize fields with duck-typing serialization behavior.

Returns:

A dictionary representation of the model.

name: str

The name of the project.

version: str

The version of the project.

write_to_disk(destination: Path, replace: bool = False)

Write this config to a file.

Parameters:
  • destination (Path) – The path to write to.

  • replace (bool) – Set to True to overwrite the file if it exists.

class ape.api.config.ConfigEnum(value)

Bases: str, 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.

Usage example:

class MyEnum(ConfigEnum):
    FOO = "FOO"
    BAR = "BAR"

class MyConfig(PluginConfig):
    my_enum: MyEnum

model = MyConfig(my_enum="FOO")
class ape.api.config.DeploymentConfig(_case_sensitive: bool | None = None, _env_prefix: str | None = None, _env_file: DotenvType | None = PosixPath('.'), _env_file_encoding: str | None = None, _env_ignore_empty: bool | None = None, _env_nested_delimiter: str | None = None, _env_parse_none_str: str | None = None, _env_parse_enums: bool | None = None, _cli_prog_name: str | None = None, _cli_parse_args: bool | list[str] | tuple[str, ...] | None = None, _cli_settings_source: CliSettingsSource[Any] | None = None, _cli_parse_none_str: str | None = None, _cli_hide_none_type: bool | None = None, _cli_avoid_json: bool | None = None, _cli_enforce_required: bool | None = None, _cli_use_class_docs_for_groups: bool | None = None, _cli_prefix: str | None = None, _secrets_dir: str | Path | None = None, *, address: ChecksumAddress, contract_type: str, **values: Any)

Bases: PluginConfig

Add ‘deployments’ to your config.

address: ChecksumAddress

The address of the deployment.

contract_type: str

The contract type name reference (must be a contract in the project).

model_config: ClassVar[SettingsConfigDict] = {'arbitrary_types_allowed': True, 'case_sensitive': False, 'cli_avoid_json': False, 'cli_enforce_required': False, 'cli_hide_none_type': False, 'cli_parse_args': None, 'cli_parse_none_str': None, 'cli_prefix': '', 'cli_prog_name': None, 'cli_settings_source': None, 'cli_use_class_docs_for_groups': False, 'env_file': None, 'env_file_encoding': None, 'env_ignore_empty': False, 'env_nested_delimiter': None, 'env_parse_enums': None, 'env_parse_none_str': None, 'env_prefix': '', 'extra': 'allow', 'json_file': None, 'json_file_encoding': None, 'protected_namespaces': ('model_', 'settings_'), 'secrets_dir': None, 'toml_file': None, 'validate_default': True, 'yaml_file': None, 'yaml_file_encoding': None}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class ape.api.config.GenericConfig

Bases: ConfigDict

The default class used when no specialized class is used.

class ape.api.config.PluginConfig(_case_sensitive: bool | None = None, _env_prefix: str | None = None, _env_file: DotenvType | None = PosixPath('.'), _env_file_encoding: str | None = None, _env_ignore_empty: bool | None = None, _env_nested_delimiter: str | None = None, _env_parse_none_str: str | None = None, _env_parse_enums: bool | None = None, _cli_prog_name: str | None = None, _cli_parse_args: bool | list[str] | tuple[str, ...] | None = None, _cli_settings_source: CliSettingsSource[Any] | None = None, _cli_parse_none_str: str | None = None, _cli_hide_none_type: bool | None = None, _cli_avoid_json: bool | None = None, _cli_enforce_required: bool | None = None, _cli_use_class_docs_for_groups: bool | None = None, _cli_prefix: str | None = None, _secrets_dir: str | Path | None = None, **values: Any)

Bases: BaseSettings

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

model_config: ClassVar[SettingsConfigDict] = {'arbitrary_types_allowed': True, 'case_sensitive': False, 'cli_avoid_json': False, 'cli_enforce_required': False, 'cli_hide_none_type': False, 'cli_parse_args': None, 'cli_parse_none_str': None, 'cli_prefix': '', 'cli_prog_name': None, 'cli_settings_source': None, 'cli_use_class_docs_for_groups': False, 'env_file': None, 'env_file_encoding': None, 'env_ignore_empty': False, 'env_nested_delimiter': None, 'env_parse_enums': None, 'env_parse_none_str': None, 'env_prefix': '', 'extra': 'allow', 'json_file': None, 'json_file_encoding': None, 'protected_namespaces': ('model_', 'settings_'), 'secrets_dir': None, 'toml_file': None, 'validate_default': True, 'yaml_file': None, 'yaml_file_encoding': None}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

Convert

class ape.api.convert.ConverterAPI

Bases: BaseInterfaceModel, Generic[ConvertedType]

abstract convert(value: Any) 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 (Any) – The value to check.

Returns:

True when the given value can be converted.

Return type:

bool

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

Explorers

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

Bases: BaseInterfaceModel

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

abstract get_address_url(address: ChecksumAddress) str

Get an address URL, such as for a transaction.

Parameters:

address (AddressType) – The address.

Returns:

The URL.

Return type:

str

abstract get_contract_type(address: ChecksumAddress) ContractType | None

Get the contract type for a given address if it has been published to this 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:

The URL.

Return type:

str

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

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, request_header: dict, fee_token_symbol: str, fee_token_decimals: int = 18)

Bases: ExtraAttributesMixin, BaseInterfaceModel

A set of related networks, such as Ethereum.

add_network(network_name: str, network: NetworkAPI)

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

Raises:

NetworkError – When the network already exists.

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

  • network (NetworkAPI) – The network to add.

property 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

property custom_network: NetworkAPI

A NetworkAPI for custom networks where the network is either not known, unspecified, or does not have an Ape plugin.

property data_folder: Path

The path to the ecosystem’s data folder, e.g. $HOME/.ape/{self.name} unless overridden.

abstract classmethod decode_address(raw_address: str | int | HashStr20 | HashBytes20) ChecksumAddress

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

Parameters:

raw_address (RawAddress) – 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_calldata(abi: ConstructorABI | MethodABI, calldata: bytes) dict

Decode method calldata.

Parameters:
  • abi (Union[ConstructorABI, MethodABI]) – The method called.

  • calldata (bytes) – The raw calldata bytes.

Returns:

A mapping of input names to decoded values. If an input is anonymous, it should use the stringified index of the input as the key.

Return type:

Dict

decode_custom_error(**kwargs)

Decode a custom error class from an ABI defined in a contract.

Parameters:
  • data (HexBytes) – The error data containing the selector and input data.

  • address (AddressType) – The address of the contract containing the error.

  • **kwargs – Additional init kwargs for the custom error class.

Returns:

If it able to decode one, else None.

Return type:

Optional[CustomError]

abstract decode_logs(logs: Sequence[dict], *events: EventABI) Iterator[ContractLog]

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

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

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

Returns:

Iterator[ContractLog]

decode_primitive_value(**kwargs)

Decode a primitive value-type given its ABI type as a str and the value itself. This method is a hook for converting addresses, HexBytes, or other primitive data-types into friendlier Python equivalents.

Parameters:
  • value (Any) – The value to decode.

  • output_type (Union[str, tuple, list]) – The value type.

Returns:

Union[str, HexBytes, tuple]

abstract decode_receipt(data: dict) ReceiptAPI

Convert data to ReceiptAPI.

Parameters:

data (Dict) – A dictionary of Receipt properties.

Returns:

ReceiptAPI

abstract decode_returndata(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_name: str

The name of the default network in this ecosystem.

Returns:

str

abstract classmethod encode_address(address: ChecksumAddress) str | int | HashStr20 | HashBytes20

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

Parameters:

address (AddressType) – The address to convert.

Returns:

RawAddress

abstract encode_calldata(abi: ConstructorABI | MethodABI, *args: Any) HexBytes

Encode method calldata.

Parameters:
  • abi (Union[ConstructorABI, MethodABI]) – The ABI of the method called.

  • *args (Any) – The arguments given to the method.

Returns:

The encoded calldata of the arguments to the given method.

Return type:

HexBytes

encode_contract_blueprint(**kwargs)

Encode a unique type of transaction that allows contracts to be created from other contracts, such as EIP-5202 or Starknet’s Declare transaction type.

Parameters:
  • contract_type (ContractType) – The type of contract to create a blueprint for. This is the type of contract that will get created by factory contracts.

  • *args (Any) – Calldata, if applicable.

  • **kwargs (Any) – Transaction specifications, such as value.

Returns:

TransactionAPI

abstract encode_deployment(deployment_bytecode: HexBytes, 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 (Any) – Constructor arguments.

  • **kwargs (Any) – Transaction arguments.

Returns:

~ape.api.transactions.TransactionAPI

Return type:

class

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

Encode a transaction object from a contract function’s ABI and call arguments. Additionally, update the transaction arguments with the overrides in kwargs.

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

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

  • *args (Any) – Function arguments.

  • **kwargs (Any) – Transaction arguments.

Returns:

~ape.api.transactions.TransactionAPI

Return type:

class

enrich_trace(trace: TraceAPI, **kwargs) TraceAPI

Enhance the data in the call tree using information about the ecosystem.

Parameters:
  • trace (TraceAPI) – The trace to enrich.

  • **kwargs – Additional kwargs to control enrichment, defined at the plugin level.

Returns:

TraceAPI

fee_token_decimals: int

The number of the decimals the fee token has.

fee_token_symbol: str

The token symbol for the currency that pays for fees, such as ETH.

get_method_selector(abi: MethodABI) HexBytes

Get a contract method selector, typically via hashing such as keccak. Defaults to using keccak but can be overridden in different ecosystems.

Override example:

from ape.api import EcosystemAPI
from eth_pydantic_types import HexBytes

class MyEcosystem(EcosystemAPI):
    def get_method_selector(self, abi: MethodABI) -> HexBytes:
        return HexBytes(abi.selector.encode())  # Simple bytes selector
Parameters:

abi (MethodABI) – The ABI object to use when calculating the selector bytes.

Returns:

The hashed method selector value.

Return type:

HexBytes

get_network(network_name: str) 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, provider_filter: Collection[str] | None = None) 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.

  • provider_filter (Optional[Collection[str]]) – Optionally filter the providers by name.

Returns:

A dictionary containing the providers in a network.

Return type:

dict

get_proxy_info(address: ChecksumAddress) ProxyInfoAPI | None

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

Parameters:

address (AddressType) – The address of the contract.

Returns:

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

Return type:

Optional[ProxyInfoAPI]

get_python_types(**kwargs)

Get the Python types for a given ABI type.

Parameters:

abi_type (ABIType) – The ABI type to get the Python types for.

Returns:

The Python types for the given ABI type.

Return type:

Union[Type, Sequence]

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

name: str

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

property networks: dict[str, '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() bytes

Serialize a transaction to bytes.

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.ForkedNetworkAPI(*, name: str, ecosystem: EcosystemAPI, request_header: dict)

Bases: NetworkAPI

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

property upstream_chain_id: int

The chain Id of the upstream network. For example, when on mainnet-fork, this should always return the chain ID for mainnet. Some providers may use a different chain ID for forked networks while some do not. This property should ALWAYS be that of the forked network, regardless.

property upstream_network: NetworkAPI

The network being forked.

property upstream_provider: UpstreamProvider

The provider used when requesting data before the local fork. Set this in your config under the network settings. When not set, will attempt to use the default provider, if one exists.

use_upstream_provider() ProviderContextManager

Connect to the upstream provider.

Returns:

ProviderContextManager

class ape.api.networks.NetworkAPI(*, name: str, ecosystem: EcosystemAPI, request_header: dict)

Bases: BaseInterfaceModel

A wrapper around a provider for a specific ecosystem.

property auto_gas_multiplier: float

The value to multiply estimated gas by for tx-insurance.

property base_fee_multiplier: float

A multiplier to apply to a transaction base fee.

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 data_folder: Path

The path to the network’s data folder, e.g. $HOME/.ape/{self.ecosystem_name}/{self.name} unless overridden.

property default_provider_name: str | None

The name of the default provider or None.

Returns:

Optional[str]

ecosystem: EcosystemAPI

The ecosystem of the network.

property ecosystem_config: PluginConfig

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

property explorer: ExplorerAPI | None

The block-explorer for the given network.

Returns:

ape.api.explorers.ExplorerAPI, optional

get_provider(provider_name: str | None = None, provider_settings: dict | None = 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

property is_adhoc: bool

Is a custom network from CLI only, e.g. was not configured in any CLI value and is mostly an “unknown” network.

property is_dev: bool

True when using a local network, including forks.

property is_fork: bool

True when using a forked network.

property is_local: bool

True when using the local network.

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

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 Node.

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: dict | None = None, disconnect_after: bool = False) 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.

  • disconnect_after (bool) – Set to True to force a disconnect after ending the context. This defaults to False so you can re-connect to the same network, such as in a multi-chain testing scenario.

Returns:

ProviderContextManager

use_provider(provider: str | ProviderAPI, provider_settings: dict | None = None, disconnect_after: bool = False, disconnect_on_exit: bool = True) 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 (Union[str, ProviderAPI]) – The provider instance or the name of the provider to use.

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

  • disconnect_after (bool) – Set to True to force a disconnect after ending the context. This defaults to False so you can re-connect to the same network, such as in a multi-chain testing scenario.

  • disconnect_on_exit (bool) – Whether to disconnect on the exit of the python session. Defaults to True.

Returns:

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, disconnect_after: bool = False, disconnect_on_exit: bool = True)

Bases: 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, unless in a multi-chain context, in which case it disconnects all providers at the very end of the Python session.

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"):
    ...

# Or, using choice-strings:

with networks.parse_network_choice("ethereum:local:test"):
    ...
property empty: bool

True when there are no providers in the context.

class ape.api.networks.ProxyInfoAPI(*, target: ChecksumAddress)

Bases: BaseModel

Information about a proxy contract.

model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

target: ChecksumAddress

The address of the implementation contract.

ape.api.networks.create_network_type(chain_id: int, network_id: int, is_fork: bool = False) type[ape.api.networks.NetworkAPI]

Easily create a NetworkAPI subclass.

Projects

class ape.api.projects.ApeProject(*, path: Path, CONFIG_FILE_NAME: str = 'ape-config', EXTENSIONS: tuple[str, ...] = ('.yaml', '.yml', '.json'))

Bases: ProjectAPI

The default ProjectAPI implementation.

extract_config(**overrides) ApeConfig

Extra configuration from the project so that Ape understands the dependencies and how to compile everything.

Parameters:

**overrides – Config overrides.

Returns:

ApeConfig

property is_valid: bool

Return True when detecting a project of this type.

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class ape.api.projects.DependencyAPI(*, name: str, config_override: dict = {})

Bases: BaseInterfaceModel

An API for obtaining sources.

config_override: dict

Set different config than what Ape can deduce.

abstract fetch(destination: Path)

Fetch the dependency. E.g. for GitHub dependency, download the files to the destination.

Parameters:

destination (Path) – The destination for the dependency files.

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

name: str

The package-name of the dependency.

abstract property package_id: str

The full name of the package, used for storage. Example: OpenZeppelin/openzepplin-contracts.

abstract property uri: str

The URI for the package.

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: Path)

Bases: BaseInterfaceModel

An API for recognizing different project types, such as brownie projects versus ape projects. NOTE: This assumed the project sources are available and unpacked. Use DependencyAPI to fetch different projects. The main task of the project API is to generate a configuration needed to compile in Ape.

abstract extract_config(**overrides) ApeConfig

Extra configuration from the project so that Ape understands the dependencies and how to compile everything.

Parameters:

**overrides – Config overrides.

Returns:

ApeConfig

abstract property is_valid: bool

Return True when detecting a project of this type.

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

path: Path

The location of the project.

Providers

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

Bases: BaseInterfaceModel

An abstract class representing a block and its attributes.

property datetime: datetime

The block timestamp as a datetime object.

hash: Any | None

The block number identifier.

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

num_transactions: int

The block hash identifier.

number: int | None

The preceeding block’s hash.

parent_hash: Any

The timestamp the block was produced. NOTE: The pending block uses the current timestamp.

property size: int

The size of the block in gas. Most of the time, this field is passed to the model at validation time, but occassionally it is missing (like in eth_subscribe:newHeads), in which case it gets calculated if and only if the user requests it (or during serialization of this model to disk).

property transactions: list[ape.api.transactions.TransactionAPI]

All transactions in a block.

classmethod validate_size(values, handler)

A validator for handling non-computed size. Saves it to a private member on this class and gets returned in computed field “size”.

class ape.api.providers.ProviderAPI(*, name: str, network: NetworkAPI, provider_settings: dict = {}, request_header: dict, block_page_size: int = 100, concurrency: int = 4)

Bases: 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.

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: PluginConfig

The provider’s configuration.

abstract connect()

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

property connection_id: str | None

A connection ID to uniquely identify and manage multiple connections to providers, especially when working with multiple providers of the same type, like multiple Geth –dev nodes.

property connection_str: str

The str representing how to connect to the node, such as an HTTP URL or an IPC path.

property data_folder: Path

The path to the provider’s data, e.g. $HOME/.api/{self.name} unless overridden.

abstract disconnect()

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

abstract estimate_gas_cost(txn: TransactionAPI, block_id: int | HexStr | HexBytes | Literal['earliest', 'latest', 'pending'] | None = None) int

Estimate the cost of gas for a transaction.

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

  • block_id (Optional[BlockID]) – The block ID to use when estimating the transaction. Useful for checking a past estimation cost of a transaction.

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

abstract property gas_price: int

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

abstract get_balance(address: ChecksumAddress, block_id: int | HexStr | HexBytes | Literal['earliest', 'latest', 'pending'] | None = None) int

Get the balance of an account.

Parameters:
  • address (AddressType) – The address of the account.

  • block_id (BlockID) – Optionally specify a block ID. Defaults to using the latest block.

Returns:

The account balance.

Return type:

int

abstract get_block(block_id: int | HexStr | HexBytes | Literal['earliest', 'latest', 'pending']) 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, block_id: int | HexStr | HexBytes | Literal['earliest', 'latest', 'pending'] | None = None) str | bytes | HexBytes

Get the bytes a contract.

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

  • block_id (Optional[BlockID]) – The block ID for checking a previous account nonce.

Returns:

The contract bytecode.

Return type:

ContractCode

abstract get_contract_logs(log_filter: LogFilter) Iterator[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, block_id: int | HexStr | HexBytes | Literal['earliest', 'latest', 'pending'] | None = None) int

Get the number of times an account has transacted.

Parameters:
  • address (AddressType) – The address of the account.

  • block_id (Optional[BlockID]) – The block ID for checking a previous account nonce.

Returns:

int

abstract get_receipt(txn_hash: str, **kwargs) ReceiptAPI

Get the information about a transaction from a transaction hash.

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

  • kwargs – Any other kwargs that other providers might allow when fetching a receipt.

Returns:

The receipt of the transaction with the given hash.

Return type:

ReceiptAPI

get_storage(**kwargs)

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

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

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

  • block_id (Optional[BlockID]) – The block ID for checking a previous storage value.

Returns:

The value of the storage slot.

Return type:

HexBytes

get_transaction_trace(**kwargs)

Provide a detailed description of opcodes.

Parameters:

transaction_hash (Union[HexBytes, str]) – The hash of a transaction to trace.

Returns:

A transaction trace.

Return type:

TraceAPI

get_transactions_by_account_nonce(**kwargs)

Get account history for the given account.

Parameters:
  • account (AddressType) – The address of the account.

  • start_nonce (int) – The nonce of the account to start the search with.

  • stop_nonce (int) – The nonce of the account to stop the search with.

Returns:

Iterator[ReceiptAPI]

abstract get_transactions_by_block(block_id: int | HexStr | HexBytes | Literal['earliest', 'latest', 'pending']) Iterator[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, **kwargs) VirtualMachineError

Get a virtual machine error from an error returned from your RPC.

Parameters:

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

Returns:

An error representing what

went wrong in the call.

Return type:

VirtualMachineError

property http_uri: str | None

Return the raw HTTP/HTTPS URI to connect to this provider, if supported.

abstract property is_connected: bool

True if currently connected to the provider. False otherwise.

abstract make_request(rpc: str, parameters: Iterable | None = None) Any

Make a raw RPC request to the provider. Advanced featues such as tracing may utilize this to by-pass unnecessary class-serializations.

abstract property max_gas: int

The max gas limit value you can use.

mine(**kwargs)

Defined to make the ProviderAPI interchangeable with a TestProviderAPI, as in ape.managers.chain.ChainManager.

Raises:

APINotImplementedError – Unless overriden.

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

name: str

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

network: NetworkAPI

A reference to the network this provider provides.

property network_choice: str

The connected network choice string.

poll_blocks(**kwargs)

Poll new blocks.

NOTE: When a chain reorganization occurs, this method logs an error and yields the missed blocks, even if they were previously yielded with different block numbers.

NOTE: This is a daemon method; it does not terminate unless an exception occurs or a stop_block is given.

Parameters:
  • stop_block (Optional[int]) – Optionally set a future block number to stop at. Defaults to never-ending.

  • required_confirmations (Optional[int]) – The amount of confirmations to wait before yielding the block. The more confirmations, the less likely a reorg will occur. Defaults to the network’s configured required confirmations.

  • new_block_timeout (Optional[float]) – The amount of time to wait for a new block before timing out. Defaults to 10 seconds for local networks or 50 * block_time for live networks.

Returns:

Iterator[BlockAPI]

poll_logs(**kwargs)

Poll new blocks. Optionally set a start block to include historical blocks.

NOTE: This is a daemon method; it does not terminate unless an exception occurs.

Usage example:

for new_log in contract.MyEvent.poll_logs():
    print(f"New event log found: block_number={new_log.block_number}")
Parameters:
  • stop_block (Optional[int]) – Optionally set a future block number to stop at. Defaults to never-ending.

  • address (Optional[str]) – The address of the contract to filter logs by. Defaults to all addresses.

  • topics (Optional[list[Union[str, list[str]]]]) – The topics to filter logs by. Defaults to all topics.

  • required_confirmations (Optional[int]) – The amount of confirmations to wait before yielding the block. The more confirmations, the less likely a reorg will occur. Defaults to the network’s configured required confirmations.

  • new_block_timeout (Optional[int]) – The amount of time to wait for a new block before quitting. Defaults to 10 seconds for local networks or 50 * block_time for live networks.

  • events (Optional[list[EventABI]]) – An optional list of events to listen on.

Returns:

Iterator[ContractLog]

prepare_transaction(txn: TransactionAPI) 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.

restore(**kwargs)

Defined to make the ProviderAPI interchangeable with a TestProviderAPI, as in ape.managers.chain.ChainManager.

Raises:

APINotImplementedError – Unless overriden.

abstract send_call(txn: TransactionAPI, block_id: int | HexStr | HexBytes | Literal['earliest', 'latest', 'pending'] | None = None, state: dict | None = None, **kwargs) HexBytes

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

Parameters:
  • txnTransactionAPI

  • block_id (Optional[BlockID]) – The block ID to use to send a call at a historical point of a contract. Useful for checking a past estimation cost of a transaction.

  • state (Optional[dict]) – Modify the state of the blockchain prior to sending the call, for testing purposes.

  • **kwargs – Provider-specific extra kwargs.

Returns:

The result of the transaction call.

Return type:

str

send_private_transaction(txn: TransactionAPI, **kwargs) ReceiptAPI

Send a transaction through a private mempool (if supported by the Provider).

Raises:

APINotImplementedError – If using a non-local network and not implemented by the provider.

Parameters:
  • txn (TransactionAPI) – The transaction to privately publish.

  • **kwargs – Additional kwargs to be optionally handled by the provider.

Returns:

ReceiptAPI

abstract send_transaction(txn: TransactionAPI) ReceiptAPI

Send a transaction to the network.

Parameters:

txn (TransactionAPI) – The transaction to send.

Returns:

ReceiptAPI

set_balance(**kwargs)

Change the balance of an account.

Parameters:
  • address (AddressType) – An address on the network.

  • amount (int) – The balance to set in the address.

set_code(**kwargs)

Change the code of a smart contract, for development purposes. Test providers implement this method when they support it.

Parameters:
  • address (AddressType) – An address on the network.

  • code (ContractCode) – The new bytecode.

set_storage(**kwargs)

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

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

  • slot (int) – Storage slot to write the value to.

  • value – (HexBytes): The value to overwrite the raw storage slot with.

set_timestamp(**kwargs)

Defined to make the ProviderAPI interchangeable with a TestProviderAPI, as in ape.managers.chain.ChainManager.

Raises:

APINotImplementedError – Unless overriden.

property settings: PluginConfig

The combination of settings from ape-config.yaml and .provider_settings.

snapshot(**kwargs)

Defined to make the ProviderAPI interchangeable with a TestProviderAPI, as in ape.managers.chain.ChainManager.

Raises:

APINotImplementedError – Unless overriden.

stream_request(**kwargs)

Stream a request, great for large requests like events or traces.

Parameters:
  • method (str) – The RPC method to call.

  • params (Iterable) – Parameters for the method.s

  • iter_path (str) – The response dict-path to the items.

Returns:

An iterator of items.

property supports_tracing: bool

True when the provider can provide transaction traces.

unlock_account(**kwargs)

Ask the provider to allow an address to submit transactions without validating signatures. This feature is intended to be subclassed by a TestProviderAPI so that during a fork-mode test, a transaction can be submitted by an arbitrary account or contract without a private key.

Raises:

NotImplementedError – When this provider does not support unlocking an account.

Parameters:

address (AddressType) – The address to unlock.

Returns:

True if successfully unlocked account and False otherwise.

Return type:

bool

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.

property ws_uri: str | None

Return the raw WS/WSS URI to connect to this provider, if supported.

class ape.api.providers.SubprocessProvider(*, name: str, network: NetworkAPI, provider_settings: dict = {}, request_header: dict, block_page_size: int = 100, concurrency: int = 4, PROCESS_WAIT_TIMEOUT: int = 15, process: Popen | None = None, is_stopping: bool = False, stdout_queue: JoinableQueue | None = None, stderr_queue: JoinableQueue | None = None)

Bases: 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.

property connection_id: str | None

A connection ID to uniquely identify and manage multiple connections to providers, especially when working with multiple providers of the same type, like multiple Geth –dev nodes.

disconnect()

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

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

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: NetworkAPI, provider_settings: dict = {}, request_header: dict, block_page_size: int = 100, concurrency: int = 4)

Bases: ProviderAPI

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

abstract property auto_mine: bool

Whether automine is enabled.

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.

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

abstract restore(snapshot_id: 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() 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: NetworkAPI, provider_settings: dict = {}, request_header: dict, block_page_size: int = 100, concurrency: int = 4)

Bases: ProviderAPI

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

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

Transactions

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

Bases: ExtraAttributesMixin, 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() ReceiptAPI

Wait for a transaction to be considered confirmed.

Returns:

The receipt that is now confirmed.

Return type:

ReceiptAPI

property debug_logs_lines: list[str]

Return any debug log data outputted by the transaction as strings suitable for printing

property debug_logs_typed: list[tuple[Any]]

Return any debug log data outputted by the transaction.

abstract decode_logs(abi: list[typing.Union[ethpm_types.abi.EventABI, ForwardRef('ContractEvent')]] | ~ethpm_types.abi.EventABI | ContractEvent | None = None) ContractLogContainer

Decode the logs on the receipt.

Parameters:

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

Returns:

list[ContractLog]

property events: ContractLogContainer

All the events that were emitted from this call.

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: MethodABI | None

The method ABI of the method called to produce this receipt.

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

raise_for_status() NoReturn | None

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.

show_debug_logs()

Output debug logs to logging system

show_events(**kwargs)

Show the events from the receipt.

show_gas_report(**kwargs)

Display a gas report for the calls made in this transaction.

show_source_traceback(**kwargs)

Show a receipt traceback mapping to lines in the source code. Only works when the contract type and source code are both available, like in local projects.

show_trace(**kwargs)

Display the complete sequence of contracts and methods called during the transaction.

Parameters:
  • verbose (bool) – Set to True to include more information.

  • file (IO[str]) – The file to send output to. Defaults to stdout.

property source_traceback

A Pythonic style traceback for both failing and non-failing receipts. Requires a provider that implements :meth:~ape.api.providers.ProviderAPI.get_transaction_trace`.

abstract property total_fees_paid: int

The total amount of fees paid for the transaction.

property trace: TraceAPI

The TraceAPI of the transaction.

track_coverage()

Track this receipt’s source code coverage in the on-going session coverage report. Requires using a provider that supports transaction traces to track full coverage. Else, is limited to receipt-level tracking. This gets called when running tests with the --coverage flag.

track_gas()

Track this receipt’s gas in the on-going session gas-report. Requires using a provider that supports transaction traces to get full data. Else, is limited to receipt-level data. This gets called when running tests with the --gas flag.

class ape.api.transactions.TransactionAPI(*args, chainId: int | None = 0, to: ChecksumAddress | None = None, sender: ChecksumAddress | None = None, gas: int | None = None, nonce: int | None = None, value: int = 0, data: HexBytes = HexBytes('0x'), type: int, max_fee: int | None = None, max_priority_fee: int | None = None, required_confirmations: int | None = None, signature: TransactionSignature | None = None)

Bases: 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.

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True, 'populate_by_name': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

property receipt: ReceiptAPI | None

This transaction’s associated published receipt, if it exists.

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.

property trace: TraceAPI

The transaction trace. Only works if this transaction was published and you are using a provider that support tracing.

Raises:

APINotImplementedError – When using a provider that does not support tracing.

abstract property txn_hash: HexBytes

The calculated hash of the transaction.

Query

class ape.api.query.AccountTransactionQuery(*, columns: Sequence[str], account: ChecksumAddress, start_nonce: int = 0, stop_nonce: int)

Bases: _BaseQuery

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

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class ape.api.query.BlockQuery(*, columns: Sequence[str], start_block: int = 0, stop_block: int, step: int = 1)

Bases: _BaseBlockQuery

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

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class ape.api.query.BlockTransactionQuery(*, columns: Sequence[str], block_id: Any)

Bases: _BaseQuery

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

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class ape.api.query.ContractCreation(*, txn_hash: str, block: int, deployer: ChecksumAddress, factory: ChecksumAddress | None = None)

Bases: BaseModel, BaseInterface

Contract-creation metadata, such as the transaction and deployer. Useful for contract-verification, block_identifier= usage, and other use-cases.

To get contract-creation metadata, you need a query engine that can provide it, such as the ape-etherscan plugin or a node connected to the OTS namespace.

block: int

The block number of the deploy transaction.

deployer: ChecksumAddress

The contract deployer address.

factory: ChecksumAddress | None

The address of the factory contract, if there is one and it is known (depends on the query provider!).

classmethod from_receipt(receipt: ReceiptAPI) ContractCreation

Create a metadata class.

Parameters:

receipt (ReceiptAPI) – The receipt of the deploy transaction.

Returns:

ContractCreation

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

property receipt: ReceiptAPI

The deploy transaction ReceiptAPI.

txn_hash: str

The transaction hash of the deploy transaction.

class ape.api.query.ContractCreationQuery(*, columns: Sequence[str], contract: ChecksumAddress)

Bases: _BaseQuery

A QueryType that obtains information about contract deployment. Returns ContractCreation(txn_hash, block, deployer, factory).

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class ape.api.query.ContractEventQuery(*, columns: ~collections.abc.Sequence[str], start_block: int = 0, stop_block: int, step: int = 1, contract: list[typing.Annotated[eth_typing.evm.ChecksumAddress, <class 'ape.types.address._AddressValidator'>]] | ~eth_typing.evm.ChecksumAddress, event: ~ethpm_types.abi.EventABI, search_topics: dict[str, typing.Any] | None = None)

Bases: _BaseBlockQuery

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

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class ape.api.query.ContractMethodQuery(*, columns: Sequence[str], start_block: int = 0, stop_block: int, step: int = 1, contract: ChecksumAddress, method: MethodABI, method_args: dict[str, Any])

Bases: _BaseBlockQuery

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

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class ape.api.query.QueryAPI

Bases: BaseInterface

abstract estimate_query(query: BlockQuery | BlockTransactionQuery | AccountTransactionQuery | ContractCreationQuery | ContractEventQuery | ContractMethodQuery) int | None

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: BlockQuery | BlockTransactionQuery | AccountTransactionQuery | ContractCreationQuery | ContractEventQuery | ContractMethodQuery) Iterator

Executes the query using best performing estimate_query query engine.

Parameters:

query (QueryType) – query to execute

Returns:

Iterator

update_cache(query: BlockQuery | BlockTransactionQuery | AccountTransactionQuery | ContractCreationQuery | ContractEventQuery | ContractMethodQuery, result: Iterator[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