From 0c4cccd1cede17c4fa1771078c85422fa2b6ad8a Mon Sep 17 00:00:00 2001 From: Francesco Ceccon Date: Thu, 11 Jan 2024 11:25:07 +0100 Subject: [PATCH] Add examples --- examples/starknet-client/index.ts | 55 +++++++++++++++++++++++++++ examples/starknet-client/package.json | 15 ++++++++ 2 files changed, 70 insertions(+) create mode 100644 examples/starknet-client/index.ts create mode 100644 examples/starknet-client/package.json diff --git a/examples/starknet-client/index.ts b/examples/starknet-client/index.ts new file mode 100644 index 0000000..d3a9562 --- /dev/null +++ b/examples/starknet-client/index.ts @@ -0,0 +1,55 @@ +import { StreamClient } from "@apibara/protocol"; +import { Filter, StarkNetCursor, v1alpha2 } from "@apibara/starknet"; + +async function main() { + const client = new StreamClient({ + url: "sepolia.starknet.a5a.ch", + token: process.env.DNA_TOKEN, + async onReconnect(err, retryCount) { + console.log("reconnect", err, retryCount); + // Sleep for 1 second before retrying. + await new Promise(resolve => setTimeout(resolve, 1000)); + + return { reconnect: true }; + } + }) + + const filter = Filter.create().withHeader({ weak: false }).encode(); + + client.configure({ + filter, + batchSize: 1, + cursor: StarkNetCursor.createWithBlockNumber(18_000), + }) + + for await (const message of client) { + switch (message.message) { + case "data": { + if (!message.data?.data) { + continue; + } + for (const data of message.data.data) { + const block = v1alpha2.Block.decode(data); + const { header } = block; + if (!header) { + continue; + } + console.log("Block " + header.blockNumber?.toString()); + } + break; + } + case "invalidate": { + break; + } + case "heartbeat": { + console.log("Received heartbeat"); + break; + } + } + } +} + +main().then(() => process.exit(0)).catch(error => { + console.error(error); + process.exit(1); +}); diff --git a/examples/starknet-client/package.json b/examples/starknet-client/package.json new file mode 100644 index 0000000..49c1350 --- /dev/null +++ b/examples/starknet-client/package.json @@ -0,0 +1,15 @@ +{ + "name": "starknet-client-example", + "version": "0.0.0", + "private": true, + "scripts": { + "start": "ts-node index.ts" + }, + "dependencies": { + "@apibara/protocol": "workspace:*", + "@apibara/starknet": "workspace:*" + }, + "devDependencies": { + "ts-node": "^10.9.1" + } +}