Skip to content

Commit

Permalink
adjust ID to be O(1) lookup
Browse files Browse the repository at this point in the history
  • Loading branch information
holic committed Nov 2, 2023
1 parent a0f288e commit 7aa8f01
Show file tree
Hide file tree
Showing 9 changed files with 42 additions and 50 deletions.
6 changes: 3 additions & 3 deletions packages/store-sync/src/zustand/createStorageAdapter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ const blocks = groupLogsByBlockNumber(
topics: log.topics as [Hex, ...Hex[]],
strict: true,
});
return formatLog(log as any as RpcLog, { args, eventName: eventName as string }) as StoreEventsLog;
return formatLog(log as unknown as RpcLog, { args, eventName: eventName as string }) as StoreEventsLog;
})
);

Expand All @@ -34,8 +34,8 @@ describe("createStorageAdapter", () => {

expect(useStore.getState().getRecords(tables.NumberList)).toMatchInlineSnapshot(`
{
"0x6e9474e9c83676b9a71133ff96db43e7aa0a4342:0x746200000000000000000000000000004e756d6265724c697374000000000000:0x": {
"id": "0x6e9474e9c83676b9a71133ff96db43e7aa0a4342:0x746200000000000000000000000000004e756d6265724c697374000000000000:0x",
"0x746200000000000000000000000000004e756d6265724c697374000000000000:0x": {
"id": "0x746200000000000000000000000000004e756d6265724c697374000000000000:0x",
"key": {},
"keyTuple": [],
"table": {
Expand Down
7 changes: 3 additions & 4 deletions packages/store-sync/src/zustand/createStorageAdapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { isTableRegistrationLog } from "../isTableRegistrationLog";
import { logToTable } from "./logToTable";
import { hexToResource, spliceHex } from "@latticexyz/common";
import { debug } from "./debug";
import { logToId } from "./logToId";
import { getId } from "./getId";
import { size } from "viem";
import { decodeKey, decodeValueArgs } from "@latticexyz/protocol-parser";
import { flattenSchema } from "../flattenSchema";
Expand Down Expand Up @@ -58,7 +58,7 @@ export function createStorageAdapter<tables extends Tables>({
continue;
}

const id = logToId(log);
const id = getId(log.args);

if (log.eventName === "Store_SetRecord") {
debug("setting record", {
Expand Down Expand Up @@ -181,7 +181,6 @@ export function createStorageAdapter<tables extends Tables>({
),
};

// TODO: improve types
store.setState({ records: records as any });
store.setState({ records });
};
}
13 changes: 5 additions & 8 deletions packages/store-sync/src/zustand/createStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { RawRecord, TableRecord } from "./common";
import { Hex, concatHex } from "viem";
import { encodeKey } from "@latticexyz/protocol-parser";
import { flattenSchema } from "../flattenSchema";
import { getId } from "./getId";

type TableRecords<table extends Table> = {
readonly [id: string]: TableRecord<table>;
Expand Down Expand Up @@ -50,19 +51,15 @@ export function createStore<tables extends Tables>(opts: CreateStoreOptions<tabl
const records = get().records;
return Object.fromEntries(
Object.entries(records).filter(([id, record]) => record.table.tableId === table.tableId)
) as any as TableRecords<table>;
) as unknown as TableRecords<table>;
},
getRecord: <table extends Table>(
table: table,
key: SchemaToPrimitives<table["keySchema"]>
): TableRecord<table> | undefined => {
const records = Object.values(get().records);
const expectedKeyTuple = encodeKey(flattenSchema(table.keySchema), key);
const record = records.find(
(record) =>
record.table.tableId === table.tableId && concatHex([...record.keyTuple]) === concatHex(expectedKeyTuple)
);
return record as TableRecord<table> | undefined;
const keyTuple = encodeKey(flattenSchema(table.keySchema), key);
const id = getId({ tableId: table.tableId, keyTuple });
return get().records[id] as unknown as TableRecord<table> | undefined;
},
getValue: <table extends Table>(
table: table,
Expand Down
16 changes: 16 additions & 0 deletions packages/store-sync/src/zustand/getId.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { describe, it, expect } from "vitest";
import { getId } from "./getId";

describe("getId", () => {
it("should convert a store event log to a unique ID", async () => {
expect(
getId({
tableId: "0x74626d756473746f72650000000000005461626c657300000000000000000000",
keyTuple: ["0x74626d756473746f72650000000000005461626c657300000000000000000000"],
})
).toMatchInlineSnapshot(
// eslint-disable-next-line max-len
'"0x74626d756473746f72650000000000005461626c657300000000000000000000:0x74626d756473746f72650000000000005461626c657300000000000000000000"'
);
});
});
11 changes: 11 additions & 0 deletions packages/store-sync/src/zustand/getId.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { Hex, concatHex } from "viem";

type GetIdOptions = {
readonly tableId: Hex;
readonly keyTuple: readonly Hex[];
};

export function getId({ tableId, keyTuple }: GetIdOptions): string {
// TODO: pass in keyTuple directly once types are fixed (https://github.com/wagmi-dev/viem/pull/1417)
return `${tableId}:${concatHex([...keyTuple])}`;
}
2 changes: 1 addition & 1 deletion packages/store-sync/src/zustand/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
export * from "./common";
export * from "./createStorageAdapter";
export * from "./createStore";
export * from "./logToId";
export * from "./getId";
export * from "./logToTable";
export * from "./syncToZustand";
27 changes: 0 additions & 27 deletions packages/store-sync/src/zustand/logToId.test.ts

This file was deleted.

7 changes: 0 additions & 7 deletions packages/store-sync/src/zustand/logToId.ts

This file was deleted.

3 changes: 3 additions & 0 deletions packages/store-sync/src/zustand/syncToZustand.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,16 @@ import { createStoreSync } from "../createStoreSync";
import { ZustandStore } from "./createStore";
import { createStore } from "./createStore";
import { createStorageAdapter } from "./createStorageAdapter";
import { Address } from "viem";

type AllTables<config extends StoreConfig, extraTables extends Tables> = ResolvedStoreConfig<config>["tables"] &
extraTables &
typeof storeTables &
typeof worldTables;

type SyncToZustandOptions<config extends StoreConfig, extraTables extends Tables> = SyncOptions & {
// require address for now to keep the data model + retrieval simpler
address: Address;
config: config;
tables?: extraTables;
store?: ZustandStore<AllTables<config, extraTables>>;
Expand Down

0 comments on commit 7aa8f01

Please sign in to comment.