### Install py-polkadot-sdk using pip Source: https://github.com/jamdottech/py-polkadot-sdk/blob/master/docs/getting-started/installation.md Installs the `substrate-interface` library from PyPI using the pip package manager. This is the standard way to add the library to your Python environment. ```bash pip install substrate-interface ``` -------------------------------- ### Deploying and Interacting with a Smart Contract in Python Source: https://github.com/jamdottech/py-polkadot-sdk/blob/master/docs/examples.md This snippet demonstrates the process of checking if a contract exists at a specific address, deploying it if not found, and then interacting with its methods ('get' and 'flip'). It includes steps for uploading WASM code, deploying the contract with initial arguments and gas limits, reading contract state, performing gas estimation via a dry run, and executing a state-changing transaction. ```python contract_info = substrate.query("Contracts", "ContractInfoOf", [contract_address]) if contract_info.value: print(f'Found contract on chain: {contract_info.value}') # Create contract instance from deterministic address contract = ContractInstance.create_from_address( contract_address=contract_address, metadata_file=os.path.join(os.path.dirname(__file__), 'assets', 'flipper.json'), substrate=substrate ) else: # Upload WASM code code = ContractCode.create_from_contract_files( metadata_file=os.path.join(os.path.dirname(__file__), 'assets', 'flipper.json'), wasm_file=os.path.join(os.path.dirname(__file__), 'assets', 'flipper.wasm'), substrate=substrate ) # Deploy contract print('Deploy contract...') contract = code.deploy( keypair=keypair, constructor="new", args={'init_value': True}, value=0, gas_limit={'ref_time': 25990000000, 'proof_size': 11990383647911208550}, upload_code=True ) print(f'✅ Deployed @ {contract.contract_address}') # Read current value result = contract.read(keypair, 'get') print('Current value of "get":', result.contract_result_data) # Do a gas estimation of the message gas_predit_result = contract.read(keypair, 'flip') print('Result of dry-run: ', gas_predit_result.value) print('Gas estimate: ', gas_predit_result.gas_required) # Do the actual call print('Executing contract call...') contract_receipt = contract.exec(keypair, 'flip', args={ }, gas_limit=gas_predit_result.gas_required) if contract_receipt.is_success: print(f'Events triggered in contract: {contract_receipt.contract_events}') else: print(f'Error message: {contract_receipt.error_message}') result = contract.read(keypair, 'get') print('Current value of "get":', result.contract_result_data) ``` -------------------------------- ### Install substrate-interface Python Library Source: https://github.com/jamdottech/py-polkadot-sdk/blob/master/README.md Installs the `substrate-interface` library using pip, the Python package installer. This is the first step to use the library. ```Bash pip install substrate-interface ``` -------------------------------- ### Subscribing to Multiple Storage Key Changes in Python Source: https://github.com/jamdottech/py-polkadot-sdk/blob/master/docs/examples.md This example illustrates how to subscribe to updates for multiple storage keys simultaneously. It creates storage keys for two different account addresses and passes them to the `subscribe_storage` method. The handler function is called for each individual key update, printing which key was updated and its new value. ```python from substrateinterface import SubstrateInterface def subscription_handler(storage_key, updated_obj, update_nr, subscription_id): print(f"Update for {storage_key.params[0]}: {updated_obj.value}") substrate = SubstrateInterface(url="ws://127.0.0.1:9944") # Accounts to track storage_keys = [ substrate.create_storage_key( "System", "Account", ["5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY"] ), substrate.create_storage_key( "System", "Account", ["5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty"] ) ] result = substrate.subscribe_storage( storage_keys=storage_keys, subscription_handler=subscription_handler ) ``` -------------------------------- ### Querying Mapped Storage (Basic) with py-polkadot-sdk (Python) Source: https://github.com/jamdottech/py-polkadot-sdk/blob/master/docs/usage/query-storage.md Explains how to iterate over key/value pairs of a mapped storage function using `substrate.query_map()`. This example retrieves the first 199 entries of the 'System.Account' map and prints the free balance for each account. ```python # Retrieve the first 199 System.Account entries result = substrate.query_map('System', 'Account', max_results=199) for account, account_info in result: print(f"Free balance of account '{account.value}': {account_info.value['data']['free']}") ``` -------------------------------- ### Initialize SubstrateInterface in Python Source: https://github.com/jamdottech/py-polkadot-sdk/blob/master/docs/getting-started/installation.md Initializes a connection to a Substrate node using the `SubstrateInterface` class. The URL specifies the WebSocket endpoint of the node. Properties like ss58_format are automatically determined. ```python substrate = SubstrateInterface(url="ws://127.0.0.1:9944") ``` -------------------------------- ### Subscribing to New Block Headers in Python Source: https://github.com/jamdottech/py-polkadot-sdk/blob/master/docs/examples.md This example shows how to establish a subscription to receive notifications whenever a new block header is finalized on the chain. It defines a handler function that processes each new header, prints the block number, retrieves the full block details, and iterates through its extrinsics. The subscription can be cancelled by returning a value from the handler. ```python from substrateinterface import SubstrateInterface substrate = SubstrateInterface(url="ws://127.0.0.1:9944") def subscription_handler(obj, update_nr, subscription_id): print(f"New block #{obj['header']['number']}") block = substrate.get_block(block_number=obj['header']['number']) for idx, extrinsic in enumerate(block['extrinsics']): print(f'# {idx}: {extrinsic.value}') if update_nr > 2: return {'message': 'Subscription will cancel when a value is returned', 'updates_processed': update_nr} result = substrate.subscribe_block_headers(subscription_handler) print(result) ``` -------------------------------- ### Getting Transaction Fee Info with py-polkadot-sdk Source: https://github.com/jamdottech/py-polkadot-sdk/blob/master/docs/examples.md Shows how to retrieve estimated transaction fees for a specific call using the `get_payment_info` method of the `substrate-interface`. It composes a `Balances.transfer_keep_alive` call and then queries the network for its payment details. ```python from substrateinterface import SubstrateInterface, Keypair # import logging # logging.basicConfig(level=logging.DEBUG) substrate = SubstrateInterface( url="ws://127.0.0.1:9944" ) keypair = Keypair.create_from_uri('//Alice') call = substrate.compose_call( call_module='Balances', call_function='transfer_keep_alive', call_params={ 'dest': '5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty', 'value': 1 * 10**15 } ) # Get payment info payment_info = substrate.get_payment_info(call=call, keypair=keypair) print("Payment info: ", payment_info) ``` -------------------------------- ### Submitting Batch Calls with py-polkadot-sdk Source: https://github.com/jamdottech/py-polkadot-sdk/blob/master/docs/examples.md Demonstrates how to compose and submit a batch extrinsic containing multiple calls using the `substrate-interface` library. It shows how to create individual calls, batch them using the `Utility.batch` function, sign the batch extrinsic, and handle the submission receipt. ```python from substrateinterface import SubstrateInterface, Keypair from substrateinterface.exceptions import SubstrateRequestException substrate = SubstrateInterface( url="ws://127.0.0.1:9944" ) keypair = Keypair.create_from_uri('//Alice') balance_call = substrate.compose_call( call_module='Balances', call_function='transfer_keep_alive', call_params={ 'dest': '5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty', 'value': 1 * 10**15 } ) call = substrate.compose_call( call_module='Utility', call_function='batch', call_params={ 'calls': [balance_call, balance_call] } ) extrinsic = substrate.create_signed_extrinsic( call=call, keypair=keypair, era={'period': 64} ) try: receipt = substrate.submit_extrinsic(extrinsic, wait_for_inclusion=True) print('Extrinsic "{}" included in block "{}"'.format( receipt.extrinsic_hash, receipt.block_hash )) if receipt.is_success: print('✅ Success, triggered events:') for event in receipt.triggered_events: print(f'* {event.value}') else: print('⚠️ Extrinsic Failed: ', receipt.error_message) except SubstrateRequestException as e: print("Failed to send: {}".format(e)) ``` -------------------------------- ### Interacting with ink! Contracts with py-polkadot-sdk Source: https://github.com/jamdottech/py-polkadot-sdk/blob/master/docs/examples.md Begins the process of interacting with an ink! smart contract. It shows how to initialize the `SubstrateInterface` and a keypair, and sets a placeholder for the contract address. The snippet is incomplete but sets up the basic connection and account needed for contract interaction. ```python import os from substrateinterface.contracts import ContractCode, ContractInstance from substrateinterface import SubstrateInterface, Keypair substrate = SubstrateInterface( url="ws://127.0.0.1:9944" ) keypair = Keypair.create_from_uri('//Alice') contract_address = "5GhwarrVMH8kjb8XyW6zCfURHbHy3v84afzLbADyYYX6H2Kk" ``` -------------------------------- ### Creating and Submitting Multisig Transactions with py-polkadot-sdk Source: https://github.com/jamdottech/py-polkadot-sdk/blob/master/docs/examples.md Explains how to create and finalize a multisignature transaction. It demonstrates generating a multisig account address, composing a call, initiating the multisig transaction with one signatory, and then finalizing it with another signatory. ```python from substrateinterface import SubstrateInterface, Keypair substrate = SubstrateInterface(url="ws://127.0.0.1:9944") keypair_alice = Keypair.create_from_uri('//Alice', ss58_format=substrate.ss58_format) keypair_bob = Keypair.create_from_uri('//Bob', ss58_format=substrate.ss58_format) keypair_charlie = Keypair.create_from_uri('//Charlie', ss58_format=substrate.ss58_format) # Generate multi-sig account from signatories and threshold multisig_account = substrate.generate_multisig_account( signatories=[ keypair_alice.ss58_address, keypair_bob.ss58_address, keypair_charlie.ss58_address ], threshold=2 ) call = substrate.compose_call( call_module='Balances', call_function='transfer_keep_alive', call_params={ 'dest': keypair_alice.ss58_address, 'value': 3 * 10 ** 3 } ) # Initiate multisig tx extrinsic = substrate.create_multisig_extrinsic(call, keypair_alice, multisig_account, era={'period': 64}) receipt = substrate.submit_extrinsic(extrinsic, wait_for_inclusion=True) if not receipt.is_success: print(f"⚠️ {receipt.error_message}") exit() # Finalize multisig tx with other signatory extrinsic = substrate.create_multisig_extrinsic(call, keypair_bob, multisig_account, era={'period': 64}) receipt = substrate.submit_extrinsic(extrinsic, wait_for_inclusion=True) if receipt.is_success: print(f"✅ {receipt.triggered_events}") else: print(f"⚠️ {receipt.error_message}") ``` -------------------------------- ### Querying Mapped Storage with py-polkadot-sdk Source: https://github.com/jamdottech/py-polkadot-sdk/blob/master/docs/examples.md Illustrates how to query a mapped storage function on the Substrate chain using the `query_map` method. It specifically queries the `System.Account` storage map to retrieve account information, limiting the results to the first 100 entries and printing each account and its details. ```python from substrateinterface import SubstrateInterface substrate = SubstrateInterface( url="ws://127.0.0.1:9944" ) result = substrate.query_map("System", "Account", max_results=100) for account, account_info in result: print(f'* {account.value}: {account_info.value}') ``` -------------------------------- ### Create and Submit Balance Transfer Extrinsic in Python Source: https://github.com/jamdottech/py-polkadot-sdk/blob/master/docs/getting-started/installation.md Demonstrates how to compose a balance transfer extrinsic, sign it with a keypair derived from a mnemonic URI, and submit it to the network. It waits for the extrinsic to be included in a block and prints the transaction and block hashes. ```python call = substrate.compose_call( call_module='Balances', call_function='transfer_keep_alive', call_params={ 'dest': '5E9oDs9PjpsBbxXxRE9uMaZZhnBAV38n2ouLB28oecBDdeQo', 'value': 1 * 10**12 } ) keypair = Keypair.create_from_uri('//Alice') extrinsic = substrate.create_signed_extrinsic(call=call, keypair=keypair) receipt = substrate.submit_extrinsic(extrinsic, wait_for_inclusion=True) print(f"Extrinsic '{receipt.extrinsic_hash}' sent and included in block '{receipt.block_hash}'") ``` -------------------------------- ### Query Account Balance in Python Source: https://github.com/jamdottech/py-polkadot-sdk/blob/master/docs/getting-started/installation.md Queries the balance information for a specific account on the connected Substrate node using the `query` method. It retrieves the 'System' pallet, 'Account' storage item, and filters by the account address. The free balance is then extracted and printed. ```python result = substrate.query('System', 'Account', ['F4xQKRUagnSGjFqafyhajLs94e7Vvzvr8ebwYJceKpr8R7T']) print(result.value['data']['free']) # 635278638077956496 ``` -------------------------------- ### Querying Mapped Storage (Batched) with py-polkadot-sdk (Python) Source: https://github.com/jamdottech/py-polkadot-sdk/blob/master/docs/usage/query-storage.md Shows how `substrate.query_map()` handles large results by fetching them in batches. This example explicitly sets `page_size` and `max_results` to demonstrate retrieving entries in chunks, which is automatically managed by the `QueryMapResult` iterator. ```python # Retrieve all System.Account entries in batches of 200 (automatically appended by `QueryMapResult` iterator) result = substrate.query_map('System', 'Account', page_size=200, max_results=400) for account, account_info in result: print(f"Free balance of account '{account.value}': {account_info.value['data']['free']}") ``` -------------------------------- ### Installing PolkascanExtension with pip (Bash) Source: https://github.com/jamdottech/py-polkadot-sdk/blob/master/docs/extensions/polkascan-extension.md Command to install the PolkascanExtension library using the pip package manager. This is the first step to use the extension. ```bash pip install substrate-interface-polkascan ``` -------------------------------- ### Installing Subsquid Extension via pip Source: https://github.com/jamdottech/py-polkadot-sdk/blob/master/docs/extensions/subsquid-extension.md This snippet shows the command to install the Subsquid Extension package using pip, the Python package installer. This is the standard way to add the extension to your Python environment. ```bash pip install substrate-interface-subsquid ``` -------------------------------- ### Querying Historic Account Balance in Python Source: https://github.com/jamdottech/py-polkadot-sdk/blob/master/docs/examples.md This code demonstrates how to query the balance of a specific account at a historical block number. It retrieves the block hash for the given number, then uses it to query the 'System', 'Account' storage item at that specific point in history. A helper function is included to format the balance using the chain's token decimals and symbol. ```python from substrateinterface import SubstrateInterface substrate = SubstrateInterface(url="ws://127.0.0.1:9944") block_number = 10 block_hash = substrate.get_block_hash(block_number) result = substrate.query( "System", "Account", ["5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY"], block_hash=block_hash ) def format_balance(amount: int): amount = format(amount / 10**substrate.properties.get('tokenDecimals', 0), ".15g") return f"{amount} {substrate.properties.get('tokenSymbol', 'UNIT')}" balance = (result.value["data"]["free"] + result.value["data"]["reserved"]) print(f"Balance @ {block_number}: {format_balance(balance)}") ``` -------------------------------- ### Subscribing to Single Storage Key Changes in Python Source: https://github.com/jamdottech/py-polkadot-sdk/blob/master/docs/examples.md This snippet demonstrates how to subscribe to updates for a specific storage key, in this case, the account information for a given address. The handler function receives the initial value and subsequent updates, printing the account data each time it changes. The subscription remains active until the handler returns a value. ```python from substrateinterface import SubstrateInterface substrate = SubstrateInterface( url="ws://127.0.0.1:9944" ) def subscription_handler(account_info_obj, update_nr, subscription_id): if update_nr == 0: print('Initial account data:', account_info_obj.value) if update_nr > 0: # Do something with the update print('Account data changed:', account_info_obj.value) # The execution will block until an arbitrary value is returned, which will be the result of the `query` if update_nr > 5: return account_info_obj result = substrate.query("System", "Account", ["5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY"], subscription_handler=subscription_handler) print(result) ``` -------------------------------- ### Get Runtime API Parameter Information (Python) Source: https://github.com/jamdottech/py-polkadot-sdk/blob/master/docs/usage/call-runtime-apis.md Illustrates how to fetch detailed information about the expected parameters for a specific runtime API method. This helper function assists in correctly structuring the input arguments before making a runtime call. ```python runtime_call = substrate.get_metadata_runtime_call_function("ContractsApi", "call") param_info = runtime_call.get_param_info() ``` -------------------------------- ### Getting Call Parameter Info in Python Source: https://github.com/jamdottech/py-polkadot-sdk/blob/master/docs/usage/extrinsics.md This snippet demonstrates how to obtain a call function object from the Substrate metadata and then use its `get_param_info()` method to retrieve a detailed breakdown of its parameters, which is useful for constructing complex call arguments. ```Python call_function = substrate.get_metadata_call_function("XTokens", "transfer") param_info = call_function.get_param_info() ``` -------------------------------- ### Getting Storage Parameter Info with py-polkadot-sdk (Python) Source: https://github.com/jamdottech/py-polkadot-sdk/blob/master/docs/usage/query-storage.md Illustrates how to use the `get_param_info()` helper function on a storage function object obtained via `get_metadata_storage_function()` to understand the structure and types required for composing complex storage function parameters. The output shows the expected format for parameters like 'Token' or 'DexShare'. ```python storage_function = substrate.get_metadata_storage_function("Tokens", "TotalIssuance") print(storage_function.get_param_info()) # [{ # 'Token': ('ACA', 'AUSD', 'DOT', 'LDOT', 'RENBTC', 'CASH', 'KAR', 'KUSD', 'KSM', 'LKSM', 'TAI', 'BNC', 'VSKSM', 'PHA', 'KINT', 'KBTC'), # 'DexShare': ({'Token': ('ACA', 'AUSD', 'DOT', 'LDOT', 'RENBTC', 'CASH', 'KAR', 'KUSD', 'KSM', 'LKSM', 'TAI', 'BNC', 'VSKSM', 'PHA', 'KINT', 'KBTC'), 'Erc20': '[u8; 20]', 'LiquidCrowdloan': 'u32', 'ForeignAsset': 'u16'}, {'Token': ('ACA', 'AUSD', 'DOT', 'LDOT', 'RENBTC', 'CASH', 'KAR', 'KUSD', 'KSM', 'LKSM', 'TAI', 'BNC', 'VSKSM', 'PHA', 'KINT', 'KBTC'), 'Erc20': '[u8; 20]', 'LiquidCrowdloan': 'u32', 'ForeignAsset': 'u16'}), # 'Erc20': '[u8; 20]', # 'StableAssetPoolToken': 'u32', # 'LiquidCrowdloan': 'u32', # 'ForeignAsset': 'u16' # }] ``` -------------------------------- ### Querying DoubleMap Storage with py-polkadot-sdk (Python) Source: https://github.com/jamdottech/py-polkadot-sdk/blob/master/docs/usage/query-storage.md Provides an example of querying a `DoubleMap` storage function, specifically 'Staking.ErasStakers'. It uses `substrate.query_map()` and includes the first key parameter (`params=[2100]`) to iterate over the second key dimension for a specific era. ```python era_stakers = substrate.query_map( module='Staking', storage_function='ErasStakers', params=[2100] ) ``` -------------------------------- ### Using SubstrateInterface Context Manager in Python Source: https://github.com/jamdottech/py-polkadot-sdk/blob/master/docs/usage/cleanup-and-context-manager.md This snippet shows how to use the `SubstrateInterface` within a Python `with` statement. This ensures that the `close()` method is automatically called when the block is exited, releasing resources like the websocket connection. The example queries system events within the context. ```python with SubstrateInterface(url="wss://rpc.polkadot.io") as substrate: events = substrate.query("System", "Events") ``` -------------------------------- ### Getting Block Timestamp by Number Source: https://github.com/jamdottech/py-polkadot-sdk/blob/master/docs/extensions/substrate-node-extension.md Provides an example of using the 'get_block_timestamp' method to retrieve the timestamp associated with a given block number. ```python # Get timestamp for specific block number block_timestamp = substrate.extensions.get_block_timestamp(block_number) ``` -------------------------------- ### Reading Data from ink! Contract with Python Source: https://github.com/jamdottech/py-polkadot-sdk/blob/master/docs/usage/ink-contract-interfacing.md Performs a read-only call to a contract method ('get') using a keypair and prints the returned data from the contract result. ```python result = contract.read(keypair, 'get') print('Current value of \"get\":', result.contract_result_data) ``` -------------------------------- ### Initializing PolkascanExtension in Python Source: https://github.com/jamdottech/py-polkadot-sdk/blob/master/docs/extensions/polkascan-extension.md Demonstrates how to import necessary classes, create a SubstrateInterface instance, and register the PolkascanExtension with a specified GraphQL API URL. ```python from substrateinterface import SubstrateInterface from substrateinterface_polkascan.extensions import PolkascanExtension substrate = SubstrateInterface(url="ws://127.0.0.1:9944") substrate.register_extension(PolkascanExtension(url='http://127.0.0.1:8000/graphql/')) ``` -------------------------------- ### Initializing SubstrateNodeExtension Source: https://github.com/jamdottech/py-polkadot-sdk/blob/master/docs/extensions/substrate-node-extension.md Initializes the SubstrateInterface and registers the SubstrateNodeExtension. The 'max_block_range' parameter controls the maximum number of blocks to scan for queries, impacting performance. ```python substrate = SubstrateInterface(url="ws://127.0.0.1:9944") # Provide maximum block range (bigger range descreases performance) substrate.register_extension(SubstrateNodeExtension(max_block_range=100)) ``` -------------------------------- ### Deploying ink! Contract with Python Source: https://github.com/jamdottech/py-polkadot-sdk/blob/master/docs/usage/ink-contract-interfacing.md Connects to a Substrate node, loads contract code from metadata and WASM files, and deploys the contract using a specified keypair, endowment, gas limit, constructor, and initial arguments. ```python substrate = SubstrateInterface( url="ws://127.0.0.1:9944", type_registry_preset='canvas' ) keypair = Keypair.create_from_uri('//Alice') # Deploy contract code = ContractCode.create_from_contract_files( metadata_file=os.path.join(os.path.dirname(__file__), 'assets', 'flipper.json'), wasm_file=os.path.join(os.path.dirname(__file__), 'assets', 'flipper.wasm'), substrate=substrate ) contract = code.deploy( keypair=keypair, endowment=0, gas_limit=1000000000000, constructor="new", args={'init_value': True}, upload_code=True ) print(f'✅ Deployed @ {contract.contract_address}') ``` -------------------------------- ### Serialized ScaleType Output (JSON) Source: https://github.com/jamdottech/py-polkadot-sdk/blob/master/docs/usage/using-scaletype-objects.md Illustrates the structure of the dictionary produced by calling the serialize() method on a ScaleType object, using the account_info example. This shows how the nested structure is represented as a standard Python dictionary, suitable for JSON conversion. ```json { "nonce": 5, "consumers": 0, "providers": 1, "sufficients": 0, "data": { "free": 1152921503981846391, "reserved": 0, "misc_frozen": 0, "fee_frozen": 0 } } ``` -------------------------------- ### Initializing SubstrateInterface with Subsquid Extension Source: https://github.com/jamdottech/py-polkadot-sdk/blob/master/docs/extensions/subsquid-extension.md This Python code demonstrates how to initialize the SubstrateInterface and then register the SubsquidExtension with it. It requires importing the necessary classes and providing the URL for the Substrate node and the Subsquid GraphQL endpoint. ```python from substrateinterface import SubstrateInterface from substrateinterface_subsquid.extensions import SubsquidExtension substrate = SubstrateInterface(url="wss://rpc.polkadot.io") substrate.register_extension(SubsquidExtension(url='https://squid.subsquid.io/gs-explorer-polkadot/graphql')) ``` -------------------------------- ### Query Account Balance in Python Source: https://github.com/jamdottech/py-polkadot-sdk/blob/master/README.md Queries the 'System' module and 'Account' storage entry for a specific SS58 address using the initialized `substrate` interface. It then prints the free balance value from the result. ```Python result = substrate.query('System', 'Account', ['F4xQKRUagnSGjFqafyhajLs94e7Vvzvr8ebwYJceKpr8R7T']) print(result.value['data']['free']) # 635278638077956496 ``` -------------------------------- ### Call Runtime API Method (Python) Source: https://github.com/jamdottech/py-polkadot-sdk/blob/master/docs/usage/call-runtime-apis.md Demonstrates how to execute a specific runtime API method on a Substrate node. It shows how to specify the API and method names and pass required parameters, such as an account ID for querying the nonce. ```python result = substrate.runtime_call("AccountNonceApi", "account_nonce", ["5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY"]) ``` -------------------------------- ### Initiate Multisig Extrinsic - Python Source: https://github.com/jamdottech/py-polkadot-sdk/blob/master/docs/usage/extrinsics.md Shows how to compose the call to be executed by the multisig, create the multisig extrinsic using one signatory's keypair and the multisig account details, and submit it to the chain, waiting for inclusion. This is the first step in a multi-signature process. ```python call = substrate.compose_call( call_module='System', call_function='remark_with_event', call_params={ 'remark': 'Multisig test' } ) extrinsic = substrate.create_multisig_extrinsic(call, keypair_alice, multisig_account, era={'period': 64}) receipt = substrate.submit_extrinsic(extrinsic, wait_for_inclusion=True) ``` -------------------------------- ### List Available Runtime APIs and Methods (Python) Source: https://github.com/jamdottech/py-polkadot-sdk/blob/master/docs/usage/call-runtime-apis.md Shows how to retrieve a comprehensive list of all runtime API functions exposed by the connected Substrate node. This is useful for discovering available functionality and their signatures. ```python runtime_calls = substrate.get_metadata_runtime_call_functions() ``` -------------------------------- ### Querying Multiple Storage Entries with py-polkadot-sdk (Python) Source: https://github.com/jamdottech/py-polkadot-sdk/blob/master/docs/usage/query-storage.md Demonstrates the efficient way to query multiple storage entries in a single RPC request using `substrate.query_multi()`. It requires creating a list of storage keys using `substrate.create_storage_key()` for each desired entry and then iterating through the results. ```python storage_keys = [ substrate.create_storage_key( "System", "Account", ["F4xQKRUagnSGjFqafyhajLs94e7Vvzvr8ebwYJceKpr8R7T"] ), substrate.create_storage_key( "System", "Account", ["GSEX8kR4Kz5UZGhvRUCJG93D5hhTAoVZ5tAe6Zne7V42DSi"] ), substrate.create_storage_key( "Staking", "Bonded", ["GSEX8kR4Kz5UZGhvRUCJG93D5hhTAoVZ5tAe6Zne7V42DSi"] ) ] result = substrate.query_multi(storage_keys) for storage_key, value_obj in result: print(storage_key, value_obj) ``` -------------------------------- ### Initialize Substrate Interface in Python Source: https://github.com/jamdottech/py-polkadot-sdk/blob/master/README.md Creates an instance of the `SubstrateInterface` class, connecting to a Substrate node via WebSocket. The URL specifies the node address and port. ```Python substrate = SubstrateInterface(url="ws://127.0.0.1:9944") ``` -------------------------------- ### Generate Multisig Account Address - Python Source: https://github.com/jamdottech/py-polkadot-sdk/blob/master/docs/usage/extrinsics.md Explains how to create a Keypair for one signatory and then use the generate_multisig_account function to derive the deterministic multisig account address based on a list of signatory addresses and the required threshold for approval. ```python keypair_alice = Keypair.create_from_uri('//Alice', ss58_format=substrate.ss58_format) multisig_account = substrate.generate_multisig_account( signatories=[ keypair_alice.ss58_address, '5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty', '5FLSigC9HGRKVhB9FiEo4Y3koPsNmBmLJbpXg2mp1hXcS59Y' ], threshold=2 ) ``` -------------------------------- ### Estimating Network Fees Polkadot Python Source: https://github.com/jamdottech/py-polkadot-sdk/blob/master/docs/usage/extrinsics.md This snippet demonstrates how to estimate the network fees for a given extrinsic call using the `get_payment_info` method of the substrate object. It requires a prepared `call` object and the signing `keypair`. The method returns a dictionary containing fee details like class, partial fee, and weight. ```python payment_info = substrate.get_payment_info(call=call, keypair=keypair) ``` -------------------------------- ### Querying Single Storage Item with py-polkadot-sdk (Python) Source: https://github.com/jamdottech/py-polkadot-sdk/blob/master/docs/usage/query-storage.md Demonstrates how to query a single storage item, specifically the 'Account' storage function within the 'System' pallet, for a given address using the `substrate.query()` method. It shows how to access specific fields like 'nonce' and 'data.free' from the result object. ```python result = substrate.query('System', 'Account', ['F4xQKRUagnSGjFqafyhajLs94e7Vvzvr8ebwYJceKpr8R7T']) print(result.value['nonce']) # 7695 print(result.value['data']['free']) # 635278638077956496 ``` -------------------------------- ### Instantiating Existing ink! Contract with Python Source: https://github.com/jamdottech/py-polkadot-sdk/blob/master/docs/usage/ink-contract-interfacing.md Creates a ContractInstance object for an already deployed contract using its deterministic address, the contract's metadata file, and the Substrate interface. ```python # Create contract instance from deterministic address contract = ContractInstance.create_from_address( contract_address=contract_address, metadata_file=os.path.join(os.path.dirname(__file__), 'assets', 'flipper.json'), substrate=substrate ) ``` -------------------------------- ### Querying Storage at Specific Block Hash with py-polkadot-sdk (Python) Source: https://github.com/jamdottech/py-polkadot-sdk/blob/master/docs/usage/query-storage.md Shows how to query the state of a storage item at a historical block by providing the `block_hash` parameter to the `substrate.query()` method. This allows retrieving data as it existed at a particular point in the blockchain's history. ```python account_info = substrate.query( module='System', storage_function='Account', params=['F4xQKRUagnSGjFqafyhajLs94e7Vvzvr8ebwYJceKpr8R7T'], block_hash='0x176e064454388fd78941a0bace38db424e71db9d5d5ed0272ead7003a02234fa' ) print(account_info['nonce'].value) # 7673 print(account_info['data']['free'].value) # 637747267365404068 ``` -------------------------------- ### Create Keypair from Mnemonic and Sign/Verify (SR25519) - Python Source: https://github.com/jamdottech/py-polkadot-sdk/blob/master/docs/usage/keypair-creation-and-signing.md Demonstrates generating a BIP39 mnemonic, creating a keypair from it using the default SR25519 cryptography, signing a test message, and verifying the signature. ```python mnemonic = Keypair.generate_mnemonic() keypair = Keypair.create_from_mnemonic(mnemonic) signature = keypair.sign("Test123") if keypair.verify("Test123", signature): print('Verified') ``` -------------------------------- ### Create Keypair from Mnemonic URI (Soft/Hard Derivation) - Python Source: https://github.com/jamdottech/py-polkadot-sdk/blob/master/docs/usage/keypair-creation-and-signing.md Illustrates creating a keypair by combining a mnemonic with soft and hard key derivation paths specified in a URI format. ```python mnemonic = Keypair.generate_mnemonic() keypair = Keypair.create_from_uri(mnemonic + '//hard/soft') ``` -------------------------------- ### Create Keypair from Default Development URI - Python Source: https://github.com/jamdottech/py-polkadot-sdk/blob/master/docs/usage/keypair-creation-and-signing.md Demonstrates creating a keypair using a URI that omits the mnemonic, causing the library to use the default development mnemonic (e.g., for accounts like '//Alice'). ```python keypair = Keypair.create_from_uri('//Alice') ``` -------------------------------- ### Submit Standard Signed Extrinsic - Python Source: https://github.com/jamdottech/py-polkadot-sdk/blob/master/docs/usage/extrinsics.md Shows how to compose a runtime call, create a signed extrinsic using a keypair, and submit it to the chain, waiting for block inclusion. Includes basic error handling for submission failures. ```python call = substrate.compose_call( call_module='Balances', call_function='transfer_keep_alive', call_params={ 'dest': '5E9oDs9PjpsBbxXxRE9uMaZZhnBAV38n2ouLB28oecBDdeQo', 'value': 1 * 10**12 } ) extrinsic = substrate.create_signed_extrinsic(call=call, keypair=keypair) try: receipt = substrate.submit_extrinsic(extrinsic, wait_for_inclusion=True) print(f"Extrinsic '{receipt.extrinsic_hash}' sent and included in block '{receipt.block_hash}'") except SubstrateRequestException as e: print("Failed to send: {}".format(e)) ``` -------------------------------- ### Create and Submit Balance Transfer Extrinsic in Python Source: https://github.com/jamdottech/py-polkadot-sdk/blob/master/README.md Composes a 'Balances' transfer call with a destination address and value. It then signs the call using a keypair derived from a URI and submits the signed extrinsic to the node, waiting for its inclusion in a block. ```Python call = substrate.compose_call( call_module='Balances', call_function='transfer', call_params={ 'dest': '5E9oDs9PjpsBbxXxRE9uMaZZhnBAV38n2ouLB28oecBDdeQo', 'value': 1 * 10**12 } ) keypair = Keypair.create_from_uri('//Alice') extrinsic = substrate.create_signed_extrinsic(call=call, keypair=keypair) receipt = substrate.submit_extrinsic(extrinsic, wait_for_inclusion=True) print(f"Extrinsic '{receipt.extrinsic_hash}' sent and included in block '{receipt.block_hash}'") ``` -------------------------------- ### Create Keypair from Mnemonic URI (BIP44 ECDSA) - Python Source: https://github.com/jamdottech/py-polkadot-sdk/blob/master/docs/usage/keypair-creation-and-signing.md Explains how to create an ECDSA keypair from a mnemonic using a BIP44 derivation path specified in a URI, which is commonly used for compatibility with Ethereum wallets. ```python mnemonic = Keypair.generate_mnemonic() keypair = Keypair.create_from_uri(f"{mnemonic}/m/44'/60'/0'/0/0", crypto_type=KeypairType.ECDSA) ``` -------------------------------- ### Verify Signature with Public Key (Ethereum/ECDSA) - Python Source: https://github.com/jamdottech/py-polkadot-sdk/blob/master/docs/usage/keypair-creation-and-signing.md Shows how to verify a signature using only the public key (hex format) of the signer, specifically for Ethereum-style keypairs using ECDSA cryptography. ```python keypair = Keypair.create_from_uri("/m/44'/60/0'/0", crypto_type=KeypairType.ECDSA) signature = keypair.sign('test') keypair_public = Keypair(public_key='0x5e20a619338338772e97aa444e001043da96a43b', crypto_type=KeypairType.ECDSA) result = keypair_public.verify('test', signature) ``` -------------------------------- ### Subscribing to Single Storage Key using query() in Python Source: https://github.com/jamdottech/py-polkadot-sdk/blob/master/docs/usage/subscriptions.md Demonstrates subscribing to a single storage item using the `query()` function with a `subscription_handler`. The handler receives updates, and returning a value from the handler terminates the subscription. ```python def subscription_handler(account_info_obj, update_nr, subscription_id): if update_nr == 0: print('Initial account data:', account_info_obj.value) if update_nr > 0: # Do something with the update print('Account data changed:', account_info_obj.value) # The execution will block until an arbitrary value is returned, which will be the result of the `query` if update_nr > 5: return account_info_obj result = substrate.query("System", "Account", ["5GNJqTPyNqANBkUVMN1LPPrxXnFouWXoe2wNSmmEoLctxiZY"], subscription_handler=subscription_handler) print(result) ``` -------------------------------- ### Create Keypair from Encrypted PolkadotJS JSON - Python Source: https://github.com/jamdottech/py-polkadot-sdk/blob/master/docs/usage/keypair-creation-and-signing.md Shows how to load an encrypted keypair from a file saved in the PolkadotJS JSON format, requiring a passphrase for decryption and specifying the SS58 format. ```python with open('5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY.json', 'r') as fp: json_data = fp.read() keypair = Keypair.create_from_encrypted_json(json_data, passphrase="test", ss58_format=42) ``` -------------------------------- ### Finalize Multisig Extrinsic - Python Source: https://github.com/jamdottech/py-polkadot-sdk/blob/master/docs/usage/extrinsics.md Shows how a second signatory creates a multisig extrinsic for the *same* call and multisig account. Submitting this extrinsic provides the necessary second signature, triggering the execution of the original call on-chain once the threshold is met. ```python # Define the multisig account by supplying its signatories and threshold keypair_charlie = Keypair.create_from_uri('//Charlie', ss58_format=substrate.ss58_format) multisig_account = substrate.generate_multisig_account( signatories=[ keypair_charlie.ss58_address, '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY', '5FLSigC9HGRKVhB9FiEo4Y3koPsNmBmLJbpXg2mp1hXcS59Y' ], threshold=2 ) extrinsic = substrate.create_multisig_extrinsic(call, keypair_charlie, multisig_account, era={'period': 64}) receipt = substrate.submit_extrinsic(extrinsic, wait_for_inclusion=True) ``` -------------------------------- ### Subscribing to Multiple Storage Keys using subscribe_storage() in Python Source: https://github.com/jamdottech/py-polkadot-sdk/blob/master/docs/usage/subscriptions.md Shows how to subscribe to changes for multiple storage keys efficiently using the `subscribe_storage()` function. Updates for any of the tracked keys are pushed to the `subscription_handler`, and returning a value ends the subscription. ```python def subscription_handler(storage_key, updated_obj, update_nr, subscription_id): print(f"Update for {storage_key.params[0]}: {updated_obj.value}") # Accounts to track storage_keys = [ substrate.create_storage_key( "System", "Account", ["5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY"] ), substrate.create_storage_key( "System", "Account", ["5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty"] ) ] result = substrate.subscribe_storage( storage_keys=storage_keys, subscription_handler=subscription_handler ) ``` -------------------------------- ### Create Keypair from Mnemonic (ECDSA) - Python Source: https://github.com/jamdottech/py-polkadot-sdk/blob/master/docs/usage/keypair-creation-and-signing.md Shows how to create a keypair from a mnemonic while explicitly specifying the ECDSA cryptography type, which is suitable for generating Ethereum-style addresses, and prints the resulting SS58 address. ```python keypair = Keypair.create_from_mnemonic(mnemonic, crypto_type=KeypairType.ECDSA) print(keypair.ss58_address) # '0x6741864968e8b87c6e32e19cde88A11a3Cc636E9' ``` -------------------------------- ### Executing ink! Contract Call with Python Source: https://github.com/jamdottech/py-polkadot-sdk/blob/master/docs/usage/ink-contract-interfacing.md First performs a dry-run ('read') of a state-changing method ('flip') to estimate gas requirements, then executes the actual transaction ('exec') with the estimated gas limit, and reports the success or failure including triggered events or error messages. ```python # Do a gas estimation of the message gas_predit_result = contract.read(keypair, 'flip') print('Result of dry-run: ', gas_predit_result.value) print('Gas estimate: ', gas_predit_result.gas_required) # Do the actual call print('Executing contract call...') contract_receipt = contract.exec(keypair, 'flip', args={ }, gas_limit=gas_predit_result.gas_required) if contract_receipt.is_success: print(f'Events triggered in contract: {contract_receipt.contract_events}') else: print(f'Error message: {contract_receipt.error_message}') ``` -------------------------------- ### Filtering Events with SubstrateNodeExtension Source: https://github.com/jamdottech/py-polkadot-sdk/blob/master/docs/extensions/substrate-node-extension.md Demonstrates how to use the 'filter_events' method to retrieve events of a specific type ('Balances.Transfer') within a block range. A negative 'block_start' value queries the last N blocks. ```python # Returns all `Balances.Transfer` events from the last 30 blocks events = substrate.extensions.filter_events(pallet_name="Balances", event_name="Transfer", block_start=-30) ``` -------------------------------- ### Searching Block Number by Datetime Source: https://github.com/jamdottech/py-polkadot-sdk/blob/master/docs/extensions/substrate-node-extension.md Illustrates using the 'search_block_number' method to find the block number corresponding to a specific Python 'datetime' object. ```python # Search for block number corresponding a specific datetime block_datetime = datetime(2020, 7, 12, 0, 0, 0) block_number = substrate.extensions.search_block_number(block_datetime=block_datetime) ``` -------------------------------- ### Verify Signature with Public Address (Substrate/SR25519) - Python Source: https://github.com/jamdottech/py-polkadot-sdk/blob/master/docs/usage/keypair-creation-and-signing.md Demonstrates verifying a signature using only the public address (SS58 format) of the signer, specifically for Substrate-style keypairs using SR25519 cryptography. ```python keypair = Keypair.create_from_uri("//Alice", crypto_type=KeypairType.SR25519) signature = keypair.sign('test') keypair_public = Keypair(ss58_address='5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY', crypto_type=KeypairType.SR25519) result = keypair_public.verify('test', signature) ```