ape.contracts

class ape.contracts.base.ContractTypeWrapper

Bases: ManagerAccessMixin

decode_input(calldata: bytes) Tuple[str, Dict[str, Any]]

Decode the given calldata using this contract. If the calldata has a method ID prefix, Ape will detect it and find the corresponding method, else it will error.

Parameters:

calldata (bytes) – The calldata to decode.

Returns:

A tuple containing the method selector along a mapping of input names to their decoded values. If an input does not have a number, it will have the stringified index as its key.

Return type:

Tuple[str, Dict[str, Any]]

property identifier_lookup: Dict[str, ConstructorABI | MethodABI | EventABI | StructABI | ErrorABI]

Provides a mapping of method, error, and event selector identifiers to ABI Types.

property selector_identifiers: Dict[str, str]

Provides a mapping of function signatures (pre-hashed selectors) to selector identifiers.

property source_path: Path | None

Returns the path to the local contract if determined that this container belongs to the active project by cross checking source_id.

WARN: The will return a path if the contract has the same source ID as one in the current project. That does not necessarily mean they are the same contract, however.

class ape.contracts.base.ContractInstance(address: ChecksumAddress, contract_type: ContractType, txn_hash: str | None = None)

Bases: BaseAddress, ContractTypeWrapper

An interactive instance of a smart contract. After you deploy a contract using the deploy method, you get back a contract instance.

Usage example:

from ape import accounts, project

a = accounts.load("alias")  # Load an account by alias
contract = a.deploy(project.MyContract)  # The result of 'deploy()' is a ContractInstance
__call__(*args, **kwargs) ReceiptAPI

Call this address directly. For contracts, this may mean invoking their default handler.

Parameters:

**kwargs – Transaction arguments, such as sender or data.

Returns:

ReceiptAPI

__dir__() List[str]

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

Returns:

List[str]

__getattr__(attr_name: str) Any

Access a method, property, event, or error on the contract using . access.

Usage example:

result = contract.vote()  # Implies a method named "vote" exists on the contract.
Parameters:

attr_name (str) – The name of the method or property to access.

Returns:

The return value from the contract call, or a transaction receipt.

Return type:

Any

property address: ChecksumAddress

The address of the contract.

Returns:

AddressType

call_view_method(method_name: str, *args, **kwargs) Any

Call a contract’s view function directly using the method_name. This is helpful in the scenario where the contract has a method name matching an attribute of the BaseAddress class, such as nonce or balance

Parameters:
  • method_name (str) – The contract method name to be called

  • *args – Contract method arguments.

  • **kwargs – Transaction values, such as value or sender

Returns:

Output of smart contract view call.

Return type:

Any

get_error_by_signature(signature: str) Type[CustomError]

Get an error by its signature, similar to get_event_by_signature().

Parameters:

signature (str) – The signature of the error.

Returns:

CustomError

get_event_by_signature(signature: str) ContractEvent

Get an event by its signature. Most often, you can use the __getattr__() method on this class to access events. However, in the case when you have more than one event with the same name, such as the case where one event is coming from a base contract, you can use this method to access the respective events.

Parameters:

signature (str) – The signature of the event.

Returns:

ContractEvent

invoke_transaction(method_name: str, *args, **kwargs) ReceiptAPI

Call a contract’s function directly using the method_name. This function is for non-view function’s which may change contract state and will execute a transaction. This is helpful in the scenario where the contract has a method name matching an attribute of the BaseAddress class, such as nonce or balance

Parameters:
  • method_name (str) – The contract method name to be called

  • *args – Contract method arguments.

  • **kwargs – Transaction values, such as value or sender

Returns:

Output of smart contract interaction.

Return type:

ReceiptAPI

property receipt: ReceiptAPI

The receipt associated with deploying the contract instance, if it is known and exists.

class ape.contracts.base.ContractContainer(contract_type: ContractType)

Bases: ContractTypeWrapper

A wrapper around the contract type that has access to the provider. When you import your contracts from the ape.managers.project.ProjectManager, you are using this class.

Usage example:

from ape import project

contract_container = project.MyContract  # Assuming there is a contract named "MyContract"
__call__(*args, **kwargs) TransactionAPI

Call self as a function.

__getattr__(name: str) Any

Access a contract error or event type via its ABI name using . access.

Parameters:

name (str) – The name of the event or error.

Returns:

ContractEvent or a subclass of CustomError or any real attribute of the class.

at(address: ChecksumAddress, txn_hash: str | None = None) ContractInstance

Get a contract at the given address.

Usage example:

from ape import project

my_contract = project.MyContract.at("0xAbC1230001112223334445566611855443322111")
Parameters:
  • address (str) – The address to initialize a contract. NOTE: Things will not work as expected if the contract is not actually deployed to this address or if the contract at the given address has a different ABI than contract_type.

  • txn_hash (str) – The hash of the transaction that deployed the contract, if available. Defaults to None.

Returns:

ContractInstance

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

Deploy a contract.

Parameters:
  • *args (Any) – The contract’s constructor arguments as Python types.

  • publish (bool) – Whether to also perform contract-verification. Defaults to False.

Returns:

ContractInstance

property deployments

Contract deployments.

Usage example:

# Get the latest deployment
my_contract = project.MyContract.deployments[-1]
class ape.contracts.base.ContractEvent

Bases: BaseInterfaceModel

The types of events on a ContractInstance. Use the event types via . access on the contract instances.

Usage example:

# 'my_contract' refers to a ContractInstance in this case.
my_event_type = my_contract.MyEvent
__call__(*args: Any, **kwargs: Any) MockContractLog

Call self as a function.

__iter__() Iterator[ContractLog]

Get all logs that have occurred for this event.

from_receipt(receipt: ReceiptAPI) List[ContractLog]

Get all the events from the given receipt.

Parameters:

receipt (ReceiptAPI) – The receipt containing the logs.

Returns:

List[ContractLog]

property name: str

The name of the contract event, as defined in the contract.

poll_logs(start_block: int | None = None, stop_block: int | None = None, required_confirmations: int | None = None, new_block_timeout: int | None = None) Iterator[ContractLog]

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

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

Usage example:

for new_log in contract.MyEvent.poll_logs():
    print(f"New event log found: block_number={new_log.block_number}")
Parameters:
  • start_block (Optional[int]) – The block number to start with. Defaults to the pending block number.

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

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

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

Returns:

Iterator[ContractLog]

query(*columns: str, start_block: int = 0, stop_block: int | None = None, step: int = 1, engine_to_use: str | None = None) DataFrame

Iterate through blocks for log events

Parameters:
  • *columns (str) – *-based argument for columns in the DataFrame to return.

  • start_block (int) – The first block, by number, to include in the query. Defaults to 0.

  • stop_block (Optional[int]) – The last block, by number, to include in the query. Defaults to the latest block.

  • step (int) – The number of blocks to iterate between block numbers. Defaults to 1.

  • engine_to_use (Optional[str]) – query engine to use, bypasses query engine selection algorithm.

Returns:

pd.DataFrame

range(start_or_stop: int, stop: int | None = None, search_topics: Dict[str, Any] | None = None, extra_addresses: List | None = None) Iterator[ContractLog]

Search through the logs for this event using the given filter parameters.

Parameters:
  • start_or_stop (int) – When also given stop, this is the earliest block number in the desired log set. Otherwise, it is the total amount of blocks to get starting from 0.

  • stop (Optional[int]) – The latest block number in the desired log set. Defaults to delegating to provider.

  • search_topics (Optional[Dict]) – Search topics, such as indexed event inputs, to query by. Defaults to getting all events.

  • extra_addresses (Optional[List[AddressType]]) – Additional contract addresses containing the same event type. Defaults to only looking at the contract instance where this event is defined.

Returns:

Iterator[ContractLog]