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
      }
    });
  });
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, 2022 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

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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