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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. package/dist/factories/MethodIdFactory.d.ts +9 -0
  2. package/dist/factories/MethodIdFactory.d.ts.map +1 -0
  3. package/dist/factories/MethodIdFactory.js +12 -0
  4. package/dist/factories/MethodIdFactory.js.map +1 -0
  5. package/dist/index.d.ts +5 -7
  6. package/dist/index.d.ts.map +1 -1
  7. package/dist/index.js +6 -7
  8. package/dist/index.js.map +1 -0
  9. package/dist/messages/OutgoingMessages.d.ts +215 -0
  10. package/dist/messages/OutgoingMessages.d.ts.map +1 -0
  11. package/dist/messages/OutgoingMessages.js +66 -0
  12. package/dist/messages/OutgoingMessages.js.map +1 -0
  13. package/dist/method/MethodParameterEncoder.d.ts +26 -0
  14. package/dist/method/MethodParameterEncoder.d.ts.map +1 -0
  15. package/dist/method/MethodParameterEncoder.js +169 -0
  16. package/dist/method/MethodParameterEncoder.js.map +1 -0
  17. package/dist/method/runtimeMethod.d.ts +22 -5
  18. package/dist/method/runtimeMethod.d.ts.map +1 -1
  19. package/dist/method/runtimeMethod.js +79 -24
  20. package/dist/method/runtimeMethod.js.map +1 -0
  21. package/dist/module/decorator.js +1 -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 +22 -28
  28. package/dist/runtime/Runtime.d.ts.map +1 -1
  29. package/dist/runtime/Runtime.js +116 -70
  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 +23 -14
  36. package/dist/runtime/RuntimeModule.d.ts.map +1 -1
  37. package/dist/runtime/RuntimeModule.js +47 -10
  38. package/dist/runtime/RuntimeModule.js.map +1 -0
  39. package/dist/state/InMemoryStateService.d.ts +11 -10
  40. package/dist/state/InMemoryStateService.d.ts.map +1 -1
  41. package/dist/state/InMemoryStateService.js +11 -8
  42. package/dist/state/InMemoryStateService.js.map +1 -0
  43. package/jest.config.cjs +12 -1
  44. package/package.json +10 -11
  45. package/src/factories/MethodIdFactory.ts +15 -0
  46. package/src/index.ts +5 -7
  47. package/src/messages/OutgoingMessages.ts +122 -0
  48. package/src/method/MethodParameterEncoder.ts +260 -0
  49. package/src/method/runtimeMethod.ts +146 -31
  50. package/src/runtime/MethodIdResolver.ts +108 -0
  51. package/src/runtime/Runtime.ts +191 -112
  52. package/src/runtime/RuntimeEnvironment.ts +16 -0
  53. package/src/runtime/RuntimeModule.ts +77 -27
  54. package/src/state/InMemoryStateService.ts +14 -18
  55. package/test/Runtime.test.ts +69 -36
  56. package/test/TestingRuntime.ts +43 -0
  57. package/test/messages/message.test.ts +42 -0
  58. package/test/method/MethodParameterEncoder.test.ts +121 -0
  59. package/test/method/runtimeMethod-fail.test.ts +50 -0
  60. package/{src/method/decorator.test.ts → test/method/runtimeMethod.test.ts} +3 -3
  61. package/test/modules/Admin.ts +4 -4
  62. package/test/modules/Balances.test.ts +92 -78
  63. package/test/modules/Balances.ts +19 -16
  64. package/test/modules/MethodIdResolver.test.ts +73 -0
  65. package/test/modules/State.test.ts +81 -0
  66. package/test/runtimeMethod.test.ts +192 -20
  67. package/test/tsconfig.json +7 -0
  68. package/tsconfig.json +2 -2
  69. package/dist/chain/Chain.d.ts +0 -109
  70. package/dist/chain/Chain.d.ts.map +0 -1
  71. package/dist/chain/Chain.js +0 -229
  72. package/dist/method/MethodExecutionContext.d.ts +0 -73
  73. package/dist/method/MethodExecutionContext.d.ts.map +0 -1
  74. package/dist/method/MethodExecutionContext.js +0 -112
  75. package/dist/method/MethodParameterDecoder.d.ts +0 -22
  76. package/dist/method/MethodParameterDecoder.d.ts.map +0 -1
  77. package/dist/method/MethodParameterDecoder.js +0 -33
  78. package/dist/method/RuntimeMethodExecutionContext.d.ts +0 -57
  79. package/dist/method/RuntimeMethodExecutionContext.d.ts.map +0 -1
  80. package/dist/method/RuntimeMethodExecutionContext.js +0 -92
  81. package/dist/method/assert.d.ts +0 -12
  82. package/dist/method/assert.d.ts.map +0 -1
  83. package/dist/method/assert.js +0 -23
  84. package/dist/method/decorator.d.ts +0 -45
  85. package/dist/method/decorator.d.ts.map +0 -1
  86. package/dist/method/decorator.js +0 -140
  87. package/dist/state/State.d.ts +0 -65
  88. package/dist/state/State.d.ts.map +0 -1
  89. package/dist/state/State.js +0 -114
  90. package/dist/state/StateMap.d.ts +0 -37
  91. package/dist/state/StateMap.d.ts.map +0 -1
  92. package/dist/state/StateMap.js +0 -56
  93. package/dist/state/StateServiceProvider.d.ts +0 -10
  94. package/dist/state/StateServiceProvider.d.ts.map +0 -1
  95. package/dist/state/StateServiceProvider.js +0 -34
  96. package/dist/state/decorator.d.ts +0 -7
  97. package/dist/state/decorator.d.ts.map +0 -1
  98. package/dist/state/decorator.js +0 -42
  99. package/src/method/MethodParameterDecoder.ts +0 -68
  100. package/src/method/RuntimeMethodExecutionContext.ts +0 -111
  101. package/src/method/assert.test.ts +0 -49
  102. package/src/method/assert.ts +0 -27
  103. package/src/state/State.ts +0 -154
  104. package/src/state/StateMap.ts +0 -69
  105. package/src/state/StateServiceProvider.ts +0 -24
  106. package/src/state/decorator.ts +0 -65
  107. package/test/state/MerkleTree.test.ts +0 -95
  108. package/test/state/MockAsyncMerkleStore.ts +0 -28
  109. package/test/transaction.test.ts +0 -82
  110. package/tsconfig.test.json +0 -9
@@ -1,37 +1,101 @@
1
1
  import "reflect-metadata";
2
- import { Bool, PublicKey } from "snarkyjs";
2
+ import {
3
+ PublicKey,
4
+ Struct,
5
+ Bool,
6
+ PrivateKey,
7
+ Field,
8
+ UInt64,
9
+ Poseidon,
10
+ } from "o1js";
11
+ import {
12
+ MethodPublicOutput,
13
+ NetworkState,
14
+ RuntimeMethodExecutionContext,
15
+ RuntimeTransaction,
16
+ } from "@proto-kit/protocol";
17
+ import { container } from "tsyringe";
18
+ import { AreProofsEnabled, log } from "@proto-kit/common";
3
19
 
4
- import { InMemoryStateService, Runtime } from "../src";
5
- import { MethodParameterDecoder } from "../src/method/MethodParameterDecoder";
20
+ import {
21
+ Runtime,
22
+ MethodParameterEncoder,
23
+ runtimeModule,
24
+ RuntimeModule,
25
+ runtimeMethod,
26
+ toEventsHash,
27
+ RuntimeEvents,
28
+ } from "../src";
6
29
 
7
30
  import { Balances } from "./modules/Balances";
31
+ import { createTestingRuntime } from "./TestingRuntime";
8
32
 
9
- describe("runtimeMethod", () => {
10
- const parameters = [PublicKey.empty()];
33
+ export class PrimaryTestEvent extends Struct({
34
+ message: Bool,
35
+ }) {}
11
36
 
12
- it("should create correct param types", () => {
13
- // eslint-disable-next-line jest/prefer-expect-assertions
14
- expect.assertions(1 + parameters.length);
37
+ export class SecondaryTestEvent extends Struct({
38
+ message: Bool,
39
+ }) {}
40
+
41
+ @runtimeModule()
42
+ class EventMaker extends RuntimeModule {
43
+ public constructor() {
44
+ super();
45
+ }
15
46
 
16
- const runtime = Runtime.from({
17
- state: new InMemoryStateService(),
47
+ public events = new RuntimeEvents({
48
+ primary: PrimaryTestEvent,
49
+ secondary: SecondaryTestEvent,
50
+ });
18
51
 
19
- modules: {
52
+ @runtimeMethod()
53
+ public async makeEvent() {
54
+ this.events.emit("primary", new PrimaryTestEvent({ message: Bool(false) }));
55
+ // Should not emit as condition is false.
56
+ this.events.emitIf(
57
+ Bool(false),
58
+ "primary",
59
+ new PrimaryTestEvent({ message: Bool(false) })
60
+ );
61
+ this.events.emit(
62
+ "secondary",
63
+ new SecondaryTestEvent({ message: Bool(true) })
64
+ );
65
+ }
66
+ }
67
+
68
+ describe("runtimeMethod", () => {
69
+ const parameters = [PublicKey.empty<typeof PublicKey>()];
70
+
71
+ let runtime: Runtime<{
72
+ Balances: typeof Balances;
73
+ EventMaker: typeof EventMaker;
74
+ }>;
75
+
76
+ beforeEach(() => {
77
+ log.setLevel(log.levels.DEBUG);
78
+ ({ runtime } = createTestingRuntime(
79
+ {
20
80
  Balances,
81
+ EventMaker,
21
82
  },
83
+ {
84
+ Balances: {},
85
+ EventMaker: {},
86
+ }
87
+ ));
88
+ });
22
89
 
23
- config: {
24
- Balances: {
25
- test: Bool(true),
26
- },
27
- },
28
- });
90
+ it("should create correct param types", async () => {
91
+ expect.assertions(1 + parameters.length);
29
92
 
30
93
  const module = runtime.resolve("Balances");
31
94
 
32
- const decoder = MethodParameterDecoder.fromMethod(module, "getBalance");
33
- const recodedParameters = decoder.fromFields(
34
- parameters.flatMap((x) => x.toFields())
95
+ const decoder = MethodParameterEncoder.fromMethod(module, "getBalance");
96
+ const recodedParameters = await decoder.decode(
97
+ parameters.flatMap((x) => x.toFields()),
98
+ []
35
99
  );
36
100
 
37
101
  expect(parameters).toHaveLength(recodedParameters.length);
@@ -40,4 +104,112 @@ describe("runtimeMethod", () => {
40
104
  expect(parameter).toStrictEqual(recodedParameters[index]);
41
105
  });
42
106
  });
107
+
108
+ it("should throw on incorrect methodId on tx", async () => {
109
+ expect.assertions(1);
110
+
111
+ const context = container.resolve(RuntimeMethodExecutionContext);
112
+
113
+ runtime.registerValue({
114
+ AppChain: {
115
+ areProofsEnabled: false,
116
+ } as AreProofsEnabled,
117
+ });
118
+
119
+ context.setup({
120
+ transaction: RuntimeTransaction.dummyTransaction(),
121
+ networkState: NetworkState.empty(),
122
+ });
123
+
124
+ const module = runtime.resolve("Balances");
125
+ await module.getBalance(PublicKey.empty<typeof PublicKey>());
126
+
127
+ context.setup({
128
+ transaction: RuntimeTransaction.dummyTransaction(),
129
+ networkState: NetworkState.empty(),
130
+ });
131
+
132
+ await expect(context.current().result.prover!()).rejects.toThrow(
133
+ "Runtimemethod called with wrong methodId on the transaction object"
134
+ );
135
+ });
136
+
137
+ it("should capture event", async () => {
138
+ expect.assertions(5);
139
+
140
+ const context = container.resolve(RuntimeMethodExecutionContext);
141
+
142
+ runtime.registerValue({
143
+ AppChain: {
144
+ areProofsEnabled: false,
145
+ } as AreProofsEnabled,
146
+ });
147
+
148
+ const eventMakerMethodId = runtime.methodIdResolver.getMethodId(
149
+ "EventMaker",
150
+ "makeEvent"
151
+ );
152
+
153
+ const privateKey = PrivateKey.random();
154
+ context.setup({
155
+ transaction: RuntimeTransaction.fromTransaction({
156
+ sender: privateKey.toPublicKey(),
157
+ nonce: UInt64.from(0),
158
+ methodId: Field(eventMakerMethodId),
159
+ argsHash: Poseidon.hash([]),
160
+ }),
161
+ networkState: NetworkState.empty(),
162
+ });
163
+
164
+ const module = runtime.resolve("EventMaker");
165
+ await module.makeEvent();
166
+
167
+ const firstExpectedEvent = {
168
+ eventType: PrimaryTestEvent,
169
+ event: new PrimaryTestEvent({
170
+ message: Bool(false),
171
+ }),
172
+ eventName: "primary",
173
+ condition: Bool(true),
174
+ };
175
+
176
+ const secondExpectedEvent = {
177
+ eventType: PrimaryTestEvent,
178
+ event: new PrimaryTestEvent({
179
+ message: Bool(false),
180
+ }),
181
+ eventName: "primary",
182
+ condition: Bool(false),
183
+ };
184
+
185
+ const thirdExpectedEvent = {
186
+ eventType: SecondaryTestEvent,
187
+ event: new SecondaryTestEvent({
188
+ message: Bool(true),
189
+ }),
190
+ eventName: "secondary",
191
+ condition: Bool(true),
192
+ };
193
+
194
+ const eventsResults = context.current().result.events;
195
+ expect(eventsResults).toHaveLength(3);
196
+ expect(eventsResults[0]).toStrictEqual(firstExpectedEvent);
197
+ expect(eventsResults[1]).toStrictEqual(secondExpectedEvent);
198
+ expect(eventsResults[2]).toStrictEqual(thirdExpectedEvent);
199
+
200
+ context.afterMethod();
201
+
202
+ const proof = await context.current().result.prover!();
203
+ const publicOuput = proof.publicOutput as MethodPublicOutput;
204
+ const { eventsHash } = publicOuput;
205
+ // Note that we omit the second event from below as it was
206
+ // not emitted due to the condition being false.
207
+ expect(eventsHash).toStrictEqual(
208
+ toEventsHash([
209
+ { ...firstExpectedEvent, condition: Bool(true) },
210
+ { ...secondExpectedEvent, condition: Bool(false) },
211
+ { ...thirdExpectedEvent, condition: Bool(true) },
212
+ ])
213
+ );
214
+ });
43
215
  });
@@ -0,0 +1,7 @@
1
+ {
2
+ "extends": "./../../../tsconfig.json",
3
+ "compilerOptions": {
4
+ "experimentalDecorators": true
5
+ },
6
+ "include": ["../src/**/*.test.ts", "./**/*.ts", "./*.ts", "../src/**/*.ts"]
7
+ }
package/tsconfig.json CHANGED
@@ -3,6 +3,6 @@
3
3
  "compilerOptions": {
4
4
  "outDir": "./dist"
5
5
  },
6
- "include": ["./src", "src/index.ts"],
7
- "exclude": ["./dist/**/*.ts", "./**/*.test.ts", "./test/**/*.ts"]
6
+ "include": ["./src/index.ts"],
7
+ "exclude": ["./dist/**/*.ts"]
8
8
  }
@@ -1,109 +0,0 @@
1
- import { Experimental, Proof } from "snarkyjs";
2
- import { MethodPublicInput, Subclass } from "@yab/protocol";
3
- import { type AnyConstructor } from "../module/decorator.js";
4
- import type { StateService } from "../state/InMemoryStateService.js";
5
- export interface RuntimeModules {
6
- [name: string]: AnyConstructor;
7
- }
8
- export interface ChainConfig<ChainRuntimeModules extends RuntimeModules> {
9
- state: StateService;
10
- runtimeModules: ChainRuntimeModules;
11
- }
12
- /**
13
- * Wrapper for an application specific chain, which helps orchestrate
14
- * runtime modules into an interoperable runtime.
15
- */
16
- export declare class Chain<ChainRuntimeModules extends RuntimeModules> {
17
- config: ChainConfig<ChainRuntimeModules>;
18
- /**
19
- * Alternative constructor for `Chain`.
20
- *
21
- * @param config - Configuration for the returned Chain
22
- * @returns Chain with the provided config
23
- */
24
- static from<ChainRuntimeModules extends RuntimeModules>(config: ChainConfig<ChainRuntimeModules>): Chain<ChainRuntimeModules>;
25
- private readonly runtimeContainer;
26
- areProofsEnabled: boolean;
27
- program?: ReturnType<typeof Experimental.ZkProgram>;
28
- /**
29
- * Creates a new Chain from the provided config
30
- *
31
- * @param config - Configuration object for the constructed Chain
32
- */
33
- constructor(config: ChainConfig<ChainRuntimeModules>);
34
- /**
35
- * Add a name and other respective properties required by RuntimeModules,
36
- * that come from the current Chain
37
- *
38
- * @param name - Name of the runtime module to decorate
39
- */
40
- private decorateRuntimeModule;
41
- /**
42
- * @returns A list of
43
- */
44
- get runtimeModuleNames(): string[];
45
- /**
46
- * Returns a runtime module registred under the given key.
47
- *
48
- * @param name - Name of the runtime module to get
49
- * @returns A runtime module stored under the given key
50
- */
51
- getRuntimeModule<Key extends keyof ChainRuntimeModules>(name: Key): InstanceType<ChainRuntimeModules[Key]>;
52
- /**
53
- * Registers a runtime module under the given name.
54
- *
55
- * @param name - Name of the runtime module to identify it by
56
- * @param runtimeModule - Runtime module to register
57
- */
58
- registerRuntimeModule(name: string, runtimeModule: AnyConstructor): void;
59
- /**
60
- * Sets if proofs are enabled or not
61
- * @param areProofsEnabled
62
- */
63
- setProofsEnabled(areProofsEnabled: boolean): void;
64
- /**
65
- * Precompiles the current runtime modules into a ZkProgram.
66
- *
67
- * @returns - Analysis of the precompiled ZkProgram
68
- */
69
- precompile(): {
70
- analyze: (this: Chain<RuntimeModules>) => {
71
- methodName: string;
72
- analysis: {
73
- rows: number;
74
- gates: import("snarkyjs/dist/node/snarky.js").Gate[];
75
- inputs: [] | [import("snarkyjs/dist/node/snarky.js").Provable<any> | ((new (...args: any) => Proof<unknown>) & {
76
- prototype: Proof<any>;
77
- publicInputType: import("snarkyjs/dist/node/lib/circuit_value.js").FlexibleProvablePure<any>;
78
- tag: () => {
79
- name: string;
80
- };
81
- fromJSON: typeof Proof.fromJSON;
82
- } & {
83
- prototype: Proof<unknown>;
84
- }), ...(import("snarkyjs/dist/node/snarky.js").Provable<any> | ((new (...args: any) => Proof<unknown>) & {
85
- prototype: Proof<any>;
86
- publicInputType: import("snarkyjs/dist/node/lib/circuit_value.js").FlexibleProvablePure<any>;
87
- tag: () => {
88
- name: string;
89
- };
90
- fromJSON: typeof Proof.fromJSON;
91
- } & {
92
- prototype: Proof<unknown>;
93
- }))[]];
94
- };
95
- }[];
96
- toPretty: () => void;
97
- };
98
- getProofClass(): Subclass<typeof Proof<MethodPublicInput>>;
99
- /**
100
- * Compiles the current runtime modules configuration
101
- * into a ZkProgram and then into a verification key.
102
- *
103
- * @returns The resulting artifact of ZkProgram compilation (verification key)
104
- */
105
- compile(): Promise<{
106
- verificationKey: string;
107
- }>;
108
- }
109
- //# sourceMappingURL=Chain.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"Chain.d.ts","sourceRoot":"","sources":["../../src/chain/Chain.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,YAAY,EAAE,KAAK,EAAE,MAAM,UAAU,CAAC;AAC/C,OAAO,EAAE,iBAAiB,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAO5D,OAAO,EAAE,KAAK,cAAc,EAAmB,MAAM,wBAAwB,CAAC;AAE9E,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,kCAAkC,CAAC;AAErE,MAAM,WAAW,cAAc;IAC7B,CAAC,IAAI,EAAE,MAAM,GAAG,cAAc,CAAC;CAChC;AAED,MAAM,WAAW,WAAW,CAAC,mBAAmB,SAAS,cAAc;IACrE,KAAK,EAAE,YAAY,CAAC;IACpB,cAAc,EAAE,mBAAmB,CAAC;CACrC;AAyCD;;;GAGG;AACH,qBAAa,KAAK,CAAC,mBAAmB,SAAS,cAAc;IA2BjC,MAAM,EAAE,WAAW,CAAC,mBAAmB,CAAC;IA1BlE;;;;;OAKG;WACW,IAAI,CAAC,mBAAmB,SAAS,cAAc,EAC3D,MAAM,EAAE,WAAW,CAAC,mBAAmB,CAAC;IAM1C,OAAO,CAAC,QAAQ,CAAC,gBAAgB,CAAsB;IAGhD,gBAAgB,UAAS;IAGzB,OAAO,CAAC,EAAE,UAAU,CAAC,OAAO,YAAY,CAAC,SAAS,CAAC,CAAC;IAE3D;;;;OAIG;gBACuB,MAAM,EAAE,WAAW,CAAC,mBAAmB,CAAC;IASlE;;;;;OAKG;IACH,OAAO,CAAC,qBAAqB;IAO7B;;OAEG;IACH,IAAW,kBAAkB,aAE5B;IAED;;;;;OAKG;IACI,gBAAgB,CAAC,GAAG,SAAS,MAAM,mBAAmB,EAAE,IAAI,EAAE,GAAG;IAexE;;;;;OAKG;IACI,qBAAqB,CAAC,IAAI,EAAE,MAAM,EAAE,aAAa,EAAE,cAAc;IAkCxE;;;OAGG;IACI,gBAAgB,CAAC,gBAAgB,EAAE,OAAO;IAIjD;;;;OAIG;IACI,UAAU;wBA8EQ,MAAM,cAAc,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;IA4CvC,aAAa,IAAI,QAAQ,CAAC,OAAO,KAAK,CAAC,iBAAiB,CAAC,CAAC;IAcjE;;;;;OAKG;IACU,OAAO;;;CAcrB"}
@@ -1,229 +0,0 @@
1
- /* eslint-disable max-lines */
2
- import { container, Lifecycle } from "tsyringe";
3
- import { Experimental, Proof } from "snarkyjs";
4
- import { MethodPublicInput } from "@yab/protocol";
5
- import { combineMethodName, isMethod, toWrappedMethod, } from "../method/decorator.js";
6
- import { isRuntimeModule } from "../module/decorator.js";
7
- const errors = {
8
- onlyStringNames: () => new TypeError("Only string names are supported"),
9
- notRegistredRuntimeModule: (name) => new Error(`Unable to retrieve module: ${name}, it is not registred as a runtime module for this chain`),
10
- missingDecorator: (name, runtimeModuleName) => new Error(`Unable to register module: ${name} / ${runtimeModuleName},
11
- did you forget to add @runtimeModule()?`),
12
- nonModuleDependecy: (runtimeModuleName) => new Error(`
13
- Unable to register module: ${runtimeModuleName}, attempting to inject a non-module dependency`),
14
- unknownDependency: (runtimeModuleName, name) => new Error(`Unable to register module: ${runtimeModuleName},
15
- attempting to inject a dependency that is not registred
16
- as a runtime module for this chain: ${name}`),
17
- unableToAnalyze: (name) => new Error(`Unable to analyze program for chain: ${name}`),
18
- precompileFirst: () => new Error("You have to call precompile() before being able to create the proof class"),
19
- zkProgramMissing: () => new Error("Unable to compile chain, pre-compilation did not produce a zkProgram"),
20
- };
21
- /**
22
- * Wrapper for an application specific chain, which helps orchestrate
23
- * runtime modules into an interoperable runtime.
24
- */
25
- export class Chain {
26
- /**
27
- * Alternative constructor for `Chain`.
28
- *
29
- * @param config - Configuration for the returned Chain
30
- * @returns Chain with the provided config
31
- */
32
- static from(config) {
33
- return new Chain(config);
34
- }
35
- /**
36
- * Creates a new Chain from the provided config
37
- *
38
- * @param config - Configuration object for the constructed Chain
39
- */
40
- constructor(config) {
41
- this.config = config;
42
- // determines whether any proving should be done when running methods
43
- this.areProofsEnabled = false;
44
- this.runtimeContainer = container.createChildContainer();
45
- Object.entries(this.config.runtimeModules).forEach(([name, runtimeModule]) => {
46
- this.registerRuntimeModule(name, runtimeModule);
47
- });
48
- }
49
- /**
50
- * Add a name and other respective properties required by RuntimeModules,
51
- * that come from the current Chain
52
- *
53
- * @param name - Name of the runtime module to decorate
54
- */
55
- decorateRuntimeModule(name) {
56
- const runtimeModuleInstance = this.runtimeContainer.resolve(name);
57
- runtimeModuleInstance.name = name;
58
- runtimeModuleInstance.chain = this;
59
- }
60
- /**
61
- * @returns A list of
62
- */
63
- get runtimeModuleNames() {
64
- return Object.keys(this.config.runtimeModules);
65
- }
66
- /**
67
- * Returns a runtime module registred under the given key.
68
- *
69
- * @param name - Name of the runtime module to get
70
- * @returns A runtime module stored under the given key
71
- */
72
- getRuntimeModule(name) {
73
- if (typeof name !== "string") {
74
- throw errors.onlyStringNames();
75
- }
76
- if (!this.runtimeModuleNames.includes(name)) {
77
- throw errors.notRegistredRuntimeModule(name);
78
- }
79
- // eslint-disable-next-line @typescript-eslint/no-unsafe-return
80
- return this.runtimeContainer.resolve(name);
81
- }
82
- /**
83
- * Registers a runtime module under the given name.
84
- *
85
- * @param name - Name of the runtime module to identify it by
86
- * @param runtimeModule - Runtime module to register
87
- */
88
- registerRuntimeModule(name, runtimeModule) {
89
- if (!isRuntimeModule(runtimeModule)) {
90
- throw errors.missingDecorator(name, runtimeModule.name);
91
- }
92
- this.runtimeContainer.register(name, {
93
- useClass: runtimeModule,
94
- }, {
95
- lifecycle: Lifecycle.ContainerScoped,
96
- });
97
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
98
- const dependencies = Reflect.getMetadata("design:paramtypes", runtimeModule);
99
- dependencies?.forEach((dependency) => {
100
- const name = typeof dependency === "string" ? dependency : dependency.name;
101
- // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
102
- if (!name) {
103
- throw errors.nonModuleDependecy(runtimeModule.name);
104
- }
105
- if (!this.runtimeModuleNames.includes(name)) {
106
- throw errors.unknownDependency(runtimeModule.name, name);
107
- }
108
- });
109
- this.decorateRuntimeModule(name);
110
- }
111
- /**
112
- * Sets if proofs are enabled or not
113
- * @param areProofsEnabled
114
- */
115
- setProofsEnabled(areProofsEnabled) {
116
- this.areProofsEnabled = areProofsEnabled;
117
- }
118
- /**
119
- * Precompiles the current runtime modules into a ZkProgram.
120
- *
121
- * @returns - Analysis of the precompiled ZkProgram
122
- */
123
- precompile() {
124
- const methods = this.runtimeModuleNames.reduce((allMethods, runtimeModuleName) => {
125
- // eslint-disable-next-line max-len
126
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
127
- const runtimeModule = this.getRuntimeModule(runtimeModuleName);
128
- // eslint-disable-next-line max-len
129
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
130
- const modulePrototype = Object.getPrototypeOf(runtimeModule);
131
- const modulePrototypeMethods = Object.getOwnPropertyNames(modulePrototype);
132
- const moduleMethods = modulePrototypeMethods.reduce((allModuleMethods, methodName) => {
133
- if (isMethod(runtimeModule, methodName)) {
134
- const combinedMethodName = combineMethodName(runtimeModuleName, methodName);
135
- const method = modulePrototype[methodName];
136
- const wrappedMethod = Reflect.apply(toWrappedMethod, runtimeModule, [methodName, method]);
137
- // eslint-disable-next-line no-warning-comments
138
- // TODO: find out how to import the Tuple type
139
- // eslint-disable-next-line max-len
140
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
141
- const privateInputs = Reflect.getMetadata("design:paramtypes", runtimeModule, methodName);
142
- return {
143
- ...allModuleMethods,
144
- [combinedMethodName]: {
145
- // eslint-disable-next-line max-len
146
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
147
- privateInputs,
148
- method: wrappedMethod,
149
- },
150
- };
151
- }
152
- return allModuleMethods;
153
- }, {});
154
- return {
155
- ...allMethods,
156
- ...moduleMethods,
157
- };
158
- }, {});
159
- // eslint-disable-next-line @typescript-eslint/require-array-sort-compare
160
- const sortedMethods = Object.fromEntries(Object.entries(methods).sort());
161
- this.program = Experimental.ZkProgram({
162
- publicInput: MethodPublicInput,
163
- methods: sortedMethods,
164
- });
165
- function analyze() {
166
- if (!this.program) {
167
- throw errors.unableToAnalyze(this.constructor.name);
168
- }
169
- const zkProgramAnalysis = this.program.analyzeMethods();
170
- return Object.keys(sortedMethods).map((methodName, index) => {
171
- const { rows, gates } = zkProgramAnalysis[index];
172
- const { privateInputs: inputs } = sortedMethods[methodName];
173
- return {
174
- methodName,
175
- analysis: {
176
- rows,
177
- gates,
178
- inputs,
179
- },
180
- };
181
- });
182
- }
183
- return {
184
- analyze,
185
- toPretty: () => {
186
- Reflect.apply(analyze, this, []).forEach(({ methodName, analysis: methodAnalysis }) => {
187
- const inputs = methodAnalysis.inputs.map(
188
- // eslint-disable-next-line max-len
189
- // eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/consistent-type-assertions, @typescript-eslint/no-explicit-any
190
- (input) => input.name);
191
- console.log(`
192
- Method: ${methodName}
193
- Rows: ${methodAnalysis.rows},
194
- Gates: ${methodAnalysis.gates.length}
195
- Inputs: [${inputs.join(", ")}]
196
- `);
197
- });
198
- },
199
- };
200
- }
201
- getProofClass() {
202
- if (this.program === undefined) {
203
- throw errors.precompileFirst();
204
- }
205
- const { program } = this;
206
- return ((programClosure) => { var _a; return _a = class AppChainProof extends Proof {
207
- },
208
- _a.publicInputType = MethodPublicInput,
209
- _a.tag = () => programClosure,
210
- _a; })(program);
211
- }
212
- /**
213
- * Compiles the current runtime modules configuration
214
- * into a ZkProgram and then into a verification key.
215
- *
216
- * @returns The resulting artifact of ZkProgram compilation (verification key)
217
- */
218
- async compile() {
219
- this.precompile();
220
- if (!this.program) {
221
- throw errors.zkProgramMissing();
222
- }
223
- const { areProofsEnabled, program } = this;
224
- this.setProofsEnabled(false);
225
- const artifact = await program.compile();
226
- this.setProofsEnabled(areProofsEnabled);
227
- return artifact;
228
- }
229
- }
@@ -1,73 +0,0 @@
1
- import { Bool, type Proof } from "snarkyjs";
2
- import type { StateTransition, MethodPublicInput } from "@yab/protocol";
3
- export declare class MethodExecutionResult<ResultValue> {
4
- stateTransitions: StateTransition<any>[];
5
- status: Bool;
6
- statusMessage?: string;
7
- value?: ResultValue;
8
- publicInput?: MethodPublicInput;
9
- prove?: () => Promise<Proof<MethodPublicInput>>;
10
- }
11
- /**
12
- * Execution context used to wrap runtime module methods,
13
- * allowing them to post relevant information (such as execution status)
14
- * into the context without any unnecessary 'prop drilling'.
15
- */
16
- export declare class MethodExecutionContext<ResultValue> {
17
- result: MethodExecutionResult<ResultValue>;
18
- methods: string[];
19
- constructor(result?: MethodExecutionResult<ResultValue>);
20
- /**
21
- * Adds an in-method generated state transition to the current context
22
- * @param stateTransition - State transition to add to the context
23
- */
24
- addStateTransition<Value>(stateTransition: StateTransition<Value>): void;
25
- /**
26
- * @param message - Status message to acompany the current status
27
- */
28
- setStatusMessage(message?: string): void;
29
- /**
30
- * @param status - Execution status of the current method
31
- */
32
- setStatus(status: Bool): void;
33
- /**
34
- * @param value = Return value of the executed method
35
- */
36
- setValue(value: ResultValue): void;
37
- /**
38
- * Adds a method prover to the current execution context,
39
- * which can be collected and ran asynchronously at a later point in time.
40
- *
41
- * @param prove - Prover function to be ran later,
42
- * when the method execution needs to be proven
43
- */
44
- setProve(prove: () => Promise<Proof<MethodPublicInput>>): void;
45
- setPublicInput(publicInput: MethodPublicInput): void;
46
- /**
47
- * Adds a method to the method execution stack, reseting the execution context
48
- * in a case a new top-level (non nested) method call is made.
49
- *
50
- * @param methodName - Name of the method being captured in the context
51
- */
52
- beforeMethod(methodName: string): void;
53
- /**
54
- * Removes the latest method from the execution context stack,
55
- * keeping track of the amount of 'unfinished' methods. Allowing
56
- * for the context to distinguish between top-level and nested method calls.
57
- */
58
- afterMethod(): void;
59
- get isTopLevel(): boolean;
60
- get isFinished(): boolean;
61
- /**
62
- * @returns - Current execution context state
63
- */
64
- current(): {
65
- isFinished: boolean;
66
- result: MethodExecutionResult<ResultValue>;
67
- };
68
- /**
69
- * Manually clears/resets the execution context
70
- */
71
- clear(): void;
72
- }
73
- //# sourceMappingURL=MethodExecutionContext.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"MethodExecutionContext.d.ts","sourceRoot":"","sources":["../../src/method/MethodExecutionContext.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,KAAK,KAAK,EAAE,MAAM,UAAU,CAAC;AAE5C,OAAO,KAAK,EAAE,eAAe,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAExE,qBAAa,qBAAqB,CAAC,WAAW;IAErC,gBAAgB,EAAE,eAAe,CAAC,GAAG,CAAC,EAAE,CAAM;IAE9C,MAAM,EAAE,IAAI,CAAc;IAE1B,aAAa,CAAC,EAAE,MAAM,CAAC;IAEvB,KAAK,CAAC,EAAE,WAAW,CAAC;IAEpB,WAAW,CAAC,EAAE,iBAAiB,CAAC;IAEhC,KAAK,CAAC,EAAE,MAAM,OAAO,CAAC,KAAK,CAAC,iBAAiB,CAAC,CAAC,CAAC;CACxD;AAED;;;;GAIG;AACH,qBACa,sBAAsB,CAAC,WAAW;IAIpC,MAAM,EAAE,qBAAqB,CAAC,WAAW,CAAC;IAH5C,OAAO,EAAE,MAAM,EAAE,CAAM;gBAGrB,MAAM,GAAE,qBAAqB,CAAC,WAAW,CAA+B;IAGjF;;;OAGG;IACI,kBAAkB,CAAC,KAAK,EAAE,eAAe,EAAE,eAAe,CAAC,KAAK,CAAC;IAIxE;;OAEG;IACI,gBAAgB,CAAC,OAAO,CAAC,EAAE,MAAM;IAIxC;;OAEG;IACI,SAAS,CAAC,MAAM,EAAE,IAAI;IAI7B;;OAEG;IACI,QAAQ,CAAC,KAAK,EAAE,WAAW;IAIlC;;;;;;OAMG;IACI,QAAQ,CAAC,KAAK,EAAE,MAAM,OAAO,CAAC,KAAK,CAAC,iBAAiB,CAAC,CAAC;IAIvD,cAAc,CAAC,WAAW,EAAE,iBAAiB;IAEpD;;;;;OAKG;IACI,YAAY,CAAC,UAAU,EAAE,MAAM;IAOtC;;;;OAIG;IACI,WAAW;IAIlB,IAAW,UAAU,YAEpB;IAED,IAAW,UAAU,YAEpB;IAED;;OAEG;IACI,OAAO,IAAI;QAChB,UAAU,EAAE,OAAO,CAAC;QACpB,MAAM,EAAE,qBAAqB,CAAC,WAAW,CAAC,CAAC;KAC5C;IAOD;;OAEG;IACI,KAAK;CAGb"}