/
zkappWorker.ts
88 lines (75 loc) · 2.48 KB
/
zkappWorker.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
import { Mina, PublicKey, fetchAccount } from 'o1js';
type Transaction = Awaited<ReturnType<typeof Mina.transaction>>;
// ---------------------------------------------------------------------------------------
import type { Add } from '../../../contracts/src/Add';
const state = {
Add: null as null | typeof Add,
zkapp: null as null | Add,
transaction: null as null | Transaction,
};
// ---------------------------------------------------------------------------------------
const functions = {
setActiveInstanceToDevnet: async (args: {}) => {
const Network = Mina.Network(
'https://api.minascan.io/node/devnet/v1/graphql'
);
console.log('Devnet network instance configured.');
Mina.setActiveInstance(Network);
},
loadContract: async (args: {}) => {
const { Add } = await import('../../../contracts/build/src/Add.js');
state.Add = Add;
},
compileContract: async (args: {}) => {
await state.Add!.compile();
},
fetchAccount: async (args: { publicKey58: string }) => {
const publicKey = PublicKey.fromBase58(args.publicKey58);
return await fetchAccount({ publicKey });
},
initZkappInstance: async (args: { publicKey58: string }) => {
const publicKey = PublicKey.fromBase58(args.publicKey58);
state.zkapp = new state.Add!(publicKey);
},
getNum: async (args: {}) => {
const currentNum = await state.zkapp!.num.get();
return JSON.stringify(currentNum.toJSON());
},
createUpdateTransaction: async (args: {}) => {
const transaction = await Mina.transaction(async () => {
await state.zkapp!.update();
});
state.transaction = transaction;
},
proveUpdateTransaction: async (args: {}) => {
await state.transaction!.prove();
},
getTransactionJSON: async (args: {}) => {
return state.transaction!.toJSON();
},
};
// ---------------------------------------------------------------------------------------
export type WorkerFunctions = keyof typeof functions;
export type ZkappWorkerRequest = {
id: number;
fn: WorkerFunctions;
args: any;
};
export type ZkappWorkerReponse = {
id: number;
data: any;
};
if (typeof window !== 'undefined') {
addEventListener(
'message',
async (event: MessageEvent<ZkappWorkerRequest>) => {
const returnData = await functions[event.data.fn](event.data.args);
const message: ZkappWorkerReponse = {
id: event.data.id,
data: returnData,
};
postMessage(message);
}
);
}
console.log('Web Worker Successfully Initialized.');