ape.types

Address

ape.types.address.AddressType

“A checksum address in Ape.”

alias of Annotated[ChecksumAddress, _AddressValidator]

ape.types.address.RawAddress

A raw data-type representation of an address.

alias of str | int | HashStr20 | HashBytes20

Signatures

class ape.types.signatures.SignableMessage(version: bytes, header: bytes, body: bytes)

Bases: NamedTuple

A message compatible with EIP-191 that is ready to be signed.

The properties are components of an EIP-191 signable message. Other message formats can be encoded into this format for easy signing. This data structure doesn’t need to know about the original message format. For example, you can think of EIP-712 as compiling down to an EIP-191 message.

In typical usage, you should never need to create these by hand. Instead, use one of the available encode_* methods in this module, like:

  • encode_structured_data()

  • encode_intended_validator()

  • encode_defunct()

  • encode_typed_data()

body: bytes

Alias for field number 2

header: bytes

Alias for field number 1

version: bytes

Alias for field number 0

class ape.types.signatures.MessageSignature(v: int, r: bytes, s: bytes)

Bases: _Signature

A ECDSA signature (vrs) of a message.

class ape.types.signatures.TransactionSignature(v: int, r: bytes, s: bytes)

Bases: _Signature

A ECDSA signature (vrs) of a transaction.

signatures.recover_signer(sig: MessageSignature) AddressType

Get the address of the signer.

Parameters:
Returns:

address of message signer.

Return type:

AddressType

Coverage

class ape.types.coverage.ContractCoverage(*, name: str, functions: list[FunctionCoverage] = [])

Bases: BaseModel

An individual contract’s coverage.

property function_hits: Annotated[int, Ge(ge=0)]

The number of functions with a hit counter greater than zero.

property function_rate: float

The rate of functions hit versus total functions.

functions: list[FunctionCoverage]

The coverage of each function individually.

property line_rate: float

The number of lines hit divided by number of lines.

property lines_covered: Annotated[int, Ge(ge=0)]

All lines that have a hit count greater than zero.

property lines_valid: Annotated[int, Ge(ge=0)]

The number of lines valid for coverage.

property miss_count: Annotated[int, Ge(ge=0)]

The number of lines missed.

model_dump(*args, **kwargs) dict

Usage docs: https://docs.pydantic.dev/2.10/concepts/serialization/#modelmodel_dump

Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.

Parameters:
  • mode – The mode in which to_python should run. If mode is ‘json’, the output will only contain JSON serializable types. If mode is ‘python’, the output may contain non-JSON-serializable Python objects.

  • include – A set of fields to include in the output.

  • exclude – A set of fields to exclude from the output.

  • context – Additional context to pass to the serializer.

  • by_alias – Whether to use the field’s alias in the dictionary key if defined.

  • exclude_unset – Whether to exclude fields that have not been explicitly set.

  • exclude_defaults – Whether to exclude fields that are set to their default value.

  • exclude_none – Whether to exclude fields that have a value of None.

  • round_trip – If True, dumped values should be valid as input for non-idempotent types such as Json[T].

  • warnings – How to handle serialization errors. False/”none” ignores them, True/”warn” logs errors, “error” raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].

  • serialize_as_any – Whether to serialize fields with duck-typing serialization behavior.

Returns:

A dictionary representation of the model.

name: str

The name of the contract.

property statements: list[CoverageStatement]

All valid coverage lines from every function in this contract.

class ape.types.coverage.ContractSourceCoverage(*, source_id: str, contracts: list[ContractCoverage] = [])

Bases: BaseModel

An individual source file with coverage collected.

contracts: list[ContractCoverage]

Coverage for each contract in the source file.

property function_hits: Annotated[int, Ge(ge=0)]

The number of functions with a hit counter greater than zero.

property function_rate: float

The rate of functions hit versus total functions.

include(contract_name: str) ContractCoverage

Ensure a contract is included in the report.

property line_rate: float

The number of lines hit divided by number of lines.

property lines_covered: Annotated[int, Ge(ge=0)]

All lines with a hit count greater than zero from every function in every contract in this source.

property lines_valid: Annotated[int, Ge(ge=0)]

The number of lines valid for coverage.

property miss_count: Annotated[int, Ge(ge=0)]

The number of lines missed.

model_dump(*args, **kwargs) dict

Usage docs: https://docs.pydantic.dev/2.10/concepts/serialization/#modelmodel_dump

Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.

Parameters:
  • mode – The mode in which to_python should run. If mode is ‘json’, the output will only contain JSON serializable types. If mode is ‘python’, the output may contain non-JSON-serializable Python objects.

  • include – A set of fields to include in the output.

  • exclude – A set of fields to exclude from the output.

  • context – Additional context to pass to the serializer.

  • by_alias – Whether to use the field’s alias in the dictionary key if defined.

  • exclude_unset – Whether to exclude fields that have not been explicitly set.

  • exclude_defaults – Whether to exclude fields that are set to their default value.

  • exclude_none – Whether to exclude fields that have a value of None.

  • round_trip – If True, dumped values should be valid as input for non-idempotent types such as Json[T].

  • warnings – How to handle serialization errors. False/”none” ignores them, True/”warn” logs errors, “error” raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].

  • serialize_as_any – Whether to serialize fields with duck-typing serialization behavior.

Returns:

A dictionary representation of the model.

source_id: str

The ID of the source covered.

property statements: list[CoverageStatement]

All valid coverage lines from every function in every contract in this source.

property total_functions: Annotated[int, Ge(ge=0)]

The total number of functions in this source.

class ape.types.coverage.CoverageProject(*, name: str, sources: list[ContractSourceCoverage] = [])

Bases: BaseModel

A project with coverage collected.

property function_hits: Annotated[int, Ge(ge=0)]

The number of functions with a hit counter greater than zero.

property function_rate: float

The rate of functions hit versus total functions.

property line_rate: float

The number of lines hit divided by number of lines.

property lines_covered: Annotated[int, Ge(ge=0)]

The number of lines with a hit count greater than zero from every function in every contract in every source in this this project.

property lines_valid: Annotated[int, Ge(ge=0)]

The number of lines valid for coverage.

property miss_count: Annotated[int, Ge(ge=0)]

The number of lines missed.

model_dump(*args, **kwargs) dict

Usage docs: https://docs.pydantic.dev/2.10/concepts/serialization/#modelmodel_dump

Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.

Parameters:
  • mode – The mode in which to_python should run. If mode is ‘json’, the output will only contain JSON serializable types. If mode is ‘python’, the output may contain non-JSON-serializable Python objects.

  • include – A set of fields to include in the output.

  • exclude – A set of fields to exclude from the output.

  • context – Additional context to pass to the serializer.

  • by_alias – Whether to use the field’s alias in the dictionary key if defined.

  • exclude_unset – Whether to exclude fields that have not been explicitly set.

  • exclude_defaults – Whether to exclude fields that are set to their default value.

  • exclude_none – Whether to exclude fields that have a value of None.

  • round_trip – If True, dumped values should be valid as input for non-idempotent types such as Json[T].

  • warnings – How to handle serialization errors. False/”none” ignores them, True/”warn” logs errors, “error” raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].

  • serialize_as_any – Whether to serialize fields with duck-typing serialization behavior.

Returns:

A dictionary representation of the model.

name: str

The name of the project being covered.

sources: list[ContractSourceCoverage]

Coverage for each source in the project.

property statements: list[CoverageStatement]

All valid coverage lines from every function in every contract in every source in this project.

property total_functions: Annotated[int, Ge(ge=0)]

The total number of functions in this source.

class ape.types.coverage.CoverageReport(*, source_folders: list[Path], timestamp: int, projects: list[CoverageProject] = [])

Bases: BaseModel

Coverage report schema inspired from coverage.py.

property function_hits: Annotated[int, Ge(ge=0)]

The number of functions with a hit counter greater than zero.

property function_rate: float

The rate of functions hit versus total functions.

get_html(verbose: bool = False) str

The coverage HTML report as a string.

get_xml() str

The coverage XML report as a string. The XML coverage data schema is meant to be compatible with codecov.io. Thus, some of coverage is modified slightly, and some of the naming conventions (based on 90s Java) won’t be super relevant to smart-contract projects.

property line_rate: float

The number of lines hit divided by number of lines.

property lines_covered: Annotated[int, Ge(ge=0)]

All lines with a hit count greater than zero from every function in every contract in every source in every project in this report.

property lines_valid: Annotated[int, Ge(ge=0)]

The number of lines valid for coverage.

property miss_count: Annotated[int, Ge(ge=0)]

The number of lines missed.

model_dump(*args, **kwargs) dict

Usage docs: https://docs.pydantic.dev/2.10/concepts/serialization/#modelmodel_dump

Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.

Parameters:
  • mode – The mode in which to_python should run. If mode is ‘json’, the output will only contain JSON serializable types. If mode is ‘python’, the output may contain non-JSON-serializable Python objects.

  • include – A set of fields to include in the output.

  • exclude – A set of fields to exclude from the output.

  • context – Additional context to pass to the serializer.

  • by_alias – Whether to use the field’s alias in the dictionary key if defined.

  • exclude_unset – Whether to exclude fields that have not been explicitly set.

  • exclude_defaults – Whether to exclude fields that are set to their default value.

  • exclude_none – Whether to exclude fields that have a value of None.

  • round_trip – If True, dumped values should be valid as input for non-idempotent types such as Json[T].

  • warnings – How to handle serialization errors. False/”none” ignores them, True/”warn” logs errors, “error” raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].

  • serialize_as_any – Whether to serialize fields with duck-typing serialization behavior.

Returns:

A dictionary representation of the model.

projects: list[CoverageProject]

Each project with individual coverage tracked.

source_folders: list[Path]

All source folders to use. This is needed for codecov.

property sources: list[str]

Every source ID in the report.

property statements: list[CoverageStatement]

All valid coverage lines from every function in every contract in every source from every project in this report.

timestamp: int

The timestamp the report was generated, in milliseconds.

property total_functions: Annotated[int, Ge(ge=0)]

The total number of functions in this source.

class ape.types.coverage.CoverageStatement(*, location: tuple[int, int, int, int] | None = None, pcs: set[int], hit_count: Annotated[int, Ge(ge=0)] = 0, tag: str | None = None)

Bases: BaseModel

An item that can get hit during coverage. Examples of coverage items are line segments, which are generally calculated from groupings of AST nodes occupying the same location, that can be tracked by their PC values. During a transaction’s trace, we find these values and we find the corresponding coverage item and increment the hit count. Another example of a coverage item is a compiler-builtin check, also marked by a PC value. If we encounter such PC in a trace, its hit count is incremented. Builtin compiler checks may or may not correspond to an actual location in the source code, depending on the type of check.

hit_count: Annotated[int, Ge(ge=0)]

The times this node was hit.

location: tuple[int, int, int, int] | None

The location of the item (line, column, endline, endcolumn). If multiple PCs share an exact location, it is only tracked as one.

pcs: set[int]

The PCs for this node.

tag: str | None

An additional tag to mark this statement with. This is useful if the location field is empty.

class ape.types.coverage.FunctionCoverage(*, name: str, full_name: str, statements: list[CoverageStatement] = [], hit_count: Annotated[int, Ge(ge=0)] = 0)

Bases: BaseModel

The individual coverage of a function defined in a smart contact.

full_name: str

The unique name of the function.

hit_count: Annotated[int, Ge(ge=0)]

The times this function was called. NOTE: This is needed as a separate data point since not all methods may have statements (such as auto-getters).

property line_rate: float

The number of lines hit divided by number of lines.

property lines_covered: Annotated[int, Ge(ge=0)]

The number of lines with a hit counter greater than zero in this method.

property lines_valid: Annotated[int, Ge(ge=0)]

All lines valid for coverage in this method.

property miss_count: Annotated[int, Ge(ge=0)]

The number of lines missed.

model_dump(*args, **kwargs) dict

Usage docs: https://docs.pydantic.dev/2.10/concepts/serialization/#modelmodel_dump

Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.

Parameters:
  • mode – The mode in which to_python should run. If mode is ‘json’, the output will only contain JSON serializable types. If mode is ‘python’, the output may contain non-JSON-serializable Python objects.

  • include – A set of fields to include in the output.

  • exclude – A set of fields to exclude from the output.

  • context – Additional context to pass to the serializer.

  • by_alias – Whether to use the field’s alias in the dictionary key if defined.

  • exclude_unset – Whether to exclude fields that have not been explicitly set.

  • exclude_defaults – Whether to exclude fields that are set to their default value.

  • exclude_none – Whether to exclude fields that have a value of None.

  • round_trip – If True, dumped values should be valid as input for non-idempotent types such as Json[T].

  • warnings – How to handle serialization errors. False/”none” ignores them, True/”warn” logs errors, “error” raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].

  • serialize_as_any – Whether to serialize fields with duck-typing serialization behavior.

Returns:

A dictionary representation of the model.

name: str

The display name of the function.

profile_statement(pc: int, location: tuple[int, int, int, int] | None = None, tag: str | None = None)

Initialize a statement in the coverage profile with a hit count starting at zero. This statement is ready to accumulate hits as tests execute.

Parameters:
  • pc (int) – The program counter of the statement.

  • location (Optional[ethpm_types.source.SourceStatement]) – The location of the statement, if it exists.

  • tag (Optional[str]) – Optionally provide more information about the statements being hit. This is useful for builtin statements that may be missing context otherwise.

statements: list[CoverageStatement]

For statement coverage, these are the individual items. See CoverageStatement for more details.

Events

class ape.types.events.ContractLog(*, event_name: str, contract_address: Annotated[ChecksumAddress, _AddressValidator] = '0x0000000000000000000000000000000000000000', event_arguments: dict[str, Any] = {}, transaction_hash: Any, block_number: Annotated[int, BeforeValidator(func=_hex_int_validator, json_schema_input_type=PydanticUndefined)], block_hash: Any, log_index: Annotated[int, BeforeValidator(func=_hex_int_validator, json_schema_input_type=PydanticUndefined)], transaction_index: Annotated[int, BeforeValidator(func=_hex_int_validator, json_schema_input_type=PydanticUndefined)] | None = None)

An instance of a log from a contract.

block_hash: Any

The hash of the block containing the transaction that produced this log.

block_number: Annotated[int, BeforeValidator(func=_hex_int_validator, json_schema_input_type=PydanticUndefined)]

The number of the block containing the transaction that produced this log.

log_index: Annotated[int, BeforeValidator(func=_hex_int_validator, json_schema_input_type=PydanticUndefined)]

The index of the log on the transaction.

property timestamp: int

The UNIX timestamp of when the event was emitted.

NOTE: This performs a block lookup.

transaction_hash: Any

The hash of the transaction containing this log.

transaction_index: Annotated[int, BeforeValidator(func=_hex_int_validator, json_schema_input_type=PydanticUndefined)] | None

The index of the transaction’s position when the log was created. Is None when from the pending block.

class ape.types.events.ContractLogContainer(iterable=(), /)

Container for ContractLogs which is adding capability of filtering logs

class ape.types.events.LogFilter(*, addresses: list[Annotated[ChecksumAddress, _AddressValidator]] = [], events: list[EventABI] = [], topic_filter: Sequence[HexStr | None | Sequence[HexStr | None]] = [], start_block: int = 0, stop_block: int | None = None, selectors: dict[str, EventABI] = {})
classmethod from_event(event: EventABI | ContractEvent, search_topics: dict[str, Any] | None = None, addresses: list[Annotated[ChecksumAddress, _AddressValidator]] | None = None, start_block=None, stop_block=None)

Construct a log filter from an event topic query.

model_dump(*args, **kwargs)

Usage docs: https://docs.pydantic.dev/2.10/concepts/serialization/#modelmodel_dump

Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.

Parameters:
  • mode – The mode in which to_python should run. If mode is ‘json’, the output will only contain JSON serializable types. If mode is ‘python’, the output may contain non-JSON-serializable Python objects.

  • include – A set of fields to include in the output.

  • exclude – A set of fields to exclude from the output.

  • context – Additional context to pass to the serializer.

  • by_alias – Whether to use the field’s alias in the dictionary key if defined.

  • exclude_unset – Whether to exclude fields that have not been explicitly set.

  • exclude_defaults – Whether to exclude fields that are set to their default value.

  • exclude_none – Whether to exclude fields that have a value of None.

  • round_trip – If True, dumped values should be valid as input for non-idempotent types such as Json[T].

  • warnings – How to handle serialization errors. False/”none” ignores them, True/”warn” logs errors, “error” raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].

  • serialize_as_any – Whether to serialize fields with duck-typing serialization behavior.

Returns:

A dictionary representation of the model.

class ape.types.events.MockContractLog(*, event_name: str, contract_address: Annotated[ChecksumAddress, _AddressValidator] = '0x0000000000000000000000000000000000000000', event_arguments: dict[str, Any] = {})

A mock version of the ContractLog class used for testing purposes. This class is designed to match a subset of event arguments in a ContractLog instance by only comparing those event arguments that the user explicitly provides.

Inherits from BaseContractLog, and overrides the equality method for custom comparison of event arguments between a MockContractLog and a ContractLog instance.

VM

ape.types.vm.BlockID

An ID that can match a block, such as the literals "earliest", "latest", or "pending" as well as a block number or hash (HexBytes).

alias of int | HexStr | HexBytes | Literal[‘earliest’, ‘latest’, ‘pending’]

ape.types.vm.SnapshotID

An ID representing a point in time on a blockchain, as used in the snapshot() and snapshot() methods. Can be a str, int, or bytes. Providers will expect and handle snapshot IDs differently. There shouldn’t be a need to change providers when using this feature, so there should not be confusion over this type in practical use cases.

alias of str | int | bytes

Gas

class ape.types.gas.AutoGasLimit(*, multiplier: float = 1.0)

Additional settings for gas_limit: auto.

multiplier: float

A multiplier to estimated gas.

ape.types.gas.GasLimit

A value you can give to Ape for handling gas-limit calculations. "auto" refers to automatically figuring out the gas, "max" refers to using the maximum block gas limit, and otherwise you can provide a numeric value.

alias of Literal[‘auto’, ‘max’] | int | str | AutoGasLimit

Trace

class ape.types.trace.ControlFlow(*, statements: list[Statement], closure: Closure, source_path: Path | None = None, depth: int)

A collection of linear source nodes up until a jump.

property begin_lineno: int | None

The first line number in the sequence.

closure: Closure

The defining closure, such as a function or module, of the code sequence.

depth: int

The depth at which this flow was executed, where 1 is the first calling function.

property end_lineno: int | None

The last line number.

extend(location: SourceLocation, pcs: set[int] | None = None, ws_start: int | None = None)

Extend this node’s content with other content that follows it directly.

Raises:

ValueError – When there is a gap in content.

Parameters:
  • location (SourceLocation) – The location of the content, in the form (lineno, col_offset, end_lineno, end_coloffset).

  • pcs (Optional[set[int]]) – The PC values of the statements.

  • ws_start (Optional[int]) – Optionally provide a white-space starting point to back-fill.

format(use_arrow: bool = True) str

Format this trace node into a string presentable to the user.

property line_numbers: list[int]

The list of all line numbers as part of this node.

property next_statement: SourceStatement | None

Returns the next statement that _would_ execute if the program were to progress to the next line.

source_path: Path | None

The path to the local contract file. Only exists when is from a local contract.

property source_statements: list[SourceStatement]

All statements coming directly from a contract’s source. Excludes implicit-compiler statements.

statements: list[Statement]

The source node statements.

property ws_begin_lineno: int | None

The first line number in the sequence, including whitespace.

ape.types.trace.GasReport

A gas report in Ape.

class ape.types.trace.SourceTraceback(root: RootModelRootType = PydanticUndefined)

A full execution traceback including source code.

add_builtin_jump(name: str, _type: str, full_name: str | None = None, source_path: Path | None = None, pcs: set[int] | None = None)

A convenience method for appending a control flow that happened from an internal compiler built-in code. See the ape-vyper plugin for a usage example.

Parameters:
  • name (str) – The name of the compiler built-in.

  • _type (str) – A str describing the type of check.

  • full_name (Optional[str]) – A full-name ID.

  • source_path (Optional[Path]) – The source file related, if there is one.

  • pcs (Optional[set[int]]) – Program counter values mapping to this check.

add_jump(location: SourceLocation, function: Function, depth: int, pcs: set[int] | None = None, source_path: Path | None = None)

Add an execution sequence from a jump.

Parameters:
  • location (SourceLocation) – The location to add.

  • function (Function) – The function executing.

  • source_path (Optional[Path]) – The path of the source file.

  • depth (int) – The depth of the function call in the call tree.

  • pcs (Optional[set[int]]) – The program counter values.

  • source_path – The path of the source file.

append(_SourceTraceback__object) None

Append the given control flow to this one.

property execution: list[ControlFlow]

All the control flows in order. Each set of statements in a control flow is separated by a jump.

extend(_SourceTraceback__iterable) None

Append all the control flows from the given traceback to this one.

extend_last(location: SourceLocation, pcs: set[int] | None = None)

Extend the last node with more content.

Parameters:
  • location (SourceLocation) – The location of the new content.

  • pcs (Optional[set[int]]) – The PC values to add on.

format() str

Get a formatted traceback string for displaying to users.

property last: ControlFlow | None

The last control flow in the traceback, if there is one.

property revert_type: str | None

The revert type, such as a builtin-error code or a user dev-message, if there is one.

property source_statements: list[SourceStatement]

All source statements from each control flow.

property statements: list[Statement]

All statements from each control flow.

Units

ape.types.units.CurrencyValue

An alias to CurrencyValueComparable for situations when you know for sure the type is a currency-value (and not just comparable to one).

ape.types.units.CurrencyValueComparable

alias of CurrencyValueComparable

Basic

ape.types.basic.HexInt

Validate any hex-str or bytes into an integer. To be used on pydantic-fields.

alias of Annotated[int, BeforeValidator(func=_hex_int_validator, json_schema_input_type=PydanticUndefined)]