@apibara/protocol
This package contains the client used to stream data from Apibara.
Installation#
Install the package from npm:
npm add @apibara/protocol
yarn install @apibara/protocol
pnpm add @apibara/protocol
Example#
This example shows how to connect to the StarkNet stream and stream all
Ethereum ERC20 token Transfer
events.
Start by importing the types and classes used by this example.
import {StreamClient,ChannelCredentials,v1alpha2} from '@apibara/protocol'import {Filter,FieldElement,v1alpha2 as starknet} from '@apibara/starknet'import { hash } from 'starknet'
Then create the filter object. The filter is used to
ask the stream for specific data, in this case the stream will only contain
events matching the given key (the Transfer
event) and emitted from the given
smart contract.
const address = FieldElement.fromBigInt('0x049d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7')const transferKey = [FieldElement.fromBigInt(hash.getSelectorFromName('Transfer'))]// Create stream filter. The client will only receive the specified data.//// - events: all transfer events from the eth contract// - state update: all storage diffs from the eth contractconst filter = Filter.create().addEvent((ev) =>ev.withFromAddress(address).withKeys(transferKey)).withStateUpdate((su) =>su.addStorageDiff((st) => st.withContractAddress(address))).encode()
Then create the client, specifying the authorization token created in the Apibara dashboard.
const client = new StreamClient({url: 'mainnet.starknet.a5a.ch',token: '<dna_token>'})
If you're connecting to a local instance of Apibara you need to disable SSL.
const client = new StreamClient({url: 'localhost:7171',credentials: ChannelCredentials.createInsecure(),})
You can specify gRPC options using the clientOptions
argument:
const client = new StreamClient({url: 'mainnet.starknet.a5a.ch',clientOptions: {'grpc.max_receive_message_length': 128 * 1_048_576, // 128 MiB},})
The client needs to send its configuration to the server, we can do this with the configure
method.
This method accepts a filter (each stream type has a different filter), a batch size and the requested data finality.
Apibara sends historical data in batches to maximize performance, the batch size can be tweaked to optimize syncing speed.
await client.configure({filter,batchSize: 10,finality: v1alpha2.DataFinality.DATA_STATUS_FINALIZED})
Finally, we can iterate over the async stream generated by the client. Each message contains a batch of data.
for await (const message of client) {if (message.data?.data) {// handle data}}
The data contained in a batch is specific to each stream.