This repository has been archived by the owner on Feb 26, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
DashProvider.tsx
278 lines (248 loc) · 8.34 KB
/
DashProvider.tsx
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
import { useReducer, useEffect, useRef, useMemo, useCallback } from "react";
import { useAccount, useNetwork } from "wagmi";
import { sha1 } from "object-hash";
import type { ReceivedMessageLifecycle } from "@truffle/dashboard-message-bus-client";
import {
isCliEventMessage,
isLogMessage,
isDebugMessage
} from "@truffle/dashboard-message-bus-common";
import type {
Message,
DashboardProviderMessage
} from "@truffle/dashboard-message-bus-common";
import { forProject } from "@truffle/decoder";
import type {
Compilation,
WorkflowCompileResult
} from "@truffle/compile-common";
import { DashContext, reducer, initialState } from "src/contexts/DashContext";
import type { State } from "src/contexts/DashContext";
import {
confirmMessage,
rejectMessage,
getChainNameByID
} from "src/utils/dash";
const ARBITRARY_DB_MAX_BYTES = 500_000_000;
const ARBITRARY_DB_MAX_PERCENT = 0.8;
type DashProviderProps = {
children: React.ReactNode;
};
function DashProvider({ children }: DashProviderProps): JSX.Element {
const { isConnected } = useAccount();
const { chain } = useNetwork();
const [state, dispatch] = useReducer(reducer, initialState);
const initCalled = useRef(false);
const stateRef = useRef<State>(state);
stateRef.current = state;
console.debug({ state });
const dbHelper = useMemo(
() => ({
dbPromise: stateRef.current.dbPromise,
async has(hash: string) {
return !!(await (await this.dbPromise).getKey("Compilation", hash));
},
async insert(hash: string, compilation: Compilation) {
(await this.dbPromise).put("Compilation", {
dataHash: hash,
data: compilation,
timeAdded: Date.now()
});
},
async canInsert() {
const { usage, quota } = await navigator.storage.estimate();
if (usage && quota) {
return (
usage / quota < ARBITRARY_DB_MAX_PERCENT &&
usage < ARBITRARY_DB_MAX_BYTES
);
}
},
async prune() {
if (await this.canInsert()) return;
const dbProxy = await this.dbPromise;
const transaction = dbProxy.transaction("Compilation", "readwrite");
const index = transaction.store.index("TimeAdded");
for await (const cursor of index.iterate(null, "next")) {
await cursor.delete();
if (await this.canInsert()) {
break;
}
}
}
}),
[]
);
const handleWorkflowCompileResult = useCallback(
async (data: WorkflowCompileResult) => {
const { compilations } = data;
if (compilations.length === 0 || !stateRef.current.decoder) return;
let decoderNeedsUpdate = false;
const decoderCompilations = [...stateRef.current.decoderCompilations!];
const decoderCompilationHashes = new Set(
stateRef.current.decoderCompilationHashes
);
// Iterate over incoming compilations and determine if they are useful to
// in-memory decoder or db.
// Do not try to optimize by:
// - Batch inserting.
// - Mirroring some kind of db state.
for (const compilation of compilations) {
const hash = sha1(compilation);
// If the in-memory decoder doesn't have this compilation,
// save it for decoder re-init after this for-loop ends.
const isNewToDecoder =
!stateRef.current.decoderCompilationHashes!.has(hash) &&
!decoderCompilationHashes.has(hash);
if (isNewToDecoder) {
decoderCompilations.push(compilation);
decoderCompilationHashes.add(hash);
decoderNeedsUpdate = true;
}
// If db doesn't have this compilation,
// delete old compilations (if necessary) and insert.
const isNewToDb = !(await dbHelper.has(hash));
if (isNewToDb) {
await dbHelper.prune();
try {
await dbHelper.insert(hash, compilation);
} catch (err) {
console.error(err);
}
}
}
if (decoderNeedsUpdate) {
const decoder = await forProject({
projectInfo: { commonCompilations: decoderCompilations },
// @ts-ignore
provider: window.ethereum
});
dispatch({
type: "set-decoder",
data: {
decoder,
decoderCompilations,
decoderCompilationHashes
}
});
}
},
[dbHelper]
);
useEffect(() => {
// This obviates the need for a cleanup callback
if (initCalled.current) return;
initCalled.current = true;
const initBusClient = async () => {
const { busClient } = state;
await busClient.ready();
const { host, port } = busClient.options;
console.debug(`Connected to message bus at ws://${host}:${port}`);
// Message bus client subscribes to and handles messages
const subscription = busClient.subscribe({});
const messageHandler = async (
lifecycle: ReceivedMessageLifecycle<Message>
) => {
const { message } = lifecycle;
if (isCliEventMessage(message)) {
console.debug("Received cli-event message", message);
if (message.payload.label === "workflow-compile-result") {
// Handle compilations separately because:
// a) Db operations are async
// b) Avoid duplicate work (e.g. loop, hash)
handleWorkflowCompileResult(message.payload.data);
}
} else if (isLogMessage(message)) {
// Log messages do not alter state, not sending to reducer
console.debug(`Received log message`, message);
lifecycle.respond({ payload: undefined });
} else if (isDebugMessage(message)) {
// Debug messages do not alter state, not sending to reducer
console.debug("Received debug message", message);
lifecycle.respond({ payload: undefined });
} else {
// Other messages do alter state
dispatch({
type: "handle-message",
data: lifecycle
});
}
};
subscription.on("message", messageHandler);
};
const initDecoder = async () => {
const { dbPromise } = state;
const compilationStore = await (await dbPromise).getAll("Compilation");
console.debug(`Compilation store`, compilationStore);
const decoderCompilations: State["decoderCompilations"] = new Array(
compilationStore.length
);
const decoderCompilationHashes: State["decoderCompilationHashes"] =
new Set();
compilationStore.forEach((row, index) => {
decoderCompilations[index] = row.data;
decoderCompilationHashes.add(row.dataHash);
});
const decoder = await forProject({
projectInfo: { commonCompilations: decoderCompilations },
// @ts-ignore
provider: window.ethereum
});
dispatch({
type: "set-decoder",
data: {
decoder,
decoderCompilations,
decoderCompilationHashes
}
});
};
const init = async () => {
await initDecoder();
await initBusClient();
};
init();
}, [state, handleWorkflowCompileResult]);
useEffect(() => {
const updateChainInfo = () => {
const data: State["chainInfo"] = { id: null, name: null };
if (chain) {
const { id, name } = chain;
let updated;
if (name === `Chain ${id}`) {
updated = getChainNameByID(id);
}
data.id = id;
data.name = updated ?? name;
dispatch({
type: "set-notice",
data: { show: true, type: "CONFIRM_CHAIN" }
});
}
dispatch({ type: "set-chain-info", data });
};
updateChainInfo();
}, [chain]);
useEffect(() => {
dispatch({
type: "set-notice",
data: { show: !isConnected, type: "CONNECT" }
});
}, [isConnected]);
const operations = {
userConfirmMessage: (
lifecycle: ReceivedMessageLifecycle<DashboardProviderMessage>
) => confirmMessage(lifecycle),
userRejectMessage: (
lifecycle: ReceivedMessageLifecycle<DashboardProviderMessage>
) => void rejectMessage(lifecycle, "USER"),
toggleNotice: () =>
void dispatch({ type: "set-notice", data: { show: !state.notice.show } })
};
return (
<DashContext.Provider value={{ state, operations }}>
{children}
</DashContext.Provider>
);
}
export default DashProvider;