-
Notifications
You must be signed in to change notification settings - Fork 196
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat(store-sync): add syncToStash util #3192
Merged
Merged
Changes from 9 commits
Commits
Show all changes
21 commits
Select commit
Hold shift + click to select a range
092f735
feat(store-sync): add syncToStash util
alvrs 0b1df9d
add storage adapter test
alvrs d8884f2
Create lucky-cows-fail.md
alvrs e849e71
export internally
alvrs 0fa1431
move changeset to stash release pr
alvrs b40c55e
move to local imports
alvrs a956537
clean up test
alvrs b656458
Merge remote-tracking branch 'origin/main' into alvrs/sync-to-stash
holic 737e3d8
small refactor
holic a19168f
reduce diff
holic a0b5612
use tree shakable stuff
holic b17ab4e
more
holic 57e03e7
fix type name
holic d07c6bd
add changeset for syncToStash
alvrs e55c61a
update changeset
holic 24f0773
Update .changeset/lucky-cows-fail.md
holic 945807f
more changeset tweaks
holic 076d3fb
add stash to ts paths
holic 5fe044c
less specific type
holic c12d0a9
more paths
holic b5a5cbc
Merge branch 'main' into alvrs/sync-to-stash
alvrs File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1 +1,2 @@ | ||
export * from "../sql"; | ||
export * from "../stash"; |
92 changes: 92 additions & 0 deletions
92
packages/store-sync/src/stash/createStorageAdapter.test.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,92 @@ | ||
import { beforeAll, describe, expect, it } from "vitest"; | ||
import { storeEventsAbi } from "@latticexyz/store"; | ||
import { createStorageAdapter } from "./createStorageAdapter"; | ||
import { config, deployMockGame } from "../../test/mockGame"; | ||
import { fetchAndStoreLogs } from "../fetchAndStoreLogs"; | ||
import { testClient } from "../../test/common"; | ||
import { getBlockNumber } from "viem/actions"; | ||
import { createStash } from "@latticexyz/stash/internal"; | ||
|
||
describe("createStorageAdapter", async () => { | ||
beforeAll(async () => { | ||
await deployMockGame(); | ||
}); | ||
|
||
it("sets component values from logs", async () => { | ||
const stash = createStash(config); | ||
const storageAdapter = createStorageAdapter({ stash }); | ||
|
||
console.log("fetching blocks"); | ||
// eslint-disable-next-line @typescript-eslint/no-unused-vars | ||
for await (const block of fetchAndStoreLogs({ | ||
storageAdapter, | ||
publicClient: testClient, | ||
events: storeEventsAbi, | ||
fromBlock: 0n, | ||
toBlock: await getBlockNumber(testClient), | ||
})) { | ||
// | ||
} | ||
|
||
expect(stash.get().records).toMatchInlineSnapshot(` | ||
{ | ||
"": { | ||
"Health": { | ||
"0x078cf0753dd50f7C56F20B3Ae02719EA199BE2eb": { | ||
"health": 0n, | ||
"player": "0x078cf0753dd50f7C56F20B3Ae02719EA199BE2eb", | ||
}, | ||
"0x1D96F2f6BeF1202E4Ce1Ff6Dad0c2CB002861d3e": { | ||
"health": 5n, | ||
"player": "0x1D96F2f6BeF1202E4Ce1Ff6Dad0c2CB002861d3e", | ||
}, | ||
"0x328809Bc894f92807417D2dAD6b7C998c1aFdac6": { | ||
"health": 5n, | ||
"player": "0x328809Bc894f92807417D2dAD6b7C998c1aFdac6", | ||
}, | ||
}, | ||
"Inventory": {}, | ||
"Position": { | ||
"0x078cf0753dd50f7C56F20B3Ae02719EA199BE2eb": { | ||
"player": "0x078cf0753dd50f7C56F20B3Ae02719EA199BE2eb", | ||
"x": 3, | ||
"y": 5, | ||
}, | ||
"0x1D96F2f6BeF1202E4Ce1Ff6Dad0c2CB002861d3e": { | ||
"player": "0x1D96F2f6BeF1202E4Ce1Ff6Dad0c2CB002861d3e", | ||
"x": 1, | ||
"y": -1, | ||
}, | ||
"0x328809Bc894f92807417D2dAD6b7C998c1aFdac6": { | ||
"player": "0x328809Bc894f92807417D2dAD6b7C998c1aFdac6", | ||
"x": 3, | ||
"y": 5, | ||
}, | ||
"0xdBa86119a787422C593ceF119E40887f396024E2": { | ||
"player": "0xdBa86119a787422C593ceF119E40887f396024E2", | ||
"x": 100, | ||
"y": 100, | ||
}, | ||
}, | ||
"Score": {}, | ||
"Terrain": { | ||
"3|5": { | ||
"terrainType": 2, | ||
"x": 3, | ||
"y": 5, | ||
}, | ||
}, | ||
"Winner": {}, | ||
}, | ||
} | ||
`); | ||
|
||
expect(stash.getRecord({ table: config.tables.Terrain, key: { x: 3, y: 5 } })).toMatchInlineSnapshot(` | ||
{ | ||
"terrainType": 2, | ||
"x": 3, | ||
"y": 5, | ||
} | ||
`); | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,77 @@ | ||
import { CreateStoreResult, getTable, StoreConfig } from "@latticexyz/stash/internal"; | ||
import { | ||
decodeKey, | ||
decodeValueArgs, | ||
encodeValueArgs, | ||
getKeySchema, | ||
getSchemaTypes, | ||
getValueSchema, | ||
KeySchema, | ||
} from "@latticexyz/protocol-parser/internal"; | ||
import { spliceHex } from "@latticexyz/common"; | ||
import { size } from "viem"; | ||
import { Table } from "@latticexyz/config"; | ||
import { StorageAdapter, StorageAdapterBlock, emptyValueArgs } from "../common"; | ||
|
||
export type CreateStorageAdapter<config extends StoreConfig> = { | ||
stash: CreateStoreResult<config>; | ||
}; | ||
|
||
export function createStorageAdapter<const config extends StoreConfig>({ | ||
stash, | ||
}: CreateStorageAdapter<config>): StorageAdapter { | ||
const tables = Object.values(stash.get().config).flatMap((namespace) => Object.values(namespace)) as readonly Table[]; | ||
|
||
return async function storageAdapter({ logs }: StorageAdapterBlock): Promise<void> { | ||
for (const log of logs) { | ||
const tableConfig = tables.find((t) => t.tableId === log.args.tableId); | ||
if (!tableConfig) continue; | ||
|
||
// TODO: this should probably return `| undefined`? | ||
const table = getTable({ stash, table: tableConfig }); | ||
|
||
const valueSchema = getSchemaTypes(getValueSchema(tableConfig)); | ||
const keySchema = getSchemaTypes(getKeySchema(tableConfig)) as KeySchema; | ||
const key = decodeKey(keySchema, log.args.keyTuple); | ||
|
||
if (log.eventName === "Store_SetRecord") { | ||
const value = decodeValueArgs(valueSchema, log.args); | ||
table.setRecord({ key, value }); | ||
} else if (log.eventName === "Store_SpliceStaticData") { | ||
const previousValue = table.getRecord({ key }); | ||
|
||
const { | ||
staticData: previousStaticData, | ||
encodedLengths, | ||
dynamicData, | ||
} = previousValue ? encodeValueArgs(valueSchema, previousValue) : emptyValueArgs; | ||
|
||
const staticData = spliceHex(previousStaticData, log.args.start, size(log.args.data), log.args.data); | ||
const value = decodeValueArgs(valueSchema, { | ||
staticData, | ||
encodedLengths, | ||
dynamicData, | ||
}); | ||
|
||
table.setRecord({ key, value }); | ||
} else if (log.eventName === "Store_SpliceDynamicData") { | ||
const previousValue = table.getRecord({ key }); | ||
|
||
const { staticData, dynamicData: previousDynamicData } = previousValue | ||
? encodeValueArgs(valueSchema, previousValue) | ||
: emptyValueArgs; | ||
|
||
const dynamicData = spliceHex(previousDynamicData, log.args.start, log.args.deleteCount, log.args.data); | ||
const value = decodeValueArgs(valueSchema, { | ||
staticData, | ||
encodedLengths: log.args.encodedLengths, | ||
dynamicData, | ||
}); | ||
|
||
table.setRecord({ key, value }); | ||
} else if (log.eventName === "Store_DeleteRecord") { | ||
table.deleteRecord({ key }); | ||
} | ||
} | ||
}; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
export * from "./createStorageAdapter"; | ||
export * from "./syncToStash"; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,76 @@ | ||
import { CreateStoreResult, StoreConfig } from "@latticexyz/stash/internal"; | ||
import { Address, Client, publicActions } from "viem"; | ||
import { createStorageAdapter } from "./createStorageAdapter"; | ||
import { defineTable } from "@latticexyz/store/config/v2"; | ||
import { SyncStep } from "../SyncStep"; | ||
import { SyncResult } from "../common"; | ||
import { createStoreSync } from "../createStoreSync"; | ||
import { getSchemaPrimitives, getValueSchema } from "@latticexyz/protocol-parser/internal"; | ||
|
||
export const SyncProgress = defineTable({ | ||
namespaceLabel: "syncToStash", | ||
label: "SyncProgress", | ||
schema: { | ||
step: "string", | ||
percentage: "uint32", | ||
latestBlockNumber: "uint256", | ||
lastBlockNumberProcessed: "uint256", | ||
message: "string", | ||
}, | ||
key: [], | ||
}); | ||
|
||
export const initialProgress = { | ||
step: SyncStep.INITIALIZE, | ||
percentage: 0, | ||
latestBlockNumber: 0n, | ||
lastBlockNumberProcessed: 0n, | ||
message: "Connecting", | ||
} satisfies getSchemaPrimitives<getValueSchema<typeof SyncProgress>>; | ||
|
||
export type SyncToStashOptions<config extends StoreConfig> = { | ||
stash: CreateStoreResult<config>; | ||
client: Client; | ||
address: Address; | ||
startSync?: boolean; | ||
}; | ||
|
||
export type SyncToStashResult = Omit<SyncResult, "waitForTransaction"> & { | ||
waitForStateChange: SyncResult["waitForTransaction"]; | ||
stopSync: () => void; | ||
}; | ||
|
||
export async function syncToStash<const config extends StoreConfig>({ | ||
stash, | ||
client, | ||
address, | ||
startSync = true, | ||
}: SyncToStashOptions<config>): Promise<SyncToStashResult> { | ||
stash.registerTable({ table: SyncProgress }); | ||
|
||
const storageAdapter = createStorageAdapter({ stash }); | ||
|
||
const { waitForTransaction: waitForStateChange, ...sync } = await createStoreSync({ | ||
storageAdapter, | ||
publicClient: client.extend(publicActions) as never, | ||
address, | ||
onProgress: (nextValue) => { | ||
const currentValue = stash.getRecord({ table: SyncProgress, key: {} }); | ||
// update sync progress until we're caught up and live | ||
if (currentValue?.step !== SyncStep.LIVE) { | ||
stash.setRecord({ table: SyncProgress, key: {}, value: nextValue }); | ||
} | ||
}, | ||
}); | ||
|
||
const sub = startSync ? sync.storedBlockLogs$.subscribe() : null; | ||
function stopSync(): void { | ||
sub?.unsubscribe(); | ||
} | ||
|
||
return { | ||
...sync, | ||
waitForStateChange, | ||
stopSync, | ||
}; | ||
} |
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@alvrs this is where types got wonky