@proto-kit/common 0.1.1-develop.165 → 0.1.1-develop.1665

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 (249) 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 +69 -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 -17
  30. package/dist/config/ModuleContainer.d.ts.map +1 -1
  31. package/dist/config/ModuleContainer.js +164 -22
  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 +29 -0
  42. package/dist/dependencyFactory/DependencyFactory.d.ts.map +1 -0
  43. package/dist/dependencyFactory/DependencyFactory.js +2 -0
  44. package/dist/dependencyFactory/DependencyFactory.js.map +1 -0
  45. package/dist/dummyVerificationKey.d.ts +3 -0
  46. package/dist/dummyVerificationKey.d.ts.map +1 -0
  47. package/dist/dummyVerificationKey.js +8 -0
  48. package/dist/dummyVerificationKey.js.map +1 -0
  49. package/dist/events/EventEmitter.d.ts +19 -0
  50. package/dist/events/EventEmitter.d.ts.map +1 -0
  51. package/dist/events/EventEmitter.js +35 -0
  52. package/dist/events/EventEmitter.js.map +1 -0
  53. package/dist/events/EventEmitterProxy.d.ts +18 -0
  54. package/dist/events/EventEmitterProxy.d.ts.map +1 -0
  55. package/dist/events/EventEmitterProxy.js +35 -0
  56. package/dist/events/EventEmitterProxy.js.map +1 -0
  57. package/dist/events/EventEmittingComponent.d.ts +9 -0
  58. package/dist/events/EventEmittingComponent.d.ts.map +1 -0
  59. package/dist/events/EventEmittingComponent.js +2 -0
  60. package/dist/events/EventEmittingComponent.js.map +1 -0
  61. package/dist/events/ReplayingSingleUseEventEmitter.d.ts +17 -0
  62. package/dist/events/ReplayingSingleUseEventEmitter.d.ts.map +1 -0
  63. package/dist/events/ReplayingSingleUseEventEmitter.js +34 -0
  64. package/dist/events/ReplayingSingleUseEventEmitter.js.map +1 -0
  65. package/dist/index.d.ts +24 -1
  66. package/dist/index.d.ts.map +1 -1
  67. package/dist/index.js +25 -2
  68. package/dist/index.js.map +1 -0
  69. package/dist/log.d.ts +37 -0
  70. package/dist/log.d.ts.map +1 -0
  71. package/dist/log.js +114 -0
  72. package/dist/log.js.map +1 -0
  73. package/dist/trees/lmt/AbstractLinkedMerkleTree.d.ts +288 -0
  74. package/dist/trees/lmt/AbstractLinkedMerkleTree.d.ts.map +1 -0
  75. package/dist/trees/lmt/AbstractLinkedMerkleTree.js +22 -0
  76. package/dist/trees/lmt/AbstractLinkedMerkleTree.js.map +1 -0
  77. package/dist/trees/lmt/InMemoryLinkedLeafStore.d.ts +21 -0
  78. package/dist/trees/lmt/InMemoryLinkedLeafStore.d.ts.map +1 -0
  79. package/dist/trees/lmt/InMemoryLinkedLeafStore.js +26 -0
  80. package/dist/trees/lmt/InMemoryLinkedLeafStore.js.map +1 -0
  81. package/dist/trees/lmt/LinkedLeafStore.d.ts +16 -0
  82. package/dist/trees/lmt/LinkedLeafStore.d.ts.map +1 -0
  83. package/dist/trees/lmt/LinkedLeafStore.js +2 -0
  84. package/dist/trees/lmt/LinkedLeafStore.js.map +1 -0
  85. package/dist/trees/lmt/LinkedMerkleTree.d.ts +11 -0
  86. package/dist/trees/lmt/LinkedMerkleTree.d.ts.map +1 -0
  87. package/dist/trees/lmt/LinkedMerkleTree.js +241 -0
  88. package/dist/trees/lmt/LinkedMerkleTree.js.map +1 -0
  89. package/dist/trees/lmt/LinkedMerkleTreeCircuitOps.d.ts +113 -0
  90. package/dist/trees/lmt/LinkedMerkleTreeCircuitOps.d.ts.map +1 -0
  91. package/dist/trees/lmt/LinkedMerkleTreeCircuitOps.js +113 -0
  92. package/dist/trees/lmt/LinkedMerkleTreeCircuitOps.js.map +1 -0
  93. package/dist/trees/lmt/LinkedMerkleTreeTypes.d.ts +74 -0
  94. package/dist/trees/lmt/LinkedMerkleTreeTypes.d.ts.map +1 -0
  95. package/dist/trees/lmt/LinkedMerkleTreeTypes.js +50 -0
  96. package/dist/trees/lmt/LinkedMerkleTreeTypes.js.map +1 -0
  97. package/dist/trees/sparse/InMemoryMerkleTreeStorage.d.ts +11 -0
  98. package/dist/trees/sparse/InMemoryMerkleTreeStorage.d.ts.map +1 -0
  99. package/dist/trees/sparse/InMemoryMerkleTreeStorage.js +13 -0
  100. package/dist/trees/sparse/InMemoryMerkleTreeStorage.js.map +1 -0
  101. package/dist/trees/sparse/MerkleTreeStore.d.ts +5 -0
  102. package/dist/trees/sparse/MerkleTreeStore.d.ts.map +1 -0
  103. package/dist/trees/sparse/MerkleTreeStore.js +2 -0
  104. package/dist/trees/sparse/MerkleTreeStore.js.map +1 -0
  105. package/dist/trees/sparse/MockAsyncMerkleStore.d.ts +9 -0
  106. package/dist/trees/sparse/MockAsyncMerkleStore.d.ts.map +1 -0
  107. package/dist/trees/sparse/MockAsyncMerkleStore.js +20 -0
  108. package/dist/trees/sparse/MockAsyncMerkleStore.js.map +1 -0
  109. package/dist/trees/sparse/RollupMerkleTree.d.ts +157 -0
  110. package/dist/trees/sparse/RollupMerkleTree.d.ts.map +1 -0
  111. package/dist/trees/sparse/RollupMerkleTree.js +272 -0
  112. package/dist/trees/sparse/RollupMerkleTree.js.map +1 -0
  113. package/dist/types.d.ts +16 -0
  114. package/dist/types.d.ts.map +1 -1
  115. package/dist/types.js +12 -1
  116. package/dist/types.js.map +1 -0
  117. package/dist/utils.d.ts +62 -0
  118. package/dist/utils.d.ts.map +1 -1
  119. package/dist/utils.js +155 -0
  120. package/dist/utils.js.map +1 -0
  121. package/dist/zkProgrammable/ProvableMethodExecutionContext.d.ts +4 -3
  122. package/dist/zkProgrammable/ProvableMethodExecutionContext.d.ts.map +1 -1
  123. package/dist/zkProgrammable/ProvableMethodExecutionContext.js +2 -3
  124. package/dist/zkProgrammable/ProvableMethodExecutionContext.js.map +1 -0
  125. package/dist/zkProgrammable/ZkProgrammable.d.ts +15 -7
  126. package/dist/zkProgrammable/ZkProgrammable.d.ts.map +1 -1
  127. package/dist/zkProgrammable/ZkProgrammable.js +34 -15
  128. package/dist/zkProgrammable/ZkProgrammable.js.map +1 -0
  129. package/dist/zkProgrammable/provableMethod.d.ts +8 -5
  130. package/dist/zkProgrammable/provableMethod.d.ts.map +1 -1
  131. package/dist/zkProgrammable/provableMethod.js +15 -13
  132. package/dist/zkProgrammable/provableMethod.js.map +1 -0
  133. package/jest.config.cjs +12 -1
  134. package/package.json +8 -7
  135. package/src/compiling/AtomicCompileHelper.ts +62 -0
  136. package/src/compiling/CompilableModule.ts +6 -0
  137. package/src/compiling/CompileRegistry.ts +79 -0
  138. package/src/compiling/services/ChildVerificationKeyService.ts +26 -0
  139. package/src/config/ChildContainerCreatable.ts +5 -0
  140. package/src/config/ChildContainerProvider.ts +5 -0
  141. package/src/config/ConfigurableModule.ts +15 -2
  142. package/src/config/ModuleContainer.ts +287 -46
  143. package/src/config/Startable.ts +3 -0
  144. package/src/config/injectAlias.ts +70 -0
  145. package/src/dependencyFactory/DependencyFactory.ts +57 -0
  146. package/src/dummyVerificationKey.ts +10 -0
  147. package/src/events/EventEmitter.ts +61 -0
  148. package/src/events/EventEmitterProxy.ts +81 -0
  149. package/src/events/EventEmittingComponent.ts +11 -0
  150. package/src/events/ReplayingSingleUseEventEmitter.ts +42 -0
  151. package/src/index.ts +24 -2
  152. package/src/log.ts +143 -0
  153. package/src/trees/lmt/AbstractLinkedMerkleTree.ts +102 -0
  154. package/src/trees/lmt/InMemoryLinkedLeafStore.ts +42 -0
  155. package/src/trees/lmt/LinkedLeafStore.ts +13 -0
  156. package/src/trees/lmt/LinkedMerkleTree.ts +335 -0
  157. package/src/trees/lmt/LinkedMerkleTreeCircuitOps.ts +188 -0
  158. package/src/trees/lmt/LinkedMerkleTreeTypes.ts +53 -0
  159. package/src/trees/sparse/InMemoryMerkleTreeStorage.ts +17 -0
  160. package/src/trees/sparse/MerkleTreeStore.ts +5 -0
  161. package/src/trees/sparse/MockAsyncMerkleStore.ts +30 -0
  162. package/src/trees/sparse/RollupMerkleTree.ts +427 -0
  163. package/src/types.ts +43 -2
  164. package/src/utils.ts +287 -0
  165. package/src/zkProgrammable/ProvableMethodExecutionContext.ts +6 -6
  166. package/src/zkProgrammable/ZkProgrammable.ts +61 -29
  167. package/src/zkProgrammable/provableMethod.ts +38 -21
  168. package/test/config/ContainerEvents.test.ts +65 -0
  169. package/test/config/ModuleContainer.test.ts +146 -15
  170. package/test/config/injectAlias.test.ts +28 -0
  171. package/test/trees/LinkedMerkleTree.test.ts +124 -0
  172. package/test/trees/LinkedMerkleTreeCircuitOps.test.ts +147 -0
  173. package/test/trees/MerkleTree.test.ts +220 -0
  174. package/test/tsconfig.json +5 -2
  175. package/test/zkProgrammable/ZkProgrammable.test.ts +135 -114
  176. package/tsconfig.json +1 -1
  177. package/dist/Constants.d.ts +0 -4
  178. package/dist/Constants.d.ts.map +0 -1
  179. package/dist/Constants.js +0 -3
  180. package/dist/config/ConfigurationAggregator.d.ts +0 -10
  181. package/dist/config/ConfigurationAggregator.d.ts.map +0 -1
  182. package/dist/config/ConfigurationAggregator.js +0 -35
  183. package/dist/config/ConfigurationReceiver.d.ts +0 -25
  184. package/dist/config/ConfigurationReceiver.d.ts.map +0 -1
  185. package/dist/config/ConfigurationReceiver.js +0 -36
  186. package/dist/config/types.d.ts +0 -2
  187. package/dist/config/types.d.ts.map +0 -1
  188. package/dist/config/types.js +0 -1
  189. package/dist/model/MethodPublicInput.d.ts +0 -51
  190. package/dist/model/MethodPublicInput.d.ts.map +0 -1
  191. package/dist/model/MethodPublicInput.js +0 -11
  192. package/dist/model/Option.d.ts +0 -89
  193. package/dist/model/Option.d.ts.map +0 -1
  194. package/dist/model/Option.js +0 -86
  195. package/dist/model/Path.d.ts +0 -31
  196. package/dist/model/Path.d.ts.map +0 -1
  197. package/dist/model/Path.js +0 -44
  198. package/dist/model/StateTransition.d.ts +0 -85
  199. package/dist/model/StateTransition.d.ts.map +0 -1
  200. package/dist/model/StateTransition.js +0 -58
  201. package/dist/model/StateTransitionProvableBatch.d.ts +0 -56
  202. package/dist/model/StateTransitionProvableBatch.d.ts.map +0 -1
  203. package/dist/model/StateTransitionProvableBatch.js +0 -20
  204. package/dist/prover/block/BlockProver.d.ts +0 -199
  205. package/dist/prover/block/BlockProver.d.ts.map +0 -1
  206. package/dist/prover/block/BlockProver.js +0 -119
  207. package/dist/prover/block/BlockScopedModule.d.ts +0 -3
  208. package/dist/prover/block/BlockScopedModule.d.ts.map +0 -1
  209. package/dist/prover/block/BlockScopedModule.js +0 -6
  210. package/dist/prover/statetransition/StateTransitionProver.d.ts +0 -92
  211. package/dist/prover/statetransition/StateTransitionProver.d.ts.map +0 -1
  212. package/dist/prover/statetransition/StateTransitionProver.js +0 -127
  213. package/dist/prover/statetransition/StateTransitionWitnessProvider.d.ts +0 -16
  214. package/dist/prover/statetransition/StateTransitionWitnessProvider.d.ts.map +0 -1
  215. package/dist/prover/statetransition/StateTransitionWitnessProvider.js +0 -17
  216. package/dist/src/model/Option.d.ts +0 -158
  217. package/dist/src/model/Option.d.ts.map +0 -1
  218. package/dist/src/model/Option.js +0 -53
  219. package/dist/src/model/Path.d.ts +0 -35
  220. package/dist/src/model/Path.d.ts.map +0 -1
  221. package/dist/src/model/Path.js +0 -51
  222. package/dist/src/model/StateTransition.d.ts +0 -201
  223. package/dist/src/model/StateTransition.d.ts.map +0 -1
  224. package/dist/src/model/StateTransition.js +0 -43
  225. package/dist/src/utils/PrefixedHashList.d.ts +0 -15
  226. package/dist/src/utils/PrefixedHashList.d.ts.map +0 -1
  227. package/dist/src/utils/PrefixedHashList.js +0 -28
  228. package/dist/src/utils/ProvableHashList.d.ts +0 -30
  229. package/dist/src/utils/ProvableHashList.d.ts.map +0 -1
  230. package/dist/src/utils/ProvableHashList.js +0 -43
  231. package/dist/utils/PrefixedHashList.d.ts +0 -14
  232. package/dist/utils/PrefixedHashList.d.ts.map +0 -1
  233. package/dist/utils/PrefixedHashList.js +0 -12
  234. package/dist/utils/PrefixedProvableHashList.d.ts +0 -8
  235. package/dist/utils/PrefixedProvableHashList.d.ts.map +0 -1
  236. package/dist/utils/PrefixedProvableHashList.js +0 -12
  237. package/dist/utils/ProvableHashList.d.ts +0 -26
  238. package/dist/utils/ProvableHashList.d.ts.map +0 -1
  239. package/dist/utils/ProvableHashList.js +0 -35
  240. package/dist/utils/Utils.d.ts +0 -22
  241. package/dist/utils/Utils.d.ts.map +0 -1
  242. package/dist/utils/Utils.js +0 -41
  243. package/dist/utils/merkletree/MemoryMerkleTreeStorage.d.ts +0 -26
  244. package/dist/utils/merkletree/MemoryMerkleTreeStorage.d.ts.map +0 -1
  245. package/dist/utils/merkletree/MemoryMerkleTreeStorage.js +0 -79
  246. package/dist/utils/merkletree/RollupMerkleTree.d.ts +0 -143
  247. package/dist/utils/merkletree/RollupMerkleTree.d.ts.map +0 -1
  248. package/dist/utils/merkletree/RollupMerkleTree.js +0 -246
  249. 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)
@@ -8,3 +19,279 @@ export function requireTrue(
8
19
  : errorOrFunction;
9
20
  }
10
21
  }
22
+
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;
50
+ if (end === undefined) {
51
+ end = startOrEnd;
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
+ return [newState, collectedTargets.concat(addition)];
91
+ },
92
+ [initialValue, []]
93
+ );
94
+ }
95
+
96
+ export function mapSequential<T, R>(
97
+ array: T[],
98
+ f: (element: T, index: number, array: T[]) => Promise<R>
99
+ ): Promise<R[]> {
100
+ return array.reduce<Promise<R[]>>(async (r, element, index, a) => {
101
+ const ret = await r;
102
+ const next = await f(element, index, a);
103
+ ret.push(next);
104
+ return ret;
105
+ }, Promise.resolve([]));
106
+ }
107
+
108
+ /**
109
+ * Computes a dummy value for the given value type.
110
+ *
111
+ * @param valueType - Value type to generate the dummy value for
112
+ * @returns Dummy value for the given value type
113
+ */
114
+ export function dummyValue<Value>(
115
+ valueType: FlexibleProvablePure<Value>
116
+ ): Value {
117
+ const length = valueType.sizeInFields();
118
+ const fields = Array.from({ length }, () => Field(0));
119
+
120
+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
121
+ return valueType.fromFields(fields) as Value;
122
+ }
123
+
124
+ export function noop(): void {}
125
+
126
+ export interface ToFieldable {
127
+ toFields: () => Field[];
128
+ }
129
+
130
+ export interface ToFieldableStatic {
131
+ toFields: (value: unknown) => Field[];
132
+ }
133
+
134
+ export interface ToJSONableStatic {
135
+ toJSON: (value: unknown) => any;
136
+ }
137
+
138
+ // export interface ProofTypes {
139
+ // publicOutputType?: ToFieldableStatic;
140
+ // publicInputType?: ToFieldableStatic;
141
+ // }
142
+
143
+ export type ProofTypes =
144
+ | typeof Proof<unknown, unknown>
145
+ | typeof DynamicProof<unknown, unknown>;
146
+
147
+ export async function sleep(ms: number) {
148
+ await new Promise((resolve) => {
149
+ setTimeout(resolve, ms);
150
+ });
151
+ }
152
+
153
+ export function filterNonNull<Type>(value: Type | null): value is Type {
154
+ return value !== null;
155
+ }
156
+
157
+ export function filterNonUndefined<Type>(
158
+ value: Type | undefined
159
+ ): value is Type {
160
+ return value !== undefined;
161
+ }
162
+
163
+ const encoder = new TextEncoder();
164
+
165
+ // Copied from o1js binable.ts:317
166
+ export function prefixToField(prefix: string): Field {
167
+ const fieldSize = Field.sizeInBytes;
168
+ if (prefix.length >= fieldSize) throw Error("prefix too long");
169
+ const stringBytes = [...encoder.encode(prefix)];
170
+ return Field.fromBytes(
171
+ stringBytes.concat(Array(fieldSize - stringBytes.length).fill(0))
172
+ );
173
+ }
174
+
175
+ export function hashWithPrefix(prefix: string, input: Field[]) {
176
+ const salt = Poseidon.update(
177
+ [Field(0), Field(0), Field(0)],
178
+ [prefixToField(prefix)]
179
+ );
180
+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
181
+ return Poseidon.update(salt as [Field, Field, Field], input)[0];
182
+ }
183
+
184
+ // end copy
185
+
186
+ export function expectDefined<T>(value: T | undefined): asserts value is T {
187
+ expect(value).toBeDefined();
188
+ }
189
+
190
+ type NonMethodKeys<Type> = {
191
+ [Key in keyof Type]: Type[Key] extends Function ? never : Key;
192
+ }[keyof Type];
193
+ export type NonMethods<Type> = Pick<Type, NonMethodKeys<Type>>;
194
+
195
+ export const MAX_FIELD = Field(Field.ORDER - 1n);
196
+
197
+ /**
198
+ * Returns a boolean indicating whether a given class is a subclass of another class,
199
+ * indicated by the name parameter.
200
+ */
201
+ // TODO Change to class reference based comparisons
202
+ export function isSubtypeOfName(
203
+ clas: TypedClass<unknown>,
204
+ name: string
205
+ ): boolean {
206
+ if (clas === undefined || clas === null) {
207
+ return false;
208
+ }
209
+
210
+ if (clas.name === name) {
211
+ return true;
212
+ }
213
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
214
+ return isSubtypeOfName(Object.getPrototypeOf(clas), name);
215
+ }
216
+
217
+ // TODO Eventually, replace this by a schema validation library
218
+ export function safeParseJson<T>(json: string) {
219
+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
220
+ return JSON.parse(json) as T;
221
+ }
222
+
223
+ export type Nullable<T> = {
224
+ [Key in keyof T]: T[Key] | undefined;
225
+ };
226
+
227
+ export function isFull<T>(t: Nullable<T>): t is T {
228
+ return Object.values(t).findIndex((v) => v === undefined) === -1;
229
+ }
230
+
231
+ // TODO Restructure utils into separate package and multiple files
232
+
233
+ export function padArray<T>(
234
+ array: T[],
235
+ batchSize: number,
236
+ generator: (index: number) => T
237
+ ): T[] {
238
+ const slice = array.slice();
239
+ const dummies = range(0, batchSize - (array.length % batchSize)).map((i) =>
240
+ generator(i + array.length)
241
+ );
242
+ slice.push(...dummies);
243
+ return slice;
244
+ }
245
+
246
+ export function batch<T>(
247
+ arr: T[],
248
+ batchSize: number,
249
+ dummy: (index: number) => T
250
+ ): T[][] {
251
+ const padded = padArray(arr, batchSize, dummy);
252
+
253
+ const partitioned = _.groupBy(
254
+ padded.map((v, i) => [v, i] as const),
255
+ ([v, i]) => Math.floor(i / batchSize)
256
+ );
257
+
258
+ const numBatches = Math.ceil(arr.length / batchSize);
259
+
260
+ return range(0, numBatches).map((i) => partitioned[i].map((x) => x[0]));
261
+ }
262
+
263
+ export type Reference<T> = {
264
+ set value(value: T);
265
+ get value(): T;
266
+ };
267
+
268
+ class ReferenceObject<T> {
269
+ public constructor(private internalValue: T) {}
270
+
271
+ get value() {
272
+ return this.internalValue;
273
+ }
274
+
275
+ set value(t: T) {
276
+ this.internalValue = t;
277
+ }
278
+ }
279
+
280
+ export function createReference<T>(initial: T): Reference<T> {
281
+ return new ReferenceObject(initial);
282
+ }
283
+
284
+ export namespace BigIntMath {
285
+ export function max(...args: bigint[]) {
286
+ return args.reduce((m, e) => (e > m ? e : m));
287
+ }
288
+ }
289
+
290
+ export function assertDefined<T>(
291
+ t: T | undefined,
292
+ msg?: string
293
+ ): asserts t is T {
294
+ if (t === undefined) {
295
+ throw new Error(msg ?? "Value is undefined");
296
+ }
297
+ }
@@ -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 {
@@ -26,26 +34,26 @@ export interface Compile {
26
34
  }
27
35
 
28
36
  export interface PlainZkProgram<PublicInput = undefined, PublicOutput = void> {
37
+ name: string;
29
38
  compile: Compile;
30
39
  verify: Verify<PublicInput, PublicOutput>;
31
40
  Proof: ReturnType<
32
- typeof Experimental.ZkProgram.Proof<
41
+ typeof ZkProgram.Proof<
33
42
  FlexibleProvablePure<PublicInput>,
34
43
  FlexibleProvablePure<PublicOutput>
35
44
  >
36
45
  >;
37
46
  methods: Record<
38
47
  string,
39
- | ((
40
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
41
- ...args: any
42
- ) => Promise<Proof<PublicInput, PublicOutput>>)
48
+ | ((...args: any) => Promise<Proof<PublicInput, PublicOutput>>)
43
49
  | ((
44
50
  publicInput: PublicInput,
45
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
46
51
  ...args: any
47
52
  ) => Promise<Proof<PublicInput, PublicOutput>>)
48
53
  >;
54
+ analyzeMethods: () => Promise<
55
+ Record<string, Awaited<ReturnType<typeof Provable.constraintSystem>>>
56
+ >;
49
57
  }
50
58
 
51
59
  export function verifyToMockable<PublicInput, PublicOutput>(
@@ -60,18 +68,19 @@ export function verifyToMockable<PublicInput, PublicOutput>(
60
68
  verified = await verify(proof);
61
69
  } catch (error: unknown) {
62
70
  // silently fail verification
63
- console.error(error);
71
+ log.error(error);
64
72
  verified = false;
65
73
  }
66
74
 
67
75
  return verified;
68
76
  }
69
77
 
70
- return proof.proof === mockProof;
78
+ return proof.proof === MOCK_PROOF;
71
79
  };
72
80
  }
73
81
 
74
- export const mockVerificationKey = "mock-verification-key";
82
+ export const MOCK_VERIFICATION_KEY = dummyVerificationKey();
83
+
75
84
  export function compileToMockable(
76
85
  compile: Compile,
77
86
  { areProofsEnabled }: AreProofsEnabled
@@ -82,38 +91,61 @@ export function compileToMockable(
82
91
  }
83
92
 
84
93
  return {
85
- verificationKey: mockVerificationKey,
94
+ verificationKey: MOCK_VERIFICATION_KEY,
86
95
  };
87
96
  };
88
97
  }
89
98
 
90
99
  export abstract class ZkProgrammable<
91
100
  PublicInput = undefined,
92
- PublicOutput = void
101
+ PublicOutput = void,
93
102
  > {
94
- public abstract get appChain(): AreProofsEnabled | undefined;
103
+ public abstract get areProofsEnabled(): AreProofsEnabled | undefined;
95
104
 
96
- public abstract zkProgramFactory(): PlainZkProgram<PublicInput, PublicOutput>;
105
+ public abstract zkProgramFactory(): PlainZkProgram<
106
+ PublicInput,
107
+ PublicOutput
108
+ >[];
97
109
 
98
- @Memoize()
99
- public get zkProgram(): PlainZkProgram<PublicInput, PublicOutput> {
100
- const zkProgram = this.zkProgramFactory();
110
+ private zkProgramSingleton?: PlainZkProgram<PublicInput, PublicOutput>[];
101
111
 
102
- if (!this.appChain) {
103
- throw errors.appChainNotSet(this.constructor.name);
112
+ @Memoize()
113
+ public get zkProgram(): PlainZkProgram<PublicInput, PublicOutput>[] {
114
+ if (this.zkProgramSingleton === undefined) {
115
+ this.zkProgramSingleton = this.zkProgramFactory();
104
116
  }
105
117
 
106
- return {
107
- ...zkProgram,
108
- verify: verifyToMockable(zkProgram.verify, this.appChain),
109
- compile: compileToMockable(zkProgram.compile, this.appChain),
110
- };
118
+ return this.zkProgramSingleton.map((bucket) => {
119
+ if (!this.areProofsEnabled) {
120
+ throw errors.areProofsEnabledNotSet(this.constructor.name);
121
+ }
122
+ return {
123
+ ...bucket,
124
+ verify: verifyToMockable(bucket.verify, this.areProofsEnabled),
125
+ compile: compileToMockable(bucket.compile, this.areProofsEnabled),
126
+ };
127
+ });
128
+ }
129
+
130
+ public async compile(registry: CompileRegistry) {
131
+ return await reduceSequential(
132
+ this.zkProgram,
133
+ async (acc, program) => {
134
+ const result = await registry.compile(program);
135
+ return {
136
+ ...acc,
137
+ [program.name]: result,
138
+ };
139
+ },
140
+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
141
+ {} as Record<string, CompileArtifact>
142
+ );
111
143
  }
112
144
  }
113
145
 
114
146
  export interface WithZkProgrammable<
115
147
  PublicInput = undefined,
116
- PublicOutput = void
148
+ PublicOutput = void,
117
149
  > {
118
150
  zkProgrammable: ZkProgrammable<PublicInput, PublicOutput>;
119
151
  }
@@ -1,35 +1,52 @@
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];
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
+ );
37
+ }
38
+
39
+ if (areProofsEnabled) {
40
+ const programProvableMethod = zkProgram.methods[methodName];
23
41
  return await Reflect.apply(programProvableMethod, this, args);
24
42
  }
25
43
 
26
- // create a mock proof by simulating method execution in JS
27
- const publicOutput = Reflect.apply(simulatedMethod, this, args);
44
+ // create a mock proof by simulating method> execution in JS
45
+ const publicOutput = await Reflect.apply(simulatedMethod, this, args);
28
46
 
29
- return new this.zkProgram.Proof({
30
- proof: mockProof,
47
+ return new zkProgram.Proof({
48
+ proof: MOCK_PROOF,
31
49
 
32
- // eslint-disable-next-line no-warning-comments
33
50
  // TODO: provide undefined if public input is not used
34
51
  publicInput: isFirstParameterPublicInput ? args[0] : undefined,
35
52
  publicOutput,
@@ -58,18 +75,19 @@ export function provableMethod(
58
75
  ProvableMethodExecutionContext
59
76
  )
60
77
  ) {
61
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
62
- return <Target extends ZkProgrammable<any, any>>(
78
+ return <
79
+ Target extends WithZkProgrammable<any, any> | ZkProgrammable<any, any>,
80
+ >(
63
81
  target: Target,
64
82
  methodName: string,
65
- descriptor: PropertyDescriptor
83
+ descriptor: TypedPropertyDescriptor<(...args: any[]) => Promise<any> | any>
66
84
  ) => {
67
85
  // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
68
86
  const simulatedMethod = descriptor.value as DecoratedMethod;
69
87
 
70
- descriptor.value = function value(
88
+ descriptor.value = async function value(
71
89
  this: ZkProgrammable<unknown, unknown>,
72
- ...args: FlexibleProvable<unknown>[]
90
+ ...args: ArgumentTypes
73
91
  ) {
74
92
  const prover = toProver(
75
93
  methodName,
@@ -93,7 +111,6 @@ export function provableMethod(
93
111
  * or not, execute its simulated (Javascript) version and
94
112
  * return the result.
95
113
  */
96
- // eslint-disable-next-line @typescript-eslint/init-declarations
97
114
  let result: unknown;
98
115
  try {
99
116
  result = Reflect.apply(simulatedMethod, this, args);
@@ -0,0 +1,65 @@
1
+ import "reflect-metadata";
2
+ import { injectable, container as tsyringeContainer } from "tsyringe";
3
+
4
+ import {
5
+ BaseModuleInstanceType,
6
+ ConfigurableModule,
7
+ EventEmitter,
8
+ EventEmittingComponent,
9
+ ModuleContainer,
10
+ ModulesRecord,
11
+ } from "../../src";
12
+
13
+ class TestContainer<
14
+ Modules extends ModulesRecord,
15
+ > extends ModuleContainer<Modules> {}
16
+
17
+ type TestEvents = {
18
+ test: [string];
19
+ };
20
+
21
+ @injectable()
22
+ class TestModule
23
+ extends ConfigurableModule<{}>
24
+ implements BaseModuleInstanceType, EventEmittingComponent<TestEvents>
25
+ {
26
+ events = new EventEmitter<TestEvents>();
27
+ }
28
+
29
+ type TestEvents2 = {
30
+ test2: [number];
31
+ };
32
+
33
+ class TestModule2
34
+ extends ConfigurableModule<{}>
35
+ implements BaseModuleInstanceType, EventEmittingComponent<TestEvents2>
36
+ {
37
+ events = new EventEmitter<TestEvents2>();
38
+ }
39
+
40
+ describe("test event propagation", () => {
41
+ it("should propagate events up", () => {
42
+ expect.assertions(1);
43
+
44
+ const container = new TestContainer({
45
+ test: TestModule,
46
+ test2: TestModule2,
47
+ });
48
+
49
+ container.configure({
50
+ test: {},
51
+ test2: {},
52
+ });
53
+
54
+ container.create(() => tsyringeContainer.createChildContainer());
55
+
56
+ const testvalue = "testString123";
57
+
58
+ container.events.on("test", (value: string) => {
59
+ expect(value).toStrictEqual(testvalue);
60
+ });
61
+
62
+ const module = container.resolve("test");
63
+ module.events.emit("test", testvalue);
64
+ });
65
+ });