API

Clients

class pons.Client(provider: Provider)[source]

An Ethereum RPC client.

async with session() AsyncIterator[ClientSession][source]

Opens a session to the client allowing the backend to optimize sequential requests.

class pons.ClientSession[source]

An open session to the provider.

The methods of this class may raise the following exceptions: ProviderError, ContractLegacyError, ContractError, ContractPanic, TransactionFailed, BadResponseFormat, ABIDecodingError,

await broadcast_transact(signer: Signer, call: BaseBoundMethodCall, amount: None | Amount = None, gas: int | None = None) TxHash[source]

Broadcasts the transaction without waiting for it to be finalized. See transact() for the information on the parameters.

await broadcast_transfer(signer: Signer, destination_address: Address, amount: Amount, gas: int | None = None) TxHash[source]

Broadcasts the fund transfer transaction, but does not wait for it to be processed. If gas is None, the required amount of gas is estimated first, otherwise the provided value is used.

await call(call: BaseBoundMethodCall, block: int | BlockLabel = BlockLabel.LATEST, sender_address: None | Address = None) Any[source]

Sends a prepared contact method call to the provided address. Returns the decoded output.

If sender_address is provided, it will be included in the call and affect the return value if the method uses msg.sender internally.

await chain_id() int[source]

Calls the eth_chainId RPC method.

await deploy(signer: Signer, call: BoundConstructorCall, amount: None | Amount = None, gas: int | None = None) DeployedContract[source]

Deploys the contract passing args to the constructor. If gas is None, the required amount of gas is estimated first, otherwise the provided value is used. Waits for the transaction to be confirmed. amount denotes the amount of currency to send to the constructor.

Raises TransactionFailed if the transaction was submitted successfully, but could not be processed. If gas estimation is run, see the additional errors that may be raised in the docs for estimate_deploy().

await estimate_deploy(sender_address: Address, call: BoundConstructorCall, amount: None | Amount = None, block: int | BlockLabel = BlockLabel.LATEST) int[source]

Estimates the amount of gas required to deploy the contract with the given args. Use with the same amount argument you would use to deploy the contract in production, and the sender_address equal to the address of the transaction signer.

Raises ContractPanic, ContractLegacyError, or ContractError if a known error was caught during the dry run. If the error was unknown, falls back to ethereum_rpc.RPCError.

await estimate_transact(sender_address: Address, call: BaseBoundMethodCall, amount: None | Amount = None, block: int | BlockLabel = BlockLabel.LATEST) int[source]

Estimates the amount of gas required to transact with a contract. Use with the same amount argument you would use to transact with the contract in production, and the sender_address equal to the address of the transaction signer.

Raises ContractPanic, ContractLegacyError, or ContractError if a known error was caught during the dry run. If the error was unknown, falls back to ethereum_rpc.RPCError.

await estimate_transfer(source_address: Address, destination_address: Address, amount: Amount, block: int | BlockLabel = BlockLabel.LATEST) int[source]

Estimates the amount of gas required to transfer amount. Raises a ethereum_rpc.RPCError if there is not enough funds in source_address.

await get_balance(address: Address, block: int | BlockLabel = BlockLabel.LATEST) Amount[source]

Query the balance of address at block.

await get_block(block_id: BlockHash | int | BlockLabel, *, with_transactions: bool = False) None | BlockInfo[source]
await get_transaction(tx_hash: TxHash) None | TxInfo[source]
async for ... in iter_blocks(poll_interval: int = 1) AsyncIterator[BlockHash][source]

Yields hashes of new blocks being mined.

async for ... in iter_events(event_filter: BoundEventFilter, poll_interval: int = 1, from_block: int | BlockLabel = BlockLabel.LATEST, to_block: int | BlockLabel = BlockLabel.LATEST) AsyncIterator[dict[str, Any]][source]

Yields decoded log entries produced by the filter. The fields that were hashed when converted to topics (that is, fields of reference types) are set to None.

async for ... in iter_pending_transactions(poll_interval: int = 1) AsyncIterator[TxHash][source]

Yields hashes of new transactions being submitted.

await net_version() str[source]

Calls the net_version RPC method.

await transact(signer: Signer, call: BaseBoundMethodCall, amount: None | Amount = None, gas: int | None = None, return_events: None | Sequence[BoundEvent] = None) dict[BoundEvent, list[dict[str, Any]]][source]

Transacts with the contract using a prepared method call. If gas is None, the required amount of gas is estimated first, otherwise the provided value is used. Waits for the transaction to be confirmed. amount denotes the amount of currency to send with the transaction.

If any bound events are given in return_events, the provider will be queried for any firing of these events originating from the hash of the completed transaction (from the contract addresses the events are bound to), and the results will be returned as a dictionary keyed by the corresponding event object.

Raises TransactionFailed if the transaction was submitted successfully, but could not be processed. If gas estimation is run, see the additional errors that may be raised in the docs for estimate_transact().

await transfer(signer: Signer, destination_address: Address, amount: Amount, gas: int | None = None) None[source]

Transfers funds from the address of the attached signer to the destination address. If gas is None, the required amount of gas is estimated first, otherwise the provided value is used. Waits for the transaction to be confirmed.

Raises TransactionFailed if the transaction was submitted successfully, but could not be processed.

await wait_for_transaction_receipt(tx_hash: TxHash, poll_latency: float = 1.0) TxReceipt[source]

Queries the transaction receipt waiting for poll_latency between each attempt.

property rpc: ClientSessionRPC
class pons.ClientSessionRPC[source]

The hub for methods which directly correspond to Ethereum RPC calls.

The methods of this class may raise ProviderError (coming from the lower level) or BadResponseFormat (failed to deserialize the response into the expected type).

await eth_block_number() int[source]

Calls the eth_blockNumber RPC method.

await eth_call(call: BaseBoundMethodCall, block: int | BlockLabel = BlockLabel.LATEST, sender_address: None | Address = None) Any[source]

Sends a prepared contact method call to the provided address. Returns the decoded output.

If sender_address is provided, it will be included in the call and affect the return value if the method uses msg.sender internally.

await eth_chain_id() int[source]

Calls the eth_chainId RPC method.

await eth_estimate_gas(params: EstimateGasParams, block: int | BlockLabel) int[source]

Calls the eth_estimateGas RPC method.

await eth_gas_price() Amount[source]

Calls the eth_gasPrice RPC method.

await eth_get_balance(address: Address, block: int | BlockLabel = BlockLabel.LATEST) Amount[source]

Calls the eth_getBalance RPC method.

await eth_get_block_by_hash(block_hash: BlockHash, *, with_transactions: bool = False) None | BlockInfo[source]

Calls the eth_getBlockByHash RPC method.

await eth_get_block_by_number(block: int | BlockLabel = BlockLabel.LATEST, *, with_transactions: bool = False) None | BlockInfo[source]

Calls the eth_getBlockByNumber RPC method.

await eth_get_code(address: Address, block: int | BlockLabel = BlockLabel.LATEST) bytes[source]

Calls the eth_getCode RPC method.

await eth_get_filter_changes(filter_: BlockFilter | PendingTransactionFilter | LogFilter) tuple[BlockHash, ...] | tuple[TxHash, ...] | tuple[LogEntry, ...][source]

Calls the eth_getFilterChanges RPC method. Depending on what filter_ was, returns a tuple of corresponding results.

await eth_get_filter_logs(filter_: BlockFilter | PendingTransactionFilter | LogFilter) tuple[BlockHash, ...] | tuple[TxHash, ...] | tuple[LogEntry, ...][source]

Calls the eth_getFilterLogs RPC method.

await eth_get_logs(source: None | Address | Iterable[Address] = None, event_filter: None | EventFilter = None, from_block: int | BlockLabel = BlockLabel.LATEST, to_block: int | BlockLabel = BlockLabel.LATEST) tuple[LogEntry, ...][source]

Calls the eth_getLogs RPC method.

await eth_get_storage_at(address: Address, position: int, block: int | BlockLabel = BlockLabel.LATEST) bytes[source]

Calls the eth_getCode RPC method.

await eth_get_transaction_by_hash(tx_hash: TxHash) None | TxInfo[source]

Calls the eth_getTransactionByHash RPC method.

await eth_get_transaction_count(address: Address, block: int | BlockLabel = BlockLabel.LATEST) int[source]

Calls the eth_getTransactionCount RPC method.

await eth_get_transaction_receipt(tx_hash: TxHash) None | TxReceipt[source]

Calls the eth_getTransactionReceipt RPC method.

await eth_new_block_filter() BlockFilter[source]

Calls the eth_newBlockFilter RPC method.

await eth_new_filter(source: None | Address | Iterable[Address] = None, event_filter: None | EventFilter = None, from_block: int | BlockLabel = BlockLabel.LATEST, to_block: int | BlockLabel = BlockLabel.LATEST) LogFilter[source]

Calls the eth_newFilter RPC method.

await eth_new_pending_transaction_filter() PendingTransactionFilter[source]

Calls the eth_newPendingTransactionFilter RPC method.

await eth_send_raw_transaction(tx_bytes: bytes) TxHash[source]

Sends a signed and serialized transaction.

await net_version() str[source]

Calls the net_version RPC method.

Providers

class pons.Provider[source]

Bases: ABC

The base class for JSON RPC providers.

class pons.HTTPProvider(url: str)[source]

Bases: Provider

A provider for RPC via HTTP(S).

class pons.ProviderPath[source]

Identifies a pinned provider.

Fallback providers

class pons.FallbackProvider(providers: Mapping[str, Provider], strategy: FallbackStrategyFactory | None = None, *, same_provider: bool = False)[source]

Bases: Provider

A provider that encompasses several providers and for every request tries every one of them until the request is successful. The order is chosen according to the given strategy.

If same_provider is True, the given providers are treated as endpoints pointing to the same physical provider, for the purpose of stateful requests (e.g. filter creation).

If strategy is None, an instance of PriorityFallback is used.

If a request attempt results in an error for which use_fallback returns True, the next provider based on the chosen strategy will be selected. Otherwise (or if it is the last provider), the error is raised normally.

errors() list[tuple[ProviderPath, ProviderError]][source]

Returns the list of recorded errors for sub-providers.

Only the most recent error for every sub-provider is recorded. Querying this method clears the recorded errors.

class pons.CycleFallback(weights: None | Iterable[int] = None)[source]

Bases: FallbackStrategyFactory

Creates a strategy where the providers are cycled such that the number of times a given provider is first in the priority list is equal to the corresponding entry in weights (the length of which should match the number of providers). If weights is not given, a list of 1 will be used.

class pons.PriorityFallback[source]

Bases: FallbackStrategyFactory

class pons.FallbackStrategyFactory[source]

Bases: ABC

An abstract class defining a fallback strategy factory for multiple providers. This will be called in FallbackProvider to create an actual strategy object (which may be mutated).

abstractmethod make_strategy(provider_ids: Set[str]) FallbackStrategy[source]

Returns a strategy object.

class pons.FallbackStrategy[source]

Bases: ABC

An abstract class defining a fallback strategy for multiple providers.

abstractmethod get_provider_order() list[str][source]

Returns the suggested order of providers to query, based on the accumulated data. This method is called once on every high-level request to the provider.

Errors

Provider level

class pons.ProviderError(error: RPCError | Unreachable | InvalidResponse | ProtocolError)[source]

Bases: Exception

Describes an error on the provider’s side.

error: RPCError | Unreachable | InvalidResponse | ProtocolError

The specific error.

class pons.InvalidResponse[source]

Bases: Exception

Raised when the remote server’s response is not of an expected format.

class pons.Unreachable[source]

Bases: Exception

Raised when there is a problem connecting to the provider.

class pons.ProtocolError[source]

Bases: ABC, Exception

A protocol-specific error, indicating that the provider returned an error status with no additional information allowing to categorize the error further.

See the provider-specifc derived class for this exception for more details.

class pons.HTTPError(status_code: int, message: str)[source]

Bases: ProtocolError

Raised when the provider returns a response with a status code other than 200, and no "error" field in the associated JSON data.

Client level

class pons.BadResponseFormat[source]

Bases: Exception

Raised if the RPC provider returned an unexpectedly formatted response.

class pons.ABIDecodingError[source]

Bases: Exception

Raised on an error when decoding a value in an Eth ABI encoded bytestring.

class pons.TransactionFailed[source]

Bases: Exception

Raised for invalid transactions that are not contract executions (e.g. transfers or contract deployments).

class pons._client.ContractPanicReason(value)[source]

Reasons leading to a contract call panicking.

classmethod from_int(val: int) ContractPanicReason[source]
ASSERTION = 1

If you call assert with an argument that evaluates to false.

COMPILER = 0

Used for generic compiler inserted panics.

DIVISION_BY_ZERO = 18

If you divide or modulo by zero (e.g. 5 / 0 or 23 % 0).

EMPTY_ARRAY = 49

If you call .pop() on an empty array.

INVALID_ENCODING = 34

If you access a storage byte array that is incorrectly encoded.

INVALID_ENUM_VALUE = 33

If you convert a value that is too big or negative into an enum type.

OUT_OF_BOUNDS = 50

If you access an array, bytesN or an array slice at an out-of-bounds or negative index (i.e. x[i] where i >= x.length or i < 0).

OUT_OF_MEMORY = 65

If you allocate too much memory or create an array that is too large.

OVERFLOW = 17

If an arithmetic operation results in underflow or overflow outside of an unchecked { ... } block.

UNKNOWN = -1

Unknown panic code.

ZERO_DEREFERENCE = 81

If you call a zero-initialized variable of internal function type.

class pons.ContractPanic[source]

Bases: Exception

A panic raised in a contract call.

Reason

alias of ContractPanicReason

classmethod from_code(code: int) ContractPanic[source]
reason: ContractPanicReason

Parsed panic reason.

class pons.ContractLegacyError[source]

Bases: Exception

A raised Solidity legacy error (from require() or revert()).

message: str

The error message.

class pons.ContractError[source]

Bases: Exception

A raised Solidity error (from revert SomeError(...)).

data: dict[str, Any]

The unpacked error data, corresponding to the ABI.

error: Error

The recognized ABI Error object.

Signers

class pons.Signer[source]

Bases: ABC

The base class for transaction signers.

abstractmethod sign_transaction(tx_dict: Dict[str, Sequence[Dict[str, HexStr | Sequence[HexStr]]] | bytes | HexStr | int]) bytes[source]

Signs the given transaction and returns the RLP-packed transaction along with the signature.

abstract property address: Address

Returns the address corresponding to the signer’s private key.

class pons.AccountSigner(account: LocalAccount)[source]

Bases: Signer

A signer wrapper for LocalAccount from eth-account package.

staticmethod create() AccountSigner[source]

Creates an account with a random private key.

sign_transaction(tx_dict: Dict[str, Sequence[Dict[str, HexStr | Sequence[HexStr]]] | bytes | HexStr | int]) bytes[source]

Signs the given transaction and returns the RLP-packed transaction along with the signature.

property account: LocalAccount

Returns the account object used to create this signer.

property address: Address

Returns the address corresponding to the signer’s private key.

property private_key: bytes

Returns the private key corresponding to this signer. Handle with care.

Contract ABI

class pons.ABI_JSON

A JSON-ifiable object (bool, int, float, str, None, iterable of JSON, or mapping of str to JSON).

class pons.ContractABI(constructor: None | Constructor = None, fallback: None | Fallback = None, receive: None | Receive = None, methods: None | Iterable[Method | MultiMethod] = None, events: None | Iterable[Event] = None, errors: None | Iterable[Error] = None)[source]

A wrapper for contract ABI.

Contract methods are grouped by type and are accessible via the attributes below.

classmethod from_json(json_abi: None | bool | int | float | str | Sequence[ABI_JSON] | Mapping[str, ABI_JSON]) ContractABI[source]

Creates this object from a JSON ABI (e.g. generated by a Solidity compiler).

resolve_error(error_data: bytes) tuple[Error, dict[str, Any]][source]

Given the packed error data, attempts to find the error in the ABI and decode the data into its fields.

constructor: Constructor

Contract’s constructor.

error: Methods[Error]

Contract’s errors.

event: Methods[Event]

Contract’s events.

fallback: None | Fallback

Contract’s fallback method.

method: Methods[Method | MultiMethod]

Contract’s regular methods.

receive: None | Receive

Contract’s receive method.

class pons.Mutability(value)[source]

Possible states of a contract’s method mutability.

classmethod from_json(entry: None | bool | int | float | str | Sequence[ABI_JSON] | Mapping[str, ABI_JSON]) Mutability[source]
NONPAYABLE = 'nonpayable'

Solidity’s nonpayable (may write the contract state).

PAYABLE = 'payable'

Solidity’s payable (may write the contract state and accept associated funds with transactions).

PURE = 'pure'

Solidity’s pure (does not read or write the contract state).

VIEW = 'view'

Solidity’s view (may read the contract state).

property mutating: bool
property payable: bool
class pons.Constructor(inputs: Mapping[str, Type] | Sequence[Type], *, payable: bool = False)[source]

Contract constructor.

Note

If the name of a parameter given to the constructor matches a Python keyword, _ will be appended to it.

__call__(*args: Any, **kwargs: Any) ConstructorCall[source]

Returns an encoded call with given arguments.

classmethod from_json(method_entry: None | bool | int | float | str | Sequence[ABI_JSON] | Mapping[str, ABI_JSON]) Constructor[source]
inputs: Signature

Input signature.

payable: bool

Whether this method is marked as payable

class pons.Method(name: str, mutability: Mutability, inputs: Mapping[str, Type] | Sequence[Type], outputs: None | Mapping[str, Type] | Sequence[Type] | Type = None)[source]

A contract method.

Note

If the name of a parameter (input or output) given to the constructor matches a Python keyword, _ will be appended to it.

__call__(*args: Any, **kwargs: Any) MethodCall[source]

Returns an encoded call with given arguments.

bind(*args: Any, **kwargs: Any) BoundArguments[source]
call_bound(bound_args: BoundArguments) MethodCall[source]
decode_output(output_bytes: bytes) Any[source]

Decodes the output from ABI-packed bytes.

classmethod from_json(method_entry: None | bool | int | float | str | Sequence[ABI_JSON] | Mapping[str, ABI_JSON]) Method[source]

Creates this object from a JSON ABI method entry.

with_method(method: Method) MultiMethod[source]
inputs: Signature

The input signature of this method.

mutating: bool

Whether this method may mutate the contract state.

name: str

The name of this method.

outputs: Signature

Method’s output signature.

payable: bool

Whether this method is marked as payable.

property selector: bytes

Method’s selector.

class pons.MultiMethod(*methods: Method)[source]

An overloaded contract method, containing several Method objects with the same name but different input signatures.

__call__(*args: Any, **kwds: Any) MethodCall[source]

Returns an encoded call with given arguments.

with_method(method: Method) MultiMethod[source]

Returns a new MultiMethod with the given method included.

property methods: dict[str, Method]

All the overloaded methods, indexed by the canonical form of their input signatures.

property name: str

The name of this method.

class pons.Event(name: str, fields: Mapping[str, Type], indexed: Set[str], *, anonymous: bool = False)[source]

A contract event.

Note

If the name of a field given to the constructor matches a Python keyword, _ will be appended to it.

decode_log_entry(log_entry: LogEntry) dict[str, Any][source]

Decodes the event fields from the given log entry. Fields that cannot be decoded (indexed reference types, which are hashed before saving them to the log) are set to None.

classmethod from_json(event_entry: None | bool | int | float | str | Sequence[ABI_JSON] | Mapping[str, ABI_JSON]) Event[source]

Creates this object from a JSON ABI method entry.

class pons.Error(name: str, fields: Mapping[str, Type])[source]

A custom contract error.

decode_fields(data_bytes: bytes) dict[str, Any][source]

Decodes the error fields from the given packed data.

classmethod from_json(error_entry: None | bool | int | float | str | Sequence[ABI_JSON] | Mapping[str, ABI_JSON]) Error[source]

Creates this object from a JSON ABI method entry.

property selector: bytes

Error’s selector.

class pons.Fallback(*, payable: bool = False)[source]

A fallback method.

classmethod from_json(method_entry: None | bool | int | float | str | Sequence[ABI_JSON] | Mapping[str, ABI_JSON]) Fallback[source]

Creates this object from a JSON ABI method entry.

payable: bool

Whether this method is marked as payable

class pons.Receive(*, payable: bool = False)[source]

A receive method.

classmethod from_json(method_entry: None | bool | int | float | str | Sequence[ABI_JSON] | Mapping[str, ABI_JSON]) Receive[source]

Creates this object from a JSON ABI method entry.

payable: bool

Whether this method is marked as payable

Testing utilities

pons exposes several types useful for testing applications that connect to Ethereum RPC servers. Not intended for the production environment.

Install the feature local-provider for the local_provider module to be available.

Install the feature http-provider-server for the http_provider_server module to be available.

Compiler

Install with the feature compiler for it to be available.

Multicall contract

The library includes a helper for interacting with the Multicall contract (https://github.com/mds1/multicall3).

class pons.Multicall(multicall3_address: Address)[source]

A helper for interacting with the Multicall contract (v3).

aggregate(calls: Iterable[BoundMethodCall], *, allow_failure: bool = False) BoundMultiMethodCall[source]

Creates an aggregated call out of provided calls. The return value is a list of tuples (success: bool, result: Any) in the same order as calls.

If at least one of the calls is mutating, the resulting call will be mutating as well.

If allow_failure is False, a contract error in one of the calls will result in a contract error being raised. If it is True, any contract errors will be recorded in the corresponding return values, but no exception will be raised.

Note

If allow_failure is True, and one of the calls reverts, the successful calls will not be reverted as well.

aggregate_value(calls: Iterable[tuple[BoundMethodCall, Amount]], *, allow_failure: bool = False) BoundMultiMethodValueCall[source]

Same as aggregate(), but takes an associated amount that will be passed to the corresponding method. The sum of the amounts must be lesser or equal to the amount passed with the invocation of the aggregated call.

class pons.BoundMultiMethodCall(calls: Iterable[BoundMethodCall], multicall3_address: Address, *, allow_failure: bool = False)[source]

Bases: BaseBoundMethodCall

decode_output(output_bytes: bytes) list[Any][source]

Decodes contract output packed into the bytestring.

property contract_abi: ContractABI

The corresponding contract’s ABI.

property contract_address: Address

The contract address.

property data_bytes: bytes

Encoded call arguments with the selector.

property mutating: bool

Whether this method is marked as payable or nonpayable.

property payable: bool

Whether this method is marked as payable.

class pons.BoundMultiMethodValueCall(calls: Iterable[tuple[BoundMethodCall, Amount]], multicall3_address: Address, *, allow_failure: bool = False)[source]

Bases: BoundMethodCall

decode_output(output_bytes: bytes) list[Any][source]

Decodes contract output packed into the bytestring.

property contract_abi: ContractABI

The corresponding contract’s ABI.

property contract_address: Address

The contract address.

property data_bytes: bytes

Encoded call arguments with the selector.

property mutating: bool

Whether this method is marked as payable or nonpayable.

property payable: bool

Whether this method is marked as payable.

Secondary classes

The instances of these classes are not created by the user directly, but rather found as return values, or attributes of other objects.

class pons.ConstructorCall[source]

A call to the contract’s constructor.

input_bytes: bytes

Encoded call arguments.

class pons.MethodCall[source]

A call to a contract’s regular method.

data_bytes: bytes

Encoded call arguments with the selector.

method: Method

The method object that encoded this call.

class pons.EventFilter[source]

A filter for events coming from any contract address.

topics: tuple[None | tuple[LogTopic, ...], ...]
class pons.BoundConstructor[source]

A constructor bound to a specific contract’s bytecode.

__call__(*args: Any, **kwargs: Any) BoundConstructorCall[source]

Returns a constructor call with encoded arguments and bytecode.

class pons.BoundConstructorCall[source]

A constructor call with encoded arguments and bytecode.

contract_abi: ContractABI

The corresponding contract’s ABI

data_bytes: bytes

Encoded arguments and the contract’s bytecode.

payable: bool

Whether this call is payable.

class pons.BoundMethod[source]

A regular method bound to a specific contract’s address.

__call__(*args: Any, **kwargs: Any) BoundMethodCall[source]

Returns a contract call with encoded arguments bound to a specific address.

class pons.BaseBoundMethodCall[source]

The base class for contract method calls bound to a specific contract address.

abstractmethod decode_output(output_bytes: bytes) Any[source]

Decodes contract output packed into the bytestring.

abstract property contract_abi: ContractABI

The corresponding contract’s ABI.

abstract property contract_address: Address

The contract address.

abstract property data_bytes: bytes

Encoded call arguments with the selector.

abstract property mutating: bool

Whether this method is marked as payable or nonpayable.

abstract property payable: bool

Whether this method is marked as payable.

class pons.BoundMethodCall[source]

Bases: BaseBoundMethodCall

A regular method call with encoded arguments bound to a specific contract address.

decode_output(output_bytes: bytes) Any[source]

Decodes contract output packed into the bytestring.

property contract_abi: ContractABI

The corresponding contract’s ABI.

property contract_address: Address

The contract address.

property data_bytes: bytes

Encoded call arguments with the selector.

property mutating: bool

Whether this method is marked as payable or nonpayable.

property payable: bool

Whether this method is marked as payable.

class pons.BoundEvent[source]

An event creation call with encoded topics bound to a specific contract address.

__call__(*args: Any, **kwargs: Any) BoundEventFilter[source]

Returns an event filter with encoded arguments bound to a specific address.

class pons.BoundEventFilter[source]

An event filter bound to a specific contract address.

decode_log_entry(log_entry: LogEntry) dict[str, Any][source]
contract_address: Address

The contract address.

topics: tuple[None | tuple[LogTopic, ...], ...]

Encoded topics for filtering.

Utility classes

class pons._contract_abi.Methods[source]

Bases: Generic [MethodType].

A holder for named methods which can be accessed as attributes, or iterated over.

__getattr__(method_name: str) MethodType[source]

Returns the method by name.

__iter__() Iterator[MethodType][source]

Returns the iterator over all methods.

class pons._contract_abi.MethodType

Generic method type parameter.

class pons._contract_abi.Signature[source]

Generalized signature of either inputs or outputs of a method.

property canonical_form: str

Returns the signature serialized in the canonical form as a string.

class pons._contract_abi.Method(name: str, mutability: Mutability, inputs: Mapping[str, Type] | Sequence[Type], outputs: None | Mapping[str, Type] | Sequence[Type] | Type = None)[source]

A contract method.

Note

If the name of a parameter (input or output) given to the constructor matches a Python keyword, _ will be appended to it.

bind(*args: Any, **kwargs: Any) BoundArguments[source]
call_bound(bound_args: BoundArguments) MethodCall[source]
decode_output(output_bytes: bytes) Any[source]

Decodes the output from ABI-packed bytes.

classmethod from_json(method_entry: None | bool | int | float | str | Sequence[ABI_JSON] | Mapping[str, ABI_JSON]) Method[source]

Creates this object from a JSON ABI method entry.

with_method(method: Method) MultiMethod[source]
inputs: Signature

The input signature of this method.

mutating: bool

Whether this method may mutate the contract state.

name: str

The name of this method.

outputs: Signature

Method’s output signature.

payable: bool

Whether this method is marked as payable.

property selector: bytes

Method’s selector.

Utility methods

pons.get_create_address(deployer: Address, nonce: int) Address[source]

Returns the deterministic deployed contract address as produced by CREATE opcode. Here deployer is the contract address invoking CREATE (if initiated in a contract), or the transaction initiator, if a contract is created via an RPC transaction. init_code is the deployment code (see data_bytes).

pons.get_create2_address(deployer: Address, init_code: bytes, salt: bytes) Address[source]

Returns the deterministic deployed contract address as produced by CREATE2 opcode. Here deployer is the contract address invoking CREATE2 (not the transaction initiator), init_code is the deployment code (see data_bytes), and salt is a length 32 bytestring.

Compiled and deployed contracts

class pons.CompiledContract(abi: ContractABI, bytecode: bytes)[source]

A compiled contract (ABI and bytecode).

classmethod from_compiler_output(json_abi: list[dict[str, None | bool | int | float | str | Sequence[ABI_JSON] | Mapping[str, ABI_JSON]]], bytecode: bytes) CompiledContract[source]

Creates a compiled contract object from the output of a Solidity compiler.

abi: ContractABI

Contract’s ABI.

bytecode: bytes

Contract’s bytecode.

property constructor: BoundConstructor

Returns the constructor bound to this contract’s bytecode.

class pons.DeployedContract(abi: ContractABI, address: Address)[source]

A deployed contract (ABI and address).

abi: ContractABI

Contract’s ABI.

address: Address

Contract’s address.

error: Methods[Error]

Contract’s errors.

event: Methods[BoundEvent]

Contract’s events bound to the address.

method: Methods[BoundMethod]

Contract’s regular methods bound to the address.

Filter objects

class pons.BlockFilter[source]

A block filter created on a remote provider.

Expires after some time subject to the provider’s settings.

class pons.PendingTransactionFilter[source]

A pending transaction filter created on a remote provider.

Expires after some time subject to the provider’s settings.

class pons.LogFilter[source]

A log filter created on a remote provider.

Expires after some time subject to the provider’s settings.

Solidity types

Type aliases are exported from the abi submodule. Arrays can be obtained from Type objects by indexing them (either with an integer for a fixed-size array, or with ... for a variable-sized array).

Helper aliases are exported from pons.abi submodule:

pons.abi.uint(bits: int) UInt[source]

Returns the uint<bits> type.

pons.abi.int(bits: int) Int[source]

Returns the int<bits> type.

pons.abi.bytes(size: int | None = None) Bytes[source]

Returns the bytes<size> type, or bytes if size is None.

pons.abi.address: AddressType

address type.

pons.abi.string: String

string type.

pons.abi.bool: Bool

bool type.

pons.abi.struct(**kwargs: Type) Struct[source]

Returns the structure type with given fields.

Actual type objects, for reference:

class pons._abi_types.Type[source]

The base type for Solidity types.

class pons._abi_types.UInt(bits: int)[source]

Corresponds to the Solidity uint<bits> type.

class pons._abi_types.Int(bits: int)[source]

Corresponds to the Solidity int<bits> type.

class pons._abi_types.Bytes(size: int | None = None)[source]

Corresponds to the Solidity bytes<size> type.

class pons._abi_types.AddressType[source]

Corresponds to the Solidity address type. Not to be confused with ethereum_rpc.Address which represents an address value.

class pons._abi_types.String[source]

Corresponds to the Solidity string type.

class pons._abi_types.Bool[source]

Corresponds to the Solidity bool type.

class pons._abi_types.Struct(fields: Mapping[str, Type])[source]

Corresponds to the Solidity struct type.