@proto-kit/module 0.1.1-develop.191 → 0.1.1-develop.2024

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 +6 -6
  2. package/dist/factories/MethodIdFactory.d.ts.map +1 -1
  3. package/dist/factories/MethodIdFactory.js +10 -34
  4. package/dist/factories/MethodIdFactory.js.map +1 -0
  5. package/dist/index.d.ts +4 -7
  6. package/dist/index.d.ts.map +1 -1
  7. package/dist/index.js +5 -7
  8. package/dist/index.js.map +1 -0
  9. package/dist/messages/OutgoingMessage.d.ts +96 -0
  10. package/dist/messages/OutgoingMessage.d.ts.map +1 -0
  11. package/dist/messages/OutgoingMessage.js +68 -0
  12. package/dist/messages/OutgoingMessage.js.map +1 -0
  13. package/dist/messages/OutgoingMessages.d.ts +231 -0
  14. package/dist/messages/OutgoingMessages.d.ts.map +1 -0
  15. package/dist/messages/OutgoingMessages.js +66 -0
  16. package/dist/messages/OutgoingMessages.js.map +1 -0
  17. package/dist/method/MethodParameterEncoder.d.ts +26 -0
  18. package/dist/method/MethodParameterEncoder.d.ts.map +1 -0
  19. package/dist/method/MethodParameterEncoder.js +169 -0
  20. package/dist/method/MethodParameterEncoder.js.map +1 -0
  21. package/dist/method/runtimeMethod.d.ts +21 -5
  22. package/dist/method/runtimeMethod.d.ts.map +1 -1
  23. package/dist/method/runtimeMethod.js +69 -25
  24. package/dist/method/runtimeMethod.js.map +1 -0
  25. package/dist/module/decorator.js +1 -0
  26. package/dist/module/decorator.js.map +1 -0
  27. package/dist/runtime/MethodIdResolver.d.ts +10 -8
  28. package/dist/runtime/MethodIdResolver.d.ts.map +1 -1
  29. package/dist/runtime/MethodIdResolver.js +74 -33
  30. package/dist/runtime/MethodIdResolver.js.map +1 -0
  31. package/dist/runtime/Runtime.d.ts +20 -26
  32. package/dist/runtime/Runtime.d.ts.map +1 -1
  33. package/dist/runtime/Runtime.js +117 -62
  34. package/dist/runtime/Runtime.js.map +1 -0
  35. package/dist/runtime/RuntimeEnvironment.d.ts +10 -0
  36. package/dist/runtime/RuntimeEnvironment.d.ts.map +1 -0
  37. package/dist/runtime/RuntimeEnvironment.js +2 -0
  38. package/dist/runtime/RuntimeEnvironment.js.map +1 -0
  39. package/dist/runtime/RuntimeModule.d.ts +18 -15
  40. package/dist/runtime/RuntimeModule.d.ts.map +1 -1
  41. package/dist/runtime/RuntimeModule.js +33 -8
  42. package/dist/runtime/RuntimeModule.js.map +1 -0
  43. package/dist/state/InMemoryStateService.d.ts +11 -10
  44. package/dist/state/InMemoryStateService.d.ts.map +1 -1
  45. package/dist/state/InMemoryStateService.js +11 -8
  46. package/dist/state/InMemoryStateService.js.map +1 -0
  47. package/dist/state/decorator.d.ts.map +1 -1
  48. package/dist/state/decorator.js +2 -4
  49. package/dist/state/decorator.js.map +1 -0
  50. package/dist/testing/TestingRuntime.d.ts +8 -0
  51. package/dist/testing/TestingRuntime.d.ts.map +1 -0
  52. package/dist/testing/TestingRuntime.js +31 -0
  53. package/dist/testing/TestingRuntime.js.map +1 -0
  54. package/jest.config.cjs +12 -1
  55. package/package.json +10 -11
  56. package/src/factories/MethodIdFactory.ts +10 -17
  57. package/src/index.ts +4 -7
  58. package/src/messages/OutgoingMessages.ts +122 -0
  59. package/src/method/MethodParameterEncoder.ts +262 -0
  60. package/src/method/runtimeMethod.ts +130 -33
  61. package/src/runtime/MethodIdResolver.ts +83 -46
  62. package/src/runtime/Runtime.ts +193 -100
  63. package/src/runtime/RuntimeEnvironment.ts +16 -0
  64. package/src/runtime/RuntimeModule.ts +62 -30
  65. package/src/state/InMemoryStateService.ts +14 -18
  66. package/test/Runtime.test.ts +68 -42
  67. package/test/TestingRuntime.ts +43 -0
  68. package/test/messages/message.test.ts +42 -0
  69. package/test/method/MethodParameterEncoder.test.ts +124 -0
  70. package/test/method/runtimeMethod-fail.test.ts +53 -0
  71. package/{src/method/decorator.test.ts → test/method/runtimeMethod.test.ts} +3 -3
  72. package/test/modules/Admin.ts +4 -4
  73. package/test/modules/Balances.test.ts +92 -78
  74. package/test/modules/Balances.ts +15 -17
  75. package/test/modules/{methodId.test.ts → MethodIdResolver.test.ts} +24 -36
  76. package/test/modules/State.test.ts +81 -0
  77. package/test/runtimeMethod.test.ts +192 -20
  78. package/test/tsconfig.json +7 -0
  79. package/tsconfig.json +2 -2
  80. package/LICENSE.md +0 -201
  81. package/dist/method/MethodParameterDecoder.d.ts +0 -22
  82. package/dist/method/MethodParameterDecoder.d.ts.map +0 -1
  83. package/dist/method/MethodParameterDecoder.js +0 -33
  84. package/dist/method/RuntimeMethodExecutionContext.d.ts +0 -57
  85. package/dist/method/RuntimeMethodExecutionContext.d.ts.map +0 -1
  86. package/dist/method/RuntimeMethodExecutionContext.js +0 -92
  87. package/dist/method/assert.d.ts +0 -12
  88. package/dist/method/assert.d.ts.map +0 -1
  89. package/dist/method/assert.js +0 -23
  90. package/dist/state/State.d.ts +0 -65
  91. package/dist/state/State.d.ts.map +0 -1
  92. package/dist/state/State.js +0 -114
  93. package/dist/state/StateMap.d.ts +0 -37
  94. package/dist/state/StateMap.d.ts.map +0 -1
  95. package/dist/state/StateMap.js +0 -56
  96. package/dist/state/StateServiceProvider.d.ts +0 -10
  97. package/dist/state/StateServiceProvider.d.ts.map +0 -1
  98. package/dist/state/StateServiceProvider.js +0 -34
  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
@@ -11,12 +11,10 @@ const errors = {
11
11
  */
12
12
  export function state() {
13
13
  return (target, propertyKey) => {
14
- // eslint-disable-next-line @typescript-eslint/init-declarations
15
14
  let value;
16
15
  Object.defineProperty(target, propertyKey, {
17
16
  enumerable: true,
18
17
  get: function get() {
19
- // eslint-disable-next-line max-len
20
18
  // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
21
19
  const self = this;
22
20
  if (self.name === undefined) {
@@ -28,9 +26,8 @@ export function state() {
28
26
  const path = Path.fromProperty(self.name, propertyKey);
29
27
  if (value) {
30
28
  value.path = path;
31
- // eslint-disable-next-line no-warning-comments
32
29
  // TODO: why is this complaining about `any`?
33
- value.runtime = self.runtime;
30
+ value.stateServiceProvider = self.runtime.stateServiceProvider;
34
31
  }
35
32
  return value;
36
33
  },
@@ -40,3 +37,4 @@ export function state() {
40
37
  });
41
38
  };
42
39
  }
40
+ //# sourceMappingURL=decorator.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"decorator.js","sourceRoot":"","sources":["../../src/state/decorator.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAS,MAAM,qBAAqB,CAAC;AAIlD,MAAM,MAAM,GAAG;IACb,WAAW,EAAE,CAAC,SAAiB,EAAE,EAAE,CACjC,IAAI,KAAK,CACP,oDAAoD,SAAS;iFACc,CAC5E;IAEH,cAAc,EAAE,CAAC,SAAiB,EAAE,EAAE,CACpC,IAAI,KAAK,CACP,0CAA0C,SAAS;iFACwB,CAC5E;CACJ,CAAC;AAEF;;;GAGG;AACH,MAAM,UAAU,KAAK;IACnB,OAAO,CACL,MAA2B,EAC3B,WAAmB,EACnB,EAAE;QACF,IAAI,KAAiC,CAAC;QAEtC,MAAM,CAAC,cAAc,CAAC,MAAM,EAAE,WAAW,EAAE;YACzC,UAAU,EAAE,IAAI;YAEhB,GAAG,EAAE,SAAS,GAAG;gBACf,yEAAyE;gBACzE,MAAM,IAAI,GAAG,IAA2B,CAAC;gBAEzC,IAAI,IAAI,CAAC,IAAI,KAAK,SAAS,EAAE;oBAC3B,MAAM,MAAM,CAAC,WAAW,CAAC,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC;iBACjD;gBAED,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE;oBACjB,MAAM,MAAM,CAAC,cAAc,CAAC,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC;iBACpD;gBAED,MAAM,IAAI,GAAG,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,IAAI,EAAE,WAAW,CAAC,CAAC;gBACvD,IAAI,KAAK,EAAE;oBACT,KAAK,CAAC,IAAI,GAAG,IAAI,CAAC;oBAElB,6CAA6C;oBAE7C,KAAK,CAAC,oBAAoB,GAAG,IAAI,CAAC,OAAO,CAAC,oBAAoB,CAAC;iBAChE;gBACD,OAAO,KAAK,CAAC;YACf,CAAC;YAED,GAAG,EAAE,CAAC,QAAwB,EAAE,EAAE;gBAChC,KAAK,GAAG,QAAQ,CAAC;YACnB,CAAC;SACF,CAAC,CAAC;IACL,CAAC,CAAC;AACJ,CAAC"}
@@ -0,0 +1,8 @@
1
+ import { ModulesConfig } from "@proto-kit/common";
2
+ import { Runtime, RuntimeModulesRecord } from "../runtime/Runtime";
3
+ import { InMemoryStateService } from "../state/InMemoryStateService";
4
+ export declare function createTestingRuntime<Modules extends RuntimeModulesRecord>(modules: Modules, config: ModulesConfig<Modules>): {
5
+ runtime: Runtime<Modules>;
6
+ state: InMemoryStateService;
7
+ };
8
+ //# sourceMappingURL=TestingRuntime.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"TestingRuntime.d.ts","sourceRoot":"","sources":["../../src/testing/TestingRuntime.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAIlD,OAAO,EAAE,OAAO,EAAE,oBAAoB,EAAE,MAAM,oBAAoB,CAAC;AACnE,OAAO,EAAE,oBAAoB,EAAE,MAAM,+BAA+B,CAAC;AAErE,wBAAgB,oBAAoB,CAAC,OAAO,SAAS,oBAAoB,EACvE,OAAO,EAAE,OAAO,EAChB,MAAM,EAAE,aAAa,CAAC,OAAO,CAAC,GAC7B;IACD,OAAO,EAAE,OAAO,CAAC,OAAO,CAAC,CAAC;IAC1B,KAAK,EAAE,oBAAoB,CAAC;CAC7B,CAgCA"}
@@ -0,0 +1,31 @@
1
+ import { StateServiceProvider } from "@proto-kit/protocol";
2
+ import { container } from "tsyringe";
3
+ import { Runtime } from "../runtime/Runtime";
4
+ import { InMemoryStateService } from "../state/InMemoryStateService";
5
+ export function createTestingRuntime(modules, config) {
6
+ const state = new InMemoryStateService();
7
+ const Runtimeclass = Runtime.from({
8
+ modules,
9
+ });
10
+ const runtime = new Runtimeclass();
11
+ runtime.configure(config);
12
+ runtime.create(() => container.createChildContainer());
13
+ runtime.dependencyContainer.register("AreProofsEnabled", {
14
+ useValue: {
15
+ areProofsEnabled: false,
16
+ setProofsEnabled(areProofsEnabled) {
17
+ this.areProofsEnabled = areProofsEnabled;
18
+ },
19
+ },
20
+ });
21
+ runtime.registerValue({
22
+ StateServiceProvider: new StateServiceProvider(),
23
+ Runtime: runtime,
24
+ });
25
+ runtime.stateServiceProvider.setCurrentStateService(state);
26
+ return {
27
+ runtime,
28
+ state,
29
+ };
30
+ }
31
+ //# sourceMappingURL=TestingRuntime.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"TestingRuntime.js","sourceRoot":"","sources":["../../src/testing/TestingRuntime.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AAC3D,OAAO,EAAE,SAAS,EAAE,MAAM,UAAU,CAAC;AAErC,OAAO,EAAE,OAAO,EAAwB,MAAM,oBAAoB,CAAC;AACnE,OAAO,EAAE,oBAAoB,EAAE,MAAM,+BAA+B,CAAC;AAErE,MAAM,UAAU,oBAAoB,CAClC,OAAgB,EAChB,MAA8B;IAK9B,MAAM,KAAK,GAAG,IAAI,oBAAoB,EAAE,CAAC;IAEzC,MAAM,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC;QAChC,OAAO;KACR,CAAC,CAAC;IACH,MAAM,OAAO,GAAG,IAAI,YAAY,EAAE,CAAC;IAEnC,OAAO,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC;IAE1B,OAAO,CAAC,MAAM,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,oBAAoB,EAAE,CAAC,CAAC;IAEvD,OAAO,CAAC,mBAAmB,CAAC,QAAQ,CAAC,kBAAkB,EAAE;QACvD,QAAQ,EAAE;YACR,gBAAgB,EAAE,KAAK;YAEvB,gBAAgB,CAAC,gBAAyB;gBACxC,IAAI,CAAC,gBAAgB,GAAG,gBAAgB,CAAC;YAC3C,CAAC;SACF;KACF,CAAC,CAAC;IACH,OAAO,CAAC,aAAa,CAAC;QACpB,oBAAoB,EAAE,IAAI,oBAAoB,EAAE;QAChD,OAAO,EAAE,OAAO;KACjB,CAAC,CAAC;IAEH,OAAO,CAAC,oBAAoB,CAAC,sBAAsB,CAAC,KAAK,CAAC,CAAC;IAE3D,OAAO;QACL,OAAO;QACP,KAAK;KACN,CAAC;AACJ,CAAC"}
package/jest.config.cjs CHANGED
@@ -1 +1,12 @@
1
- module.exports = require("../../jest.config.cjs");
1
+ // @ts-ignore
2
+ const config = require("../../jest.config.cjs");
3
+
4
+ module.exports = {
5
+ ...config,
6
+ collectCoverageFrom: [
7
+ "packages/module/src/**",
8
+ "!**/node_modules/**",
9
+ "!**/dist/**",
10
+ ],
11
+ coverageDirectory: "coverage/module",
12
+ };
package/package.json CHANGED
@@ -2,35 +2,34 @@
2
2
  "name": "@proto-kit/module",
3
3
  "license": "MIT",
4
4
  "private": false,
5
- "version": "0.1.1-develop.191+554ba10",
5
+ "version": "0.1.1-develop.2024+5a945075",
6
6
  "type": "module",
7
7
  "scripts": {
8
8
  "build": "tsc -p tsconfig.json",
9
9
  "dev": "tsc -p tsconfig.json --watch",
10
10
  "lint": "eslint ./src ./test",
11
- "test:file": "node --experimental-vm-modules --experimental-wasm-modules --experimental-wasm-threads ../../node_modules/jest/bin/jest.js",
12
- "test": "npm run test:file -- ./src/** ./test/**",
13
- "test:watch": "npm run test:file -- ./src/** ./test/** --watch"
11
+ "test:file": "node --experimental-vm-modules --experimental-wasm-modules ../../node_modules/jest/bin/jest.js",
12
+ "test": "npm run test:file -- ./test/**",
13
+ "test:watch": "npm run test:file -- ./test/** --watch"
14
14
  },
15
15
  "main": "dist/index.js",
16
16
  "publishConfig": {
17
17
  "access": "public"
18
18
  },
19
19
  "dependencies": {
20
- "@proto-kit/common": "*",
21
- "@proto-kit/protocol": "*",
22
20
  "lodash": "^4.17.21",
23
21
  "loglevel": "^1.8.1",
24
- "reflect-metadata": "^0.1.13",
25
- "ts-mixer": "^6.0.3"
22
+ "reflect-metadata": "^0.1.13"
26
23
  },
27
24
  "devDependencies": {
28
25
  "@jest/globals": "^29.5.0",
29
26
  "@types/lodash": "^4.14.194"
30
27
  },
31
28
  "peerDependencies": {
32
- "snarkyjs": "0.12.0",
33
- "tsyringe": "^4.7.0"
29
+ "@proto-kit/common": "*",
30
+ "@proto-kit/protocol": "*",
31
+ "o1js": "^2.10.0",
32
+ "tsyringe": "^4.10.0"
34
33
  },
35
- "gitHead": "554ba102c48f41a62409ff01354582567ef4124a"
34
+ "gitHead": "fb121dd0802012f70abff6afe48e82a67c13318d"
36
35
  }
@@ -1,22 +1,15 @@
1
- import {
2
- dependency, dependencyFactory,
3
- DependencyFactory
4
- } from "@proto-kit/common";
5
- import { inject, injectable } from "tsyringe";
1
+ import { DependencyFactory, DependencyRecord } from "@proto-kit/common";
6
2
 
7
3
  import { MethodIdResolver } from "../runtime/MethodIdResolver";
8
- import type { Runtime, RuntimeModulesRecord } from "../runtime/Runtime";
9
4
 
10
- @dependencyFactory()
11
- export class MethodIdFactory extends DependencyFactory {
12
- public constructor(
13
- @inject("Runtime") private readonly runtime: Runtime<RuntimeModulesRecord>
14
- ) {
15
- super();
16
- }
17
-
18
- @dependency()
19
- public methodIdResolver(): MethodIdResolver {
20
- return new MethodIdResolver(this.runtime, this.runtime.definition.modules);
5
+ export class MethodIdFactory {
6
+ public static dependencies() {
7
+ return {
8
+ methodIdResolver: {
9
+ useClass: MethodIdResolver,
10
+ },
11
+ } satisfies DependencyRecord;
21
12
  }
22
13
  }
14
+
15
+ MethodIdFactory satisfies DependencyFactory;
package/src/index.ts CHANGED
@@ -1,13 +1,10 @@
1
- export * from "./method/RuntimeMethodExecutionContext";
2
- export * from "./method/assert";
3
1
  export * from "./method/runtimeMethod";
4
2
  export * from "./module/decorator";
5
3
  export * from "./runtime/RuntimeModule";
4
+ export * from "./runtime/RuntimeEnvironment";
6
5
  export * from "./runtime/Runtime";
7
6
  export * from "./state/InMemoryStateService";
8
- export * from "./state/State";
9
- export * from "./state/StateMap";
10
- export * from "./state/StateServiceProvider";
11
- export * from "./state/decorator";
12
- export * from "./method/MethodParameterDecoder";
7
+ export * from "./method/MethodParameterEncoder";
13
8
  export * from "./runtime/MethodIdResolver";
9
+ export * from "./factories/MethodIdFactory";
10
+ export * from "./messages/OutgoingMessages";
@@ -0,0 +1,122 @@
1
+ import {
2
+ Field,
3
+ FlexibleProvablePure,
4
+ InferProvable,
5
+ Struct,
6
+ TokenId,
7
+ } from "o1js";
8
+ import {
9
+ OutgoingMessageEvent,
10
+ OutgoingMessageKeyStruct,
11
+ PROTOKIT_FIELD_PREFIXES,
12
+ RuntimeMethodExecutionContext,
13
+ state as stateDecorator,
14
+ StateMap,
15
+ WithPath,
16
+ WithStateServiceProvider,
17
+ } from "@proto-kit/protocol";
18
+ // eslint-disable-next-line import/no-extraneous-dependencies
19
+ import { Mixin } from "ts-mixer";
20
+ import { prefixToField, StringKeyOf } from "@proto-kit/common";
21
+ import { container } from "tsyringe";
22
+
23
+ export type OutgoingMessagesRecord = Record<string, FlexibleProvablePure<any>>;
24
+
25
+ export const outgoingMessage = stateDecorator;
26
+
27
+ export class OutgoingMessages<
28
+ Messages extends OutgoingMessagesRecord,
29
+ > extends Mixin(WithPath, WithStateServiceProvider) {
30
+ public readonly eventTypes: Record<
31
+ string,
32
+ {
33
+ messageType: FlexibleProvablePure<{ messageType: Field; value: any }>;
34
+ eventType: FlexibleProvablePure<{
35
+ key: OutgoingMessageKeyStruct;
36
+ value: any;
37
+ messageType: Field;
38
+ }>;
39
+ }
40
+ >;
41
+
42
+ public constructor(private readonly messages: Messages) {
43
+ super();
44
+ this.eventTypes = this.computeEventTypes();
45
+ }
46
+
47
+ private counterState() {
48
+ const state = new StateMap(Field, Field);
49
+ state.path = PROTOKIT_FIELD_PREFIXES.OUTGOING_MESSAGE_COUNTER_PATH;
50
+ state.stateServiceProvider = this.stateServiceProvider;
51
+ return state;
52
+ }
53
+
54
+ public static getEventName(key: string) {
55
+ return `outgoing-${key}`;
56
+ }
57
+
58
+ public computeEventTypes() {
59
+ return Object.fromEntries(
60
+ Object.entries(this.messages).map(([key, type]) => {
61
+ class OutgoingMessageEventStruct extends Struct({
62
+ key: OutgoingMessageKeyStruct,
63
+ value: type,
64
+ messageType: Field,
65
+ }) {}
66
+
67
+ class OutgoingMessageStruct extends Struct({
68
+ value: type,
69
+ messageType: Field,
70
+ }) {}
71
+
72
+ return [
73
+ OutgoingMessages.getEventName(key),
74
+ {
75
+ messageType: OutgoingMessageStruct,
76
+ eventType: OutgoingMessageEventStruct,
77
+ },
78
+ ];
79
+ })
80
+ );
81
+ }
82
+
83
+ private emitEvent<Key extends StringKeyOf<Messages>>(
84
+ eventName: string,
85
+ value: OutgoingMessageEvent<InferProvable<Messages[Key]>>
86
+ ) {
87
+ const outgoingMessageType = this.eventTypes[eventName].eventType;
88
+
89
+ return container
90
+ .resolve(RuntimeMethodExecutionContext)
91
+ .addEvent<
92
+ OutgoingMessageEvent<InferProvable<Messages[Key]>>
93
+ >(outgoingMessageType, value, eventName);
94
+ }
95
+
96
+ public async emitMessage<Key extends StringKeyOf<Messages>>(
97
+ key: Key,
98
+ value: InferProvable<Messages[Key]>,
99
+ tokenId: Field = TokenId.default
100
+ ) {
101
+ const eventName = OutgoingMessages.getEventName(key);
102
+
103
+ const stateMap = new StateMap(
104
+ OutgoingMessageKeyStruct,
105
+ this.eventTypes[eventName].messageType
106
+ );
107
+ stateMap.path = PROTOKIT_FIELD_PREFIXES.OUTGOING_MESSAGE_BASE_PATH;
108
+ stateMap.stateServiceProvider = this.stateServiceProvider;
109
+
110
+ const counterState = this.counterState();
111
+ const counterOption = await counterState.get(tokenId);
112
+ const counter = counterOption.orElse(Field(0));
113
+
114
+ const messageKey = { index: counter, tokenId };
115
+ const messageType = prefixToField(key);
116
+
117
+ await counterState.set(tokenId, counter.add(1));
118
+ await stateMap.set(messageKey, { messageType, value });
119
+
120
+ this.emitEvent(eventName, { key: messageKey, value, messageType });
121
+ }
122
+ }
@@ -0,0 +1,262 @@
1
+ /* eslint-disable @typescript-eslint/consistent-type-assertions */
2
+ import {
3
+ Field,
4
+ Proof,
5
+ Provable,
6
+ DynamicProof,
7
+ FlexibleProvablePure,
8
+ FlexibleProvable,
9
+ } from "o1js";
10
+ import {
11
+ ArgumentTypes,
12
+ ProofTypes,
13
+ ToFieldableStatic,
14
+ TypedClass,
15
+ filterNonUndefined,
16
+ } from "@proto-kit/common";
17
+
18
+ import type { RuntimeModule } from "../runtime/RuntimeModule";
19
+
20
+ const errors = {
21
+ fieldLengthNotMatching: (expected: number, actual: number) =>
22
+ new Error(`Expected ${expected} field elements, got ${actual}`),
23
+
24
+ typeNotCompatible: (name: string, error?: string) =>
25
+ new Error(
26
+ `Cannot decode type ${name}, it has to be either a Struct, CircuitValue or built-in snarkyjs type.${
27
+ error !== undefined ? `Caused by: ${error}` : ""
28
+ }`
29
+ ),
30
+ };
31
+
32
+ type ArgumentType =
33
+ | FlexibleProvable<any>
34
+ | typeof Proof<unknown, unknown>
35
+ | typeof DynamicProof<unknown, unknown>;
36
+
37
+ type ArgTypeArray = ArgumentType[];
38
+
39
+ type ArgArray = ArgumentTypes[];
40
+
41
+ function isProofType(type: unknown): type is typeof Proof {
42
+ return (type as unknown as TypedClass<unknown>).prototype instanceof Proof;
43
+ }
44
+
45
+ function isDynamicProofType(type: unknown): type is typeof DynamicProof {
46
+ return (
47
+ (type as unknown as TypedClass<unknown>).prototype instanceof DynamicProof
48
+ );
49
+ }
50
+
51
+ function isProofBaseType(
52
+ type: unknown
53
+ ): type is typeof Proof | typeof DynamicProof {
54
+ return isProofType(type) || isDynamicProofType(type);
55
+ }
56
+
57
+ function getAllPropertyNamesOfPrototypeChain(type: unknown): string[] {
58
+ if (type === undefined || type === null) {
59
+ return [];
60
+ }
61
+ return Object.getOwnPropertyNames(type).concat(
62
+ ...getAllPropertyNamesOfPrototypeChain(Object.getPrototypeOf(type))
63
+ );
64
+ }
65
+
66
+ export function isFlexibleProvablePure(
67
+ type: unknown
68
+ ): type is FlexibleProvablePure<unknown> {
69
+ // The required properties are defined on the prototype for Structs and CircuitValues
70
+ // but on the constructor function itself for Field and Bool
71
+ // For aliases like Balance in library, it can even be 2 steps upwards the prototype chain
72
+ const props = getAllPropertyNamesOfPrototypeChain(type);
73
+ const mandatory = ["toFields", "fromFields", "sizeInFields"];
74
+ return mandatory.every((prop) => props.includes(prop));
75
+ }
76
+
77
+ export function checkArgsProvable(
78
+ target: RuntimeModule<unknown>,
79
+ methodName: string
80
+ ) {
81
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
82
+ const paramtypes: ArgTypeArray = Reflect.getMetadata(
83
+ "design:paramtypes",
84
+ target,
85
+ methodName
86
+ );
87
+
88
+ if (paramtypes === undefined) {
89
+ throw new Error(
90
+ `Method with name ${methodName} doesn't exist on this module`
91
+ );
92
+ }
93
+
94
+ const indizes = paramtypes
95
+ .map((type, index) => {
96
+ if (isProofBaseType(type) || isFlexibleProvablePure(type)) {
97
+ return undefined;
98
+ }
99
+ return `${index}`;
100
+ })
101
+ .filter(filterNonUndefined);
102
+ if (indizes.length > 0) {
103
+ const indexString = indizes.reduce((a, b) => `${a}, ${b}`);
104
+ throw new Error(
105
+ `Not all arguments of method '${target.name}.${methodName}' are provable types or proofs (indizes: [${indexString}])`
106
+ );
107
+ }
108
+ return paramtypes;
109
+ }
110
+
111
+ export class MethodParameterEncoder {
112
+ public static fromMethod(target: RuntimeModule<unknown>, methodName: string) {
113
+ const paramtypes = checkArgsProvable(target, methodName);
114
+
115
+ return new MethodParameterEncoder(paramtypes);
116
+ }
117
+
118
+ public static fieldSize(type: ArgumentType): number | undefined {
119
+ if (isProofBaseType(type)) {
120
+ return (
121
+ (MethodParameterEncoder.fieldSize(type.publicInputType) ?? 0) +
122
+ (MethodParameterEncoder.fieldSize(type.publicOutputType) ?? 0)
123
+ );
124
+ }
125
+ // as any, since we shouldn't be using this workaround in the first place
126
+ return (type as FlexibleProvable<unknown>).sizeInFields();
127
+ }
128
+
129
+ public constructor(private readonly types: ArgTypeArray) {}
130
+
131
+ public decode(fields: Field[], auxiliary: string[]): Promise<ArgArray> {
132
+ if (fields.length < this.fieldSize()) {
133
+ throw errors.fieldLengthNotMatching(this.fieldSize(), fields.length);
134
+ }
135
+
136
+ let stack = fields.slice();
137
+ const auxiliaryStack = auxiliary.slice();
138
+
139
+ return Promise.all(
140
+ this.types.map((type) => {
141
+ const numberFieldsNeeded = MethodParameterEncoder.fieldSize(type) ?? -1;
142
+ if (numberFieldsNeeded === -1) {
143
+ throw errors.typeNotCompatible(type.constructor.name);
144
+ }
145
+ const structFields = stack.slice(0, numberFieldsNeeded);
146
+ stack = stack.slice(numberFieldsNeeded);
147
+
148
+ // Decode proof
149
+ if (isProofBaseType(type)) {
150
+ const auxiliaryData = auxiliaryStack.shift();
151
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
152
+ const proofData: { proof: string; maxProofsVerified: 0 | 1 | 2 } =
153
+ JSON.parse(auxiliaryData!);
154
+
155
+ const inputFieldSize = MethodParameterEncoder.fieldSize(
156
+ type.publicInputType
157
+ )!;
158
+ const input = structFields
159
+ .slice(0, inputFieldSize)
160
+ .map((x) => x.toString());
161
+ const output = structFields
162
+ .slice(inputFieldSize)
163
+ .map((x) => x.toString());
164
+
165
+ // fromJSON has incompatible signature for Proof and DynamicProof
166
+ if (isProofType(type)) {
167
+ return type.fromJSON({
168
+ ...proofData,
169
+ publicInput: input,
170
+ publicOutput: output,
171
+ });
172
+ }
173
+ if (isDynamicProofType(type)) {
174
+ return type.fromJSON({
175
+ ...proofData,
176
+ publicInput: input,
177
+ publicOutput: output,
178
+ });
179
+ }
180
+ }
181
+
182
+ return (type as FlexibleProvable<unknown>).fromFields(
183
+ structFields,
184
+ []
185
+ ) as any;
186
+ })
187
+ );
188
+ }
189
+
190
+ /**
191
+ * Variant of encode() for provable code that skips the unprovable
192
+ * json encoding
193
+ */
194
+ public encode(args: ArgumentTypes) {
195
+ /**
196
+ * Use the type info obtained previously to convert
197
+ * the args passed to fields
198
+ */
199
+ return args
200
+ .map((argument, index) => {
201
+ if (argument instanceof Proof || argument instanceof DynamicProof) {
202
+ const argumentType = this.types[index] as ProofTypes;
203
+
204
+ const { publicOutputType, publicInputType } = argumentType;
205
+
206
+ const inputFields =
207
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
208
+ publicInputType?.toFields(argument.publicInput as any) ?? [];
209
+
210
+ const outputFields =
211
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
212
+ publicOutputType?.toFields(argument.publicOutput as any) ?? [];
213
+
214
+ let auxiliary = "";
215
+
216
+ // Has to be asProver, because this function will be called by runtimeMethod
217
+ // to transform the args into a Field[] to compute the argsHash
218
+ // In this case, the auxiliary might be empty, but it isn't used by that method anyways
219
+ Provable.asProver(() => {
220
+ const jsonProof = argument.toJSON();
221
+ auxiliary = JSON.stringify({
222
+ proof: jsonProof.proof,
223
+ maxProofsVerified: jsonProof.maxProofsVerified,
224
+ });
225
+ });
226
+
227
+ return {
228
+ fields: [...inputFields, ...outputFields],
229
+ auxiliary,
230
+ };
231
+ }
232
+
233
+ const argumentType = this.types[index] as ToFieldableStatic;
234
+ return {
235
+ fields: argumentType.toFields(argument),
236
+ auxiliary: undefined,
237
+ };
238
+ })
239
+ .reduce<{
240
+ fields: Field[];
241
+ auxiliary: string[];
242
+ }>(
243
+ (a, b) => {
244
+ return {
245
+ fields: [...a.fields, ...b.fields],
246
+ auxiliary:
247
+ b.auxiliary !== undefined
248
+ ? [...a.auxiliary, b.auxiliary]
249
+ : a.auxiliary,
250
+ };
251
+ },
252
+ { fields: [], auxiliary: [] }
253
+ );
254
+ }
255
+
256
+ public fieldSize(): number {
257
+ return this.types
258
+ .map((type) => MethodParameterEncoder.fieldSize(type) ?? 0)
259
+ .reduce((a, b) => a + b, 0);
260
+ }
261
+ }
262
+ /* eslint-enable @typescript-eslint/consistent-type-assertions */