-
Notifications
You must be signed in to change notification settings - Fork 54
/
Copy pathindex.ts
452 lines (417 loc) · 16 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
import {
Component,
ComponentValue,
Entity,
Metadata,
Schema,
setComponent,
} from "@dojoengine/recs";
import {
Clause,
EntityKeysClause,
OrderBy,
PatternMatching,
ToriiClient,
} from "@dojoengine/torii-client";
import { convertValues } from "../utils";
/**
* Fetches and synchronizes entities with their components. This is useful for initializing the world state.
* @param client - The client instance for API communication.
* @param components - An array of component definitions.
* @param clause - An optional clause to filter entities.
* @param entityKeyClause - An array of entity key clauses to synchronize.
* @param limit - The maximum number of entities to fetch per request (default: 100).
* @param logging - Whether to log debug information (default: true).
* @returns A promise that resolves to a subscription for entity updates.
*
* @example
* // Fetch all entities and their components
* const components = createClientComponents({ contractComponents });
* const subscription = await getSyncEntities(client, components);
*
* @example
* // Fetch filtered entities and their components
* const components = createClientComponents({ contractComponents });
* const clause = { ... }; // Define your filter clause
* const entityKeyClause = [ ... ]; // Define your entity key clauses
* const subscription = await getSyncEntities(client, components, clause, entityKeyClause);
*
* This function fetches entities and their components from the client, then
* sets up a subscription for entity updates. It uses the provided clause (if any)
* to filter entities and the specified components to determine which data to retrieve.
* The function fetches entities in batches, controlled by the 'limit' parameter,
* and then establishes a real-time subscription for future updates.
*/
export const getSyncEntities = async <S extends Schema>(
client: ToriiClient,
components: Component<S, Metadata, undefined>[],
clause: Clause | undefined,
entityKeyClause: EntityKeysClause[],
orderBy: OrderBy[] = [],
entityModels: string[] = [],
limit: number = 100,
logging: boolean = false
) => {
if (logging) console.log("Starting getSyncEntities ", clause);
await getEntities(
client,
clause,
components,
orderBy,
entityModels,
limit,
logging
);
return await syncEntities(client, components, entityKeyClause, logging);
};
/**
* Fetches and synchronizes events with their components. This is useful for initializing the world state with event data.
* @param client - The client instance for API communication.
* @param components - An array of component definitions.
* @param clause - An optional clause to filter events.
* @param entityKeyClause - An array of entity key clauses to synchronize.
* @param limit - The maximum number of events to fetch per request (default: 100).
* @param logging - Whether to log debug information (default: false).
* @param historical - Whether to fetch and subscribe to historical events (default: false).
* @param callback - An optional callback function to be called after fetching events.
* @returns A promise that resolves to a subscription for event updates.
*
* @example
* // Fetch all events and their components
* const components = createClientComponents({ contractComponents });
* const subscription = await getSyncEvents(client, components, undefined, entityKeyClause);
*
* @example
* // Fetch filtered events and their components
* const components = createClientComponents({ contractComponents });
* const clause = { ... }; // Define your filter clause
* const entityKeyClause = [ ... ]; // Define your entity key clauses
* const subscription = await getSyncEvents(client, components, clause, entityKeyClause);
*
* This function fetches events and their components from the client, then
* sets up a subscription for event updates. It uses the provided clause (if any)
* to filter events and the specified components to determine which data to retrieve.
* The function fetches events in batches, controlled by the 'limit' parameter,
* and then establishes a real-time subscription for future updates.
*/
export const getSyncEvents = async <S extends Schema>(
client: ToriiClient,
components: Component<S, Metadata, undefined>[],
clause: Clause | undefined,
entityKeyClause: EntityKeysClause[],
orderBy: OrderBy[] = [],
entityModels: string[] = [],
limit: number = 100,
logging: boolean = false,
historical: boolean = true,
callback?: () => void
) => {
if (logging) console.log("Starting getSyncEvents");
await getEvents(
client,
components,
orderBy,
entityModels,
limit,
clause,
logging,
historical,
callback
);
return await syncEvents(client, components, entityKeyClause, logging);
};
/**
* Fetches all entities and their components from the client.
* @param client - The client instance for API communication.
* @param clause - An optional clause to filter entities.
* @param components - An array of component definitions.
* @param limit - The maximum number of entities to fetch per request (default: 100).
* @param logging - Whether to log debug information (default: false).
*
* @example
* const components = createClientComponents({ contractComponents });
* await getEntities(client, undefined, components, 100);
*
* This function performs paginated queries to fetch all entities and their components.
*/
export const getEntities = async <S extends Schema>(
client: ToriiClient,
clause: Clause | undefined,
components: Component<S, Metadata, undefined>[],
orderBy: OrderBy[] = [],
entityModels: string[] = [],
limit: number = 100,
logging: boolean = false
) => {
if (logging) console.log("Starting getEntities");
let offset = 0;
let continueFetching = true;
while (continueFetching) {
const entities = await client.getEntities({
limit,
offset,
clause,
order_by: orderBy,
entity_models: entityModels,
dont_include_hashed_keys: false,
});
if (logging) console.log("entities", entities);
if (logging) console.log(`Fetched ${entities} entities`);
setEntities(entities, components, logging);
if (Object.keys(entities).length < limit) {
continueFetching = false;
} else {
offset += limit;
}
}
};
/**
* Fetches event messages from the client and synchronizes them with t
* he specified components.
* @param client - The client instance for API communication.
* @param components - An array of component definitions.
* @param limit - The maximum number of event messages to fetch per request (default: 100).
* @param clause - An optional clause to filter event messages.
* @param logging - Whether to log debug information (default: false).
* @param historical - Whether to fetch historical events (default: false).
* @param callback - An optional callback function to be called after fetching events.
*/
export const getEvents = async <S extends Schema>(
client: ToriiClient,
components: Component<S, Metadata, undefined>[],
orderBy: OrderBy[] = [],
entityModels: string[] = [],
limit: number = 100,
clause: Clause | undefined,
logging: boolean = false,
historical: boolean = false,
callback?: () => void
) => {
if (logging) console.log("Starting getEvents");
let offset = 0;
let continueFetching = true;
while (continueFetching) {
const entities = await client.getEventMessages(
{
limit,
offset,
clause,
order_by: orderBy,
entity_models: entityModels,
dont_include_hashed_keys: false,
},
historical
);
if (logging) console.log("entities", entities);
setEntities(entities, components, logging);
if (Object.keys(entities).length === 0) {
continueFetching = false;
} else {
offset += limit;
}
}
callback && callback();
};
/**
* Fetches entities and their components from the client based on specified criteria.
* @param client - The client instance for API communication.
* @param components - An array of component definitions to fetch.
* @param entityKeyClause - An EntityKeysClause to filter entities by their keys.
* @param patternMatching - The pattern matching strategy for entity keys (default: "FixedLen").
* @param limit - The maximum number of entities to fetch per request (default: 1000).
* @param logging - Whether to log debug information (default: false).
*
* @example
* const components = createClientComponents({ contractComponents });
* await getEntitiesQuery(client, components, { Keys: { keys: ["0x1"], models: ["Position"] } }, "FixedLen", 1000);
*
* This function performs paginated queries to fetch all matching entities and their
* components. It uses the provided EntityKeysClause to filter entities and
* the specified components to determine which data to retrieve.
*
* Note: Make sure to synchronize the entities by calling the syncEntities method after this.
*/
export const getEntitiesQuery = async <S extends Schema>(
client: ToriiClient,
components: Component<S, Metadata, undefined>[],
entityKeyClause: EntityKeysClause,
patternMatching: PatternMatching = "FixedLen",
orderBy: OrderBy[] = [],
entityModels: string[] = [],
limit: number = 1000,
logging: boolean = false
) => {
if (logging) console.log("Starting getEntitiesQuery");
let cursor = 0;
let continueFetching = true;
const componentArray = Object.values(components);
const clause: Clause | null = entityKeyClause
? {
Keys: {
keys:
"HashedKeys" in entityKeyClause
? entityKeyClause.HashedKeys
: entityKeyClause.Keys.keys,
pattern_matching: patternMatching,
models: [
...componentArray.map((c) => c.metadata?.name as string),
],
},
}
: null;
const fetchedEntities = await client.getEntities({
limit,
offset: cursor,
clause: clause || undefined,
order_by: orderBy,
entity_models: entityModels,
dont_include_hashed_keys: false,
});
while (continueFetching) {
if (logging)
console.log(
`Fetched ${Object.keys(fetchedEntities).length} entities ${cursor}`
);
setEntities(fetchedEntities, components, logging);
if (Object.keys(fetchedEntities).length < limit) {
continueFetching = false;
} else {
cursor += limit;
}
}
};
/**
* Sets up a subscription to sync entity updates.
* @param client - The client instance for API communication.
* @param components - An array of component definitions.
* @param entityKeyClause - An array of EntityKeysClause to filter entities.
* @param logging - Whether to log debug information (default: true).
* @returns A promise that resolves with the subscription handler.
* @example
* const sync = await syncEntities(client, components, entityKeyClause);
* // later...
* sync.cancel(); // cancel the subscription
*/
export const syncEntities = async <S extends Schema>(
client: ToriiClient,
components: Component<S, Metadata, undefined>[],
entityKeyClause: EntityKeysClause[],
logging: boolean = true
) => {
if (logging) console.log("Starting syncEntities");
return await client.onEntityUpdated(
entityKeyClause,
(fetchedEntities: any, data: any) => {
if (logging) console.log("Entity updated", fetchedEntities);
setEntities({ [fetchedEntities]: data }, components, logging);
}
);
};
/**
* Sets up a subscription to sync event messages.
* @param client - The client instance for API communication.
* @param components - An array of component definitions.
* @param entityKeyClause - An array of EntityKeysClause to filter entities.
* @param logging - Whether to log debug information (default: false).
* @param historical - Whether to sync to historical events (default: false).
* @returns A promise that resolves with the subscription handler.
* @example
* const sync = await syncEvents(client, components, entityKeyClause);
* // later...
* sync.cancel(); // cancel the subscription
*/
export const syncEvents = async <S extends Schema>(
client: ToriiClient,
components: Component<S, Metadata, undefined>[],
entityKeyClause: EntityKeysClause[],
logging: boolean = false,
historical: boolean = false
) => {
if (logging) console.log("Starting syncEvents");
return await client.onEventMessageUpdated(
entityKeyClause,
historical,
(fetchedEntities: any, data: any) => {
if (logging) console.log("Event message updated", fetchedEntities);
setEntities({ [fetchedEntities]: data }, components, logging);
}
);
};
/**
* Updates the components of entities in the local state.
* @param entities - An object of entities with their updated component data.
* @param components - An array of component definitions.
* @param logging - Whether to log debug information (default: false).
*/
export const setEntities = async <S extends Schema>(
entities: any,
components: Component<S, Metadata, undefined>[],
logging: boolean = false
) => {
if (
Object.keys(entities).length === 0 ||
(Object.keys(entities).length === 1 &&
entities["0x0"] &&
Object.keys(entities["0x0"]).length === 0)
) {
console.warn("No entities to set");
return;
}
if (logging) console.log("Entities to set:", entities);
for (let key in entities) {
if (!Object.hasOwn(entities, key)) {
continue;
}
for (let componentName in entities[key]) {
if (!Object.hasOwn(entities[key], componentName)) {
continue;
}
let recsComponent = Object.values(components).find(
(component) =>
component.metadata?.namespace +
"-" +
component.metadata?.name ===
componentName
);
if (recsComponent) {
try {
const rawValue = entities[key][componentName];
if (logging)
console.log(
`Raw value for ${componentName} on ${key}:`,
rawValue
);
const convertedValue = convertValues(
recsComponent.schema,
rawValue
) as ComponentValue;
if (logging)
console.log(
`Converted value for ${componentName} on ${key}:`,
convertedValue
);
if (!convertedValue) {
console.error(
`convertValues returned undefined or invalid for ${componentName} on ${key}`
);
}
setComponent(recsComponent, key as Entity, convertedValue);
if (logging)
console.log(
`Set component ${recsComponent.metadata?.name} on ${key}`
);
} catch (error) {
console.warn(
`Failed to set component ${recsComponent.metadata?.name} on ${key}`,
error
);
}
} else {
if (logging)
console.warn(
`Component ${componentName} not found in provided components.`
);
}
}
}
};