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, ABI_W_SELECTOR_T]

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.

class ape.contracts.base.ContractInstance(address: AddressType, contract_type: ContractType, txn_hash: str | HexBytes | 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

__repr__() str

Return repr(self).

property address: AddressType

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

property creation_metadata: ContractCreation | None

txn_hash, block, deployer, factory, receipt. See ContractCreation for more details. NOTE: Must be either connected to a node that provides this data, such as a node with the ots_ namespace enabled, or have a query-plugin installed that can fetch this data, such as ape-etherscan.

Type:

Contract creation details

classmethod from_receipt(receipt: ReceiptAPI, contract_type: ContractType) ContractInstance

Create a contract instance from the contract deployment receipt.

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

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

Bases: ContractTypeWrapper, ExtraAttributesMixin

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.

__eq__(other)

Return self==value.

__hash__ = None
__repr__() str

Return repr(self).

at(address: AddressType, txn_hash: str | HexBytes | 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 (Union[str, HexBytes]) – 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.

__repr__() str

Return repr(self).

__signature__: ClassVar[Signature] = <Signature (*args, contract: ape.contracts.base.ContractTypeWrapper, abi: ethpm_types.abi.EventABI) -> None>

The synthesized __init__ [Signature][inspect.Signature] of the model.

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 info: str

NatSpec info derived from the contract-type developer-documentation.

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]