Instance

These operations are specifically designed for use within instance handlers and are tailored to handle blockchain reorganisations (reorgs) automatically. When you're indexing blockchain data and writing to a reorg-aware database, InstanceDBOperations ensure that any reorgs are managed behind the scenes, eliminating the need for manual intervention. It's recommended to use these operations for all write operations within instance handler code, as they ensure the data remains consistent and reliable, even in the event of a reorg.

import { Instance } from "@blockflow-labs/sdk";


Operations

The Instance client in the Blockflow SDK provides two primary operations that are crucial for managing blockchain data with automatic reorg handling:

  1. save The save operation is used to store data in your database. This function ensures that any blockchain data being indexed is saved reliably, with built-in reorg handling to maintain data integrity in case of blockchain reorganisations.

  2. load The load operation retrieves data from the database. It allows you to access previously stored blockchain data, ensuring that the data is reorg-aware and consistent with the current blockchain state.


How to Use

To use the Instance Client in combination with MongoClient, you can set it up as shown in the example below. This code maintains two databases:

  1. One to store all Transfer events.

  2. Another to store sender information, the number of times a transfer was made from a given address.

import { IEventContext, IBind, ISecrets } from "@blockflow-labs/utils";

import { Instance } from "@blockflow-labs/sdk";

import { Sender, Transfer, ITransfer, ISender } from "../../types/generated";

/**
 * @dev Event::Transfer(address from, address to, uint256 value)
 * @param context trigger object with contains {event: {from ,to ,value }, transaction, block, log}
 * @param bind init function for database wrapper methods
 */
export const TransferHandler = async (
  context: IEventContext,
  bind: IBind,
  secrets: ISecrets
) => {
  // Implement your event handler logic for Transfer here

  const { event, transaction, block, log } = context;
  const { from, to, value } = event;

  const client = Instance.MongoClient(bind);

  const transferDB = client.db(Transfer);
  const senderDB = client.db(Sender);

  let transfer: ITransfer = {
    from: from.toString(),
    to: to.toString(),
    amount: value.toString(),
  };

  let sender: ISender = await senderDB.load({
    account: from.toString(),
  });

  if (!sender) {
    sender = {
      account: from.toString(),
      frequency: 1,
    };
  } else {
    sender = {
      ...sender,
      frequency: sender.frequency + 1,
    };
  }

  await Promise.all([transferDB.save(transfer), senderDB.save(sender)]);
};

Last updated