ABI encoding

Basic concepts

Function selector

Function selector is computed as first 4 bytes of:

sha3(signature)

where signature is of form funcName(uint8,bool,string) (types of arguments in parentheses) and must not contain any whitespace. All types are normalized to standard form (e.g. fixed is transformed into fixed128x18 before hashing).

Supported types

Supported types for argument encoding

Type

Description

Elementary types

uint<M>
int<M>
Unsigned and signed M-bit integer.
\(0 < M \leq 256\), \(M \equiv 0 \pmod 8\)

address

Synonym for uint160 with special semantical meaning.

int
uint
Synonyms for int256 and uint256
Normalized to full form when computing selector.

bool

Equivalent to uint8, restricted to 0 or 1

fixed<M>x<N>
ufixed<M>x<N>
Signed (unsigned) fixed-point M-bit number
such that number \(x\) represents value \(\left\lfloor \frac{x}{10^N} \right\rfloor\)
\(0 < M \leq 256\), \(0 < N \leq 80\), \(M \equiv N \equiv 0 \pmod 8\)
fixed
ufixed
Synonyms for fixed128x18 and fixed128x18
Normalized to full form when computing selector.

bytes<M>

Sequence of M bytes.

function

Synonym of bytes24. 20 bytes address + 4 bytes signature.

Fixed-length types

<type>[M]

Fixed sized array of type <type>.
Examples: int[10], uint256[33]

Dynamic types

bytes

Bytes of arbitrary length.

string

String of arbitrary length.

<type>[]

Array of <type> of arbitrary length.

Further reading

Specification

API documentation

ABI encoding module.

Classes:

Function

ABI Function.

Constructor

ABI constructor function.

Event

ABI Event.

Coder

Convenient wrapper to namespace encoding functions.

FunctionResult

Mixin for NamedTuple with convenience methods.

Encodable

Base class for Function and Event.

FunctionBase

Base class for ABI functions (function itself and constructor).

Type or structure checkers:

StateMutabilityT

Literal type of stateMutability parameter.

FuncParameterT

Type of ABI function parameter.

FunctionT

Type of ABI function dictionary representation.

ConstructorT

Type of ABI function dictionary representation.

EventParameterT

Type of ABI event parameter.

EventT

Type of ABI event dictionary representation.

MUTABILITY

Validation Schema for stateMutability parameter.

FUNC_PARAMETER

Validation Schema for function parameter.

FUNCTION

Validation Schema for ABI function.

CONSTRUCTOR

Validation Schema for ABI constructor.

EVENT_PARAMETER

Validation Schema for event parameter.

EVENT

Validation Schema for ABI event.

Functions:

calc_event_topic

Calculate the event log topic (32 bytes) from the ABI json.

calc_function_selector

Calculate the function selector (4 bytes) from the ABI json.

class thor_devkit.abi.Function(definition: thor_devkit.abi.FunctionT)[source]

Bases: thor_devkit.abi._WithName, thor_devkit.abi.FunctionBase

ABI Function.

Initialize a function by definition.

Changed in version 2.0.0: Argument renamed from f_definition to definition.

Parameters

definition (FunctionT) – A dict with style of FUNCTION

Methods:

apply_recursive_names

Build namedtuple from values.

decode_parameters

Decode parameters back to values.

make_proper_type

Extract type string (inline tuples) from JSON.

encode

Encode the parameters according to the function definition.

decode

Decode function call output data back into human readable results.

encode_outputs

Encode the return values according to the function definition.

from_solidity

Instantiate Function from solidity definition.

Deprecated:

get_name

Get name of object.

get_selector

First 4 bytes of function signature hash.

Attributes:

name

Get name of object.

selector

First 4 bytes of function signature hash.

classmethod apply_recursive_names(value: Any, typeinfo: thor_devkit.abi._ParamT, chain: Optional[Sequence[str]] = None) Union[thor_devkit.abi.FunctionResult, List[thor_devkit.abi.FunctionResult], Any]

Build namedtuple from values.

decode_parameters(value: bytes) thor_devkit.abi.FunctionResult

Decode parameters back to values.

New in version 2.0.0.

Parameters

value (bytes) – Data to decode.

Returns

Decoded values.

Return type

FunctionResult

get_name() str

Get name of object.

Deprecated since version 2.0.0: Use name property instead.

classmethod make_proper_type(elem: thor_devkit.abi._ParamT) str

Extract type string (inline tuples) from JSON.

property name: str

Get name of object.

New in version 2.0.0.

property selector: bytes

First 4 bytes of function signature hash.

New in version 2.0.0.

encode(parameters: Union[Sequence[Any], Mapping[str, Any]], to_hex: Literal[True]) str[source]
encode(parameters: typing.Union[typing.Sequence[typing.Any], typing.Mapping[str, typing.Any]], to_hex: typing.Literal[False] = <object object>) bytes

Encode the parameters according to the function definition.

Changed in version 2.0.0: parameter to_hex is deprecated, use "0x" + result.hex() directly instead.

Parameters
  • parameters (Sequence[Any] or Mapping[str, Any]) – A list of parameters waiting to be encoded, or a mapping from names to values.

  • to_hex (bool, default: False) – If the return should be 0x... hex string

Returns

  • bytes – By default or if to_hex=False was passed.

  • str – If to_hex=True was passed.

Examples

Encode sequence:

>>> func = Function({
...     'inputs': [{'internalType': 'string', 'name': '', 'type': 'string'}],
...     'outputs': [],
...     'name': 'myFunction',
...     'stateMutability': 'pure',
...     'type': 'function',
... })
>>> enc = func.encode(['foo'])
>>> assert enc == (
...     func.selector
...     + b'\x20'.rjust(32, b'\x00')  # Address of argument
...     + b'\x03'.rjust(32, b'\x00')  # Length
...     + b'foo'.ljust(32, b'\x00')  # String itself
... )

Encode mapping:

>>> func = Function({
...     'inputs': [{'internalType': 'string', 'name': 'arg', 'type': 'string'}],
...     'outputs': [],
...     'name': 'myFunction',
...     'stateMutability': 'pure',
...     'type': 'function',
... })
>>> enc = func.encode({'arg': 'foo'})
>>> assert enc == (
...     func.selector
...     + b'\x20'.rjust(32, b'\x00')  # Address of argument
...     + b'\x03'.rjust(32, b'\x00')  # Length
...     + b'foo'.ljust(32, b'\x00')  # String itself
... )
decode(output_data: bytes) thor_devkit.abi.FunctionResult[source]

Decode function call output data back into human readable results.

The result is a dynamic subclass of typing.NamedTuple (collections.namedtuple() return type) and FunctionResult

Changed in version 2.0.0: Return type is not a dict anymore.

Parameters

output_data (bytes) – Data to decode.

Returns

Decoded data.

Return type

FunctionResult

Examples

>>> data = {
...     "inputs": [],
...     "name": "getStr",
...     "outputs": [{"name": "memory", "type": "string"}],
...     "stateMutability": "pure",
...     "type": "function",
... }
>>> func = Function(data)
>>> memory = b"Hello world!"  # encoded string
>>> binary = bytes.fromhex(
...     "20".rjust(64, "0")  # address of first argument
...     + hex(len(memory))[2:].rjust(64, "0")  # length of string
...     + memory.hex().ljust(64, "0")  # content
... )
>>> result = func.decode(binary)
>>> result.memory  # Access by name
'Hello world!'
>>> result[0]  # Access by index
'Hello world!'
>>> result.to_dict()  # Convert to dictionary
{'memory': 'Hello world!'}

With unnamed attributes:

>>> data = {
...     "inputs": [],
...     "name": "getBool",
...     "outputs": [{"internalType": "bool", "name": "", "type": "bool"}],
...     "stateMutability": "pure",
...     "type": "function",
... }
>>> func = Function(data)
>>> result = func.decode(bytes.fromhex("1".rjust(64, "0")))
>>> result.ret_0  # Access by name
True
>>> result[0]  # Access by index
True
>>> result.to_dict()  # Convert to dictionary
{'ret_0': True}
encode_outputs(values: Union[Sequence[Any], Mapping[str, Any]]) bytes[source]

Encode the return values according to the function definition.

New in version 2.0.0.

Parameters

values (Sequence[Any] or Mapping[str, Any]) – A list of parameters waiting to be encoded, or a mapping from names to values.

Returns

Encoded output values.

Return type

bytes

Raises

ValueError – If mapping was given for unnamed parameters or mapping keys are not the same as output names.

classmethod from_solidity(*, text: Optional[str] = None, file: Optional[Union[str, os.PathLike[str]]] = None, name: Optional[str] = None, version: Optional[str] = None) thor_devkit.abi.Function[source]

Instantiate Function from solidity definition.

New in version 2.0.0.

Parameters
  • text (str or None (keyword-only)) – Program text.

  • file (os.PathLike or Path or None (keyword-only)) – File with program source.

  • name (str or None) – Name of function to select. Do not filter by name if None.

  • version (str or None (keyword-only)) – Solidity version (supported by install_solc()) or None to use default.

Raises
  • ValueError – If required type (event or function) cannot be uniquely extracted.

  • SolcError – If input is not a valid solidity code.

See also

py-solc-x

underlying library reference.

Examples

>>> from pprint import pprint
>>> contract = '''
...     contract A {
...         function f(uint x) public returns(bool) {}
...     }
... '''
>>> func = Function.from_solidity(text=contract)
>>> pprint(func._definition)
{'inputs': [{'internalType': 'uint256', 'name': 'x', 'type': 'uint256'}],
 'name': 'f',
 'outputs': [{'internalType': 'bool', 'name': '', 'type': 'bool'}],
 'stateMutability': 'nonpayable',
 'type': 'function'}

No matching function:

>>> Function.from_solidity(text='contract A { event E(int x); }')
Traceback (most recent call last):
ValueError: Missing value of expected type.

Many matching functions:

>>> contract = '''
...     contract A {
...         function f1(int x) public {}
...         function f2() public {}
...     }
... '''
>>> Function.from_solidity(text=contract)
Traceback (most recent call last):
ValueError: Ambiguous input: more than one function given.

Many matching functions, select by name:

>>> contract = '''
...     contract A {
...         function f1(int x) public {}
...         function f2() public {}
...     }
... '''
>>> func = Function.from_solidity(text=contract, name='f2')
>>> pprint(func._definition)
{'inputs': [],
 'name': 'f2',
 'outputs': [],
 'stateMutability': 'nonpayable',
 'type': 'function'}

Syntax error:

>>> Function.from_solidity(
...     text='contract A { function x() {} }'
... )  
Traceback (most recent call last):
solcx.exceptions.SolcError: An error occurred during execution
get_selector() bytes[source]

First 4 bytes of function signature hash.

Deprecated since version 2.0.0: Use selector property instead.

class thor_devkit.abi.Constructor(definition: thor_devkit.abi.ConstructorT)[source]

Bases: thor_devkit.abi.FunctionBase

ABI constructor function.

New in version 2.0.0.

Examples

>>> body = {
...     'type': 'constructor',
...     'inputs': [{'type': 'int', 'name': 'x'}],
...     'stateMutability': 'nonpayable',
... }
>>> Constructor(body)  
<thor_devkit.abi.Constructor object at ...>

Or create from contract:

>>> contract = r'contract A { constructor(int x) {} }'
>>> Constructor.from_solidity(text=contract)  
<thor_devkit.abi.Constructor object at ...>

Initialize a constructor by definition.

Parameters

definition (ConstructorT) – A dict with style of CONSTRUCTOR

Methods:

apply_recursive_names

Build namedtuple from values.

decode_parameters

Decode parameters back to values.

encode

Encode the parameters according to the function definition.

from_solidity

Instantiate Encodable from solidity definition.

make_proper_type

Extract type string (inline tuples) from JSON.

decode

Constructor does not have outputs, so nothing to decode.

Attributes:

selector

Empty bytes, because constructor is unnamed.

classmethod apply_recursive_names(value: Any, typeinfo: thor_devkit.abi._ParamT, chain: Optional[Sequence[str]] = None) Union[thor_devkit.abi.FunctionResult, List[thor_devkit.abi.FunctionResult], Any]

Build namedtuple from values.

decode_parameters(value: bytes) thor_devkit.abi.FunctionResult

Decode parameters back to values.

New in version 2.0.0.

Parameters

value (bytes) – Data to decode.

Returns

Decoded values.

Return type

FunctionResult

encode(parameters: Union[Sequence[Any], Mapping[str, Any]]) bytes

Encode the parameters according to the function definition.

Parameters

parameters (Sequence[Any] or Mapping[str, Any]) – A list of parameters waiting to be encoded, or a mapping from names to values.

Returns

Encoded value

Return type

bytes

classmethod from_solidity(*, text: Optional[str] = None, file: Optional[Union[str, os.PathLike[str]]] = None, name: Optional[str] = None, version: Optional[str] = None) thor_devkit.abi._Self

Instantiate Encodable from solidity definition.

New in version 2.0.0.

Parameters
  • text (str or None (keyword-only)) – Program text.

  • file (os.PathLike or Path or None (keyword-only)) – File with program source.

  • name (str or None) – Name of encodable to extract.

  • version (str or None (keyword-only)) – Solidity version (supported by install_solc()) or None to use default.

Raises
  • ValueError – If required type (event or function) cannot be uniquely extracted.

  • SolcError – If input is not a valid solidity code.

See also

py-solc-x

underlying library reference.

classmethod make_proper_type(elem: thor_devkit.abi._ParamT) str

Extract type string (inline tuples) from JSON.

property selector: bytes

Empty bytes, because constructor is unnamed.

decode(data: bytes) NoReturn[source]

Constructor does not have outputs, so nothing to decode.

class thor_devkit.abi.Event(definition: thor_devkit.abi.EventT)[source]

Bases: thor_devkit.abi._WithName, thor_devkit.abi.Encodable[thor_devkit.abi.EventParameterT]

ABI Event.

Initialize an Event with definition.

Changed in version 2.0.0: Argument renamed from e_definition to definition.

Parameters

e_definition (EventT) – A dict with style of EVENT.

Raises
  • ValueError – If number of indexed parameters exceeds the limit.

  • Invalid – If given definition is malformed.

Methods:

apply_recursive_names

Build namedtuple from values.

make_proper_type

Extract type string (inline tuples) from JSON.

is_dynamic_type

Check if the input type requires hashing in indexed parameter.

pad

Join sequence of bytes together and pad to multiple of mod.

dynamic_type_to_topic

Encode single value according to given type_.

encode

Assemble indexed keys into topics.

encode_data

Encode unindexed parameters into bytes.

encode_full

Encode both indexed and unindexed parameters.

decode

Decode "data" according to the "topic"s.

from_solidity

Instantiate Event from solidity definition.

Deprecated:

get_name

Get name of object.

get_signature

Get signature.

Attributes:

name

Get name of object.

is_anonymous

Whether this event is anonymous.

signature

First 4 bytes of event signature hash.

classmethod apply_recursive_names(value: Any, typeinfo: thor_devkit.abi._ParamT, chain: Optional[Sequence[str]] = None) Union[thor_devkit.abi.FunctionResult, List[thor_devkit.abi.FunctionResult], Any]

Build namedtuple from values.

get_name() str

Get name of object.

Deprecated since version 2.0.0: Use name property instead.

classmethod make_proper_type(elem: thor_devkit.abi._ParamT) str

Extract type string (inline tuples) from JSON.

property name: str

Get name of object.

New in version 2.0.0.

property is_anonymous: bool

Whether this event is anonymous.

New in version 2.0.0.

property signature: bytes

First 4 bytes of event signature hash.

New in version 2.0.0.

classmethod is_dynamic_type(t: str) bool[source]

Check if the input type requires hashing in indexed parameter.

All bytes, strings and dynamic arrays are dynamic, plus all structs and fixed-size arrays are hashed (see Specification).

static pad(data: Union[Sequence[bytes], bytes], mod: int = 32, to: Literal['r', 'l'] = 'l') bytes[source]

Join sequence of bytes together and pad to multiple of mod.

New in version 2.0.0.

Parameters
  • data (bytes or Sequence[bytes]) – Data to process.

  • mod (int, default: 32) – Length unit (bytes are padded to multiple of this parameter)

  • to (Literal["r", "l"]) – Pad to left or to right.

Returns

Given sequence joined and padded to multiple of mod.

Return type

bytes

Examples

>>> Event.pad(b'foo', 32, 'l').hex()
'666f6f0000000000000000000000000000000000000000000000000000000000'
>>> Event.pad(b'\x07', 16, 'r').hex()
'00000000000000000000000000000007'
>>> Event.pad([b'foo', b'bar'], 32, 'l').hex()
'666f6f6261720000000000000000000000000000000000000000000000000000'
>>> Event.pad([b'\x07', b'\x04'], 16, 'r').hex()
'00000000000000000000000000000704'
classmethod dynamic_type_to_topic(type_: thor_devkit.abi.EventParameterT, value: Any) List[bytes][source]

Encode single value according to given type_.

encode(parameters: Union[Mapping[str, Any], Sequence[Any]]) List[Optional[bytes]][source]

Assemble indexed keys into topics.

Commonly used to filter out logs of concerned topics, e.g. to filter out VIP180 transfer logs of a certain wallet, certain amount.

Parameters

parameters (Mapping[str, Any] or Sequence[Any]) – A dict/list of indexed parameters of the given event. Fill in None to occupy the position, if you aren’t sure about the value.

Returns

Encoded parameters with None preserved from input.

Return type

List[bytes or None]

Raises
  • TypeError – Unknown parameters type (neither mapping nor sequence)

  • ValueError – If there is unnamed parameter in definition and dict of parameters is given, or if parameters count doesn’t match the definition.

Examples

Let’s say we have

MyEvent(address from indexed, address to indexed, uint256 value)

Then corresponding event is

>>> event = Event({
...     'inputs': [
...         {'name': 'from', 'indexed': True, 'type': 'address'},
...         {'name': 'to', 'indexed': True, 'type': 'address'},
...         {'name': 'value', 'indexed': False, 'type': 'uint256'},
...     ],
...     'name': 'MyEvent',
...     'type': 'event',
... })

We can use it to encode all topics:

>>> address_from = '0x' + 'f' * 40
>>> address_to = '0x' + '9' * 40
>>> enc = event.encode([address_from, address_to])
>>> assert tuple(enc) == (
...     event.signature,
...     bytes.fromhex(hex(int(address_from, 16))[2:].rjust(64, '0')),
...     bytes.fromhex(hex(int(address_to, 16))[2:].rjust(64, '0')),
... )

Note the interesting conversion here: address is equivalent to uint160, so one would expect just bytes.fromhex(address_from[2:]), right? Indexed event parameters are always padded to 32 bytes too, even if they are shorter. Numbers are padded to the right (or as two’s complement, if negative), strings and bytes - to the left.

Or we can convert only some of params:

>>> enc = event.encode([address_from, None])
>>> assert tuple(enc) == (
...     event.signature,
...     bytes.fromhex(hex(int(address_from, 16))[2:].rjust(64, '0')),
...     None,
... )

Mapping is also accepted for named parameters:

>>> enc = event.encode({'from': address_from, 'to': None})
>>> assert tuple(enc) == (
...     event.signature,
...     bytes.fromhex(hex(int(address_from, 16))[2:].rjust(64, '0')),
...     None,
... )
encode_data(parameters: Union[Mapping[str, Any], Sequence[Any]]) bytes[source]

Encode unindexed parameters into bytes.

New in version 2.0.0.

Parameters

parameters (Mapping[str, Any] or Sequence[Any]) – A dict/list of unindexed parameters of the given event.

Returns

Encoded result.

Return type

bytes

Examples

>>> event = Event({
...     'inputs': [
...         {'name': 'from', 'indexed': True, 'type': 'address'},
...         {'name': 'value', 'indexed': False, 'type': 'uint256'},
...         {'name': 'to', 'indexed': True, 'type': 'address'},
...         {'name': 'value2', 'indexed': False, 'type': 'uint64'},
...     ],
...     'name': 'MyEvent',
...     'type': 'event',
... })

We can use it to encode values as a sequence:

>>> enc = event.encode_data([256, 129])  # 256 == 0x100, 129 == 0x81
>>> assert enc.hex() == '100'.rjust(64, '0') + '81'.rjust(64, '0')

Or as a mapping:

>>> enc = event.encode_data({'value': 256, 'value2': 129})
>>> assert enc.hex() == '100'.rjust(64, '0') + '81'.rjust(64, '0')
encode_full(parameters: Union[Mapping[str, Any], Sequence[Any]]) Tuple[List[Optional[bytes]], bytes][source]

Encode both indexed and unindexed parameters.

New in version 2.0.0.

Parameters

parameters (Mapping[str, Any] or Sequence[Any]) – A dict/list of all parameters of the given event.

Returns

Tuple with first item being Event.encode() result and second item being Event.encode_data() result.

Return type

Tuple[List[bytes or None], bytes]

Raises
  • ValueError – If some required parameters were missing, of some extra parameters were given.

  • TypeError – If given parameters are neither sequence nor mapping.

Examples

>>> event = Event({
...     'inputs': [
...         {'name': 'from', 'indexed': True, 'type': 'address'},
...         {'name': 'value', 'indexed': False, 'type': 'uint256'},
...         {'name': 'to', 'indexed': True, 'type': 'address'},
...         {'name': 'value2', 'indexed': False, 'type': 'uint64'},
...     ],
...     'name': 'MyEvent',
...     'type': 'event',
... })
>>> address_from = '0x' + 'f' * 40
>>> address_to = '0x' + '9' * 40

Expected values:

>>> topics_enc = event.encode([address_from, address_to])
>>> data_enc = event.encode_data([256, 127])

Now with Event.encode_full():

>>> topics, data = event.encode_full([address_from, 256, address_to, 127])
>>> assert topics == topics_enc
>>> assert data == data_enc

Or in mapping form (note that order doesn’t matter):

>>> topics, data = event.encode_full({
...     'to': address_to,
...     'value': 256,
...     'value2': 127,
...     'from': address_from,
... })
>>> assert topics == topics_enc
>>> assert data == data_enc
decode(data: bytes, topics: Optional[Sequence[Optional[bytes]]] = None) thor_devkit.abi.FunctionResult[source]

Decode “data” according to the “topic”s.

One output can contain an array of logs.

Changed in version 2.0.0: Return type is not a dict anymore.

Parameters
  • data (bytes) – Data to decode. It should be b'\x00' for event without unindexed parameters.

  • topics (Sequence[bytes or None], optional) –

    Sequence of topics. Fill unknown or not important positions with None, it will be preserved.

    None is interpreted like list of proper length where all items (except signature, if needed) are None.

Returns

Decoded data.

Return type

FunctionResult

Raises

ValueError – If topics count does not match the number of indexed parameters.

Notes

One log contains mainly 3 entries:

  • For a non-indexed parameters event:

    "address": "The emitting contract address",
    "topics": [
        "signature of event"
    ],
    "data": "0x..."  # contains parameters values
    
  • For an indexed parameters event:

    "address": "The emitting contract address",
    "topics": [
        "signature of event",
        "indexed param 1",
        "indexed param 2",
        # ...
        # --> max 3 entries of indexed params.
    ],
    "data": "0x..."  # remaining unindexed parameters values
    

If the event is “anonymous” then the signature is not inserted into the “topics” list, hence topics[0] is not the signature.

Examples

Decode indexed topic that is not hashed:

>>> event = Event({
...     'inputs': [
...         {'indexed': True, 'name': 'a1', 'type': 'bool'},
...     ],
...     'name': 'MyEvent',
...     'type': 'event',
... })
>>> topics = [
...     event.signature,  # Not anonymous
...     b'\x01'.rjust(32, b'\x00'),  # True as 32-byte integer
... ]
>>> data = b'\x00'  # No unindexed topics
>>> event.decode(data, topics).to_dict()
{'a1': True}

Decode mix of indexed and unindexed parameters:

>>> event = Event({
...     'inputs': [
...         {'indexed': True, 'name': 't1', 'type': 'bool'},
...         {'indexed': True, 'name': 't2', 'type': 'bool'},
...         {'indexed': False, 'name': 'u1', 'type': 'string'},
...     ],
...     'name': 'MyEvent',
...     'type': 'event',
...     'anonymous': True,
... })
>>> topics = [
...     b'\x01'.rjust(32, b'\x00'),  # True as 32-byte integer
...     b'\x00'.rjust(32, b'\x00'),  # False as 32-byte integer
... ]
>>> data = (
...     b''
...     + b'\x20'.rjust(32, b'\x00')  # address of first argument
...     + b'\x03'.rjust(32, b'\x00')  # length of b'foo'
...     + b'foo'.ljust(32, b'\x00')  # b'foo'
... )  # string 'foo' encoded
>>> event.decode(data, topics).to_dict()
{'t1': True, 't2': False, 'u1': 'foo'}

“Decode” hashed topic:

>>> from thor_devkit.cry import keccak256
>>> event = Event({
...     'inputs': [
...         {'indexed': True, 'name': 't1', 'type': 'string'},
...     ],
...     'name': 'MyEvent',
...     'type': 'event',
...     'anonymous': True,
... })
>>> encoded_topic = b'foo'.ljust(32, b'\x00')
>>> topic = keccak256([encoded_topic])[0]
>>> assert event.decode(b'\x00', [topic]).t1 == topic

Note that we don’t get a string as output due to the nature of indexed parameters.

See also

Function.decode()

for examples of result usage.

classmethod from_solidity(*, text: Optional[str] = None, file: Optional[Union[str, os.PathLike[str]]] = None, name: Optional[str] = None, version: Optional[str] = None) thor_devkit.abi.Event[source]

Instantiate Event from solidity definition.

New in version 2.0.0.

Parameters
  • text (str or None (keyword-only)) – Program text.

  • file (os.PathLike or Path or None (keyword-only)) – File with program source.

  • name (str or None) – Name of event to select. Do not filter by name if None.

  • version (str or None (keyword-only)) – Solidity version (supported by install_solc()) or None to use default.

Raises
  • ValueError – If required type (event or function) cannot be uniquely extracted.

  • SolcError – If input is not a valid solidity code.

See also

py-solc-x

underlying library reference.

Examples

>>> from pprint import pprint
>>> contract = '''
...     contract A {
...         event E(uint x) anonymous;
...     }
... '''
>>> ev = Event.from_solidity(text=contract)
>>> pprint(ev._definition)
{'anonymous': True,
 'inputs': [{'indexed': False,
             'internalType': 'uint256',
             'name': 'x',
             'type': 'uint256'}],
 'name': 'E',
 'type': 'event'}

No matching events:

>>> Event.from_solidity(text='contract A { function f(int x) public {} }')
Traceback (most recent call last):
ValueError: Missing value of expected type.

Many matching events:

>>> contract = '''
...     contract A {
...         event E1(int x) anonymous;
...         event E2() ;
...     }
... '''
>>> Event.from_solidity(text=contract)
Traceback (most recent call last):
ValueError: Ambiguous input: more than one event given.

Many matching events, use name:

>>> ev = Event.from_solidity(text=contract, name='E2')
>>> pprint(ev._definition)
{'anonymous': False, 'inputs': [], 'name': 'E2', 'type': 'event'}

Syntax error:

>>> Event.from_solidity(
...     text='contract A { event E() {} }'
... )  
Traceback (most recent call last):
solcx.exceptions.SolcError: An error occurred during execution
get_signature() bytes[source]

Get signature.

Deprecated since version 2.0.0: Use signature property instead

class thor_devkit.abi.Coder[source]

Bases: object

Convenient wrapper to namespace encoding functions.

Methods:

encode_list

Encode a sequence of values, into a single bytes.

decode_list

Decode the data, back to a (...) tuple.

encode_single

Encode value of type t into single bytes.

decode_single

Decode data of type t back to a single object.

static encode_list(types: Sequence[str], values: Sequence[Any]) bytes[source]

Encode a sequence of values, into a single bytes.

static decode_list(types: Sequence[str], data: bytes) List[Any][source]

Decode the data, back to a (...) tuple.

static encode_single(t: str, value: Any) bytes[source]

Encode value of type t into single bytes.

static decode_single(t: str, data: bytes) Any[source]

Decode data of type t back to a single object.

thor_devkit.abi.StateMutabilityT(*args, **kwargs)

Literal type of stateMutability parameter.

Must be a string, one of: “pure”, “view”, “payable”, “nonpayable”.

New in version 2.0.0.

alias of Literal[‘pure’, ‘view’, ‘payable’, ‘nonpayable’]

class thor_devkit.abi.FuncParameterT[source]

Bases: TypedDict

Type of ABI function parameter.

New in version 2.0.0.

Attributes:

internalType

InternalType is used for struct name aliases, may be ignored.

components

Sequence of components, each must be FuncParameterT.

name

Parameter name.

type

Parameter type.

internalType: typing_extensions.NotRequired[str]

InternalType is used for struct name aliases, may be ignored.

components: typing_extensions.NotRequired[Sequence[thor_devkit.abi.FuncParameterT]]

Sequence of components, each must be FuncParameterT.

name: str

Parameter name.

type: str

Parameter type.

class thor_devkit.abi.FunctionT[source]

Bases: TypedDict

Type of ABI function dictionary representation.

New in version 2.0.0.

Attributes:

type

Always function.

name

Function name.

stateMutability

Mutability (pure, view, payable or nonpayable).

inputs

Function parameters.

outputs

Function returns.

type: Literal['function']

Always function.

name: str

Function name.

stateMutability: Literal['pure', 'view', 'payable', 'nonpayable']

Mutability (pure, view, payable or nonpayable).

inputs: Sequence[thor_devkit.abi.FuncParameterT]

Function parameters.

outputs: Sequence[thor_devkit.abi.FuncParameterT]

Function returns.

class thor_devkit.abi.ConstructorT[source]

Bases: TypedDict

Type of ABI function dictionary representation.

New in version 2.0.0.

Attributes:

type

Always function.

stateMutability

Mutability (pure, view, payable or nonpayable).

inputs

Constructor parameters.

type: Literal['constructor']

Always function.

stateMutability: Literal['pure', 'view', 'payable', 'nonpayable']

Mutability (pure, view, payable or nonpayable).

inputs: Sequence[thor_devkit.abi.FuncParameterT]

Constructor parameters.

class thor_devkit.abi.EventParameterT[source]

Bases: TypedDict

Type of ABI event parameter.

New in version 2.0.0.

Attributes:

indexed

Whether parameter is indexed.

internalType

InternalType is used for struct name aliases, may be ignored.

components

Sequence of components, each must be EventParameterT.

name

Parameter name.

type

Parameter type.

indexed: bool

Whether parameter is indexed.

internalType: typing_extensions.NotRequired[str]

InternalType is used for struct name aliases, may be ignored.

components: typing_extensions.NotRequired[Sequence[thor_devkit.abi.EventParameterT]]

Sequence of components, each must be EventParameterT.

name: str

Parameter name.

type: str

Parameter type.

class thor_devkit.abi.EventT[source]

Bases: TypedDict

Type of ABI event dictionary representation.

New in version 2.0.0.

Attributes:

type

Always event.

name

Event name.

inputs

Event inputs.

anonymous

Whether event is anonymous (does not include signature in topic).

type: Literal['event']

Always event.

name: str

Event name.

inputs: Sequence[thor_devkit.abi.EventParameterT]

Event inputs.

anonymous: typing_extensions.NotRequired[bool]

Whether event is anonymous (does not include signature in topic).

thor_devkit.abi.MUTABILITY(data): Final

Validation Schema for stateMutability parameter.

Must be a string, one of: “pure”, “view”, “payable”, “nonpayable”.

Changed in version 2.0.0: Removed unsupported “constant” option.

thor_devkit.abi.FUNC_PARAMETER(data): Final

Validation Schema for function parameter.

thor_devkit.abi.FUNCTION(data): Final

Validation Schema for ABI function.

Changed in version 2.0.0: Removed not required members which are not produced by solidity compiler by default, namely constant and payable. All non-standard parameters are silently discarded now.

thor_devkit.abi.CONSTRUCTOR(data): Final

Validation Schema for ABI constructor.

Constructor is a special function case that doesn’t produce outputs and is unnamed.

New in version 2.0.0.

thor_devkit.abi.EVENT_PARAMETER(data): Final

Validation Schema for event parameter.

thor_devkit.abi.EVENT(data): Final

Validation Schema for ABI event.

thor_devkit.abi.calc_event_topic(abi_json: thor_devkit.abi.EventT) bytes[source]

Calculate the event log topic (32 bytes) from the ABI json.

thor_devkit.abi.calc_function_selector(abi_json: thor_devkit.abi.FunctionT) bytes[source]

Calculate the function selector (4 bytes) from the ABI json.

class thor_devkit.abi.FunctionResult[source]

Bases: object

Mixin for NamedTuple with convenience methods.

It is returned from Event.decode() and Function.decode().

When obtained from decode method of Function or Event, this class will contain decoded parameters. They can be obtained either by name or by numeric index as from plain tuples.

New in version 2.0.0.

Warning

Names of result items can slightly differ from names in definition. See details below.

See also

FunctionResult.name_to_identifier()

Details of names changing.

Function.decode()

for examples of items access

Methods:

to_dict

Return dictionary representation (recursively).

name_to_identifier

Convert given word to valid python identifier.

name_from_identifier

Reverse conversion to valid python identifier.

to_dict() Dict[str, Any][source]

Return dictionary representation (recursively).

Returns

Dictionary of form {name: value} (all inner namedtuples are converted too)

Return type

Dict[str, Any]

Note

This method reverts name changing, except empty strings. Unnamed parameters will be still represented as ret_{i}, while python keywords are restored (so from_ is again from key).

static name_to_identifier(word: str, position: int = 0) str[source]

Convert given word to valid python identifier.

It assumes that word is a valid solidity identifier or empty string.

The following rules apply:

  • Empty string are converted to f"ret_{position}"

  • Python keyword (maybe already with underscores at the end) gets underscore (_) appended

  • All other words are returned unchanged.

Parameters
  • word (str) – Solidity identifier to make compatible.

  • position (int) – Arbitrary integer, unique for your collection (different for different calls).

Returns

Valid python identifier.

Return type

str

Raises

ValueError – If given string is not a valid solidity identifier.

Examples

>>> FunctionResult.name_to_identifier('foo')
'foo'
>>> FunctionResult.name_to_identifier('')
'ret_0'
>>> FunctionResult.name_to_identifier('', 1)
'ret_1'
>>> FunctionResult.name_to_identifier('for')
'for_'
>>> FunctionResult.name_to_identifier('from_')
'from__'
>>> FunctionResult.name_to_identifier('1f')
Traceback (most recent call last):
ValueError: Invalid identifier given: '1f'
static name_from_identifier(word: str) str[source]

Reverse conversion to valid python identifier.

It assumes that word was a result of FunctionResult.name_to_identifier().

The following rules apply:

  • Word that are of form keyword(_)+ (with at least one underscore _ at the end) lose one underscore

  • All other words are returned unchanged.

Parameters

word (str) – Identifier to reverse.

Returns

Valid solidity identifier.

Return type

str

Examples

>>> FunctionResult.name_from_identifier('foo')
'foo'
>>> FunctionResult.name_from_identifier('ret_0')
'ret_0'
>>> FunctionResult.name_from_identifier('for_')
'for'
>>> FunctionResult.name_from_identifier('from__')
'from_'
class thor_devkit.abi.Encodable(definition: Any)[source]

Bases: Generic[thor_devkit.abi._ParamT], abc.ABC

Base class for Function and Event.

New in version 2.0.0.

Methods:

encode

Encode parameters into bytes.

decode

Decode data from bytes to namedtuple.

make_proper_type

Extract type string (inline tuples) from JSON.

apply_recursive_names

Build namedtuple from values.

from_solidity

Instantiate Encodable from solidity definition.

abstract encode(_Encodable__parameters: Sequence[Any]) Union[bytes, str, List[Optional[bytes]]][source]

Encode parameters into bytes.

abstract decode(_Encodable__data: bytes) thor_devkit.abi.FunctionResult[source]

Decode data from bytes to namedtuple.

classmethod make_proper_type(elem: thor_devkit.abi._ParamT) str[source]

Extract type string (inline tuples) from JSON.

classmethod apply_recursive_names(value: Any, typeinfo: thor_devkit.abi._ParamT, chain: Optional[Sequence[str]] = None) Union[thor_devkit.abi.FunctionResult, List[thor_devkit.abi.FunctionResult], Any][source]

Build namedtuple from values.

classmethod from_solidity(*, text: Optional[str] = None, file: Optional[Union[str, os.PathLike[str]]] = None, name: Optional[str] = None, version: Optional[str] = None) thor_devkit.abi._Self[source]

Instantiate Encodable from solidity definition.

New in version 2.0.0.

Parameters
  • text (str or None (keyword-only)) – Program text.

  • file (os.PathLike or Path or None (keyword-only)) – File with program source.

  • name (str or None) – Name of encodable to extract.

  • version (str or None (keyword-only)) – Solidity version (supported by install_solc()) or None to use default.

Raises
  • ValueError – If required type (event or function) cannot be uniquely extracted.

  • SolcError – If input is not a valid solidity code.

See also

py-solc-x

underlying library reference.

class thor_devkit.abi.FunctionBase(definition: Any)[source]

Bases: thor_devkit.abi.Encodable[thor_devkit.abi.FuncParameterT]

Base class for ABI functions (function itself and constructor).

New in version 2.0.0.

Methods:

encode

Encode the parameters according to the function definition.

decode_parameters

Decode parameters back to values.

apply_recursive_names

Build namedtuple from values.

decode

Decode data from bytes to namedtuple.

from_solidity

Instantiate Encodable from solidity definition.

make_proper_type

Extract type string (inline tuples) from JSON.

Attributes:

selector

Selector to prepend to encoded data.

encode(parameters: Union[Sequence[Any], Mapping[str, Any]]) bytes[source]

Encode the parameters according to the function definition.

Parameters

parameters (Sequence[Any] or Mapping[str, Any]) – A list of parameters waiting to be encoded, or a mapping from names to values.

Returns

Encoded value

Return type

bytes

decode_parameters(value: bytes) thor_devkit.abi.FunctionResult[source]

Decode parameters back to values.

New in version 2.0.0.

Parameters

value (bytes) – Data to decode.

Returns

Decoded values.

Return type

FunctionResult

classmethod apply_recursive_names(value: Any, typeinfo: thor_devkit.abi._ParamT, chain: Optional[Sequence[str]] = None) Union[thor_devkit.abi.FunctionResult, List[thor_devkit.abi.FunctionResult], Any]

Build namedtuple from values.

abstract decode(_Encodable__data: bytes) thor_devkit.abi.FunctionResult

Decode data from bytes to namedtuple.

classmethod from_solidity(*, text: Optional[str] = None, file: Optional[Union[str, os.PathLike[str]]] = None, name: Optional[str] = None, version: Optional[str] = None) thor_devkit.abi._Self

Instantiate Encodable from solidity definition.

New in version 2.0.0.

Parameters
  • text (str or None (keyword-only)) – Program text.

  • file (os.PathLike or Path or None (keyword-only)) – File with program source.

  • name (str or None) – Name of encodable to extract.

  • version (str or None (keyword-only)) – Solidity version (supported by install_solc()) or None to use default.

Raises
  • ValueError – If required type (event or function) cannot be uniquely extracted.

  • SolcError – If input is not a valid solidity code.

See also

py-solc-x

underlying library reference.

classmethod make_proper_type(elem: thor_devkit.abi._ParamT) str

Extract type string (inline tuples) from JSON.

abstract property selector: bytes

Selector to prepend to encoded data.