@proto-kit/module 0.1.1-develop.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) 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 +11 -0
  6. package/dist/factories/MethodIdFactory.js.map +1 -0
  7. package/dist/index.d.ts +11 -0
  8. package/dist/index.d.ts.map +1 -0
  9. package/dist/index.js +11 -0
  10. package/dist/index.js.map +1 -0
  11. package/dist/method/MethodParameterEncoder.d.ts +26 -0
  12. package/dist/method/MethodParameterEncoder.d.ts.map +1 -0
  13. package/dist/method/MethodParameterEncoder.js +169 -0
  14. package/dist/method/MethodParameterEncoder.js.map +1 -0
  15. package/dist/method/runtimeMethod.d.ts +33 -0
  16. package/dist/method/runtimeMethod.d.ts.map +1 -0
  17. package/dist/method/runtimeMethod.js +169 -0
  18. package/dist/method/runtimeMethod.js.map +1 -0
  19. package/dist/module/decorator.d.ts +8 -0
  20. package/dist/module/decorator.d.ts.map +1 -0
  21. package/dist/module/decorator.js +16 -0
  22. package/dist/module/decorator.js.map +1 -0
  23. package/dist/runtime/MethodIdResolver.d.ts +20 -0
  24. package/dist/runtime/MethodIdResolver.d.ts.map +1 -0
  25. package/dist/runtime/MethodIdResolver.js +91 -0
  26. package/dist/runtime/MethodIdResolver.js.map +1 -0
  27. package/dist/runtime/Runtime.d.ts +72 -0
  28. package/dist/runtime/Runtime.d.ts.map +1 -0
  29. package/dist/runtime/Runtime.js +231 -0
  30. package/dist/runtime/Runtime.js.map +1 -0
  31. package/dist/runtime/RuntimeEnvironment.d.ts +10 -0
  32. package/dist/runtime/RuntimeEnvironment.d.ts.map +1 -0
  33. package/dist/runtime/RuntimeEnvironment.js +2 -0
  34. package/dist/runtime/RuntimeEnvironment.js.map +1 -0
  35. package/dist/runtime/RuntimeModule.d.ts +37 -0
  36. package/dist/runtime/RuntimeModule.d.ts.map +1 -0
  37. package/dist/runtime/RuntimeModule.js +80 -0
  38. package/dist/runtime/RuntimeModule.js.map +1 -0
  39. package/dist/state/InMemoryStateService.d.ts +15 -0
  40. package/dist/state/InMemoryStateService.d.ts.map +1 -0
  41. package/dist/state/InMemoryStateService.js +24 -0
  42. package/dist/state/InMemoryStateService.js.map +1 -0
  43. package/dist/state/decorator.d.ts +7 -0
  44. package/dist/state/decorator.d.ts.map +1 -0
  45. package/dist/state/decorator.js +40 -0
  46. package/dist/state/decorator.js.map +1 -0
  47. package/jest.config.cjs +12 -0
  48. package/package.json +35 -0
  49. package/src/factories/MethodIdFactory.ts +13 -0
  50. package/src/index.ts +10 -0
  51. package/src/method/MethodParameterEncoder.ts +260 -0
  52. package/src/method/runtimeMethod.ts +308 -0
  53. package/src/module/decorator.ts +21 -0
  54. package/src/runtime/MethodIdResolver.ts +108 -0
  55. package/src/runtime/Runtime.ts +395 -0
  56. package/src/runtime/RuntimeEnvironment.ts +16 -0
  57. package/src/runtime/RuntimeModule.ts +112 -0
  58. package/src/state/InMemoryStateService.ts +25 -0
  59. package/src/state/decorator.ts +61 -0
  60. package/test/Runtime.test.ts +70 -0
  61. package/test/TestingRuntime.ts +45 -0
  62. package/test/method/MethodParameterEncoder.test.ts +121 -0
  63. package/test/method/runtimeMethod-fail.test.ts +50 -0
  64. package/test/method/runtimeMethod.test.ts +46 -0
  65. package/test/modules/Admin.ts +19 -0
  66. package/test/modules/Balances.test.ts +337 -0
  67. package/test/modules/Balances.ts +54 -0
  68. package/test/modules/MethodIdResolver.test.ts +73 -0
  69. package/test/modules/State.test.ts +81 -0
  70. package/test/runtimeMethod.test.ts +215 -0
  71. package/test/tsconfig.json +7 -0
  72. package/tsconfig.json +8 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Runtime.js","sourceRoot":"","sources":["../../src/runtime/Runtime.ts"],"names":[],"mappings":";;;;;;;;;;AAAA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QACzC,MAAM,MAAM,GAAG,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC;QAExC,yEAAyE;QACzE,MAAM,MAAM,GAAI,MAAc,CAAC,UAAU,CAAC,CAAC;QAC3C,IAAI,MAAM,KAAK,SAAS,EAAE;YACxB,MAAM,MAAM,CAAC,cAAc,CAAC,GAAG,UAAU,IAAI,UAAU,EAAE,CAAC,CAAC;SAC5D;QAED,yEAAyE;QACzE,OAAQ,MAAmD,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IAC3E,CAAC;IAED;;;;;;OAMG;IACI,cAAc,CACnB,UAAgC,EAChC,eAA4D;QAE5D,eAAe,CAAC,IAAI,GAAG,UAAU,CAAC;QAClC,eAAe,CAAC,OAAO,GAAG,IAAI,CAAC;QAE/B,KAAK,CAAC,cAAc,CAAC,UAAU,EAAE,eAAe,CAAC,CAAC;IACpD,CAAC;IAED;;OAEG;IACH,IAAW,kBAAkB;QAC3B,OAAO,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;IAC9C,CAAC;IAEM,KAAK,CAAC,OAAO,CAAC,QAAyB;QAC5C,MAAM,OAAO,GAAG,SAAS,CAAC,OAAO,CAAC,6BAA6B,CAAC,CAAC;QACjE,OAAO,CAAC,KAAK,CAAC;YACZ,WAAW,EAAE,kBAAkB,CAAC,gBAAgB,EAAE;YAClD,YAAY,EAAE,YAAY,CAAC,KAAK,EAAE;SACnC,CAAC,CAAC;QACH,OAAO,MAAM,IAAI,CAAC,cAAc,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;IACrD,CAAC;CACF,CAAA;AA5HY,OAAO;IADnB,UAAU,EAAE;;GACA,OAAO,CA4HnB;AACD,iGAAiG"}
@@ -0,0 +1,10 @@
1
+ import { AreProofsEnabled, WithZkProgrammable } from "@proto-kit/common";
2
+ import { MethodPublicOutput, SimpleAsyncStateService, StateServiceProvider } from "@proto-kit/protocol";
3
+ import { MethodIdResolver } from "./MethodIdResolver";
4
+ export interface RuntimeEnvironment extends WithZkProgrammable<undefined, MethodPublicOutput> {
5
+ get areProofsEnabled(): AreProofsEnabled | undefined;
6
+ get stateService(): SimpleAsyncStateService;
7
+ get stateServiceProvider(): StateServiceProvider;
8
+ get methodIdResolver(): MethodIdResolver;
9
+ }
10
+ //# sourceMappingURL=RuntimeEnvironment.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"RuntimeEnvironment.d.ts","sourceRoot":"","sources":["../../src/runtime/RuntimeEnvironment.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AACzE,OAAO,EACL,kBAAkB,EAClB,uBAAuB,EACvB,oBAAoB,EACrB,MAAM,qBAAqB,CAAC;AAE7B,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAEtD,MAAM,WAAW,kBACf,SAAQ,kBAAkB,CAAC,SAAS,EAAE,kBAAkB,CAAC;IACzD,IAAI,gBAAgB,IAAI,gBAAgB,GAAG,SAAS,CAAC;IACrD,IAAI,YAAY,IAAI,uBAAuB,CAAC;IAC5C,IAAI,oBAAoB,IAAI,oBAAoB,CAAC;IACjD,IAAI,gBAAgB,IAAI,gBAAgB,CAAC;CAC1C"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=RuntimeEnvironment.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"RuntimeEnvironment.js","sourceRoot":"","sources":["../../src/runtime/RuntimeEnvironment.ts"],"names":[],"mappings":""}
@@ -0,0 +1,37 @@
1
+ import { ConfigurableModule, NoConfig, Presets } from "@proto-kit/common";
2
+ import { NetworkState, RuntimeTransaction, RuntimeMethodExecutionData } from "@proto-kit/protocol";
3
+ import { FlexibleProvablePure, Provable, Bool } from "o1js";
4
+ import { RuntimeEnvironment } from "./RuntimeEnvironment";
5
+ type EventRecord = Record<string, FlexibleProvablePure<any>>;
6
+ type InferProvable<T extends FlexibleProvablePure<any>> = T extends Provable<infer U> ? U : never;
7
+ export declare class RuntimeEvents<Events extends EventRecord> {
8
+ private readonly events;
9
+ constructor(events: Events);
10
+ emitIf<Key extends keyof Events>(condition: Bool, eventName: Key, event: InferProvable<Events[Key]>): void;
11
+ emit<Key extends keyof Events>(eventName: Key, event: InferProvable<Events[Key]>): void;
12
+ }
13
+ /**
14
+ * Base class for runtime modules providing the necessary utilities.
15
+ */
16
+ export declare class RuntimeModule<Config = NoConfig> extends ConfigurableModule<Config> {
17
+ static presets: Presets<unknown>;
18
+ /**
19
+ * Holds all method names that are callable throw transactions
20
+ */
21
+ readonly runtimeMethodNames: string[];
22
+ /**
23
+ * This property exists only to typecheck that the RuntimeModule
24
+ * was extended correctly in e.g. a decorator. We need at least
25
+ * one non-optional property in this class to make the typechecking work.
26
+ */
27
+ isRuntimeModule: boolean;
28
+ name?: string;
29
+ runtime?: RuntimeEnvironment;
30
+ events?: RuntimeEvents<any>;
31
+ constructor();
32
+ getInputs(): RuntimeMethodExecutionData;
33
+ get transaction(): RuntimeTransaction;
34
+ get network(): NetworkState;
35
+ }
36
+ export {};
37
+ //# sourceMappingURL=RuntimeModule.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"RuntimeModule.d.ts","sourceRoot":"","sources":["../../src/runtime/RuntimeModule.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,mBAAmB,CAAC;AAE1E,OAAO,EACL,YAAY,EACZ,kBAAkB,EAElB,0BAA0B,EAE3B,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,oBAAoB,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAI5D,OAAO,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAM1D,KAAK,WAAW,GAAG,MAAM,CAAC,MAAM,EAAE,oBAAoB,CAAC,GAAG,CAAC,CAAC,CAAC;AAE7D,KAAK,aAAa,CAAC,CAAC,SAAS,oBAAoB,CAAC,GAAG,CAAC,IACpD,CAAC,SAAS,QAAQ,CAAC,MAAM,CAAC,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;AAE1C,qBAAa,aAAa,CAAC,MAAM,SAAS,WAAW;IAChC,OAAO,CAAC,QAAQ,CAAC,MAAM;gBAAN,MAAM,EAAE,MAAM;IAE3C,MAAM,CAAC,GAAG,SAAS,MAAM,MAAM,EACpC,SAAS,EAAE,IAAI,EACf,SAAS,EAAE,GAAG,EACd,KAAK,EAAE,aAAa,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;IAgB5B,IAAI,CAAC,GAAG,SAAS,MAAM,MAAM,EAClC,SAAS,EAAE,GAAG,EACd,KAAK,EAAE,aAAa,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;CAIpC;AAED;;GAEG;AACH,qBACa,aAAa,CACxB,MAAM,GAAG,QAAQ,CACjB,SAAQ,kBAAkB,CAAC,MAAM,CAAC;IAClC,OAAc,OAAO,EAAE,OAAO,CAAC,OAAO,CAAC,CAAM;IAE7C;;OAEG;IACH,SAAgB,kBAAkB,EAAE,MAAM,EAAE,CAAM;IAElD;;;;OAIG;IACI,eAAe,UAAQ;IAEvB,IAAI,CAAC,EAAE,MAAM,CAAC;IAEd,OAAO,CAAC,EAAE,kBAAkB,CAAC;IAE7B,MAAM,CAAC,EAAE,aAAa,CAAC,GAAG,CAAC,CAAa;;IAYxC,SAAS,IAAI,0BAA0B;IAa9C,IAAW,WAAW,IAAI,kBAAkB,CAE3C;IAED,IAAW,OAAO,IAAI,YAAY,CAEjC;CACF"}
@@ -0,0 +1,80 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __metadata = (this && this.__metadata) || function (k, v) {
8
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
+ };
10
+ import { ConfigurableModule } from "@proto-kit/common";
11
+ import { container, injectable } from "tsyringe";
12
+ import { RuntimeMethodExecutionContext, RuntimeMethodExecutionDataStruct, } from "@proto-kit/protocol";
13
+ import { Provable, Bool } from "o1js";
14
+ import { runtimeMethodNamesMetadataKey } from "../method/runtimeMethod";
15
+ const errors = {
16
+ inputDataNotSet: () => new Error("Input data for runtime execution not set"),
17
+ };
18
+ export class RuntimeEvents {
19
+ constructor(events) {
20
+ this.events = events;
21
+ }
22
+ emitIf(condition, eventName, event) {
23
+ if (this.events === undefined) {
24
+ throw new Error("'events' property not defined, make sure to define the event types on your runtimemodule");
25
+ }
26
+ const eventType = this.events[eventName];
27
+ if (typeof eventName !== "string") {
28
+ throw new Error("Only string");
29
+ }
30
+ return container
31
+ .resolve(RuntimeMethodExecutionContext)
32
+ .addEvent(eventType, event, eventName, condition);
33
+ }
34
+ emit(eventName, event) {
35
+ this.emitIf(Bool(true), eventName, event);
36
+ }
37
+ }
38
+ /**
39
+ * Base class for runtime modules providing the necessary utilities.
40
+ */
41
+ export let RuntimeModule = class RuntimeModule extends ConfigurableModule {
42
+ constructor() {
43
+ super();
44
+ /**
45
+ * Holds all method names that are callable throw transactions
46
+ */
47
+ this.runtimeMethodNames = [];
48
+ /**
49
+ * This property exists only to typecheck that the RuntimeModule
50
+ * was extended correctly in e.g. a decorator. We need at least
51
+ * one non-optional property in this class to make the typechecking work.
52
+ */
53
+ this.isRuntimeModule = true;
54
+ this.events = undefined;
55
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
56
+ const methodNames = Reflect.getMetadata(runtimeMethodNamesMetadataKey, this);
57
+ this.runtimeMethodNames = methodNames ?? [];
58
+ }
59
+ getInputs() {
60
+ return Provable.witness(RuntimeMethodExecutionDataStruct, () => {
61
+ const { input } = container.resolve(RuntimeMethodExecutionContext);
62
+ if (input === undefined) {
63
+ throw errors.inputDataNotSet();
64
+ }
65
+ return input;
66
+ });
67
+ }
68
+ get transaction() {
69
+ return this.getInputs().transaction;
70
+ }
71
+ get network() {
72
+ return this.getInputs().networkState;
73
+ }
74
+ };
75
+ RuntimeModule.presets = {};
76
+ RuntimeModule = __decorate([
77
+ injectable(),
78
+ __metadata("design:paramtypes", [])
79
+ ], RuntimeModule);
80
+ //# sourceMappingURL=RuntimeModule.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"RuntimeModule.js","sourceRoot":"","sources":["../../src/runtime/RuntimeModule.ts"],"names":[],"mappings":";;;;;;;;;AAAA,OAAO,EAAE,kBAAkB,EAAqB,MAAM,mBAAmB,CAAC;AAC1E,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,UAAU,CAAC;AACjD,OAAO,EAGL,6BAA6B,EAE7B,gCAAgC,GACjC,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAwB,QAAQ,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAE5D,OAAO,EAAE,6BAA6B,EAAE,MAAM,yBAAyB,CAAC;AAIxE,MAAM,MAAM,GAAG;IACb,eAAe,EAAE,GAAG,EAAE,CAAC,IAAI,KAAK,CAAC,0CAA0C,CAAC;CAC7E,CAAC;AAOF,MAAM,OAAO,aAAa;IACxB,YAAoC,MAAc;QAAd,WAAM,GAAN,MAAM,CAAQ;IAAG,CAAC;IAE/C,MAAM,CACX,SAAe,EACf,SAAc,EACd,KAAiC;QAEjC,IAAI,IAAI,CAAC,MAAM,KAAK,SAAS,EAAE;YAC7B,MAAM,IAAI,KAAK,CACb,0FAA0F,CAC3F,CAAC;SACH;QACD,MAAM,SAAS,GAA8B,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,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;;AAjDa,qBAAO,GAAqB,EAAE,AAAvB,CAAwB;AAHlC,aAAa;IADzB,UAAU,EAAE;;GACA,aAAa,CAqDzB"}
@@ -0,0 +1,15 @@
1
+ import { Field } from "o1js";
2
+ import { SimpleAsyncStateService } from "@proto-kit/protocol";
3
+ /**
4
+ * Naive implementation of an in-memory variant of the StateService interface
5
+ */
6
+ export declare class InMemoryStateService implements SimpleAsyncStateService {
7
+ /**
8
+ * This mapping container null values if the specific entry has been deleted.
9
+ * This is used by the CachedState service to keep track of deletions
10
+ */
11
+ values: Record<string, Field[] | null>;
12
+ get(key: Field): Promise<Field[] | undefined>;
13
+ set(key: Field, value: Field[] | undefined): Promise<void>;
14
+ }
15
+ //# sourceMappingURL=InMemoryStateService.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"InMemoryStateService.d.ts","sourceRoot":"","sources":["../../src/state/InMemoryStateService.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,MAAM,CAAC;AAC7B,OAAO,EAAE,uBAAuB,EAAE,MAAM,qBAAqB,CAAC;AAE9D;;GAEG;AACH,qBAAa,oBAAqB,YAAW,uBAAuB;IAClE;;;OAGG;IACI,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,KAAK,EAAE,GAAG,IAAI,CAAC,CAAM;IAEtC,GAAG,CAAC,GAAG,EAAE,KAAK,GAAG,OAAO,CAAC,KAAK,EAAE,GAAG,SAAS,CAAC;IAI7C,GAAG,CAAC,GAAG,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,GAAG,SAAS;CAOxD"}
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Naive implementation of an in-memory variant of the StateService interface
3
+ */
4
+ export class InMemoryStateService {
5
+ constructor() {
6
+ /**
7
+ * This mapping container null values if the specific entry has been deleted.
8
+ * This is used by the CachedState service to keep track of deletions
9
+ */
10
+ this.values = {};
11
+ }
12
+ async get(key) {
13
+ return this.values[key.toString()] ?? undefined;
14
+ }
15
+ async set(key, value) {
16
+ if (value === undefined) {
17
+ this.values[key.toString()] = null;
18
+ }
19
+ else {
20
+ this.values[key.toString()] = value;
21
+ }
22
+ }
23
+ }
24
+ //# sourceMappingURL=InMemoryStateService.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"InMemoryStateService.js","sourceRoot":"","sources":["../../src/state/InMemoryStateService.ts"],"names":[],"mappings":"AAGA;;GAEG;AACH,MAAM,OAAO,oBAAoB;IAAjC;QACE;;;WAGG;QACI,WAAM,GAAmC,EAAE,CAAC;IAarD,CAAC;IAXQ,KAAK,CAAC,GAAG,CAAC,GAAU;QACzB,OAAO,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,QAAQ,EAAE,CAAC,IAAI,SAAS,CAAC;IAClD,CAAC;IAEM,KAAK,CAAC,GAAG,CAAC,GAAU,EAAE,KAA0B;QACrD,IAAI,KAAK,KAAK,SAAS,EAAE;YACvB,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,QAAQ,EAAE,CAAC,GAAG,IAAI,CAAC;SACpC;aAAM;YACL,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,QAAQ,EAAE,CAAC,GAAG,KAAK,CAAC;SACrC;IACH,CAAC;CACF"}
@@ -0,0 +1,7 @@
1
+ import type { RuntimeModule } from "../runtime/RuntimeModule.js";
2
+ /**
3
+ * Decorates a runtime module property as state, passing down some
4
+ * underlying values to improve developer experience.
5
+ */
6
+ export declare function state(): <TargetRuntimeModule extends RuntimeModule<unknown>>(target: TargetRuntimeModule, propertyKey: string) => void;
7
+ //# sourceMappingURL=decorator.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"decorator.d.ts","sourceRoot":"","sources":["../../src/state/decorator.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAC;AAgBjE;;;GAGG;AACH,wBAAgB,KAAK,mGAGJ,MAAM,UAmCtB"}
@@ -0,0 +1,40 @@
1
+ import { Path } from "@proto-kit/protocol";
2
+ const errors = {
3
+ missingName: (className) => new Error(`Unable to provide a unique identifier for state, ${className} is missing a name.
4
+ Did you forget to extend your runtime module with 'extends RuntimeModule'?`),
5
+ missingRuntime: (className) => new Error(`Unable to provide 'runtime' for state, ${className} is missing a name.
6
+ Did you forget to extend your runtime module with 'extends RuntimeModule'?`),
7
+ };
8
+ /**
9
+ * Decorates a runtime module property as state, passing down some
10
+ * underlying values to improve developer experience.
11
+ */
12
+ export function state() {
13
+ return (target, propertyKey) => {
14
+ let value;
15
+ Object.defineProperty(target, propertyKey, {
16
+ enumerable: true,
17
+ get: function get() {
18
+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
19
+ const self = this;
20
+ if (self.name === undefined) {
21
+ throw errors.missingName(self.constructor.name);
22
+ }
23
+ if (!self.runtime) {
24
+ throw errors.missingRuntime(self.constructor.name);
25
+ }
26
+ const path = Path.fromProperty(self.name, propertyKey);
27
+ if (value) {
28
+ value.path = path;
29
+ // TODO: why is this complaining about `any`?
30
+ value.stateServiceProvider = self.runtime.stateServiceProvider;
31
+ }
32
+ return value;
33
+ },
34
+ set: (newValue) => {
35
+ value = newValue;
36
+ },
37
+ });
38
+ };
39
+ }
40
+ //# sourceMappingURL=decorator.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"decorator.js","sourceRoot":"","sources":["../../src/state/decorator.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAS,MAAM,qBAAqB,CAAC;AAIlD,MAAM,MAAM,GAAG;IACb,WAAW,EAAE,CAAC,SAAiB,EAAE,EAAE,CACjC,IAAI,KAAK,CACP,oDAAoD,SAAS;iFACc,CAC5E;IAEH,cAAc,EAAE,CAAC,SAAiB,EAAE,EAAE,CACpC,IAAI,KAAK,CACP,0CAA0C,SAAS;iFACwB,CAC5E;CACJ,CAAC;AAEF;;;GAGG;AACH,MAAM,UAAU,KAAK;IACnB,OAAO,CACL,MAA2B,EAC3B,WAAmB,EACnB,EAAE;QACF,IAAI,KAAiC,CAAC;QAEtC,MAAM,CAAC,cAAc,CAAC,MAAM,EAAE,WAAW,EAAE;YACzC,UAAU,EAAE,IAAI;YAEhB,GAAG,EAAE,SAAS,GAAG;gBACf,yEAAyE;gBACzE,MAAM,IAAI,GAAG,IAA2B,CAAC;gBAEzC,IAAI,IAAI,CAAC,IAAI,KAAK,SAAS,EAAE;oBAC3B,MAAM,MAAM,CAAC,WAAW,CAAC,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC;iBACjD;gBAED,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE;oBACjB,MAAM,MAAM,CAAC,cAAc,CAAC,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC;iBACpD;gBAED,MAAM,IAAI,GAAG,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,IAAI,EAAE,WAAW,CAAC,CAAC;gBACvD,IAAI,KAAK,EAAE;oBACT,KAAK,CAAC,IAAI,GAAG,IAAI,CAAC;oBAElB,6CAA6C;oBAE7C,KAAK,CAAC,oBAAoB,GAAG,IAAI,CAAC,OAAO,CAAC,oBAAoB,CAAC;iBAChE;gBACD,OAAO,KAAK,CAAC;YACf,CAAC;YAED,GAAG,EAAE,CAAC,QAAwB,EAAE,EAAE;gBAChC,KAAK,GAAG,QAAQ,CAAC;YACnB,CAAC;SACF,CAAC,CAAC;IACL,CAAC,CAAC;AACJ,CAAC"}
@@ -0,0 +1,12 @@
1
+ // @ts-ignore
2
+ const config = require("../../jest.config.cjs");
3
+
4
+ module.exports = {
5
+ ...config,
6
+ collectCoverageFrom: [
7
+ "packages/module/src/**",
8
+ "!**/node_modules/**",
9
+ "!**/dist/**",
10
+ ],
11
+ coverageDirectory: "coverage/module",
12
+ };
package/package.json ADDED
@@ -0,0 +1,35 @@
1
+ {
2
+ "name": "@proto-kit/module",
3
+ "license": "MIT",
4
+ "private": false,
5
+ "version": "0.1.1-develop.0+19469b2",
6
+ "type": "module",
7
+ "scripts": {
8
+ "build": "tsc -p tsconfig.json",
9
+ "dev": "tsc -p tsconfig.json --watch",
10
+ "lint": "eslint ./src ./test",
11
+ "test:file": "node --experimental-vm-modules --experimental-wasm-modules ../../node_modules/jest/bin/jest.js",
12
+ "test": "npm run test:file -- ./test/**",
13
+ "test:watch": "npm run test:file -- ./test/** --watch"
14
+ },
15
+ "main": "dist/index.js",
16
+ "publishConfig": {
17
+ "access": "public"
18
+ },
19
+ "dependencies": {
20
+ "lodash": "^4.17.21",
21
+ "loglevel": "^1.8.1",
22
+ "reflect-metadata": "^0.1.13"
23
+ },
24
+ "devDependencies": {
25
+ "@jest/globals": "^29.5.0",
26
+ "@types/lodash": "^4.14.194"
27
+ },
28
+ "peerDependencies": {
29
+ "@proto-kit/common": "*",
30
+ "@proto-kit/protocol": "*",
31
+ "o1js": "^1.6.0",
32
+ "tsyringe": "^4.7.0"
33
+ },
34
+ "gitHead": "19469b285cd6953e6c621875d789959b521842c3"
35
+ }
@@ -0,0 +1,13 @@
1
+ import { DependencyFactory, DependencyRecord } from "@proto-kit/common";
2
+
3
+ import { MethodIdResolver } from "../runtime/MethodIdResolver";
4
+
5
+ export class MethodIdFactory implements DependencyFactory {
6
+ public dependencies() {
7
+ return {
8
+ methodIdResolver: {
9
+ useClass: MethodIdResolver,
10
+ },
11
+ } satisfies DependencyRecord;
12
+ }
13
+ }
package/src/index.ts ADDED
@@ -0,0 +1,10 @@
1
+ export * from "./method/runtimeMethod";
2
+ export * from "./module/decorator";
3
+ export * from "./runtime/RuntimeModule";
4
+ export * from "./runtime/RuntimeEnvironment";
5
+ export * from "./runtime/Runtime";
6
+ export * from "./state/InMemoryStateService";
7
+ export * from "./state/decorator";
8
+ export * from "./method/MethodParameterEncoder";
9
+ export * from "./runtime/MethodIdResolver";
10
+ export * from "./factories/MethodIdFactory";
@@ -0,0 +1,260 @@
1
+ /* eslint-disable @typescript-eslint/consistent-type-assertions */
2
+ import {
3
+ Field,
4
+ Proof,
5
+ Provable,
6
+ DynamicProof,
7
+ FlexibleProvablePure,
8
+ } from "o1js";
9
+ import {
10
+ ArgumentTypes,
11
+ ProofTypes,
12
+ ToFieldableStatic,
13
+ TypedClass,
14
+ filterNonUndefined,
15
+ } from "@proto-kit/common";
16
+
17
+ import type { RuntimeModule } from "../runtime/RuntimeModule";
18
+
19
+ const errors = {
20
+ fieldLengthNotMatching: (expected: number, actual: number) =>
21
+ new Error(`Expected ${expected} field elements, got ${actual}`),
22
+
23
+ typeNotCompatible: (name: string, error?: string) =>
24
+ new Error(
25
+ `Cannot decode type ${name}, it has to be either a Struct, CircuitValue or built-in snarkyjs type.${
26
+ error !== undefined ? `Caused by: ${error}` : ""
27
+ }`
28
+ ),
29
+ };
30
+
31
+ type ArgumentType =
32
+ | FlexibleProvablePure<any>
33
+ | typeof Proof<unknown, unknown>
34
+ | typeof DynamicProof<unknown, unknown>;
35
+
36
+ type ArgTypeArray = ArgumentType[];
37
+
38
+ type ArgArray = ArgumentTypes[];
39
+
40
+ function isProofType(type: unknown): type is typeof Proof {
41
+ return (type as unknown as TypedClass<unknown>).prototype instanceof Proof;
42
+ }
43
+
44
+ function isDynamicProofType(type: unknown): type is typeof DynamicProof {
45
+ return (
46
+ (type as unknown as TypedClass<unknown>).prototype instanceof DynamicProof
47
+ );
48
+ }
49
+
50
+ function isProofBaseType(
51
+ type: unknown
52
+ ): type is typeof Proof | typeof DynamicProof {
53
+ return isProofType(type) || isDynamicProofType(type);
54
+ }
55
+
56
+ function getAllPropertyNamesOfPrototypeChain(type: unknown): string[] {
57
+ if (type === undefined || type === null) {
58
+ return [];
59
+ }
60
+ return Object.getOwnPropertyNames(type).concat(
61
+ ...getAllPropertyNamesOfPrototypeChain(Object.getPrototypeOf(type))
62
+ );
63
+ }
64
+
65
+ export function isFlexibleProvablePure(
66
+ type: unknown
67
+ ): type is FlexibleProvablePure<unknown> {
68
+ // The required properties are defined on the prototype for Structs and CircuitValues
69
+ // but on the constructor function itself for Field and Bool
70
+ // For aliases like Balance in library, it can even be 2 steps upwards the prototype chain
71
+ const props = getAllPropertyNamesOfPrototypeChain(type);
72
+ const mandatory = ["toFields", "fromFields", "sizeInFields"];
73
+ return mandatory.every((prop) => props.includes(prop));
74
+ }
75
+
76
+ export function checkArgsProvable(
77
+ target: RuntimeModule<unknown>,
78
+ methodName: string
79
+ ) {
80
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
81
+ const paramtypes: ArgTypeArray = Reflect.getMetadata(
82
+ "design:paramtypes",
83
+ target,
84
+ methodName
85
+ );
86
+
87
+ if (paramtypes === undefined) {
88
+ throw new Error(
89
+ `Method with name ${methodName} doesn't exist on this module`
90
+ );
91
+ }
92
+
93
+ const indizes = paramtypes
94
+ .map((type, index) => {
95
+ if (isProofBaseType(type) || isFlexibleProvablePure(type)) {
96
+ return undefined;
97
+ }
98
+ return `${index}`;
99
+ })
100
+ .filter(filterNonUndefined);
101
+ if (indizes.length > 0) {
102
+ const indexString = indizes.reduce((a, b) => `${a}, ${b}`);
103
+ throw new Error(
104
+ `Not all arguments of method '${target.name}.${methodName}' are provable types or proofs (indizes: [${indexString}])`
105
+ );
106
+ }
107
+ return paramtypes;
108
+ }
109
+
110
+ export class MethodParameterEncoder {
111
+ public static fromMethod(target: RuntimeModule<unknown>, methodName: string) {
112
+ const paramtypes = checkArgsProvable(target, methodName);
113
+
114
+ return new MethodParameterEncoder(paramtypes);
115
+ }
116
+
117
+ public static fieldSize(type: ArgumentType): number | undefined {
118
+ if (isProofBaseType(type)) {
119
+ return (
120
+ (MethodParameterEncoder.fieldSize(type.publicInputType) ?? 0) +
121
+ (MethodParameterEncoder.fieldSize(type.publicOutputType) ?? 0)
122
+ );
123
+ }
124
+ // as any, since we shouldn't be using this workaround in the first place
125
+ return (type as FlexibleProvablePure<unknown>).sizeInFields();
126
+ }
127
+
128
+ public constructor(private readonly types: ArgTypeArray) {}
129
+
130
+ public decode(fields: Field[], auxiliary: string[]): Promise<ArgArray> {
131
+ if (fields.length < this.fieldSize()) {
132
+ throw errors.fieldLengthNotMatching(this.fieldSize(), fields.length);
133
+ }
134
+
135
+ let stack = fields.slice();
136
+ const auxiliaryStack = auxiliary.slice();
137
+
138
+ return Promise.all(
139
+ this.types.map((type) => {
140
+ const numberFieldsNeeded = MethodParameterEncoder.fieldSize(type) ?? -1;
141
+ if (numberFieldsNeeded === -1) {
142
+ throw errors.typeNotCompatible(type.constructor.name);
143
+ }
144
+ const structFields = stack.slice(0, numberFieldsNeeded);
145
+ stack = stack.slice(numberFieldsNeeded);
146
+
147
+ // Decode proof
148
+ if (isProofBaseType(type)) {
149
+ const auxiliaryData = auxiliaryStack.shift();
150
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
151
+ const proofData: { proof: string; maxProofsVerified: 0 | 1 | 2 } =
152
+ JSON.parse(auxiliaryData!);
153
+
154
+ const inputFieldSize = MethodParameterEncoder.fieldSize(
155
+ type.publicInputType
156
+ )!;
157
+ const input = structFields
158
+ .slice(0, inputFieldSize)
159
+ .map((x) => x.toString());
160
+ const output = structFields
161
+ .slice(inputFieldSize)
162
+ .map((x) => x.toString());
163
+
164
+ // fromJSON has incompatible signature for Proof and DynamicProof
165
+ if (isProofType(type)) {
166
+ return type.fromJSON({
167
+ ...proofData,
168
+ publicInput: input,
169
+ publicOutput: output,
170
+ });
171
+ }
172
+ if (isDynamicProofType(type)) {
173
+ return type.fromJSON({
174
+ ...proofData,
175
+ publicInput: input,
176
+ publicOutput: output,
177
+ });
178
+ }
179
+ }
180
+
181
+ return (type as FlexibleProvablePure<unknown>).fromFields(
182
+ structFields
183
+ ) as any;
184
+ })
185
+ );
186
+ }
187
+
188
+ /**
189
+ * Variant of encode() for provable code that skips the unprovable
190
+ * json encoding
191
+ */
192
+ public encode(args: ArgumentTypes) {
193
+ /**
194
+ * Use the type info obtained previously to convert
195
+ * the args passed to fields
196
+ */
197
+ return args
198
+ .map((argument, index) => {
199
+ if (argument instanceof Proof || argument instanceof DynamicProof) {
200
+ const argumentType = this.types[index] as ProofTypes;
201
+
202
+ const { publicOutputType, publicInputType } = argumentType;
203
+
204
+ const inputFields =
205
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
206
+ publicInputType?.toFields(argument.publicInput as any) ?? [];
207
+
208
+ const outputFields =
209
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
210
+ publicOutputType?.toFields(argument.publicOutput as any) ?? [];
211
+
212
+ let auxiliary = "";
213
+
214
+ // Has to be asProver, because this function will be called by runtimeMethod
215
+ // to transform the args into a Field[] to compute the argsHash
216
+ // In this case, the auxiliary might be empty, but it isn't used by that method anyways
217
+ Provable.asProver(() => {
218
+ const jsonProof = argument.toJSON();
219
+ auxiliary = JSON.stringify({
220
+ proof: jsonProof.proof,
221
+ maxProofsVerified: jsonProof.maxProofsVerified,
222
+ });
223
+ });
224
+
225
+ return {
226
+ fields: [...inputFields, ...outputFields],
227
+ auxiliary,
228
+ };
229
+ }
230
+
231
+ const argumentType = this.types[index] as ToFieldableStatic;
232
+ return {
233
+ fields: argumentType.toFields(argument),
234
+ auxiliary: undefined,
235
+ };
236
+ })
237
+ .reduce<{
238
+ fields: Field[];
239
+ auxiliary: string[];
240
+ }>(
241
+ (a, b) => {
242
+ return {
243
+ fields: [...a.fields, ...b.fields],
244
+ auxiliary:
245
+ b.auxiliary !== undefined
246
+ ? [...a.auxiliary, b.auxiliary]
247
+ : a.auxiliary,
248
+ };
249
+ },
250
+ { fields: [], auxiliary: [] }
251
+ );
252
+ }
253
+
254
+ public fieldSize(): number {
255
+ return this.types
256
+ .map((type) => MethodParameterEncoder.fieldSize(type) ?? 0)
257
+ .reduce((a, b) => a + b, 0);
258
+ }
259
+ }
260
+ /* eslint-enable @typescript-eslint/consistent-type-assertions */