@proto-kit/module 0.1.1-develop.153

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 (75) hide show
  1. package/LICENSE.md +201 -0
  2. package/README.md +114 -0
  3. package/dist/chain/Chain.d.ts +109 -0
  4. package/dist/chain/Chain.d.ts.map +1 -0
  5. package/dist/chain/Chain.js +229 -0
  6. package/dist/index.d.ts +13 -0
  7. package/dist/index.d.ts.map +1 -0
  8. package/dist/index.js +12 -0
  9. package/dist/method/MethodExecutionContext.d.ts +73 -0
  10. package/dist/method/MethodExecutionContext.d.ts.map +1 -0
  11. package/dist/method/MethodExecutionContext.js +112 -0
  12. package/dist/method/MethodParameterDecoder.d.ts +20 -0
  13. package/dist/method/MethodParameterDecoder.d.ts.map +1 -0
  14. package/dist/method/MethodParameterDecoder.js +30 -0
  15. package/dist/method/RuntimeMethodExecutionContext.d.ts +57 -0
  16. package/dist/method/RuntimeMethodExecutionContext.d.ts.map +1 -0
  17. package/dist/method/RuntimeMethodExecutionContext.js +92 -0
  18. package/dist/method/assert.d.ts +12 -0
  19. package/dist/method/assert.d.ts.map +1 -0
  20. package/dist/method/assert.js +20 -0
  21. package/dist/method/decorator.d.ts +45 -0
  22. package/dist/method/decorator.d.ts.map +1 -0
  23. package/dist/method/decorator.js +140 -0
  24. package/dist/method/runtimeMethod.d.ts +18 -0
  25. package/dist/method/runtimeMethod.d.ts.map +1 -0
  26. package/dist/method/runtimeMethod.js +114 -0
  27. package/dist/module/decorator.d.ts +8 -0
  28. package/dist/module/decorator.d.ts.map +1 -0
  29. package/dist/module/decorator.js +15 -0
  30. package/dist/runtime/Runtime.d.ts +71 -0
  31. package/dist/runtime/Runtime.d.ts.map +1 -0
  32. package/dist/runtime/Runtime.js +185 -0
  33. package/dist/runtime/RuntimeModule.d.ts +30 -0
  34. package/dist/runtime/RuntimeModule.d.ts.map +1 -0
  35. package/dist/runtime/RuntimeModule.js +44 -0
  36. package/dist/state/InMemoryStateService.d.ts +14 -0
  37. package/dist/state/InMemoryStateService.d.ts.map +1 -0
  38. package/dist/state/InMemoryStateService.js +21 -0
  39. package/dist/state/State.d.ts +65 -0
  40. package/dist/state/State.d.ts.map +1 -0
  41. package/dist/state/State.js +114 -0
  42. package/dist/state/StateMap.d.ts +37 -0
  43. package/dist/state/StateMap.d.ts.map +1 -0
  44. package/dist/state/StateMap.js +56 -0
  45. package/dist/state/StateServiceProvider.d.ts +10 -0
  46. package/dist/state/StateServiceProvider.d.ts.map +1 -0
  47. package/dist/state/StateServiceProvider.js +34 -0
  48. package/dist/state/decorator.d.ts +7 -0
  49. package/dist/state/decorator.d.ts.map +1 -0
  50. package/dist/state/decorator.js +42 -0
  51. package/jest.config.cjs +1 -0
  52. package/package.json +36 -0
  53. package/src/index.ts +12 -0
  54. package/src/method/MethodParameterDecoder.ts +55 -0
  55. package/src/method/RuntimeMethodExecutionContext.ts +111 -0
  56. package/src/method/assert.test.ts +49 -0
  57. package/src/method/assert.ts +23 -0
  58. package/src/method/decorator.test.ts +46 -0
  59. package/src/method/runtimeMethod.ts +192 -0
  60. package/src/module/decorator.ts +21 -0
  61. package/src/runtime/Runtime.ts +304 -0
  62. package/src/runtime/RuntimeModule.ts +68 -0
  63. package/src/state/InMemoryStateService.ts +29 -0
  64. package/src/state/State.ts +154 -0
  65. package/src/state/StateMap.ts +69 -0
  66. package/src/state/StateServiceProvider.ts +24 -0
  67. package/src/state/decorator.ts +65 -0
  68. package/test/Runtime.test.ts +37 -0
  69. package/test/modules/Admin.ts +19 -0
  70. package/test/modules/Balances.test.ts +340 -0
  71. package/test/modules/Balances.ts +51 -0
  72. package/test/runtimeMethod.test.ts +43 -0
  73. package/test/transaction.test.ts +82 -0
  74. package/tsconfig.json +8 -0
  75. package/tsconfig.test.json +9 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runtimeMethod.d.ts","sourceRoot":"","sources":["../../src/method/runtimeMethod.ts"],"names":[],"mappings":"AAEA,OAAO,EACL,eAAe,EAGf,kBAAkB,EACnB,MAAM,qBAAqB,CAAC;AAG7B,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAC;AAcjE,wBAAgB,sBAAsB,CAEpC,gBAAgB,EAAE,eAAe,CAAC,GAAG,CAAC,EAAE,mDAczC;AAGD,MAAM,MAAM,aAAa,GAAG,CAAC,GAAG,IAAI,EAAE,OAAO,EAAE,KAAK,kBAAkB,CAAC;AAEvE,wBAAgB,eAAe,CAC7B,IAAI,EAAE,aAAa,CAAC,OAAO,CAAC,EAC5B,UAAU,EAAE,MAAM,EAClB,YAAY,EAAE,CAAC,GAAG,IAAI,EAAE,OAAO,EAAE,KAAK,OAAO,iBAoC9C;AAED,wBAAgB,iBAAiB,CAC/B,iBAAiB,EAAE,MAAM,EACzB,UAAU,EAAE,MAAM,UAGnB;AAED,eAAO,MAAM,wBAAwB,eAAe,CAAC;AAErD;;;;;;;GAOG;AACH,wBAAgB,eAAe,CAC7B,MAAM,EAAE,aAAa,CAAC,OAAO,CAAC,EAC9B,WAAW,EAAE,MAAM,WAKpB;AAED,wBAAgB,aAAa,aAEjB,cAAc,OAAO,CAAC,cAClB,MAAM,cACN,kBAAkB,UA2EjC"}
@@ -0,0 +1,114 @@
1
+ import { container } from "tsyringe";
2
+ import { DefaultProvableHashList, ProvableStateTransition, MethodPublicOutput, } from "@proto-kit/protocol";
3
+ import { toProver } from "@proto-kit/common";
4
+ import { RuntimeMethodExecutionContext } from "./RuntimeMethodExecutionContext.js";
5
+ const errors = {
6
+ runtimeNotProvided: (name) => new Error(`Runtime was not provided for module: ${name}`),
7
+ methodInputsNotProvided: () => new Error("Method execution inputs not provided, provide them via context.inputs"),
8
+ };
9
+ export function toStateTransitionsHash(
10
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
11
+ stateTransitions) {
12
+ const stateTransitionsHashList = new DefaultProvableHashList(ProvableStateTransition);
13
+ return stateTransitions
14
+ .map((stateTransition) => stateTransition.toProvable())
15
+ .reduce((allStateTransitionsHashList, stateTransition) => allStateTransitionsHashList.push(stateTransition), stateTransitionsHashList)
16
+ .toField();
17
+ }
18
+ export function toWrappedMethod(methodName, moduleMethod) {
19
+ const executionContext = container.resolve(RuntimeMethodExecutionContext);
20
+ const wrappedMethod = (...args) => {
21
+ Reflect.apply(moduleMethod, this, args);
22
+ const { result: { stateTransitions, status }, input, } = executionContext.current();
23
+ const stateTransitionsHash = toStateTransitionsHash(stateTransitions);
24
+ if (input === undefined) {
25
+ throw errors.methodInputsNotProvided();
26
+ }
27
+ const transactionHash = input.transaction.hash();
28
+ const networkStateHash = input.networkState.hash();
29
+ return new MethodPublicOutput({
30
+ stateTransitionsHash,
31
+ status,
32
+ transactionHash,
33
+ networkStateHash,
34
+ });
35
+ };
36
+ Object.defineProperty(wrappedMethod, "name", {
37
+ value: `wrapped_${methodName}`,
38
+ writable: false,
39
+ });
40
+ return wrappedMethod;
41
+ }
42
+ export function combineMethodName(runtimeModuleName, methodName) {
43
+ return `${runtimeModuleName}.${methodName}`;
44
+ }
45
+ export const runtimeMethodMetadataKey = "yab-method";
46
+ /**
47
+ * Checks the metadata of the provided runtime module and its method,
48
+ * to see if it has been decorated with @runtimeMethod()
49
+ *
50
+ * @param target - Runtime module to check
51
+ * @param propertyKey - Name of the method to check in the prior runtime module
52
+ * @returns - If the provided method name is a runtime method or not
53
+ */
54
+ export function isRuntimeMethod(target, propertyKey) {
55
+ return Boolean(Reflect.getMetadata(runtimeMethodMetadataKey, target, propertyKey));
56
+ }
57
+ export function runtimeMethod() {
58
+ return (target, methodName, descriptor) => {
59
+ const executionContext = container.resolve(RuntimeMethodExecutionContext);
60
+ Reflect.defineMetadata(runtimeMethodMetadataKey, true, target, methodName);
61
+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
62
+ const simulatedMethod = descriptor.value;
63
+ descriptor.value = function value(...args) {
64
+ const constructorName = this.constructor.name;
65
+ /**
66
+ * If its a top level method call, wrap it into a wrapped method,
67
+ * since it'll be turned into a real/mock prover in provableMethod().
68
+ *
69
+ * Otherwise provableMethod() will just call the originalMethod provided
70
+ * if method is not called at the top level.
71
+ */
72
+ const simulatedWrappedMethod = Reflect.apply(toWrappedMethod, this, [
73
+ methodName,
74
+ simulatedMethod,
75
+ ]);
76
+ /**
77
+ * Before the prover runs, make sure it is operating on the correct
78
+ * RuntimeMethodExecutionContext state, meaning it enters and exits
79
+ * the context properly.
80
+ */
81
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
82
+ async function prover() {
83
+ executionContext.beforeMethod(constructorName, methodName, args);
84
+ const innerProver = toProver(combineMethodName(constructorName, methodName), simulatedWrappedMethod, false, ...args).bind(this);
85
+ // eslint-disable-next-line @typescript-eslint/init-declarations
86
+ let result;
87
+ try {
88
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
89
+ result = await Reflect.apply(innerProver, this, args);
90
+ }
91
+ finally {
92
+ executionContext.afterMethod();
93
+ }
94
+ return result;
95
+ }
96
+ executionContext.beforeMethod(constructorName, methodName, args);
97
+ if (executionContext.isTopLevel) {
98
+ if (!this.runtime) {
99
+ throw errors.runtimeNotProvided(constructorName);
100
+ }
101
+ executionContext.setProver(prover.bind(this.runtime.zkProgrammable));
102
+ }
103
+ // eslint-disable-next-line @typescript-eslint/init-declarations
104
+ let result;
105
+ try {
106
+ result = Reflect.apply(simulatedMethod, this, args);
107
+ }
108
+ finally {
109
+ executionContext.afterMethod();
110
+ }
111
+ return result;
112
+ };
113
+ };
114
+ }
@@ -0,0 +1,8 @@
1
+ import { StaticConfigurableModule, TypedClass } from "@proto-kit/common";
2
+ import { RuntimeModule } from "../runtime/RuntimeModule.js";
3
+ /**
4
+ * Marks the decorated class as a runtime module, while also
5
+ * making it injectable with our dependency injection solution.
6
+ */
7
+ export declare function runtimeModule(): (target: StaticConfigurableModule<unknown> & TypedClass<RuntimeModule<unknown>>) => void;
8
+ //# sourceMappingURL=decorator.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"decorator.d.ts","sourceRoot":"","sources":["../../src/module/decorator.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,wBAAwB,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAEzE,OAAO,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAC;AAE5D;;;GAGG;AACH,wBAAgB,aAAa,aAMjB,yBAAyB,OAAO,CAAC,GACvC,WAAW,cAAc,OAAO,CAAC,CAAC,UAIvC"}
@@ -0,0 +1,15 @@
1
+ import { injectable } from "tsyringe";
2
+ /**
3
+ * Marks the decorated class as a runtime module, while also
4
+ * making it injectable with our dependency injection solution.
5
+ */
6
+ export function runtimeModule() {
7
+ return (
8
+ /**
9
+ * Check if the target class extends RuntimeModule, while
10
+ * also providing static config presets
11
+ */
12
+ target) => {
13
+ injectable()(target);
14
+ };
15
+ }
@@ -0,0 +1,71 @@
1
+ import { Experimental } from "snarkyjs";
2
+ import { DependencyContainer } from "tsyringe";
3
+ import { StringKeyOf, ModuleContainer, ModulesConfig, ModulesRecord, TypedClass, ZkProgrammable, PlainZkProgram, WithZkProgrammable, AreProofsEnabled } from "@proto-kit/common";
4
+ import { MethodPublicOutput } from "@proto-kit/protocol";
5
+ import { StateService } from "../state/InMemoryStateService.js";
6
+ import { StateServiceProvider } from "../state/StateServiceProvider";
7
+ import { RuntimeModule } from "./RuntimeModule.js";
8
+ /**
9
+ * Record of modules accepted by the Runtime module container.
10
+ *
11
+ * We have to use TypedClass since RuntimeModule
12
+ * is an abstract class
13
+ */
14
+ export type RuntimeModulesRecord = ModulesRecord<TypedClass<RuntimeModule<unknown>>>;
15
+ /**
16
+ * Definition / required arguments for the Runtime class
17
+ */
18
+ export interface RuntimeDefinition<Modules extends RuntimeModulesRecord> {
19
+ state: StateService;
20
+ modules: Modules;
21
+ config?: ModulesConfig<Modules>;
22
+ }
23
+ export declare class RuntimeZkProgrammable<Modules extends RuntimeModulesRecord> extends ZkProgrammable<undefined, MethodPublicOutput> {
24
+ runtime: Runtime<Modules>;
25
+ constructor(runtime: Runtime<Modules>);
26
+ get appChain(): AreProofsEnabled | undefined;
27
+ zkProgramFactory(): PlainZkProgram<undefined, MethodPublicOutput>;
28
+ }
29
+ /**
30
+ * Wrapper for an application specific runtime, which helps orchestrate
31
+ * runtime modules into an interoperable runtime.
32
+ */
33
+ export declare class Runtime<Modules extends RuntimeModulesRecord> extends ModuleContainer<Modules> implements WithZkProgrammable<undefined, MethodPublicOutput> {
34
+ static from<Modules extends RuntimeModulesRecord>(definition: RuntimeDefinition<Modules>): Runtime<Modules>;
35
+ program?: ReturnType<typeof Experimental.ZkProgram>;
36
+ definition: RuntimeDefinition<Modules>;
37
+ zkProgrammable: ZkProgrammable<undefined, MethodPublicOutput>;
38
+ private readonly stateServiceProviderInstance;
39
+ /**
40
+ * Creates a new Runtime from the provided config
41
+ *
42
+ * @param modules - Configuration object for the constructed Runtime
43
+ */
44
+ constructor(definition: RuntimeDefinition<Modules>);
45
+ get appChain(): AreProofsEnabled | undefined;
46
+ get stateService(): StateService;
47
+ get stateServiceProvider(): StateServiceProvider;
48
+ /**
49
+ * @returns The dependency injection container of this runtime
50
+ */
51
+ get dependencyContainer(): DependencyContainer;
52
+ /**
53
+ * @param methodId The encoded name of the method to call.
54
+ * Encoding: "stringToField(module.name) << 128 + stringToField(method-name)"
55
+ */
56
+ getMethodById(methodId: bigint): (...args: unknown[]) => unknown;
57
+ getMethodNameFromId(methodId: bigint): [string, string];
58
+ getMethodId(moduleName: string, methodName: string): bigint;
59
+ /**
60
+ * Add a name and other respective properties required by RuntimeModules,
61
+ * that come from the current Runtime
62
+ *
63
+ * @param name - Name of the runtime module to decorate
64
+ */
65
+ decorateModule(moduleName: StringKeyOf<Modules>, containedModule: InstanceType<Modules[StringKeyOf<Modules>]>): void;
66
+ /**
67
+ * @returns A list of names of all the registered module names
68
+ */
69
+ get runtimeModuleNames(): string[];
70
+ }
71
+ //# sourceMappingURL=Runtime.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Runtime.d.ts","sourceRoot":"","sources":["../../src/runtime/Runtime.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AACxC,OAAO,EAAE,mBAAmB,EAAc,MAAM,UAAU,CAAC;AAC3D,OAAO,EACL,WAAW,EACX,eAAe,EACf,aAAa,EACb,aAAa,EACb,UAAU,EACV,cAAc,EACd,cAAc,EACd,kBAAkB,EAClB,gBAAgB,EACjB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAGL,kBAAkB,EACnB,MAAM,qBAAqB,CAAC;AAQ7B,OAAO,EAAE,YAAY,EAAE,MAAM,kCAAkC,CAAC;AAChE,OAAO,EAAE,oBAAoB,EAAE,MAAM,+BAA+B,CAAC;AAErE,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAEnD;;;;;GAKG;AACH,MAAM,MAAM,oBAAoB,GAAG,aAAa,CAC9C,UAAU,CAAC,aAAa,CAAC,OAAO,CAAC,CAAC,CACnC,CAAC;AAOF;;GAEG;AACH,MAAM,WAAW,iBAAiB,CAAC,OAAO,SAAS,oBAAoB;IACrE,KAAK,EAAE,YAAY,CAAC;IACpB,OAAO,EAAE,OAAO,CAAC;IACjB,MAAM,CAAC,EAAE,aAAa,CAAC,OAAO,CAAC,CAAC;CACjC;AAED,qBAAa,qBAAqB,CAChC,OAAO,SAAS,oBAAoB,CACpC,SAAQ,cAAc,CAAC,SAAS,EAAE,kBAAkB,CAAC;IAE3B,OAAO,EAAE,OAAO,CAAC,OAAO,CAAC;gBAAzB,OAAO,EAAE,OAAO,CAAC,OAAO,CAAC;IAInD,IAAW,QAAQ,iCAElB;IAEM,gBAAgB,IAAI,cAAc,CAAC,SAAS,EAAE,kBAAkB,CAAC;CAgHzE;AAED;;;GAGG;AACH,qBACa,OAAO,CAAC,OAAO,SAAS,oBAAoB,CACvD,SAAQ,eAAe,CAAC,OAAO,CAC/B,YAAW,kBAAkB,CAAC,SAAS,EAAE,kBAAkB,CAAC;WAE9C,IAAI,CAAC,OAAO,SAAS,oBAAoB,EACrD,UAAU,EAAE,iBAAiB,CAAC,OAAO,CAAC;IAMjC,OAAO,CAAC,EAAE,UAAU,CAAC,OAAO,YAAY,CAAC,SAAS,CAAC,CAAC;IAEpD,UAAU,EAAE,iBAAiB,CAAC,OAAO,CAAC,CAAC;IAEvC,cAAc,EAAE,cAAc,CAAC,SAAS,EAAE,kBAAkB,CAAC,CAAC;IAIrE,OAAO,CAAC,QAAQ,CAAC,4BAA4B,CAE3C;IAEF;;;;OAIG;gBACgB,UAAU,EAAE,iBAAiB,CAAC,OAAO,CAAC;IASzD,IAAW,QAAQ,IAAI,gBAAgB,GAAG,SAAS,CAElD;IAED,IAAW,YAAY,IAAI,YAAY,CAEtC;IAED,IAAW,oBAAoB,IAAI,oBAAoB,CAEtD;IAED;;OAEG;IACH,IAAW,mBAAmB,IAAI,mBAAmB,CAEpD;IAED;;;OAGG;IACI,aAAa,CAAC,QAAQ,EAAE,MAAM,GAAG,CAAC,GAAG,IAAI,EAAE,OAAO,EAAE,KAAK,OAAO;IAiBhE,mBAAmB,CAAC,QAAQ,EAAE,MAAM,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC;IASvD,WAAW,CAAC,UAAU,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,GAAG,MAAM;IAQlE;;;;;OAKG;IACI,cAAc,CACnB,UAAU,EAAE,WAAW,CAAC,OAAO,CAAC,EAChC,eAAe,EAAE,YAAY,CAAC,OAAO,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC,CAAC;IAQ9D;;OAEG;IACH,IAAW,kBAAkB,aAE5B;CACF"}
@@ -0,0 +1,185 @@
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
+ var Runtime_1;
11
+ // eslint-disable-next-line max-len
12
+ /* eslint-disable @typescript-eslint/no-explicit-any,@typescript-eslint/no-unsafe-assignment */
13
+ import { Experimental } from "snarkyjs";
14
+ import { injectable } from "tsyringe";
15
+ import { ModuleContainer, ZkProgrammable, } from "@proto-kit/common";
16
+ import { fieldToString, stringToField, MethodPublicOutput, } from "@proto-kit/protocol";
17
+ import { combineMethodName, isRuntimeMethod, toWrappedMethod, } from "../method/runtimeMethod.js";
18
+ import { StateServiceProvider } from "../state/StateServiceProvider";
19
+ const errors = {
20
+ methodNotFound: (methodKey) => new Error(`Unable to find method with id ${methodKey}`),
21
+ };
22
+ export class RuntimeZkProgrammable extends ZkProgrammable {
23
+ // eslint-disable-next-line @typescript-eslint/no-use-before-define
24
+ constructor(runtime) {
25
+ super();
26
+ this.runtime = runtime;
27
+ }
28
+ get appChain() {
29
+ return this.runtime.appChain;
30
+ }
31
+ zkProgramFactory() {
32
+ // We need to use explicit type annotations here,
33
+ // therefore we can't use destructuring
34
+ // eslint-disable-next-line max-len
35
+ // eslint-disable-next-line @typescript-eslint/no-use-before-define,prefer-destructuring,putout/putout
36
+ const runtime = this.runtime;
37
+ const runtimeMethods = runtime.runtimeModuleNames.reduce((allMethods, runtimeModuleName) => {
38
+ runtime.isValidModuleName(runtime.definition.modules, runtimeModuleName);
39
+ /**
40
+ * Couldnt find a better way to circumvent the type assertion
41
+ * regarding resolving only known modules. We assert in the line above
42
+ * but we cast it to any anyways to satisfy the proof system.
43
+ */
44
+ // eslint-disable-next-line max-len
45
+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
46
+ const runtimeModule = runtime.resolve(runtimeModuleName);
47
+ // eslint-disable-next-line max-len
48
+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
49
+ const modulePrototype = Object.getPrototypeOf(runtimeModule);
50
+ const modulePrototypeMethods = Object.getOwnPropertyNames(modulePrototype);
51
+ const moduleMethods = modulePrototypeMethods.reduce((allModuleMethods, methodName) => {
52
+ if (isRuntimeMethod(runtimeModule, methodName)) {
53
+ const combinedMethodName = combineMethodName(runtimeModuleName, methodName);
54
+ const method = modulePrototype[methodName];
55
+ const wrappedMethod = Reflect.apply(toWrappedMethod, runtimeModule, [methodName, method]);
56
+ // eslint-disable-next-line no-warning-comments
57
+ // TODO: find out how to import the Tuple type
58
+ const privateInputs = Reflect.getMetadata("design:paramtypes", runtimeModule, methodName);
59
+ return {
60
+ ...allModuleMethods,
61
+ [combinedMethodName]: {
62
+ privateInputs,
63
+ method: wrappedMethod,
64
+ },
65
+ };
66
+ }
67
+ return allModuleMethods;
68
+ }, {});
69
+ return {
70
+ ...allMethods,
71
+ ...moduleMethods,
72
+ };
73
+ }, {});
74
+ const sortedRuntimeMethods = Object.fromEntries(
75
+ // eslint-disable-next-line @typescript-eslint/require-array-sort-compare
76
+ Object.entries(runtimeMethods).sort());
77
+ const program = Experimental.ZkProgram({
78
+ publicOutput: MethodPublicOutput,
79
+ methods: sortedRuntimeMethods,
80
+ });
81
+ const SelfProof = Experimental.ZkProgram.Proof(program);
82
+ const methods = Object.keys(sortedRuntimeMethods).reduce((boundMethods, methodName) => {
83
+ boundMethods[methodName] = program[methodName].bind(program);
84
+ return boundMethods;
85
+ }, {});
86
+ return {
87
+ compile: program.compile.bind(program),
88
+ verify: program.verify.bind(program),
89
+ Proof: SelfProof,
90
+ methods,
91
+ };
92
+ }
93
+ }
94
+ /**
95
+ * Wrapper for an application specific runtime, which helps orchestrate
96
+ * runtime modules into an interoperable runtime.
97
+ */
98
+ let Runtime = Runtime_1 = class Runtime extends ModuleContainer {
99
+ static from(definition) {
100
+ return new Runtime_1(definition);
101
+ }
102
+ /**
103
+ * Creates a new Runtime from the provided config
104
+ *
105
+ * @param modules - Configuration object for the constructed Runtime
106
+ */
107
+ constructor(definition) {
108
+ super(definition);
109
+ // eslint-disable-next-line no-warning-comments
110
+ // TODO DI
111
+ this.stateServiceProviderInstance = new StateServiceProvider(this.definition.state);
112
+ this.definition = definition;
113
+ this.zkProgrammable = new RuntimeZkProgrammable(this);
114
+ // this.registerValue({
115
+ // Runtime: this,
116
+ // });
117
+ }
118
+ get appChain() {
119
+ return this.container.resolve("AppChain");
120
+ }
121
+ get stateService() {
122
+ return this.stateServiceProviderInstance.stateService;
123
+ }
124
+ get stateServiceProvider() {
125
+ return this.stateServiceProviderInstance;
126
+ }
127
+ /**
128
+ * @returns The dependency injection container of this runtime
129
+ */
130
+ get dependencyContainer() {
131
+ return this.container;
132
+ }
133
+ /**
134
+ * @param methodId The encoded name of the method to call.
135
+ * Encoding: "stringToField(module.name) << 128 + stringToField(method-name)"
136
+ */
137
+ getMethodById(methodId) {
138
+ const [moduleName, methodName] = this.getMethodNameFromId(methodId);
139
+ this.isValidModuleName(this.definition.modules, moduleName);
140
+ const module = this.resolve(moduleName);
141
+ // eslint-disable-next-line max-len
142
+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions,@typescript-eslint/no-unsafe-member-access
143
+ const method = module[methodName];
144
+ if (method === undefined) {
145
+ throw errors.methodNotFound(`${moduleName}.${methodName}`);
146
+ }
147
+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
148
+ return method.bind(module);
149
+ }
150
+ getMethodNameFromId(methodId) {
151
+ // eslint-disable-next-line @typescript-eslint/no-magic-numbers
152
+ const moduleName = fieldToString(methodId >> 128n);
153
+ // eslint-disable-next-line @typescript-eslint/no-magic-numbers
154
+ const methodName = fieldToString(methodId % 2n ** 128n);
155
+ return [moduleName, methodName];
156
+ }
157
+ getMethodId(moduleName, methodName) {
158
+ return (
159
+ // eslint-disable-next-line @typescript-eslint/no-magic-numbers
160
+ (stringToField(moduleName).toBigInt() << 128n) +
161
+ stringToField(methodName).toBigInt());
162
+ }
163
+ /**
164
+ * Add a name and other respective properties required by RuntimeModules,
165
+ * that come from the current Runtime
166
+ *
167
+ * @param name - Name of the runtime module to decorate
168
+ */
169
+ decorateModule(moduleName, containedModule) {
170
+ containedModule.name = moduleName;
171
+ containedModule.runtime = this;
172
+ super.decorateModule(moduleName, containedModule);
173
+ }
174
+ /**
175
+ * @returns A list of names of all the registered module names
176
+ */
177
+ get runtimeModuleNames() {
178
+ return Object.keys(this.definition.modules);
179
+ }
180
+ };
181
+ Runtime = Runtime_1 = __decorate([
182
+ injectable(),
183
+ __metadata("design:paramtypes", [Object])
184
+ ], Runtime);
185
+ export { Runtime };
@@ -0,0 +1,30 @@
1
+ import { ConfigurableModule, Presets } from "@proto-kit/common";
2
+ import { NetworkState, RuntimeTransaction } from "@proto-kit/protocol";
3
+ import { StateService } from "../state/InMemoryStateService";
4
+ import type { Runtime, RuntimeDefinition, RuntimeModulesRecord } from "./Runtime";
5
+ /**
6
+ * This type exists to carry over certain runtime properties
7
+ * to runtime modules, until we can inject them through DI.
8
+ */
9
+ export interface PartialRuntime extends Pick<Runtime<RuntimeModulesRecord>, "zkProgrammable"> {
10
+ definition: Pick<RuntimeDefinition<RuntimeModulesRecord>, "state">;
11
+ get stateService(): StateService;
12
+ }
13
+ /**
14
+ * Base class for runtime modules providing the necessary utilities.
15
+ */
16
+ export declare class RuntimeModule<Config> extends ConfigurableModule<Config> {
17
+ static presets: Presets<unknown>;
18
+ /**
19
+ * This property exists only to typecheck that the RuntimeModule
20
+ * was extended correctly in e.g. a decorator. We need at least
21
+ * one non-optional property in this class to make the typechecking work.
22
+ */
23
+ isRuntimeModule: boolean;
24
+ name?: string;
25
+ runtime?: Runtime<RuntimeModulesRecord>;
26
+ private getInputs;
27
+ get transaction(): RuntimeTransaction;
28
+ get network(): NetworkState;
29
+ }
30
+ //# 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,OAAO,EAAE,MAAM,mBAAmB,CAAC;AAEhE,OAAO,EAAE,YAAY,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AAMvE,OAAO,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAE7D,OAAO,KAAK,EACV,OAAO,EACP,iBAAiB,EACjB,oBAAoB,EACrB,MAAM,WAAW,CAAC;AAMnB;;;GAGG;AACH,MAAM,WAAW,cACf,SAAQ,IAAI,CAAC,OAAO,CAAC,oBAAoB,CAAC,EAAE,gBAAgB,CAAC;IAC7D,UAAU,EAAE,IAAI,CAAC,iBAAiB,CAAC,oBAAoB,CAAC,EAAE,OAAO,CAAC,CAAC;IAEnE,IAAI,YAAY,IAAI,YAAY,CAAC;CAClC;AAED;;GAEG;AACH,qBACa,aAAa,CAAC,MAAM,CAAE,SAAQ,kBAAkB,CAAC,MAAM,CAAC;IACnE,OAAc,OAAO,EAAE,OAAO,CAAC,OAAO,CAAC,CAAM;IAE7C;;;;OAIG;IACI,eAAe,UAAQ;IAEvB,IAAI,CAAC,EAAE,MAAM,CAAC;IAEd,OAAO,CAAC,EAAE,OAAO,CAAC,oBAAoB,CAAC,CAAC;IAE/C,OAAO,CAAC,SAAS;IAWjB,IAAW,WAAW,IAAI,kBAAkB,CAE3C;IAED,IAAW,OAAO,IAAI,YAAY,CAEjC;CACF"}
@@ -0,0 +1,44 @@
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
+ import { ConfigurableModule } from "@proto-kit/common";
8
+ import { container, injectable } from "tsyringe";
9
+ import { RuntimeMethodExecutionContext, } from "../method/RuntimeMethodExecutionContext";
10
+ const errors = {
11
+ inputDataNotSet: () => new Error("Input data for runtime execution not set"),
12
+ };
13
+ /**
14
+ * Base class for runtime modules providing the necessary utilities.
15
+ */
16
+ let RuntimeModule = class RuntimeModule extends ConfigurableModule {
17
+ constructor() {
18
+ super(...arguments);
19
+ /**
20
+ * This property exists only to typecheck that the RuntimeModule
21
+ * was extended correctly in e.g. a decorator. We need at least
22
+ * one non-optional property in this class to make the typechecking work.
23
+ */
24
+ this.isRuntimeModule = true;
25
+ }
26
+ getInputs() {
27
+ const { input } = container.resolve(RuntimeMethodExecutionContext);
28
+ if (input === undefined) {
29
+ throw errors.inputDataNotSet();
30
+ }
31
+ return input;
32
+ }
33
+ get transaction() {
34
+ return this.getInputs().transaction;
35
+ }
36
+ get network() {
37
+ return this.getInputs().networkState;
38
+ }
39
+ };
40
+ RuntimeModule.presets = {};
41
+ RuntimeModule = __decorate([
42
+ injectable()
43
+ ], RuntimeModule);
44
+ export { RuntimeModule };
@@ -0,0 +1,14 @@
1
+ import { Field } from "snarkyjs";
2
+ export interface StateService {
3
+ get: (key: Field) => Field[] | undefined;
4
+ set: (key: Field, value: Field[] | undefined) => void;
5
+ }
6
+ /**
7
+ * Naive implementation of a StateService for testing purposes
8
+ */
9
+ export declare class InMemoryStateService implements StateService {
10
+ values: Record<string, Field[] | undefined>;
11
+ get(key: Field): Field[] | undefined;
12
+ set(key: Field, value: Field[] | undefined): void;
13
+ }
14
+ //# 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,UAAU,CAAC;AAEjC,MAAM,WAAW,YAAY;IAC3B,GAAG,EAAE,CAAC,GAAG,EAAE,KAAK,KAAK,KAAK,EAAE,GAAG,SAAS,CAAC;IACzC,GAAG,EAAE,CAAC,GAAG,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,GAAG,SAAS,KAAK,IAAI,CAAC;CACvD;AAED;;GAEG;AACH,qBAAa,oBAAqB,YAAW,YAAY;IAChD,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,KAAK,EAAE,GAAG,SAAS,CAAC,CAAM;IAEjD,GAAG,CAAC,GAAG,EAAE,KAAK,GAAG,KAAK,EAAE,GAAG,SAAS;IAIpC,GAAG,CAAC,GAAG,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,GAAG,SAAS;CAWlD"}
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Naive implementation of a StateService for testing purposes
3
+ */
4
+ export class InMemoryStateService {
5
+ constructor() {
6
+ this.values = {};
7
+ }
8
+ get(key) {
9
+ return this.values[key.toString()];
10
+ }
11
+ set(key, value) {
12
+ if (value === undefined &&
13
+ Object.prototype.hasOwnProperty.call(this.values, key.toString())) {
14
+ // eslint-disable-next-line @typescript-eslint/no-dynamic-delete
15
+ delete this.values[key.toString()];
16
+ }
17
+ else {
18
+ this.values[key.toString()] = value;
19
+ }
20
+ }
21
+ }
@@ -0,0 +1,65 @@
1
+ import { Field, type FlexibleProvablePure } from "snarkyjs";
2
+ import { Option, type Path } from "@proto-kit/protocol";
3
+ import { PartialRuntime } from "../runtime/RuntimeModule.js";
4
+ export declare class WithPath {
5
+ path?: Field;
6
+ hasPathOrFail(): asserts this is {
7
+ path: Path;
8
+ };
9
+ }
10
+ export declare class WithRuntime {
11
+ runtime?: PartialRuntime;
12
+ hasRuntimeOrFail(): asserts this is {
13
+ runtime: PartialRuntime;
14
+ };
15
+ }
16
+ declare const State_base: import("ts-mixer/dist/types/types.js").Class<any[], WithPath & WithRuntime, typeof WithPath & typeof WithRuntime, false>;
17
+ /**
18
+ * Utilities for runtime module state, such as get/set
19
+ */
20
+ export declare class State<Value> extends State_base {
21
+ valueType: FlexibleProvablePure<Value>;
22
+ /**
23
+ * Creates a new state wrapper for the provided value type.
24
+ *
25
+ * @param valueType - Type of value to be stored (e.g. UInt64, Struct, ...)
26
+ * @returns New state for the given value type.
27
+ */
28
+ static from<Value>(valueType: FlexibleProvablePure<Value>): State<Value>;
29
+ /**
30
+ * Computes a dummy value for the given value type.
31
+ *
32
+ * @param valueType - Value type to generate the dummy value for
33
+ * @returns Dummy value for the given value type
34
+ */
35
+ static dummyValue<Value>(valueType: FlexibleProvablePure<Value>): Value;
36
+ constructor(valueType: FlexibleProvablePure<Value>);
37
+ /**
38
+ * Provides an in-circuit witness for the current state representation,
39
+ * and constructs an Option out of it.
40
+ *
41
+ * @returns Optional value of the current state
42
+ */
43
+ private witnessState;
44
+ /**
45
+ * Retrieves the current state and creates a state transition
46
+ * anchoring the use of the current state value in the circuit.
47
+ *
48
+ * @returns Option representation of the current state.
49
+ */
50
+ get(): Option<Value>;
51
+ /**
52
+ * Sets a new state value by creating a state transition from
53
+ * the current value to the newly set value.
54
+ *
55
+ * The newly set value isn't available via state.get(), since the
56
+ * state transitions are not applied within the same circuit.
57
+ * You can however store and access your new value in
58
+ * a separate circuit variable.
59
+ *
60
+ * @param value - Value to be set as the current state
61
+ */
62
+ set(value: Value): void;
63
+ }
64
+ export {};
65
+ //# sourceMappingURL=State.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"State.d.ts","sourceRoot":"","sources":["../../src/state/State.ts"],"names":[],"mappings":"AAGA,OAAO,EAAQ,KAAK,EAAY,KAAK,oBAAoB,EAAE,MAAM,UAAU,CAAC;AAE5E,OAAO,EAAE,MAAM,EAAmB,KAAK,IAAI,EAAE,MAAM,qBAAqB,CAAC;AAEzE,OAAO,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAC;AAG7D,qBAAa,QAAQ;IACZ,IAAI,CAAC,EAAE,KAAK,CAAC;IAEb,aAAa,IAAI,OAAO,CAAC,IAAI,IAAI;QAAE,IAAI,EAAE,IAAI,CAAA;KAAE;CAOvD;AAED,qBAAa,WAAW;IACf,OAAO,CAAC,EAAE,cAAc,CAAC;IAEzB,gBAAgB,IAAI,OAAO,CAAC,IAAI,IAAI;QACzC,OAAO,EAAE,cAAc,CAAC;KACzB;CAOF;;AAED;;GAEG;AACH,qBAAa,KAAK,CAAC,KAAK,CAAE,SAAQ,UAA4B;IA2BlC,SAAS,EAAE,oBAAoB,CAAC,KAAK,CAAC;IA1BhE;;;;;OAKG;WACW,IAAI,CAAC,KAAK,EAAE,SAAS,EAAE,oBAAoB,CAAC,KAAK,CAAC;IAIhE;;;;;OAKG;WACW,UAAU,CAAC,KAAK,EAC5B,SAAS,EAAE,oBAAoB,CAAC,KAAK,CAAC,GACrC,KAAK;gBAQkB,SAAS,EAAE,oBAAoB,CAAC,KAAK,CAAC;IAIhE;;;;;OAKG;IACH,OAAO,CAAC,YAAY;IA6BpB;;;;;OAKG;IACI,GAAG,IAAI,MAAM,CAAC,KAAK,CAAC;IAc3B;;;;;;;;;;OAUG;IACI,GAAG,CAAC,KAAK,EAAE,KAAK;CAiBxB"}