sdk_interface package

Subpackages

Submodules

sdk_interface.base module

class sdk_interface.base.ExtrinsicReceipt(substrate: SubstrateInterface, extrinsic_hash: str | None = None, block_hash: str | None = None, block_number: int | None = None, extrinsic_idx: int | None = None, finalized=None)[source]

Bases: object

Object containing information of submitted extrinsic. Block hash where extrinsic is included is required

when retrieving triggered events or determine if extrinsic was succesfull

classmethod create_from_extrinsic_identifier(substrate: SubstrateInterface, extrinsic_identifier: str) ExtrinsicReceipt[source]

Create an ExtrinsicReceipt with on-chain identifier for this extrinsic in format “[block_number]-[extrinsic_idx]” e.g. 134324-2

Parameters

substrate: SubstrateInterface extrinsic_identifier: str

Returns

ExtrinsicReceipt

property error_message: dict | None

Returns the error message if the extrinsic failed in format e.g.:

{‘type’: ‘System’, ‘name’: ‘BadOrigin’, ‘docs’: ‘Bad origin’}

Returns

dict

property extrinsic: GenericExtrinsic

Retrieves the Extrinsic subject of this receipt

Returns

Extrinsic

property extrinsic_idx: int

Retrieves the index of this extrinsic in containing block

Returns

int

get(name)[source]
get_extrinsic_identifier() str[source]

Returns the on-chain identifier for this extrinsic in format “[block_number]-[extrinsic_idx]” e.g. 134324-2 Returns ——- str

property is_success: bool

Returns True if ExtrinsicSuccess event is triggered, False in case of ExtrinsicFailed In case of False error_message will contain more details about the error

Returns

bool

process_events()[source]
retrieve_extrinsic()[source]
property total_fee_amount: int

Contains the total fee costs deducted when executing this extrinsic. This includes fee for the validator ( (Balances.Deposit event) and the fee deposited for the treasury (Treasury.Deposit event)

Returns

int

property triggered_events: list

Gets triggered events for submitted extrinsic. block_hash where extrinsic is included is required, manually set block_hash or use wait_for_inclusion when submitting extrinsic

Returns

list

property weight: int | dict

Contains the actual weight when executing this extrinsic

Returns

int (WeightV1) or dict (WeightV2)

class sdk_interface.base.SubstrateInterface(url=None, websocket=None, ss58_format=None, type_registry=None, type_registry_preset=None, cache_region=None, runtime_config=None, use_remote_preset=False, ws_options=None, auto_discover=True, auto_reconnect=True, config=None)[source]

Bases: object

apply_type_registry_presets(use_remote_preset: bool = True, auto_discover: bool = True)[source]
property chain
close()[source]

Cleans up resources for this instance like active websocket connection and active extensions

Returns

compose_call(call_module: str, call_function: str, call_params: dict | None = None, block_hash: str | None = None) GenericCall[source]

Composes a call payload which can be used in an extrinsic.

Parameters

call_module: Name of the runtime module e.g. Balances call_function: Name of the call function e.g. transfer call_params: This is a dict containing the params of the call. e.g. {‘dest’: ‘EaG2CRhJWPb7qmdcJvy3LiWdh26Jreu9Dx6R1rXxPmYXoDk’, ‘value’: 1000000000000} block_hash: Use metadata at given block_hash to compose call

Returns

GenericCall

connect_websocket()[source]

(Re)creates the websocket connection, if the URL contains a ‘ws’ or ‘wss’ scheme

Returns

convert_storage_parameter(scale_type, value)[source]
create_multisig_extrinsic(call: GenericCall, keypair: Keypair, multisig_account: MultiAccountId, max_weight: dict | int | None = None, era: dict | None = None, nonce: int | None = None, tip: int = 0, tip_asset_id: int | None = None, signature: bytes | str | None = None) GenericExtrinsic[source]

Create a Multisig extrinsic that will be signed by one of the signatories. Checks on-chain if the threshold of the multisig account is reached and try to execute the call accordingly.

Parameters

call: GenericCall to create extrinsic for keypair: Keypair of the signatory to approve given call multisig_account: MultiAccountId to use of origin of the extrinsic (see generate_multisig_account()) max_weight: Maximum allowed weight to execute the call ( Uses get_payment_info() by default) era: Specify mortality in blocks in follow format: {‘period’: [amount_blocks]} If omitted the extrinsic is immortal nonce: nonce to include in extrinsics, if omitted the current nonce is retrieved on-chain tip: The tip for the block author to gain priority during network congestion tip_asset_id: Optional asset ID with which to pay the tip signature: Optionally provide signature if externally signed

Returns

GenericExtrinsic

create_scale_object(type_string: str, data: ScaleBytes | None = None, block_hash: str | None = None, **kwargs) ScaleType[source]

Convenience method to create a SCALE object of type type_string, this will initialize the runtime automatically at moment of block_hash, or chain tip if omitted.

Parameters

type_string: str Name of SCALE type to create data: ScaleBytes Optional ScaleBytes to decode block_hash: Optional block hash for moment of decoding, when omitted the chain tip will be used kwargs

Returns

ScaleType

create_signed_extrinsic(call: GenericCall, keypair: Keypair, era: dict | None = None, nonce: int | None = None, tip: int = 0, tip_asset_id: int | None = None, signature: bytes | str | None = None) GenericExtrinsic[source]

Creates an extrinsic signed by given account details

Parameters

call: GenericCall to create extrinsic for keypair: Keypair used to sign the extrinsic era: Specify mortality in blocks in follow format: {‘period’: [amount_blocks]} If omitted the extrinsic is immortal nonce: nonce to include in extrinsics, if omitted the current nonce is retrieved on-chain tip: The tip for the block author to gain priority during network congestion tip_asset_id: Optional asset ID with which to pay the tip signature: Optionally provide signature if externally signed

Returns

GenericExtrinsic The signed Extrinsic

create_storage_key(pallet: str, storage_function: str, params: list | None = None) StorageKey[source]

Create a StorageKey instance providing storage function details. See subscribe_storage().

Parameters

pallet: name of pallet storage_function: name of storage function params: Optional list of parameters in case of a Mapped storage function

Returns

StorageKey

create_unsigned_extrinsic(call: GenericCall) GenericExtrinsic[source]

Create unsigned extrinsic for given Call Parameters ———- call: GenericCall the call the extrinsic should contain

Returns

GenericExtrinsic

static debug_message(message: str)[source]

Submits a message to the debug logger

Parameters

message: str Debug message

Returns

decode_scale(type_string, scale_bytes, block_hash=None, return_scale_obj=False)[source]

Helper function to decode arbitrary SCALE-bytes (e.g. 0x02000000) according to given RUST type_string (e.g. BlockNumber). The relevant versioning information of the type (if defined) will be applied if block_hash is set

Parameters

type_string scale_bytes block_hash return_scale_obj: if True the SCALE object itself is returned, otherwise the serialized dict value of the object

Returns

encode_scale(type_string, value, block_hash=None) ScaleBytes[source]

Helper function to encode arbitrary data into SCALE-bytes for given RUST type_string

Parameters

type_string value block_hash

Returns

ScaleBytes

extension_call(name, **kwargs)[source]
filter_events(**kwargs) list[source]
filter_extrinsics(**kwargs) list[source]
generate_multisig_account(signatories: list, threshold: int) MultiAccountId[source]

Generate deterministic Multisig account with supplied signatories and threshold Parameters ———- signatories: List of signatories threshold: Amount of approvals needed to execute

Returns

MultiAccountId

generate_signature_payload(call: GenericCall, era=None, nonce: int = 0, tip: int = 0, tip_asset_id: int | None = None, include_call_length: bool = False) ScaleBytes[source]
generate_storage_hash(storage_module: str, storage_function: str, params: list | None = None, hashers: list | None = None) str[source]

Generate a storage key for given module/function

Parameters

storage_module storage_function params: Parameters of the storage function, provided in scale encoded hex-bytes or ScaleBytes instances hashers: Hashing methods used to determine storage key, defaults to ‘Twox64Concat’ if not provided

Returns

str Hexstring respresentation of the storage key

get_account_nonce(account_address) int[source]

Returns current nonce for given account address

Parameters

account_address: SS58 formatted address

Returns

int

get_block(block_hash: str | None = None, block_number: int | None = None, ignore_decoding_errors: bool = False, include_author: bool = False, finalized_only: bool = False) dict | None[source]

Retrieves a block and decodes its containing extrinsics and log digest items. If block_hash and block_number is omited the chain tip will be retrieve, or the finalized head if finalized_only is set to true.

Either block_hash or block_number should be set, or both omitted.

Parameters

block_hash: the hash of the block to be retrieved block_number: the block number to retrieved ignore_decoding_errors: When set this will catch all decoding errors, set the item to None and continue decoding include_author: This will retrieve the block author from the validator set and add to the result finalized_only: when no block_hash or block_number is set, this will retrieve the finalized head

Returns

A dict containing the extrinsic and digest logs data

get_block_hash(block_id: int | None = None) str[source]

A pass-though to existing JSONRPC method chain_getBlockHash

Parameters

block_id

Returns

get_block_header(block_hash: str | None = None, block_number: int | None = None, ignore_decoding_errors: bool = False, include_author: bool = False, finalized_only: bool = False)[source]

Retrieves a block header and decodes its containing log digest items. If block_hash and block_number is omited the chain tip will be retrieve, or the finalized head if finalized_only is set to true.

Either block_hash or block_number should be set, or both omitted.

See get_block() to also include the extrinsics in the result

Parameters

block_hash: the hash of the block to be retrieved block_number: the block number to retrieved ignore_decoding_errors: When set this will catch all decoding errors, set the item to None and continue decoding include_author: This will retrieve the block author from the validator set and add to the result finalized_only: when no block_hash or block_number is set, this will retrieve the finalized head

Returns

A dict containing the header and digest logs data

get_block_metadata(block_hash=None, decode=True)[source]

A pass-though to existing JSONRPC method state_getMetadata.

Parameters

block_hash decode: True for decoded version

Returns

get_block_number(block_hash: str) int[source]

A convenience method to get the block number for given block_hash

Parameters

block_hash

Returns

get_block_runtime_version(block_hash)[source]

Retrieve the runtime version id of given block_hash Parameters ———- block_hash

Returns

get_block_timestamp(block_number: int) int[source]
get_chain_finalised_head()[source]

A pass-though to existing JSONRPC method chain_getFinalizedHead

Returns

get_chain_head()[source]

A pass-though to existing JSONRPC method chain_getHead

Returns

get_constant(module_name, constant_name, block_hash=None) ScaleType | None[source]

Returns the decoded ScaleType object of the constant for given module name, call function name and block_hash (or chaintip if block_hash is omitted)

Parameters

module_name constant_name block_hash

Returns

ScaleType

get_events(block_hash: str | None = None) list[source]

Convenience method to get events for a certain block (storage call for module ‘System’ and function ‘Events’)

Parameters

block_hash

Returns

list

get_extrinsics(block_hash: str | None = None, block_number: int | None = None) list[source]

Return extrinsics for given block_hash or block_number

Parameters

block_hash block_number

Returns

get_metadata(block_hash=None)[source]

Returns MetadataVersioned object for given block_hash or chaintip if block_hash is omitted

Parameters

block_hash

Returns

MetadataVersioned

get_metadata_call_function(module_name: str, call_function_name: str, block_hash: str | None = None)[source]

Retrieves the details of a call function given module name, call function name and block_hash (or chaintip if block_hash is omitted)

Parameters

module_name call_function_name block_hash

Returns

get_metadata_call_functions(block_hash=None) list[source]

Retrieves a list of all call functions in metadata active for given block_hash (or chaintip if block_hash is omitted)

Parameters

block_hash

Returns

list

get_metadata_constant(module_name, constant_name, block_hash=None)[source]

Retrieves the details of a constant for given module name, call function name and block_hash (or chaintip if block_hash is omitted)

Parameters

module_name constant_name block_hash

Returns

MetadataModuleConstants

get_metadata_constants(block_hash=None) list[source]

Retrieves a list of all constants in metadata active at given block_hash (or chaintip if block_hash is omitted)

Parameters

block_hash

Returns

list

get_metadata_error(module_name, error_name, block_hash=None)[source]

Retrieves the details of an error for given module name, call function name and block_hash

Parameters

module_name error_name block_hash

Returns

get_metadata_errors(block_hash=None) list[source]

Retrieves a list of all errors in metadata active at given block_hash (or chaintip if block_hash is omitted)

Parameters

block_hash

Returns

list

get_metadata_event(module_name, event_name, block_hash=None)[source]

Retrieves the details of an event for given module name, call function name and block_hash (or chaintip if block_hash is omitted)

Parameters

module_name event_name block_hash

Returns

get_metadata_events(block_hash=None) list[source]

Retrieves a list of all events in metadata active for given block_hash (or chaintip if block_hash is omitted)

Parameters

block_hash

Returns

list

get_metadata_module(name, block_hash=None)[source]

Retrieves modules in metadata by name for given block_hash (or chaintip if block_hash is omitted)

Parameters

name block_hash

Returns

MetadataModule

get_metadata_modules(block_hash=None)[source]

Retrieves a list of modules in metadata for given block_hash (or chaintip if block_hash is omitted)

Parameters

block_hash

Returns

get_metadata_runtime_call_function(api: str, method: str) GenericRuntimeCallDefinition[source]

Get details of a runtime API call

Parameters

api: Name of the runtime API e.g. ‘TransactionPaymentApi’ method: Name of the method e.g. ‘query_fee_details’

Returns

GenericRuntimeCallDefinition

get_metadata_runtime_call_functions() list[source]

Get a list of available runtime API calls

Returns

list

get_metadata_storage_function(module_name, storage_name, block_hash=None)[source]

Retrieves the details of a storage function for given module name, call function name and block_hash

Parameters

module_name storage_name block_hash

Returns

get_metadata_storage_functions(block_hash=None) list[source]

Retrieves a list of all storage functions in metadata active at given block_hash (or chaintip if block_hash is omitted)

Parameters

block_hash

Returns

list

get_payment_info(call: GenericCall, keypair: Keypair)[source]

Retrieves fee estimation via RPC for given extrinsic

Parameters

call: Call object to estimate fees for keypair: Keypair of the sender, does not have to include private key because no valid signature is required

Returns

Dict with payment info

E.g. {‘class’: ‘normal’, ‘partialFee’: 151000000, ‘weight’: {‘ref_time’: 143322000}}

get_runtime_metadata(block_hash=None)[source]

Retrieves and decodes the metadata for given block or chaintip if block_hash is omitted.

Parameters

block_hash

Returns

get_storage_by_key(block_hash: str, storage_key: str)[source]

A pass-though to existing JSONRPC method state_getStorage

Parameters

block_hash storage_key

Returns

get_type_definition(type_string: str, block_hash: str | None = None)[source]

Retrieves SCALE encoding specifications of given type_string

Parameters

type_string: RUST variable type, e.g. Vec<Address> or scale_info::0 block_hash

Returns

get_type_registry(block_hash: str | None = None, max_recursion: int = 4) dict[source]

Generates an exhaustive list of which RUST types exist in the runtime specified at given block_hash (or chaintip if block_hash is omitted)

MetadataV14 or higher is required.

Parameters

block_hash: Chaintip will be used if block_hash is omitted max_recursion: Increasing recursion will provide more detail but also has impact on performance

Returns

dict

implements_scaleinfo() bool | None[source]

Returns True if current runtime implementation a PortableRegistry (MetadataV14 and higher)

Returns

bool

init_runtime(block_hash=None, block_id=None)[source]

This method is used by all other methods that deals with metadata and types defined in the type registry. It optionally retrieves the block_hash when block_id is given and sets the applicable metadata for that block_hash. Also it applies all the versioned types at the time of the block_hash.

Because parsing of metadata and type registry is quite heavy, the result will be cached per runtime id. In the future there could be support for caching backends like Redis to make this cache more persistent.

Parameters

block_hash block_id

Returns

is_valid_ss58_address(value: str) bool[source]

Helper function to validate given value as ss58_address for current network/ss58_format

Parameters

value

Returns

bool

property name
property properties
query(module: str, storage_function: str, params: list | None = None, block_hash: str | None = None, subscription_handler: callable | None = None, raw_storage_key: bytes | None = None) ScaleType[source]

Retrieves the storage entry for given module, function and optional parameters at given block hash.

When a subscription_handler callback function is passed, a subscription will be maintained as long as this handler doesn’t return a value.

Example of subscription handler: ``` def subscription_handler(obj, update_nr, subscription_id):

if update_nr == 0:

print(‘Initial data:’, obj.value)

if update_nr > 0:

# Do something with the update print(‘data changed:’, obj.value)

# The execution will block until an arbitrary value is returned, which will be the result of the query if update_nr > 1:

return obj

```

Parameters

module: The module name in the metadata, e.g. Balances or Account storage_function: The storage function name, e.g. FreeBalance or AccountNonce params: list of params, in the decoded format of the applicable ScaleTypes block_hash: Optional block hash, when omitted the chain tip will be used subscription_handler: Callback function that processes the updates of the storage query subscription raw_storage_key: Optional raw storage key to query decode instead of generating one

Returns

ScaleType

query_map(module: str, storage_function: str, params: list | None = None, block_hash: str | None = None, max_results: int | None = None, start_key: str | None = None, page_size: int = 100, ignore_decoding_errors: bool = True) QueryMapResult[source]

Iterates over all key-pairs located at the given module and storage_function. The storage item must be a map.

Example:

``` result = substrate.query_map(‘System’, ‘Account’, max_results=100)

for account, account_info in result:

print(f”Free balance of account ‘{account.value}’: {account_info.value[‘data’][‘free’]}”)

```

Parameters

module: The module name in the metadata, e.g. System or Balances. storage_function: The storage function name, e.g. Account or Locks. params: The input parameters in case of for example a DoubleMap storage function block_hash: Optional block hash for result at given block, when left to None the chain tip will be used. max_results: the maximum of results required, if set the query will stop fetching results when number is reached start_key: The storage key used as offset for the results, for pagination purposes page_size: The results are fetched from the node RPC in chunks of this size ignore_decoding_errors: When set this will catch all decoding errors, set the item to None and continue decoding

Returns

QueryMapResult

query_multi(storage_keys: List[StorageKey], block_hash: str | None = None) list[source]

Query multiple storage keys in one request.

Example:

``` storage_keys = [

substrate.create_storage_key(

“System”, “Account”, [“F4xQKRUagnSGjFqafyhajLs94e7Vvzvr8ebwYJceKpr8R7T”]

), substrate.create_storage_key(

“System”, “Account”, [“GSEX8kR4Kz5UZGhvRUCJG93D5hhTAoVZ5tAe6Zne7V42DSi”]

)

]

result = substrate.query_multi(storage_keys) ```

Parameters

storage_keys: list of StorageKey objects block_hash: Optional block_hash of state snapshot

Returns

list of (storage_key, scale_obj) tuples

register_extension(extension: Extension)[source]

Register an Extension and adds its functionality to the ExtensionRegistry

Parameters

extension: Extension

Returns

reload_type_registry(use_remote_preset: bool = True, auto_discover: bool = True)[source]

Reload type registry and preset used to instantiate the SubtrateInterface object. Useful to periodically apply changes in type definitions when a runtime upgrade occurred

Parameters

use_remote_preset: When True preset is downloaded from Github master, otherwise use files from local installed scalecodec package auto_discover

Returns

retrieve_extrinsic_by_hash(block_hash: str, extrinsic_hash: str) ExtrinsicReceipt[source]

Retrieve an extrinsic by providing the block_hash and the extrinsic hash

Parameters

block_hash extrinsic_hash

Returns

ExtrinsicReceipt

retrieve_extrinsic_by_identifier(extrinsic_identifier: str) ExtrinsicReceipt[source]

Retrieve an extrinsic by its identifier in format “[block_number]-[extrinsic_index]” e.g. 333456-4

Parameters

extrinsic_identifier

Returns

ExtrinsicReceipt

retrieve_pending_extrinsics() list[source]

Retrieves and decodes pending extrinsics from the node’s transaction pool

Returns

list of extrinsics

rpc_request(method, params, result_handler=None)[source]

Method that handles the actual RPC request to the Substrate node. The other implemented functions eventually use this method to perform the request.

Parameters

result_handler: Callback function that processes the result received from the node method: method of the JSONRPC request params: a list containing the parameters of the JSONRPC request

Returns

a dict with the parsed result of the request.

runtime_call(api: str, method: str, params: list | dict | None = None, block_hash: str | None = None) ScaleType[source]

Calls a runtime API method

Parameters

api: Name of the runtime API e.g. ‘TransactionPaymentApi’ method: Name of the method e.g. ‘query_fee_details’ params: List of parameters needed to call the runtime API block_hash: Hash of the block at which to make the runtime API call

Returns

ScaleType

search_block_number(block_datetime: datetime, block_time: int = 6) int[source]
serialize_constant(constant, module, spec_version_id) dict[source]

Helper function to serialize a constant

Parameters

constant module spec_version_id

Returns

dict

serialize_module_call(module, call, spec_version, call_index=None) dict[source]

Helper function to serialize a call function

Parameters

module call spec_version call_index

Returns

dict

serialize_module_error(module, error, spec_version) dict[source]

Helper function to serialize an error

Parameters

module error spec_version

Returns

dict

serialize_module_event(module, event, spec_version, event_index) dict[source]

Helper function to serialize an event

Parameters

module event spec_version event_index

Returns

dict

serialize_storage_item(storage_item, module, spec_version_id) dict[source]

Helper function to serialize a storage item

Parameters

storage_item module spec_version_id

Returns

dict

ss58_decode(ss58_address: str) str[source]

Helper function to decode a SS58 address to a public key

Parameters

ss58_address

Returns

str containing the hex representation of the public key

ss58_encode(public_key: str | bytes, ss58_format: int | None = None) str[source]

Helper function to encode a public key to SS58 address.

If no target ss58_format is provided, it will default to the ss58 format of the network it’s connected to.

Parameters

public_key: 32 bytes or hex-string. e.g. 0x6e39f36c370dd51d9a7594846914035de7ea8de466778ea4be6c036df8151f29 ss58_format: target networkID to format the address for, defaults to the network it’s connected to

Returns

str containing the SS58 address

property ss58_format
submit_extrinsic(extrinsic: GenericExtrinsic, wait_for_inclusion: bool = False, wait_for_finalization: bool = False) ExtrinsicReceipt[source]
Submit an extrinsic to the connected node, with the possibility to wait until the extrinsic is included

in a block and/or the block is finalized. The receipt returned provided information about the block and triggered events

Parameters

extrinsic: Extrinsic The extrinsic to be sent to the network wait_for_inclusion: wait until extrinsic is included in a block (only works for websocket connections) wait_for_finalization: wait until extrinsic is finalized (only works for websocket connections)

Returns

ExtrinsicReceipt

subscribe_block_headers(subscription_handler: callable, ignore_decoding_errors: bool = False, include_author: bool = False, finalized_only=False)[source]

Subscribe to new block headers as soon as they are available. The callable subscription_handler will be executed when a new block is available and execution will block until subscription_handler will return a result other than None.

Example:

``` def subscription_handler(obj, update_nr, subscription_id):

print(f”New block #{obj[‘header’][‘number’]} produced by {obj[‘header’][‘author’]}”)

if update_nr > 10

return {‘message’: ‘Subscription will cancel when a value is returned’, ‘updates_processed’: update_nr}

result = substrate.subscribe_block_headers(subscription_handler, include_author=True) ```

Parameters

subscription_handler ignore_decoding_errors: When set this will catch all decoding errors, set the item to None and continue decoding include_author: This will retrieve the block author from the validator set and add to the result finalized_only: when no block_hash or block_number is set, this will retrieve the finalized head

Returns

Value return by subscription_handler

subscribe_storage(storage_keys: List[StorageKey], subscription_handler: callable)[source]

Subscribe to provided storage_keys and keep tracking until subscription_handler returns a value

Example of a StorageKey: ``` StorageKey.create_from_storage_function(

“System”, “Account”, [“5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY”]

)

Example of a subscription handler: ``` def subscription_handler(storage_key, obj, update_nr, subscription_id):

if update_nr == 0:

print(‘Initial data:’, storage_key, obj.value)

if update_nr > 0:

# Do something with the update print(‘data changed:’, storage_key, obj.value)

# The execution will block until an arbitrary value is returned, which will be the result of the function if update_nr > 1:

return obj

```

Parameters

storage_keys: StorageKey list of storage keys to subscribe to subscription_handler: callable to handle value changes of subscription

Returns

supports_rpc_method(name: str) bool[source]

Check if substrate RPC supports given method Parameters ———- name: name of method to check

Returns

bool

property token_decimals
property token_symbol
update_type_registry_presets() bool[source]
property version

sdk_interface.constants module

sdk_interface.contracts module

class sdk_interface.contracts.ContractCode(code_hash: bytes | None = None, metadata: ContractMetadata | None = None, wasm_bytes: bytes | None = None, substrate: SubstrateInterface | None = None)[source]

Bases: object

classmethod create_from_code_hash(code_hash: bytes, metadata_file: str, substrate: SubstrateInterface) ContractCode[source]

Create a ContractCode providing an existing contract code hash and a path to the metadata JSON file

Parameters

code_hash metadata_file substrate

Returns

ContractCode

classmethod create_from_contract_files(wasm_file: str, metadata_file: str, substrate: SubstrateInterface) ContractCode[source]

Create a ContractCode providing paths for the WASM binary file and metadata JSON file generated by the ink! project

Parameters

wasm_file metadata_file substrate

Returns

ContractCode

deploy(keypair: Keypair, constructor: str, args: dict | None = None, value: int = 0, gas_limit: dict | None = None, deployment_salt: str | None = None, upload_code: bool = False, storage_deposit_limit: int | None = None) ContractInstance[source]

Deploys a new instance of the contract after it has been uploaded on-chain, with provided constructor and constructor arguments

Parameters

keypair constructor: name of the constructor to use, provided in the metadata args: arguments for the constructor value: Value sent to created contract address gas_limit: Gas limit as WeightV2 type. Will default to {‘ref_time’: 25990000000, ‘proof_size’: 11990383647911208550}. deployment_salt: optional string or hex-string that acts as a salt for this deployment upload_code: When True the WASM blob itself will be uploaded with the deploy, False if the WASM is already present on-chain storage_deposit_limit: The maximum amount of balance that can be charged to pay for the storage consumed.

Returns

ContractInstance

upload_wasm(keypair: Keypair, storage_deposit_limit: int | None = None) ExtrinsicReceipt[source]

Created and submits an “Contracts.upload_code” extrinsic containing the WASM binary

Parameters

keypair: Keypair used to sign the extrinsic storage_deposit_limit:T he maximum amount of balance that can be charged to pay for the storage consumed

Returns

ExtrinsicReceipt

class sdk_interface.contracts.ContractEvent(*args, contract_metadata: ContractMetadata | None = None, **kwargs)[source]

Bases: ScaleType

process()[source]

Implementation of the decoding process

Returns

process_encode(value)[source]

Implementation of the encoding process

Parameters

value

Returns

ScaleBytes

class sdk_interface.contracts.ContractExecutionReceipt(*args, **kwargs)[source]

Bases: ExtrinsicReceipt

property contract_events
classmethod create_from_extrinsic_receipt(receipt: ExtrinsicReceipt, contract_metadata: ContractMetadata, contract_address: str | None = None) ContractExecutionReceipt[source]

Promotes a ExtrinsicReceipt object to a ContractExecutionReceipt. It uses the provided ContractMetadata to decode “ContractExecution” events

Parameters

receipt contract_metadata

Returns

ContractExecutionReceipt

process_events()[source]
class sdk_interface.contracts.ContractInstance(contract_address: str, metadata: ContractMetadata | None = None, substrate: SubstrateInterface | None = None)[source]

Bases: object

classmethod create_from_address(contract_address: str, metadata_file: str, substrate: SubstrateInterface | None = None) ContractInstance[source]

Create a ContractInstance object that already exists on-chain providing a SS58-address and the path to the metadata JSON of that contract

Parameters

contract_address: SS58-address of contract metadata_file: path to metadata JSON generated for contract substrate

Returns

ContractInstance

exec(keypair: Keypair, method: str, args: dict | None = None, value: int = 0, gas_limit: dict | None = None, storage_deposit_limit: int | None = None, wait_for_inclusion: bool = True, wait_for_finalization: bool = False) ContractExecutionReceipt[source]

Executes provided message by creating and submitting an extrinsic. To get a gas prediction or perform a ‘dry-run’ of executing this message, see ContractInstance.read.

Parameters

keypair method: name of message to execute args: arguments of message in {‘name’: value} format value: value to send when executing the message gas_limit: dict repesentation of WeightV2 type. When omited the gas limit will be calculated with a read() storage_deposit_limit: The maximum amount of balance that can be charged to pay for the storage consumed wait_for_inclusion: wait until extrinsic is included in a block (only works for websocket connections) wait_for_finalization: wait until extrinsic is finalized (only works for websocket connections)

Returns

ContractExecutionReceipt

init()[source]
read(keypair: Keypair, method: str, args: dict | None = None, value: int = 0, gas_limit: int | None = None, block_hash: str | None = None) GenericContractExecResult[source]

Used to execute non-mutable messages to for example read data from the contract using getters. Can also be used to predict gas limits and ‘dry-run’ the execution when a mutable message is used. This method does not submit an extrinsic.

Parameters

keypair method: name of message to execute args: arguments of message in {‘name’: value} format value: value to send when executing the message gas_limit: dict repesentation of WeightV2 type block_hash: hash of the block to execute the message on

Returns

GenericContractExecResult

class sdk_interface.contracts.ContractMetadata(metadata_dict: dict, substrate: SubstrateInterface)[source]

Bases: object

classmethod create_from_file(metadata_file: str, substrate: SubstrateInterface) ContractMetadata[source]

Create a new ContractMetadata object using the provided metadata_file, usually generated by the command “cargo +nightly contract generate-metadata” in an ink! project

Parameters

metadata_file substrate

Returns

ContractMetadata

generate_constructor_data(name, args: dict | None = None) ScaleBytes[source]

Compose the data field used in the “Contracts.instantiate” call, finding the selectors and encoded the args of given constructor

Parameters

name args

Returns

ScaleBytes

generate_message_data(name, args: dict | None = None) ScaleBytes[source]

Compose the data field used in the “Contracts.call” call, finding the selector and encoded the args of provided message name

Parameters

name: name of message in contract args: arguments required by message, in format: {‘name’: value}

Returns

ScaleBytes

get_event_data(event_id: int) dict[source]

Looks up the event data for given 0-based event_id

Parameters

event_id

Returns

get_event_id_by_topic(topic: str) int | None[source]
get_return_type_string_for_message(name) str[source]
get_type_string_for_metadata_type(type_id: int) str[source]

Adds a type included in the metadata (represented by an index in the type list) to the type registry and produces a type string that can be used in the scope of the RuntimeConfigurationObject.

Parameters

type_id 1-based index of type locating in the metadata types dict

Returns

str

sdk_interface.exceptions module

exception sdk_interface.exceptions.BlockNotFound[source]

Bases: Exception

exception sdk_interface.exceptions.ConfigurationError[source]

Bases: Exception

exception sdk_interface.exceptions.ContractExecFailedException[source]

Bases: Exception

exception sdk_interface.exceptions.ContractMetadataParseException[source]

Bases: ValueError

exception sdk_interface.exceptions.ContractReadFailedException[source]

Bases: Exception

exception sdk_interface.exceptions.DeployContractFailedException[source]

Bases: Exception

exception sdk_interface.exceptions.ExtensionCallNotFound[source]

Bases: AttributeError

exception sdk_interface.exceptions.ExtrinsicFailedException[source]

Bases: Exception

exception sdk_interface.exceptions.ExtrinsicNotFound[source]

Bases: Exception

exception sdk_interface.exceptions.StorageFunctionNotFound[source]

Bases: ValueError

exception sdk_interface.exceptions.SubstrateRequestException[source]

Bases: Exception

sdk_interface.extensions module

class sdk_interface.extensions.Extension[source]

Bases: object

Base class of all extensions

close()[source]

Cleanup process of the extension. This function is being called by the ExtensionRegistry.

Returns

debug_message(message: str)[source]

Submits a debug message in the logger

Parameters

message: str

Returns

init(substrate: SubstrateInterface)[source]

Initialization process of the extension. This function is being called by the ExtensionRegistry.

Parameters

substrate: SubstrateInterface

Returns

class sdk_interface.extensions.SearchExtension[source]

Bases: Extension

Type of Extension that implements functionality to improve and enhance search capability

filter_events(**kwargs) list[source]

Filters events to match provided search criteria e.g. block range, pallet name, accountID in attributes

Parameters

kwargs

Returns

list

filter_extrinsics(**kwargs) list[source]

Filters extrinsics to match provided search criteria e.g. block range, pallet name, signed by accountID

Parameters

kwargs

Returns

get_block_timestamp(block_number: int) int[source]

Return a UNIX timestamp for given block_number.

Parameters

block_number: int The block_number to retrieve the timestamp for

Returns

int

search_block_number(block_datetime: datetime, block_time: int = 6, **kwargs) int[source]

Search corresponding block number for provided block_datetime. the prediction tolerance is provided with block_time

Parameters

block_datetime: datetime block_time: int kwargs

Returns

int

class sdk_interface.extensions.SubstrateNodeExtension(max_block_range: int = 100)[source]

Bases: SearchExtension

Implementation of SearchExtension using only Substrate RPC methods. Could be significant inefficient.

filter_events(block_start: int | None = None, block_end: int | None = None, pallet_name: str | None = None, event_name: str | None = None, account_id: str | None = None) list[source]

Filters events to match provided search criteria e.g. block range, pallet name, accountID in attributes

Parameters

kwargs

Returns

list

filter_extrinsics(block_start: int | None = None, block_end: int | None = None, ss58_address: str | None = None, pallet_name: str | None = None, call_name: str | None = None) list[source]

Filters extrinsics to match provided search criteria e.g. block range, pallet name, signed by accountID

Parameters

kwargs

Returns

get_block_timestamp(block_number: int) int[source]

Return a UNIX timestamp for given block_number.

Parameters

block_number: int The block_number to retrieve the timestamp for

Returns

int

search_block_number(block_datetime: datetime, block_time: int = 6, **kwargs) int[source]

Search corresponding block number for provided block_datetime. the prediction tolerance is provided with block_time

Parameters

block_datetime: datetime block_time: int kwargs

Returns

int

sdk_interface.interfaces module

class sdk_interface.interfaces.ExtensionInterface(substrate)[source]

Bases: object

Keeps tracks of active extensions and which calls can be made

call(name: str, *args, **kwargs)[source]

Tries to call extension function with name and provided args and kwargs

Will raise a ExtensionCallNotFound when no method is found in current extensions

Parameters

name args kwargs

Returns

get_extension_callable(name: str) Callable[source]
register(extension: Extension)[source]

Register an extension instance to the registry and calls initialization

Parameters

extension: Extension

Returns

unregister_all()[source]

Unregister all extensions and free used resources and connections

Returns

sdk_interface.key module

class sdk_interface.key.DeriveJunction(chain_code, is_hard=False)[source]

Bases: object

classmethod from_derive_path(path: str, is_hard=False)[source]
sdk_interface.key.extract_derive_path(derive_path: str)[source]

sdk_interface.keypair module

class sdk_interface.keypair.Keypair(ss58_address: str | None = None, public_key: bytes | str | None = None, private_key: bytes | str | None = None, ss58_format: int | None = None, seed_hex: bytes | str | None = None, crypto_type: int = 1)[source]

Bases: object

classmethod create_from_encrypted_json(json_data: str | dict, passphrase: str, ss58_format: int | None = None) Keypair[source]

Create a Keypair from a PolkadotJS format encrypted JSON file

Parameters

json_data: Dict or JSON string containing PolkadotJS export format passphrase: Used to encrypt the keypair ss58_format: Which network ID to use to format the SS58 address (42 for testnet)

Returns

Keypair

classmethod create_from_mnemonic(mnemonic: str, ss58_format=42, crypto_type=1, language_code: str = 'en') Keypair[source]

Create a Keypair for given memonic

Parameters

mnemonic: Seed phrase ss58_format: Substrate address format crypto_type: Use KeypairType.SR25519 or KeypairType.ED25519 cryptography for generating the Keypair language_code: The language to use, valid values are: ‘en’, ‘zh-hans’, ‘zh-hant’, ‘fr’, ‘it’, ‘ja’, ‘ko’, ‘es’. Defaults to MnemonicLanguageCode.ENGLISH

Returns

Keypair

classmethod create_from_private_key(private_key: bytes | str, public_key: bytes | str | None = None, ss58_address: str | None = None, ss58_format: int | None = None, crypto_type: int = 1) Keypair[source]

Creates Keypair for specified public/private keys Parameters ———- private_key: hex string or bytes of private key public_key: hex string or bytes of public key ss58_address: Substrate address ss58_format: Substrate address format, default = 42 crypto_type: Use KeypairType.[SR25519|ED25519|ECDSA] cryptography for generating the Keypair

Returns

Keypair

classmethod create_from_seed(seed_hex: bytes | str, ss58_format: int | None = 42, crypto_type=1) Keypair[source]

Create a Keypair for given seed

Parameters

seed_hex: hex string of seed ss58_format: Substrate address format crypto_type: Use KeypairType.SR25519 or KeypairType.ED25519 cryptography for generating the Keypair

Returns

Keypair

classmethod create_from_uri(suri: str, ss58_format: int | None = 42, crypto_type=1, language_code: str = 'en') Keypair[source]

Creates Keypair for specified suri in following format: [mnemonic]/[soft-path]//[hard-path]

Parameters

suri: ss58_format: Substrate address format crypto_type: Use KeypairType.SR25519 or KeypairType.ED25519 cryptography for generating the Keypair language_code: The language to use, valid values are: ‘en’, ‘zh-hans’, ‘zh-hant’, ‘fr’, ‘it’, ‘ja’, ‘ko’, ‘es’. Defaults to MnemonicLanguageCode.ENGLISH

Returns

Keypair

decrypt_message(encrypted_message_with_nonce: bytes, sender_public_key: bytes) bytes[source]

Decrypts message from a specified sender

Parameters

encrypted_message_with_nonce: message to be decrypted sender_public_key: sender’s public key

Returns

Decrypted message

encrypt_message(message: bytes | str, recipient_public_key: bytes, nonce: bytes = b'\x02\xcf\xcf\x93\x91\x87 \xf3\xfe\xc6z?c\xf5\xfd1\x03\x9d\xca\x8c\'^z"') bytes[source]

Encrypts message with for specified recipient

Parameters

message: message to be encrypted, bytes or string recipient_public_key: recipient’s public key nonce: the nonce to use in the encryption

Returns

Encrypted message

export_to_encrypted_json(passphrase: str, name: str | None = None) dict[source]

Export Keypair to PolkadotJS format encrypted JSON file

Parameters

passphrase: Used to encrypt the keypair name: Display name of Keypair used

Returns

dict

classmethod generate_mnemonic(words: int = 12, language_code: str = 'en') str[source]

Generates a new seed phrase with given amount of words (default 12)

Parameters

words: The amount of words to generate, valid values are 12, 15, 18, 21 and 24 language_code: The language to use, valid values are: ‘en’, ‘zh-hans’, ‘zh-hant’, ‘fr’, ‘it’, ‘ja’, ‘ko’, ‘es’. Defaults to MnemonicLanguageCode.ENGLISH

Returns

str: Seed phrase

sign(data: ScaleBytes | bytes | str) bytes[source]

Creates a signature for given data

Parameters

data: data to sign in Scalebytes, bytes or hex string format

Returns

signature in bytes

classmethod validate_mnemonic(mnemonic: str, language_code: str = 'en') bool[source]

Verify if specified mnemonic is valid

Parameters

mnemonic: Seed phrase language_code: The language to use, valid values are: ‘en’, ‘zh-hans’, ‘zh-hant’, ‘fr’, ‘it’, ‘ja’, ‘ko’, ‘es’. Defaults to MnemonicLanguageCode.ENGLISH

Returns

bool

verify(data: ScaleBytes | bytes | str, signature: bytes | str) bool[source]

Verifies data with specified signature

Parameters

data: data to be verified in Scalebytes, bytes or hex string format signature: signature in bytes or hex string format

Returns

True if data is signed with this Keypair, otherwise False

class sdk_interface.keypair.KeypairType[source]

Bases: object

Type of cryptography, used in Keypair instance to encrypt and sign data

  • ED25519 = 0

  • SR25519 = 1

  • ECDSA = 2

ECDSA = 2
ED25519 = 0
SR25519 = 1
class sdk_interface.keypair.MnemonicLanguageCode[source]

Bases: object

Available language codes to generate mnemonics

  • ENGLISH = ‘en’

  • CHINESE_SIMPLIFIED = ‘zh-hans’

  • CHINESE_TRADITIONAL = ‘zh-hant’

  • FRENCH = ‘fr’

  • ITALIAN = ‘it’

  • JAPANESE = ‘ja’

  • KOREAN = ‘ko’

  • SPANISH = ‘es’

CHINESE_SIMPLIFIED = 'zh-hans'
CHINESE_TRADITIONAL = 'zh-hant'
ENGLISH = 'en'
FRENCH = 'fr'
ITALIAN = 'it'
JAPANESE = 'ja'
KOREAN = 'ko'
SPANISH = 'es'

sdk_interface.storage module

class sdk_interface.storage.StorageKey(pallet: str, storage_function: str, params: list, data: bytes, value_scale_type: str, metadata: GenericMetadataVersioned, runtime_config: RuntimeConfigurationObject)[source]

Bases: object

A StorageKey instance is a representation of a single state entry.

Substrate uses a simple key-value data store implemented as a database-backed, modified Merkle tree. All of Substrate’s higher-level storage abstractions are built on top of this simple key-value store.

convert_storage_parameter(scale_type: str, value: Any)[source]
classmethod create_from_data(data: bytes, runtime_config: RuntimeConfigurationObject, metadata: GenericMetadataVersioned, value_scale_type: str | None = None, pallet: str | None = None, storage_function: str | None = None) StorageKey[source]

Create a StorageKey instance providing raw storage key bytes

Parameters

data: bytes representation of the storage key runtime_config: RuntimeConfigurationObject metadata: GenericMetadataVersioned value_scale_type: type string of to decode result data pallet: name of pallet storage_function: name of storage function

Returns

StorageKey

classmethod create_from_storage_function(pallet: str, storage_function: str, params: list, runtime_config: RuntimeConfigurationObject, metadata: GenericMetadataVersioned) StorageKey[source]

Create a StorageKey instance providing storage function details

Parameters

pallet: name of pallet storage_function: name of storage function params: Optional list of parameters in case of a Mapped storage function runtime_config: RuntimeConfigurationObject metadata: GenericMetadataVersioned

Returns

StorageKey

decode_scale_value(data: ScaleBytes | None = None) ScaleType[source]

Parameters

data

Returns

generate() bytes[source]

Generate a storage key for current specified pallet/function/params

Returns

bytes

to_hex() str[source]

Returns a Hex-string representation of current StorageKey data

Returns

str

Hex string

Module contents

class sdk_interface.ContractCode(code_hash: bytes | None = None, metadata: ContractMetadata | None = None, wasm_bytes: bytes | None = None, substrate: SubstrateInterface | None = None)[source]

Bases: object

classmethod create_from_code_hash(code_hash: bytes, metadata_file: str, substrate: SubstrateInterface) ContractCode[source]

Create a ContractCode providing an existing contract code hash and a path to the metadata JSON file

Parameters

code_hash metadata_file substrate

Returns

ContractCode

classmethod create_from_contract_files(wasm_file: str, metadata_file: str, substrate: SubstrateInterface) ContractCode[source]

Create a ContractCode providing paths for the WASM binary file and metadata JSON file generated by the ink! project

Parameters

wasm_file metadata_file substrate

Returns

ContractCode

deploy(keypair: Keypair, constructor: str, args: dict | None = None, value: int = 0, gas_limit: dict | None = None, deployment_salt: str | None = None, upload_code: bool = False, storage_deposit_limit: int | None = None) ContractInstance[source]

Deploys a new instance of the contract after it has been uploaded on-chain, with provided constructor and constructor arguments

Parameters

keypair constructor: name of the constructor to use, provided in the metadata args: arguments for the constructor value: Value sent to created contract address gas_limit: Gas limit as WeightV2 type. Will default to {‘ref_time’: 25990000000, ‘proof_size’: 11990383647911208550}. deployment_salt: optional string or hex-string that acts as a salt for this deployment upload_code: When True the WASM blob itself will be uploaded with the deploy, False if the WASM is already present on-chain storage_deposit_limit: The maximum amount of balance that can be charged to pay for the storage consumed.

Returns

ContractInstance

upload_wasm(keypair: Keypair, storage_deposit_limit: int | None = None) ExtrinsicReceipt[source]

Created and submits an “Contracts.upload_code” extrinsic containing the WASM binary

Parameters

keypair: Keypair used to sign the extrinsic storage_deposit_limit:T he maximum amount of balance that can be charged to pay for the storage consumed

Returns

ExtrinsicReceipt

class sdk_interface.ContractEvent(*args, contract_metadata: ContractMetadata | None = None, **kwargs)[source]

Bases: ScaleType

process()[source]

Implementation of the decoding process

Returns

process_encode(value)[source]

Implementation of the encoding process

Parameters

value

Returns

ScaleBytes

class sdk_interface.ContractExecutionReceipt(*args, **kwargs)[source]

Bases: ExtrinsicReceipt

property contract_events
classmethod create_from_extrinsic_receipt(receipt: ExtrinsicReceipt, contract_metadata: ContractMetadata, contract_address: str | None = None) ContractExecutionReceipt[source]

Promotes a ExtrinsicReceipt object to a ContractExecutionReceipt. It uses the provided ContractMetadata to decode “ContractExecution” events

Parameters

receipt contract_metadata

Returns

ContractExecutionReceipt

process_events()[source]
class sdk_interface.ContractInstance(contract_address: str, metadata: ContractMetadata | None = None, substrate: SubstrateInterface | None = None)[source]

Bases: object

classmethod create_from_address(contract_address: str, metadata_file: str, substrate: SubstrateInterface | None = None) ContractInstance[source]

Create a ContractInstance object that already exists on-chain providing a SS58-address and the path to the metadata JSON of that contract

Parameters

contract_address: SS58-address of contract metadata_file: path to metadata JSON generated for contract substrate

Returns

ContractInstance

exec(keypair: Keypair, method: str, args: dict | None = None, value: int = 0, gas_limit: dict | None = None, storage_deposit_limit: int | None = None, wait_for_inclusion: bool = True, wait_for_finalization: bool = False) ContractExecutionReceipt[source]

Executes provided message by creating and submitting an extrinsic. To get a gas prediction or perform a ‘dry-run’ of executing this message, see ContractInstance.read.

Parameters

keypair method: name of message to execute args: arguments of message in {‘name’: value} format value: value to send when executing the message gas_limit: dict repesentation of WeightV2 type. When omited the gas limit will be calculated with a read() storage_deposit_limit: The maximum amount of balance that can be charged to pay for the storage consumed wait_for_inclusion: wait until extrinsic is included in a block (only works for websocket connections) wait_for_finalization: wait until extrinsic is finalized (only works for websocket connections)

Returns

ContractExecutionReceipt

init()[source]
read(keypair: Keypair, method: str, args: dict | None = None, value: int = 0, gas_limit: int | None = None, block_hash: str | None = None) GenericContractExecResult[source]

Used to execute non-mutable messages to for example read data from the contract using getters. Can also be used to predict gas limits and ‘dry-run’ the execution when a mutable message is used. This method does not submit an extrinsic.

Parameters

keypair method: name of message to execute args: arguments of message in {‘name’: value} format value: value to send when executing the message gas_limit: dict repesentation of WeightV2 type block_hash: hash of the block to execute the message on

Returns

GenericContractExecResult

class sdk_interface.ContractMetadata(metadata_dict: dict, substrate: SubstrateInterface)[source]

Bases: object

classmethod create_from_file(metadata_file: str, substrate: SubstrateInterface) ContractMetadata[source]

Create a new ContractMetadata object using the provided metadata_file, usually generated by the command “cargo +nightly contract generate-metadata” in an ink! project

Parameters

metadata_file substrate

Returns

ContractMetadata

generate_constructor_data(name, args: dict | None = None) ScaleBytes[source]

Compose the data field used in the “Contracts.instantiate” call, finding the selectors and encoded the args of given constructor

Parameters

name args

Returns

ScaleBytes

generate_message_data(name, args: dict | None = None) ScaleBytes[source]

Compose the data field used in the “Contracts.call” call, finding the selector and encoded the args of provided message name

Parameters

name: name of message in contract args: arguments required by message, in format: {‘name’: value}

Returns

ScaleBytes

get_event_data(event_id: int) dict[source]

Looks up the event data for given 0-based event_id

Parameters

event_id

Returns

get_event_id_by_topic(topic: str) int | None[source]
get_return_type_string_for_message(name) str[source]
get_type_string_for_metadata_type(type_id: int) str[source]

Adds a type included in the metadata (represented by an index in the type list) to the type registry and produces a type string that can be used in the scope of the RuntimeConfigurationObject.

Parameters

type_id 1-based index of type locating in the metadata types dict

Returns

str

class sdk_interface.Extension[source]

Bases: object

Base class of all extensions

close()[source]

Cleanup process of the extension. This function is being called by the ExtensionRegistry.

Returns

debug_message(message: str)[source]

Submits a debug message in the logger

Parameters

message: str

Returns

init(substrate: SubstrateInterface)[source]

Initialization process of the extension. This function is being called by the ExtensionRegistry.

Parameters

substrate: SubstrateInterface

Returns

class sdk_interface.ExtensionInterface(substrate)[source]

Bases: object

Keeps tracks of active extensions and which calls can be made

call(name: str, *args, **kwargs)[source]

Tries to call extension function with name and provided args and kwargs

Will raise a ExtensionCallNotFound when no method is found in current extensions

Parameters

name args kwargs

Returns

get_extension_callable(name: str) Callable[source]
register(extension: Extension)[source]

Register an extension instance to the registry and calls initialization

Parameters

extension: Extension

Returns

unregister_all()[source]

Unregister all extensions and free used resources and connections

Returns

class sdk_interface.ExtrinsicReceipt(substrate: SubstrateInterface, extrinsic_hash: str | None = None, block_hash: str | None = None, block_number: int | None = None, extrinsic_idx: int | None = None, finalized=None)[source]

Bases: object

Object containing information of submitted extrinsic. Block hash where extrinsic is included is required

when retrieving triggered events or determine if extrinsic was succesfull

classmethod create_from_extrinsic_identifier(substrate: SubstrateInterface, extrinsic_identifier: str) ExtrinsicReceipt[source]

Create an ExtrinsicReceipt with on-chain identifier for this extrinsic in format “[block_number]-[extrinsic_idx]” e.g. 134324-2

Parameters

substrate: SubstrateInterface extrinsic_identifier: str

Returns

ExtrinsicReceipt

property error_message: dict | None

Returns the error message if the extrinsic failed in format e.g.:

{‘type’: ‘System’, ‘name’: ‘BadOrigin’, ‘docs’: ‘Bad origin’}

Returns

dict

property extrinsic: GenericExtrinsic

Retrieves the Extrinsic subject of this receipt

Returns

Extrinsic

property extrinsic_idx: int

Retrieves the index of this extrinsic in containing block

Returns

int

get(name)[source]
get_extrinsic_identifier() str[source]

Returns the on-chain identifier for this extrinsic in format “[block_number]-[extrinsic_idx]” e.g. 134324-2 Returns ——- str

property is_success: bool

Returns True if ExtrinsicSuccess event is triggered, False in case of ExtrinsicFailed In case of False error_message will contain more details about the error

Returns

bool

process_events()[source]
retrieve_extrinsic()[source]
property total_fee_amount: int

Contains the total fee costs deducted when executing this extrinsic. This includes fee for the validator ( (Balances.Deposit event) and the fee deposited for the treasury (Treasury.Deposit event)

Returns

int

property triggered_events: list

Gets triggered events for submitted extrinsic. block_hash where extrinsic is included is required, manually set block_hash or use wait_for_inclusion when submitting extrinsic

Returns

list

property weight: int | dict

Contains the actual weight when executing this extrinsic

Returns

int (WeightV1) or dict (WeightV2)

class sdk_interface.Keypair(ss58_address: str | None = None, public_key: bytes | str | None = None, private_key: bytes | str | None = None, ss58_format: int | None = None, seed_hex: bytes | str | None = None, crypto_type: int = 1)[source]

Bases: object

classmethod create_from_encrypted_json(json_data: str | dict, passphrase: str, ss58_format: int | None = None) Keypair[source]

Create a Keypair from a PolkadotJS format encrypted JSON file

Parameters

json_data: Dict or JSON string containing PolkadotJS export format passphrase: Used to encrypt the keypair ss58_format: Which network ID to use to format the SS58 address (42 for testnet)

Returns

Keypair

classmethod create_from_mnemonic(mnemonic: str, ss58_format=42, crypto_type=1, language_code: str = 'en') Keypair[source]

Create a Keypair for given memonic

Parameters

mnemonic: Seed phrase ss58_format: Substrate address format crypto_type: Use KeypairType.SR25519 or KeypairType.ED25519 cryptography for generating the Keypair language_code: The language to use, valid values are: ‘en’, ‘zh-hans’, ‘zh-hant’, ‘fr’, ‘it’, ‘ja’, ‘ko’, ‘es’. Defaults to MnemonicLanguageCode.ENGLISH

Returns

Keypair

classmethod create_from_private_key(private_key: bytes | str, public_key: bytes | str | None = None, ss58_address: str | None = None, ss58_format: int | None = None, crypto_type: int = 1) Keypair[source]

Creates Keypair for specified public/private keys Parameters ———- private_key: hex string or bytes of private key public_key: hex string or bytes of public key ss58_address: Substrate address ss58_format: Substrate address format, default = 42 crypto_type: Use KeypairType.[SR25519|ED25519|ECDSA] cryptography for generating the Keypair

Returns

Keypair

classmethod create_from_seed(seed_hex: bytes | str, ss58_format: int | None = 42, crypto_type=1) Keypair[source]

Create a Keypair for given seed

Parameters

seed_hex: hex string of seed ss58_format: Substrate address format crypto_type: Use KeypairType.SR25519 or KeypairType.ED25519 cryptography for generating the Keypair

Returns

Keypair

classmethod create_from_uri(suri: str, ss58_format: int | None = 42, crypto_type=1, language_code: str = 'en') Keypair[source]

Creates Keypair for specified suri in following format: [mnemonic]/[soft-path]//[hard-path]

Parameters

suri: ss58_format: Substrate address format crypto_type: Use KeypairType.SR25519 or KeypairType.ED25519 cryptography for generating the Keypair language_code: The language to use, valid values are: ‘en’, ‘zh-hans’, ‘zh-hant’, ‘fr’, ‘it’, ‘ja’, ‘ko’, ‘es’. Defaults to MnemonicLanguageCode.ENGLISH

Returns

Keypair

decrypt_message(encrypted_message_with_nonce: bytes, sender_public_key: bytes) bytes[source]

Decrypts message from a specified sender

Parameters

encrypted_message_with_nonce: message to be decrypted sender_public_key: sender’s public key

Returns

Decrypted message

encrypt_message(message: bytes | str, recipient_public_key: bytes, nonce: bytes = b'\x02\xcf\xcf\x93\x91\x87 \xf3\xfe\xc6z?c\xf5\xfd1\x03\x9d\xca\x8c\'^z"') bytes[source]

Encrypts message with for specified recipient

Parameters

message: message to be encrypted, bytes or string recipient_public_key: recipient’s public key nonce: the nonce to use in the encryption

Returns

Encrypted message

export_to_encrypted_json(passphrase: str, name: str | None = None) dict[source]

Export Keypair to PolkadotJS format encrypted JSON file

Parameters

passphrase: Used to encrypt the keypair name: Display name of Keypair used

Returns

dict

classmethod generate_mnemonic(words: int = 12, language_code: str = 'en') str[source]

Generates a new seed phrase with given amount of words (default 12)

Parameters

words: The amount of words to generate, valid values are 12, 15, 18, 21 and 24 language_code: The language to use, valid values are: ‘en’, ‘zh-hans’, ‘zh-hant’, ‘fr’, ‘it’, ‘ja’, ‘ko’, ‘es’. Defaults to MnemonicLanguageCode.ENGLISH

Returns

str: Seed phrase

sign(data: ScaleBytes | bytes | str) bytes[source]

Creates a signature for given data

Parameters

data: data to sign in Scalebytes, bytes or hex string format

Returns

signature in bytes

classmethod validate_mnemonic(mnemonic: str, language_code: str = 'en') bool[source]

Verify if specified mnemonic is valid

Parameters

mnemonic: Seed phrase language_code: The language to use, valid values are: ‘en’, ‘zh-hans’, ‘zh-hant’, ‘fr’, ‘it’, ‘ja’, ‘ko’, ‘es’. Defaults to MnemonicLanguageCode.ENGLISH

Returns

bool

verify(data: ScaleBytes | bytes | str, signature: bytes | str) bool[source]

Verifies data with specified signature

Parameters

data: data to be verified in Scalebytes, bytes or hex string format signature: signature in bytes or hex string format

Returns

True if data is signed with this Keypair, otherwise False

class sdk_interface.KeypairType[source]

Bases: object

Type of cryptography, used in Keypair instance to encrypt and sign data

  • ED25519 = 0

  • SR25519 = 1

  • ECDSA = 2

ECDSA = 2
ED25519 = 0
SR25519 = 1
class sdk_interface.MnemonicLanguageCode[source]

Bases: object

Available language codes to generate mnemonics

  • ENGLISH = ‘en’

  • CHINESE_SIMPLIFIED = ‘zh-hans’

  • CHINESE_TRADITIONAL = ‘zh-hant’

  • FRENCH = ‘fr’

  • ITALIAN = ‘it’

  • JAPANESE = ‘ja’

  • KOREAN = ‘ko’

  • SPANISH = ‘es’

CHINESE_SIMPLIFIED = 'zh-hans'
CHINESE_TRADITIONAL = 'zh-hant'
ENGLISH = 'en'
FRENCH = 'fr'
ITALIAN = 'it'
JAPANESE = 'ja'
KOREAN = 'ko'
SPANISH = 'es'
class sdk_interface.SearchExtension[source]

Bases: Extension

Type of Extension that implements functionality to improve and enhance search capability

filter_events(**kwargs) list[source]

Filters events to match provided search criteria e.g. block range, pallet name, accountID in attributes

Parameters

kwargs

Returns

list

filter_extrinsics(**kwargs) list[source]

Filters extrinsics to match provided search criteria e.g. block range, pallet name, signed by accountID

Parameters

kwargs

Returns

get_block_timestamp(block_number: int) int[source]

Return a UNIX timestamp for given block_number.

Parameters

block_number: int The block_number to retrieve the timestamp for

Returns

int

search_block_number(block_datetime: datetime, block_time: int = 6, **kwargs) int[source]

Search corresponding block number for provided block_datetime. the prediction tolerance is provided with block_time

Parameters

block_datetime: datetime block_time: int kwargs

Returns

int

class sdk_interface.SubstrateInterface(url=None, websocket=None, ss58_format=None, type_registry=None, type_registry_preset=None, cache_region=None, runtime_config=None, use_remote_preset=False, ws_options=None, auto_discover=True, auto_reconnect=True, config=None)[source]

Bases: object

apply_type_registry_presets(use_remote_preset: bool = True, auto_discover: bool = True)[source]
property chain
close()[source]

Cleans up resources for this instance like active websocket connection and active extensions

Returns

compose_call(call_module: str, call_function: str, call_params: dict | None = None, block_hash: str | None = None) GenericCall[source]

Composes a call payload which can be used in an extrinsic.

Parameters

call_module: Name of the runtime module e.g. Balances call_function: Name of the call function e.g. transfer call_params: This is a dict containing the params of the call. e.g. {‘dest’: ‘EaG2CRhJWPb7qmdcJvy3LiWdh26Jreu9Dx6R1rXxPmYXoDk’, ‘value’: 1000000000000} block_hash: Use metadata at given block_hash to compose call

Returns

GenericCall

connect_websocket()[source]

(Re)creates the websocket connection, if the URL contains a ‘ws’ or ‘wss’ scheme

Returns

convert_storage_parameter(scale_type, value)[source]
create_multisig_extrinsic(call: GenericCall, keypair: Keypair, multisig_account: MultiAccountId, max_weight: dict | int | None = None, era: dict | None = None, nonce: int | None = None, tip: int = 0, tip_asset_id: int | None = None, signature: bytes | str | None = None) GenericExtrinsic[source]

Create a Multisig extrinsic that will be signed by one of the signatories. Checks on-chain if the threshold of the multisig account is reached and try to execute the call accordingly.

Parameters

call: GenericCall to create extrinsic for keypair: Keypair of the signatory to approve given call multisig_account: MultiAccountId to use of origin of the extrinsic (see generate_multisig_account()) max_weight: Maximum allowed weight to execute the call ( Uses get_payment_info() by default) era: Specify mortality in blocks in follow format: {‘period’: [amount_blocks]} If omitted the extrinsic is immortal nonce: nonce to include in extrinsics, if omitted the current nonce is retrieved on-chain tip: The tip for the block author to gain priority during network congestion tip_asset_id: Optional asset ID with which to pay the tip signature: Optionally provide signature if externally signed

Returns

GenericExtrinsic

create_scale_object(type_string: str, data: ScaleBytes | None = None, block_hash: str | None = None, **kwargs) ScaleType[source]

Convenience method to create a SCALE object of type type_string, this will initialize the runtime automatically at moment of block_hash, or chain tip if omitted.

Parameters

type_string: str Name of SCALE type to create data: ScaleBytes Optional ScaleBytes to decode block_hash: Optional block hash for moment of decoding, when omitted the chain tip will be used kwargs

Returns

ScaleType

create_signed_extrinsic(call: GenericCall, keypair: Keypair, era: dict | None = None, nonce: int | None = None, tip: int = 0, tip_asset_id: int | None = None, signature: bytes | str | None = None) GenericExtrinsic[source]

Creates an extrinsic signed by given account details

Parameters

call: GenericCall to create extrinsic for keypair: Keypair used to sign the extrinsic era: Specify mortality in blocks in follow format: {‘period’: [amount_blocks]} If omitted the extrinsic is immortal nonce: nonce to include in extrinsics, if omitted the current nonce is retrieved on-chain tip: The tip for the block author to gain priority during network congestion tip_asset_id: Optional asset ID with which to pay the tip signature: Optionally provide signature if externally signed

Returns

GenericExtrinsic The signed Extrinsic

create_storage_key(pallet: str, storage_function: str, params: list | None = None) StorageKey[source]

Create a StorageKey instance providing storage function details. See subscribe_storage().

Parameters

pallet: name of pallet storage_function: name of storage function params: Optional list of parameters in case of a Mapped storage function

Returns

StorageKey

create_unsigned_extrinsic(call: GenericCall) GenericExtrinsic[source]

Create unsigned extrinsic for given Call Parameters ———- call: GenericCall the call the extrinsic should contain

Returns

GenericExtrinsic

static debug_message(message: str)[source]

Submits a message to the debug logger

Parameters

message: str Debug message

Returns

decode_scale(type_string, scale_bytes, block_hash=None, return_scale_obj=False)[source]

Helper function to decode arbitrary SCALE-bytes (e.g. 0x02000000) according to given RUST type_string (e.g. BlockNumber). The relevant versioning information of the type (if defined) will be applied if block_hash is set

Parameters

type_string scale_bytes block_hash return_scale_obj: if True the SCALE object itself is returned, otherwise the serialized dict value of the object

Returns

encode_scale(type_string, value, block_hash=None) ScaleBytes[source]

Helper function to encode arbitrary data into SCALE-bytes for given RUST type_string

Parameters

type_string value block_hash

Returns

ScaleBytes

extension_call(name, **kwargs)[source]
filter_events(**kwargs) list[source]
filter_extrinsics(**kwargs) list[source]
generate_multisig_account(signatories: list, threshold: int) MultiAccountId[source]

Generate deterministic Multisig account with supplied signatories and threshold Parameters ———- signatories: List of signatories threshold: Amount of approvals needed to execute

Returns

MultiAccountId

generate_signature_payload(call: GenericCall, era=None, nonce: int = 0, tip: int = 0, tip_asset_id: int | None = None, include_call_length: bool = False) ScaleBytes[source]
generate_storage_hash(storage_module: str, storage_function: str, params: list | None = None, hashers: list | None = None) str[source]

Generate a storage key for given module/function

Parameters

storage_module storage_function params: Parameters of the storage function, provided in scale encoded hex-bytes or ScaleBytes instances hashers: Hashing methods used to determine storage key, defaults to ‘Twox64Concat’ if not provided

Returns

str Hexstring respresentation of the storage key

get_account_nonce(account_address) int[source]

Returns current nonce for given account address

Parameters

account_address: SS58 formatted address

Returns

int

get_block(block_hash: str | None = None, block_number: int | None = None, ignore_decoding_errors: bool = False, include_author: bool = False, finalized_only: bool = False) dict | None[source]

Retrieves a block and decodes its containing extrinsics and log digest items. If block_hash and block_number is omited the chain tip will be retrieve, or the finalized head if finalized_only is set to true.

Either block_hash or block_number should be set, or both omitted.

Parameters

block_hash: the hash of the block to be retrieved block_number: the block number to retrieved ignore_decoding_errors: When set this will catch all decoding errors, set the item to None and continue decoding include_author: This will retrieve the block author from the validator set and add to the result finalized_only: when no block_hash or block_number is set, this will retrieve the finalized head

Returns

A dict containing the extrinsic and digest logs data

get_block_hash(block_id: int | None = None) str[source]

A pass-though to existing JSONRPC method chain_getBlockHash

Parameters

block_id

Returns

get_block_header(block_hash: str | None = None, block_number: int | None = None, ignore_decoding_errors: bool = False, include_author: bool = False, finalized_only: bool = False)[source]

Retrieves a block header and decodes its containing log digest items. If block_hash and block_number is omited the chain tip will be retrieve, or the finalized head if finalized_only is set to true.

Either block_hash or block_number should be set, or both omitted.

See get_block() to also include the extrinsics in the result

Parameters

block_hash: the hash of the block to be retrieved block_number: the block number to retrieved ignore_decoding_errors: When set this will catch all decoding errors, set the item to None and continue decoding include_author: This will retrieve the block author from the validator set and add to the result finalized_only: when no block_hash or block_number is set, this will retrieve the finalized head

Returns

A dict containing the header and digest logs data

get_block_metadata(block_hash=None, decode=True)[source]

A pass-though to existing JSONRPC method state_getMetadata.

Parameters

block_hash decode: True for decoded version

Returns

get_block_number(block_hash: str) int[source]

A convenience method to get the block number for given block_hash

Parameters

block_hash

Returns

get_block_runtime_version(block_hash)[source]

Retrieve the runtime version id of given block_hash Parameters ———- block_hash

Returns

get_block_timestamp(block_number: int) int[source]
get_chain_finalised_head()[source]

A pass-though to existing JSONRPC method chain_getFinalizedHead

Returns

get_chain_head()[source]

A pass-though to existing JSONRPC method chain_getHead

Returns

get_constant(module_name, constant_name, block_hash=None) ScaleType | None[source]

Returns the decoded ScaleType object of the constant for given module name, call function name and block_hash (or chaintip if block_hash is omitted)

Parameters

module_name constant_name block_hash

Returns

ScaleType

get_events(block_hash: str | None = None) list[source]

Convenience method to get events for a certain block (storage call for module ‘System’ and function ‘Events’)

Parameters

block_hash

Returns

list

get_extrinsics(block_hash: str | None = None, block_number: int | None = None) list[source]

Return extrinsics for given block_hash or block_number

Parameters

block_hash block_number

Returns

get_metadata(block_hash=None)[source]

Returns MetadataVersioned object for given block_hash or chaintip if block_hash is omitted

Parameters

block_hash

Returns

MetadataVersioned

get_metadata_call_function(module_name: str, call_function_name: str, block_hash: str | None = None)[source]

Retrieves the details of a call function given module name, call function name and block_hash (or chaintip if block_hash is omitted)

Parameters

module_name call_function_name block_hash

Returns

get_metadata_call_functions(block_hash=None) list[source]

Retrieves a list of all call functions in metadata active for given block_hash (or chaintip if block_hash is omitted)

Parameters

block_hash

Returns

list

get_metadata_constant(module_name, constant_name, block_hash=None)[source]

Retrieves the details of a constant for given module name, call function name and block_hash (or chaintip if block_hash is omitted)

Parameters

module_name constant_name block_hash

Returns

MetadataModuleConstants

get_metadata_constants(block_hash=None) list[source]

Retrieves a list of all constants in metadata active at given block_hash (or chaintip if block_hash is omitted)

Parameters

block_hash

Returns

list

get_metadata_error(module_name, error_name, block_hash=None)[source]

Retrieves the details of an error for given module name, call function name and block_hash

Parameters

module_name error_name block_hash

Returns

get_metadata_errors(block_hash=None) list[source]

Retrieves a list of all errors in metadata active at given block_hash (or chaintip if block_hash is omitted)

Parameters

block_hash

Returns

list

get_metadata_event(module_name, event_name, block_hash=None)[source]

Retrieves the details of an event for given module name, call function name and block_hash (or chaintip if block_hash is omitted)

Parameters

module_name event_name block_hash

Returns

get_metadata_events(block_hash=None) list[source]

Retrieves a list of all events in metadata active for given block_hash (or chaintip if block_hash is omitted)

Parameters

block_hash

Returns

list

get_metadata_module(name, block_hash=None)[source]

Retrieves modules in metadata by name for given block_hash (or chaintip if block_hash is omitted)

Parameters

name block_hash

Returns

MetadataModule

get_metadata_modules(block_hash=None)[source]

Retrieves a list of modules in metadata for given block_hash (or chaintip if block_hash is omitted)

Parameters

block_hash

Returns

get_metadata_runtime_call_function(api: str, method: str) GenericRuntimeCallDefinition[source]

Get details of a runtime API call

Parameters

api: Name of the runtime API e.g. ‘TransactionPaymentApi’ method: Name of the method e.g. ‘query_fee_details’

Returns

GenericRuntimeCallDefinition

get_metadata_runtime_call_functions() list[source]

Get a list of available runtime API calls

Returns

list

get_metadata_storage_function(module_name, storage_name, block_hash=None)[source]

Retrieves the details of a storage function for given module name, call function name and block_hash

Parameters

module_name storage_name block_hash

Returns

get_metadata_storage_functions(block_hash=None) list[source]

Retrieves a list of all storage functions in metadata active at given block_hash (or chaintip if block_hash is omitted)

Parameters

block_hash

Returns

list

get_payment_info(call: GenericCall, keypair: Keypair)[source]

Retrieves fee estimation via RPC for given extrinsic

Parameters

call: Call object to estimate fees for keypair: Keypair of the sender, does not have to include private key because no valid signature is required

Returns

Dict with payment info

E.g. {‘class’: ‘normal’, ‘partialFee’: 151000000, ‘weight’: {‘ref_time’: 143322000}}

get_runtime_metadata(block_hash=None)[source]

Retrieves and decodes the metadata for given block or chaintip if block_hash is omitted.

Parameters

block_hash

Returns

get_storage_by_key(block_hash: str, storage_key: str)[source]

A pass-though to existing JSONRPC method state_getStorage

Parameters

block_hash storage_key

Returns

get_type_definition(type_string: str, block_hash: str | None = None)[source]

Retrieves SCALE encoding specifications of given type_string

Parameters

type_string: RUST variable type, e.g. Vec<Address> or scale_info::0 block_hash

Returns

get_type_registry(block_hash: str | None = None, max_recursion: int = 4) dict[source]

Generates an exhaustive list of which RUST types exist in the runtime specified at given block_hash (or chaintip if block_hash is omitted)

MetadataV14 or higher is required.

Parameters

block_hash: Chaintip will be used if block_hash is omitted max_recursion: Increasing recursion will provide more detail but also has impact on performance

Returns

dict

implements_scaleinfo() bool | None[source]

Returns True if current runtime implementation a PortableRegistry (MetadataV14 and higher)

Returns

bool

init_runtime(block_hash=None, block_id=None)[source]

This method is used by all other methods that deals with metadata and types defined in the type registry. It optionally retrieves the block_hash when block_id is given and sets the applicable metadata for that block_hash. Also it applies all the versioned types at the time of the block_hash.

Because parsing of metadata and type registry is quite heavy, the result will be cached per runtime id. In the future there could be support for caching backends like Redis to make this cache more persistent.

Parameters

block_hash block_id

Returns

is_valid_ss58_address(value: str) bool[source]

Helper function to validate given value as ss58_address for current network/ss58_format

Parameters

value

Returns

bool

property name
property properties
query(module: str, storage_function: str, params: list | None = None, block_hash: str | None = None, subscription_handler: callable | None = None, raw_storage_key: bytes | None = None) ScaleType[source]

Retrieves the storage entry for given module, function and optional parameters at given block hash.

When a subscription_handler callback function is passed, a subscription will be maintained as long as this handler doesn’t return a value.

Example of subscription handler: ``` def subscription_handler(obj, update_nr, subscription_id):

if update_nr == 0:

print(‘Initial data:’, obj.value)

if update_nr > 0:

# Do something with the update print(‘data changed:’, obj.value)

# The execution will block until an arbitrary value is returned, which will be the result of the query if update_nr > 1:

return obj

```

Parameters

module: The module name in the metadata, e.g. Balances or Account storage_function: The storage function name, e.g. FreeBalance or AccountNonce params: list of params, in the decoded format of the applicable ScaleTypes block_hash: Optional block hash, when omitted the chain tip will be used subscription_handler: Callback function that processes the updates of the storage query subscription raw_storage_key: Optional raw storage key to query decode instead of generating one

Returns

ScaleType

query_map(module: str, storage_function: str, params: list | None = None, block_hash: str | None = None, max_results: int | None = None, start_key: str | None = None, page_size: int = 100, ignore_decoding_errors: bool = True) QueryMapResult[source]

Iterates over all key-pairs located at the given module and storage_function. The storage item must be a map.

Example:

``` result = substrate.query_map(‘System’, ‘Account’, max_results=100)

for account, account_info in result:

print(f”Free balance of account ‘{account.value}’: {account_info.value[‘data’][‘free’]}”)

```

Parameters

module: The module name in the metadata, e.g. System or Balances. storage_function: The storage function name, e.g. Account or Locks. params: The input parameters in case of for example a DoubleMap storage function block_hash: Optional block hash for result at given block, when left to None the chain tip will be used. max_results: the maximum of results required, if set the query will stop fetching results when number is reached start_key: The storage key used as offset for the results, for pagination purposes page_size: The results are fetched from the node RPC in chunks of this size ignore_decoding_errors: When set this will catch all decoding errors, set the item to None and continue decoding

Returns

QueryMapResult

query_multi(storage_keys: List[StorageKey], block_hash: str | None = None) list[source]

Query multiple storage keys in one request.

Example:

``` storage_keys = [

substrate.create_storage_key(

“System”, “Account”, [“F4xQKRUagnSGjFqafyhajLs94e7Vvzvr8ebwYJceKpr8R7T”]

), substrate.create_storage_key(

“System”, “Account”, [“GSEX8kR4Kz5UZGhvRUCJG93D5hhTAoVZ5tAe6Zne7V42DSi”]

)

]

result = substrate.query_multi(storage_keys) ```

Parameters

storage_keys: list of StorageKey objects block_hash: Optional block_hash of state snapshot

Returns

list of (storage_key, scale_obj) tuples

register_extension(extension: Extension)[source]

Register an Extension and adds its functionality to the ExtensionRegistry

Parameters

extension: Extension

Returns

reload_type_registry(use_remote_preset: bool = True, auto_discover: bool = True)[source]

Reload type registry and preset used to instantiate the SubtrateInterface object. Useful to periodically apply changes in type definitions when a runtime upgrade occurred

Parameters

use_remote_preset: When True preset is downloaded from Github master, otherwise use files from local installed scalecodec package auto_discover

Returns

retrieve_extrinsic_by_hash(block_hash: str, extrinsic_hash: str) ExtrinsicReceipt[source]

Retrieve an extrinsic by providing the block_hash and the extrinsic hash

Parameters

block_hash extrinsic_hash

Returns

ExtrinsicReceipt

retrieve_extrinsic_by_identifier(extrinsic_identifier: str) ExtrinsicReceipt[source]

Retrieve an extrinsic by its identifier in format “[block_number]-[extrinsic_index]” e.g. 333456-4

Parameters

extrinsic_identifier

Returns

ExtrinsicReceipt

retrieve_pending_extrinsics() list[source]

Retrieves and decodes pending extrinsics from the node’s transaction pool

Returns

list of extrinsics

rpc_request(method, params, result_handler=None)[source]

Method that handles the actual RPC request to the Substrate node. The other implemented functions eventually use this method to perform the request.

Parameters

result_handler: Callback function that processes the result received from the node method: method of the JSONRPC request params: a list containing the parameters of the JSONRPC request

Returns

a dict with the parsed result of the request.

runtime_call(api: str, method: str, params: list | dict | None = None, block_hash: str | None = None) ScaleType[source]

Calls a runtime API method

Parameters

api: Name of the runtime API e.g. ‘TransactionPaymentApi’ method: Name of the method e.g. ‘query_fee_details’ params: List of parameters needed to call the runtime API block_hash: Hash of the block at which to make the runtime API call

Returns

ScaleType

search_block_number(block_datetime: datetime, block_time: int = 6) int[source]
serialize_constant(constant, module, spec_version_id) dict[source]

Helper function to serialize a constant

Parameters

constant module spec_version_id

Returns

dict

serialize_module_call(module, call, spec_version, call_index=None) dict[source]

Helper function to serialize a call function

Parameters

module call spec_version call_index

Returns

dict

serialize_module_error(module, error, spec_version) dict[source]

Helper function to serialize an error

Parameters

module error spec_version

Returns

dict

serialize_module_event(module, event, spec_version, event_index) dict[source]

Helper function to serialize an event

Parameters

module event spec_version event_index

Returns

dict

serialize_storage_item(storage_item, module, spec_version_id) dict[source]

Helper function to serialize a storage item

Parameters

storage_item module spec_version_id

Returns

dict

ss58_decode(ss58_address: str) str[source]

Helper function to decode a SS58 address to a public key

Parameters

ss58_address

Returns

str containing the hex representation of the public key

ss58_encode(public_key: str | bytes, ss58_format: int | None = None) str[source]

Helper function to encode a public key to SS58 address.

If no target ss58_format is provided, it will default to the ss58 format of the network it’s connected to.

Parameters

public_key: 32 bytes or hex-string. e.g. 0x6e39f36c370dd51d9a7594846914035de7ea8de466778ea4be6c036df8151f29 ss58_format: target networkID to format the address for, defaults to the network it’s connected to

Returns

str containing the SS58 address

property ss58_format
submit_extrinsic(extrinsic: GenericExtrinsic, wait_for_inclusion: bool = False, wait_for_finalization: bool = False) ExtrinsicReceipt[source]
Submit an extrinsic to the connected node, with the possibility to wait until the extrinsic is included

in a block and/or the block is finalized. The receipt returned provided information about the block and triggered events

Parameters

extrinsic: Extrinsic The extrinsic to be sent to the network wait_for_inclusion: wait until extrinsic is included in a block (only works for websocket connections) wait_for_finalization: wait until extrinsic is finalized (only works for websocket connections)

Returns

ExtrinsicReceipt

subscribe_block_headers(subscription_handler: callable, ignore_decoding_errors: bool = False, include_author: bool = False, finalized_only=False)[source]

Subscribe to new block headers as soon as they are available. The callable subscription_handler will be executed when a new block is available and execution will block until subscription_handler will return a result other than None.

Example:

``` def subscription_handler(obj, update_nr, subscription_id):

print(f”New block #{obj[‘header’][‘number’]} produced by {obj[‘header’][‘author’]}”)

if update_nr > 10

return {‘message’: ‘Subscription will cancel when a value is returned’, ‘updates_processed’: update_nr}

result = substrate.subscribe_block_headers(subscription_handler, include_author=True) ```

Parameters

subscription_handler ignore_decoding_errors: When set this will catch all decoding errors, set the item to None and continue decoding include_author: This will retrieve the block author from the validator set and add to the result finalized_only: when no block_hash or block_number is set, this will retrieve the finalized head

Returns

Value return by subscription_handler

subscribe_storage(storage_keys: List[StorageKey], subscription_handler: callable)[source]

Subscribe to provided storage_keys and keep tracking until subscription_handler returns a value

Example of a StorageKey: ``` StorageKey.create_from_storage_function(

“System”, “Account”, [“5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY”]

)

Example of a subscription handler: ``` def subscription_handler(storage_key, obj, update_nr, subscription_id):

if update_nr == 0:

print(‘Initial data:’, storage_key, obj.value)

if update_nr > 0:

# Do something with the update print(‘data changed:’, storage_key, obj.value)

# The execution will block until an arbitrary value is returned, which will be the result of the function if update_nr > 1:

return obj

```

Parameters

storage_keys: StorageKey list of storage keys to subscribe to subscription_handler: callable to handle value changes of subscription

Returns

supports_rpc_method(name: str) bool[source]

Check if substrate RPC supports given method Parameters ———- name: name of method to check

Returns

bool

property token_decimals
property token_symbol
update_type_registry_presets() bool[source]
property version
class sdk_interface.SubstrateNodeExtension(max_block_range: int = 100)[source]

Bases: SearchExtension

Implementation of SearchExtension using only Substrate RPC methods. Could be significant inefficient.

filter_events(block_start: int | None = None, block_end: int | None = None, pallet_name: str | None = None, event_name: str | None = None, account_id: str | None = None) list[source]

Filters events to match provided search criteria e.g. block range, pallet name, accountID in attributes

Parameters

kwargs

Returns

list

filter_extrinsics(block_start: int | None = None, block_end: int | None = None, ss58_address: str | None = None, pallet_name: str | None = None, call_name: str | None = None) list[source]

Filters extrinsics to match provided search criteria e.g. block range, pallet name, signed by accountID

Parameters

kwargs

Returns

get_block_timestamp(block_number: int) int[source]

Return a UNIX timestamp for given block_number.

Parameters

block_number: int The block_number to retrieve the timestamp for

Returns

int

search_block_number(block_datetime: datetime, block_time: int = 6, **kwargs) int[source]

Search corresponding block number for provided block_datetime. the prediction tolerance is provided with block_time

Parameters

block_datetime: datetime block_time: int kwargs

Returns

int