API
eth_abi.abi module
eth_abi.base module
- class eth_abi.base.BaseCoder(**kwargs)
Bases:
objectBase class for all encoder and decoder classes.
- classmethod from_type_str(type_str, registry)
Used by
ABIRegistryto get an appropriate encoder or decoder instance for the given type string and type registry.
eth_abi.codec module
- class eth_abi.codec.ABICodec(registry: ABIRegistry)
Bases:
ABIEncoder,ABIDecoder
- class eth_abi.codec.ABIDecoder(registry: ABIRegistry)
Bases:
BaseABICoderWraps a registry to provide last-mile decoding functionality.
- decode(types: Iterable[str], data: bytes | bytearray, strict: bool = True) Tuple[Any, ...]
Decodes the binary value
dataas a sequence of values of the ABI types intypesvia the head-tail mechanism into a tuple of equivalent python values.- Parameters:
types – A list or tuple of string representations of the ABI types that will be used for decoding e.g.
('uint256', 'bytes[]', '(int,int)')data – The binary value to be decoded.
strict – If
False, dynamic-type decoders will ignore validations such as making sure the data is padded to a multiple of 32 bytes or checking that padding bytes are zero / empty.Falseis how the Solidity ABI decoder currently works. However,Trueis the default for the eth-abi library.
- Returns:
A tuple of equivalent python values for the ABI values represented in
data.
- stream_class
alias of
ContextFramesBytesIO
- class eth_abi.codec.ABIEncoder(registry: ABIRegistry)
Bases:
BaseABICoderWraps a registry to provide last-mile encoding functionality.
- encode(types: Iterable[str], args: Iterable[Any]) bytes
Encodes the python values in
argsas a sequence of binary values of the ABI types intypesvia the head-tail mechanism.- Parameters:
types – A list or tuple of string representations of the ABI types that will be used for encoding e.g.
('uint256', 'bytes[]', '(int,int)')args – A list or tuple of python values to be encoded.
- Returns:
The head-tail encoded binary representation of the python values in
argsas values of the ABI types intypes.
- is_encodable(typ: str, arg: Any) bool
Determines if the python value
argis encodable as a value of the ABI typetyp.- Parameters:
typ – A string representation for the ABI type against which the python value
argwill be checked e.g.'uint256','bytes[]','(int,int)', etc.arg – The python value whose encodability should be checked.
- Returns:
Trueifargis encodable as a value of the ABI typetyp. Otherwise,False.
- is_encodable_type(typ: str) bool
Returns
Trueif values for the ABI typetypcan be encoded by this codec.- Parameters:
typ – A string representation for the ABI type that will be checked for encodability e.g.
'uint256','bytes[]','(int,int)', etc.- Returns:
Trueif values fortypcan be encoded by this codec. Otherwise,False.
- class eth_abi.codec.BaseABICoder(registry: ABIRegistry)
Bases:
objectBase class for porcelain coding APIs. These are classes which wrap instances of
ABIRegistryto provide last-mile coding functionality.
eth_abi.decoding module
- class eth_abi.decoding.BaseDecoder(**kwargs)
Bases:
BaseCoderBase class for all decoder classes. Subclass this if you want to define a custom decoder class. Subclasses must also implement
BaseCoder.from_type_str.- abstract decode(stream: ContextFramesBytesIO) Any
Decodes the given stream of bytes into a python value. Should raise
exceptions.DecodingErrorif a python value cannot be decoded from the given byte stream.
eth_abi.encoding module
- class eth_abi.encoding.BaseEncoder(**kwargs)
Bases:
BaseCoderBase class for all encoder classes. Subclass this if you want to define a custom encoder class. Subclasses must also implement
BaseCoder.from_type_str.- abstract encode(value: Any) bytes
Encodes the given value as a sequence of bytes. Should raise
exceptions.EncodingErrorifvaluecannot be encoded.
- classmethod invalidate_value(value: ~typing.Any, exc: ~typing.Type[Exception] = <class 'eth_abi.exceptions.EncodingTypeError'>, msg: str | None = None) None
Throws a standard exception for when a value is not encodable by an encoder.
- abstract validate_value(value: Any) None
Checks whether or not the given value can be encoded by this encoder. If the given value cannot be encoded, must raise
exceptions.EncodingError.
eth_abi.exceptions module
- exception eth_abi.exceptions.ABITypeError
Bases:
ValueErrorRaised when a parsed ABI type has inconsistent properties; for example, when trying to parse the type string
'uint7'(which has a bit-width that is not congruent with zero modulo eight).
- exception eth_abi.exceptions.DecodingError
Bases:
ExceptionBase exception for any error that occurs during decoding.
- exception eth_abi.exceptions.EncodingError
Bases:
ExceptionBase exception for any error that occurs during encoding.
- exception eth_abi.exceptions.EncodingTypeError
Bases:
EncodingErrorRaised when trying to encode a python value whose type is not supported for the output ABI type.
- exception eth_abi.exceptions.IllegalValue
Bases:
EncodingErrorRaised when trying to encode a python value with the correct type but with a value that is not considered legal for the output ABI type.
fixed128x19_encoder(Decimal('NaN')) # cannot encode NaN
- exception eth_abi.exceptions.InsufficientDataBytes
Bases:
DecodingErrorRaised when there are insufficient data to decode a value for a given ABI type.
- exception eth_abi.exceptions.InvalidPointer
Bases:
DecodingErrorRaised when the pointer to a value in the ABI encoding is invalid.
- exception eth_abi.exceptions.MultipleEntriesFound
Bases:
ValueError,PredicateMappingErrorRaised when multiple registrations are found for a type string in a registry’s internal mapping. This error is non-recoverable and indicates that a registry was configured incorrectly. Registrations are expected to cover completely distinct ranges of type strings.
Warning
In a future version of
eth-abi, this error class will no longer inherit fromValueError.
- exception eth_abi.exceptions.NoEntriesFound
Bases:
ValueError,PredicateMappingErrorRaised when no registration is found for a type string in a registry’s internal mapping.
Warning
In a future version of
eth-abi, this error class will no longer inherit fromValueError.
- exception eth_abi.exceptions.NonEmptyPaddingBytes
Bases:
DecodingErrorRaised when the padding bytes of an ABI value are malformed.
- exception eth_abi.exceptions.ParseError(text, pos=-1, expr=None)
Bases:
ParseErrorRaised when an ABI type string cannot be parsed.
- exception eth_abi.exceptions.PredicateMappingError
Bases:
ExceptionRaised when an error occurs in a registry’s internal mapping.
- exception eth_abi.exceptions.ValueOutOfBounds
Bases:
IllegalValueRaised when trying to encode a python value with the correct type but with a value that appears outside the range of valid values for the output ABI type.
ufixed8x1_encoder(Decimal('25.6')) # out of bounds
eth_abi.registry module
- class eth_abi.registry.ABIRegistry
- copy()
Copies a registry such that new registrations can be made or existing registrations can be unregistered without affecting any instance from which a copy was obtained. This is useful if an existing registry fulfills most of a user’s needs but requires one or two modifications. In that case, a copy of that registry can be obtained and the necessary changes made without affecting the original registry.
- has_encoder(type_str: str) bool
Returns
Trueif an encoder is found for the given type stringtype_str. Otherwise, returnsFalse. RaisesMultipleEntriesFoundif multiple encoders are found.
- register(lookup: str | Callable[[str], bool], encoder: Callable[[Any], bytes] | Type[BaseEncoder], decoder: Callable[[ContextFramesBytesIO], Any] | Type[BaseDecoder], label: str | None = None) None
Registers the given
encoderanddecoderunder the givenlookup. A unique string label may be optionally provided that can be used to refer to the registration by name.- Parameters:
lookup – A type string or type string matcher function (predicate). When the registry is queried with a type string
queryto determine which encoder or decoder to use,querywill be checked against every registration in the registry. If a registration was created with a type string forlookup, it will be considered a match iflookup == query. If a registration was created with a matcher function forlookup, it will be considered a match iflookup(query) is True. If more than one registration is found to be a match, then an exception is raised.encoder – An encoder callable or class to use if
lookupmatches a query. Ifencoderis a callable, it must accept a python value and return abytesvalue. Ifencoderis a class, it must be a valid subclass ofencoding.BaseEncoderand must also implement thefrom_type_strmethod onbase.BaseCoder.decoder – A decoder callable or class to use if
lookupmatches a query. Ifdecoderis a callable, it must accept a stream-like object of bytes and return a python value. Ifdecoderis a class, it must be a valid subclass ofdecoding.BaseDecoderand must also implement thefrom_type_strmethod onbase.BaseCoder.label – An optional label that can be used to refer to this registration by name. This label can be used to unregister an entry in the registry via the
unregistermethod and its variants.
- register_decoder(lookup: str | Callable[[str], bool], decoder: Callable[[ContextFramesBytesIO], Any] | Type[BaseDecoder], label: str | None = None) None
Registers the given
decoderunder the givenlookup. A unique string label may be optionally provided that can be used to refer to the registration by name. For more information about arguments, refer toregister.
- register_encoder(lookup: str | Callable[[str], bool], encoder: Callable[[Any], bytes] | Type[BaseEncoder], label: str | None = None) None
Registers the given
encoderunder the givenlookup. A unique string label may be optionally provided that can be used to refer to the registration by name. For more information about arguments, refer toregister.
- unregister(label: str | None) None
Unregisters the entries in the encoder and decoder registries which have the label
label.
- unregister_decoder(lookup_or_label: str | Callable[[str], bool]) None
Unregisters a decoder in the registry with the given lookup or label. If
lookup_or_labelis a string, the decoder with the labellookup_or_labelwill be unregistered. If it is an function, the decoder with the lookup functionlookup_or_labelwill be unregistered.
- unregister_encoder(lookup_or_label: str | Callable[[str], bool]) None
Unregisters an encoder in the registry with the given lookup or label. If
lookup_or_labelis a string, the encoder with the labellookup_or_labelwill be unregistered. If it is an function, the encoder with the lookup functionlookup_or_labelwill be unregistered.
eth_abi.grammar module
- class eth_abi.grammar.ABIType(arrlist=None, node=None)
Base class for results of type string parsing operations.
- arrlist
The list of array dimensions for a parsed type. Equal to
Noneif type string has no array dimensions.
- property is_array
Equal to
Trueif a type is an array type (i.e. if it has an array dimension list). Otherwise, equal toFalse.
- property is_dynamic
Equal to
Trueif a type has a dynamically sized encoding. Otherwise, equal toFalse.
- property item_type
If this type is an array type, equal to an appropriate
ABITypeinstance for the array’s items.
- node
The parsimonious
Nodeinstance associated with this parsed type. Used to generate error messages for invalid types.
- to_type_str()
Returns the string representation of an ABI type. This will be equal to the type string from which it was created.
- validate()
Validates the properties of an ABI type against the solidity ABI spec:
https://solidity.readthedocs.io/en/develop/abi-spec.html
Raises
ABITypeErrorif validation fails.
- class eth_abi.grammar.TupleType(components, arrlist=None, *, node=None)
Represents the result of parsing a tuple type string e.g. “(int,bool)”.
- property is_dynamic
Equal to
Trueif a type has a dynamically sized encoding. Otherwise, equal toFalse.
- property item_type
If this type is an array type, equal to an appropriate
ABITypeinstance for the array’s items.
- to_type_str()
Returns the string representation of an ABI type. This will be equal to the type string from which it was created.
- validate()
Validates the properties of an ABI type against the solidity ABI spec:
https://solidity.readthedocs.io/en/develop/abi-spec.html
Raises
ABITypeErrorif validation fails.
- class eth_abi.grammar.BasicType(base, sub=None, arrlist=None, *, node=None)
Represents the result of parsing a basic type string e.g. “uint”, “address”, “ufixed128x19[][2]”.
- base
The base of a basic type e.g. “uint” for “uint256” etc.
- property is_dynamic
Equal to
Trueif a type has a dynamically sized encoding. Otherwise, equal toFalse.
- property item_type
If this type is an array type, equal to an appropriate
ABITypeinstance for the array’s items.
- sub
The sub type of a basic type e.g.
256for “uint256” or(128, 18)for “ufixed128x18” etc. Equal toNoneif type string has no sub type.
- to_type_str()
Returns the string representation of an ABI type. This will be equal to the type string from which it was created.
- validate()
Validates the properties of an ABI type against the solidity ABI spec:
https://solidity.readthedocs.io/en/develop/abi-spec.html
Raises
ABITypeErrorif validation fails.
- eth_abi.grammar.normalize(type_str)
Normalizes a type string into its canonical version e.g. the type string ‘int’ becomes ‘int256’, etc.
- Parameters:
type_str – The type string to be normalized.
- Returns:
The canonical version of the input type string.
- eth_abi.grammar.parse(type_str)
Parses a type string into an appropriate instance of
ABIType. If a type string cannot be parsed, throwsParseError.- Parameters:
type_str – The type string to be parsed.
- Returns:
An instance of
ABITypecontaining information about the parsed type string.
eth_abi.tools module
- eth_abi.tools.get_abi_strategy(type_str: str) SearchStrategy
Returns a hypothesis strategy for the given ABI type.
- Parameters:
type_str – The canonical string representation of the ABI type for which a hypothesis strategy should be returned.
- Returns:
A hypothesis strategy for generating Python values that are encodable as values of the given ABI type.