code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def fetch(self, destination: Path): """ Fetch the dependency. E.g. for GitHub dependency, download the files to the destination. Args: destination (Path): The destination for the dependency files. """
Fetch the dependency. E.g. for GitHub dependency, download the files to the destination. Args: destination (Path): The destination for the dependency files.
fetch
python
ApeWorX/ape
src/ape/api/projects.py
https://github.com/ApeWorX/ape/blob/master/src/ape/api/projects.py
Apache-2.0
def is_valid(self) -> bool: """ Return ``True`` when detecting a project of this type. """
Return ``True`` when detecting a project of this type.
is_valid
python
ApeWorX/ape
src/ape/api/projects.py
https://github.com/ApeWorX/ape/blob/master/src/ape/api/projects.py
Apache-2.0
def extract_config(self, **overrides) -> "ApeConfig": """ Extra configuration from the project so that Ape understands the dependencies and how to compile everything. Args: **overrides: Config overrides. Returns: :class:`~ape.managers.config.ApeConfig` """
Extra configuration from the project so that Ape understands the dependencies and how to compile everything. Args: **overrides: Config overrides. Returns: :class:`~ape.managers.config.ApeConfig`
extract_config
python
ApeWorX/ape
src/ape/api/projects.py
https://github.com/ApeWorX/ape/blob/master/src/ape/api/projects.py
Apache-2.0
def validate_size(cls, values, handler): """ A validator for handling non-computed size. Saves it to a private member on this class and gets returned in computed field "size". """ if isinstance(values, BlockAPI): size = values.size else: if not hasattr(values, "pop"): # Handle weird AttributeDict missing pop method. # https://github.com/ethereum/web3.py/issues/3326 values = {**values} size = values.pop("size", None) model = handler(values) if size is not None: model._size = to_int(size) return model
A validator for handling non-computed size. Saves it to a private member on this class and gets returned in computed field "size".
validate_size
python
ApeWorX/ape
src/ape/api/providers.py
https://github.com/ApeWorX/ape/blob/master/src/ape/api/providers.py
Apache-2.0
def size(self) -> HexInt: """ The size of the block in gas. Most of the time, this field is passed to the model at validation time, but occasionally it is missing (like in `eth_subscribe:newHeads`), in which case it gets calculated if and only if the user requests it (or during serialization of this model to disk). """ if self._size is not None: # The size was provided with the rest of the model # (normal). return self._size raise APINotImplementedError()
The size of the block in gas. Most of the time, this field is passed to the model at validation time, but occasionally it is missing (like in `eth_subscribe:newHeads`), in which case it gets calculated if and only if the user requests it (or during serialization of this model to disk).
size
python
ApeWorX/ape
src/ape/api/providers.py
https://github.com/ApeWorX/ape/blob/master/src/ape/api/providers.py
Apache-2.0
def is_connected(self) -> bool: """ ``True`` if currently connected to the provider. ``False`` otherwise. """
``True`` if currently connected to the provider. ``False`` otherwise.
is_connected
python
ApeWorX/ape
src/ape/api/providers.py
https://github.com/ApeWorX/ape/blob/master/src/ape/api/providers.py
Apache-2.0
def connect(self): """ Connect to a provider, such as start-up a process or create an HTTP connection. """
Connect to a provider, such as start-up a process or create an HTTP connection.
connect
python
ApeWorX/ape
src/ape/api/providers.py
https://github.com/ApeWorX/ape/blob/master/src/ape/api/providers.py
Apache-2.0
def disconnect(self): """ Disconnect from a provider, such as tear-down a process or quit an HTTP session. """
Disconnect from a provider, such as tear-down a process or quit an HTTP session.
disconnect
python
ApeWorX/ape
src/ape/api/providers.py
https://github.com/ApeWorX/ape/blob/master/src/ape/api/providers.py
Apache-2.0
def settings(self) -> "PluginConfig": """ The combination of settings from ``ape-config.yaml`` and ``.provider_settings``. """ CustomConfig = self.config.__class__ data = {**self.config.model_dump(), **self.provider_settings} return CustomConfig.model_validate(data)
The combination of settings from ``ape-config.yaml`` and ``.provider_settings``.
settings
python
ApeWorX/ape
src/ape/api/providers.py
https://github.com/ApeWorX/ape/blob/master/src/ape/api/providers.py
Apache-2.0
def connection_id(self) -> Optional[str]: """ A connection ID to uniquely identify and manage multiple connections to providers, especially when working with multiple providers of the same type, like multiple Geth --dev nodes. """ try: chain_id = self.chain_id except Exception: if chain_id := self.settings.get("chain_id"): pass else: # A connection is required to obtain a chain ID for this provider. return None # NOTE: If other provider settings are different, ``.update_settings()`` # should be called. return f"{self.network_choice}:{chain_id}"
A connection ID to uniquely identify and manage multiple connections to providers, especially when working with multiple providers of the same type, like multiple Geth --dev nodes.
connection_id
python
ApeWorX/ape
src/ape/api/providers.py
https://github.com/ApeWorX/ape/blob/master/src/ape/api/providers.py
Apache-2.0
def update_settings(self, new_settings: dict): """ Change a provider's setting, such as configure a new port to run on. May require a reconnect. Args: new_settings (dict): The new provider settings. """
Change a provider's setting, such as configure a new port to run on. May require a reconnect. Args: new_settings (dict): The new provider settings.
update_settings
python
ApeWorX/ape
src/ape/api/providers.py
https://github.com/ApeWorX/ape/blob/master/src/ape/api/providers.py
Apache-2.0
def chain_id(self) -> int: """ The blockchain ID. See `ChainList <https://chainlist.org/>`__ for a comprehensive list of IDs. """
The blockchain ID. See `ChainList <https://chainlist.org/>`__ for a comprehensive list of IDs.
chain_id
python
ApeWorX/ape
src/ape/api/providers.py
https://github.com/ApeWorX/ape/blob/master/src/ape/api/providers.py
Apache-2.0
def get_balance(self, address: "AddressType", block_id: Optional["BlockID"] = None) -> int: """ Get the balance of an account. Args: address (:class:`~ape.types.address.AddressType`): The address of the account. block_id (:class:`~ape.types.BlockID`): Optionally specify a block ID. Defaults to using the latest block. Returns: int: The account balance. """
Get the balance of an account. Args: address (:class:`~ape.types.address.AddressType`): The address of the account. block_id (:class:`~ape.types.BlockID`): Optionally specify a block ID. Defaults to using the latest block. Returns: int: The account balance.
get_balance
python
ApeWorX/ape
src/ape/api/providers.py
https://github.com/ApeWorX/ape/blob/master/src/ape/api/providers.py
Apache-2.0
def get_code( self, address: "AddressType", block_id: Optional["BlockID"] = None ) -> "ContractCode": """ Get the bytes a contract. Args: address (:class:`~ape.types.address.AddressType`): The address of the contract. block_id (Optional[:class:`~ape.types.BlockID`]): The block ID for checking a previous account nonce. Returns: :class:`~ape.types.ContractCode`: The contract bytecode. """
Get the bytes a contract. Args: address (:class:`~ape.types.address.AddressType`): The address of the contract. block_id (Optional[:class:`~ape.types.BlockID`]): The block ID for checking a previous account nonce. Returns: :class:`~ape.types.ContractCode`: The contract bytecode.
get_code
python
ApeWorX/ape
src/ape/api/providers.py
https://github.com/ApeWorX/ape/blob/master/src/ape/api/providers.py
Apache-2.0
def make_request(self, rpc: str, parameters: Optional[Iterable] = None) -> Any: """ Make a raw RPC request to the provider. Advanced features such as tracing may utilize this to by-pass unnecessary class-serializations. """
Make a raw RPC request to the provider. Advanced features such as tracing may utilize this to by-pass unnecessary class-serializations.
make_request
python
ApeWorX/ape
src/ape/api/providers.py
https://github.com/ApeWorX/ape/blob/master/src/ape/api/providers.py
Apache-2.0
def stream_request( # type: ignore[empty-body] self, method: str, params: Iterable, iter_path: str = "result.item" ) -> Iterator[Any]: """ Stream a request, great for large requests like events or traces. Args: method (str): The RPC method to call. params (Iterable): Parameters for the method.s iter_path (str): The response dict-path to the items. Returns: An iterator of items. """
Stream a request, great for large requests like events or traces. Args: method (str): The RPC method to call. params (Iterable): Parameters for the method.s iter_path (str): The response dict-path to the items. Returns: An iterator of items.
stream_request
python
ApeWorX/ape
src/ape/api/providers.py
https://github.com/ApeWorX/ape/blob/master/src/ape/api/providers.py
Apache-2.0
def get_storage( # type: ignore[empty-body] self, address: "AddressType", slot: int, block_id: Optional["BlockID"] = None ) -> "HexBytes": """ Gets the raw value of a storage slot of a contract. Args: address (AddressType): The address of the contract. slot (int): Storage slot to read the value of. block_id (Optional[:class:`~ape.types.BlockID`]): The block ID for checking a previous storage value. Returns: HexBytes: The value of the storage slot. """
Gets the raw value of a storage slot of a contract. Args: address (AddressType): The address of the contract. slot (int): Storage slot to read the value of. block_id (Optional[:class:`~ape.types.BlockID`]): The block ID for checking a previous storage value. Returns: HexBytes: The value of the storage slot.
get_storage
python
ApeWorX/ape
src/ape/api/providers.py
https://github.com/ApeWorX/ape/blob/master/src/ape/api/providers.py
Apache-2.0
def get_nonce(self, address: "AddressType", block_id: Optional["BlockID"] = None) -> int: """ Get the number of times an account has transacted. Args: address (AddressType): The address of the account. block_id (Optional[:class:`~ape.types.BlockID`]): The block ID for checking a previous account nonce. Returns: int """
Get the number of times an account has transacted. Args: address (AddressType): The address of the account. block_id (Optional[:class:`~ape.types.BlockID`]): The block ID for checking a previous account nonce. Returns: int
get_nonce
python
ApeWorX/ape
src/ape/api/providers.py
https://github.com/ApeWorX/ape/blob/master/src/ape/api/providers.py
Apache-2.0
def gas_price(self) -> int: """ The price for what it costs to transact (pre-`EIP-1559 <https://eips.ethereum.org/EIPS/eip-1559>`__). """
The price for what it costs to transact (pre-`EIP-1559 <https://eips.ethereum.org/EIPS/eip-1559>`__).
gas_price
python
ApeWorX/ape
src/ape/api/providers.py
https://github.com/ApeWorX/ape/blob/master/src/ape/api/providers.py
Apache-2.0
def get_block(self, block_id: "BlockID") -> BlockAPI: """ Get a block. Args: block_id (:class:`~ape.types.BlockID`): The ID of the block to get. Can be ``"latest"``, ``"earliest"``, ``"pending"``, a block hash or a block number. Raises: :class:`~ape.exceptions.BlockNotFoundError`: Likely the exception raised when a block is not found (depends on implementation). Returns: :class:`~ape.types.BlockID`: The block for the given ID. """
Get a block. Args: block_id (:class:`~ape.types.BlockID`): The ID of the block to get. Can be ``"latest"``, ``"earliest"``, ``"pending"``, a block hash or a block number. Raises: :class:`~ape.exceptions.BlockNotFoundError`: Likely the exception raised when a block is not found (depends on implementation). Returns: :class:`~ape.types.BlockID`: The block for the given ID.
get_block
python
ApeWorX/ape
src/ape/api/providers.py
https://github.com/ApeWorX/ape/blob/master/src/ape/api/providers.py
Apache-2.0
def send_call( self, txn: TransactionAPI, block_id: Optional["BlockID"] = None, state: Optional[dict] = None, **kwargs, ) -> "HexBytes": # Return value of function """ Execute a new transaction call immediately without creating a transaction on the block chain. Args: txn: :class:`~ape.api.transactions.TransactionAPI` block_id (Optional[:class:`~ape.types.BlockID`]): The block ID to use to send a call at a historical point of a contract. Useful for checking a past estimation cost of a transaction. state (Optional[dict]): Modify the state of the blockchain prior to sending the call, for testing purposes. **kwargs: Provider-specific extra kwargs. Returns: str: The result of the transaction call. """
Execute a new transaction call immediately without creating a transaction on the block chain. Args: txn: :class:`~ape.api.transactions.TransactionAPI` block_id (Optional[:class:`~ape.types.BlockID`]): The block ID to use to send a call at a historical point of a contract. Useful for checking a past estimation cost of a transaction. state (Optional[dict]): Modify the state of the blockchain prior to sending the call, for testing purposes. **kwargs: Provider-specific extra kwargs. Returns: str: The result of the transaction call.
send_call
python
ApeWorX/ape
src/ape/api/providers.py
https://github.com/ApeWorX/ape/blob/master/src/ape/api/providers.py
Apache-2.0
def get_receipt(self, txn_hash: str, **kwargs) -> ReceiptAPI: """ Get the information about a transaction from a transaction hash. Args: txn_hash (str): The hash of the transaction to retrieve. kwargs: Any other kwargs that other providers might allow when fetching a receipt. Returns: :class:`~api.providers.ReceiptAPI`: The receipt of the transaction with the given hash. """
Get the information about a transaction from a transaction hash. Args: txn_hash (str): The hash of the transaction to retrieve. kwargs: Any other kwargs that other providers might allow when fetching a receipt. Returns: :class:`~api.providers.ReceiptAPI`: The receipt of the transaction with the given hash.
get_receipt
python
ApeWorX/ape
src/ape/api/providers.py
https://github.com/ApeWorX/ape/blob/master/src/ape/api/providers.py
Apache-2.0
def get_transactions_by_block(self, block_id: "BlockID") -> Iterator[TransactionAPI]: """ Get the information about a set of transactions from a block. Args: block_id (:class:`~ape.types.BlockID`): The ID of the block. Returns: Iterator[:class: `~ape.api.transactions.TransactionAPI`] """
Get the information about a set of transactions from a block. Args: block_id (:class:`~ape.types.BlockID`): The ID of the block. Returns: Iterator[:class: `~ape.api.transactions.TransactionAPI`]
get_transactions_by_block
python
ApeWorX/ape
src/ape/api/providers.py
https://github.com/ApeWorX/ape/blob/master/src/ape/api/providers.py
Apache-2.0
def get_transactions_by_account_nonce( # type: ignore[empty-body] self, account: "AddressType", start_nonce: int = 0, stop_nonce: int = -1, ) -> Iterator[ReceiptAPI]: """ Get account history for the given account. Args: account (:class:`~ape.types.address.AddressType`): The address of the account. start_nonce (int): The nonce of the account to start the search with. stop_nonce (int): The nonce of the account to stop the search with. Returns: Iterator[:class:`~ape.api.transactions.ReceiptAPI`] """
Get account history for the given account. Args: account (:class:`~ape.types.address.AddressType`): The address of the account. start_nonce (int): The nonce of the account to start the search with. stop_nonce (int): The nonce of the account to stop the search with. Returns: Iterator[:class:`~ape.api.transactions.ReceiptAPI`]
get_transactions_by_account_nonce
python
ApeWorX/ape
src/ape/api/providers.py
https://github.com/ApeWorX/ape/blob/master/src/ape/api/providers.py
Apache-2.0
def send_transaction(self, txn: TransactionAPI) -> ReceiptAPI: """ Send a transaction to the network. Args: txn (:class:`~ape.api.transactions.TransactionAPI`): The transaction to send. Returns: :class:`~ape.api.transactions.ReceiptAPI` """
Send a transaction to the network. Args: txn (:class:`~ape.api.transactions.TransactionAPI`): The transaction to send. Returns: :class:`~ape.api.transactions.ReceiptAPI`
send_transaction
python
ApeWorX/ape
src/ape/api/providers.py
https://github.com/ApeWorX/ape/blob/master/src/ape/api/providers.py
Apache-2.0
def get_contract_logs(self, log_filter: "LogFilter") -> Iterator["ContractLog"]: """ Get logs from contracts. Args: log_filter (:class:`~ape.types.LogFilter`): A mapping of event ABIs to topic filters. Defaults to getting all events. Returns: Iterator[:class:`~ape.types.ContractLog`] """
Get logs from contracts. Args: log_filter (:class:`~ape.types.LogFilter`): A mapping of event ABIs to topic filters. Defaults to getting all events. Returns: Iterator[:class:`~ape.types.ContractLog`]
get_contract_logs
python
ApeWorX/ape
src/ape/api/providers.py
https://github.com/ApeWorX/ape/blob/master/src/ape/api/providers.py
Apache-2.0
def send_private_transaction(self, txn: TransactionAPI, **kwargs) -> ReceiptAPI: """ Send a transaction through a private mempool (if supported by the Provider). Raises: :class:`~ape.exceptions.APINotImplementedError`: If using a non-local network and not implemented by the provider. Args: txn (:class:`~ape.api.transactions.TransactionAPI`): The transaction to privately publish. **kwargs: Additional kwargs to be optionally handled by the provider. Returns: :class:`~ape.api.transactions.ReceiptAPI` """ if self.network.is_dev: # Send the transaction as normal so testers can verify private=True # and the txn still goes through. logger.warning( f"private=True is set but connected to network '{self.network.name}' ." f"Using regular '{self.send_transaction.__name__}()' method (not private)." ) return self.send_transaction(txn) # What happens normally from `raises_not_implemented()` decorator. raise _create_raises_not_implemented_error(self.send_private_transaction)
Send a transaction through a private mempool (if supported by the Provider). Raises: :class:`~ape.exceptions.APINotImplementedError`: If using a non-local network and not implemented by the provider. Args: txn (:class:`~ape.api.transactions.TransactionAPI`): The transaction to privately publish. **kwargs: Additional kwargs to be optionally handled by the provider. Returns: :class:`~ape.api.transactions.ReceiptAPI`
send_private_transaction
python
ApeWorX/ape
src/ape/api/providers.py
https://github.com/ApeWorX/ape/blob/master/src/ape/api/providers.py
Apache-2.0
def snapshot(self) -> "SnapshotID": # type: ignore[empty-body] """ Defined to make the ``ProviderAPI`` interchangeable with a :class:`~ape.api.providers.TestProviderAPI`, as in :class:`ape.managers.chain.ChainManager`. Raises: :class:`~ape.exceptions.APINotImplementedError`: Unless overridden. """
Defined to make the ``ProviderAPI`` interchangeable with a :class:`~ape.api.providers.TestProviderAPI`, as in :class:`ape.managers.chain.ChainManager`. Raises: :class:`~ape.exceptions.APINotImplementedError`: Unless overridden.
snapshot
python
ApeWorX/ape
src/ape/api/providers.py
https://github.com/ApeWorX/ape/blob/master/src/ape/api/providers.py
Apache-2.0
def restore(self, snapshot_id: "SnapshotID"): """ Defined to make the ``ProviderAPI`` interchangeable with a :class:`~ape.api.providers.TestProviderAPI`, as in :class:`ape.managers.chain.ChainManager`. Raises: :class:`~ape.exceptions.APINotImplementedError`: Unless overridden. """
Defined to make the ``ProviderAPI`` interchangeable with a :class:`~ape.api.providers.TestProviderAPI`, as in :class:`ape.managers.chain.ChainManager`. Raises: :class:`~ape.exceptions.APINotImplementedError`: Unless overridden.
restore
python
ApeWorX/ape
src/ape/api/providers.py
https://github.com/ApeWorX/ape/blob/master/src/ape/api/providers.py
Apache-2.0
def set_timestamp(self, new_timestamp: int): """ Defined to make the ``ProviderAPI`` interchangeable with a :class:`~ape.api.providers.TestProviderAPI`, as in :class:`ape.managers.chain.ChainManager`. Raises: :class:`~ape.exceptions.APINotImplementedError`: Unless overridden. """
Defined to make the ``ProviderAPI`` interchangeable with a :class:`~ape.api.providers.TestProviderAPI`, as in :class:`ape.managers.chain.ChainManager`. Raises: :class:`~ape.exceptions.APINotImplementedError`: Unless overridden.
set_timestamp
python
ApeWorX/ape
src/ape/api/providers.py
https://github.com/ApeWorX/ape/blob/master/src/ape/api/providers.py
Apache-2.0
def mine(self, num_blocks: int = 1): """ Defined to make the ``ProviderAPI`` interchangeable with a :class:`~ape.api.providers.TestProviderAPI`, as in :class:`ape.managers.chain.ChainManager`. Raises: :class:`~ape.exceptions.APINotImplementedError`: Unless overridden. """
Defined to make the ``ProviderAPI`` interchangeable with a :class:`~ape.api.providers.TestProviderAPI`, as in :class:`ape.managers.chain.ChainManager`. Raises: :class:`~ape.exceptions.APINotImplementedError`: Unless overridden.
mine
python
ApeWorX/ape
src/ape/api/providers.py
https://github.com/ApeWorX/ape/blob/master/src/ape/api/providers.py
Apache-2.0
def set_balance(self, address: "AddressType", amount: int): """ Change the balance of an account. Args: address (AddressType): An address on the network. amount (int): The balance to set in the address. """
Change the balance of an account. Args: address (AddressType): An address on the network. amount (int): The balance to set in the address.
set_balance
python
ApeWorX/ape
src/ape/api/providers.py
https://github.com/ApeWorX/ape/blob/master/src/ape/api/providers.py
Apache-2.0
def get_test_account(self, index: int) -> "TestAccountAPI": # type: ignore[empty-body] """ Retrieve one of the provider-generated test accounts. Args: index (int): The index of the test account in the HD-Path. Returns: :class:`~ape.api.accounts.TestAccountAPI` """
Retrieve one of the provider-generated test accounts. Args: index (int): The index of the test account in the HD-Path. Returns: :class:`~ape.api.accounts.TestAccountAPI`
get_test_account
python
ApeWorX/ape
src/ape/api/providers.py
https://github.com/ApeWorX/ape/blob/master/src/ape/api/providers.py
Apache-2.0
def set_code( # type: ignore[empty-body] self, address: "AddressType", code: "ContractCode" ) -> bool: """ Change the code of a smart contract, for development purposes. Test providers implement this method when they support it. Args: address (AddressType): An address on the network. code (:class:`~ape.types.ContractCode`): The new bytecode. """
Change the code of a smart contract, for development purposes. Test providers implement this method when they support it. Args: address (AddressType): An address on the network. code (:class:`~ape.types.ContractCode`): The new bytecode.
set_code
python
ApeWorX/ape
src/ape/api/providers.py
https://github.com/ApeWorX/ape/blob/master/src/ape/api/providers.py
Apache-2.0
def set_storage( # type: ignore[empty-body] self, address: "AddressType", slot: int, value: "HexBytes" ): """ Sets the raw value of a storage slot of a contract. Args: address (str): The address of the contract. slot (int): Storage slot to write the value to. value: (HexBytes): The value to overwrite the raw storage slot with. """
Sets the raw value of a storage slot of a contract. Args: address (str): The address of the contract. slot (int): Storage slot to write the value to. value: (HexBytes): The value to overwrite the raw storage slot with.
set_storage
python
ApeWorX/ape
src/ape/api/providers.py
https://github.com/ApeWorX/ape/blob/master/src/ape/api/providers.py
Apache-2.0
def relock_account(self, address: "AddressType"): """ Stop impersonating an account. Args: address (:class:`~ape.types.address.AddressType`): The address to relock. """
Stop impersonating an account. Args: address (:class:`~ape.types.address.AddressType`): The address to relock.
relock_account
python
ApeWorX/ape
src/ape/api/providers.py
https://github.com/ApeWorX/ape/blob/master/src/ape/api/providers.py
Apache-2.0
def get_transaction_trace( # type: ignore[empty-body] self, txn_hash: Union["HexBytes", str] ) -> "TraceAPI": """ Provide a detailed description of opcodes. Args: txn_hash (Union[HexBytes, str]): The hash of a transaction to trace. Returns: :class:`~ape.api.trace.TraceAPI`: A transaction trace. """
Provide a detailed description of opcodes. Args: txn_hash (Union[HexBytes, str]): The hash of a transaction to trace. Returns: :class:`~ape.api.trace.TraceAPI`: A transaction trace.
get_transaction_trace
python
ApeWorX/ape
src/ape/api/providers.py
https://github.com/ApeWorX/ape/blob/master/src/ape/api/providers.py
Apache-2.0
def poll_blocks( # type: ignore[empty-body] self, stop_block: Optional[int] = None, required_confirmations: Optional[int] = None, new_block_timeout: Optional[int] = None, ) -> Iterator[BlockAPI]: """ Poll new blocks. **NOTE**: When a chain reorganization occurs, this method logs an error and yields the missed blocks, even if they were previously yielded with different block numbers. **NOTE**: This is a daemon method; it does not terminate unless an exception occurs or a ``stop_block`` is given. Args: stop_block (Optional[int]): Optionally set a future block number to stop at. Defaults to never-ending. required_confirmations (Optional[int]): The amount of confirmations to wait before yielding the block. The more confirmations, the less likely a reorg will occur. Defaults to the network's configured required confirmations. new_block_timeout (Optional[float]): The amount of time to wait for a new block before timing out. Defaults to 10 seconds for local networks or ``50 * block_time`` for live networks. Returns: Iterator[:class:`~ape.api.providers.BlockAPI`] """
Poll new blocks. **NOTE**: When a chain reorganization occurs, this method logs an error and yields the missed blocks, even if they were previously yielded with different block numbers. **NOTE**: This is a daemon method; it does not terminate unless an exception occurs or a ``stop_block`` is given. Args: stop_block (Optional[int]): Optionally set a future block number to stop at. Defaults to never-ending. required_confirmations (Optional[int]): The amount of confirmations to wait before yielding the block. The more confirmations, the less likely a reorg will occur. Defaults to the network's configured required confirmations. new_block_timeout (Optional[float]): The amount of time to wait for a new block before timing out. Defaults to 10 seconds for local networks or ``50 * block_time`` for live networks. Returns: Iterator[:class:`~ape.api.providers.BlockAPI`]
poll_blocks
python
ApeWorX/ape
src/ape/api/providers.py
https://github.com/ApeWorX/ape/blob/master/src/ape/api/providers.py
Apache-2.0
def poll_logs( # type: ignore[empty-body] self, stop_block: Optional[int] = None, address: Optional["AddressType"] = None, topics: Optional[list[Union[str, list[str]]]] = None, required_confirmations: Optional[int] = None, new_block_timeout: Optional[int] = None, events: Optional[list["EventABI"]] = 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}") Args: stop_block (Optional[int]): Optionally set a future block number to stop at. Defaults to never-ending. address (Optional[str]): The address of the contract to filter logs by. Defaults to all addresses. topics (Optional[list[Union[str, list[str]]]]): The topics to filter logs by. Defaults to all topics. required_confirmations (Optional[int]): The amount of confirmations to wait before yielding the block. The more confirmations, the less likely a reorg will occur. Defaults to the network's configured required confirmations. new_block_timeout (Optional[int]): The amount of time to wait for a new block before quitting. Defaults to 10 seconds for local networks or ``50 * block_time`` for live networks. events (Optional[list[``EventABI``]]): An optional list of events to listen on. Returns: Iterator[:class:`~ape.types.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}") Args: stop_block (Optional[int]): Optionally set a future block number to stop at. Defaults to never-ending. address (Optional[str]): The address of the contract to filter logs by. Defaults to all addresses. topics (Optional[list[Union[str, list[str]]]]): The topics to filter logs by. Defaults to all topics. required_confirmations (Optional[int]): The amount of confirmations to wait before yielding the block. The more confirmations, the less likely a reorg will occur. Defaults to the network's configured required confirmations. new_block_timeout (Optional[int]): The amount of time to wait for a new block before quitting. Defaults to 10 seconds for local networks or ``50 * block_time`` for live networks. events (Optional[list[``EventABI``]]): An optional list of events to listen on. Returns: Iterator[:class:`~ape.types.ContractLog`]
poll_logs
python
ApeWorX/ape
src/ape/api/providers.py
https://github.com/ApeWorX/ape/blob/master/src/ape/api/providers.py
Apache-2.0
def snapshot(self) -> "SnapshotID": """ Record the current state of the blockchain with intent to later call the method :meth:`~ape.managers.chain.ChainManager.revert` to go back to this point. This method is for local networks only. Returns: :class:`~ape.types.SnapshotID`: The snapshot ID. """
Record the current state of the blockchain with intent to later call the method :meth:`~ape.managers.chain.ChainManager.revert` to go back to this point. This method is for local networks only. Returns: :class:`~ape.types.SnapshotID`: The snapshot ID.
snapshot
python
ApeWorX/ape
src/ape/api/providers.py
https://github.com/ApeWorX/ape/blob/master/src/ape/api/providers.py
Apache-2.0
def restore(self, snapshot_id: "SnapshotID"): """ Regress the current call using the given snapshot ID. Allows developers to go back to a previous state. Args: snapshot_id (str): The snapshot ID. """
Regress the current call using the given snapshot ID. Allows developers to go back to a previous state. Args: snapshot_id (str): The snapshot ID.
restore
python
ApeWorX/ape
src/ape/api/providers.py
https://github.com/ApeWorX/ape/blob/master/src/ape/api/providers.py
Apache-2.0
def set_timestamp(self, new_timestamp: int): """ Change the pending timestamp. Args: new_timestamp (int): The timestamp to set. Returns: int: The new timestamp. """
Change the pending timestamp. Args: new_timestamp (int): The timestamp to set. Returns: int: The new timestamp.
set_timestamp
python
ApeWorX/ape
src/ape/api/providers.py
https://github.com/ApeWorX/ape/blob/master/src/ape/api/providers.py
Apache-2.0
def mine(self, num_blocks: int = 1): """ Advance by the given number of blocks. Args: num_blocks (int): The number of blocks allotted to mine. Defaults to ``1``. """
Advance by the given number of blocks. Args: num_blocks (int): The number of blocks allotted to mine. Defaults to ``1``.
mine
python
ApeWorX/ape
src/ape/api/providers.py
https://github.com/ApeWorX/ape/blob/master/src/ape/api/providers.py
Apache-2.0
def _increment_call_func_coverage_hit_count(self, txn: TransactionAPI): """ A helper method for incrementing a method call function hit count in a non-orthodox way. This is because Hardhat does not support call traces yet. """ if ( not txn.receiver or not self._test_runner or not self._test_runner.config_wrapper.track_coverage ): return if not (contract_type := self.chain_manager.contracts.get(txn.receiver)) or not ( contract_src := self.local_project._create_contract_source(contract_type) ): return method_id = txn.data[:4] if method_id in contract_type.view_methods: method = contract_type.methods[method_id] self._test_runner.coverage_tracker.hit_function(contract_src, method)
A helper method for incrementing a method call function hit count in a non-orthodox way. This is because Hardhat does not support call traces yet.
_increment_call_func_coverage_hit_count
python
ApeWorX/ape
src/ape/api/providers.py
https://github.com/ApeWorX/ape/blob/master/src/ape/api/providers.py
Apache-2.0
def build_command(self) -> list[str]: """ Get the command as a list of ``str``. Subclasses should override and add command arguments if needed. Returns: list[str]: The command to pass to ``subprocess.Popen``. """
Get the command as a list of ``str``. Subclasses should override and add command arguments if needed. Returns: list[str]: The command to pass to ``subprocess.Popen``.
build_command
python
ApeWorX/ape
src/ape/api/providers.py
https://github.com/ApeWorX/ape/blob/master/src/ape/api/providers.py
Apache-2.0
def connect(self): """ Start the process and connect to it. Subclasses handle the connection-related tasks. """ if self.is_connected: raise ProviderError("Cannot connect twice. Call disconnect before connecting again.") # Always disconnect after, # unless running tests with `disconnect_providers_after: false`. disconnect_after = ( self._test_runner is None or self.config_manager.get_config("test").disconnect_providers_after ) if disconnect_after: atexit.register(self._disconnect_atexit) # Register handlers to ensure atexit handlers are called when Python dies. def _signal_handler(signum, frame): atexit._run_exitfuncs() sys.exit(143 if signum == SIGTERM else 130) signal(SIGINT, _signal_handler) signal(SIGTERM, _signal_handler)
Start the process and connect to it. Subclasses handle the connection-related tasks.
connect
python
ApeWorX/ape
src/ape/api/providers.py
https://github.com/ApeWorX/ape/blob/master/src/ape/api/providers.py
Apache-2.0
def disconnect(self): """ Stop the process if it exists. Subclasses override this method to do provider-specific disconnection tasks. """ if self.process: self.stop() # Delete entry from managed list of running nodes. self.network_manager.running_nodes.remove_provider(self)
Stop the process if it exists. Subclasses override this method to do provider-specific disconnection tasks.
disconnect
python
ApeWorX/ape
src/ape/api/providers.py
https://github.com/ApeWorX/ape/blob/master/src/ape/api/providers.py
Apache-2.0
def start(self, timeout: int = 20): """Start the process and wait for its RPC to be ready.""" if self.is_connected: logger.info(f"Connecting to existing '{self.process_name}' process.") self.process = None # Not managing the process. elif self.allow_start: logger.info(f"Starting '{self.process_name}' process.") pre_exec_fn = _linux_set_death_signal if platform.uname().system == "Linux" else None self.stderr_queue = JoinableQueue() self.stdout_queue = JoinableQueue() if self.background or logger.level > LogLevel.DEBUG: out_file = DEVNULL else: out_file = PIPE cmd = self.build_command() process = popen(cmd, preexec_fn=pre_exec_fn, stdout=out_file, stderr=out_file) self.process = process spawn(self.produce_stdout_queue) spawn(self.produce_stderr_queue) spawn(self.consume_stdout_queue) spawn(self.consume_stderr_queue) # Cache the process so we can manage it even if lost. self.network_manager.running_nodes.cache_provider(self) with RPCTimeoutError(self, seconds=timeout) as _timeout: while True: if self.is_connected: break time.sleep(0.1) _timeout.check() else: raise ProviderError("Process not started and cannot connect to existing process.")
Start the process and wait for its RPC to be ready.
start
python
ApeWorX/ape
src/ape/api/providers.py
https://github.com/ApeWorX/ape/blob/master/src/ape/api/providers.py
Apache-2.0
def _windows_taskkill(self) -> None: """ Kills the given process and all child processes using taskkill.exe. Used for subprocesses started up on Windows which run in a cmd.exe wrapper that doesn't propagate signals by default (leaving orphaned processes). """ process = self.process if not process: return taskkill_bin = shutil.which("taskkill") if not taskkill_bin: raise SubprocessError("Could not find taskkill.exe executable.") proc = Popen( [ taskkill_bin, "/F", # forcefully terminate "/T", # terminate child processes "/PID", str(process.pid), ] ) proc.wait(timeout=self.PROCESS_WAIT_TIMEOUT)
Kills the given process and all child processes using taskkill.exe. Used for subprocesses started up on Windows which run in a cmd.exe wrapper that doesn't propagate signals by default (leaving orphaned processes).
_windows_taskkill
python
ApeWorX/ape
src/ape/api/providers.py
https://github.com/ApeWorX/ape/blob/master/src/ape/api/providers.py
Apache-2.0
def _linux_set_death_signal(): """ Automatically sends SIGTERM to child subprocesses when parent process dies (only usable on Linux). """ # from: https://stackoverflow.com/a/43152455/75956 # the first argument, 1, is the flag for PR_SET_PDEATHSIG # the second argument is what signal to send to child subprocesses libc = ctypes.CDLL("libc.so.6") return libc.prctl(1, SIGTERM)
Automatically sends SIGTERM to child subprocesses when parent process dies (only usable on Linux).
_linux_set_death_signal
python
ApeWorX/ape
src/ape/api/providers.py
https://github.com/ApeWorX/ape/blob/master/src/ape/api/providers.py
Apache-2.0
def from_receipt(cls, receipt: ReceiptAPI) -> "ContractCreation": """ Create a metadata class. Args: receipt (:class:`~ape.api.transactions.ReceiptAPI`): The receipt of the deploy transaction. Returns: :class:`~ape.api.query.ContractCreation` """ return cls( txn_hash=receipt.txn_hash, block=receipt.block_number, deployer=receipt.sender, # factory is not detected since this is meant for eoa deployments )
Create a metadata class. Args: receipt (:class:`~ape.api.transactions.ReceiptAPI`): The receipt of the deploy transaction. Returns: :class:`~ape.api.query.ContractCreation`
from_receipt
python
ApeWorX/ape
src/ape/api/query.py
https://github.com/ApeWorX/ape/blob/master/src/ape/api/query.py
Apache-2.0
def estimate_query(self, query: QueryType) -> 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. Args: query (``QueryType``): Query to estimate. Returns: Optional[int]: Represents milliseconds, returns ``None`` if unable to execute. """
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. Args: query (``QueryType``): Query to estimate. Returns: Optional[int]: Represents milliseconds, returns ``None`` if unable to execute.
estimate_query
python
ApeWorX/ape
src/ape/api/query.py
https://github.com/ApeWorX/ape/blob/master/src/ape/api/query.py
Apache-2.0
def perform_query(self, query: QueryType) -> Iterator: """ Executes the query using best performing ``estimate_query`` query engine. Args: query (``QueryType``): query to execute Returns: Iterator """
Executes the query using best performing ``estimate_query`` query engine. Args: query (``QueryType``): query to execute Returns: Iterator
perform_query
python
ApeWorX/ape
src/ape/api/query.py
https://github.com/ApeWorX/ape/blob/master/src/ape/api/query.py
Apache-2.0
def update_cache(self, query: QueryType, 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. Args: query (``QueryType``): query that was executed result (``Iterator``): the result of the query """
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. Args: query (``QueryType``): query that was executed result (``Iterator``): the result of the query
update_cache
python
ApeWorX/ape
src/ape/api/query.py
https://github.com/ApeWorX/ape/blob/master/src/ape/api/query.py
Apache-2.0
def return_value(self) -> Any: """ The return value deduced from the trace. """
The return value deduced from the trace.
return_value
python
ApeWorX/ape
src/ape/api/trace.py
https://github.com/ApeWorX/ape/blob/master/src/ape/api/trace.py
Apache-2.0
def revert_message(self) -> Optional[str]: """ The revert message deduced from the trace. """
The revert message deduced from the trace.
revert_message
python
ApeWorX/ape
src/ape/api/trace.py
https://github.com/ApeWorX/ape/blob/master/src/ape/api/trace.py
Apache-2.0
def get_raw_frames(self) -> Iterator[dict]: """ Get raw trace frames for deeper analysis. """
Get raw trace frames for deeper analysis.
get_raw_frames
python
ApeWorX/ape
src/ape/api/trace.py
https://github.com/ApeWorX/ape/blob/master/src/ape/api/trace.py
Apache-2.0
def get_raw_calltree(self) -> dict: """ Get a raw calltree for deeper analysis. """
Get a raw calltree for deeper analysis.
get_raw_calltree
python
ApeWorX/ape
src/ape/api/trace.py
https://github.com/ApeWorX/ape/blob/master/src/ape/api/trace.py
Apache-2.0
def txn_hash(self) -> HexBytes: """ The calculated hash of the transaction. """
The calculated hash of the transaction.
txn_hash
python
ApeWorX/ape
src/ape/api/transactions.py
https://github.com/ApeWorX/ape/blob/master/src/ape/api/transactions.py
Apache-2.0
def receipt(self) -> Optional["ReceiptAPI"]: """ This transaction's associated published receipt, if it exists. """ try: txn_hash = to_hex(self.txn_hash) except SignatureError: return None try: return self.chain_manager.get_receipt(txn_hash) except (TransactionNotFoundError, ProviderNotConnectedError): return None
This transaction's associated published receipt, if it exists.
receipt
python
ApeWorX/ape
src/ape/api/transactions.py
https://github.com/ApeWorX/ape/blob/master/src/ape/api/transactions.py
Apache-2.0
def to_string(self, calldata_repr: Optional["CalldataRepr"] = None) -> str: """ Get the stringified representation of the transaction. Args: calldata_repr (:class:`~ape.types.abi.CalldataRepr` | None): Pass "full" to see the full calldata. Defaults to the value from the config. Returns: str """ data = self.model_dump(mode="json") # JSON mode used for style purposes. if calldata_repr is None: # If was not specified, use the default value from the config. calldata_repr = self.local_project.config.display.calldata # Ellide the transaction calldata for abridged representations if the length exceeds 8 # (4 bytes for function selector and trailing 4 bytes). calldata = HexBytes(data["data"]) data["data"] = ( calldata[:4].to_0x_hex() + "..." + calldata[-4:].hex() if calldata_repr == "abridged" and len(calldata) > 8 else calldata.to_0x_hex() ) params = "\n ".join(f"{k}: {v}" for k, v in data.items()) cls_name = getattr(type(self), "__name__", TransactionAPI.__name__) return f"{cls_name}:\n {params}"
Get the stringified representation of the transaction. Args: calldata_repr (:class:`~ape.types.abi.CalldataRepr` | None): Pass "full" to see the full calldata. Defaults to the value from the config. Returns: str
to_string
python
ApeWorX/ape
src/ape/api/transactions.py
https://github.com/ApeWorX/ape/blob/master/src/ape/api/transactions.py
Apache-2.0
def total_fees_paid(self) -> int: """ The total amount of fees paid for the transaction. """
The total amount of fees paid for the transaction.
total_fees_paid
python
ApeWorX/ape
src/ape/api/transactions.py
https://github.com/ApeWorX/ape/blob/master/src/ape/api/transactions.py
Apache-2.0
def decode_logs( self, abi: Optional[ Union[list[Union["EventABI", "ContractEvent"]], Union["EventABI", "ContractEvent"]] ] = None, ) -> "ContractLogContainer": """ Decode the logs on the receipt. Args: abi (``EventABI``): The ABI of the event to decode into logs. Returns: list[:class:`~ape.types.ContractLog`] """
Decode the logs on the receipt. Args: abi (``EventABI``): The ABI of the event to decode into logs. Returns: list[:class:`~ape.types.ContractLog`]
decode_logs
python
ApeWorX/ape
src/ape/api/transactions.py
https://github.com/ApeWorX/ape/blob/master/src/ape/api/transactions.py
Apache-2.0
def raise_for_status(self) -> Optional[NoReturn]: """ Handle provider-specific errors regarding a non-successful :class:`~api.providers.TransactionStatusEnum`. """
Handle provider-specific errors regarding a non-successful :class:`~api.providers.TransactionStatusEnum`.
raise_for_status
python
ApeWorX/ape
src/ape/api/transactions.py
https://github.com/ApeWorX/ape/blob/master/src/ape/api/transactions.py
Apache-2.0
def await_confirmations(self) -> "ReceiptAPI": """ Wait for a transaction to be considered confirmed. Returns: :class:`~ape.api.ReceiptAPI`: The receipt that is now confirmed. """ # NOTE: Even when required_confirmations is `0`, we want to wait for the nonce to # increment. Otherwise, users may end up with invalid nonce errors in tests. self._await_sender_nonce_increment() if self.required_confirmations == 0 or self._check_error_status() or self.confirmed: return self # Confirming now. self._log_submission() self._await_confirmations() return self
Wait for a transaction to be considered confirmed. Returns: :class:`~ape.api.ReceiptAPI`: The receipt that is now confirmed.
await_confirmations
python
ApeWorX/ape
src/ape/api/transactions.py
https://github.com/ApeWorX/ape/blob/master/src/ape/api/transactions.py
Apache-2.0
def return_value(self) -> Any: """ Obtain the final return value of the call. Requires tracing to function, since this is not available from the receipt object. """ if trace := self.trace: ret_val = trace.return_value return ret_val[0] if isinstance(ret_val, tuple) and len(ret_val) == 1 else ret_val return None
Obtain the final return value of the call. Requires tracing to function, since this is not available from the receipt object.
return_value
python
ApeWorX/ape
src/ape/api/transactions.py
https://github.com/ApeWorX/ape/blob/master/src/ape/api/transactions.py
Apache-2.0
def source_traceback(self) -> "SourceTraceback": # type: ignore[empty-body] """ A Pythonic style traceback for both failing and non-failing receipts. Requires a provider that implements :meth:~ape.api.providers.ProviderAPI.get_transaction_trace`. """
A Pythonic style traceback for both failing and non-failing receipts. Requires a provider that implements :meth:~ape.api.providers.ProviderAPI.get_transaction_trace`.
source_traceback
python
ApeWorX/ape
src/ape/api/transactions.py
https://github.com/ApeWorX/ape/blob/master/src/ape/api/transactions.py
Apache-2.0
def show_trace(self, verbose: bool = False, file: IO[str] = sys.stdout): """ Display the complete sequence of contracts and methods called during the transaction. Args: verbose (bool): Set to ``True`` to include more information. file (IO[str]): The file to send output to. Defaults to stdout. """
Display the complete sequence of contracts and methods called during the transaction. Args: verbose (bool): Set to ``True`` to include more information. file (IO[str]): The file to send output to. Defaults to stdout.
show_trace
python
ApeWorX/ape
src/ape/api/transactions.py
https://github.com/ApeWorX/ape/blob/master/src/ape/api/transactions.py
Apache-2.0
def show_gas_report(self, file: IO[str] = sys.stdout): """ Display a gas report for the calls made in this transaction. """
Display a gas report for the calls made in this transaction.
show_gas_report
python
ApeWorX/ape
src/ape/api/transactions.py
https://github.com/ApeWorX/ape/blob/master/src/ape/api/transactions.py
Apache-2.0
def show_source_traceback(self): """ Show a receipt traceback mapping to lines in the source code. Only works when the contract type and source code are both available, like in local projects. """
Show a receipt traceback mapping to lines in the source code. Only works when the contract type and source code are both available, like in local projects.
show_source_traceback
python
ApeWorX/ape
src/ape/api/transactions.py
https://github.com/ApeWorX/ape/blob/master/src/ape/api/transactions.py
Apache-2.0
def show_events(self): """ Show the events from the receipt. """
Show the events from the receipt.
show_events
python
ApeWorX/ape
src/ape/api/transactions.py
https://github.com/ApeWorX/ape/blob/master/src/ape/api/transactions.py
Apache-2.0
def non_existing_alias_argument(**kwargs): """ A ``click.argument`` for an account alias that does not yet exist in ape. Args: **kwargs: click.argument overrides. """ callback = kwargs.pop("callback", _alias_callback) return click.argument("alias", callback=callback, **kwargs)
A ``click.argument`` for an account alias that does not yet exist in ape. Args: **kwargs: click.argument overrides.
non_existing_alias_argument
python
ApeWorX/ape
src/ape/cli/arguments.py
https://github.com/ApeWorX/ape/blob/master/src/ape/cli/arguments.py
Apache-2.0
def callback(cls, ctx, param, value) -> set[Path]: """ Use this for click.option / argument callbacks. """ project = ctx.params.get("project") return cls(value, project=project).filtered_paths
Use this for click.option / argument callbacks.
callback
python
ApeWorX/ape
src/ape/cli/arguments.py
https://github.com/ApeWorX/ape/blob/master/src/ape/cli/arguments.py
Apache-2.0
def filtered_paths(self) -> set[Path]: """ Get the filtered set of paths. """ value = self.value contract_paths: Iterable[Path] if value and isinstance(value, (Path, str)): # Given single path. contract_paths = (Path(value),) elif not value or value == "*": # Get all file paths in the project. return {p for p in self.project.sources.paths} elif isinstance(value, Iterable): contract_paths = value else: raise BadArgumentUsage(f"Not a path or iter[Path]: {value}") # Convert source IDs or relative paths to absolute paths. path_set = self.lookup(contract_paths) # Handle missing compilers. if self.missing_compilers: # Craft a nice message for all missing compilers. missing_ext = ", ".join(sorted(self.missing_compilers)) message = ( f"Missing compilers for the following file types: '{missing_ext}'. " "Possibly, a compiler plugin is not installed or is " "installed but not loading correctly." ) if ".vy" in self.missing_compilers: message = f"{message} Is 'ape-vyper' installed?" if ".sol" in self.missing_compilers: message = f"{message} Is 'ape-solidity' installed?" logger.warning(message) return path_set
Get the filtered set of paths.
filtered_paths
python
ApeWorX/ape
src/ape/cli/arguments.py
https://github.com/ApeWorX/ape/blob/master/src/ape/cli/arguments.py
Apache-2.0
def print_choices(self): """ Echo the choices to the terminal. """ choices = dict(enumerate(self.choices, 0)) did_print = False for idx, choice in choices.items(): click.echo(f"{idx}. {choice}") did_print = True if did_print: click.echo()
Echo the choices to the terminal.
print_choices
python
ApeWorX/ape
src/ape/cli/choices.py
https://github.com/ApeWorX/ape/blob/master/src/ape/cli/choices.py
Apache-2.0
def select_account( prompt_message: Optional[str] = None, key: _ACCOUNT_TYPE_FILTER = None ) -> "AccountAPI": """ Prompt the user to pick from their accounts and return that account. Use this method if you want to prompt users to select accounts _outside_ of CLI options. For CLI options, use :meth:`~ape.cli.options.account_option`. Args: prompt_message (Optional[str]): Customize the prompt message. key (Union[None, type[AccountAPI], Callable[[AccountAPI], bool]]): If given, the user may only select a matching account. You can provide a list of accounts, an account class type, or a callable for filtering the accounts. Returns: :class:`~ape.api.accounts.AccountAPI` """ from ape.api.accounts import AccountAPI if key and isinstance(key, type) and not issubclass(key, AccountAPI): raise AccountsError(f"Cannot return accounts with type '{key}'.") prompt = AccountAliasPromptChoice(prompt_message=prompt_message, key=key) return prompt.select_account()
Prompt the user to pick from their accounts and return that account. Use this method if you want to prompt users to select accounts _outside_ of CLI options. For CLI options, use :meth:`~ape.cli.options.account_option`. Args: prompt_message (Optional[str]): Customize the prompt message. key (Union[None, type[AccountAPI], Callable[[AccountAPI], bool]]): If given, the user may only select a matching account. You can provide a list of accounts, an account class type, or a callable for filtering the accounts. Returns: :class:`~ape.api.accounts.AccountAPI`
select_account
python
ApeWorX/ape
src/ape/cli/choices.py
https://github.com/ApeWorX/ape/blob/master/src/ape/cli/choices.py
Apache-2.0
def select_account(self) -> "AccountAPI": """ Returns the selected account. Returns: :class:`~ape.api.accounts.AccountAPI` """ from ape.utils.basemodel import ManagerAccessMixin as access accounts = access.account_manager if not self.choices or len(self.choices) == 0: raise AccountsError("No accounts found.") elif len(self.choices) == 1 and self.choices[0].startswith("TEST::"): return accounts.test_accounts[int(self.choices[0].replace("TEST::", ""))] elif len(self.choices) == 1: return accounts.load(self.choices[0]) self.print_choices() return click.prompt(self._prompt_message, type=self)
Returns the selected account. Returns: :class:`~ape.api.accounts.AccountAPI`
select_account
python
ApeWorX/ape
src/ape/cli/choices.py
https://github.com/ApeWorX/ape/blob/master/src/ape/cli/choices.py
Apache-2.0
def abort(msg: str, base_error: Optional[Exception] = None) -> NoReturn: """ End execution of the current command invocation. Args: msg (str): A message to output to the terminal. base_error (Exception, optional): Optionally provide an error to preserve the exception stack. """ if base_error: logger.error(msg) raise Abort(msg) from base_error raise Abort(msg)
End execution of the current command invocation. Args: msg (str): A message to output to the terminal. base_error (Exception, optional): Optionally provide an error to preserve the exception stack.
abort
python
ApeWorX/ape
src/ape/cli/options.py
https://github.com/ApeWorX/ape/blob/master/src/ape/cli/options.py
Apache-2.0
def verbosity_option( cli_logger: Optional[ApeLogger] = None, default: Optional[Union[str, int, LogLevel]] = None, callback: Optional[Callable] = None, **kwargs, ) -> Callable: """A decorator that adds a `--verbosity, -v` option to the decorated command. Args: cli_logger (:class:`~ape.logging.ApeLogger` | None): Optionally pass a custom logger object. default (str | int | :class:`~ape.logging.LogLevel`): The default log-level for this command. callback (Callable | None): A callback handler for passed-in verbosity values. **kwargs: Additional click overrides. Returns: click option """ _logger = cli_logger or logger default = logger.level if default is None else default kwarguments = _create_verbosity_kwargs( _logger=_logger, default=default, callback=callback, **kwargs ) return lambda f: click.option(*_VERBOSITY_VALUES, **kwarguments)(f)
A decorator that adds a `--verbosity, -v` option to the decorated command. Args: cli_logger (:class:`~ape.logging.ApeLogger` | None): Optionally pass a custom logger object. default (str | int | :class:`~ape.logging.LogLevel`): The default log-level for this command. callback (Callable | None): A callback handler for passed-in verbosity values. **kwargs: Additional click overrides. Returns: click option
verbosity_option
python
ApeWorX/ape
src/ape/cli/options.py
https://github.com/ApeWorX/ape/blob/master/src/ape/cli/options.py
Apache-2.0
def ape_cli_context( default_log_level: Optional[Union[str, int, LogLevel]] = None, obj_type: type = ApeCliContextObject, ) -> Callable: """ A ``click`` context object with helpful utilities. Use in your commands to get access to common utility features, such as logging or accessing managers. Args: default_log_level (str | int | :class:`~ape.logging.LogLevel` | None): The log-level value to pass to :meth:`~ape.cli.options.verbosity_option`. obj_type (Type): The context object type. Defaults to :class:`~ape.cli.options.ApeCliContextObject`. Sub-class the context to extend its functionality in your CLIs, such as if you want to add additional manager classes to the context. Returns: click option """ default_log_level = logger.level if default_log_level is None else default_log_level def decorator(f): f = verbosity_option(logger, default=default_log_level)(f) f = click.make_pass_decorator(obj_type, ensure=True)(f) return f return decorator
A ``click`` context object with helpful utilities. Use in your commands to get access to common utility features, such as logging or accessing managers. Args: default_log_level (str | int | :class:`~ape.logging.LogLevel` | None): The log-level value to pass to :meth:`~ape.cli.options.verbosity_option`. obj_type (Type): The context object type. Defaults to :class:`~ape.cli.options.ApeCliContextObject`. Sub-class the context to extend its functionality in your CLIs, such as if you want to add additional manager classes to the context. Returns: click option
ape_cli_context
python
ApeWorX/ape
src/ape/cli/options.py
https://github.com/ApeWorX/ape/blob/master/src/ape/cli/options.py
Apache-2.0
def network_option( default: Optional[Union[str, Callable]] = "auto", ecosystem: Optional[Union[list[str], str]] = None, network: Optional[Union[list[str], str]] = None, provider: Optional[Union[list[str], str]] = None, required: bool = False, **kwargs, ) -> Callable: """ A ``click.option`` for specifying a network. Args: default (Optional[str]): Optionally, change which network to use as the default. Defaults to how ``ape`` normally selects a default network unless ``required=True``, then defaults to ``None``. ecosystem (Optional[Union[list[str], str]]): Filter the options by ecosystem. Defaults to getting all ecosystems. network (Optional[Union[list[str], str]]): Filter the options by network. Defaults to getting all networks in ecosystems. provider (Optional[Union[list[str], str]]): Filter the options by provider. Defaults to getting all providers in networks. required (bool): Whether the option is required. Defaults to ``False``. When set to ``True``, the default value is ``None``. kwargs: Additional overrides to ``click.option``. """ def decorator(f): # These are the available network object names you can request. network_object_names = ("ecosystem", "network", "provider") requested_network_objects = _get_requested_networks(f, network_object_names) # When using network_option, handle parsing now so we can pass to # callback outside of command context. user_callback = kwargs.pop("callback", None) def callback(ctx, param, value): keep_as_choice_str = param.type.base_type is str try: provider_obj = _get_provider(value, default, keep_as_choice_str) except Exception as err: raise click.BadOptionUsage("--network", str(err), ctx) if provider_obj: _update_context_with_network(ctx, provider_obj, requested_network_objects) elif keep_as_choice_str: # Add raw choice to object context. ctx.obj = ctx.obj or {} ctx.params = ctx.params or {} ctx.obj["network"] = value ctx.params["network"] = value # else: provider is None, meaning not connected intentionally. return value if user_callback is None else user_callback(ctx, param, value) wrapped_f = _wrap_network_function(network_object_names, requested_network_objects, f) # Use NetworkChoice option. kwargs["type"] = None # Set this to false to avoid click passing in a str value for network. # This happens with `kwargs["type"] = None` and we are already handling # `network` via the partial. kwargs["expose_value"] = False # The callback will set any requests values in the command. kwargs["callback"] = callback # Create the actual option. return click.option( default=default, ecosystem=ecosystem, network=network, provider=provider, required=required, cls=NetworkOption, **kwargs, )(wrapped_f) return decorator
A ``click.option`` for specifying a network. Args: default (Optional[str]): Optionally, change which network to use as the default. Defaults to how ``ape`` normally selects a default network unless ``required=True``, then defaults to ``None``. ecosystem (Optional[Union[list[str], str]]): Filter the options by ecosystem. Defaults to getting all ecosystems. network (Optional[Union[list[str], str]]): Filter the options by network. Defaults to getting all networks in ecosystems. provider (Optional[Union[list[str], str]]): Filter the options by provider. Defaults to getting all providers in networks. required (bool): Whether the option is required. Defaults to ``False``. When set to ``True``, the default value is ``None``. kwargs: Additional overrides to ``click.option``.
network_option
python
ApeWorX/ape
src/ape/cli/options.py
https://github.com/ApeWorX/ape/blob/master/src/ape/cli/options.py
Apache-2.0
def skip_confirmation_option(help="") -> Callable: """ A ``click.option`` for skipping confirmation (``--yes``). Args: help (str): CLI option help text. Defaults to ``""``. """ return click.option( "-y", "--yes", "skip_confirmation", default=False, is_flag=True, help=help, )
A ``click.option`` for skipping confirmation (``--yes``). Args: help (str): CLI option help text. Defaults to ``""``.
skip_confirmation_option
python
ApeWorX/ape
src/ape/cli/options.py
https://github.com/ApeWorX/ape/blob/master/src/ape/cli/options.py
Apache-2.0
def account_option(account_type: _ACCOUNT_TYPE_FILTER = None) -> Callable: """ A CLI option that accepts either the account alias or the account number. If not given anything, it will prompt the user to select an account. """ return click.option( "--account", type=AccountAliasPromptChoice(key=account_type), callback=_account_callback, )
A CLI option that accepts either the account alias or the account number. If not given anything, it will prompt the user to select an account.
account_option
python
ApeWorX/ape
src/ape/cli/options.py
https://github.com/ApeWorX/ape/blob/master/src/ape/cli/options.py
Apache-2.0
def contract_option(help=None, required=False, multiple=False) -> Callable: """ Contract(s) from the current project. If you pass ``multiple=True``, you will get a list of contract types from the callback. :class:`~ape.exceptions.ContractError`: In the callback when it fails to load the contracts. """ help = help or "The name of a contract in the current project" return click.option( "--contract", help=help, required=required, callback=_load_contracts, multiple=multiple )
Contract(s) from the current project. If you pass ``multiple=True``, you will get a list of contract types from the callback. :class:`~ape.exceptions.ContractError`: In the callback when it fails to load the contracts.
contract_option
python
ApeWorX/ape
src/ape/cli/options.py
https://github.com/ApeWorX/ape/blob/master/src/ape/cli/options.py
Apache-2.0
def output_format_option(default: OutputFormat = OutputFormat.TREE) -> Callable: """ A ``click.option`` for specifying a format to use when outputting data. Args: default (:class:`~ape.cli.choices.OutputFormat`): Defaults to ``TREE`` format. """ return click.option( "--format", "output_format", type=output_format_choice(), default=default.value, callback=lambda ctx, param, value: OutputFormat(value.upper()), )
A ``click.option`` for specifying a format to use when outputting data. Args: default (:class:`~ape.cli.choices.OutputFormat`): Defaults to ``TREE`` format.
output_format_option
python
ApeWorX/ape
src/ape/cli/options.py
https://github.com/ApeWorX/ape/blob/master/src/ape/cli/options.py
Apache-2.0
def incompatible_with(incompatible_opts) -> type[click.Option]: """ Factory for creating custom ``click.Option`` subclasses that enforce incompatibility with the option strings passed to this function. Usage example:: import click @click.command() @click.option("--option", cls=incompatible_with(["other_option"])) def cmd(option, other_option): .... """ if isinstance(incompatible_opts, str): incompatible_opts = [incompatible_opts] class IncompatibleOption(click.Option): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def handle_parse_result(self, ctx, opts, args): # if None it means we're in autocomplete mode and don't want to validate if ctx.obj is not None: found_incompatible = ", ".join( [f"--{opt.replace('_', '-')}" for opt in opts if opt in incompatible_opts] ) if self.name is not None and self.name in opts and found_incompatible: name = self.name.replace("_", "-") raise click.BadOptionUsage( option_name=self.name, message=f"'--{name}' can't be used with '{found_incompatible}'.", ) return super().handle_parse_result(ctx, opts, args) return IncompatibleOption
Factory for creating custom ``click.Option`` subclasses that enforce incompatibility with the option strings passed to this function. Usage example:: import click @click.command() @click.option("--option", cls=incompatible_with(["other_option"])) def cmd(option, other_option): ....
incompatible_with
python
ApeWorX/ape
src/ape/cli/options.py
https://github.com/ApeWorX/ape/blob/master/src/ape/cli/options.py
Apache-2.0
def _repr_pretty_(self, printer, cycle): """ Show the NatSpec of a Method in any IPython console (including ``ape console``). """ console = get_rich_console() output = self._get_info(enrich=True) or "\n".join(abi.signature for abi in self.abis) console.print(output)
Show the NatSpec of a Method in any IPython console (including ``ape console``).
_repr_pretty_
python
ApeWorX/ape
src/ape/contracts/base.py
https://github.com/ApeWorX/ape/blob/master/src/ape/contracts/base.py
Apache-2.0
def estimate_gas_cost(self, *args, **kwargs) -> int: """ Get the estimated gas cost (according to the provider) for the contract method call (as if it were a transaction). Args: *args: The contract method invocation arguments. **kwargs: Transaction kwargs, such as value or sender. Returns: int: The estimated cost of gas to execute the transaction reported in the fee-currency's smallest unit, e.g. Wei. """ selected_abi = _select_method_abi(self.abis, args) arguments = self.conversion_manager.convert_method_args(selected_abi, args) return self.transact.estimate_gas_cost(*arguments, **kwargs)
Get the estimated gas cost (according to the provider) for the contract method call (as if it were a transaction). Args: *args: The contract method invocation arguments. **kwargs: Transaction kwargs, such as value or sender. Returns: int: The estimated cost of gas to execute the transaction reported in the fee-currency's smallest unit, e.g. Wei.
estimate_gas_cost
python
ApeWorX/ape
src/ape/contracts/base.py
https://github.com/ApeWorX/ape/blob/master/src/ape/contracts/base.py
Apache-2.0
def as_transaction(self, *args, **kwargs) -> "TransactionAPI": """ Get a :class:`~ape.api.transactions.TransactionAPI` for this contract method invocation. This is useful for simulations or estimating fees without sending the transaction. Args: *args: The contract method invocation arguments. **kwargs: Transaction kwargs, such as value or sender. Returns: :class:`~ape.api.transactions.TransactionAPI` """ sign = kwargs.pop("sign", False) contract_transaction = self._as_transaction(*args) transaction = contract_transaction.serialize_transaction(*args, **kwargs) self.provider.prepare_transaction(transaction) if sender := kwargs.get("sender"): if isinstance(sender, AccountAPI): prepped_tx = sender.prepare_transaction(transaction) return (sender.sign_transaction(prepped_tx) or prepped_tx) if sign else prepped_tx return transaction
Get a :class:`~ape.api.transactions.TransactionAPI` for this contract method invocation. This is useful for simulations or estimating fees without sending the transaction. Args: *args: The contract method invocation arguments. **kwargs: Transaction kwargs, such as value or sender. Returns: :class:`~ape.api.transactions.TransactionAPI`
as_transaction
python
ApeWorX/ape
src/ape/contracts/base.py
https://github.com/ApeWorX/ape/blob/master/src/ape/contracts/base.py
Apache-2.0
def as_transaction_bytes(self, *args, **txn_kwargs) -> HexBytes: """ Get a signed serialized transaction. Returns: HexBytes: The serialized transaction """ txn_kwargs["sign"] = True tx = self.as_transaction(*args, **txn_kwargs) return tx.serialize_transaction()
Get a signed serialized transaction. Returns: HexBytes: The serialized transaction
as_transaction_bytes
python
ApeWorX/ape
src/ape/contracts/base.py
https://github.com/ApeWorX/ape/blob/master/src/ape/contracts/base.py
Apache-2.0
def estimate_gas_cost(self, *args, **kwargs) -> int: """ Get the estimated gas cost (according to the provider) for the contract method-invocation transaction. Args: *args: The contract method invocation arguments. **kwargs: Transaction kwargs, such as value or sender. Returns: int: The estimated cost of gas to execute the transaction reported in the fee-currency's smallest unit, e.g. Wei. """ selected_abi = _select_method_abi(self.abis, args) arguments = self.conversion_manager.convert_method_args(selected_abi, args) txn = self.as_transaction(*arguments, **kwargs) return self.provider.estimate_gas_cost(txn)
Get the estimated gas cost (according to the provider) for the contract method-invocation transaction. Args: *args: The contract method invocation arguments. **kwargs: Transaction kwargs, such as value or sender. Returns: int: The estimated cost of gas to execute the transaction reported in the fee-currency's smallest unit, e.g. Wei.
estimate_gas_cost
python
ApeWorX/ape
src/ape/contracts/base.py
https://github.com/ApeWorX/ape/blob/master/src/ape/contracts/base.py
Apache-2.0
def __getitem_int(self, index: int) -> ContractLog: """ Access events on the contract by the index of when they occurred. Args: index (int): The index such that ``0`` is the first log to have occurred and ``-1`` is the last. Returns: :class:`~ape.contracts.base.ContractLog` """ logs = self.provider.get_contract_logs(self.log_filter) try: if index == 0: return next(logs) elif index > 0: return next(islice(logs, index, index + 1)) else: return list(logs)[index] except (IndexError, StopIteration) as err: raise IndexError(f"No log at index '{index}' for event '{self.abi.name}'.") from err
Access events on the contract by the index of when they occurred. Args: index (int): The index such that ``0`` is the first log to have occurred and ``-1`` is the last. Returns: :class:`~ape.contracts.base.ContractLog`
__getitem_int
python
ApeWorX/ape
src/ape/contracts/base.py
https://github.com/ApeWorX/ape/blob/master/src/ape/contracts/base.py
Apache-2.0
def __getitem_slice(self, value: slice) -> list[ContractLog]: """ Access a slice of logs from this event. Args: value (slice): The range of log to get, e.g. ``[5:10]``. Returns: Iterator[:class:`~ape.contracts.base.ContractLog`] """ logs = self.provider.get_contract_logs(self.log_filter) return list(islice(logs, value.start, value.stop, value.step))
Access a slice of logs from this event. Args: value (slice): The range of log to get, e.g. ``[5:10]``. Returns: Iterator[:class:`~ape.contracts.base.ContractLog`]
__getitem_slice
python
ApeWorX/ape
src/ape/contracts/base.py
https://github.com/ApeWorX/ape/blob/master/src/ape/contracts/base.py
Apache-2.0
def __call__(self, *args: Any, **kwargs: Any) -> MockContractLog: """ Create a mock-instance of a log using this event ABI and the contract address. Args: *args: Positional arguments for the event. **kwargs: Key-word arguments for the event. Returns: :class:`~ape.types.events.MockContractLog` """ # Create a dictionary from the positional arguments event_args: dict[Any, Any] = dict(zip((ipt.name for ipt in self.abi.inputs), args)) if overlapping_keys := set(event_args).intersection(kwargs): raise ValueError( f"Overlapping keys found in arguments: '{', '.join(overlapping_keys)}'." ) # Update event_args with keyword arguments event_args.update(kwargs) # Check that event_args.keys() is a subset of the expected input names keys_given = set(event_args.keys()) keys_expected = {ipt.name for ipt in self.abi.inputs} if unknown_input_names := keys_given - keys_expected: message = "Unknown keys: " sections = [] for unknown in unknown_input_names: if matches := difflib.get_close_matches(unknown, keys_expected, n=1, cutoff=0.5): matches_str = ", ".join(matches) sections.append(f"{unknown} (did you mean: '{matches_str}'?)") else: sections.append(unknown) message = f"{message} '{', '.join(sections)}'" raise ValueError(message) # Convert the arguments using the conversion manager converted_args = {} ecosystem = self.provider.network.ecosystem parser = StructParser(self.abi) for key, value in event_args.items(): if value is None: continue input_abi = next(ipt for ipt in self.abi.inputs if ipt.name == key) py_type = ecosystem.get_python_types(input_abi) if isinstance(value, dict): ls_values = list(value.values()) converted_values = self.conversion_manager.convert(ls_values, py_type) converted_args[key] = parser.decode_input([converted_values]) elif isinstance(value, (list, tuple)): converted_args[key] = parser.decode_input(value) else: converted_args[key] = self.conversion_manager.convert(value, py_type) properties: dict = { "event_arguments": converted_args, "event_name": self.abi.name, } if hasattr(self.contract, "address"): # Only address if this is off an instance. properties["contract_address"] = self.contract.address return MockContractLog(**properties)
Create a mock-instance of a log using this event ABI and the contract address. Args: *args: Positional arguments for the event. **kwargs: Key-word arguments for the event. Returns: :class:`~ape.types.events.MockContractLog`
__call__
python
ApeWorX/ape
src/ape/contracts/base.py
https://github.com/ApeWorX/ape/blob/master/src/ape/contracts/base.py
Apache-2.0
def query( self, *columns: str, start_block: int = 0, stop_block: Optional[int] = None, step: int = 1, engine_to_use: Optional[str] = None, ) -> "DataFrame": """ Iterate through blocks for log events Args: *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 """ # perf: pandas import is really slow. Avoid importing at module level. import pandas as pd HEAD = self.chain_manager.blocks.height if start_block < 0: start_block = HEAD + start_block if stop_block is None: stop_block = HEAD elif stop_block < 0: stop_block = HEAD + stop_block elif stop_block > HEAD: raise ChainError( f"'stop={stop_block}' cannot be greater than the chain length ({HEAD})." ) query: dict = { "columns": (list(ContractLog.__pydantic_fields__) if columns[0] == "*" else columns), "event": self.abi, "start_block": start_block, "stop_block": stop_block, "step": step, } if hasattr(self.contract, "address"): # Only query for a specific contract when checking an instance. query["contract"] = self.contract.address contract_event_query = ContractEventQuery(**query) contract_events = self.query_manager.query( contract_event_query, engine_to_use=engine_to_use ) columns_ls = validate_and_expand_columns(columns, ContractLog) data = map(partial(extract_fields, columns=columns_ls), contract_events) return pd.DataFrame(columns=columns_ls, data=data)
Iterate through blocks for log events Args: *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
query
python
ApeWorX/ape
src/ape/contracts/base.py
https://github.com/ApeWorX/ape/blob/master/src/ape/contracts/base.py
Apache-2.0
def range( self, start_or_stop: int, stop: Optional[int] = None, search_topics: Optional[dict[str, Any]] = None, extra_addresses: Optional[list] = None, ) -> Iterator[ContractLog]: """ Search through the logs for this event using the given filter parameters. Args: 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[:class:`~ape.types.address.AddressType`]]): Additional contract addresses containing the same event type. Defaults to only looking at the contract instance where this event is defined. Returns: Iterator[:class:`~ape.contracts.base.ContractLog`] """ if not (contract_address := getattr(self.contract, "address", None)): return start_block = None stop_block = None HEAD = self.chain_manager.blocks.height # Current block height if stop is None: contract = None try: contract = self.chain_manager.contracts.instance_at(contract_address) except Exception: pass # Determine the start block from contract creation metadata if contract and (creation := contract.creation_metadata): start_block = creation.block # Handle single parameter usage (like Python's range(stop)) if start_or_stop == 0: # stop==0 is the same as stop==HEAD # because of the -1 (turns to negative). stop_block = HEAD + 1 elif start_or_stop >= 0: # Given like range(1) stop_block = min(start_or_stop - 1, HEAD) else: # Give like range(-1) stop_block = HEAD + start_or_stop elif start_or_stop is not None and stop is not None: # Handle cases where both start and stop are provided if start_or_stop >= 0: start_block = min(start_or_stop, HEAD) else: # Negative start relative to HEAD adjusted_value = HEAD + start_or_stop + 1 start_block = max(adjusted_value, 0) if stop == 0: # stop==0 is the same as stop==HEAD # because of the -1 (turns to negative). stop_block = HEAD elif stop > 0: # Positive stop, capped to the chain HEAD stop_block = min(stop - 1, HEAD) else: # Negative stop. adjusted_value = HEAD + stop stop_block = max(adjusted_value, 0) # Gather all addresses to query (contract and any extra ones provided) addresses = list(set([contract_address] + (extra_addresses or []))) # Construct the event query contract_event_query = ContractEventQuery( columns=list(ContractLog.__pydantic_fields__), # Ensure all necessary columns contract=addresses, event=self.abi, search_topics=search_topics, start_block=start_block or 0, # Default to block 0 if not set stop_block=stop_block, # None means query to the current HEAD ) # Execute the query and yield results yield from self.query_manager.query(contract_event_query) # type: ignore
Search through the logs for this event using the given filter parameters. Args: 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[:class:`~ape.types.address.AddressType`]]): Additional contract addresses containing the same event type. Defaults to only looking at the contract instance where this event is defined. Returns: Iterator[:class:`~ape.contracts.base.ContractLog`]
range
python
ApeWorX/ape
src/ape/contracts/base.py
https://github.com/ApeWorX/ape/blob/master/src/ape/contracts/base.py
Apache-2.0
def from_receipt(self, receipt: "ReceiptAPI") -> list[ContractLog]: """ Get all the events from the given receipt. Args: receipt (:class:`~ape.api.transactions.ReceiptAPI`): The receipt containing the logs. Returns: list[:class:`~ape.contracts.base.ContractLog`] """ ecosystem = self.provider.network.ecosystem # NOTE: Safe to use a list because a receipt should never have too many logs. return list( ecosystem.decode_logs( # NOTE: Filter out logs that do not match this address (if address available) # (okay to be empty list, since EcosystemAPI.decode_logs will return []) [ log for log in receipt.logs if log["address"] == getattr(self.contract, "address", log["address"]) ], self.abi, ) )
Get all the events from the given receipt. Args: receipt (:class:`~ape.api.transactions.ReceiptAPI`): The receipt containing the logs. Returns: list[:class:`~ape.contracts.base.ContractLog`]
from_receipt
python
ApeWorX/ape
src/ape/contracts/base.py
https://github.com/ApeWorX/ape/blob/master/src/ape/contracts/base.py
Apache-2.0
def poll_logs( self, start_block: Optional[int] = None, stop_block: Optional[int] = None, required_confirmations: Optional[int] = None, new_block_timeout: Optional[int] = None, search_topics: Optional[dict[str, Any]] = None, **search_topic_kwargs: dict[str, Any], ) -> Iterator[ContractLog]: """ Poll new logs for this event. Can specify topic filters to use when setting up the filter. 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(arg=1): print(f"New event log found: block_number={new_log.block_number}") Args: 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. search_topics (Optional[dict[str, Any]]): A dictionary of search topics to use when constructing a polling filter. Overrides the value of `**search_topics_kwargs`. search_topics_kwargs: Search topics to use when constructing a polling filter. Allows easily specifying topic filters using kwarg syntax but can be used w/ `search_topics` Returns: Iterator[:class:`~ape.types.ContractLog`] """ if required_confirmations is None: required_confirmations = self.provider.network.required_confirmations # NOTE: We process historical blocks separately here to minimize rpc calls height = max(self.chain_manager.blocks.height - required_confirmations, 0) if start_block and height > 0 and start_block < height: yield from self.range(start_block, height) start_block = height + 1 if search_topics: search_topic_kwargs.update(search_topics) topics = encode_topics(self.abi, search_topic_kwargs) if address := getattr(self.contract, "address", None): # NOTE: Now we process the rest yield from self.provider.poll_logs( stop_block=stop_block, address=address, required_confirmations=required_confirmations, new_block_timeout=new_block_timeout, events=[self.abi], topics=topics, )
Poll new logs for this event. Can specify topic filters to use when setting up the filter. 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(arg=1): print(f"New event log found: block_number={new_log.block_number}") Args: 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. search_topics (Optional[dict[str, Any]]): A dictionary of search topics to use when constructing a polling filter. Overrides the value of `**search_topics_kwargs`. search_topics_kwargs: Search topics to use when constructing a polling filter. Allows easily specifying topic filters using kwarg syntax but can be used w/ `search_topics` Returns: Iterator[:class:`~ape.types.ContractLog`]
poll_logs
python
ApeWorX/ape
src/ape/contracts/base.py
https://github.com/ApeWorX/ape/blob/master/src/ape/contracts/base.py
Apache-2.0
def __call__(self, *args, **kwargs) -> MockContractLog: """ Create a mock contract log using the first working ABI. Args: *args: Positional arguments for the event. **kwargs: Key-word arguments for the event. Returns: :class:`~ape.types.events.MockContractLog` """ # TODO: Use composite error. errors = [] for evt in self.events: try: return evt(*args, **kwargs) except ValueError as err: errors.append(err) continue # not a match error_str = ", ".join([f"{e}" for e in errors]) raise ValueError(f"Could not make a mock contract log. Errors: {error_str}")
Create a mock contract log using the first working ABI. Args: *args: Positional arguments for the event. **kwargs: Key-word arguments for the event. Returns: :class:`~ape.types.events.MockContractLog`
__call__
python
ApeWorX/ape
src/ape/contracts/base.py
https://github.com/ApeWorX/ape/blob/master/src/ape/contracts/base.py
Apache-2.0
def source_path(self) -> Optional[Path]: """ Returns the path to the local contract if determined that this container belongs to the active project by cross checking source_id. """ if not (source_id := self.contract_type.source_id): return None base = self.base_path or self.local_project.path path = base / source_id return path if path.is_file() else None
Returns the path to the local contract if determined that this container belongs to the active project by cross checking source_id.
source_path
python
ApeWorX/ape
src/ape/contracts/base.py
https://github.com/ApeWorX/ape/blob/master/src/ape/contracts/base.py
Apache-2.0