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
Type |
Description |
---|---|
Elementary types |
|
uint<M> int<M> |
Unsigned and signed
M -bit integer.\(0 < M \leq 256\),
\(M \equiv 0 \pmod 8\)
|
|
Synonym for |
int uint |
Synonyms for
int256 and uint256 Normalized to full form when computing selector.
|
|
Equivalent to |
fixed<M>x<N> ufixed<M>x<N> |
Signed (unsigned) fixed-point
M -bit numbersuch 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.
|
|
Sequence of |
|
Synonym of |
Fixed-length types |
|
|
Fixed sized array of type
<type> .Examples:
int[10] , uint256[33] |
Dynamic types |
|
|
Bytes of arbitrary length. |
|
String of arbitrary length. |
|
Array of |
Further reading
API documentation
ABI encoding module.
Classes:
ABI Function. |
|
ABI constructor function. |
|
ABI Event. |
|
Convenient wrapper to namespace encoding functions. |
|
Mixin for |
|
Base class for ABI functions (function itself and constructor). |
Type or structure checkers:
Literal type of |
|
Type of ABI function parameter. |
|
Type of ABI function dictionary representation. |
|
Type of ABI function dictionary representation. |
|
Type of ABI event parameter. |
|
Type of ABI event dictionary representation. |
|
Validation |
|
Validation |
|
Validation |
|
Validation |
|
Validation |
|
Validation |
Functions:
Calculate the event log topic (32 bytes) from the ABI json. |
|
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
todefinition
.Methods:
Build namedtuple from values.
Decode parameters back to values.
Extract type string (inline tuples) from JSON.
Encode the parameters according to the function definition.
Decode function call output data back into human readable results.
Encode the return values according to the function definition.
Instantiate
Function
from solidity definition.Deprecated:
Get name of object.
First 4 bytes of function signature hash.
Attributes:
Get name of object.
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
- classmethod make_proper_type(elem: thor_devkit.abi._ParamT) str
Extract type string (inline tuples) from JSON.
- 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
- 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) andFunctionResult
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
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
- 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()
) orNone
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
- 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:
Build namedtuple from values.
Decode parameters back to values.
Encode the parameters according to the function definition.
Instantiate
Encodable
from solidity definition.Extract type string (inline tuples) from JSON.
Constructor does not have outputs, so nothing to decode.
Attributes:
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
- encode(parameters: Union[Sequence[Any], Mapping[str, Any]]) bytes
Encode the parameters according to the function definition.
- 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()
) orNone
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.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
todefinition
.- Parameters
- Raises
ValueError – If number of indexed parameters exceeds the limit.
Invalid – If given definition is malformed.
Methods:
Build namedtuple from values.
Extract type string (inline tuples) from JSON.
Check if the input type requires hashing in indexed parameter.
Join sequence of bytes together and pad to multiple of
mod
.Encode single value according to given
type_
.Assemble indexed keys into topics.
Encode unindexed parameters into bytes.
Encode both indexed and unindexed parameters.
Decode "data" according to the "topic"s.
Instantiate
Event
from solidity definition.Deprecated:
Get name of object.
Get signature.
Attributes:
Get name of object.
Whether this event is anonymous.
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.
- classmethod make_proper_type(elem: thor_devkit.abi._ParamT) str
Extract type string (inline tuples) from JSON.
- 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
- Returns
Given sequence joined and padded to multiple of
mod
.- Return type
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 touint160
, so one would expect justbytes.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
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 beingEvent.encode_data()
result.- Return type
- 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) areNone
.
- Returns
Decoded data.
- Return type
- 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()
) orNone
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
- class thor_devkit.abi.Coder[source]
Bases:
object
Convenient wrapper to namespace encoding functions.
Methods:
Encode a sequence of values, into a single bytes.
Decode the data, back to a
(...)
tuple.Encode value of type
t
into single bytes.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.
- 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 is used for struct name aliases, may be ignored.
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
.
- class thor_devkit.abi.FunctionT[source]
Bases:
TypedDict
Type of ABI function dictionary representation.
New in version 2.0.0.
Attributes:
Always
function
.Function name.
Mutability (pure, view, payable or nonpayable).
Function parameters.
Function returns.
- type: Literal['function']
Always
function
.
- 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:
Always
function
.Mutability (pure, view, payable or nonpayable).
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:
Whether parameter is indexed.
InternalType is used for struct name aliases, may be ignored.
Sequence of components, each must be
EventParameterT
.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.EventParameterT]]
Sequence of components, each must be
EventParameterT
.
- class thor_devkit.abi.EventT[source]
Bases:
TypedDict
Type of ABI event dictionary representation.
New in version 2.0.0.
Attributes:
Always
event
.Event name.
Event inputs.
Whether event is anonymous (does not include signature in
topic
).- type: Literal['event']
Always
event
.
- inputs: Sequence[thor_devkit.abi.EventParameterT]
Event inputs.
- thor_devkit.abi.MUTABILITY(data): Final
Validation
Schema
forstateMutability
parameter.Must be a string, one of: “pure”, “view”, “payable”, “nonpayable”.
Changed in version 2.0.0: Removed unsupported “constant” option.
- 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
andpayable
. 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.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()
andFunction.decode()
.When obtained from
decode
method ofFunction
orEvent
, 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:
Return dictionary representation (recursively).
Convert given word to valid python 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 (sofrom_
is againfrom
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 validsolidity
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 (
_
) appendedAll other words are returned unchanged.
- Parameters
- Returns
Valid python identifier.
- Return type
- 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 ofFunctionResult.name_to_identifier()
.The following rules apply:
Word that are of form
keyword(_)+
(with at least one underscore_
at the end) lose one underscoreAll other words are returned unchanged.
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
andEvent
.New in version 2.0.0.
Methods:
Encode parameters into bytes.
Decode data from bytes to namedtuple.
Extract type string (inline tuples) from JSON.
Build namedtuple from values.
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()
) orNone
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 the parameters according to the function definition.
Decode parameters back to values.
Build namedtuple from values.
Decode data from bytes to namedtuple.
Instantiate
Encodable
from solidity definition.Extract type string (inline tuples) from JSON.
Attributes:
Selector to prepend to encoded data.
- encode(parameters: Union[Sequence[Any], Mapping[str, Any]]) bytes [source]
Encode the parameters according to the function definition.
- 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
- 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()
) orNone
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.