How to subscribe to the balance change of multiple wallets #326
-
Hey py-substrate-interface community! Polkadot.js clearly states it's possible (and even encouraged) to subscribe to events of multiple subjects: Let's say I would like to track the balance change of two wallets, how could I do that using SubstrateInterface, as the following code for a single wallet doesn't work: Could somebody point me to the right direction on how can I do such a Multi Query via SubstrateInterface please? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 5 replies
-
It's possible, but because this library is blocking by nature (unlike PolkadotJS), you'll need to use threads with separate instances. Here's an example of how you can do it: from concurrent.futures import ThreadPoolExecutor
from substrateinterface import SubstrateInterface
accounts = [
"5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY",
"5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty"
]
def track_account(account: str):
print(f"Tracking {account} ..")
with SubstrateInterface(url='ws://127.0.0.1:9944/', ss58_format=42) as substrate:
def subscription_handler(account_info_obj, update_nr, subscription_id):
print("Balance change:", account, account_info_obj.value)
substrate.query("System", "Account", [account], subscription_handler=subscription_handler)
with ThreadPoolExecutor(4) as executor:
executor.map(track_account, accounts) |
Beta Was this translation helpful? Give feedback.
-
Since v1.6.0 is now possible to subscribe to multiple storage keys in one instance: 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
) |
Beta Was this translation helpful? Give feedback.
Since v1.6.0 is now possible to subscribe to multiple storage keys in one instance: