1

I am subscribing system events using the events api. After I got the specific event I am looking for, how should get the block hash of this event?

Thanks

api.query.system.events((events) => {
    console.log(`\nReceived ${events.length} events:`);

    // Loop through the Vec<EventRecord>
    events.forEach((record) => {
      const { event, phase } = record;

      // found the one
      if (event.section === 'SomeSection') {
          // notify user the block hash
      }
    });
  });
New contributor
KaiKang.eth is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
1
  • More specifically I am listening to events fired by a chain bridge. I would like to notify the users of the block hash when their assets are arrived at the polkadot side of bridge. Aug 5 at 10:16

1 Answer 1

1

There may be a simpler way to do this but here is a script:

import { ApiPromise, WsProvider } from '@polkadot/api';

export const getEvents = async () => {

    const wsProvider = new WsProvider('wss://rpc.polkadot.io');
    const api = await ApiPromise.create({ provider: wsProvider });
    await api.rpc.chain.subscribeNewHeads(async (header) => {
        console.log(`Chain is at block: #${header.number}`);
        const blockHash = await api.rpc.chain.getBlockHash(header.number);
        console.log(`blockHash: ${blockHash}`);
        const at = await api.at(blockHash);
        const events = await at.query.system.events();
        console.log(events.toHuman());
    });
}

Your Answer

KaiKang.eth is a new contributor. Be nice, and check out our Code of Conduct.

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.