/
setupMUDV2Network.ts
211 lines (189 loc) · 6.85 KB
/
setupMUDV2Network.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
import {
createNetwork,
createContracts,
Mappings,
createTxQueue,
createSyncWorker,
Ack,
InputType,
SingletonID,
RawTableRecord,
keyTupleToEntityID,
} from "@latticexyz/network";
import { BehaviorSubject, concatMap, from, Subject } from "rxjs";
import { Components, defineComponent, Type, World } from "@latticexyz/recs";
import { computed } from "mobx";
import { keccak256 } from "@latticexyz/utils";
import { TableId } from "@latticexyz/common/deprecated";
import { World as WorldContract } from "@latticexyz/world/types/ethers-contracts/World";
import { IWorldKernel__factory } from "@latticexyz/world/types/ethers-contracts/factories/IWorldKernel.sol/IWorldKernel__factory";
import { defineStringComponent } from "../components";
import { ContractComponent, ContractComponents, SetupContractConfig } from "./types";
import { applyNetworkUpdates, createEncoders } from "./utils";
import { defineContractComponents as defineStoreComponents } from "../mud-definitions/store/contractComponents";
import { defineContractComponents as defineWorldComponents } from "../mud-definitions/world/contractComponents";
import * as devObservables from "../dev/observables";
import { Abi } from "abitype";
import { createDatabase, createDatabaseClient } from "@latticexyz/store-cache";
import { StoreConfig } from "@latticexyz/store";
type SetupMUDV2NetworkOptions<C extends ContractComponents, S extends StoreConfig> = {
networkConfig: SetupContractConfig;
world: World;
contractComponents: C;
initialGasPrice?: number;
fetchSystemCalls?: boolean;
syncThread?: "main" | "worker";
syncStoreCache?: boolean;
storeConfig: S;
worldAbi: Abi; // TODO: should this extend IWorldKernel ABI or a subset of?
};
export async function setupMUDV2Network<C extends ContractComponents, S extends StoreConfig>({
networkConfig,
world,
contractComponents,
initialGasPrice,
fetchSystemCalls,
syncThread,
storeConfig,
syncStoreCache = true,
worldAbi = IWorldKernel__factory.abi,
}: SetupMUDV2NetworkOptions<C, S>) {
devObservables.worldAbi$.next(worldAbi);
const SystemsRegistry = defineStringComponent(world, {
id: "SystemsRegistry",
metadata: { contractId: "world.component.systems" },
});
const ComponentsRegistry = defineStringComponent(world, {
id: "ComponentsRegistry",
metadata: { contractId: "world.component.components" },
});
// used by SyncWorker to notify client of sync progress
const LoadingState = defineComponent(
world,
{
state: Type.Number,
msg: Type.String,
percentage: Type.Number,
},
{
id: "LoadingState",
metadata: { contractId: "component.LoadingState" },
}
);
const storeSchemaTableId = new TableId("mudstore", "schema");
const storeSchemaComponent = defineComponent(
world,
{ valueSchema: Type.String, keySchema: Type.String },
{
metadata: {
contractId: storeSchemaTableId.toHex(),
tableId: storeSchemaTableId.toString(),
},
}
);
const storeComponents = defineStoreComponents(world);
const worldComponents = defineWorldComponents(world);
const components = {
// v2 components
storeSchemaComponent,
...storeComponents,
...worldComponents,
...contractComponents,
// v1 components
SystemsRegistry,
ComponentsRegistry,
LoadingState,
} satisfies Components;
// Mapping from component contract id to key in components object
const mappings: Mappings<typeof components> = {};
// Function to register new components in mappings object
function registerComponent(key: string, component: ContractComponent) {
if (typeof component.metadata?.tableId === "string") {
mappings[component.metadata.tableId] = key;
} else {
mappings[
keccak256(typeof component.metadata?.contractId === "string" ? component.metadata.contractId : component.id)
] = key;
}
}
// Register initial components in mappings object
for (const key of Object.keys(components)) {
registerComponent(key, components[key]);
}
const network = await createNetwork(networkConfig);
world.registerDisposer(network.dispose);
const signerOrProvider = computed(() => network.signer.get() || network.providers.get().json);
const { contracts, config: contractsConfig } = await createContracts<{ World: WorldContract }>({
config: { World: { abi: IWorldKernel__factory.abi, address: networkConfig.worldAddress } },
signerOrProvider,
});
const gasPriceInput$ = new BehaviorSubject<number>(
// If no initial gas price is provided, check the gas price once and add a 30% buffer
initialGasPrice || Math.ceil((await signerOrProvider.get().getGasPrice()).toNumber() * 1.3)
);
// TODO: replace this with `fastTxExecutor`
const { txQueue, dispose: disposeTxQueue } = createTxQueue(contracts, network, gasPriceInput$, {
devMode: networkConfig.devMode,
});
world.registerDisposer(disposeTxQueue);
// For LoadingState updates
const singletonEntity = world.registerEntity({ id: SingletonID });
// Register player entity
const address = network.connectedAddress.get();
const playerEntity = address ? world.registerEntity({ id: keyTupleToEntityID([address]) }) : undefined;
// Create sync worker
const ack$ = new Subject<Ack>();
// Avoid passing externalProvider to sync worker (too complex to copy)
const {
provider: { externalProvider: _, ...providerConfig },
...syncWorkerConfig
} = networkConfig;
const { ecsEvents$, input$, dispose } = createSyncWorker<typeof components>(ack$, { thread: syncThread });
world.registerDisposer(dispose);
function startSync(initialRecords?: RawTableRecord[], initialBlockNumber?: number) {
input$.next({
type: InputType.Config,
data: {
...syncWorkerConfig,
provider: providerConfig,
worldContract: contractsConfig.World,
initialBlockNumber: initialBlockNumber ?? networkConfig.initialBlockNumber,
disableCache: networkConfig.disableCache || [31337, 1337].includes(networkConfig.chainId), // Disable cache on local networks (hardhat / anvil)
fetchSystemCalls,
initialRecords,
},
});
}
const db = createDatabase();
const storeCache = createDatabaseClient(db, storeConfig);
const { txReduced$ } = applyNetworkUpdates(
world,
components,
ecsEvents$,
mappings,
ack$,
syncStoreCache ? storeConfig : undefined,
syncStoreCache ? storeCache : undefined
);
const encoders = networkConfig.encoders
? createEncoders(world, ComponentsRegistry, signerOrProvider)
: new Promise((resolve) => resolve({}));
return {
txQueue,
txReduced$,
encoders,
network,
startSync,
gasPriceInput$,
ecsEvent$: ecsEvents$.pipe(concatMap((updates) => from(updates))),
mappings,
registerComponent,
networkConfig,
world,
components,
singletonEntityId: SingletonID,
singletonEntity,
playerEntity,
storeCache,
};
}