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.

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

The decoded output is returned according to Method.decode_output rules.

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[FieldValues][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[FieldValues]][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_accounts() list[Address][source]

Returns a list of addresses owned by client.

await eth_block_number() int[source]

Returns the number of the most recent block.

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

Executes a new message call immediately without creating a transaction on the blockchain. Often used for executing read-only smart contract functions, for example the balanceOf for an ERC-20 contract.

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

The decoded output is returned according to Method.decode_output rules.

await eth_chain_id() int[source]

Returns the chain ID used for signing replay-protected transactions.

await eth_coinbase() Address[source]

Returns the client coinbase address.

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

Generates and returns an estimate of how much gas is necessary to allow the transaction to complete. The transaction will not be added to the blockchain. Note that the estimate may be significantly more than the amount of gas actually used by the transaction, for a variety of reasons including EVM mechanics and node performance.

await eth_gas_price() Amount[source]

Returns an estimate of the current price per gas in wei, according to a provider-specific algorithm.

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

Returns the balance of the account of given address.

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

Returns information about a block by hash.

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

Returns information about a block by block number.

await eth_get_block_transaction_count_by_hash(block_hash: BlockHash) int[source]

Returns the number of transactions in a block from a block matching the given block hash.

await eth_get_block_transaction_count_by_number(block: int | BlockLabel) int[source]

Returns the number of transactions in a block matching the given block number.

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

Returns code at a given address.

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

Polling method for a filter, which returns an array of logs which occurred since last poll.

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]

Returns an array of all logs matching filter with given id.

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]

Returns an array of all logs matching a given filter object.

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

Returns the value from a storage position at a given address.

await eth_get_transaction_by_block_hash_and_index(block_hash: BlockHash, index: int) TxInfo[source]

Returns information about a transaction by block hash and transaction index position.

await eth_get_transaction_by_block_number_and_index(block: int | BlockLabel, index: int) TxInfo[source]

Returns information about a transaction by block number and transaction index position.

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

Returns the information about a transaction requested by transaction hash.

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

Returns the number of transactions sent from an address.

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

Returns the receipt of a transaction by transaction hash.

Note

That the receipt is not available for pending transactions.

await eth_get_uncle_by_block_hash_and_index(block_hash: BlockHash, index: int) None | BlockInfo[source]

Returns information about a uncle of a block by hash and uncle index position.

await eth_get_uncle_by_block_number_and_index(block: int | BlockLabel, index: int) None | BlockInfo[source]

Returns information about a uncle of a block by number and uncle index position.

await eth_get_uncle_count_by_block_hash(block_hash: BlockHash) int[source]

Returns the number of uncles in a block from a block matching the given block hash.

await eth_get_uncle_count_by_block_number(block: int | BlockLabel) int[source]

Returns the number of uncles in a block from a block matching the given block number.

await eth_new_block_filter() BlockFilter[source]

Creates a filter in the node, to notify when a new block arrives.

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]

Creates a filter object, based on filter options, to notify when the state changes (logs).

await eth_new_pending_transaction_filter() PendingTransactionFilter[source]

Creates a filter in the node, to notify when new pending transactions arrive.

await eth_send_raw_transaction(tx_bytes: bytes) TxHash[source]

Creates new message call transaction or a contract creation for signed transactions.

await eth_uninstall_filter(filter_: BlockFilter | PendingTransactionFilter | LogFilter) bool[source]

Uninstalls a filter with given id. Should always be called when watch is no longer needed.

Returns true if there was an active filter with a given filter ID.

Note

Many providers will automatically uninstall filters after some time if they are not queried.

await net_listening() bool[source]

Returns True if client is actively listening for network connections.

await net_peer_count() int[source]

Returns number of peers currently connected to the client.

await net_version() str[source]

Returns the current network id.

await web3_client_version() str[source]

Returns the current client version.

await web3_sha3(data: bytes) bytes[source]

Returns Keccak-256 (not the standardized SHA3-256) of the given data.

Providers

class pons.Provider[source]

Bases: ABC

The base class for JSON RPC providers.

class pons.ProviderPath[source]

Identifies a pinned provider.

HTTP

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

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.

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: FieldValues

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, FieldValues][source]

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

to_json() None | bool | int | float | str | Sequence[ABI_JSON] | Mapping[str, ABI_JSON][source]

Returns the serialized list of contract items (methods, errors, events).

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[tuple[str | None, 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]
to_json() None | bool | int | float | str | Sequence[ABI_JSON] | Mapping[str, ABI_JSON][source]

Returns this object’s JSON ABI.

inputs: Fields

Input signature.

payable: bool

Whether this method is marked as payable

class pons.Method(name: str, mutability: Mutability, inputs: Mapping[str, Type] | Sequence[Type] | Sequence[tuple[str | None, Type]], outputs: None | Mapping[str, Type] | Sequence[Type] | Sequence[tuple[str | None, 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]

Binds the given arguments to the method’s signature.

call_bound(bound_args: BoundArguments) MethodCall[source]

Creates a method call object using previouosly bound arguments.

decode_output(output_bytes: bytes) Any[source]

Decodes the output from ABI-packed bytes.

If there is only a single output, its value is returned. If all the fields in the output are unnamed, it is returned as a tuple of values. Otherwise it is returned as a FieldValues object.

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.

to_json() None | bool | int | float | str | Sequence[ABI_JSON] | Mapping[str, ABI_JSON][source]

Returns this object’s JSON ABI.

with_method(method: Method) MultiMethod[source]

Returns a multimethod resulting from joining this method with method.

inputs: Fields

The input signature of this method.

mutating: bool

Whether this method may mutate the contract state.

name: str

The name of this method.

outputs: Fields

The output signature of this method.

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.

to_json() list[None | bool | int | float | str | Sequence[ABI_JSON] | Mapping[str, ABI_JSON]][source]

Returns this object’s JSON ABI.

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] | Sequence[tuple[str | None, Type]], indexed: Set[str] | Sequence[bool], *, anonymous: bool = False)[source]

A contract event.

decode_log_entry(log_entry: LogEntry) FieldValues[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.

to_json() None | bool | int | float | str | Sequence[ABI_JSON] | Mapping[str, ABI_JSON][source]

Returns this object’s JSON ABI.

anonymous: bool

Whether the event is anonymous.

fields: EventFields

The event fields.

name: str

The name of this event.

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

A custom contract error.

decode_fields(data_bytes: bytes) FieldValues[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.

to_json() None | bool | int | float | str | Sequence[ABI_JSON] | Mapping[str, ABI_JSON][source]

Returns this object’s JSON ABI.

fields: Fields

The fields of the structure.

name: str

The name of the error structure.

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.

to_json() None | bool | int | float | str | Sequence[ABI_JSON] | Mapping[str, ABI_JSON][source]

Returns this object’s JSON ABI.

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.

to_json() None | bool | int | float | str | Sequence[ABI_JSON] | Mapping[str, ABI_JSON][source]

Returns this object’s JSON ABI.

payable: bool

Whether this method is marked as payable

class pons.Fields(fields: Mapping[str, Type] | Sequence[Type] | Sequence[tuple[str | None, Type]])[source]

Describes a sequence of optionally named typed values. These can be method parameters, method outputs, error fields, or event fields.

decode(value_bytes: bytes) FieldValues[source]

Decodes the packed bytestring into a list of pairs of the original parameter/field name and the value.

encode(values: Iterable[Any]) bytes[source]

Encodes the given position values into bytes according to field types.

to_json() None | bool | int | float | str | Sequence[ABI_JSON] | Mapping[str, ABI_JSON][source]

Returns this object’s JSON ABI.

property as_signature: Signature

Returns the fields represented as a signature.

Note

In Solidity, it is possible to have named and anonymous method parameters or event/error fields in arbitrary order. This cannot be mapped to Python function signatures. Also it is possible that some parameter names are Python keywords, so they will be rejected by the Signature constructor.

So the keyword names will be postfixed with a _, and anonymous fields will be given auto-generated names.

property canonical_form: str

Returns the field types serialized in the canonical form as a string.

property named_fields: set[str]
names: tuple[str | None, ...]

Field names.

types: tuple[Type, ...]

Field types.

class pons.EventFields(fields: Mapping[str, Type] | Sequence[Type] | Sequence[tuple[str | None, Type]], indexed: Set[str] | Sequence[bool])[source]

Bases: Fields

Fields of an event structure.

decode_log_entry(topics: Sequence[bytes], data: bytes) FieldValues[source]

Decodes the event fields from the given log entry data.

encode_to_topics(*args: Any, **kwargs: Any) tuple[None | tuple[bytes, ...], ...][source]

Binds given arguments to event’s indexed parameters and encodes them as log topics.

Note

If keyword arguments are used, any field names that matched Python keywords need to be postfixed by a _.

to_json() None | bool | int | float | str | Sequence[ABI_JSON] | Mapping[str, ABI_JSON][source]

Returns this object’s JSON ABI.

indexed: tuple[bool, ...]

A sequence indicating whether the field at the given position is indexed.

class pons.FieldValues(values: Sequence[tuple[str | None, Any]])[source]

A container for field values of an event, error, or a method return.

Since Solidity allows fields at arbitrary positions to be anonymous, a dictionary cannot handle all the possibilities.

__getattr__(name: str) Any[source]

Returns the value with the given name.

__getitem__(name: str) Any[source]

Returns the value with the given name.

property as_dict: dict[str, Any]

Returns the equivalent dictionary representation.

Raises ValueError if there are anonymous fields present.

property as_tuple: tuple[Any, ...]

Returns the equivalent tuple representation (a tuple of the values with the field names omitted).

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) FieldValues[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.

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.