@proto-kit/common 0.1.1-develop.190 → 0.1.1-develop.2024

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 (238) hide show
  1. package/dist/compiling/AtomicCompileHelper.d.ts +13 -0
  2. package/dist/compiling/AtomicCompileHelper.d.ts.map +1 -0
  3. package/dist/compiling/AtomicCompileHelper.js +40 -0
  4. package/dist/compiling/AtomicCompileHelper.js.map +1 -0
  5. package/dist/compiling/CompilableModule.d.ts +6 -0
  6. package/dist/compiling/CompilableModule.d.ts.map +1 -0
  7. package/dist/compiling/CompilableModule.js +2 -0
  8. package/dist/compiling/CompilableModule.js.map +1 -0
  9. package/dist/compiling/CompileRegistry.d.ts +26 -0
  10. package/dist/compiling/CompileRegistry.d.ts.map +1 -0
  11. package/dist/compiling/CompileRegistry.js +67 -0
  12. package/dist/compiling/CompileRegistry.js.map +1 -0
  13. package/dist/compiling/services/ChildVerificationKeyService.d.ts +10 -0
  14. package/dist/compiling/services/ChildVerificationKeyService.d.ts.map +1 -0
  15. package/dist/compiling/services/ChildVerificationKeyService.js +27 -0
  16. package/dist/compiling/services/ChildVerificationKeyService.js.map +1 -0
  17. package/dist/config/ChildContainerCreatable.d.ts +5 -0
  18. package/dist/config/ChildContainerCreatable.d.ts.map +1 -0
  19. package/dist/config/ChildContainerCreatable.js +2 -0
  20. package/dist/config/ChildContainerCreatable.js.map +1 -0
  21. package/dist/config/ChildContainerProvider.d.ts +5 -0
  22. package/dist/config/ChildContainerProvider.d.ts.map +1 -0
  23. package/dist/config/ChildContainerProvider.js +2 -0
  24. package/dist/config/ChildContainerProvider.js.map +1 -0
  25. package/dist/config/ConfigurableModule.d.ts +6 -2
  26. package/dist/config/ConfigurableModule.d.ts.map +1 -1
  27. package/dist/config/ConfigurableModule.js +5 -0
  28. package/dist/config/ConfigurableModule.js.map +1 -0
  29. package/dist/config/ModuleContainer.d.ts +70 -23
  30. package/dist/config/ModuleContainer.d.ts.map +1 -1
  31. package/dist/config/ModuleContainer.js +164 -31
  32. package/dist/config/ModuleContainer.js.map +1 -0
  33. package/dist/config/Startable.d.ts +4 -0
  34. package/dist/config/Startable.d.ts.map +1 -0
  35. package/dist/config/Startable.js +2 -0
  36. package/dist/config/Startable.js.map +1 -0
  37. package/dist/config/injectAlias.d.ts +18 -0
  38. package/dist/config/injectAlias.d.ts.map +1 -0
  39. package/dist/config/injectAlias.js +47 -0
  40. package/dist/config/injectAlias.js.map +1 -0
  41. package/dist/dependencyFactory/DependencyFactory.d.ts +14 -9
  42. package/dist/dependencyFactory/DependencyFactory.d.ts.map +1 -1
  43. package/dist/dependencyFactory/DependencyFactory.js +2 -96
  44. package/dist/dependencyFactory/DependencyFactory.js.map +1 -0
  45. package/dist/dependencyFactory/injectOptional.d.ts +16 -0
  46. package/dist/dependencyFactory/injectOptional.d.ts.map +1 -0
  47. package/dist/dependencyFactory/injectOptional.js +40 -0
  48. package/dist/dependencyFactory/injectOptional.js.map +1 -0
  49. package/dist/dummyVerificationKey.d.ts +3 -0
  50. package/dist/dummyVerificationKey.d.ts.map +1 -0
  51. package/dist/dummyVerificationKey.js +8 -0
  52. package/dist/dummyVerificationKey.js.map +1 -0
  53. package/dist/events/EventEmitter.d.ts +19 -0
  54. package/dist/events/EventEmitter.d.ts.map +1 -0
  55. package/dist/events/EventEmitter.js +35 -0
  56. package/dist/events/EventEmitter.js.map +1 -0
  57. package/dist/events/EventEmitterProxy.d.ts +18 -0
  58. package/dist/events/EventEmitterProxy.d.ts.map +1 -0
  59. package/dist/events/EventEmitterProxy.js +35 -0
  60. package/dist/events/EventEmitterProxy.js.map +1 -0
  61. package/dist/events/EventEmittingComponent.d.ts +9 -0
  62. package/dist/events/EventEmittingComponent.d.ts.map +1 -0
  63. package/dist/events/EventEmittingComponent.js +2 -0
  64. package/dist/events/EventEmittingComponent.js.map +1 -0
  65. package/dist/events/ReplayingSingleUseEventEmitter.d.ts +17 -0
  66. package/dist/events/ReplayingSingleUseEventEmitter.d.ts.map +1 -0
  67. package/dist/events/ReplayingSingleUseEventEmitter.js +34 -0
  68. package/dist/events/ReplayingSingleUseEventEmitter.js.map +1 -0
  69. package/dist/index.d.ts +23 -1
  70. package/dist/index.d.ts.map +1 -1
  71. package/dist/index.js +24 -2
  72. package/dist/index.js.map +1 -0
  73. package/dist/log.d.ts +37 -0
  74. package/dist/log.d.ts.map +1 -0
  75. package/dist/log.js +117 -0
  76. package/dist/log.js.map +1 -0
  77. package/dist/trees/InMemoryLinkedLeafStore.d.ts +21 -0
  78. package/dist/trees/InMemoryLinkedLeafStore.d.ts.map +1 -0
  79. package/dist/trees/InMemoryLinkedLeafStore.js +26 -0
  80. package/dist/trees/InMemoryLinkedLeafStore.js.map +1 -0
  81. package/dist/trees/InMemoryLinkedMerkleLeafStore.d.ts +7 -0
  82. package/dist/trees/InMemoryLinkedMerkleLeafStore.d.ts.map +1 -0
  83. package/dist/trees/InMemoryLinkedMerkleLeafStore.js +6 -0
  84. package/dist/trees/InMemoryLinkedMerkleLeafStore.js.map +1 -0
  85. package/dist/trees/InMemoryMerkleTreeStorage.d.ts +11 -0
  86. package/dist/trees/InMemoryMerkleTreeStorage.d.ts.map +1 -0
  87. package/dist/trees/InMemoryMerkleTreeStorage.js +13 -0
  88. package/dist/trees/InMemoryMerkleTreeStorage.js.map +1 -0
  89. package/dist/trees/LinkedMerkleTree.d.ts +345 -0
  90. package/dist/trees/LinkedMerkleTree.d.ts.map +1 -0
  91. package/dist/trees/LinkedMerkleTree.js +337 -0
  92. package/dist/trees/LinkedMerkleTree.js.map +1 -0
  93. package/dist/trees/LinkedMerkleTreeStore.d.ts +24 -0
  94. package/dist/trees/LinkedMerkleTreeStore.d.ts.map +1 -0
  95. package/dist/trees/LinkedMerkleTreeStore.js +2 -0
  96. package/dist/trees/LinkedMerkleTreeStore.js.map +1 -0
  97. package/dist/trees/MerkleTreeStore.d.ts +5 -0
  98. package/dist/trees/MerkleTreeStore.d.ts.map +1 -0
  99. package/dist/trees/MerkleTreeStore.js +2 -0
  100. package/dist/trees/MerkleTreeStore.js.map +1 -0
  101. package/dist/trees/MockAsyncMerkleStore.d.ts +9 -0
  102. package/dist/trees/MockAsyncMerkleStore.d.ts.map +1 -0
  103. package/dist/trees/MockAsyncMerkleStore.js +20 -0
  104. package/dist/trees/MockAsyncMerkleStore.js.map +1 -0
  105. package/dist/trees/RollupMerkleTree.d.ts +147 -0
  106. package/dist/trees/RollupMerkleTree.d.ts.map +1 -0
  107. package/dist/trees/RollupMerkleTree.js +218 -0
  108. package/dist/trees/RollupMerkleTree.js.map +1 -0
  109. package/dist/trees/VirtualMerkleTreeStore.d.ts +13 -0
  110. package/dist/trees/VirtualMerkleTreeStore.d.ts.map +1 -0
  111. package/dist/trees/VirtualMerkleTreeStore.js +18 -0
  112. package/dist/trees/VirtualMerkleTreeStore.js.map +1 -0
  113. package/dist/trees/lmt/AbstractLinkedMerkleTree.d.ts +288 -0
  114. package/dist/trees/lmt/AbstractLinkedMerkleTree.d.ts.map +1 -0
  115. package/dist/trees/lmt/AbstractLinkedMerkleTree.js +22 -0
  116. package/dist/trees/lmt/AbstractLinkedMerkleTree.js.map +1 -0
  117. package/dist/trees/lmt/InMemoryLinkedLeafStore.d.ts +21 -0
  118. package/dist/trees/lmt/InMemoryLinkedLeafStore.d.ts.map +1 -0
  119. package/dist/trees/lmt/InMemoryLinkedLeafStore.js +26 -0
  120. package/dist/trees/lmt/InMemoryLinkedLeafStore.js.map +1 -0
  121. package/dist/trees/lmt/InMemoryLinkedMerkleLeafStore.d.ts +7 -0
  122. package/dist/trees/lmt/InMemoryLinkedMerkleLeafStore.d.ts.map +1 -0
  123. package/dist/trees/lmt/InMemoryLinkedMerkleLeafStore.js +6 -0
  124. package/dist/trees/lmt/InMemoryLinkedMerkleLeafStore.js.map +1 -0
  125. package/dist/trees/lmt/LinkedLeafStore.d.ts +16 -0
  126. package/dist/trees/lmt/LinkedLeafStore.d.ts.map +1 -0
  127. package/dist/trees/lmt/LinkedLeafStore.js +2 -0
  128. package/dist/trees/lmt/LinkedLeafStore.js.map +1 -0
  129. package/dist/trees/lmt/LinkedLinkedStore.d.ts +16 -0
  130. package/dist/trees/lmt/LinkedLinkedStore.d.ts.map +1 -0
  131. package/dist/trees/lmt/LinkedLinkedStore.js +2 -0
  132. package/dist/trees/lmt/LinkedLinkedStore.js.map +1 -0
  133. package/dist/trees/lmt/LinkedMerkleTree.d.ts +11 -0
  134. package/dist/trees/lmt/LinkedMerkleTree.d.ts.map +1 -0
  135. package/dist/trees/lmt/LinkedMerkleTree.js +241 -0
  136. package/dist/trees/lmt/LinkedMerkleTree.js.map +1 -0
  137. package/dist/trees/lmt/LinkedMerkleTreeCircuitOps.d.ts +113 -0
  138. package/dist/trees/lmt/LinkedMerkleTreeCircuitOps.d.ts.map +1 -0
  139. package/dist/trees/lmt/LinkedMerkleTreeCircuitOps.js +113 -0
  140. package/dist/trees/lmt/LinkedMerkleTreeCircuitOps.js.map +1 -0
  141. package/dist/trees/lmt/LinkedMerkleTreeDatabase.d.ts +7 -0
  142. package/dist/trees/lmt/LinkedMerkleTreeDatabase.d.ts.map +1 -0
  143. package/dist/trees/lmt/LinkedMerkleTreeDatabase.js +2 -0
  144. package/dist/trees/lmt/LinkedMerkleTreeDatabase.js.map +1 -0
  145. package/dist/trees/lmt/LinkedMerkleTreeStore.d.ts +16 -0
  146. package/dist/trees/lmt/LinkedMerkleTreeStore.d.ts.map +1 -0
  147. package/dist/trees/lmt/LinkedMerkleTreeStore.js +2 -0
  148. package/dist/trees/lmt/LinkedMerkleTreeStore.js.map +1 -0
  149. package/dist/trees/lmt/LinkedMerkleTreeTypes.d.ts +74 -0
  150. package/dist/trees/lmt/LinkedMerkleTreeTypes.d.ts.map +1 -0
  151. package/dist/trees/lmt/LinkedMerkleTreeTypes.js +50 -0
  152. package/dist/trees/lmt/LinkedMerkleTreeTypes.js.map +1 -0
  153. package/dist/trees/sparse/InMemoryMerkleTreeStorage.d.ts +11 -0
  154. package/dist/trees/sparse/InMemoryMerkleTreeStorage.d.ts.map +1 -0
  155. package/dist/trees/sparse/InMemoryMerkleTreeStorage.js +13 -0
  156. package/dist/trees/sparse/InMemoryMerkleTreeStorage.js.map +1 -0
  157. package/dist/trees/sparse/MerkleTreeStore.d.ts +5 -0
  158. package/dist/trees/sparse/MerkleTreeStore.d.ts.map +1 -0
  159. package/dist/trees/sparse/MerkleTreeStore.js +2 -0
  160. package/dist/trees/sparse/MerkleTreeStore.js.map +1 -0
  161. package/dist/trees/sparse/MockAsyncMerkleStore.d.ts +9 -0
  162. package/dist/trees/sparse/MockAsyncMerkleStore.d.ts.map +1 -0
  163. package/dist/trees/sparse/MockAsyncMerkleStore.js +20 -0
  164. package/dist/trees/sparse/MockAsyncMerkleStore.js.map +1 -0
  165. package/dist/trees/sparse/RollupMerkleTree.d.ts +158 -0
  166. package/dist/trees/sparse/RollupMerkleTree.d.ts.map +1 -0
  167. package/dist/trees/sparse/RollupMerkleTree.js +330 -0
  168. package/dist/trees/sparse/RollupMerkleTree.js.map +1 -0
  169. package/dist/types.d.ts +62 -0
  170. package/dist/types.d.ts.map +1 -1
  171. package/dist/types.js +14 -1
  172. package/dist/types.js.map +1 -0
  173. package/dist/union/union.d.ts +177 -0
  174. package/dist/union/union.d.ts.map +1 -0
  175. package/dist/union/union.js +35 -0
  176. package/dist/union/union.js.map +1 -0
  177. package/dist/utils.d.ts +64 -1
  178. package/dist/utils.d.ts.map +1 -1
  179. package/dist/utils.js +165 -3
  180. package/dist/utils.js.map +1 -0
  181. package/dist/zkProgrammable/ProvableMethodExecutionContext.d.ts +4 -3
  182. package/dist/zkProgrammable/ProvableMethodExecutionContext.d.ts.map +1 -1
  183. package/dist/zkProgrammable/ProvableMethodExecutionContext.js +2 -3
  184. package/dist/zkProgrammable/ProvableMethodExecutionContext.js.map +1 -0
  185. package/dist/zkProgrammable/ZkProgrammable.d.ts +23 -9
  186. package/dist/zkProgrammable/ZkProgrammable.d.ts.map +1 -1
  187. package/dist/zkProgrammable/ZkProgrammable.js +34 -15
  188. package/dist/zkProgrammable/ZkProgrammable.js.map +1 -0
  189. package/dist/zkProgrammable/provableMethod.d.ts +8 -5
  190. package/dist/zkProgrammable/provableMethod.d.ts.map +1 -1
  191. package/dist/zkProgrammable/provableMethod.js +30 -15
  192. package/dist/zkProgrammable/provableMethod.js.map +1 -0
  193. package/jest.config.cjs +12 -1
  194. package/package.json +8 -7
  195. package/src/compiling/AtomicCompileHelper.ts +62 -0
  196. package/src/compiling/CompilableModule.ts +6 -0
  197. package/src/compiling/CompileRegistry.ts +74 -0
  198. package/src/compiling/services/ChildVerificationKeyService.ts +26 -0
  199. package/src/config/ChildContainerCreatable.ts +5 -0
  200. package/src/config/ChildContainerProvider.ts +5 -0
  201. package/src/config/ConfigurableModule.ts +15 -2
  202. package/src/config/ModuleContainer.ts +286 -58
  203. package/src/config/Startable.ts +3 -0
  204. package/src/config/injectAlias.ts +70 -0
  205. package/src/dependencyFactory/DependencyFactory.ts +34 -109
  206. package/src/dummyVerificationKey.ts +10 -0
  207. package/src/events/EventEmitter.ts +61 -0
  208. package/src/events/EventEmitterProxy.ts +81 -0
  209. package/src/events/EventEmittingComponent.ts +11 -0
  210. package/src/events/ReplayingSingleUseEventEmitter.ts +42 -0
  211. package/src/index.ts +23 -2
  212. package/src/log.ts +145 -0
  213. package/src/trees/lmt/AbstractLinkedMerkleTree.ts +102 -0
  214. package/src/trees/lmt/InMemoryLinkedLeafStore.ts +42 -0
  215. package/src/trees/lmt/LinkedLeafStore.ts +13 -0
  216. package/src/trees/lmt/LinkedMerkleTree.ts +335 -0
  217. package/src/trees/lmt/LinkedMerkleTreeCircuitOps.ts +188 -0
  218. package/src/trees/lmt/LinkedMerkleTreeTypes.ts +53 -0
  219. package/src/trees/sparse/InMemoryMerkleTreeStorage.ts +17 -0
  220. package/src/trees/sparse/MerkleTreeStore.ts +5 -0
  221. package/src/trees/sparse/MockAsyncMerkleStore.ts +30 -0
  222. package/src/trees/sparse/RollupMerkleTree.ts +512 -0
  223. package/src/types.ts +53 -2
  224. package/src/utils.ts +298 -3
  225. package/src/zkProgrammable/ProvableMethodExecutionContext.ts +6 -6
  226. package/src/zkProgrammable/ZkProgrammable.ts +72 -31
  227. package/src/zkProgrammable/provableMethod.ts +53 -24
  228. package/test/config/ContainerEvents.test.ts +65 -0
  229. package/test/config/ModuleContainer.test.ts +146 -15
  230. package/test/config/injectAlias.test.ts +28 -0
  231. package/test/trees/LinkedMerkleTree.test.ts +124 -0
  232. package/test/trees/LinkedMerkleTreeCircuitOps.test.ts +147 -0
  233. package/test/trees/MerkleTree.test.ts +251 -0
  234. package/test/tsconfig.json +5 -2
  235. package/test/zkProgrammable/ZkProgrammable.test.ts +145 -119
  236. package/tsconfig.json +1 -1
  237. package/LICENSE.md +0 -201
  238. package/tsconfig.test.json +0 -9
package/src/utils.ts CHANGED
@@ -1,3 +1,14 @@
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";
11
+
1
12
  export function requireTrue(
2
13
  condition: boolean,
3
14
  errorOrFunction: Error | (() => Error)
@@ -9,10 +20,294 @@ export function requireTrue(
9
20
  }
10
21
  }
11
22
 
12
- 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;
13
50
  if (end === undefined) {
14
51
  end = startOrEnd;
15
- startOrEnd = 0;
52
+ start = 0;
53
+ }
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
+ );
98
+ }
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
+ }
123
+
124
+ /**
125
+ * Computes a dummy value for the given value type.
126
+ *
127
+ * @param valueType - Value type to generate the dummy value for
128
+ * @returns Dummy value for the given value type
129
+ */
130
+ export function dummyValue<Value>(
131
+ valueType: FlexibleProvablePure<Value>
132
+ ): Value {
133
+ const length = valueType.sizeInFields();
134
+ const fields = Array.from({ length }, () => Field(0));
135
+
136
+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
137
+ return valueType.fromFields(fields) as Value;
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");
16
312
  }
17
- return Array.from({ length: end - startOrEnd }, (ignored, index) => index);
18
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,23 @@
1
- import { Experimental, FlexibleProvablePure, Proof } from "snarkyjs";
1
+ import { ZkProgram, FlexibleProvablePure, Proof, Field, Provable } from "o1js";
2
2
  import { Memoize } from "typescript-memoize";
3
3
 
4
- import { mockProof } from "./provableMethod";
4
+ import { log } from "../log";
5
+ import { dummyVerificationKey } from "../dummyVerificationKey";
6
+ import { reduceSequential } from "../utils";
7
+ import type { CompileRegistry } from "../compiling/CompileRegistry";
8
+
9
+ import { MOCK_PROOF } from "./provableMethod";
5
10
 
6
11
  const errors = {
7
- appChainNotSet: (name: string) =>
8
- new Error(`Appchain was not injected for: ${name}`),
12
+ areProofsEnabledNotSet: (name: string) =>
13
+ new Error(`AreProofsEnabled was not injected for: ${name}`),
9
14
  };
10
15
 
11
16
  export interface CompileArtifact {
12
- verificationKey: string;
17
+ verificationKey: {
18
+ data: string;
19
+ hash: Field;
20
+ };
13
21
  }
14
22
 
15
23
  export interface AreProofsEnabled {
@@ -25,26 +33,35 @@ export interface Compile {
25
33
  (): Promise<CompileArtifact>;
26
34
  }
27
35
 
28
- export interface PlainZkProgram<PublicInput = undefined, PublicOutput = void> {
36
+ export interface PlainZkProgram<
37
+ PublicInput = undefined,
38
+ PublicOutput = undefined,
39
+ > {
40
+ name: string;
29
41
  compile: Compile;
30
42
  verify: Verify<PublicInput, PublicOutput>;
31
43
  Proof: ReturnType<
32
- typeof Experimental.ZkProgram.Proof<
44
+ typeof ZkProgram.Proof<
33
45
  FlexibleProvablePure<PublicInput>,
34
46
  FlexibleProvablePure<PublicOutput>
35
47
  >
36
48
  >;
37
49
  methods: Record<
38
50
  string,
39
- | ((
40
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
41
- ...args: any
42
- ) => Promise<Proof<PublicInput, PublicOutput>>)
51
+ | ((...args: any) => Promise<{
52
+ proof: Proof<PublicInput, PublicOutput>;
53
+ auxiliaryOutput: any;
54
+ }>)
43
55
  | ((
44
56
  publicInput: PublicInput,
45
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
46
57
  ...args: any
47
- ) => Promise<Proof<PublicInput, PublicOutput>>)
58
+ ) => Promise<{
59
+ proof: Proof<PublicInput, PublicOutput>;
60
+ auxiliaryOutput: any;
61
+ }>)
62
+ >;
63
+ analyzeMethods: () => Promise<
64
+ Record<string, Awaited<ReturnType<typeof Provable.constraintSystem>>>
48
65
  >;
49
66
  }
50
67
 
@@ -60,18 +77,19 @@ export function verifyToMockable<PublicInput, PublicOutput>(
60
77
  verified = await verify(proof);
61
78
  } catch (error: unknown) {
62
79
  // silently fail verification
63
- console.error(error);
80
+ log.error(error);
64
81
  verified = false;
65
82
  }
66
83
 
67
84
  return verified;
68
85
  }
69
86
 
70
- return proof.proof === mockProof;
87
+ return proof.proof === MOCK_PROOF;
71
88
  };
72
89
  }
73
90
 
74
- export const mockVerificationKey = "mock-verification-key";
91
+ export const MOCK_VERIFICATION_KEY = dummyVerificationKey();
92
+
75
93
  export function compileToMockable(
76
94
  compile: Compile,
77
95
  { areProofsEnabled }: AreProofsEnabled
@@ -82,38 +100,61 @@ export function compileToMockable(
82
100
  }
83
101
 
84
102
  return {
85
- verificationKey: mockVerificationKey,
103
+ verificationKey: MOCK_VERIFICATION_KEY,
86
104
  };
87
105
  };
88
106
  }
89
107
 
90
108
  export abstract class ZkProgrammable<
91
109
  PublicInput = undefined,
92
- PublicOutput = void
110
+ PublicOutput = void,
93
111
  > {
94
- public abstract get appChain(): AreProofsEnabled | undefined;
112
+ public abstract get areProofsEnabled(): AreProofsEnabled | undefined;
95
113
 
96
- public abstract zkProgramFactory(): PlainZkProgram<PublicInput, PublicOutput>;
114
+ public abstract zkProgramFactory(): PlainZkProgram<
115
+ PublicInput,
116
+ PublicOutput
117
+ >[];
97
118
 
98
- @Memoize()
99
- public get zkProgram(): PlainZkProgram<PublicInput, PublicOutput> {
100
- const zkProgram = this.zkProgramFactory();
119
+ private zkProgramSingleton?: PlainZkProgram<PublicInput, PublicOutput>[];
101
120
 
102
- if (!this.appChain) {
103
- throw errors.appChainNotSet(this.constructor.name);
121
+ @Memoize()
122
+ public get zkProgram(): PlainZkProgram<PublicInput, PublicOutput>[] {
123
+ if (this.zkProgramSingleton === undefined) {
124
+ this.zkProgramSingleton = this.zkProgramFactory();
104
125
  }
105
126
 
106
- return {
107
- ...zkProgram,
108
- verify: verifyToMockable(zkProgram.verify, this.appChain),
109
- compile: compileToMockable(zkProgram.compile, this.appChain),
110
- };
127
+ return this.zkProgramSingleton.map((bucket) => {
128
+ if (!this.areProofsEnabled) {
129
+ throw errors.areProofsEnabledNotSet(this.constructor.name);
130
+ }
131
+ return {
132
+ ...bucket,
133
+ verify: verifyToMockable(bucket.verify, this.areProofsEnabled),
134
+ compile: compileToMockable(bucket.compile, this.areProofsEnabled),
135
+ };
136
+ });
137
+ }
138
+
139
+ public async compile(registry: CompileRegistry) {
140
+ return await reduceSequential(
141
+ this.zkProgram,
142
+ async (acc, program) => {
143
+ const result = await registry.compile(program);
144
+ return {
145
+ ...acc,
146
+ [program.name]: result,
147
+ };
148
+ },
149
+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
150
+ {} as Record<string, CompileArtifact>
151
+ );
111
152
  }
112
153
  }
113
154
 
114
155
  export interface WithZkProgrammable<
115
156
  PublicInput = undefined,
116
- PublicOutput = void
157
+ PublicOutput = void,
117
158
  > {
118
159
  zkProgrammable: ZkProgrammable<PublicInput, PublicOutput>;
119
160
  }
@@ -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
- import type { ZkProgrammable } from "./ZkProgrammable";
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
@@ -58,18 +87,19 @@ export function provableMethod(
58
87
  ProvableMethodExecutionContext
59
88
  )
60
89
  ) {
61
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
62
- return <Target extends ZkProgrammable<any, any>>(
90
+ return <
91
+ Target extends WithZkProgrammable<any, any> | ZkProgrammable<any, any>,
92
+ >(
63
93
  target: Target,
64
94
  methodName: string,
65
- descriptor: PropertyDescriptor
95
+ descriptor: TypedPropertyDescriptor<(...args: any[]) => Promise<any> | any>
66
96
  ) => {
67
97
  // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
68
98
  const simulatedMethod = descriptor.value as DecoratedMethod;
69
99
 
70
- descriptor.value = function value(
100
+ descriptor.value = async function value(
71
101
  this: ZkProgrammable<unknown, unknown>,
72
- ...args: FlexibleProvable<unknown>[]
102
+ ...args: ArgumentTypes
73
103
  ) {
74
104
  const prover = toProver(
75
105
  methodName,
@@ -93,7 +123,6 @@ export function provableMethod(
93
123
  * or not, execute its simulated (Javascript) version and
94
124
  * return the result.
95
125
  */
96
- // eslint-disable-next-line @typescript-eslint/init-declarations
97
126
  let result: unknown;
98
127
  try {
99
128
  result = Reflect.apply(simulatedMethod, this, args);