ape.api
Accounts
- class ape.api.accounts.AccountAPI
Bases:
ape.utils.basemodel.BaseInterfaceModel
,ape.api.address.BaseAddress
An API class representing an account.
- __dir__() List[str]
Display methods to IPython on
a.[TAB]
tab completion.- Returns
Method names that IPython uses for tab completion.
- Return type
List[str]
- __hash__ = None
- property alias: Optional[str]
A shortened-name for quicker access to the account.
- call(txn: ape.api.transactions.TransactionAPI, send_everything: bool = False) ape.api.transactions.ReceiptAPI
Make a transaction call.
- Raises
AccountsError – When the nonce is invalid or the sender does not have enough funds.
TransactionError – When the required confirmations are negative.
SignatureError – When the user does not sign the transaction.
- Parameters
txn (
TransactionAPI
) – An invoke-transaction.send_everything (bool) –
True
will send the difference from balance and fee.
- Returns
- check_signature(data: Union[eth_account.messages.SignableMessage, ape.api.transactions.TransactionAPI], signature: Optional[ape.types.signatures._Signature] = None) bool
Verify a message or transaction was signed by this account.
- Parameters
data (Union[
SignableMessage
,TransactionAPI
]) – # noqa: E501 The message or transaction to verify.signature (Optional[
_Signature
]) – TheMessageSignature
or theTransactionSignature
.
- Returns
True
if the data was signed by this account.False
otherwise.- Return type
bool
- deploy(contract: ContractContainer, *args, **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.- Returns
An instance of the deployed contract.
- Return type
ContractInstance
- prepare_transaction(txn: ape.api.transactions.TransactionAPI) ape.api.transactions.TransactionAPI
Set default values on a transaction.
- Raises
AccountsError – When the account cannot afford the transaction or the nonce is invalid.
TransactionError – When given negative required confirmations.
- Parameters
txn (
TransactionAPI
) – The transaction to prepare.- Returns
- abstract sign_message(msg: eth_account.messages.SignableMessage) Optional[ape.types.signatures.MessageSignature]
Sign a message.
- Parameters
msg (
SignableMessage
) – The message to sign. See these docs # noqa: E501 for more type information on this type.- Returns
The signed message.
- Return type
MessageSignature
(optional)
- abstract sign_transaction(txn: ape.api.transactions.TransactionAPI) Optional[ape.types.signatures.TransactionSignature]
Sign a transaction.
- Parameters
txn (
TransactionAPI
) – The transaction to sign.- Returns
The signed transaction.
- Return type
TransactionSignature
(optional)
- transfer(account: Union[str, ChecksumAddress, ape.api.address.BaseAddress], value: Optional[Union[str, int]] = None, data: Optional[Union[bytes, str]] = None, **kwargs) ape.api.transactions.ReceiptAPI
Send funds to an account.
- Parameters
account (str) – The account to send funds to.
value (str) – The amount to send.
data (str) – Extra data to include in the transaction.
- Returns
- class ape.api.accounts.AccountContainerAPI(*, data_folder: pathlib.Path, account_type: Type[ape.api.accounts.AccountAPI])
Bases:
ape.utils.basemodel.BaseInterfaceModel
An API class representing a collection of
AccountAPI
instances.- __contains__(address: ChecksumAddress) bool
Check if the address is an existing account in
ape
.- Raises
IndexError – When the given account address is not in this container.
- Parameters
address (
AddressType
) – An account address.- Returns
True
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) ape.api.accounts.AccountAPI
Get an account by address.
- Parameters
address (
AddressType
) – The address to get. The type is an alias to ChecksumAddress. # noqa: E501- Raises
IndexError – When there is no local account with the given address.
- Returns
- __hash__ = None
- abstract __len__() int
Number of accounts.
- abstract property accounts: Iterator[ape.api.accounts.AccountAPI]
Iterate over all accounts.
- Returns
Iterator[
AccountAPI
]
- abstract property aliases: Iterator[str]
Iterate over all available aliases.
- Returns
Iterator[str]
- append(account: ape.api.accounts.AccountAPI)
Add an account to the container.
- Raises
AccountsError – When the account is already in the container.
- Parameters
account (
AccountAPI
) – The account to add.
- remove(account: ape.api.accounts.AccountAPI)
Delete an account.
- Raises
AccountsError – When the account is not known to
ape
.- Parameters
account (
AccountAPI
) – The account to remove.
- class ape.api.accounts.ImpersonatedAccount(*, raw_address: ChecksumAddress)
Bases:
ape.api.accounts.AccountAPI
An account to use that does not require signing.
- __hash__ = None
- property address: ChecksumAddress
The address of this account. Subclasses must override and provide this value.
- call(txn: ape.api.transactions.TransactionAPI, send_everything: bool = False) ape.api.transactions.ReceiptAPI
Make a transaction call.
- Raises
AccountsError – When the nonce is invalid or the sender does not have enough funds.
TransactionError – When the required confirmations are negative.
SignatureError – When the user does not sign the transaction.
- Parameters
txn (
TransactionAPI
) – An invoke-transaction.send_everything (bool) –
True
will send the difference from balance and fee.
- Returns
- sign_message(msg: eth_account.messages.SignableMessage) Optional[ape.types.signatures.MessageSignature]
Sign a message.
- Parameters
msg (
SignableMessage
) – The message to sign. See these docs # noqa: E501 for more type information on this type.- Returns
The signed message.
- Return type
MessageSignature
(optional)
- sign_transaction(txn: ape.api.transactions.TransactionAPI) Optional[ape.types.signatures.TransactionSignature]
Sign a transaction.
- Parameters
txn (
TransactionAPI
) – The transaction to sign.- Returns
The signed transaction.
- Return type
TransactionSignature
(optional)
- class ape.api.accounts.TestAccountAPI
Bases:
ape.api.accounts.AccountAPI
Test accounts for
ape test
(such accounts that 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: pathlib.Path, account_type: Type[ape.api.accounts.AccountAPI])
Bases:
ape.api.accounts.AccountContainerAPI
Test account containers for
ape test
(such containers that generate accounts usingGeneratedDevAccounts
) should implement this API instead ofAccountContainerAPI
directly. This is how they show up in theaccounts
test fixture.- __hash__ = None
Address
- class ape.api.address.Address(address: ChecksumAddress)
Bases:
ape.api.address.BaseAddress
A generic blockchain address.
Typically, this is used when we do not know the contract type at a given address, or to refer to an EOA the user doesn’t personally control.
- property address: ChecksumAddress
The raw address type.
- Returns
An alias to ChecksumAddress. # noqa: E501
- Return type
AddressType
- class ape.api.address.BaseAddress
Bases:
ape.utils.basemodel.BaseInterface
A base address API class. All account-types subclass this type.
- abstract property address: ChecksumAddress
The address of this account. Subclasses must override and provide this value.
- property balance: int
The total balance of the account.
- property code: bytes
The raw bytes of the smart-contract code at the address.
- property codesize: int
The number of bytes in the smart contract.
- property is_contract: bool
True
when there is code associated with the address.
- property nonce: int
The number of transactions associated with the address.
Compiler
- class ape.api.compiler.CompilerAPI
Bases:
ape.utils.basemodel.BaseInterfaceModel
Compiler plugins, such as for languages like Solidity or Vyper, implement this API.
See the repository for the ape-solidity plugin or the ape-vyper plugin as example implementations of this API.
- abstract compile(contract_filepaths: List[pathlib.Path], base_path: Optional[pathlib.Path]) List[ethpm_types.contract_type.ContractType]
Compile the given source files. All compiler plugins must implement this function.
- Parameters
contract_filepaths (List[pathlib.Path]) – A list of source file paths to compile.
base_path (Optional[pathlib.Path]) – Optionally provide the base path, such as the project
contracts/
directory. Defaults toNone
. When using in a project viaape compile
, gets set to the project’scontracts/
directory.
- Returns
List[
ContractType
]
- abstract get_versions(all_paths: List[pathlib.Path]) Set[str]
Retrieve the set of available compiler versions for this plugin to compile
all_paths
.- Parameters
all_paths (List[pathlib.Path]) – The list of paths.
- Returns
A set of available compiler versions.
- Return type
Set[str]
Config
- class ape.api.config.ConfigEnum(value)
Bases:
str
,enum.Enum
A configuration Enum type. Use this to limit the values of a config item, such as colors
"RED"
,"BLUE"
,"GREEN"
, rather than any arbitrarystr
.
- class ape.api.config.GenericConfig(_env_file: Optional[Union[str, os.PathLike]] = '<object object>', _env_file_encoding: Optional[str] = None, _env_nested_delimiter: Optional[str] = None, _secrets_dir: Optional[Union[str, os.PathLike]] = None, *, __root__: dict = {})
Bases:
ape.api.config.PluginConfig
The default class used when no specialized class is used.
- __hash__ = None
- class ape.api.config.PluginConfig(_env_file: Optional[Union[str, os.PathLike]] = '<object object>', _env_file_encoding: Optional[str] = None, _env_nested_delimiter: Optional[str] = None, _secrets_dir: Optional[Union[str, os.PathLike]] = None)
Bases:
pydantic.env_settings.BaseSettings
A base plugin configuration class. Each plugin that includes a config API must register a subclass of this class.
- __hash__ = None
Convert
- class ape.api.convert.ConverterAPI
Bases:
Generic
[ape.api.convert.ConvertedType
],ape.utils.basemodel.BaseInterfaceModel
- abstract convert(value: Any) ape.api.convert.ConvertedType
Convert the given value to the type specified as the generic for this class. Implementations of this API must throw a
ConversionError
when the item fails to convert properly.
- abstract is_convertible(value: Any) bool
Returns
True
if string value provided 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: ape.api.networks.NetworkAPI)
Bases:
ape.utils.basemodel.BaseInterfaceModel
An API class representing a blockchain explorer for a particular network in a particular ecosystem.
- abstract get_account_transactions(address: ChecksumAddress) Iterator[ReceiptAPI]
Get a list of list of transactions performed by an address.
- Parameters
address (
AddressType
) – The account address.- Returns
Iterator[
ReceiptAPI
]
- abstract get_address_url(address: ChecksumAddress) str
Get an address URL, such as for a transaction.
- Parameters
address (
AddressType
) – The address to get the URL for.- Returns
str
- abstract get_contract_type(address: ChecksumAddress) Optional[ethpm_types.contract_type.ContractType]
Get the contract type for a given address if it has been published in an explorer.
- Parameters
address (
AddressType
) – The contract address.- Returns
If not published, returns
None
.- Return type
Optional[
ContractType
]
- abstract get_transaction_url(transaction_hash: str) str
Get the transaction URL for the given transaction.
- Parameters
transaction_hash (str) – The transaction hash.
- Returns
str
Networks
- class ape.api.networks.EcosystemAPI(*, name: str, data_folder: pathlib.Path, request_header: dict)
Bases:
ape.utils.basemodel.BaseInterfaceModel
A set of related networks, such as Ethereum.
- __getattr__(network_name: str) ape.api.networks.NetworkAPI
Get a network by name using
.
access.Usage example:
from ape import networks mainnet = networks.ecosystem.mainnet
- Raises
NetworkNotFoundError – When there is no network with the given name.
- Parameters
network_name (str) – The name of the network to retrieve.
- Returns
- __getitem__(network_name: str) ape.api.networks.NetworkAPI
Get a network by name.
- Raises
NetworkNotFoundError – When there is no network with the given name.
- Parameters
network_name (str) – The name of the network to retrieve.
- Returns
- __hash__ = None
- add_network(network_name: str, network: ape.api.networks.NetworkAPI)
Attach a new network to an ecosystem (e.g. L2 networks like Optimism).
- Raises
ape.exceptions.NetworkError – When the network already exists.
- Parameters
network_name (str) – The name of the network to add.
- Returns
- property config: ape.api.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: pathlib.Path
The path to the
.ape
directory.
- abstract classmethod decode_address(raw_address: Union[str, int, hexbytes.main.HexBytes]) ChecksumAddress
Convert a raw address to the ecosystem’s native address type.
- Parameters
raw_address (Union[str, int]) – The address to convert.
- Returns
AddressType
- abstract decode_block(data: dict) BlockAPI
Decode data to a
BlockAPI
.- Parameters
data (dict) – A dictionary of data to decode.
- Returns
- abstract decode_logs(abi: ethpm_types.abi.EventABI, raw_logs: List[Dict]) Iterator[ape.types.ContractLog]
Decode any contract logs that match the given event ABI from the raw log data.
- Parameters
abi (EventABI) – The event producing the logs.
raw_logs (List[Dict]) – A list of raw log data from the chain.
- 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: ethpm_types.abi.MethodABI, raw_data: bytes) Any
Get the result of a contract call.
- Arg:
abi (MethodABI): The method called. raw_data (bytes): Raw returned data.
- Returns
All of the values returned from the contract function.
- Return type
Any
- property default_network: str
The name of the default network in this ecosystem.
- Returns
str
- abstract classmethod encode_address(address: ChecksumAddress) Union[str, int, hexbytes.main.HexBytes]
Convert the ecosystem’s native address type to a raw integer or str address.
- Parameters
address (Union[str, int]) – The address to convert.
- Returns
Union[str, int]
- abstract encode_deployment(deployment_bytecode: hexbytes.main.HexBytes, abi: ethpm_types.abi.ConstructorABI, *args, **kwargs) TransactionAPI
Create a deployment transaction in the given ecosystem. This may require connecting to other networks.
- Parameters
deployment_bytecode (HexBytes) – The bytecode to deploy.
abi (ConstructorABI) – The constructor interface of the contract.
*args – Constructor arguments.
**kwargs – Transaction arguments.
- Returns
~ape.api.transactions.TransactionAPI
- Return type
class
- abstract encode_transaction(address: ChecksumAddress, abi: ethpm_types.abi.MethodABI, *args, **kwargs) TransactionAPI
Encode a transaction object from a contract function’s abi and call arguments. Update the transaction arguments with the overrides in
kwargs
as well.- Parameters
address (AddressType) – The address of the contract.
abi (MethodABI) – The function to call on the contract.
*args – Function arguments.
**kwargs – Transaction arguments.
- Returns
~ape.api.transactions.TransactionAPI
- Return type
class
- get_network(network_name: str) ape.api.networks.NetworkAPI
Get the network for the given name.
- Parameters
network_name (str) – The name of the network to get.
- Raises
NetworkNotFoundError – When the network is not present.
- Returns
- get_network_data(network_name: str) Dict
Get a dictionary of data about providers in the network.
NOTE: The keys are added in an opinionated order for nicely translating into
yaml
.- Parameters
network_name (str) – The name of the network to get provider data from.
- Returns
A dictionary containing the providers in a network.
- Return type
dict
- get_proxy_info(address: ChecksumAddress) Optional[ape.api.networks.ProxyInfoAPI]
Information about a proxy contract such as proxy type and implementation address.
- Parameters
address (str) – The address of the contract.
- Returns
Returns
None
if the contract does not use any known proxy pattern.- Return type
Optional[
ProxyInfoAPI
]
- name: str
The name of the ecosystem. This should be set the same name as the plugin.
- property networks: Dict[str, ape.api.networks.NetworkAPI]
A dictionary of network names mapped to their API implementation.
- Returns
Dict[str,
NetworkAPI
]
- request_header: dict
A shareable HTTP header for network requests.
- serialize_transaction(transaction: TransactionAPI) bytes
Serialize a transaction to bytes.
- Parameters
transaction (
TransactionAPI
) – The transaction to encode.- Returns
bytes
- set_default_network(network_name: str)
Change the default network.
- Raises
NetworkError – When the network does not exist.
- Parameters
network_name (str) – The name of the default network to switch to.
- class ape.api.networks.NetworkAPI(*, name: str, ecosystem: ape.api.networks.EcosystemAPI, data_folder: pathlib.Path, request_header: Dict)
Bases:
ape.utils.basemodel.BaseInterfaceModel
A wrapper around a provider for a specific ecosystem.
- __hash__ = None
- property block_time: int
The approximate amount of time it takes for a new block to get mined to the chain. Configure in your
ape-config.yaml
file.Config example:
ethereum: mainnet: block_time: 15
- Returns
int
- property chain_id: int
The ID of the blockchain.
NOTE: Unless overridden, returns same as
ape.api.providers.ProviderAPI.chain_id
.- Returns
int
- property config: ape.api.config.PluginConfig
The configuration of the network. See
ConfigManager
for more information on plugin configurations.
- data_folder: pathlib.Path
The path to the
.ape
directory.
- property default_provider: Optional[str]
The name of the default provider or
None
.- Returns
Optional[str]
- ecosystem: ape.api.networks.EcosystemAPI
The ecosystem of the network.
- property explorer: Optional[ExplorerAPI]
The block-explorer for the given network.
- Returns
ape.api.explorers.ExplorerAPI
, optional
- get_provider(provider_name: Optional[str] = None, provider_settings: Optional[dict] = None)
Get a provider for the given name. If given
None
, returns the default provider.- Parameters
provider_name (str, optional) – The name of the provider to get. Defaults to
None
. 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 network_id: int
The ID of the network.
NOTE: Unless overridden, returns same as
chain_id
.- Returns
int
- property providers
The providers of the network, such as Infura, Alchemy, or Geth.
- Returns
Dict[str, partial[
ProviderAPI
]]
- 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.
- Returns
int
- 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.
- use_default_provider(provider_settings: Optional[Dict] = None) ape.api.networks.ProviderContextManager
Temporarily connect and use the default provider. When entering the context, it calls method
ape.api.providers.ProviderAPI.connect()
and when exiting, it calls 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.
- Returns
- use_provider(provider_name: str, provider_settings: Optional[dict] = None) ape.api.networks.ProviderContextManager
Use and connect to a provider in a temporary context. When entering the context, it calls method
ape.api.providers.ProviderAPI.connect()
and when exiting, it calls 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.
provider_settings (dict, optional) – Settings to apply to the provider. Defaults to
None
.
- Returns
- class ape.api.networks.ProviderContextManager(provider: ProviderAPI, network_manager: NetworkManager)
Bases:
object
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:
pydantic.main.BaseModel
Information about a proxy contract.
- __hash__ = None
- target: ChecksumAddress
The address of the implementation contract.
- ape.api.networks.create_network_type(chain_id: int, network_id: int) Type[ape.api.networks.NetworkAPI]
Easily create a
ape.api.networks.NetworkAPI
subclass.
Projects
- class ape.api.projects.DependencyAPI(*, name: str, version: str = None, contracts_folder: str = 'contracts', exclude: List[str] = ['package.json', 'package-lock.json'])
Bases:
ape.utils.basemodel.BaseInterfaceModel
A base-class for dependency sources, such as GitHub or IPFS.
- property cached_manifest: Optional[ethpm_types.manifest.PackageManifest]
The manifest from the
.ape/packages/<dependency-name>/<version-id>
if it exists and is valid.
- contracts_folder: str
The name of the dependency’s
contracts/
directory. This is 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() ethpm_types.manifest.PackageManifest
Create a
ProjectAPI
implementation, 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.- Returns
- name: str
The name of the dependency.
- version: Optional[str]
The version of the dependency. Omit to use the latest.
- abstract property version_id: str
The ID to use as the sub-directory in the download cache. Most often, this is either a version number or a branch name.
- class ape.api.projects.ProjectAPI(*, path: pathlib.Path, contracts_folder: pathlib.Path, name: str = None, version: str = None)
Bases:
ape.utils.basemodel.BaseInterfaceModel
An abstract base-class for working with projects. This class can also be extended to a plugin for supporting non-ape projects.
- property cached_manifest: Optional[ethpm_types.manifest.PackageManifest]
The
PackageManifest
atmanifest_cachefile
if it exists and is valid.
- contracts_folder: pathlib.Path
The path to the contracts in the project.
- abstract create_manifest(file_paths: Optional[List[pathlib.Path]] = None, use_cache: bool = True) ethpm_types.manifest.PackageManifest
Create a manifest from the project.
- Parameters
file_paths (Optional[List]) – 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: pathlib.Path
The path to the project’s cached manifest. The manifest is a cached file representing the project and is useful for sharing, such as uploading to IPFS.
- Returns
pathlib.Path
- name: Optional[str]
The name of this project when another project uses it as a dependency.
- path: pathlib.Path
The project path.
- version: Optional[str]
The version of the project whe another project uses it as a dependency.
Providers
- class ape.api.providers.BlockAPI(*, num_transactions: int = 0, hash: Any = None, number: int = None, parentHash: Any = HexBytes('0x0000000000000000000000000000000000000000000000000000000000000000'), size: int, timestamp: int)
Bases:
ape.utils.basemodel.BaseInterfaceModel
An abstract class representing a block and its attributes.
- class ape.api.providers.ProviderAPI(*, name: str, network: ape.api.networks.NetworkAPI, provider_settings: dict, data_folder: pathlib.Path, request_header: dict, cached_chain_id: int = None)
Bases:
ape.utils.basemodel.BaseInterfaceModel
An abstraction of a connection to a network in an ecosystem. Example
ProviderAPI
implementations include the ape-infura plugin or the ape-hardhat plugin.- property base_fee: int
The minimum value required to get your transaction included on the next block. Only providers that implement EIP-1559 will use this property.
- Raises
NotImplementedError – When this provider does not implement EIP-1559.
- cached_chain_id: Optional[int]
Implementation providers may use this to cache and re-use chain ID.
- property config: ape.api.config.PluginConfig
The provider’s configuration.
- abstract connect()
Connect a to a provider, such as start-up a process or create an HTTP connection.
- data_folder: pathlib.Path
The path to the
.ape
directory.
- abstract disconnect()
Disconnect from a provider, such as tear-down a process or quit an HTTP session.
- abstract estimate_gas_cost(txn: ape.api.transactions.TransactionAPI) int
Estimate the cost of gas for a transaction.
- Parameters
txn (
TransactionAPI
) – The transaction to estimate the gas for.- Returns
The estimated cost of gas.
- Return type
int
- abstract get_balance(address: str) int
Get the balance of an account.
- Parameters
address (str) – The address of the account.
- Returns
The account balance.
- Return type
int
- abstract get_block(block_id: Union[str, int, hexbytes.main.HexBytes, Literal['earliest', 'latest', 'pending']]) ape.api.providers.BlockAPI
Get a block.
- abstract get_code(address: str) bytes
Get the bytes a contract.
- Parameters
address (str) – The address of the contract.
- Returns
The contract byte-code.
- Return type
bytes
- abstract get_contract_logs(address: Union[ChecksumAddress, List[ChecksumAddress]], abi: Union[ethpm_types.abi.EventABI, List[ethpm_types.abi.EventABI]], start_block: Optional[int] = None, stop_block: Optional[int] = None, block_page_size: Optional[int] = None, event_parameters: Optional[Dict] = None) Iterator[ape.types.ContractLog]
Get all logs matching the given set of filter parameters.
- Parameters
address (
AddressType
) – The contract address that defines the logs.abi (
EventABI
) – The event of interest’s ABI.start_block (Optional[int]) – Get events that occurred in blocks after the block with this ID.
stop_block (Optional[int]) – Get events that occurred in blocks before the block with this ID.
block_page_size (Optional[int]) – Use this parameter to adjust request block range sizes.
event_parameters (Optional[Dict]) – Filter by event parameter values.
- Returns
Iterator[
ContractLog
]
- abstract get_nonce(address: str) int
Get the number of times an account has transacted.
- Parameters
address (str) – The address of the account.
- Returns
int
- abstract get_transaction(txn_hash: str) ape.api.transactions.ReceiptAPI
Get the information about a transaction from a transaction hash.
- Parameters
txn_hash (str) – The hash of the transaction to retrieve.
- Returns
The receipt of the transaction with the given hash.
- Return type
ReceiptAPI
- abstract get_transactions_by_block(block_id: Union[str, int, hexbytes.main.HexBytes, Literal['earliest', 'latest', 'pending']]) Iterator[ape.api.transactions.TransactionAPI]
Get the information about a set of transactions from a block.
- Parameters
block_id (
BlockID
) – The ID of the block.- Returns
class: ~ape.api.transactions.TransactionAPI]
- Return type
Iterator[
- get_virtual_machine_error(exception: Exception) ape.exceptions.VirtualMachineError
Get a virtual machine error from an error returned from your RPC. If from a contract revert / assert statement, you will be given a special
ContractLogicError
that can be checked 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
- name: str
The name of the provider (should be the plugin name).
- network: ape.api.networks.NetworkAPI
A reference to the network this provider provides.
- prepare_transaction(txn: ape.api.transactions.TransactionAPI) ape.api.transactions.TransactionAPI
Set default values on the transaction.
- Raises
TransactionError – When given negative required confirmations.
- Parameters
txn (
TransactionAPI
) – The transaction to prepare.- Returns
- property priority_fee: int
A miner tip to incentivize them to include your transaction in a block.
- Raises
NotImplementedError – When the provider does not implement EIP-1559 typed transactions.
- provider_settings: dict
The settings for the provider, as overrides to the configuration.
- request_header: dict
A header to set on HTTP/RPC requests.
- abstract send_call(txn: ape.api.transactions.TransactionAPI) bytes
Execute a new transaction call immediately without creating a transaction on the block chain.
- Parameters
txn –
TransactionAPI
- Returns
The result of the transaction call.
- Return type
str
- abstract send_transaction(txn: ape.api.transactions.TransactionAPI) ape.api.transactions.ReceiptAPI
Send a transaction to the network.
- Parameters
txn (
TransactionAPI
) – The transaction to send.- Returns
- abstract update_settings(new_settings: dict)
Change a provider’s setting, such as configure a new port to run on. May require a reconnect.
- Parameters
new_settings (dict) – The new provider settings.
- class ape.api.providers.SubprocessProvider(*, name: str, network: ape.api.networks.NetworkAPI, provider_settings: dict, data_folder: pathlib.Path, request_header: dict, cached_chain_id: int = None, process: subprocess.Popen = None, is_stopping: bool = False, stdout_queue: ape.utils.process.JoinableQueue = None, stderr_queue: ape.utils.process.JoinableQueue = None, PROCESS_WAIT_TIMEOUT: int = 15)
Bases:
ape.api.providers.ProviderAPI
A provider that manages a process, such as for
ganache
.- abstract build_command() List[str]
Get the command as a list of
str
. Subclasses should override and add command arguments if needed.- Returns
The command to pass to
subprocess.Popen
.- Return type
List[str]
- connect()
Start the process and connect to it. Subclasses handle the connection-related tasks.
- disconnect()
Stop the process if it exists. Subclasses override this method to do provider-specific disconnection tasks.
- abstract property is_connected: bool
True
if the process is running and connected.False
otherwise.
- abstract property process_name: str
The name of the process, such as
Hardhat node
.
- start(timeout: int = 20)
Start the process and wait for its RPC to be ready.
- stop()
Kill the process.
- class ape.api.providers.TestProviderAPI(*, name: str, network: ape.api.networks.NetworkAPI, provider_settings: dict, data_folder: pathlib.Path, request_header: dict, cached_chain_id: int = None)
Bases:
ape.api.providers.ProviderAPI
An API for providers that have development functionality, such as snapshotting.
- abstract mine(num_blocks: int = 1)
Advance by the given number of blocks.
- Parameters
num_blocks (int) – The number of blocks allotted to mine. Defaults to
1
.
- abstract revert(snapshot_id: Union[str, int, bytes])
Regress the current call using the given snapshot ID. Allows developers to go back to a previous state.
- Parameters
snapshot_id (str) – The snapshot ID.
- abstract set_timestamp(new_timestamp: int)
Change the pending timestamp.
- Parameters
new_timestamp (int) – The timestamp to set.
- Returns
The new timestamp.
- Return type
int
- abstract snapshot() Union[str, int, bytes]
Record the current state of the blockchain with intent to later call the method
revert()
to go back to this point. This method is for local networks only.- Returns
The snapshot ID.
- Return type
SnapshotID
- class ape.api.providers.UpstreamProvider(*, name: str, network: ape.api.networks.NetworkAPI, provider_settings: dict, data_folder: pathlib.Path, request_header: dict, cached_chain_id: int = None)
Bases:
ape.api.providers.ProviderAPI
A provider that can also be set as another provider’s upstream.
- abstract property connection_str: str
The str used by downstream providers to connect to this one. For example, the URL for HTTP-based providers.
- class ape.api.providers.Web3Provider(*, name: str, network: ape.api.networks.NetworkAPI, provider_settings: dict, data_folder: pathlib.Path, request_header: dict, cached_chain_id: int = None)
Bases:
ape.api.providers.ProviderAPI
,abc.ABC
A base provider mixin class that uses the [web3.py](https://web3py.readthedocs.io/en/stable/) 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: ape.api.transactions.TransactionAPI) int
Estimate the cost of gas for a transaction.
- Parameters
txn (
TransactionAPI
) – The transaction to estimate the gas for.- Returns
The estimated cost of gas.
- Return type
int
- get_balance(address: str) int
Get the balance of an account.
- Parameters
address (str) – The address of the account.
- Returns
The account balance.
- Return type
int
- get_block(block_id: Union[str, int, hexbytes.main.HexBytes, Literal['earliest', 'latest', 'pending']]) ape.api.providers.BlockAPI
Get a block.
- get_code(address: str) bytes
Get the bytes a contract.
- Parameters
address (str) – The address of the contract.
- Returns
The contract byte-code.
- Return type
bytes
- get_contract_logs(address: Union[ChecksumAddress, List[ChecksumAddress]], abi: Union[List[ethpm_types.abi.EventABI], ethpm_types.abi.EventABI], start_block: Optional[int] = None, stop_block: Optional[int] = None, block_page_size: Optional[int] = None, event_parameters: Optional[Dict] = None) Iterator[ape.types.ContractLog]
Get all logs matching the given set of filter parameters.
- Parameters
address (
AddressType
) – The contract address that defines the logs.abi (
EventABI
) – The event of interest’s ABI.start_block (Optional[int]) – Get events that occurred in blocks after the block with this ID.
stop_block (Optional[int]) – Get events that occurred in blocks before the block with this ID.
block_page_size (Optional[int]) – Use this parameter to adjust request block range sizes.
event_parameters (Optional[Dict]) – Filter by event parameter values.
- Returns
Iterator[
ContractLog
]
- get_nonce(address: str) int
Get the number of times an account has transacted.
- Parameters
address (str) – The address of the account.
- Returns
int
- get_transaction(txn_hash: str, required_confirmations: int = 0) ape.api.transactions.ReceiptAPI
Get the information about a transaction from a transaction hash.
- Parameters
txn_hash (str) – The hash of the transaction to retrieve.
- Returns
The receipt of the transaction with the given hash.
- Return type
ReceiptAPI
- get_transactions_by_block(block_id: Union[str, int, hexbytes.main.HexBytes, Literal['earliest', 'latest', 'pending']]) Iterator
Get the information about a set of transactions from a block.
- Parameters
block_id (
BlockID
) – The ID of the block.- Returns
class: ~ape.api.transactions.TransactionAPI]
- Return type
Iterator[
- property priority_fee: int
A miner tip to incentivize them to include your transaction in a block.
- Raises
NotImplementedError – When the provider does not implement EIP-1559 typed transactions.
- send_call(txn: ape.api.transactions.TransactionAPI) bytes
Execute a new transaction call immediately without creating a transaction on the block chain.
- Parameters
txn –
TransactionAPI
- Returns
The result of the transaction call.
- Return type
str
- send_transaction(txn: ape.api.transactions.TransactionAPI) ape.api.transactions.ReceiptAPI
Send a transaction to the network.
- Parameters
txn (
TransactionAPI
) – The transaction to send.- Returns
- 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.
Transactions
- class ape.api.transactions.ReceiptAPI(*, contract_address: str = None, block_number: int, data: bytes = b'', gas_limit: int, gas_price: int, gas_used: int, logs: List[dict] = [], nonce: int = None, receiver: str, required_confirmations: int = 0, sender: str, status: int, txn_hash: str, value: int = 0)
Bases:
ape.utils.basemodel.BaseInterfaceModel
An abstract class to represent a transaction receipt. The receipt contains information about the transaction, such as the status and required confirmations.
NOTE: Use a
required_confirmations
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() ape.api.transactions.ReceiptAPI
Wait for a transaction to be considered confirmed.
- Returns
The receipt that is now confirmed.
- Return type
ReceiptAPI
- decode_logs(abi: Union[ethpm_types.abi.EventABI, ContractEvent]) Iterator[ape.types.ContractLog]
Decode the logs on the receipt.
- Parameters
abi (
EventABI
) – The ABI of the event to decode into logs.- Returns
Iterator[
ContractLog
]
- property failed: bool
Whether the receipt represents a failing transaction. Ecosystem plugins override this property when their receipts are able to be failing.
- raise_for_status()
Handle provider-specific errors regarding a non-successful
TransactionStatusEnum
.
- abstract property ran_out_of_gas: bool
Check if a transaction has 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
- abstract property total_fees_paid: int
The total amount of fees paid for the transaction.
- property trace: Iterator[evm_trace.base.TraceFrame]
The trace of the transaction, if available from your provider.
- class ape.api.transactions.TransactionAPI(*, chainId: int = 0, to: str = None, from: str = None, gas: int = None, nonce: int = None, value: int = 0, data: bytes = b'', type: typing.Union[int, bytes, str], max_fee: int = None, max_priority_fee: int = None, required_confirmations: int = None, signature: ape.types.signatures.TransactionSignature = None)
Bases:
ape.utils.basemodel.BaseInterfaceModel
An API class representing a transaction. Ecosystem plugins implement one or more of transaction APIs depending on which schemas they permit, such as typed-transactions from EIP-1559.
- abstract serialize_transaction() bytes
Serialize the transaction
- property total_transfer_value: int
The total amount of WEI that a transaction could use. Useful for determining if an account balance can afford to submit the transaction.
- abstract property txn_hash: ethpm_types.utils.HexBytes
The calculated hash of the transaction.
Query
- class ape.api.query.AccountTransactionQuery(*, columns: List[str], account: ChecksumAddress, start_nonce: pydantic.types.NonNegativeInt = 0, stop_nonce: pydantic.types.NonNegativeInt)
Bases:
ape.api.query._BaseQuery
A
QueryType
that collects properties ofTransactionAPI
over a range of transactions made byaccount
betweenstart_nonce
andstop_nonce
.- __hash__ = None
- class ape.api.query.BlockQuery(*, columns: List[str], start_block: pydantic.types.NonNegativeInt = 0, stop_block: pydantic.types.NonNegativeInt, step: pydantic.types.PositiveInt = 1)
Bases:
ape.api.query._BaseBlockQuery
A
QueryType
that collects properties 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:
ape.api.query._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: pydantic.types.NonNegativeInt = 0, stop_block: pydantic.types.NonNegativeInt, step: pydantic.types.PositiveInt = 1, contract: ChecksumAddress, event: ethpm_types.abi.EventABI)
Bases:
ape.api.query._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: pydantic.types.NonNegativeInt = 0, stop_block: pydantic.types.NonNegativeInt, step: pydantic.types.PositiveInt = 1, contract: ChecksumAddress, method: ethpm_types.abi.MethodABI, method_args: Dict[str, Any])
Bases:
ape.api.query._BaseBlockQuery
A
QueryType
that collects return values from callingmethod
incontract
over a range of blocks betweenstart_block
andstop_block
.- __hash__ = None
- class ape.api.query.QueryAPI
Bases:
ape.utils.basemodel.BaseInterfaceModel
- __hash__ = None
- abstract estimate_query(query: Union[ape.api.query.BlockQuery, ape.api.query.BlockTransactionQuery, ape.api.query.AccountTransactionQuery, ape.api.query.ContractEventQuery, ape.api.query.ContractMethodQuery]) Optional[int]
Estimation of time needed to complete the query. The estimation is returned as an int representing milliseconds. A value of None indicates that the query engine is not available for use or is unable to complete the query.
- Parameters
query (
QueryType
) – Query to estimate.- Returns
Represents milliseconds, returns
None
if unable to execute.- Return type
Optional[int]
- abstract perform_query(query: Union[ape.api.query.BlockQuery, ape.api.query.BlockTransactionQuery, ape.api.query.AccountTransactionQuery, ape.api.query.ContractEventQuery, ape.api.query.ContractMethodQuery]) Iterator
Executes the query using best performing
estimate_query
query engine.- Parameters
query (
QueryType
) – query to execute- Returns
Iterator
- update_cache(query: Union[ape.api.query.BlockQuery, ape.api.query.BlockTransactionQuery, ape.api.query.AccountTransactionQuery, ape.api.query.ContractEventQuery, ape.api.query.ContractMethodQuery], result: Iterator)
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