@silvana-one/mina-prover 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +1 -0
  3. package/dist/node/api/api.d.ts +211 -0
  4. package/dist/node/api/api.js +472 -0
  5. package/dist/node/api/api.js.map +1 -0
  6. package/dist/node/index.cjs +1161 -0
  7. package/dist/node/index.d.ts +4 -0
  8. package/dist/node/index.js +5 -0
  9. package/dist/node/index.js.map +1 -0
  10. package/dist/node/local/local.d.ts +292 -0
  11. package/dist/node/local/local.js +528 -0
  12. package/dist/node/local/local.js.map +1 -0
  13. package/dist/node/tokens/index.d.ts +2 -0
  14. package/dist/node/tokens/index.js +3 -0
  15. package/dist/node/tokens/index.js.map +1 -0
  16. package/dist/node/tokens/nft.d.ts +29 -0
  17. package/dist/node/tokens/nft.js +107 -0
  18. package/dist/node/tokens/nft.js.map +1 -0
  19. package/dist/node/tokens/token.d.ts +29 -0
  20. package/dist/node/tokens/token.js +99 -0
  21. package/dist/node/tokens/token.js.map +1 -0
  22. package/dist/node/verification/index.d.ts +1 -0
  23. package/dist/node/verification/index.js +2 -0
  24. package/dist/node/verification/index.js.map +1 -0
  25. package/dist/node/verification/verification.d.ts +21 -0
  26. package/dist/node/verification/verification.js +2 -0
  27. package/dist/node/verification/verification.js.map +1 -0
  28. package/dist/tsconfig.tsbuildinfo +1 -0
  29. package/dist/tsconfig.web.tsbuildinfo +1 -0
  30. package/dist/web/api/api.d.ts +211 -0
  31. package/dist/web/api/api.js +472 -0
  32. package/dist/web/api/api.js.map +1 -0
  33. package/dist/web/index.d.ts +4 -0
  34. package/dist/web/index.js +5 -0
  35. package/dist/web/index.js.map +1 -0
  36. package/dist/web/local/local.d.ts +292 -0
  37. package/dist/web/local/local.js +528 -0
  38. package/dist/web/local/local.js.map +1 -0
  39. package/dist/web/tokens/index.d.ts +2 -0
  40. package/dist/web/tokens/index.js +3 -0
  41. package/dist/web/tokens/index.js.map +1 -0
  42. package/dist/web/tokens/nft.d.ts +29 -0
  43. package/dist/web/tokens/nft.js +107 -0
  44. package/dist/web/tokens/nft.js.map +1 -0
  45. package/dist/web/tokens/token.d.ts +29 -0
  46. package/dist/web/tokens/token.js +99 -0
  47. package/dist/web/tokens/token.js.map +1 -0
  48. package/dist/web/verification/index.d.ts +1 -0
  49. package/dist/web/verification/index.js +2 -0
  50. package/dist/web/verification/index.js.map +1 -0
  51. package/dist/web/verification/verification.d.ts +21 -0
  52. package/dist/web/verification/verification.js +2 -0
  53. package/dist/web/verification/verification.js.map +1 -0
  54. package/package.json +68 -0
  55. package/src/api/api.ts +613 -0
  56. package/src/index.ts +4 -0
  57. package/src/local/local.ts +651 -0
  58. package/src/tokens/index.ts +2 -0
  59. package/src/tokens/nft.ts +147 -0
  60. package/src/tokens/token.ts +140 -0
  61. package/src/verification/index.ts +1 -0
  62. package/src/verification/verification.ts +23 -0
package/src/api/api.ts ADDED
@@ -0,0 +1,613 @@
1
+ import chalk from "chalk";
2
+ import { sleep } from "@silvana-one/mina-utils";
3
+ import { LocalCloud, LocalStorage } from "../local/local.js";
4
+ import {
5
+ zkCloudWorker,
6
+ Cloud,
7
+ JobData,
8
+ config,
9
+ blockchain,
10
+ } from "@silvana-one/prover";
11
+ const { ZKCLOUDWORKER_AUTH, ZKCLOUDWORKER_API } = config;
12
+
13
+ /**
14
+ * The APICommand type for interacting with the zkCloudWorker
15
+ * @typedef { "recursiveProof" | "execute" | "sendTransactions" | "jobResult" | "deploy" | "getBalance" | "queryBilling" } ApiCommand
16
+ * @property recursiveProof The command for the recursiveProof calculation
17
+ * @property execute The command for the execute function call (sync or async)
18
+ * @property sendTransactions The command for sending transactions to the cloud
19
+ * @property jobResult The command for getting the result of the job
20
+ * @property deploy The command for deploying the code to the cloud, it is recommended use CLI tools for deployment
21
+ * @property getBalance The command for getting the balance of the user's account with zkCloudWorker
22
+ * @property queryBilling The command for getting the billing report of the user's account with zkCloudWorker
23
+ */
24
+ export type ApiCommand =
25
+ | "recursiveProof"
26
+ | "execute"
27
+ | "sendTransactions"
28
+ | "jobResult"
29
+ | "deploy"
30
+ | "getBalance"
31
+ | "queryBilling";
32
+
33
+ /**
34
+ * API class for interacting with the zkCloudWorker
35
+ * @property jwt The jwt token for authentication, get it at https://t.me/minanft_bot?start=auth
36
+ * @property endpoint The endpoint of the serverless api
37
+ * @property chain The blockchain network to use
38
+ * @property webhook The webhook for the serverless api to get the results
39
+ * @property localWorker The local worker for the serverless api to test the code locally
40
+ */
41
+ export class zkCloudWorkerClient {
42
+ readonly jwt: string;
43
+ readonly endpoint?: string;
44
+ readonly chain: blockchain;
45
+ readonly webhook?: string;
46
+ readonly localWorker?: (cloud: Cloud) => Promise<zkCloudWorker>;
47
+
48
+ /**
49
+ * Constructor for the API class
50
+ * @param params the parameters for the API class
51
+ * @param params.jwt The jwt token for authentication, get it at https://t.me/minanft_bot?start=auth
52
+ * @param params.zkcloudworker The local worker for the serverless api to test the code locally
53
+ * @param params.chain The blockchain network to use
54
+ * @param params.webhook The webhook for the serverless api to get the results
55
+ */
56
+ constructor(params: {
57
+ jwt: string;
58
+ zkcloudworker?: (cloud: Cloud) => Promise<zkCloudWorker>;
59
+ chain?: blockchain;
60
+ webhook?: string;
61
+ }) {
62
+ const { jwt, zkcloudworker, webhook } = params;
63
+ this.jwt = jwt;
64
+
65
+ const chain = params.chain ?? "devnet";
66
+ this.chain = chain;
67
+ this.endpoint =
68
+ chain === "devnet" || chain === "zeko" || chain === "mainnet"
69
+ ? ZKCLOUDWORKER_API + chain
70
+ : undefined;
71
+ this.webhook = webhook;
72
+ if (jwt === "local") {
73
+ if (zkcloudworker === undefined)
74
+ throw new Error("worker is required for local mode");
75
+ this.localWorker = zkcloudworker;
76
+ }
77
+ }
78
+
79
+ /**
80
+ * Starts a new job for the proof calculation using serverless api call
81
+ * @param data the data for the proof call
82
+ * @param data.developer the developer
83
+ * @param data.repo the repo to use
84
+ * @param data.transactions the transactions
85
+ * @param data.task the task of the job
86
+ * @param data.userId the userId of the job
87
+ * @param data.args the arguments of the job, should be serialized JSON or string
88
+ * @param data.metadata the metadata of the job, should be serialized JSON or string
89
+ * @param data.webhook the webhook for the job
90
+ * @returns { success: boolean, error?: string, jobId?: string }
91
+ * where jonId is the jobId of the job
92
+ *
93
+ * The developers repo should provide a zkcloudworker function
94
+ * that can be called with the given parameters, see the examples
95
+ */
96
+ public async recursiveProof(data: {
97
+ developer: string;
98
+ repo: string;
99
+ transactions: string[];
100
+ task?: string;
101
+ userId?: string;
102
+ args?: string;
103
+ metadata?: string;
104
+ webhook?: string;
105
+ }): Promise<{
106
+ success: boolean;
107
+ error?: string;
108
+ jobId?: string;
109
+ }> {
110
+ const result = await this.apiHub("recursiveProof", data);
111
+ if (
112
+ result.data === "error" ||
113
+ (typeof result.data === "string" && result.data.startsWith("error"))
114
+ )
115
+ return {
116
+ success: false,
117
+ error: result.error,
118
+ };
119
+ else if (result.success === false || result.data?.success === false)
120
+ return {
121
+ success: false,
122
+ error:
123
+ result.error ?? result.data?.error ?? "recursiveProof call failed",
124
+ };
125
+ else if (
126
+ result.success === true &&
127
+ result.data?.success === true &&
128
+ result.data?.jobId !== undefined
129
+ )
130
+ return {
131
+ success: result.success,
132
+ jobId: result.data.jobId,
133
+ error: result.error,
134
+ };
135
+ else
136
+ return {
137
+ success: false,
138
+ error: "recursiveProof call error",
139
+ };
140
+ }
141
+
142
+ /**
143
+ * Starts a new job for the function call using serverless api call
144
+ * @param data the data for the proof call
145
+ * @param data.developer the developer
146
+ * @param data.repo the repo to use
147
+ * @param data.transactions the transactions
148
+ * @param data.task the task of the job
149
+ * @param data.userId the userId of the job
150
+ * @param data.args the arguments of the job
151
+ * @param data.metadata the metadata of the job
152
+ * @param data.mode the mode of the job execution: "sync" will not create a job, it will execute the function synchronously within 30 seconds and with the memory limit of 256 MB
153
+ * @returns { success: boolean, error?: string, jobId?: string, result?: any }
154
+ * where jonId is the jobId of the job (for async calls), result is the result of the job (for sync calls)
155
+ */
156
+ public async execute(data: {
157
+ developer: string;
158
+ repo: string;
159
+ transactions: string[];
160
+ task: string;
161
+ userId?: string;
162
+ args?: string;
163
+ metadata?: string;
164
+ mode?: string;
165
+ }): Promise<{
166
+ success: boolean;
167
+ error?: string;
168
+ jobId?: string;
169
+ result?: any;
170
+ }> {
171
+ const result = await this.apiHub("execute", data);
172
+ if (
173
+ result.data === "error" ||
174
+ (typeof result.data === "string" && result.data.startsWith("error"))
175
+ )
176
+ return {
177
+ success: false,
178
+ error: result.error,
179
+ };
180
+ else if (result.success === false || result.data?.success === false)
181
+ return {
182
+ success: false,
183
+ error: result.error ?? result.data?.error ?? "execute call failed",
184
+ };
185
+ else if (
186
+ result.success === true &&
187
+ data.mode === "sync" &&
188
+ result.data !== undefined
189
+ )
190
+ return {
191
+ success: result.success,
192
+ jobId: undefined,
193
+ result: result.data,
194
+ error: result.error,
195
+ };
196
+ else if (
197
+ result.success === true &&
198
+ data.mode !== "sync" &&
199
+ result.data?.success === true &&
200
+ result.data?.jobId !== undefined
201
+ )
202
+ return {
203
+ success: result.success,
204
+ jobId: result.data.jobId,
205
+ result: undefined,
206
+ error: result.error,
207
+ };
208
+ else
209
+ return {
210
+ success: false,
211
+ error: "execute call error",
212
+ };
213
+ }
214
+
215
+ /**
216
+ * Sends transactions to the blockchain using serverless api call
217
+ * @param data the data for the proof call
218
+ * @param data.developer the developer
219
+ * @param data.repo the repo to use
220
+ * @param data.transactions the transactions
221
+ * @returns { success: boolean, error?: string, txId?: string[] }
222
+ * where txId is the transaction id of the transaction, in the sequence of the input transactions
223
+ */
224
+ public async sendTransactions(data: {
225
+ developer: string;
226
+ repo: string;
227
+ transactions: string[];
228
+ }): Promise<{
229
+ success: boolean;
230
+ error?: string;
231
+ txId?: string[];
232
+ }> {
233
+ const result = await this.apiHub("sendTransactions", data);
234
+ if (result.data === "error")
235
+ // TODO: check if this is correct in AWS code
236
+ return {
237
+ success: false,
238
+ error: result.error,
239
+ };
240
+ else
241
+ return {
242
+ success: result.success,
243
+ txId: result.data,
244
+ error: result.error,
245
+ };
246
+ }
247
+
248
+ /**
249
+ * Gets the result of the job using serverless api call
250
+ * @param data the data for the jobResult call
251
+ * @param data.jobId the jobId of the job
252
+ * @param data.includeLogs include logs in the result, default is false
253
+ * @returns { success: boolean, error?: string, result?: any }
254
+ * where result is the result of the job
255
+ * if the job is not finished yet, the result will be undefined
256
+ * if the job failed, the result will be undefined and error will be set
257
+ * if the job is finished, the result will be set and error will be undefined
258
+ * if the job is not found, the result will be undefined and error will be set
259
+ */
260
+ public async jobResult(data: {
261
+ jobId: string;
262
+ includeLogs?: boolean;
263
+ }): Promise<
264
+ | {
265
+ success: false;
266
+ error?: string;
267
+ result?: string;
268
+ }
269
+ | {
270
+ success: true;
271
+ error?: string;
272
+ result: JobData;
273
+ }
274
+ > {
275
+ const result = await this.apiHub("jobResult", data);
276
+ if (this.isError(result.data))
277
+ return {
278
+ success: false,
279
+ error: result.error,
280
+ result: result.data,
281
+ };
282
+ else
283
+ return {
284
+ success: result.success,
285
+ error: result.error,
286
+ result: result.success ? (result.data as JobData) : result.data,
287
+ };
288
+ }
289
+
290
+ /**
291
+ * Deploys the code to the cloud using serverless api call
292
+ * @param data the data for the deploy call
293
+ * @param data.repo the repo to use
294
+ * @param data.developer the developer
295
+ * @param data.packageManager the package manager to use
296
+ * @returns { success: boolean, error?: string, jobId?: string}
297
+ * where jobId is the jobId of the job
298
+ */
299
+ public async deploy(data: {
300
+ repo: string;
301
+ developer: string;
302
+ packageManager: string;
303
+ }): Promise<{
304
+ success: boolean;
305
+ error?: string;
306
+ jobId?: string;
307
+ }> {
308
+ // TODO: encrypt env.json
309
+ const { repo, developer, packageManager } = data;
310
+ const result = await this.apiHub("deploy", {
311
+ developer,
312
+ repo,
313
+ args: packageManager,
314
+ });
315
+ if (
316
+ result.data === "error" ||
317
+ (typeof result.data === "string" && result.data.startsWith("error"))
318
+ )
319
+ return {
320
+ success: false,
321
+ error: result.error,
322
+ };
323
+ else
324
+ return {
325
+ success: result.success && result.data?.success,
326
+ jobId: result.data?.jobId,
327
+ error: result.error,
328
+ };
329
+ }
330
+
331
+ /**
332
+ * Gets the billing report for the jobs sent using JWT
333
+ * @returns { success: boolean, error?: string, result?: any }
334
+ * where result is the billing report
335
+ */
336
+ public async queryBilling(): Promise<{
337
+ success: boolean;
338
+ error?: string;
339
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
340
+ result?: any;
341
+ }> {
342
+ const result = await this.apiHub("queryBilling", {});
343
+ if (this.isError(result.data))
344
+ return {
345
+ success: false,
346
+ error: result.error,
347
+ result: result.data,
348
+ };
349
+ else
350
+ return {
351
+ success: result.success,
352
+ error: result.error,
353
+ result: result.data,
354
+ };
355
+ }
356
+
357
+ /**
358
+ * Gets the remaining balance
359
+ * @returns { success: boolean, error?: string, result?: any }
360
+ * where result is the balance
361
+ */
362
+ public async getBalance(): Promise<{
363
+ success: boolean;
364
+ error?: string;
365
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
366
+ result?: any;
367
+ }> {
368
+ const result = await this.apiHub("getBalance", {});
369
+ if (this.isError(result.data))
370
+ return {
371
+ success: false,
372
+ error: result.error,
373
+ result: result.data,
374
+ };
375
+ else
376
+ return {
377
+ success: result.success,
378
+ error: result.error,
379
+ result: result.data,
380
+ };
381
+ }
382
+
383
+ /**
384
+ * Waits for the job to finish
385
+ * @param data the data for the waitForJobResult call
386
+ * @param data.jobId the jobId of the job
387
+ * @param data.maxAttempts the maximum number of attempts, default is 360 (2 hours)
388
+ * @param data.interval the interval between attempts, default is 20000 (20 seconds)
389
+ * @param data.maxErrors the maximum number of network errors, default is 10
390
+ * @param data.printLogs print logs, default is true
391
+ * @returns { success: boolean, error?: string, result?: any }
392
+ * where result is the result of the job
393
+ */
394
+ public async waitForJobResult(data: {
395
+ jobId: string;
396
+ maxAttempts?: number;
397
+ interval?: number;
398
+ maxErrors?: number;
399
+ printLogs?: boolean; // print logs, default is true
400
+ }): Promise<{
401
+ success: boolean;
402
+ error?: string;
403
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
404
+ result?: any;
405
+ }> {
406
+ if (this.jwt === "local") return this.jobResult({ jobId: data.jobId });
407
+ const maxAttempts = data?.maxAttempts ?? 360; // 1 hour
408
+ const interval = data?.interval ?? 10000;
409
+ const maxErrors = data?.maxErrors ?? 10;
410
+ const errorDelay = 30000; // 30 seconds
411
+ const printedLogs: string[] = [];
412
+ const printLogs: boolean = data.printLogs ?? true;
413
+
414
+ function print(logs: string[]) {
415
+ logs.forEach((log) => {
416
+ if (printedLogs.includes(log) === false) {
417
+ printedLogs.push(log);
418
+ if (printLogs) {
419
+ // replace all occurrences of "error" with red color
420
+ const text = log.replace(/error/gi, (matched) =>
421
+ chalk.red(matched)
422
+ );
423
+ console.log(text);
424
+ }
425
+ }
426
+ });
427
+ }
428
+ let attempts = 0;
429
+ let errors = 0;
430
+ while (attempts < maxAttempts) {
431
+ const result = await this.apiHub("jobResult", {
432
+ jobId: data.jobId,
433
+ includeLogs: printLogs,
434
+ });
435
+ const isAllLogsFetched =
436
+ result?.data?.isFullLog === true || printLogs === false;
437
+ if (
438
+ printLogs === true &&
439
+ result?.data?.logs !== undefined &&
440
+ result?.data?.logs !== null &&
441
+ Array.isArray(result.data.logs) === true
442
+ )
443
+ print(result.data.logs);
444
+ if (result.success === false) {
445
+ errors++;
446
+ if (errors > maxErrors) {
447
+ return {
448
+ success: false,
449
+ error: "Too many network errors",
450
+ result: undefined,
451
+ };
452
+ }
453
+ await sleep(errorDelay * errors);
454
+ } else {
455
+ if (this.isError(result.data) && isAllLogsFetched)
456
+ return {
457
+ success: false,
458
+ error: result.error,
459
+ result: result.data,
460
+ };
461
+ else if (result.data?.result !== undefined && isAllLogsFetched) {
462
+ return {
463
+ success: result.success,
464
+ error: result.error,
465
+ result: result.data,
466
+ };
467
+ } else if (result.data?.jobStatus === "failed" && isAllLogsFetched) {
468
+ return {
469
+ success: false,
470
+ error: "Job failed",
471
+ result: result.data,
472
+ };
473
+ }
474
+ await sleep(interval);
475
+ }
476
+ attempts++;
477
+ }
478
+ return {
479
+ success: false,
480
+ error: "Timeout",
481
+ result: undefined,
482
+ };
483
+ }
484
+
485
+ /**
486
+ * Calls the serverless API
487
+ * @param command the command of the API
488
+ * @param data the data of the API
489
+ * */
490
+ private async apiHub(
491
+ command: ApiCommand,
492
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
493
+ data: any
494
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
495
+ ): Promise<{ success: boolean; data?: any; error?: any }> {
496
+ if (this.jwt === "local") {
497
+ if (this.localWorker === undefined)
498
+ throw new Error("localWorker is undefined");
499
+
500
+ switch (command) {
501
+ case "recursiveProof": {
502
+ const jobId = await LocalCloud.run({
503
+ command: "recursiveProof",
504
+ data,
505
+ chain: this.chain,
506
+ localWorker: this.localWorker,
507
+ });
508
+ return {
509
+ success: true,
510
+ data: { success: true, jobId },
511
+ };
512
+ }
513
+ case "execute": {
514
+ const jobId = await LocalCloud.run({
515
+ command: "execute",
516
+ data,
517
+ chain: this.chain,
518
+ localWorker: this.localWorker,
519
+ });
520
+ if (data.mode === "sync")
521
+ return {
522
+ success: true,
523
+ data: LocalStorage.jobEvents[jobId].result,
524
+ };
525
+ else
526
+ return {
527
+ success: true,
528
+ data: { success: true, jobId },
529
+ };
530
+ }
531
+ case "jobResult": {
532
+ const job = LocalStorage.jobs[data.jobId];
533
+ if (job === undefined) {
534
+ return {
535
+ success: false,
536
+ error: "local job not found",
537
+ };
538
+ } else {
539
+ return {
540
+ success: true,
541
+ data: job,
542
+ };
543
+ }
544
+ }
545
+ case "sendTransactions": {
546
+ return {
547
+ success: true,
548
+ data: await LocalCloud.addTransactions(data.transactions),
549
+ };
550
+ }
551
+ case "deploy":
552
+ return {
553
+ success: true,
554
+ data: "local_deploy",
555
+ };
556
+ case "queryBilling":
557
+ return {
558
+ success: true,
559
+ data: "local_queryBilling",
560
+ };
561
+ default:
562
+ return {
563
+ success: false,
564
+ error: "local_error",
565
+ };
566
+ }
567
+ } else {
568
+ if (this.endpoint === undefined)
569
+ throw new Error(
570
+ "zkCloudWorker supports only mainnet, devnet and zeko chains in the cloud."
571
+ );
572
+ const apiData = {
573
+ auth: ZKCLOUDWORKER_AUTH,
574
+ command: command,
575
+ jwtToken: this.jwt,
576
+ data: data,
577
+ chain: this.chain,
578
+ webhook: this.webhook, // TODO: implement webhook code on AWS
579
+ };
580
+
581
+ try {
582
+ const response = await fetch(this.endpoint, {
583
+ method: "POST",
584
+ headers: {
585
+ "Content-Type": "application/json",
586
+ },
587
+ body: JSON.stringify(apiData),
588
+ });
589
+ if (!response.ok) {
590
+ return {
591
+ success: false,
592
+ error: `fetch error: ${response.statusText} status: ${response.status}`,
593
+ };
594
+ }
595
+ const data = await response.json();
596
+ return { success: true, data: data };
597
+ } catch (error: any) {
598
+ console.error("apiHub error:", error.message ?? error);
599
+ return { success: false, error: error };
600
+ }
601
+ }
602
+ }
603
+
604
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
605
+ private isError(data: any): boolean {
606
+ if (data === "error") return true;
607
+ if (data?.jobStatus === "failed") return true;
608
+ if (typeof data === "string" && data.toLowerCase().startsWith("error"))
609
+ return true;
610
+ if (data !== undefined && data.error !== undefined) return true;
611
+ return false;
612
+ }
613
+ }
package/src/index.ts ADDED
@@ -0,0 +1,4 @@
1
+ export * from "./api/api.js";
2
+ export * from "./local/local.js";
3
+ export * from "./verification/index.js";
4
+ export * from "./tokens/index.js";