@proto-kit/module 0.1.1-develop.600 → 0.1.1-develop.833

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 (108) hide show
  1. package/LICENSE.md +201 -201
  2. package/dist/method/MethodParameterDecoder.d.ts +10 -10
  3. package/dist/method/MethodParameterDecoder.js +40 -40
  4. package/dist/method/MethodParameterEncoder.d.ts +15 -8
  5. package/dist/method/MethodParameterEncoder.d.ts.map +1 -1
  6. package/dist/method/MethodParameterEncoder.js +122 -48
  7. package/dist/method/runtimeMethod.d.ts +6 -5
  8. package/dist/method/runtimeMethod.d.ts.map +1 -1
  9. package/dist/method/runtimeMethod.js +13 -26
  10. package/dist/runtime/MethodIdResolver.d.ts +7 -0
  11. package/dist/runtime/MethodIdResolver.d.ts.map +1 -1
  12. package/dist/runtime/MethodIdResolver.js +35 -2
  13. package/dist/runtime/Runtime.d.ts +6 -5
  14. package/dist/runtime/Runtime.d.ts.map +1 -1
  15. package/dist/runtime/Runtime.js +29 -22
  16. package/dist/runtime/RuntimeEnvironment.d.ts +2 -2
  17. package/dist/runtime/RuntimeEnvironment.d.ts.map +1 -1
  18. package/dist/runtime/RuntimeModule.d.ts +2 -2
  19. package/dist/runtime/RuntimeModule.d.ts.map +1 -1
  20. package/dist/runtime/RuntimeModule.js +10 -8
  21. package/dist/src/factories/MethodIdFactory.d.ts +10 -0
  22. package/dist/src/factories/MethodIdFactory.d.ts.map +1 -0
  23. package/dist/src/factories/MethodIdFactory.js +10 -0
  24. package/dist/src/index.d.ts +11 -0
  25. package/dist/src/index.d.ts.map +1 -0
  26. package/dist/src/index.js +10 -0
  27. package/dist/src/method/MethodParameterEncoder.d.ts +22 -0
  28. package/dist/src/method/MethodParameterEncoder.d.ts.map +1 -0
  29. package/dist/src/method/MethodParameterEncoder.js +103 -0
  30. package/dist/src/method/runtimeMethod.d.ts +26 -0
  31. package/dist/src/method/runtimeMethod.d.ts.map +1 -0
  32. package/dist/src/method/runtimeMethod.js +164 -0
  33. package/dist/src/module/decorator.d.ts +8 -0
  34. package/dist/src/module/decorator.d.ts.map +1 -0
  35. package/dist/src/module/decorator.js +15 -0
  36. package/dist/src/runtime/MethodIdResolver.d.ts +20 -0
  37. package/dist/src/runtime/MethodIdResolver.d.ts.map +1 -0
  38. package/dist/src/runtime/MethodIdResolver.js +100 -0
  39. package/dist/src/runtime/Runtime.d.ts +71 -0
  40. package/dist/src/runtime/Runtime.d.ts.map +1 -0
  41. package/dist/src/runtime/Runtime.js +215 -0
  42. package/dist/src/runtime/RuntimeEnvironment.d.ts +10 -0
  43. package/dist/src/runtime/RuntimeEnvironment.d.ts.map +1 -0
  44. package/dist/src/runtime/RuntimeEnvironment.js +1 -0
  45. package/dist/src/runtime/RuntimeModule.d.ts +26 -0
  46. package/dist/src/runtime/RuntimeModule.d.ts.map +1 -0
  47. package/dist/src/runtime/RuntimeModule.js +85 -0
  48. package/dist/src/state/InMemoryStateService.d.ts +15 -0
  49. package/dist/src/state/InMemoryStateService.d.ts.map +1 -0
  50. package/dist/src/state/InMemoryStateService.js +28 -0
  51. package/dist/src/state/decorator.d.ts +7 -0
  52. package/dist/src/state/decorator.d.ts.map +1 -0
  53. package/dist/src/state/decorator.js +39 -0
  54. package/dist/state/InMemoryStateService.d.ts +10 -6
  55. package/dist/state/InMemoryStateService.d.ts.map +1 -1
  56. package/dist/state/InMemoryStateService.js +10 -8
  57. package/dist/state/decorator.d.ts.map +1 -1
  58. package/dist/state/decorator.js +0 -3
  59. package/dist/test/Runtime.test.d.ts +2 -0
  60. package/dist/test/Runtime.test.d.ts.map +1 -0
  61. package/dist/test/Runtime.test.js +24 -0
  62. package/dist/test/TestingRuntime.d.ts +7 -0
  63. package/dist/test/TestingRuntime.d.ts.map +1 -0
  64. package/dist/test/TestingRuntime.js +29 -0
  65. package/dist/test/method/runtimeMethod.test.d.ts +2 -0
  66. package/dist/test/method/runtimeMethod.test.d.ts.map +1 -0
  67. package/dist/test/method/runtimeMethod.test.js +30 -0
  68. package/dist/test/modules/Admin.d.ts +10 -0
  69. package/dist/test/modules/Admin.d.ts.map +1 -0
  70. package/dist/test/modules/Admin.js +29 -0
  71. package/dist/test/modules/Balances.d.ts +23 -0
  72. package/dist/test/modules/Balances.d.ts.map +1 -0
  73. package/dist/test/modules/Balances.js +98 -0
  74. package/dist/test/modules/Balances.test.d.ts +2 -0
  75. package/dist/test/modules/Balances.test.d.ts.map +1 -0
  76. package/dist/test/modules/Balances.test.js +201 -0
  77. package/dist/test/modules/MethodIdResolver.test.d.ts +2 -0
  78. package/dist/test/modules/MethodIdResolver.test.d.ts.map +1 -0
  79. package/dist/test/modules/MethodIdResolver.test.js +67 -0
  80. package/dist/test/modules/State.test.d.ts +2 -0
  81. package/dist/test/modules/State.test.d.ts.map +1 -0
  82. package/dist/test/modules/State.test.js +42 -0
  83. package/dist/test/runtimeMethod.test.d.ts +2 -0
  84. package/dist/test/runtimeMethod.test.d.ts.map +1 -0
  85. package/dist/test/runtimeMethod.test.js +50 -0
  86. package/package.json +5 -5
  87. package/src/method/MethodParameterEncoder.ts +192 -81
  88. package/src/method/runtimeMethod.ts +29 -44
  89. package/src/runtime/MethodIdResolver.ts +51 -1
  90. package/src/runtime/Runtime.ts +48 -29
  91. package/src/runtime/RuntimeEnvironment.ts +4 -7
  92. package/src/runtime/RuntimeModule.ts +13 -15
  93. package/src/state/InMemoryStateService.ts +13 -13
  94. package/src/state/decorator.ts +1 -3
  95. package/test/Runtime.test.ts +68 -41
  96. package/test/TestingRuntime.ts +45 -0
  97. package/test/method/MethodParameterEncoder.test.ts +152 -0
  98. package/{src/method/decorator.test.ts → test/method/runtimeMethod.test.ts} +2 -2
  99. package/test/modules/Admin.ts +3 -3
  100. package/test/modules/Balances.test.ts +57 -61
  101. package/test/modules/Balances.ts +15 -18
  102. package/test/modules/{methodId.test.ts → MethodIdResolver.test.ts} +14 -23
  103. package/test/modules/State.test.ts +41 -50
  104. package/test/runtimeMethod.test.ts +19 -32
  105. package/test/tsconfig.json +7 -0
  106. package/tsconfig.json +2 -2
  107. package/test/transaction.test.ts +0 -82
  108. package/tsconfig.test.json +0 -9
@@ -1,5 +1,5 @@
1
1
  import { ConfigurableModule, NoConfig, Presets } from "@proto-kit/common";
2
- import { NetworkState, RuntimeTransaction } from "@proto-kit/protocol";
2
+ import { NetworkState, RuntimeTransaction, RuntimeMethodExecutionData } from "@proto-kit/protocol";
3
3
  import { RuntimeEnvironment } from "./RuntimeEnvironment";
4
4
  /**
5
5
  * Base class for runtime modules providing the necessary utilities.
@@ -19,7 +19,7 @@ export declare class RuntimeModule<Config = NoConfig> extends ConfigurableModule
19
19
  name?: string;
20
20
  runtime?: RuntimeEnvironment;
21
21
  constructor();
22
- private getInputs;
22
+ getInputs(): RuntimeMethodExecutionData;
23
23
  get transaction(): RuntimeTransaction;
24
24
  get network(): NetworkState;
25
25
  }
@@ -1 +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,EAInB,MAAM,qBAAqB,CAAC;AAS7B,OAAO,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAM1D;;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;;IAYpC,OAAO,CAAC,SAAS;IAWjB,IAAW,WAAW,IAAI,kBAAkB,CAE3C;IAED,IAAW,OAAO,IAAI,YAAY,CAEjC;CACF"}
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;AAK7B,OAAO,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAM1D;;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;;IAY7B,SAAS,IAAI,0BAA0B;IAa9C,IAAW,WAAW,IAAI,kBAAkB,CAE3C;IAED,IAAW,OAAO,IAAI,YAAY,CAEjC;CACF"}
@@ -9,7 +9,8 @@ var __metadata = (this && this.__metadata) || function (k, v) {
9
9
  };
10
10
  import { ConfigurableModule } from "@proto-kit/common";
11
11
  import { container, injectable } from "tsyringe";
12
- import { RuntimeMethodExecutionContext, } from "@proto-kit/protocol";
12
+ import { RuntimeMethodExecutionContext, RuntimeMethodExecutionDataStruct, } from "@proto-kit/protocol";
13
+ import { Provable } from "o1js";
13
14
  import { runtimeMethodNamesMetadataKey } from "../method/runtimeMethod";
14
15
  const errors = {
15
16
  inputDataNotSet: () => new Error("Input data for runtime execution not set"),
@@ -17,7 +18,7 @@ const errors = {
17
18
  /**
18
19
  * Base class for runtime modules providing the necessary utilities.
19
20
  */
20
- let RuntimeModule = class RuntimeModule extends ConfigurableModule {
21
+ export let RuntimeModule = class RuntimeModule extends ConfigurableModule {
21
22
  constructor() {
22
23
  super();
23
24
  /**
@@ -35,11 +36,13 @@ let RuntimeModule = class RuntimeModule extends ConfigurableModule {
35
36
  this.runtimeMethodNames = methodNames ?? [];
36
37
  }
37
38
  getInputs() {
38
- const { input } = container.resolve(RuntimeMethodExecutionContext);
39
- if (input === undefined) {
40
- throw errors.inputDataNotSet();
41
- }
42
- return input;
39
+ return Provable.witness(RuntimeMethodExecutionDataStruct, () => {
40
+ const { input } = container.resolve(RuntimeMethodExecutionContext);
41
+ if (input === undefined) {
42
+ throw errors.inputDataNotSet();
43
+ }
44
+ return input;
45
+ });
43
46
  }
44
47
  get transaction() {
45
48
  return this.getInputs().transaction;
@@ -53,4 +56,3 @@ RuntimeModule = __decorate([
53
56
  injectable(),
54
57
  __metadata("design:paramtypes", [])
55
58
  ], RuntimeModule);
56
- export { RuntimeModule };
@@ -0,0 +1,10 @@
1
+ import { DependencyFactory } from "@proto-kit/common";
2
+ import { MethodIdResolver } from "../runtime/MethodIdResolver";
3
+ export declare class MethodIdFactory implements DependencyFactory {
4
+ dependencies(): {
5
+ methodIdResolver: {
6
+ useClass: typeof MethodIdResolver;
7
+ };
8
+ };
9
+ }
10
+ //# sourceMappingURL=MethodIdFactory.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"MethodIdFactory.d.ts","sourceRoot":"","sources":["../../../src/factories/MethodIdFactory.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAoB,MAAM,mBAAmB,CAAC;AAExE,OAAO,EAAE,gBAAgB,EAAE,MAAM,6BAA6B,CAAC;AAE/D,qBAAa,eAAgB,YAAW,iBAAiB;IAChD,YAAY;;;;;CAOpB"}
@@ -0,0 +1,10 @@
1
+ import { MethodIdResolver } from "../runtime/MethodIdResolver";
2
+ export class MethodIdFactory {
3
+ dependencies() {
4
+ return {
5
+ methodIdResolver: {
6
+ useClass: MethodIdResolver,
7
+ },
8
+ };
9
+ }
10
+ }
@@ -0,0 +1,11 @@
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";
11
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,wBAAwB,CAAC;AACvC,cAAc,oBAAoB,CAAC;AACnC,cAAc,yBAAyB,CAAC;AACxC,cAAc,8BAA8B,CAAC;AAC7C,cAAc,mBAAmB,CAAC;AAClC,cAAc,8BAA8B,CAAC;AAC7C,cAAc,mBAAmB,CAAC;AAClC,cAAc,iCAAiC,CAAC;AAChD,cAAc,4BAA4B,CAAC;AAC3C,cAAc,6BAA6B,CAAC"}
@@ -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,22 @@
1
+ import { Field, FlexibleProvable, ProvableExtended } from "o1js";
2
+ import { ArgumentTypes } from "@proto-kit/common";
3
+ import type { RuntimeModule } from "../runtime/RuntimeModule";
4
+ export declare class MethodParameterEncoder {
5
+ private readonly types;
6
+ static fromMethod(target: RuntimeModule<unknown>, methodName: string): MethodParameterEncoder;
7
+ static fieldSize(type: ProvableExtended<unknown>): number | undefined;
8
+ private constructor();
9
+ decode(argsJSON: string[]): FlexibleProvable<unknown>[];
10
+ decodeFields(fields: Field[]): ArgumentTypes;
11
+ /**
12
+ * Variant of encode() for provable code that skips the unprovable
13
+ * json encoding
14
+ */
15
+ encodeAsFields(args: ArgumentTypes): import("o1js/dist/node/lib/provable/field").Field[];
16
+ encode(args: ArgumentTypes): {
17
+ argsFields: Field[];
18
+ argsJSON: string[];
19
+ };
20
+ get fieldSize(): number;
21
+ }
22
+ //# sourceMappingURL=MethodParameterEncoder.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"MethodParameterEncoder.d.ts","sourceRoot":"","sources":["../../../src/method/MethodParameterEncoder.ts"],"names":[],"mappings":"AACA,OAAO,EACL,KAAK,EACL,gBAAgB,EAGhB,gBAAgB,EACjB,MAAM,MAAM,CAAC;AACd,OAAO,EACL,aAAa,EAKd,MAAM,mBAAmB,CAAC;AAE3B,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AAgB9D,qBAAa,sBAAsB;IAuBb,OAAO,CAAC,QAAQ,CAAC,KAAK;WAtB5B,UAAU,CAAC,MAAM,EAAE,aAAa,CAAC,OAAO,CAAC,EAAE,UAAU,EAAE,MAAM;WAiB7D,SAAS,CAAC,IAAI,EAAE,gBAAgB,CAAC,OAAO,CAAC,GAAG,MAAM,GAAG,SAAS;IAK5E,OAAO;IAEA,MAAM,CAAC,QAAQ,EAAE,MAAM,EAAE,GAAG,gBAAgB,CAAC,OAAO,CAAC,EAAE;IAmBvD,YAAY,CAAC,MAAM,EAAE,KAAK,EAAE,GAAG,aAAa;IAkBnD;;;OAGG;IACI,cAAc,CAAC,IAAI,EAAE,aAAa;IA2BlC,MAAM,CAAC,IAAI,EAAE,aAAa,GAAG;QAClC,UAAU,EAAE,KAAK,EAAE,CAAC;QACpB,QAAQ,EAAE,MAAM,EAAE,CAAC;KACpB;IAqBD,IAAW,SAAS,IAAI,MAAM,CAI7B;CACF"}
@@ -0,0 +1,103 @@
1
+ /* eslint-disable no-underscore-dangle,@typescript-eslint/consistent-type-assertions */
2
+ import { Proof, Provable, } from "o1js";
3
+ const errors = {
4
+ fieldLengthNotMatching: (expected, actual) => new Error(`Expected ${expected} field elements, got ${actual}`),
5
+ typeNotCompatible: (name, error) => new Error(`Cannot decode type ${name}, it has to be either a Struct, CircuitValue or built-in snarkyjs type.${error !== undefined ? `Caused by: ${error}` : ""}`),
6
+ };
7
+ export class MethodParameterEncoder {
8
+ static fromMethod(target, methodName) {
9
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
10
+ const paramtypes = Reflect.getMetadata("design:paramtypes", target, methodName);
11
+ if (paramtypes === undefined) {
12
+ throw new Error(`Method with name ${methodName} doesn't exist on this module`);
13
+ }
14
+ return new MethodParameterEncoder(paramtypes);
15
+ }
16
+ static fieldSize(type) {
17
+ // as any, since we shouldn't be using this workaround in the first place
18
+ return type.prototype._fields?.length ?? type.sizeInFields?.();
19
+ }
20
+ constructor(types) {
21
+ Object.defineProperty(this, "types", {
22
+ enumerable: true,
23
+ configurable: true,
24
+ writable: true,
25
+ value: types
26
+ });
27
+ }
28
+ decode(argsJSON) {
29
+ return this.types.map((type, index) => {
30
+ let value;
31
+ try {
32
+ value = type.fromJSON(JSON.parse(argsJSON[index]));
33
+ }
34
+ catch (e) {
35
+ if (e instanceof Error) {
36
+ throw errors.typeNotCompatible(type.constructor.name, e.message);
37
+ }
38
+ throw errors.typeNotCompatible(type.constructor.name);
39
+ }
40
+ return value;
41
+ });
42
+ }
43
+ decodeFields(fields) {
44
+ if (fields.length < this.fieldSize) {
45
+ throw errors.fieldLengthNotMatching(this.fieldSize, fields.length);
46
+ }
47
+ let stack = fields.slice();
48
+ return this.types.map((type) => {
49
+ const numberFieldsNeeded = MethodParameterEncoder.fieldSize(type) ?? -1;
50
+ if (numberFieldsNeeded === -1) {
51
+ throw errors.typeNotCompatible(type.constructor.name);
52
+ }
53
+ const structFields = stack.slice(0, numberFieldsNeeded);
54
+ stack = stack.slice(numberFieldsNeeded);
55
+ return type.fromFields(structFields, []);
56
+ });
57
+ }
58
+ /**
59
+ * Variant of encode() for provable code that skips the unprovable
60
+ * json encoding
61
+ */
62
+ encodeAsFields(args) {
63
+ /**
64
+ * Use the type info obtained previously to convert
65
+ * the args passed to fields
66
+ */
67
+ return args.flatMap((argument, index) => {
68
+ if (argument instanceof Proof) {
69
+ const argumentType = this.types[index];
70
+ const publicOutputType = argumentType?.publicOutputType;
71
+ const publicInputType = argumentType?.publicInputType;
72
+ const inputFields = publicInputType?.toFields(argument.publicInput) ?? [];
73
+ const outputFields = publicOutputType?.toFields(argument.publicOutput) ?? [];
74
+ return [...inputFields, ...outputFields];
75
+ }
76
+ const argumentType = this.types[index];
77
+ return argumentType.toFields(argument);
78
+ });
79
+ }
80
+ encode(args) {
81
+ const argsFields = this.encodeAsFields(args);
82
+ let argsJSON = [];
83
+ Provable.asProver(() => {
84
+ argsJSON = args.map((argument, index) => {
85
+ if (argument instanceof Proof) {
86
+ return JSON.stringify(argument.toJSON());
87
+ }
88
+ const argumentType = this.types[index];
89
+ return JSON.stringify(argumentType.toJSON(argument));
90
+ });
91
+ });
92
+ return {
93
+ argsFields,
94
+ argsJSON,
95
+ };
96
+ }
97
+ get fieldSize() {
98
+ return this.types
99
+ .map((type) => MethodParameterEncoder.fieldSize(type) ?? 0)
100
+ .reduce((a, b) => a + b, 0);
101
+ }
102
+ }
103
+ /* eslint-enable no-underscore-dangle,@typescript-eslint/consistent-type-assertions */
@@ -0,0 +1,26 @@
1
+ import { StateTransition, MethodPublicOutput } from "@proto-kit/protocol";
2
+ import { ArgumentTypes } from "@proto-kit/common";
3
+ import type { RuntimeModule } from "../runtime/RuntimeModule.js";
4
+ export declare function toStateTransitionsHash(stateTransitions: StateTransition<any>[]): import("o1js/dist/node/lib/provable/field.js").Field;
5
+ export type WrappedMethod = (...args: ArgumentTypes) => MethodPublicOutput;
6
+ export type AsyncWrappedMethod = (...args: ArgumentTypes) => Promise<MethodPublicOutput>;
7
+ export declare function toWrappedMethod(this: RuntimeModule<unknown>, methodName: string, moduleMethod: (...args: ArgumentTypes) => Promise<any>, options: {
8
+ invocationType: RuntimeMethodInvocationType;
9
+ }): AsyncWrappedMethod;
10
+ export declare function combineMethodName(runtimeModuleName: string, methodName: string): string;
11
+ export declare const runtimeMethodMetadataKey = "yab-method";
12
+ export declare const runtimeMethodNamesMetadataKey = "proto-kit-runtime-methods";
13
+ export declare const runtimeMethodTypeMetadataKey = "proto-kit-runtime-method-type";
14
+ /**
15
+ * Checks the metadata of the provided runtime module and its method,
16
+ * to see if it has been decorated with @runtimeMethod()
17
+ *
18
+ * @param target - Runtime module to check
19
+ * @param propertyKey - Name of the method to check in the prior runtime module
20
+ * @returns - If the provided method name is a runtime method or not
21
+ */
22
+ export declare function isRuntimeMethod(target: RuntimeModule<unknown>, propertyKey: string): boolean;
23
+ export type RuntimeMethodInvocationType = "SIGNATURE" | "INCOMING_MESSAGE";
24
+ export declare function runtimeMessage(): (target: RuntimeModule<unknown>, methodName: string, descriptor: TypedPropertyDescriptor<(...args: any[]) => any>) => void;
25
+ export declare function runtimeMethod(): (target: RuntimeModule<unknown>, methodName: string, descriptor: TypedPropertyDescriptor<(...args: any[]) => any>) => void;
26
+ //# sourceMappingURL=runtimeMethod.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runtimeMethod.d.ts","sourceRoot":"","sources":["../../../src/method/runtimeMethod.ts"],"names":[],"mappings":"AAEA,OAAO,EACL,eAAe,EAEf,kBAAkB,EAGnB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAIL,aAAa,EACd,MAAM,mBAAmB,CAAC;AAE3B,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAC;AAqBjE,wBAAgB,sBAAsB,CACpC,gBAAgB,EAAE,eAAe,CAAC,GAAG,CAAC,EAAE,wDAczC;AAED,MAAM,MAAM,aAAa,GAAG,CAAC,GAAG,IAAI,EAAE,aAAa,KAAK,kBAAkB,CAAC;AAC3E,MAAM,MAAM,kBAAkB,GAAG,CAC/B,GAAG,IAAI,EAAE,aAAa,KACnB,OAAO,CAAC,kBAAkB,CAAC,CAAC;AAEjC,wBAAgB,eAAe,CAC7B,IAAI,EAAE,aAAa,CAAC,OAAO,CAAC,EAC5B,UAAU,EAAE,MAAM,EAClB,YAAY,EAAE,CAAC,GAAG,IAAI,EAAE,aAAa,KAAK,OAAO,CAAC,GAAG,CAAC,EACtD,OAAO,EAAE;IACP,cAAc,EAAE,2BAA2B,CAAC;CAC7C,GACA,kBAAkB,CAgFpB;AAED,wBAAgB,iBAAiB,CAC/B,iBAAiB,EAAE,MAAM,EACzB,UAAU,EAAE,MAAM,UAGnB;AAED,eAAO,MAAM,wBAAwB,eAAe,CAAC;AACrD,eAAO,MAAM,6BAA6B,8BAA8B,CAAC;AACzE,eAAO,MAAM,4BAA4B,kCAAkC,CAAC;AAE5E;;;;;;;GAOG;AACH,wBAAgB,eAAe,CAC7B,MAAM,EAAE,aAAa,CAAC,OAAO,CAAC,EAC9B,WAAW,EAAE,MAAM,WAKpB;AAED,MAAM,MAAM,2BAA2B,GAAG,WAAW,GAAG,kBAAkB,CAAC;AA4G3E,wBAAgB,cAAc,+HAI7B;AAED,wBAAgB,aAAa,+HAI5B"}
@@ -0,0 +1,164 @@
1
+ import { Bool, Field, Poseidon } from "o1js";
2
+ import { container } from "tsyringe";
3
+ import { ProvableStateTransition, MethodPublicOutput, RuntimeMethodExecutionContext, StateTransitionReductionList, } from "@proto-kit/protocol";
4
+ import { toProver, } from "@proto-kit/common";
5
+ import { MethodParameterEncoder } from "./MethodParameterEncoder";
6
+ const errors = {
7
+ runtimeNotProvided: (name) => new Error(`Runtime was not provided for module: ${name}`),
8
+ methodInputsNotProvided: () => new Error("Method execution inputs not provided, provide them via context.inputs"),
9
+ runtimeNameNotSet: () => new Error("Runtime name was not set"),
10
+ fieldNotConstant: (name) => new Error(`In-circuit field ${name} not a constant, this is likely a framework bug`),
11
+ };
12
+ export function toStateTransitionsHash(stateTransitions) {
13
+ const stateTransitionsHashList = new StateTransitionReductionList(ProvableStateTransition);
14
+ return stateTransitions
15
+ .map((stateTransition) => stateTransition.toProvable())
16
+ .reduce((allStateTransitionsHashList, stateTransition) => allStateTransitionsHashList.push(stateTransition), stateTransitionsHashList)
17
+ .toField();
18
+ }
19
+ export function toWrappedMethod(methodName, moduleMethod, options) {
20
+ const executionContext = container.resolve(RuntimeMethodExecutionContext);
21
+ const wrappedMethod = async (...args) => {
22
+ await Reflect.apply(moduleMethod, this, args);
23
+ const { result: { stateTransitions, status }, } = executionContext.current();
24
+ const stateTransitionsHash = toStateTransitionsHash(stateTransitions);
25
+ const { name, runtime } = this;
26
+ if (name === undefined) {
27
+ throw errors.runtimeNameNotSet();
28
+ }
29
+ if (runtime === undefined) {
30
+ throw errors.runtimeNotProvided(name);
31
+ }
32
+ const { transaction, networkState } = executionContext.witnessInput();
33
+ const { methodIdResolver } = runtime;
34
+ // Assert that the given transaction has the correct methodId
35
+ const thisMethodId = Field(methodIdResolver.getMethodId(name, methodName));
36
+ if (!thisMethodId.isConstant()) {
37
+ throw errors.fieldNotConstant("methodId");
38
+ }
39
+ transaction.methodId.assertEquals(thisMethodId, "Runtimemethod called with wrong methodId on the transaction object");
40
+ /**
41
+ * Use the type info obtained previously to convert
42
+ * the args passed to fields
43
+ */
44
+ const { argsFields } = MethodParameterEncoder.fromMethod(this, methodName).encode(args);
45
+ // Assert that the argsHash that has been signed matches the given arguments
46
+ // We can use js-if here, because args are statically sized
47
+ // i.e. the result of the if-statement will be the same for all executions
48
+ // of this method
49
+ const argsHash = (args ?? []).length > 0 ? Poseidon.hash(argsFields) : Field(0);
50
+ transaction.argsHash.assertEquals(argsHash, "argsHash and therefore arguments of transaction and runtime call does not match");
51
+ const isMessage = Bool(options.invocationType === "INCOMING_MESSAGE");
52
+ transaction.assertTransactionType(Bool(isMessage));
53
+ const transactionHash = transaction.hash();
54
+ const networkStateHash = networkState.hash();
55
+ return new MethodPublicOutput({
56
+ stateTransitionsHash,
57
+ status,
58
+ transactionHash,
59
+ networkStateHash,
60
+ isMessage,
61
+ });
62
+ };
63
+ Object.defineProperty(wrappedMethod, "name", {
64
+ value: `wrapped_${methodName}`,
65
+ writable: false,
66
+ });
67
+ return wrappedMethod;
68
+ }
69
+ export function combineMethodName(runtimeModuleName, methodName) {
70
+ return `${runtimeModuleName}.${methodName}`;
71
+ }
72
+ export const runtimeMethodMetadataKey = "yab-method";
73
+ export const runtimeMethodNamesMetadataKey = "proto-kit-runtime-methods";
74
+ export const runtimeMethodTypeMetadataKey = "proto-kit-runtime-method-type";
75
+ /**
76
+ * Checks the metadata of the provided runtime module and its method,
77
+ * to see if it has been decorated with @runtimeMethod()
78
+ *
79
+ * @param target - Runtime module to check
80
+ * @param propertyKey - Name of the method to check in the prior runtime module
81
+ * @returns - If the provided method name is a runtime method or not
82
+ */
83
+ export function isRuntimeMethod(target, propertyKey) {
84
+ return Boolean(Reflect.getMetadata(runtimeMethodMetadataKey, target, propertyKey));
85
+ }
86
+ function runtimeMethodInternal(options) {
87
+ return (target, methodName, descriptor) => {
88
+ const executionContext = container.resolve(RuntimeMethodExecutionContext);
89
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
90
+ let data = Reflect.getMetadata(runtimeMethodNamesMetadataKey, target);
91
+ if (data !== undefined) {
92
+ data.push(methodName);
93
+ }
94
+ else {
95
+ data = [methodName];
96
+ }
97
+ Reflect.defineMetadata(runtimeMethodNamesMetadataKey, data, target);
98
+ Reflect.defineMetadata(runtimeMethodMetadataKey, true, target, methodName);
99
+ Reflect.defineMetadata(runtimeMethodTypeMetadataKey, options.invocationType, target, methodName);
100
+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
101
+ const simulatedMethod = descriptor.value;
102
+ descriptor.value = async function value(...args) {
103
+ const constructorName = this.name;
104
+ /**
105
+ * If its a top level method call, wrap it into a wrapped method,
106
+ * since it'll be turned into a real/mock prover in provableMethod().
107
+ *
108
+ * Otherwise provableMethod() will just call the originalMethod provided
109
+ * if method is not called at the top level.
110
+ */
111
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
112
+ const simulatedWrappedMethod = Reflect.apply(toWrappedMethod, this, [
113
+ methodName,
114
+ simulatedMethod,
115
+ options,
116
+ ]);
117
+ /**
118
+ * Before the prover runs, make sure it is operating on the correct
119
+ * RuntimeMethodExecutionContext state, meaning it enters and exits
120
+ * the context properly.
121
+ */
122
+ async function prover() {
123
+ executionContext.beforeMethod(constructorName, methodName, args);
124
+ const innerProver = toProver(combineMethodName(constructorName, methodName),
125
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
126
+ simulatedWrappedMethod, false, ...args).bind(this);
127
+ let result;
128
+ try {
129
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
130
+ result = await Reflect.apply(innerProver, this, args);
131
+ }
132
+ finally {
133
+ executionContext.afterMethod();
134
+ }
135
+ return result;
136
+ }
137
+ executionContext.beforeMethod(constructorName, methodName, args);
138
+ if (executionContext.isTopLevel) {
139
+ if (!this.runtime) {
140
+ throw errors.runtimeNotProvided(constructorName);
141
+ }
142
+ executionContext.setProver(prover.bind(this.runtime.zkProgrammable));
143
+ }
144
+ let result;
145
+ try {
146
+ result = Reflect.apply(simulatedMethod, this, args);
147
+ }
148
+ finally {
149
+ executionContext.afterMethod();
150
+ }
151
+ return result;
152
+ };
153
+ };
154
+ }
155
+ export function runtimeMessage() {
156
+ return runtimeMethodInternal({
157
+ invocationType: "INCOMING_MESSAGE",
158
+ });
159
+ }
160
+ export function runtimeMethod() {
161
+ return runtimeMethodInternal({
162
+ invocationType: "SIGNATURE",
163
+ });
164
+ }
@@ -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,20 @@
1
+ import { RuntimeMethodIdMapping } from "@proto-kit/protocol";
2
+ import type { Runtime, RuntimeModulesRecord } from "./Runtime";
3
+ /**
4
+ * Please see `getMethodId` to learn more about
5
+ * methodId encoding
6
+ */
7
+ export declare class MethodIdResolver {
8
+ private readonly runtime;
9
+ private readonly dictionary;
10
+ constructor(runtime: Runtime<RuntimeModulesRecord>);
11
+ /**
12
+ * The purpose of this method is to provide a dictionary where
13
+ * we can look up properties like methodId and invocationType
14
+ * for each runtimeMethod using their module name and method name
15
+ */
16
+ methodIdMap(): RuntimeMethodIdMapping;
17
+ getMethodNameFromId(methodId: bigint): [string, string] | undefined;
18
+ getMethodId(moduleName: string, methodName: string): bigint;
19
+ }
20
+ //# sourceMappingURL=MethodIdResolver.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"MethodIdResolver.d.ts","sourceRoot":"","sources":["../../../src/runtime/MethodIdResolver.ts"],"names":[],"mappings":"AACA,OAAO,EAAiB,sBAAsB,EAAE,MAAM,qBAAqB,CAAC;AAS5E,OAAO,KAAK,EAAE,OAAO,EAAE,oBAAoB,EAAE,MAAM,WAAW,CAAC;AAE/D;;;GAGG;AACH,qBACa,gBAAgB;IAMN,OAAO,CAAC,QAAQ,CAAC,OAAO;IAL7C,OAAO,CAAC,QAAQ,CAAC,UAAU,CAEpB;gBAG+B,OAAO,EAAE,OAAO,CAAC,oBAAoB,CAAC;IAkB5E;;;;OAIG;IACI,WAAW,IAAI,sBAAsB;IAuCrC,mBAAmB,CAAC,QAAQ,EAAE,MAAM,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,SAAS;IAcnE,WAAW,CAAC,UAAU,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,GAAG,MAAM;CAQnE"}
@@ -0,0 +1,100 @@
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 __param = (this && this.__param) || function (paramIndex, decorator) {
11
+ return function (target, key) { decorator(target, key, paramIndex); }
12
+ };
13
+ import { filterNonUndefined } from "@proto-kit/common";
14
+ import { stringToField } from "@proto-kit/protocol";
15
+ import { Poseidon } from "o1js";
16
+ import { inject, injectable } from "tsyringe";
17
+ import { runtimeMethodTypeMetadataKey, } from "../method/runtimeMethod";
18
+ /**
19
+ * Please see `getMethodId` to learn more about
20
+ * methodId encoding
21
+ */
22
+ export let MethodIdResolver = class MethodIdResolver {
23
+ constructor(runtime) {
24
+ Object.defineProperty(this, "runtime", {
25
+ enumerable: true,
26
+ configurable: true,
27
+ writable: true,
28
+ value: runtime
29
+ });
30
+ Object.defineProperty(this, "dictionary", {
31
+ enumerable: true,
32
+ configurable: true,
33
+ writable: true,
34
+ value: {}
35
+ });
36
+ this.dictionary = runtime.runtimeModuleNames.reduce((dict, moduleName) => {
37
+ this.runtime.assertIsValidModuleName(moduleName);
38
+ runtime.resolve(moduleName).runtimeMethodNames.forEach((methodName) => {
39
+ dict[this.getMethodId(moduleName, methodName).toString()] = {
40
+ moduleName,
41
+ methodName,
42
+ };
43
+ });
44
+ return dict;
45
+ }, {});
46
+ }
47
+ /**
48
+ * The purpose of this method is to provide a dictionary where
49
+ * we can look up properties like methodId and invocationType
50
+ * for each runtimeMethod using their module name and method name
51
+ */
52
+ methodIdMap() {
53
+ const methodIdResolver = this.runtime.dependencyContainer.resolve("MethodIdResolver");
54
+ const rawMappings = this.runtime.moduleNames.flatMap((moduleName) => {
55
+ const module = this.runtime.resolve(moduleName);
56
+ return module.runtimeMethodNames.map((method) => {
57
+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
58
+ const type = Reflect.getMetadata(runtimeMethodTypeMetadataKey, module, method);
59
+ if (type !== undefined) {
60
+ return {
61
+ name: `${moduleName}.${method}`,
62
+ methodId: methodIdResolver.getMethodId(moduleName, method),
63
+ type,
64
+ };
65
+ }
66
+ return undefined;
67
+ });
68
+ });
69
+ return rawMappings
70
+ .filter(filterNonUndefined)
71
+ .reduce((acc, entry) => {
72
+ acc[entry.name] = {
73
+ methodId: entry.methodId,
74
+ type: entry.type,
75
+ };
76
+ return acc;
77
+ }, {});
78
+ }
79
+ getMethodNameFromId(methodId) {
80
+ const methodPath = this.dictionary[methodId.toString()];
81
+ if (methodPath === undefined) {
82
+ return undefined;
83
+ }
84
+ const { moduleName, methodName } = methodPath;
85
+ this.runtime.assertIsValidModuleName(moduleName);
86
+ return [moduleName, methodName];
87
+ }
88
+ getMethodId(moduleName, methodName) {
89
+ this.runtime.assertIsValidModuleName(moduleName);
90
+ return Poseidon.hash([
91
+ stringToField(moduleName),
92
+ stringToField(methodName),
93
+ ]).toBigInt();
94
+ }
95
+ };
96
+ MethodIdResolver = __decorate([
97
+ injectable(),
98
+ __param(0, inject("Runtime")),
99
+ __metadata("design:paramtypes", [Function])
100
+ ], MethodIdResolver);