Skip to content

Commit

Permalink
feat(zustand): add sync progress (#1928)
Browse files Browse the repository at this point in the history
  • Loading branch information
holic authored Nov 13, 2023
1 parent 50bfa36 commit 2b3c948
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
15 changes: 15 additions & 0 deletions packages/store-sync/src/zustand/createStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { Hex } from "viem";
import { encodeKey } from "@latticexyz/protocol-parser";
import { flattenSchema } from "../flattenSchema";
import { getId } from "./getId";
import { SyncStep } from "../SyncStep";

type TableRecords<table extends Table> = {
readonly [id: string]: TableRecord<table>;
Expand All @@ -13,6 +14,13 @@ type TableRecords<table extends Table> = {
// TODO: split this into distinct stores and combine (https://docs.pmnd.rs/zustand/guides/typescript#slices-pattern)?

export type ZustandState<tables extends Tables> = {
readonly syncProgress: {
readonly step: SyncStep;
readonly message: string;
readonly percentage: number;
readonly latestBlockNumber: bigint;
readonly lastBlockNumberProcessed: bigint;
};
/** Tables derived from table registration store events */
readonly tables: {
readonly [tableId: Hex]: Table;
Expand Down Expand Up @@ -44,6 +52,13 @@ export type CreateStoreOptions<tables extends Tables> = {

export function createStore<tables extends Tables>(opts: CreateStoreOptions<tables>): ZustandStore<tables> {
return create<ZustandState<tables>>((set, get) => ({
syncProgress: {
step: SyncStep.INITIALIZE,
message: "Connecting",
percentage: 0,
latestBlockNumber: 0n,
lastBlockNumberProcessed: 0n,
},
tables: Object.fromEntries(Object.entries(opts.tables).map(([, table]) => [table.tableId, table])),
rawRecords: {},
records: {},
Expand Down
6 changes: 6 additions & 0 deletions packages/store-sync/src/zustand/syncToZustand.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { ZustandStore } from "./createStore";
import { createStore } from "./createStore";
import { createStorageAdapter } from "./createStorageAdapter";
import { Address } from "viem";
import { SyncStep } from "../SyncStep";

type AllTables<
config extends StoreConfig,
Expand Down Expand Up @@ -52,6 +53,11 @@ export async function syncToZustand<config extends StoreConfig, extraTables exte
const storeSync = await createStoreSync({
storageAdapter,
...syncOptions,
onProgress: (syncProgress) => {
// already live, no need for more progress updates
if (useStore.getState().syncProgress.step === SyncStep.LIVE) return;
useStore.setState(() => ({ syncProgress }));
},
});

const sub = startSync ? storeSync.storedBlockLogs$.subscribe() : null;
Expand Down

0 comments on commit 2b3c948

Please sign in to comment.