-
Hi, I want to subscribe to balance changes. I want to receive the balance in an event or trigger an event about a change, increase or decrease in the balance. Could you tell me how I can do this? I didn't find this in the documentation. Thanks. |
Beta Was this translation helpful? Give feedback.
Replies: 6 comments
-
Hello, I believe you can subscribe to the storage key |
Beta Was this translation helpful? Give feedback.
-
I've tried to do it like in code below. Future startBalanceListening(String address, Function(BalanceData) onUpdate) async { |
Beta Was this translation helpful? Give feedback.
-
|
Beta Was this translation helpful? Give feedback.
-
thanks, I'll try :) |
Beta Was this translation helpful? Give feedback.
-
Thanks to your help, chatGpt and official Polkadot.js documentation I find out everything work correct with this code :) final MyChainDot _myChainDot;
final Map<String, StreamSubscription<StorageChangeSet>> _addressSubscriptionMap = {};
@override
Future<void> startBalanceListening(String? address, Function(BalanceData) onUpdate) async {
if (address == null || address.isEmpty || _addressSubscriptionMap[address] != null) return;
final accountPubKey = Address.decode(address).pubkey;
final storageAccountKeyQuery = [_myChainDot.query.system.accountKey(accountPubKey)];
_addressSubscriptionMap[address] = await _myChainDot.rpc.state.subscribeStorage(
storageAccountKeyQuery,
(storageChangeSet) async {
final accountInfo = await _myChainDot.query.system.account(accountPubKey);
onUpdate.call(
BalanceData(
accountId: address,
accountNonce: accountInfo.nonce,
availableBalance: (accountInfo.data.free + accountInfo.data.reserved + accountInfo.data.frozen),
),
);
},
);
}
@override
Future<void> stopBalancesListening(String? address) async {
if (address == null || address.isEmpty || _addressSubscriptionMap[address] == null) return;
final subscription = _addressSubscriptionMap[address];
if (subscription == null) return;
_addressSubscriptionMap.remove(address);
await subscription.cancel();
} |
Beta Was this translation helpful? Give feedback.
-
Great, glad it helped |
Beta Was this translation helpful? Give feedback.
Thanks to your help, chatGpt and official Polkadot.js documentation I find out everything work correct with this code :)