@proto-kit/module 0.1.1-develop.1086

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 (60) hide show
  1. package/LICENSE.md +201 -0
  2. package/README.md +114 -0
  3. package/dist/factories/MethodIdFactory.d.ts +10 -0
  4. package/dist/factories/MethodIdFactory.d.ts.map +1 -0
  5. package/dist/factories/MethodIdFactory.js +10 -0
  6. package/dist/index.d.ts +11 -0
  7. package/dist/index.d.ts.map +1 -0
  8. package/dist/index.js +10 -0
  9. package/dist/method/MethodParameterEncoder.d.ts +24 -0
  10. package/dist/method/MethodParameterEncoder.d.ts.map +1 -0
  11. package/dist/method/MethodParameterEncoder.js +164 -0
  12. package/dist/method/runtimeMethod.d.ts +33 -0
  13. package/dist/method/runtimeMethod.d.ts.map +1 -0
  14. package/dist/method/runtimeMethod.js +167 -0
  15. package/dist/module/decorator.d.ts +8 -0
  16. package/dist/module/decorator.d.ts.map +1 -0
  17. package/dist/module/decorator.js +15 -0
  18. package/dist/runtime/MethodIdResolver.d.ts +20 -0
  19. package/dist/runtime/MethodIdResolver.d.ts.map +1 -0
  20. package/dist/runtime/MethodIdResolver.js +90 -0
  21. package/dist/runtime/Runtime.d.ts +71 -0
  22. package/dist/runtime/Runtime.d.ts.map +1 -0
  23. package/dist/runtime/Runtime.js +220 -0
  24. package/dist/runtime/RuntimeEnvironment.d.ts +10 -0
  25. package/dist/runtime/RuntimeEnvironment.d.ts.map +1 -0
  26. package/dist/runtime/RuntimeEnvironment.js +1 -0
  27. package/dist/runtime/RuntimeModule.d.ts +37 -0
  28. package/dist/runtime/RuntimeModule.d.ts.map +1 -0
  29. package/dist/runtime/RuntimeModule.js +79 -0
  30. package/dist/state/InMemoryStateService.d.ts +15 -0
  31. package/dist/state/InMemoryStateService.d.ts.map +1 -0
  32. package/dist/state/InMemoryStateService.js +23 -0
  33. package/dist/state/decorator.d.ts +7 -0
  34. package/dist/state/decorator.d.ts.map +1 -0
  35. package/dist/state/decorator.js +39 -0
  36. package/jest.config.cjs +1 -0
  37. package/package.json +35 -0
  38. package/src/factories/MethodIdFactory.ts +13 -0
  39. package/src/index.ts +10 -0
  40. package/src/method/MethodParameterEncoder.ts +252 -0
  41. package/src/method/runtimeMethod.ts +307 -0
  42. package/src/module/decorator.ts +21 -0
  43. package/src/runtime/MethodIdResolver.ts +108 -0
  44. package/src/runtime/Runtime.ts +379 -0
  45. package/src/runtime/RuntimeEnvironment.ts +16 -0
  46. package/src/runtime/RuntimeModule.ts +112 -0
  47. package/src/state/InMemoryStateService.ts +25 -0
  48. package/src/state/decorator.ts +61 -0
  49. package/test/Runtime.test.ts +70 -0
  50. package/test/TestingRuntime.ts +45 -0
  51. package/test/method/MethodParameterEncoder.test.ts +152 -0
  52. package/test/method/runtimeMethod.test.ts +46 -0
  53. package/test/modules/Admin.ts +19 -0
  54. package/test/modules/Balances.test.ts +337 -0
  55. package/test/modules/Balances.ts +54 -0
  56. package/test/modules/MethodIdResolver.test.ts +73 -0
  57. package/test/modules/State.test.ts +81 -0
  58. package/test/runtimeMethod.test.ts +215 -0
  59. package/test/tsconfig.json +7 -0
  60. package/tsconfig.json +8 -0
@@ -0,0 +1,307 @@
1
+ import { Bool, Field, FlexibleProvablePure, Poseidon } from "o1js";
2
+ import { container } from "tsyringe";
3
+ import {
4
+ StateTransition,
5
+ ProvableStateTransition,
6
+ MethodPublicOutput,
7
+ RuntimeMethodExecutionContext,
8
+ StateTransitionReductionList,
9
+ DefaultProvableHashList,
10
+ } from "@proto-kit/protocol";
11
+ import {
12
+ DecoratedMethod,
13
+ toProver,
14
+ ZkProgrammable,
15
+ ArgumentTypes,
16
+ } from "@proto-kit/common";
17
+
18
+ import type { RuntimeModule } from "../runtime/RuntimeModule.js";
19
+
20
+ import { MethodParameterEncoder } from "./MethodParameterEncoder";
21
+
22
+ const errors = {
23
+ runtimeNotProvided: (name: string) =>
24
+ new Error(`Runtime was not provided for module: ${name}`),
25
+
26
+ methodInputsNotProvided: () =>
27
+ new Error(
28
+ "Method execution inputs not provided, provide them via context.inputs"
29
+ ),
30
+
31
+ runtimeNameNotSet: () => new Error("Runtime name was not set"),
32
+
33
+ fieldNotConstant: (name: string) =>
34
+ new Error(
35
+ `In-circuit field ${name} not a constant, this is likely a framework bug`
36
+ ),
37
+ };
38
+
39
+ export function toStateTransitionsHash(
40
+ stateTransitions: StateTransition<any>[]
41
+ ) {
42
+ const stateTransitionsHashList = new StateTransitionReductionList(
43
+ ProvableStateTransition
44
+ );
45
+
46
+ return stateTransitions
47
+ .map((stateTransition) => stateTransition.toProvable())
48
+ .reduce(
49
+ (allStateTransitionsHashList, stateTransition) =>
50
+ allStateTransitionsHashList.push(stateTransition),
51
+ stateTransitionsHashList
52
+ )
53
+ .toField();
54
+ }
55
+
56
+ export function toEventsHash(
57
+ events: {
58
+ eventType: FlexibleProvablePure<any>;
59
+ event: any;
60
+ eventName: string;
61
+ condition: Bool;
62
+ }[]
63
+ ) {
64
+ return events.reduce((acc, event) => {
65
+ const hashList = new DefaultProvableHashList(event.eventType, acc);
66
+ hashList.pushIf(event.event, event.condition);
67
+ return hashList.commitment;
68
+ }, Field(0));
69
+ }
70
+
71
+ export type WrappedMethod = (...args: ArgumentTypes) => MethodPublicOutput;
72
+ export type AsyncWrappedMethod = (
73
+ ...args: ArgumentTypes
74
+ ) => Promise<MethodPublicOutput>;
75
+
76
+ export function toWrappedMethod(
77
+ this: RuntimeModule<unknown>,
78
+ methodName: string,
79
+ moduleMethod: (...args: ArgumentTypes) => Promise<any>,
80
+ options: {
81
+ invocationType: RuntimeMethodInvocationType;
82
+ }
83
+ ): AsyncWrappedMethod {
84
+ const executionContext = container.resolve<RuntimeMethodExecutionContext>(
85
+ RuntimeMethodExecutionContext
86
+ );
87
+
88
+ const wrappedMethod: AsyncWrappedMethod = async (
89
+ ...args
90
+ ): Promise<MethodPublicOutput> => {
91
+ await Reflect.apply(moduleMethod, this, args);
92
+ const {
93
+ result: { stateTransitions, status, events },
94
+ } = executionContext.current();
95
+
96
+ const stateTransitionsHash = toStateTransitionsHash(stateTransitions);
97
+ const eventsHash = toEventsHash(events);
98
+
99
+ const { name, runtime } = this;
100
+
101
+ if (name === undefined) {
102
+ throw errors.runtimeNameNotSet();
103
+ }
104
+ if (runtime === undefined) {
105
+ throw errors.runtimeNotProvided(name);
106
+ }
107
+
108
+ const { transaction, networkState } = executionContext.witnessInput();
109
+ const { methodIdResolver } = runtime;
110
+
111
+ // Assert that the given transaction has the correct methodId
112
+ const thisMethodId = Field(methodIdResolver.getMethodId(name, methodName));
113
+ if (!thisMethodId.isConstant()) {
114
+ throw errors.fieldNotConstant("methodId");
115
+ }
116
+
117
+ transaction.methodId.assertEquals(
118
+ thisMethodId,
119
+ "Runtimemethod called with wrong methodId on the transaction object"
120
+ );
121
+
122
+ /**
123
+ * Use the type info obtained previously to convert
124
+ * the args passed to fields
125
+ */
126
+ const { fields } = MethodParameterEncoder.fromMethod(
127
+ this,
128
+ methodName
129
+ ).encode(args);
130
+
131
+ // Assert that the argsHash that has been signed matches the given arguments
132
+ const argsHash = Poseidon.hash(fields);
133
+
134
+ transaction.argsHash.assertEquals(
135
+ argsHash,
136
+ "argsHash and therefore arguments of transaction and runtime call does not match"
137
+ );
138
+
139
+ const isMessage = Bool(options.invocationType === "INCOMING_MESSAGE");
140
+ transaction.assertTransactionType(Bool(isMessage));
141
+
142
+ const transactionHash = transaction.hash();
143
+ const networkStateHash = networkState.hash();
144
+
145
+ return new MethodPublicOutput({
146
+ stateTransitionsHash,
147
+ status,
148
+ transactionHash,
149
+ networkStateHash,
150
+ isMessage,
151
+ eventsHash,
152
+ });
153
+ };
154
+
155
+ Object.defineProperty(wrappedMethod, "name", {
156
+ value: `wrapped_${methodName}`,
157
+ writable: false,
158
+ });
159
+
160
+ return wrappedMethod;
161
+ }
162
+
163
+ export function combineMethodName(
164
+ runtimeModuleName: string,
165
+ methodName: string
166
+ ) {
167
+ return `${runtimeModuleName}.${methodName}`;
168
+ }
169
+
170
+ export const runtimeMethodMetadataKey = "yab-method";
171
+ export const runtimeMethodNamesMetadataKey = "proto-kit-runtime-methods";
172
+ export const runtimeMethodTypeMetadataKey = "proto-kit-runtime-method-type";
173
+
174
+ /**
175
+ * Checks the metadata of the provided runtime module and its method,
176
+ * to see if it has been decorated with @runtimeMethod()
177
+ *
178
+ * @param target - Runtime module to check
179
+ * @param propertyKey - Name of the method to check in the prior runtime module
180
+ * @returns - If the provided method name is a runtime method or not
181
+ */
182
+ export function isRuntimeMethod(
183
+ target: RuntimeModule<unknown>,
184
+ propertyKey: string
185
+ ) {
186
+ return Boolean(
187
+ Reflect.getMetadata(runtimeMethodMetadataKey, target, propertyKey)
188
+ );
189
+ }
190
+
191
+ export type RuntimeMethodInvocationType = "SIGNATURE" | "INCOMING_MESSAGE";
192
+
193
+ function runtimeMethodInternal(options: {
194
+ invocationType: RuntimeMethodInvocationType;
195
+ }) {
196
+ return (
197
+ target: RuntimeModule<unknown>,
198
+ methodName: string,
199
+ descriptor: TypedPropertyDescriptor<
200
+ // TODO Limit possible parameter types
201
+ (...args: any[]) => Promise<any>
202
+ >
203
+ ) => {
204
+ const executionContext = container.resolve<RuntimeMethodExecutionContext>(
205
+ RuntimeMethodExecutionContext
206
+ );
207
+
208
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
209
+ let data: string[] | undefined = Reflect.getMetadata(
210
+ runtimeMethodNamesMetadataKey,
211
+ target
212
+ );
213
+ if (data !== undefined) {
214
+ data.push(methodName);
215
+ } else {
216
+ data = [methodName];
217
+ }
218
+ Reflect.defineMetadata(runtimeMethodNamesMetadataKey, data, target);
219
+
220
+ Reflect.defineMetadata(runtimeMethodMetadataKey, true, target, methodName);
221
+
222
+ Reflect.defineMetadata(
223
+ runtimeMethodTypeMetadataKey,
224
+ options.invocationType,
225
+ target,
226
+ methodName
227
+ );
228
+
229
+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
230
+ const simulatedMethod = descriptor.value as DecoratedMethod;
231
+
232
+ descriptor.value = async function value(
233
+ this: RuntimeModule<unknown>,
234
+ ...args: ArgumentTypes
235
+ ) {
236
+ const constructorName = this.name!;
237
+
238
+ /**
239
+ * If its a top level method call, wrap it into a wrapped method,
240
+ * since it'll be turned into a real/mock prover in provableMethod().
241
+ *
242
+ * Otherwise provableMethod() will just call the originalMethod provided
243
+ * if method is not called at the top level.
244
+ */
245
+ const simulatedWrappedMethod = Reflect.apply(toWrappedMethod, this, [
246
+ methodName,
247
+ simulatedMethod,
248
+ options,
249
+ ]);
250
+
251
+ /**
252
+ * Before the prover runs, make sure it is operating on the correct
253
+ * RuntimeMethodExecutionContext state, meaning it enters and exits
254
+ * the context properly.
255
+ */
256
+
257
+ async function prover(this: ZkProgrammable<any, any>) {
258
+ executionContext.beforeMethod(constructorName, methodName, args);
259
+ const innerProver = toProver(
260
+ combineMethodName(constructorName, methodName),
261
+ simulatedWrappedMethod,
262
+ false,
263
+ ...args
264
+ ).bind(this);
265
+ let result: Awaited<ReturnType<typeof innerProver>>;
266
+ try {
267
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
268
+ result = await Reflect.apply(innerProver, this, args);
269
+ } finally {
270
+ executionContext.afterMethod();
271
+ }
272
+
273
+ return result;
274
+ }
275
+
276
+ executionContext.beforeMethod(constructorName, methodName, args);
277
+
278
+ if (executionContext.isTopLevel) {
279
+ if (!this.runtime) {
280
+ throw errors.runtimeNotProvided(constructorName);
281
+ }
282
+ executionContext.setProver(prover.bind(this.runtime.zkProgrammable));
283
+ }
284
+
285
+ let result: unknown;
286
+ try {
287
+ result = await Reflect.apply(simulatedMethod, this, args);
288
+ } finally {
289
+ executionContext.afterMethod();
290
+ }
291
+
292
+ return result;
293
+ };
294
+ };
295
+ }
296
+
297
+ export function runtimeMessage() {
298
+ return runtimeMethodInternal({
299
+ invocationType: "INCOMING_MESSAGE",
300
+ });
301
+ }
302
+
303
+ export function runtimeMethod() {
304
+ return runtimeMethodInternal({
305
+ invocationType: "SIGNATURE",
306
+ });
307
+ }
@@ -0,0 +1,21 @@
1
+ import { injectable } from "tsyringe";
2
+ import { StaticConfigurableModule, TypedClass } from "@proto-kit/common";
3
+
4
+ import { RuntimeModule } from "../runtime/RuntimeModule.js";
5
+
6
+ /**
7
+ * Marks the decorated class as a runtime module, while also
8
+ * making it injectable with our dependency injection solution.
9
+ */
10
+ export function runtimeModule() {
11
+ return (
12
+ /**
13
+ * Check if the target class extends RuntimeModule, while
14
+ * also providing static config presets
15
+ */
16
+ target: StaticConfigurableModule<unknown> &
17
+ TypedClass<RuntimeModule<unknown>>
18
+ ) => {
19
+ injectable()(target);
20
+ };
21
+ }
@@ -0,0 +1,108 @@
1
+ import { filterNonUndefined } from "@proto-kit/common";
2
+ import { stringToField, RuntimeMethodIdMapping } from "@proto-kit/protocol";
3
+ import { Poseidon } from "o1js";
4
+ import { inject, injectable } from "tsyringe";
5
+
6
+ import {
7
+ RuntimeMethodInvocationType,
8
+ runtimeMethodTypeMetadataKey,
9
+ } from "../method/runtimeMethod";
10
+
11
+ import type { Runtime, RuntimeModulesRecord } from "./Runtime";
12
+
13
+ /**
14
+ * Please see `getMethodId` to learn more about
15
+ * methodId encoding
16
+ */
17
+ @injectable()
18
+ export class MethodIdResolver {
19
+ private readonly dictionary: {
20
+ [key: string]: { moduleName: string; methodName: string };
21
+ } = {};
22
+
23
+ public constructor(
24
+ @inject("Runtime") private readonly runtime: Runtime<RuntimeModulesRecord>
25
+ ) {
26
+ this.dictionary = runtime.runtimeModuleNames.reduce<
27
+ Record<string, { moduleName: string; methodName: string }>
28
+ >((dict, moduleName) => {
29
+ this.runtime.assertIsValidModuleName(moduleName);
30
+
31
+ runtime.resolve(moduleName).runtimeMethodNames.forEach((methodName) => {
32
+ dict[this.getMethodId(moduleName, methodName).toString()] = {
33
+ moduleName,
34
+ methodName,
35
+ };
36
+ });
37
+
38
+ return dict;
39
+ }, {});
40
+ }
41
+
42
+ /**
43
+ * The purpose of this method is to provide a dictionary where
44
+ * we can look up properties like methodId and invocationType
45
+ * for each runtimeMethod using their module name and method name
46
+ */
47
+ public methodIdMap(): RuntimeMethodIdMapping {
48
+ const methodIdResolver =
49
+ this.runtime.dependencyContainer.resolve<MethodIdResolver>(
50
+ "MethodIdResolver"
51
+ );
52
+
53
+ const rawMappings = this.runtime.moduleNames.flatMap((moduleName) => {
54
+ const module = this.runtime.resolve(moduleName);
55
+ return module.runtimeMethodNames.map((method) => {
56
+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
57
+ const type = Reflect.getMetadata(
58
+ runtimeMethodTypeMetadataKey,
59
+ module,
60
+ method
61
+ ) as RuntimeMethodInvocationType | undefined;
62
+
63
+ if (type !== undefined) {
64
+ return {
65
+ name: `${moduleName}.${method}`,
66
+ methodId: methodIdResolver.getMethodId(moduleName, method),
67
+ type,
68
+ } as const;
69
+ }
70
+
71
+ return undefined;
72
+ });
73
+ });
74
+
75
+ return rawMappings
76
+ .filter(filterNonUndefined)
77
+ .reduce<RuntimeMethodIdMapping>((acc, entry) => {
78
+ acc[entry.name] = {
79
+ methodId: entry.methodId,
80
+ type: entry.type,
81
+ };
82
+ return acc;
83
+ }, {});
84
+ }
85
+
86
+ public getMethodNameFromId(methodId: bigint): [string, string] | undefined {
87
+ const methodPath = this.dictionary[methodId.toString()];
88
+
89
+ if (methodPath === undefined) {
90
+ return undefined;
91
+ }
92
+
93
+ const { moduleName, methodName } = methodPath;
94
+
95
+ this.runtime.assertIsValidModuleName(moduleName);
96
+
97
+ return [moduleName, methodName];
98
+ }
99
+
100
+ public getMethodId(moduleName: string, methodName: string): bigint {
101
+ this.runtime.assertIsValidModuleName(moduleName);
102
+
103
+ return Poseidon.hash([
104
+ stringToField(moduleName),
105
+ stringToField(methodName),
106
+ ]).toBigInt();
107
+ }
108
+ }