@proto-kit/common 0.1.1-develop.211 → 0.1.1-develop.2137

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 (258) hide show
  1. package/dist/cache/CacheManifest.d.ts +11 -0
  2. package/dist/cache/CacheManifest.d.ts.map +1 -0
  3. package/dist/cache/CacheManifest.js +56 -0
  4. package/dist/cache/CacheManifest.js.map +1 -0
  5. package/dist/cache/ProxyCache.d.ts +13 -0
  6. package/dist/cache/ProxyCache.d.ts.map +1 -0
  7. package/dist/cache/ProxyCache.js +24 -0
  8. package/dist/cache/ProxyCache.js.map +1 -0
  9. package/dist/cache/RemoteCache.d.ts +8 -0
  10. package/dist/cache/RemoteCache.d.ts.map +1 -0
  11. package/dist/cache/RemoteCache.js +2 -0
  12. package/dist/cache/RemoteCache.js.map +1 -0
  13. package/dist/cache/RemoteCacheCompiler.d.ts +16 -0
  14. package/dist/cache/RemoteCacheCompiler.d.ts.map +1 -0
  15. package/dist/cache/RemoteCacheCompiler.js +104 -0
  16. package/dist/cache/RemoteCacheCompiler.js.map +1 -0
  17. package/dist/compiling/AtomicCompileHelper.d.ts +15 -0
  18. package/dist/compiling/AtomicCompileHelper.d.ts.map +1 -0
  19. package/dist/compiling/AtomicCompileHelper.js +61 -0
  20. package/dist/compiling/AtomicCompileHelper.js.map +1 -0
  21. package/dist/compiling/CompilableModule.d.ts +6 -0
  22. package/dist/compiling/CompilableModule.d.ts.map +1 -0
  23. package/dist/compiling/CompilableModule.js +2 -0
  24. package/dist/compiling/CompilableModule.js.map +1 -0
  25. package/dist/compiling/CompileRegistry.d.ts +25 -0
  26. package/dist/compiling/CompileRegistry.d.ts.map +1 -0
  27. package/dist/compiling/CompileRegistry.js +62 -0
  28. package/dist/compiling/CompileRegistry.js.map +1 -0
  29. package/dist/compiling/services/ChildVerificationKeyService.d.ts +10 -0
  30. package/dist/compiling/services/ChildVerificationKeyService.d.ts.map +1 -0
  31. package/dist/compiling/services/ChildVerificationKeyService.js +27 -0
  32. package/dist/compiling/services/ChildVerificationKeyService.js.map +1 -0
  33. package/dist/config/ChildContainerCreatable.d.ts +5 -0
  34. package/dist/config/ChildContainerCreatable.d.ts.map +1 -0
  35. package/dist/config/ChildContainerCreatable.js +2 -0
  36. package/dist/config/ChildContainerCreatable.js.map +1 -0
  37. package/dist/config/ChildContainerProvider.d.ts +5 -0
  38. package/dist/config/ChildContainerProvider.d.ts.map +1 -0
  39. package/dist/config/ChildContainerProvider.js +2 -0
  40. package/dist/config/ChildContainerProvider.js.map +1 -0
  41. package/dist/config/ConfigurableModule.d.ts +6 -2
  42. package/dist/config/ConfigurableModule.d.ts.map +1 -1
  43. package/dist/config/ConfigurableModule.js +5 -0
  44. package/dist/config/ConfigurableModule.js.map +1 -0
  45. package/dist/config/ModuleContainer.d.ts +70 -23
  46. package/dist/config/ModuleContainer.d.ts.map +1 -1
  47. package/dist/config/ModuleContainer.js +164 -31
  48. package/dist/config/ModuleContainer.js.map +1 -0
  49. package/dist/config/Startable.d.ts +4 -0
  50. package/dist/config/Startable.d.ts.map +1 -0
  51. package/dist/config/Startable.js +2 -0
  52. package/dist/config/Startable.js.map +1 -0
  53. package/dist/config/injectAlias.d.ts +18 -0
  54. package/dist/config/injectAlias.d.ts.map +1 -0
  55. package/dist/config/injectAlias.js +47 -0
  56. package/dist/config/injectAlias.js.map +1 -0
  57. package/dist/dependencyFactory/DependencyFactory.d.ts +14 -9
  58. package/dist/dependencyFactory/DependencyFactory.d.ts.map +1 -1
  59. package/dist/dependencyFactory/DependencyFactory.js +2 -96
  60. package/dist/dependencyFactory/DependencyFactory.js.map +1 -0
  61. package/dist/dependencyFactory/injectOptional.d.ts +16 -0
  62. package/dist/dependencyFactory/injectOptional.d.ts.map +1 -0
  63. package/dist/dependencyFactory/injectOptional.js +40 -0
  64. package/dist/dependencyFactory/injectOptional.js.map +1 -0
  65. package/dist/dummyVerificationKey.d.ts +3 -0
  66. package/dist/dummyVerificationKey.d.ts.map +1 -0
  67. package/dist/dummyVerificationKey.js +8 -0
  68. package/dist/dummyVerificationKey.js.map +1 -0
  69. package/dist/events/EventEmitter.d.ts +19 -0
  70. package/dist/events/EventEmitter.d.ts.map +1 -0
  71. package/dist/events/EventEmitter.js +35 -0
  72. package/dist/events/EventEmitter.js.map +1 -0
  73. package/dist/events/EventEmitterProxy.d.ts +18 -0
  74. package/dist/events/EventEmitterProxy.d.ts.map +1 -0
  75. package/dist/events/EventEmitterProxy.js +35 -0
  76. package/dist/events/EventEmitterProxy.js.map +1 -0
  77. package/dist/events/EventEmittingComponent.d.ts +9 -0
  78. package/dist/events/EventEmittingComponent.d.ts.map +1 -0
  79. package/dist/events/EventEmittingComponent.js +2 -0
  80. package/dist/events/EventEmittingComponent.js.map +1 -0
  81. package/dist/events/ReplayingSingleUseEventEmitter.d.ts +17 -0
  82. package/dist/events/ReplayingSingleUseEventEmitter.d.ts.map +1 -0
  83. package/dist/events/ReplayingSingleUseEventEmitter.js +34 -0
  84. package/dist/events/ReplayingSingleUseEventEmitter.js.map +1 -0
  85. package/dist/index.d.ts +27 -1
  86. package/dist/index.d.ts.map +1 -1
  87. package/dist/index.js +28 -2
  88. package/dist/index.js.map +1 -0
  89. package/dist/log.d.ts +37 -0
  90. package/dist/log.d.ts.map +1 -0
  91. package/dist/log.js +117 -0
  92. package/dist/log.js.map +1 -0
  93. package/dist/trees/InMemoryLinkedLeafStore.d.ts +21 -0
  94. package/dist/trees/InMemoryLinkedLeafStore.d.ts.map +1 -0
  95. package/dist/trees/InMemoryLinkedLeafStore.js +26 -0
  96. package/dist/trees/InMemoryLinkedLeafStore.js.map +1 -0
  97. package/dist/trees/InMemoryLinkedMerkleLeafStore.d.ts +7 -0
  98. package/dist/trees/InMemoryLinkedMerkleLeafStore.d.ts.map +1 -0
  99. package/dist/trees/InMemoryLinkedMerkleLeafStore.js +6 -0
  100. package/dist/trees/InMemoryLinkedMerkleLeafStore.js.map +1 -0
  101. package/dist/trees/InMemoryMerkleTreeStorage.d.ts +11 -0
  102. package/dist/trees/InMemoryMerkleTreeStorage.d.ts.map +1 -0
  103. package/dist/trees/InMemoryMerkleTreeStorage.js +13 -0
  104. package/dist/trees/InMemoryMerkleTreeStorage.js.map +1 -0
  105. package/dist/trees/LinkedMerkleTree.d.ts +345 -0
  106. package/dist/trees/LinkedMerkleTree.d.ts.map +1 -0
  107. package/dist/trees/LinkedMerkleTree.js +337 -0
  108. package/dist/trees/LinkedMerkleTree.js.map +1 -0
  109. package/dist/trees/LinkedMerkleTreeStore.d.ts +24 -0
  110. package/dist/trees/LinkedMerkleTreeStore.d.ts.map +1 -0
  111. package/dist/trees/LinkedMerkleTreeStore.js +2 -0
  112. package/dist/trees/LinkedMerkleTreeStore.js.map +1 -0
  113. package/dist/trees/MerkleTreeStore.d.ts +5 -0
  114. package/dist/trees/MerkleTreeStore.d.ts.map +1 -0
  115. package/dist/trees/MerkleTreeStore.js +2 -0
  116. package/dist/trees/MerkleTreeStore.js.map +1 -0
  117. package/dist/trees/MockAsyncMerkleStore.d.ts +9 -0
  118. package/dist/trees/MockAsyncMerkleStore.d.ts.map +1 -0
  119. package/dist/trees/MockAsyncMerkleStore.js +20 -0
  120. package/dist/trees/MockAsyncMerkleStore.js.map +1 -0
  121. package/dist/trees/RollupMerkleTree.d.ts +147 -0
  122. package/dist/trees/RollupMerkleTree.d.ts.map +1 -0
  123. package/dist/trees/RollupMerkleTree.js +218 -0
  124. package/dist/trees/RollupMerkleTree.js.map +1 -0
  125. package/dist/trees/VirtualMerkleTreeStore.d.ts +13 -0
  126. package/dist/trees/VirtualMerkleTreeStore.d.ts.map +1 -0
  127. package/dist/trees/VirtualMerkleTreeStore.js +18 -0
  128. package/dist/trees/VirtualMerkleTreeStore.js.map +1 -0
  129. package/dist/trees/lmt/AbstractLinkedMerkleTree.d.ts +288 -0
  130. package/dist/trees/lmt/AbstractLinkedMerkleTree.d.ts.map +1 -0
  131. package/dist/trees/lmt/AbstractLinkedMerkleTree.js +22 -0
  132. package/dist/trees/lmt/AbstractLinkedMerkleTree.js.map +1 -0
  133. package/dist/trees/lmt/InMemoryLinkedLeafStore.d.ts +21 -0
  134. package/dist/trees/lmt/InMemoryLinkedLeafStore.d.ts.map +1 -0
  135. package/dist/trees/lmt/InMemoryLinkedLeafStore.js +26 -0
  136. package/dist/trees/lmt/InMemoryLinkedLeafStore.js.map +1 -0
  137. package/dist/trees/lmt/InMemoryLinkedMerkleLeafStore.d.ts +7 -0
  138. package/dist/trees/lmt/InMemoryLinkedMerkleLeafStore.d.ts.map +1 -0
  139. package/dist/trees/lmt/InMemoryLinkedMerkleLeafStore.js +6 -0
  140. package/dist/trees/lmt/InMemoryLinkedMerkleLeafStore.js.map +1 -0
  141. package/dist/trees/lmt/LinkedLeafStore.d.ts +16 -0
  142. package/dist/trees/lmt/LinkedLeafStore.d.ts.map +1 -0
  143. package/dist/trees/lmt/LinkedLeafStore.js +2 -0
  144. package/dist/trees/lmt/LinkedLeafStore.js.map +1 -0
  145. package/dist/trees/lmt/LinkedLinkedStore.d.ts +16 -0
  146. package/dist/trees/lmt/LinkedLinkedStore.d.ts.map +1 -0
  147. package/dist/trees/lmt/LinkedLinkedStore.js +2 -0
  148. package/dist/trees/lmt/LinkedLinkedStore.js.map +1 -0
  149. package/dist/trees/lmt/LinkedMerkleTree.d.ts +11 -0
  150. package/dist/trees/lmt/LinkedMerkleTree.d.ts.map +1 -0
  151. package/dist/trees/lmt/LinkedMerkleTree.js +241 -0
  152. package/dist/trees/lmt/LinkedMerkleTree.js.map +1 -0
  153. package/dist/trees/lmt/LinkedMerkleTreeCircuitOps.d.ts +113 -0
  154. package/dist/trees/lmt/LinkedMerkleTreeCircuitOps.d.ts.map +1 -0
  155. package/dist/trees/lmt/LinkedMerkleTreeCircuitOps.js +113 -0
  156. package/dist/trees/lmt/LinkedMerkleTreeCircuitOps.js.map +1 -0
  157. package/dist/trees/lmt/LinkedMerkleTreeDatabase.d.ts +7 -0
  158. package/dist/trees/lmt/LinkedMerkleTreeDatabase.d.ts.map +1 -0
  159. package/dist/trees/lmt/LinkedMerkleTreeDatabase.js +2 -0
  160. package/dist/trees/lmt/LinkedMerkleTreeDatabase.js.map +1 -0
  161. package/dist/trees/lmt/LinkedMerkleTreeStore.d.ts +16 -0
  162. package/dist/trees/lmt/LinkedMerkleTreeStore.d.ts.map +1 -0
  163. package/dist/trees/lmt/LinkedMerkleTreeStore.js +2 -0
  164. package/dist/trees/lmt/LinkedMerkleTreeStore.js.map +1 -0
  165. package/dist/trees/lmt/LinkedMerkleTreeTypes.d.ts +74 -0
  166. package/dist/trees/lmt/LinkedMerkleTreeTypes.d.ts.map +1 -0
  167. package/dist/trees/lmt/LinkedMerkleTreeTypes.js +50 -0
  168. package/dist/trees/lmt/LinkedMerkleTreeTypes.js.map +1 -0
  169. package/dist/trees/sparse/InMemoryMerkleTreeStorage.d.ts +11 -0
  170. package/dist/trees/sparse/InMemoryMerkleTreeStorage.d.ts.map +1 -0
  171. package/dist/trees/sparse/InMemoryMerkleTreeStorage.js +13 -0
  172. package/dist/trees/sparse/InMemoryMerkleTreeStorage.js.map +1 -0
  173. package/dist/trees/sparse/MerkleTreeStore.d.ts +5 -0
  174. package/dist/trees/sparse/MerkleTreeStore.d.ts.map +1 -0
  175. package/dist/trees/sparse/MerkleTreeStore.js +2 -0
  176. package/dist/trees/sparse/MerkleTreeStore.js.map +1 -0
  177. package/dist/trees/sparse/MockAsyncMerkleStore.d.ts +9 -0
  178. package/dist/trees/sparse/MockAsyncMerkleStore.d.ts.map +1 -0
  179. package/dist/trees/sparse/MockAsyncMerkleStore.js +20 -0
  180. package/dist/trees/sparse/MockAsyncMerkleStore.js.map +1 -0
  181. package/dist/trees/sparse/RollupMerkleTree.d.ts +158 -0
  182. package/dist/trees/sparse/RollupMerkleTree.d.ts.map +1 -0
  183. package/dist/trees/sparse/RollupMerkleTree.js +330 -0
  184. package/dist/trees/sparse/RollupMerkleTree.js.map +1 -0
  185. package/dist/types.d.ts +62 -0
  186. package/dist/types.d.ts.map +1 -1
  187. package/dist/types.js +14 -1
  188. package/dist/types.js.map +1 -0
  189. package/dist/union/union.d.ts +177 -0
  190. package/dist/union/union.d.ts.map +1 -0
  191. package/dist/union/union.js +35 -0
  192. package/dist/union/union.js.map +1 -0
  193. package/dist/utils.d.ts +57 -2
  194. package/dist/utils.d.ts.map +1 -1
  195. package/dist/utils.js +153 -4
  196. package/dist/utils.js.map +1 -0
  197. package/dist/zkProgrammable/ProvableMethodExecutionContext.d.ts +4 -3
  198. package/dist/zkProgrammable/ProvableMethodExecutionContext.d.ts.map +1 -1
  199. package/dist/zkProgrammable/ProvableMethodExecutionContext.js +2 -3
  200. package/dist/zkProgrammable/ProvableMethodExecutionContext.js.map +1 -0
  201. package/dist/zkProgrammable/ZkProgrammable.d.ts +32 -11
  202. package/dist/zkProgrammable/ZkProgrammable.d.ts.map +1 -1
  203. package/dist/zkProgrammable/ZkProgrammable.js +36 -17
  204. package/dist/zkProgrammable/ZkProgrammable.js.map +1 -0
  205. package/dist/zkProgrammable/provableMethod.d.ts +7 -4
  206. package/dist/zkProgrammable/provableMethod.d.ts.map +1 -1
  207. package/dist/zkProgrammable/provableMethod.js +30 -14
  208. package/dist/zkProgrammable/provableMethod.js.map +1 -0
  209. package/jest.config.cjs +12 -1
  210. package/package.json +9 -7
  211. package/src/cache/CacheManifest.ts +57 -0
  212. package/src/cache/ProxyCache.ts +30 -0
  213. package/src/cache/RemoteCache.ts +9 -0
  214. package/src/cache/RemoteCacheCompiler.ts +131 -0
  215. package/src/compiling/AtomicCompileHelper.ts +71 -0
  216. package/src/compiling/CompilableModule.ts +6 -0
  217. package/src/compiling/CompileRegistry.ts +64 -0
  218. package/src/compiling/services/ChildVerificationKeyService.ts +26 -0
  219. package/src/config/ChildContainerCreatable.ts +5 -0
  220. package/src/config/ChildContainerProvider.ts +5 -0
  221. package/src/config/ConfigurableModule.ts +15 -2
  222. package/src/config/ModuleContainer.ts +286 -58
  223. package/src/config/Startable.ts +3 -0
  224. package/src/config/injectAlias.ts +70 -0
  225. package/src/dependencyFactory/DependencyFactory.ts +34 -109
  226. package/src/dummyVerificationKey.ts +10 -0
  227. package/src/events/EventEmitter.ts +61 -0
  228. package/src/events/EventEmitterProxy.ts +81 -0
  229. package/src/events/EventEmittingComponent.ts +11 -0
  230. package/src/events/ReplayingSingleUseEventEmitter.ts +42 -0
  231. package/src/index.ts +27 -2
  232. package/src/log.ts +145 -0
  233. package/src/trees/lmt/AbstractLinkedMerkleTree.ts +102 -0
  234. package/src/trees/lmt/InMemoryLinkedLeafStore.ts +42 -0
  235. package/src/trees/lmt/LinkedLeafStore.ts +13 -0
  236. package/src/trees/lmt/LinkedMerkleTree.ts +335 -0
  237. package/src/trees/lmt/LinkedMerkleTreeCircuitOps.ts +188 -0
  238. package/src/trees/lmt/LinkedMerkleTreeTypes.ts +53 -0
  239. package/src/trees/sparse/InMemoryMerkleTreeStorage.ts +17 -0
  240. package/src/trees/sparse/MerkleTreeStore.ts +5 -0
  241. package/src/trees/sparse/MockAsyncMerkleStore.ts +30 -0
  242. package/src/trees/sparse/RollupMerkleTree.ts +512 -0
  243. package/src/types.ts +53 -2
  244. package/src/utils.ts +281 -5
  245. package/src/zkProgrammable/ProvableMethodExecutionContext.ts +6 -6
  246. package/src/zkProgrammable/ZkProgrammable.ts +90 -35
  247. package/src/zkProgrammable/provableMethod.ts +50 -23
  248. package/test/config/ContainerEvents.test.ts +65 -0
  249. package/test/config/ModuleContainer.test.ts +146 -15
  250. package/test/config/injectAlias.test.ts +28 -0
  251. package/test/trees/LinkedMerkleTree.test.ts +124 -0
  252. package/test/trees/LinkedMerkleTreeCircuitOps.test.ts +147 -0
  253. package/test/trees/MerkleTree.test.ts +251 -0
  254. package/test/tsconfig.json +5 -2
  255. package/test/zkProgrammable/ZkProgrammable.test.ts +145 -119
  256. package/tsconfig.json +1 -1
  257. package/LICENSE.md +0 -201
  258. package/tsconfig.test.json +0 -9
package/src/utils.ts CHANGED
@@ -1,4 +1,13 @@
1
- import { Field, FlexibleProvable, FlexibleProvablePure } from "snarkyjs";
1
+ import {
2
+ Field,
3
+ FlexibleProvablePure,
4
+ Poseidon,
5
+ DynamicProof,
6
+ Proof,
7
+ } from "o1js";
8
+ import _ from "lodash";
9
+
10
+ import { TypedClass } from "./types";
2
11
 
3
12
  export function requireTrue(
4
13
  condition: boolean,
@@ -11,14 +20,106 @@ export function requireTrue(
11
20
  }
12
21
  }
13
22
 
14
- export function range(startOrEnd: number, end: number | undefined): number[] {
23
+ /**
24
+ * Utility function to split an array of type T into a record <K, T[]> based on a
25
+ * function T => K that determines the key of each record
26
+ */
27
+ export function splitArray<T, K extends string | number>(
28
+ arr: T[],
29
+ split: (t: T) => K
30
+ ): Record<K, T[] | undefined> {
31
+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
32
+ const record = {} as { [Key in K]: T[] };
33
+ arr.forEach((element) => {
34
+ const k = split(element);
35
+ if (record[k] !== undefined) {
36
+ record[k].push(element);
37
+ } else {
38
+ record[k] = [element];
39
+ }
40
+ });
41
+ return record;
42
+ }
43
+
44
+ export function range(
45
+ startOrEnd: number,
46
+ endOrNothing?: number | undefined
47
+ ): number[] {
48
+ let end = endOrNothing;
49
+ let start = startOrEnd;
15
50
  if (end === undefined) {
16
51
  end = startOrEnd;
17
- startOrEnd = 0;
52
+ start = 0;
18
53
  }
19
- return Array.from({ length: end - startOrEnd }, (ignored, index) => index);
54
+ return Array.from({ length: end - start }, (ignored, index) => index + start);
55
+ }
56
+
57
+ export function reduceSequential<T, U>(
58
+ array: T[],
59
+ callbackfn: (
60
+ previousValue: U,
61
+ currentValue: T,
62
+ currentIndex: number,
63
+ array: T[]
64
+ ) => Promise<U>,
65
+ initialValue: U
66
+ ): Promise<U> {
67
+ return array.reduce<Promise<U>>(
68
+ async (previousPromise, current, index, arr) => {
69
+ const previous = await previousPromise;
70
+ return await callbackfn(previous, current, index, arr);
71
+ },
72
+ Promise.resolve(initialValue)
73
+ );
74
+ }
75
+
76
+ export function yieldSequential<Source, State, Target>(
77
+ array: Source[],
78
+ callbackfn: (
79
+ previousValue: State,
80
+ currentValue: Source,
81
+ currentIndex: number,
82
+ array: Source[]
83
+ ) => Promise<[State, Target]>,
84
+ initialValue: State
85
+ ): Promise<[State, Target[]]> {
86
+ return reduceSequential<Source, [State, Target[]]>(
87
+ array,
88
+ async ([state, collectedTargets], curr, index, arr) => {
89
+ const [newState, addition] = await callbackfn(state, curr, index, arr);
90
+ // The reason we wrap this in an array here is for a special case where Target is a tuple
91
+ // or array itself. In this case, js interprets by flattening the Value in the array
92
+ // (which it does when a function (like concat) uses a spread operator and the
93
+ // input is an array)
94
+ return [newState, collectedTargets.concat([addition])];
95
+ },
96
+ [initialValue, []]
97
+ );
20
98
  }
21
99
 
100
+ export function mapSequential<T, R>(
101
+ array: T[],
102
+ f: (element: T, index: number, array: T[]) => Promise<R>
103
+ ): Promise<R[]> {
104
+ return array.reduce<Promise<R[]>>(async (r, element, index, a) => {
105
+ const ret = await r;
106
+ const next = await f(element, index, a);
107
+ ret.push(next);
108
+ return ret;
109
+ }, Promise.resolve([]));
110
+ }
111
+
112
+ export function unzip<A, B>(array: [A, B][]): [A[], B[]] {
113
+ const as = array.map(([a]) => a);
114
+ const bs = array.map(([, b]) => b);
115
+ return [as, bs];
116
+ }
117
+
118
+ export function assertSizeOneOrTwo<T>(arr: T[]): asserts arr is [T] | [T, T] {
119
+ if (!(arr.length === 1 || arr.length === 2)) {
120
+ throw new Error("Given array not size 1 or 2");
121
+ }
122
+ }
22
123
 
23
124
  /**
24
125
  * Computes a dummy value for the given value type.
@@ -34,4 +135,179 @@ export function dummyValue<Value>(
34
135
 
35
136
  // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
36
137
  return valueType.fromFields(fields) as Value;
37
- }
138
+ }
139
+
140
+ export function noop(): void {}
141
+
142
+ export interface ToFieldable {
143
+ toFields: () => Field[];
144
+ }
145
+
146
+ export interface ToFieldableStatic {
147
+ toFields: (value: unknown) => Field[];
148
+ }
149
+
150
+ export interface ToJSONableStatic {
151
+ toJSON: (value: unknown) => any;
152
+ }
153
+
154
+ // export interface ProofTypes {
155
+ // publicOutputType?: ToFieldableStatic;
156
+ // publicInputType?: ToFieldableStatic;
157
+ // }
158
+
159
+ export type ProofTypes =
160
+ | typeof Proof<unknown, unknown>
161
+ | typeof DynamicProof<unknown, unknown>;
162
+
163
+ export async function sleep(ms: number) {
164
+ await new Promise((resolve) => {
165
+ setTimeout(resolve, ms);
166
+ });
167
+ }
168
+
169
+ export function filterNonNull<Type>(value: Type | null): value is Type {
170
+ return value !== null;
171
+ }
172
+
173
+ export function filterNonUndefined<Type>(
174
+ value: Type | undefined
175
+ ): value is Type {
176
+ return value !== undefined;
177
+ }
178
+
179
+ const encoder = new TextEncoder();
180
+
181
+ // Copied from o1js binable.ts:317
182
+ export function prefixToField(prefix: string): Field {
183
+ const fieldSize = Field.sizeInBytes;
184
+ if (prefix.length >= fieldSize) throw Error("prefix too long");
185
+ const stringBytes = [...encoder.encode(prefix)];
186
+ return Field.fromBytes(
187
+ stringBytes.concat(Array(fieldSize - stringBytes.length).fill(0))
188
+ );
189
+ }
190
+
191
+ export function hashWithPrefix(prefix: string, input: Field[]) {
192
+ const salt = Poseidon.update(
193
+ [Field(0), Field(0), Field(0)],
194
+ [prefixToField(prefix)]
195
+ );
196
+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
197
+ return Poseidon.update(salt as [Field, Field, Field], input)[0];
198
+ }
199
+
200
+ // end copy
201
+
202
+ export function expectDefined<T>(value: T | undefined): asserts value is T {
203
+ expect(value).toBeDefined();
204
+ }
205
+
206
+ type NonMethodKeys<Type> = {
207
+ [Key in keyof Type]: Type[Key] extends Function ? never : Key;
208
+ }[keyof Type];
209
+ export type NonMethods<Type> = Pick<Type, NonMethodKeys<Type>>;
210
+
211
+ export const MAX_FIELD = Field(Field.ORDER - 1n);
212
+
213
+ /**
214
+ * Returns a boolean indicating whether a given class is a subclass of another class,
215
+ * indicated by the name parameter.
216
+ */
217
+ // TODO Change to class reference based comparisons
218
+ export function isSubtypeOfName(
219
+ clas: TypedClass<unknown>,
220
+ name: string
221
+ ): boolean {
222
+ if (clas === undefined || clas === null) {
223
+ return false;
224
+ }
225
+
226
+ if (clas.name === name) {
227
+ return true;
228
+ }
229
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
230
+ return isSubtypeOfName(Object.getPrototypeOf(clas), name);
231
+ }
232
+
233
+ // TODO Eventually, replace this by a schema validation library
234
+ export function safeParseJson<T>(json: string) {
235
+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
236
+ return JSON.parse(json) as T;
237
+ }
238
+
239
+ export type Nullable<T> = {
240
+ [Key in keyof T]: T[Key] | undefined;
241
+ };
242
+
243
+ export function isFull<T>(t: Nullable<T>): t is T {
244
+ return Object.values(t).findIndex((v) => v === undefined) === -1;
245
+ }
246
+
247
+ // TODO Restructure utils into separate package and multiple files
248
+
249
+ export function padArray<T>(
250
+ array: T[],
251
+ batchSize: number,
252
+ generator: (index: number) => T
253
+ ): T[] {
254
+ const slice = array.slice();
255
+ const dummies = range(0, batchSize - (array.length % batchSize)).map((i) =>
256
+ generator(i + array.length)
257
+ );
258
+ slice.push(...dummies);
259
+ return slice;
260
+ }
261
+
262
+ export function batch<T>(
263
+ arr: T[],
264
+ batchSize: number,
265
+ dummy: (index: number) => T
266
+ ): T[][] {
267
+ const padded = padArray(arr, batchSize, dummy);
268
+
269
+ const partitioned = _.groupBy(
270
+ padded.map((v, i) => [v, i] as const),
271
+ ([v, i]) => Math.floor(i / batchSize)
272
+ );
273
+
274
+ const numBatches = Math.ceil(arr.length / batchSize);
275
+
276
+ return range(0, numBatches).map((i) => partitioned[i].map((x) => x[0]));
277
+ }
278
+
279
+ export type Reference<T> = {
280
+ set value(value: T);
281
+ get value(): T;
282
+ };
283
+
284
+ class ReferenceObject<T> {
285
+ public constructor(private internalValue: T) {}
286
+
287
+ get value() {
288
+ return this.internalValue;
289
+ }
290
+
291
+ set value(t: T) {
292
+ this.internalValue = t;
293
+ }
294
+ }
295
+
296
+ export function createReference<T>(initial: T): Reference<T> {
297
+ return new ReferenceObject(initial);
298
+ }
299
+
300
+ export namespace BigIntMath {
301
+ export function max(...args: bigint[]) {
302
+ return args.reduce((m, e) => (e > m ? e : m));
303
+ }
304
+ }
305
+
306
+ export function assertDefined<T>(
307
+ t: T | undefined,
308
+ msg?: string
309
+ ): asserts t is T {
310
+ if (t === undefined) {
311
+ throw new Error(msg ?? "Value is undefined");
312
+ }
313
+ }
@@ -1,7 +1,9 @@
1
- import type { FlexibleProvable, Proof } from "snarkyjs";
1
+ import type { Proof } from "o1js";
2
2
  import { singleton } from "tsyringe";
3
3
  import uniqueId from "lodash/uniqueId";
4
4
 
5
+ import type { ArgumentTypes } from "./provableMethod";
6
+
5
7
  const errors = {
6
8
  moduleOrMethodNameNotSet: () => new Error("Module or method name not set"),
7
9
 
@@ -16,13 +18,12 @@ export class ProvableMethodExecutionResult {
16
18
 
17
19
  public methodName?: string;
18
20
 
19
- public args?: FlexibleProvable<unknown>[];
21
+ public args?: ArgumentTypes;
20
22
 
21
23
  public prover?: () => Promise<Proof<unknown, unknown>>;
22
24
 
23
25
  public async prove<
24
- // eslint-disable-next-line etc/no-misused-generics
25
- ProofType extends Proof<unknown, unknown>
26
+ ProofType extends Proof<unknown, unknown>,
26
27
  >(): Promise<ProofType> {
27
28
  if (!this.prover) {
28
29
  // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
@@ -52,7 +53,6 @@ export class ProvableMethodExecutionContext {
52
53
  public result: ProvableMethodExecutionResult =
53
54
  new ProvableMethodExecutionResult();
54
55
 
55
- // eslint-disable-next-line no-warning-comments,max-len
56
56
  // TODO See if we should make this class generic, bc I think we can persist the type
57
57
  /**
58
58
  * Adds a method prover to the current execution context,
@@ -74,7 +74,7 @@ export class ProvableMethodExecutionContext {
74
74
  public beforeMethod(
75
75
  moduleName: string,
76
76
  methodName: string,
77
- args: FlexibleProvable<unknown>[]
77
+ args: ArgumentTypes
78
78
  ) {
79
79
  if (this.isFinished) {
80
80
  this.clear();
@@ -1,15 +1,30 @@
1
- import { Experimental, FlexibleProvablePure, Proof } from "snarkyjs";
1
+ import {
2
+ ZkProgram,
3
+ FlexibleProvablePure,
4
+ Proof,
5
+ Field,
6
+ Provable,
7
+ Cache as O1Cache,
8
+ } from "o1js";
2
9
  import { Memoize } from "typescript-memoize";
3
10
 
4
- import { mockProof } from "./provableMethod";
11
+ import { log } from "../log";
12
+ import { dummyVerificationKey } from "../dummyVerificationKey";
13
+ import { reduceSequential } from "../utils";
14
+ import type { CompileRegistry } from "../compiling/CompileRegistry";
15
+
16
+ import { MOCK_PROOF } from "./provableMethod";
5
17
 
6
18
  const errors = {
7
- appChainNotSet: (name: string) =>
8
- new Error(`Appchain was not injected for: ${name}`),
19
+ areProofsEnabledNotSet: (name: string) =>
20
+ new Error(`AreProofsEnabled was not injected for: ${name}`),
9
21
  };
10
22
 
11
23
  export interface CompileArtifact {
12
- verificationKey: string;
24
+ verificationKey: {
25
+ data: string;
26
+ hash: Field;
27
+ };
13
28
  }
14
29
 
15
30
  export interface AreProofsEnabled {
@@ -22,29 +37,45 @@ export interface Verify<PublicInput, PublicOutput> {
22
37
  }
23
38
 
24
39
  export interface Compile {
25
- (): Promise<CompileArtifact>;
40
+ (options?: {
41
+ cache?: O1Cache;
42
+ forceRecompile?: boolean;
43
+ proofsEnabled?: boolean;
44
+ withRuntimeTables?: boolean;
45
+ numChunks?: number;
46
+ lazyMode?: boolean;
47
+ }): Promise<CompileArtifact>;
26
48
  }
27
49
 
28
- export interface PlainZkProgram<PublicInput = undefined, PublicOutput = void> {
50
+ export interface PlainZkProgram<
51
+ PublicInput = undefined,
52
+ PublicOutput = undefined,
53
+ > {
54
+ name: string;
29
55
  compile: Compile;
30
56
  verify: Verify<PublicInput, PublicOutput>;
31
57
  Proof: ReturnType<
32
- typeof Experimental.ZkProgram.Proof<
58
+ typeof ZkProgram.Proof<
33
59
  FlexibleProvablePure<PublicInput>,
34
60
  FlexibleProvablePure<PublicOutput>
35
61
  >
36
62
  >;
37
63
  methods: Record<
38
64
  string,
39
- | ((
40
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
41
- ...args: any
42
- ) => Promise<Proof<PublicInput, PublicOutput>>)
65
+ | ((...args: any) => Promise<{
66
+ proof: Proof<PublicInput, PublicOutput>;
67
+ auxiliaryOutput: any;
68
+ }>)
43
69
  | ((
44
70
  publicInput: PublicInput,
45
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
46
71
  ...args: any
47
- ) => Promise<Proof<PublicInput, PublicOutput>>)
72
+ ) => Promise<{
73
+ proof: Proof<PublicInput, PublicOutput>;
74
+ auxiliaryOutput: any;
75
+ }>)
76
+ >;
77
+ analyzeMethods: () => Promise<
78
+ Record<string, Awaited<ReturnType<typeof Provable.constraintSystem>>>
48
79
  >;
49
80
  }
50
81
 
@@ -60,60 +91,84 @@ export function verifyToMockable<PublicInput, PublicOutput>(
60
91
  verified = await verify(proof);
61
92
  } catch (error: unknown) {
62
93
  // silently fail verification
63
- console.error(error);
94
+ log.error(error);
64
95
  verified = false;
65
96
  }
66
97
 
67
98
  return verified;
68
99
  }
69
100
 
70
- return proof.proof === mockProof;
101
+ return proof.proof === MOCK_PROOF;
71
102
  };
72
103
  }
73
104
 
74
- export const mockVerificationKey = "mock-verification-key";
105
+ export const MOCK_VERIFICATION_KEY = dummyVerificationKey();
106
+
75
107
  export function compileToMockable(
76
108
  compile: Compile,
77
109
  { areProofsEnabled }: AreProofsEnabled
78
- ): () => Promise<CompileArtifact> {
79
- return async () => {
110
+ ): Compile {
111
+ return async (...args) => {
80
112
  if (areProofsEnabled) {
81
- return await compile();
113
+ return await compile(...args);
82
114
  }
83
115
 
84
116
  return {
85
- verificationKey: mockVerificationKey,
117
+ verificationKey: MOCK_VERIFICATION_KEY,
86
118
  };
87
119
  };
88
120
  }
89
121
 
90
122
  export abstract class ZkProgrammable<
91
123
  PublicInput = undefined,
92
- PublicOutput = void
124
+ PublicOutput = void,
93
125
  > {
94
- public abstract get appChain(): AreProofsEnabled | undefined;
126
+ public abstract get areProofsEnabled(): AreProofsEnabled | undefined;
95
127
 
96
- public abstract zkProgramFactory(): PlainZkProgram<PublicInput, PublicOutput>;
128
+ public abstract zkProgramFactory(): PlainZkProgram<
129
+ PublicInput,
130
+ PublicOutput
131
+ >[];
97
132
 
98
- @Memoize()
99
- public get zkProgram(): PlainZkProgram<PublicInput, PublicOutput> {
100
- const zkProgram = this.zkProgramFactory();
133
+ private zkProgramSingleton?: PlainZkProgram<PublicInput, PublicOutput>[];
101
134
 
102
- if (!this.appChain) {
103
- throw errors.appChainNotSet(this.constructor.name);
135
+ @Memoize()
136
+ public get zkProgram(): PlainZkProgram<PublicInput, PublicOutput>[] {
137
+ if (this.zkProgramSingleton === undefined) {
138
+ this.zkProgramSingleton = this.zkProgramFactory();
104
139
  }
105
140
 
106
- return {
107
- ...zkProgram,
108
- verify: verifyToMockable(zkProgram.verify, this.appChain),
109
- compile: compileToMockable(zkProgram.compile, this.appChain),
110
- };
141
+ return this.zkProgramSingleton.map((bucket) => {
142
+ if (!this.areProofsEnabled) {
143
+ throw errors.areProofsEnabledNotSet(this.constructor.name);
144
+ }
145
+ return {
146
+ ...bucket,
147
+ verify: verifyToMockable(bucket.verify, this.areProofsEnabled),
148
+ compile: compileToMockable(bucket.compile, this.areProofsEnabled),
149
+ };
150
+ });
151
+ }
152
+
153
+ public async compile(registry: CompileRegistry) {
154
+ return await reduceSequential(
155
+ this.zkProgram,
156
+ async (acc, program) => {
157
+ const result = await registry.compile(program);
158
+ return {
159
+ ...acc,
160
+ [program.name]: result,
161
+ };
162
+ },
163
+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
164
+ {} as Record<string, CompileArtifact>
165
+ );
111
166
  }
112
167
  }
113
168
 
114
169
  export interface WithZkProgrammable<
115
170
  PublicInput = undefined,
116
- PublicOutput = void
171
+ PublicOutput = void,
117
172
  > {
118
173
  zkProgrammable: ZkProgrammable<PublicInput, PublicOutput>;
119
174
  }
@@ -1,39 +1,68 @@
1
- import { FlexibleProvable } from "snarkyjs";
1
+ import { Proof, DynamicProof } from "o1js";
2
2
  import { container } from "tsyringe";
3
3
 
4
4
  import { ProvableMethodExecutionContext } from "./ProvableMethodExecutionContext";
5
5
  import type { WithZkProgrammable, ZkProgrammable } from "./ZkProgrammable";
6
6
 
7
- // eslint-disable-next-line etc/prefer-interface
8
- export type DecoratedMethod = (...args: unknown[]) => unknown;
7
+ // Now, in o1js provable types are normal js objects, therefore any
8
+ export type O1JSPrimitive = object | string | boolean | number;
9
+ export type ArgumentTypes = (
10
+ | O1JSPrimitive
11
+ | Proof<unknown, unknown>
12
+ | DynamicProof<unknown, unknown>
13
+ )[];
9
14
 
10
- export const mockProof = "mock-proof";
15
+ export type DecoratedMethod = (...args: ArgumentTypes) => Promise<unknown>;
16
+
17
+ export const MOCK_PROOF = "mock-proof";
18
+ // (await Proof.dummy(Field(0), Field(0), 2)).proof as string;
11
19
 
12
20
  export function toProver(
13
21
  methodName: string,
14
22
  simulatedMethod: DecoratedMethod,
15
23
  isFirstParameterPublicInput: boolean,
16
- ...args: unknown[]
24
+ ...args: ArgumentTypes
17
25
  ) {
18
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
19
26
  return async function prover(this: ZkProgrammable<any, any>) {
20
- const areProofsEnabled = this.appChain?.areProofsEnabled;
21
- if (areProofsEnabled ?? false) {
22
- const programProvableMethod = this.zkProgram.methods[methodName];
23
- return await Reflect.apply(programProvableMethod, this, args);
27
+ const { areProofsEnabled } = this.areProofsEnabled!;
28
+
29
+ const zkProgram = this.zkProgram.find((prog) =>
30
+ Object.keys(prog.methods).includes(methodName)
31
+ );
32
+
33
+ if (zkProgram === undefined) {
34
+ throw new Error(
35
+ `Correct ZkProgram not found (searching for method ${methodName})`
36
+ );
24
37
  }
25
38
 
26
- // create a mock proof by simulating method execution in JS
27
- const publicOutput = Reflect.apply(simulatedMethod, this, args);
39
+ if (areProofsEnabled) {
40
+ const programProvableMethod = zkProgram.methods[methodName];
41
+ const result = await Reflect.apply(programProvableMethod, this, args);
42
+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
43
+ return result.proof as Proof<any, any>;
44
+ }
45
+
46
+ // create a mock proof by simulating method> execution in JS
47
+ const publicOutput = await Reflect.apply(simulatedMethod, this, args);
28
48
 
29
- return new this.zkProgram.Proof({
30
- proof: mockProof,
49
+ return new zkProgram.Proof({
50
+ proof: MOCK_PROOF,
31
51
 
32
- // eslint-disable-next-line no-warning-comments
33
52
  // TODO: provide undefined if public input is not used
34
53
  publicInput: isFirstParameterPublicInput ? args[0] : undefined,
35
- publicOutput,
36
-
54
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
55
+ publicOutput: (() => {
56
+ // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
57
+ if (!publicOutput || typeof publicOutput !== "object") {
58
+ return undefined;
59
+ }
60
+ if ("publicOutput" in publicOutput) {
61
+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
62
+ return (publicOutput as any).publicOutput;
63
+ }
64
+ return publicOutput;
65
+ })(),
37
66
  /**
38
67
  * We set this to the max possible number, to avoid having
39
68
  * to manually count in-circuit proof verifications
@@ -59,19 +88,18 @@ export function provableMethod(
59
88
  )
60
89
  ) {
61
90
  return <
62
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
63
- Target extends WithZkProgrammable<any, any> | ZkProgrammable<any, any>
91
+ Target extends WithZkProgrammable<any, any> | ZkProgrammable<any, any>,
64
92
  >(
65
93
  target: Target,
66
94
  methodName: string,
67
- descriptor: PropertyDescriptor
95
+ descriptor: TypedPropertyDescriptor<(...args: any[]) => Promise<any> | any>
68
96
  ) => {
69
97
  // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
70
98
  const simulatedMethod = descriptor.value as DecoratedMethod;
71
99
 
72
- descriptor.value = function value(
100
+ descriptor.value = async function value(
73
101
  this: ZkProgrammable<unknown, unknown>,
74
- ...args: FlexibleProvable<unknown>[]
102
+ ...args: ArgumentTypes
75
103
  ) {
76
104
  const prover = toProver(
77
105
  methodName,
@@ -95,7 +123,6 @@ export function provableMethod(
95
123
  * or not, execute its simulated (Javascript) version and
96
124
  * return the result.
97
125
  */
98
- // eslint-disable-next-line @typescript-eslint/init-declarations
99
126
  let result: unknown;
100
127
  try {
101
128
  result = Reflect.apply(simulatedMethod, this, args);