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]
- __hash__ = None
- 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 toFalse
.private (bool) –
True
with use thesend_private_transaction()
method.**signer_options – Additional kwargs given to the signer to modify the signing operation.
- Returns:
- check_signature(data: SignableMessage | TransactionAPI, signature: MessageSignature | None = None) 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.
- 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 toFalse
.
- Returns:
An instance of the deployed contract.
- Return type:
ContractInstance
- 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:
- abstract sign_message(msg: SignableMessage) MessageSignature | None
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: 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 (str) – The account to send funds to.
value (str) – The amount to send.
data (str) – Extra data to include in the transaction.
private (bool) –
True
asks the provider to make the transaction private. For example, EVM providers uses the RPCeth_sendPrivateTransaction
to achieve this. Local providers may ignore this value.
- Returns:
- class ape.api.accounts.AccountContainerAPI(*, data_folder: Path, account_type: Type[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
ifape
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:
IndexError – When there is no local account with the given address.
- Returns:
- __hash__ = None
- abstract __len__() int
Number of accounts.
- abstract property accounts: Iterator[AccountAPI]
Iterate over all accounts.
- Returns:
Iterator[
AccountAPI
]
- abstract property aliases: Iterator[str]
Iterate over 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.
- 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.
- __hash__ = None
- 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 toFalse
.private (bool) –
True
with use thesend_private_transaction()
method.**signer_options – Additional kwargs given to the signer to modify the signing operation.
- Returns:
- sign_message(msg: SignableMessage) MessageSignature | None
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: TransactionAPI, **kwargs) 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 useGeneratedDevAccounts
) should implement this API instead ofAccountAPI
directly. This is how they show up in theaccounts
test fixture.- __hash__ = None
- class ape.api.accounts.TestAccountContainerAPI(*, data_folder: Path, account_type: Type[AccountAPI])
Bases:
AccountContainerAPI
Test account containers for
ape test
(such containers that generate accounts usingGeneratedDevAccounts
) should implement this API instead ofAccountContainerAPI
directly. This is how they show up in theaccounts
test fixture.- __hash__ = None
- abstract generate_account() TestAccountAPI
Generate a new test account
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
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: List[Path], base_path: Path | None) List[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 toNone
. When using in a project viaape compile
, gets set to the project’scontracts/
directory.
- Returns:
List[
ContractType
]
- enrich_error(err: ContractLogicError) ContractLogicError
Enrich a contract logic error using compiler information, such known PC locations for compiler runtime errors, such as math errors.
- Parameters:
err (
ContractLogicError
) – The exception to enrich.- Returns:
The enriched exception.
- Return type:
- abstract get_versions(all_paths: List[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]
- property supports_source_tracing: bool
Returns
True
if this compiler is able to provider a source traceback for a given trace.
Config
- 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 arbitrarystr
.
- class ape.api.config.GenericConfig(_env_file: str | PathLike | List[str | PathLike] | Tuple[str | PathLike, ...] | None = '<object object>', _env_file_encoding: str | None = None, _env_nested_delimiter: str | None = None, _secrets_dir: str | PathLike | None = None, *, __root__: dict = {})
Bases:
PluginConfig
The default class used when no specialized class is used.
- __hash__ = None
- class ape.api.config.PluginConfig(_env_file: str | PathLike | List[str | PathLike] | Tuple[str | PathLike, ...] | None = '<object object>', _env_file_encoding: str | None = None, _env_nested_delimiter: str | None = None, _secrets_dir: str | PathLike | None = None)
Bases:
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
[ConvertedType
],BaseInterfaceModel
- 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 byvalue
is convertible usingape.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: 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 to get the URL for.- Returns:
str
- abstract get_contract_type(address: ChecksumAddress) ContractType | None
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: Path, request_header: dict, fee_token_symbol: str, fee_token_decimals: int = 18)
Bases:
BaseInterfaceModel
A set of related networks, such as Ethereum.
- __getattr__(network_name: str) 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:
- __getitem__(network_name: str) 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:
- __hash__ = None
- 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:
- 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: Path
The path to the
.ape
directory.
- abstract classmethod decode_address(raw_address: str | int | 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:
- abstract decode_calldata(abi: ConstructorABI | MethodABI, calldata: bytes) Dict
Decode method calldata.
- Parameters:
abi (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
- abstract decode_logs(logs: List[Dict], *events: EventABI) Iterator[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:
- 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: str
The name of the default network in this ecosystem.
- Returns:
str
- abstract classmethod encode_address(address: ChecksumAddress) str | int | 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_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
- 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 – Constructor arguments.
**kwargs – 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. 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
- enrich_calltree(call: CallTreeNode, **kwargs) CallTreeNode
Enhance the data in the call tree using information about the ecosystem.
- Parameters:
call (
CallTreeNode
) – The call tree node to enrich.kwargs – Additional kwargs to help with enrichment.
- Returns:
CallTreeNode
- 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 usingkeccak
but can be overridden in different ecosystems.Override example:
from ape.api import EcosystemAPI from ethpm_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:
- 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) ProxyInfoAPI | None
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, 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: EcosystemAPI, data_folder: Path, request_header: Dict)
Bases:
BaseInterfaceModel
A wrapper around a provider for a specific ecosystem.
- __hash__ = None
- 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 config: PluginConfig
The configuration of the network. See
ConfigManager
for more information on plugin configurations.
- data_folder: Path
The path to the
.ape
directory.
- property default_provider: str | None
The name of the default provider or
None
.- Returns:
Optional[str]
- ecosystem: EcosystemAPI
The ecosystem of the network.
- 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
. WhenNone
, returns the default provider.provider_settings (dict, optional) – Settings to apply to the provider. Defaults to
None
.
- Returns:
- name: str
The name of the network.
- 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: 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 methodape.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 toFalse
so you can re-connect to the same network, such as in a multi-chain testing scenario.
- Returns:
- use_provider(provider_name: str, provider_settings: Dict | None = None, disconnect_after: bool = False) 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 methodape.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.
disconnect_after (bool) – Set to
True
to force a disconnect after ending the context. This defaults toFalse
so you can re-connect to the same network, such as in a multi-chain testing scenario.provider_settings (dict, optional) – Settings to apply to the provider. Defaults to
None
.
- Returns:
- 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)
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 theape.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:
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[NetworkAPI]
Easily create a
NetworkAPI
subclass.
Projects
- class ape.api.projects.DependencyAPI(*, name: str, version: str | None = None, contracts_folder: str = 'contracts', exclude: List[str] = ['package.json', 'package-lock.json', '**/.build/**/*.json'], config_override: Dict = {})
Bases:
BaseInterfaceModel
A base-class for dependency sources, such as GitHub or IPFS.
- property cached_manifest: PackageManifest | None
The manifest from the
.ape/packages/<dependency-name>/<version-id>
if it exists and is valid.
- compile(use_cache: bool = True) PackageManifest
Compile the contract types in this dependency into a package manifest.
- Parameters:
use_cache (bool) – Defaults to
True
. Set toFalse
to force a re-compile.
NOTE: By default, dependency’s compile lazily.
- config_override: Dict
Extra settings to include in the dependency’s configuration.
- contracts_folder: str
The name of the dependency’s
contracts/
directory. This is whereape
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(use_cache: bool = True) PackageManifest
Create a
PackageManifest
definition, presumably by downloading and compiling the dependency.Implementations may use
self.project_manager
to call methodget_project()
to dynamically get the correctProjectAPI
. based on the project’s structure.- Parameters:
use_cache (bool) – Defaults to
True
. Set toFalse
to force a re-install.- Returns:
PackageManifest
- name: str
The name of the dependency.
- abstract property uri: AnyUrl | FileUrl
The URI to use when listing in a PackageManifest.
- version: str | None
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: Path, contracts_folder: Path, name: str | None = None, version: str | None = None, config_file_name: str = 'ape-config.yaml')
Bases:
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: PackageManifest | None
The
PackageManifest
atmanifest_cachefile
if it exists and is valid.
- contracts_folder: Path
The path to the contracts in the project.
- abstract create_manifest(file_paths: List[Path] | None = None, use_cache: bool = True) 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 bestProjectAPI
to use when compiling a project.
- property manifest_cachefile: 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: str | None
The name of this project when another project uses it as a dependency.
- path: Path
The project path.
- process_config_file(**kwargs) bool
Process the project’s config file. Returns
True
if had to create a temporaryape-config.yaml
file.
- version: str | None
The version of the project whe another project uses it as a dependency.
Providers
- class ape.api.providers.BlockAPI(*, num_transactions: int = 0, hash: Any | None = None, number: int | None = None, parentHash: Any = HexBytes('0x0000000000000000000000000000000000000000000000000000000000000000'), size: int, timestamp: int)
Bases:
BaseInterfaceModel
An abstract class representing a block and its attributes.
- class ape.api.providers.ProviderAPI(*, name: str, network: NetworkAPI, provider_settings: dict, data_folder: Path, request_header: dict, cached_chain_id: int | None = None, 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.
- cached_chain_id: int | None
Implementation providers may use this to cache and re-use chain ID.
- 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.
- data_folder: 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: 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 get_balance(address: ChecksumAddress) int
Get the balance of an account.
- Parameters:
address (
AddressType
) – The address of the account.- 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:
- abstract get_code(address: ChecksumAddress, **kwargs) str | bytes | HexBytes
Get the bytes a contract.
- Parameters:
address (
AddressType
) – The address of the contract.**kwargs – Additional, provider-specific kwargs.
- 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) 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, **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
- 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:
- 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.
- 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: NetworkAPI
A reference to the network this provider provides.
- property network_choice: str
The connected network choice string.
- 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:
- 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: 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
- 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:
- abstract send_transaction(txn: TransactionAPI) ReceiptAPI
Send a transaction to the network.
- Parameters:
txn (
TransactionAPI
) – The transaction to send.- Returns:
- 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.
- 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, data_folder: Path, request_header: dict, cached_chain_id: int | None = None, block_page_size: int = 100, concurrency: int = 4, process: Popen | None = None, is_stopping: bool = False, stdout_queue: JoinableQueue | None = None, stderr_queue: JoinableQueue | None = None, PROCESS_WAIT_TIMEOUT: int = 15)
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.
- 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: NetworkAPI, provider_settings: dict, data_folder: Path, request_header: dict, cached_chain_id: int | None = None, block_page_size: int = 100, concurrency: int = 4)
Bases:
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: 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, data_folder: Path, request_header: dict, cached_chain_id: int | None = None, block_page_size: int = 100, concurrency: int = 4)
Bases:
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(*args, name: str, network: NetworkAPI, provider_settings: dict, data_folder: Path, request_header: dict, cached_chain_id: int | None = None, block_page_size: int = 100, concurrency: int = 4)
Bases:
ProviderAPI
,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.
- estimate_gas_cost(txn: 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. Also, you can aliasblock_id
.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
- get_balance(address: ChecksumAddress) int
Get the balance of an account.
- Parameters:
address (
AddressType
) – The address of the account.- Returns:
The account balance.
- Return type:
int
- 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:
- get_code(address: ChecksumAddress, **kwargs) str | bytes | HexBytes
Get the bytes a contract.
- Parameters:
address (
AddressType
) – The address of the contract.kwargs –
block_identifier
(BlockID
): The block ID for checking a previous account nonce. Also, you can use aliasblock_id
.
- Returns:
The contract bytecode.
- Return type:
ContractCode
- 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
]
- get_nonce(address: ChecksumAddress, **kwargs) int
Get the number of times an account has transacted.
- Parameters:
address (AddressType) – The address of the account.
kwargs –
block_identifier
(BlockID
): The block ID for checking a previous account nonce. Also, you can use aliasblock_id
.
- Returns:
int
- get_receipt(txn_hash: str, required_confirmations: int = 0, timeout: int | None = None, **kwargs) 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: ChecksumAddress, slot: int, **kwargs) bytes
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.
kwargs –
block_identifier
(BlockID
): The block ID for checking previous contract storage values. Also, you can use aliasblock_id
.
- Returns:
The value of the storage slot.
- Return type:
bytes
- 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. If from a contract revert / assert statement, you will be given a special
ContractLogicError
that can be checked inape.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:
- property http_uri: str | None
Return the raw HTTP/HTTPS URI to connect to this provider, if supported.
- 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.
- 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:
- 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: TransactionAPI, **kwargs) bytes
Execute a new transaction call immediately without creating a transaction on the block chain.
- Parameters:
txn –
TransactionAPI
kwargs –
block_identifier
(BlockID
): The block ID to use to send a call at a historical point of a contract. Also, you can us aliasblock_id
. 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 toTrue
to display the call’s trace. Defaults toFalse
.show_gas_report (bool): Set to ``True
to display the call’s gas report. Defaults toFalse
.skip_trace
(bool): Set toTrue
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: TransactionAPI) ReceiptAPI
Send a transaction to the network.
- Parameters:
txn (
TransactionAPI
) – The transaction to send.- Returns:
- 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
Access to the
web3
object as if you didWeb3(HTTPProvider(uri))
.
- property ws_uri: str | None
Return the raw WS/WSS URI to connect to this provider, if supported.
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:
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
of0
in your transaction to not wait for confirmations.Get a receipt by making transactions in
ape
, such as interacting with aape.contracts.base.ContractInstance
.- await_confirmations() ReceiptAPI
Wait for a transaction to be considered confirmed.
- Returns:
The receipt that is now confirmed.
- Return type:
ReceiptAPI
- abstract decode_logs(abi: List[EventABI | ContractEvent] | 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.
- 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 givengas_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[TraceFrame]
The trace of the transaction, if available from your provider.
- 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(*, chainId: int | None = 0, to: ChecksumAddress | None = None, sender: ChecksumAddress | None = None, gas: int | None = None, nonce: int | None = None, value: int = 0, data: bytes = b'', 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.
- 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: Iterator[TraceFrame]
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: List[str], account: ChecksumAddress, start_nonce: NonNegativeInt = 0, stop_nonce: NonNegativeInt)
Bases:
_BaseQuery
A
QueryType
that collects properties ofTransactionAPI
over a range of transactions made byaccount
betweenstart_nonce
andstop_nonce
.- __hash__ = None
- class ape.api.query.BlockQuery(*, columns: List[str], start_block: NonNegativeInt = 0, stop_block: NonNegativeInt, step: PositiveInt = 1)
Bases:
_BaseBlockQuery
A
QueryType
that collects properties ofBlockAPI
over a range of blocks betweenstart_block
andstop_block
.- __hash__ = None
- class ape.api.query.BlockTransactionQuery(*, columns: List[str], block_id: Any = None)
Bases:
_BaseQuery
A
QueryType
that collects properties ofTransactionAPI
over a range of transactions collected inside theBlockAPI` object represented by ``block_id
.- __hash__ = None
- class ape.api.query.ContractEventQuery(*, columns: List[str], start_block: NonNegativeInt = 0, stop_block: NonNegativeInt, step: PositiveInt = 1, contract: ChecksumAddress | List[ChecksumAddress], event: EventABI, search_topics: Dict[str, Any] | None = None)
Bases:
_BaseBlockQuery
A
QueryType
that collects members fromevent
over a range of logs emitted bycontract
betweenstart_block
andstop_block
.- __hash__ = None
- class ape.api.query.ContractMethodQuery(*, columns: List[str], start_block: NonNegativeInt = 0, stop_block: NonNegativeInt, step: PositiveInt = 1, contract: ChecksumAddress, method: MethodABI, method_args: Dict[str, Any])
Bases:
_BaseBlockQuery
A
QueryType
that collects return values from callingmethod
incontract
over a range of blocks betweenstart_block
andstop_block
.- __hash__ = None
- 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 executedresult (
Iterator
) – the result of the query