@proto-kit/module 0.1.1-develop.211 → 0.1.1-develop.2137

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 (155) 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 +67 -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 +75 -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 +9 -9
  56. package/src/factories/MethodIdFactory.ts +10 -17
  57. package/src/index.ts +4 -4
  58. package/src/messages/OutgoingMessages.ts +124 -0
  59. package/src/method/MethodParameterEncoder.ts +262 -0
  60. package/src/method/runtimeMethod.ts +131 -33
  61. package/src/runtime/MethodIdResolver.ts +85 -46
  62. package/src/runtime/Runtime.ts +187 -96
  63. package/src/runtime/RuntimeEnvironment.ts +16 -0
  64. package/src/runtime/RuntimeModule.ts +58 -27
  65. package/src/state/InMemoryStateService.ts +14 -14
  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 +88 -79
  74. package/test/modules/Balances.ts +15 -21
  75. package/test/modules/{methodId.test.ts → MethodIdResolver.test.ts} +24 -35
  76. package/test/modules/State.test.ts +46 -53
  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/module/src/factories/MethodIdFactory.d.ts +0 -9
  91. package/dist/module/src/factories/MethodIdFactory.d.ts.map +0 -1
  92. package/dist/module/src/factories/MethodIdFactory.js +0 -36
  93. package/dist/module/src/index.d.ts +0 -11
  94. package/dist/module/src/index.d.ts.map +0 -1
  95. package/dist/module/src/index.js +0 -10
  96. package/dist/module/src/method/MethodParameterDecoder.d.ts +0 -22
  97. package/dist/module/src/method/MethodParameterDecoder.d.ts.map +0 -1
  98. package/dist/module/src/method/MethodParameterDecoder.js +0 -33
  99. package/dist/module/src/method/runtimeMethod.d.ts +0 -19
  100. package/dist/module/src/method/runtimeMethod.d.ts.map +0 -1
  101. package/dist/module/src/method/runtimeMethod.js +0 -123
  102. package/dist/module/src/module/decorator.d.ts +0 -8
  103. package/dist/module/src/module/decorator.d.ts.map +0 -1
  104. package/dist/module/src/module/decorator.js +0 -15
  105. package/dist/module/src/runtime/MethodIdResolver.d.ts +0 -18
  106. package/dist/module/src/runtime/MethodIdResolver.d.ts.map +0 -1
  107. package/dist/module/src/runtime/MethodIdResolver.js +0 -50
  108. package/dist/module/src/runtime/Runtime.d.ts +0 -72
  109. package/dist/module/src/runtime/Runtime.d.ts.map +0 -1
  110. package/dist/module/src/runtime/Runtime.js +0 -184
  111. package/dist/module/src/runtime/RuntimeModule.d.ts +0 -35
  112. package/dist/module/src/runtime/RuntimeModule.d.ts.map +0 -1
  113. package/dist/module/src/runtime/RuntimeModule.js +0 -56
  114. package/dist/module/src/state/InMemoryStateService.d.ts +0 -11
  115. package/dist/module/src/state/InMemoryStateService.d.ts.map +0 -1
  116. package/dist/module/src/state/InMemoryStateService.js +0 -21
  117. package/dist/module/src/state/decorator.d.ts +0 -7
  118. package/dist/module/src/state/decorator.d.ts.map +0 -1
  119. package/dist/module/src/state/decorator.js +0 -42
  120. package/dist/protocol/src/model/Option.d.ts +0 -98
  121. package/dist/protocol/src/model/Option.d.ts.map +0 -1
  122. package/dist/protocol/src/model/Option.js +0 -98
  123. package/dist/protocol/src/model/StateTransition.d.ts +0 -96
  124. package/dist/protocol/src/model/StateTransition.d.ts.map +0 -1
  125. package/dist/protocol/src/model/StateTransition.js +0 -65
  126. package/dist/protocol/src/model/network/NetworkState.d.ts +0 -64
  127. package/dist/protocol/src/model/network/NetworkState.d.ts.map +0 -1
  128. package/dist/protocol/src/model/network/NetworkState.js +0 -12
  129. package/dist/protocol/src/model/transaction/ProtocolTransaction.d.ts +0 -70
  130. package/dist/protocol/src/model/transaction/ProtocolTransaction.d.ts.map +0 -1
  131. package/dist/protocol/src/model/transaction/ProtocolTransaction.js +0 -18
  132. package/dist/protocol/src/model/transaction/RuntimeTransaction.d.ts +0 -63
  133. package/dist/protocol/src/model/transaction/RuntimeTransaction.d.ts.map +0 -1
  134. package/dist/protocol/src/model/transaction/RuntimeTransaction.js +0 -29
  135. package/dist/protocol/src/state/assert/assert.d.ts +0 -12
  136. package/dist/protocol/src/state/assert/assert.d.ts.map +0 -1
  137. package/dist/protocol/src/state/assert/assert.js +0 -23
  138. package/dist/protocol/src/state/context/RuntimeMethodExecutionContext.d.ts +0 -60
  139. package/dist/protocol/src/state/context/RuntimeMethodExecutionContext.d.ts.map +0 -1
  140. package/dist/protocol/src/state/context/RuntimeMethodExecutionContext.js +0 -105
  141. package/dist/state/State.d.ts +0 -65
  142. package/dist/state/State.d.ts.map +0 -1
  143. package/dist/state/State.js +0 -114
  144. package/dist/state/StateMap.d.ts +0 -37
  145. package/dist/state/StateMap.d.ts.map +0 -1
  146. package/dist/state/StateMap.js +0 -56
  147. package/dist/state/StateServiceProvider.d.ts +0 -10
  148. package/dist/state/StateServiceProvider.d.ts.map +0 -1
  149. package/dist/state/StateServiceProvider.js +0 -34
  150. package/src/method/MethodParameterDecoder.ts +0 -70
  151. package/src/state/decorator.ts +0 -63
  152. package/test/state/MerkleTree.test.ts +0 -95
  153. package/test/state/MockAsyncMerkleStore.ts +0 -28
  154. package/test/transaction.test.ts +0 -82
  155. package/tsconfig.test.json +0 -9
@@ -1,114 +0,0 @@
1
- /* eslint-disable new-cap */
2
- import { Mixin } from "ts-mixer";
3
- import { Bool, Field, Provable } from "snarkyjs";
4
- import { container } from "tsyringe";
5
- import { Option, StateTransition } from "@proto-kit/protocol";
6
- import { RuntimeMethodExecutionContext } from "../method/RuntimeMethodExecutionContext.js";
7
- export class WithPath {
8
- hasPathOrFail() {
9
- if (!this.path) {
10
- throw new Error("Could not find 'path', did you forget to add '@state' to your state property?");
11
- }
12
- }
13
- }
14
- export class WithRuntime {
15
- hasRuntimeOrFail() {
16
- if (!this.runtime) {
17
- throw new Error("Could not find 'runtime', did you forget to add '@state' to your state property?");
18
- }
19
- }
20
- }
21
- /**
22
- * Utilities for runtime module state, such as get/set
23
- */
24
- export class State extends Mixin(WithPath, WithRuntime) {
25
- /**
26
- * Creates a new state wrapper for the provided value type.
27
- *
28
- * @param valueType - Type of value to be stored (e.g. UInt64, Struct, ...)
29
- * @returns New state for the given value type.
30
- */
31
- static from(valueType) {
32
- return new State(valueType);
33
- }
34
- /**
35
- * Computes a dummy value for the given value type.
36
- *
37
- * @param valueType - Value type to generate the dummy value for
38
- * @returns Dummy value for the given value type
39
- */
40
- static dummyValue(valueType) {
41
- const length = valueType.sizeInFields();
42
- const fields = Array.from({ length }, () => Field(0));
43
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
44
- return valueType.fromFields(fields);
45
- }
46
- constructor(valueType) {
47
- super();
48
- this.valueType = valueType;
49
- }
50
- /**
51
- * Provides an in-circuit witness for the current state representation,
52
- * and constructs an Option out of it.
53
- *
54
- * @returns Optional value of the current state
55
- */
56
- witnessState() {
57
- // get the value from storage, or return a dummy value instead
58
- const value = Provable.witness(this.valueType, () => {
59
- this.hasRuntimeOrFail();
60
- this.hasPathOrFail();
61
- const fields = this.runtime.stateService.get(this.path);
62
- if (fields) {
63
- // eslint-disable-next-line max-len
64
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
65
- return this.valueType.fromFields(fields);
66
- }
67
- return State.dummyValue(this.valueType);
68
- });
69
- // check if the value exists in the storage or not
70
- const isSome = Provable.witness(Bool, () => {
71
- this.hasRuntimeOrFail();
72
- this.hasPathOrFail();
73
- const fields = this.runtime.stateService.get(this.path);
74
- return Bool(fields !== undefined);
75
- });
76
- return Option.from(isSome, value, this.valueType);
77
- }
78
- /**
79
- * Retrieves the current state and creates a state transition
80
- * anchoring the use of the current state value in the circuit.
81
- *
82
- * @returns Option representation of the current state.
83
- */
84
- get() {
85
- const option = this.witnessState();
86
- this.hasPathOrFail();
87
- const stateTransition = StateTransition.from(this.path, option);
88
- container
89
- .resolve(RuntimeMethodExecutionContext)
90
- .addStateTransition(stateTransition);
91
- return option;
92
- }
93
- /**
94
- * Sets a new state value by creating a state transition from
95
- * the current value to the newly set value.
96
- *
97
- * The newly set value isn't available via state.get(), since the
98
- * state transitions are not applied within the same circuit.
99
- * You can however store and access your new value in
100
- * a separate circuit variable.
101
- *
102
- * @param value - Value to be set as the current state
103
- */
104
- set(value) {
105
- // link the transition to the current state
106
- const fromOption = this.witnessState();
107
- const toOption = Option.from(Bool(true), value, this.valueType);
108
- this.hasPathOrFail();
109
- const stateTransition = StateTransition.fromTo(this.path, fromOption, toOption);
110
- container
111
- .resolve(RuntimeMethodExecutionContext)
112
- .addStateTransition(stateTransition);
113
- }
114
- }
@@ -1,37 +0,0 @@
1
- import type { Field, FlexibleProvablePure } from "snarkyjs";
2
- import { type Option, ToFieldable } from "@proto-kit/protocol";
3
- import { WithRuntime, WithPath } from "./State.js";
4
- declare const StateMap_base: import("ts-mixer/dist/types/types.js").Class<any[], WithPath & WithRuntime, typeof WithPath & typeof WithRuntime, false>;
5
- /**
6
- * Map-like wrapper for state
7
- */
8
- export declare class StateMap<KeyType, ValueType extends ToFieldable> extends StateMap_base {
9
- keyType: FlexibleProvablePure<KeyType>;
10
- valueType: FlexibleProvablePure<ValueType>;
11
- /**
12
- * Create a new state map with the given key and value types
13
- *
14
- * @param keyType - Type to be used as a key
15
- * @param valueType - Type to be stored as a value
16
- * @returns State map with provided key and value types.
17
- */
18
- static from<KeyType, ValueType extends ToFieldable>(keyType: FlexibleProvablePure<KeyType>, valueType: FlexibleProvablePure<ValueType>): StateMap<KeyType, ValueType>;
19
- constructor(keyType: FlexibleProvablePure<KeyType>, valueType: FlexibleProvablePure<ValueType>);
20
- getPath(key: KeyType): Field;
21
- /**
22
- * Obtains a value for the provided key in the current state map.
23
- *
24
- * @param key - Key to obtain the state for
25
- * @returns Value for the provided key.
26
- */
27
- get(key: KeyType): Option<ValueType>;
28
- /**
29
- * Sets a value for the given key in the current state map.
30
- *
31
- * @param key - Key to store the value under
32
- * @param value - Value to be stored under the given key
33
- */
34
- set(key: KeyType, value: ValueType): void;
35
- }
36
- export {};
37
- //# sourceMappingURL=StateMap.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"StateMap.d.ts","sourceRoot":"","sources":["../../src/state/StateMap.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,oBAAoB,EAAE,MAAM,UAAU,CAAC;AAC5D,OAAO,EAAQ,KAAK,MAAM,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAGrE,OAAO,EAAS,WAAW,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;;AAE1D;;GAEG;AAEH,qBAAa,QAAQ,CAAC,OAAO,EAAE,SAAS,SAAS,WAAW,CAAE,SAAQ,aAA4B;IAgBvF,OAAO,EAAE,oBAAoB,CAAC,OAAO,CAAC;IACtC,SAAS,EAAE,oBAAoB,CAAC,SAAS,CAAC;IAhBnD;;;;;;OAMG;WACW,IAAI,CAAC,OAAO,EAAE,SAAS,SAAS,WAAW,EACvD,OAAO,EAAE,oBAAoB,CAAC,OAAO,CAAC,EACtC,SAAS,EAAE,oBAAoB,CAAC,SAAS,CAAC;gBAMnC,OAAO,EAAE,oBAAoB,CAAC,OAAO,CAAC,EACtC,SAAS,EAAE,oBAAoB,CAAC,SAAS,CAAC;IAK5C,OAAO,CAAC,GAAG,EAAE,OAAO,GAAG,KAAK;IAKnC;;;;;OAKG;IACI,GAAG,CAAC,GAAG,EAAE,OAAO,GAAG,MAAM,CAAC,SAAS,CAAC;IAU3C;;;;;OAKG;IACI,GAAG,CAAC,GAAG,EAAE,OAAO,EAAE,KAAK,EAAE,SAAS;CAS1C"}
@@ -1,56 +0,0 @@
1
- import { Path } from "@proto-kit/protocol";
2
- import { Mixin } from "ts-mixer";
3
- import { State, WithRuntime, WithPath } from "./State.js";
4
- /**
5
- * Map-like wrapper for state
6
- */
7
- // eslint-disable-next-line new-cap
8
- export class StateMap extends Mixin(WithPath, WithRuntime) {
9
- /**
10
- * Create a new state map with the given key and value types
11
- *
12
- * @param keyType - Type to be used as a key
13
- * @param valueType - Type to be stored as a value
14
- * @returns State map with provided key and value types.
15
- */
16
- static from(keyType, valueType) {
17
- return new StateMap(keyType, valueType);
18
- }
19
- constructor(keyType, valueType) {
20
- super();
21
- this.keyType = keyType;
22
- this.valueType = valueType;
23
- }
24
- getPath(key) {
25
- this.hasPathOrFail();
26
- return Path.fromKey(this.path, this.keyType, key);
27
- }
28
- /**
29
- * Obtains a value for the provided key in the current state map.
30
- *
31
- * @param key - Key to obtain the state for
32
- * @returns Value for the provided key.
33
- */
34
- get(key) {
35
- const state = State.from(this.valueType);
36
- this.hasPathOrFail();
37
- this.hasRuntimeOrFail();
38
- state.path = this.getPath(key);
39
- state.runtime = this.runtime;
40
- return state.get();
41
- }
42
- /**
43
- * Sets a value for the given key in the current state map.
44
- *
45
- * @param key - Key to store the value under
46
- * @param value - Value to be stored under the given key
47
- */
48
- set(key, value) {
49
- const state = State.from(this.valueType);
50
- this.hasPathOrFail();
51
- this.hasRuntimeOrFail();
52
- state.path = Path.fromKey(this.path, this.keyType, key);
53
- state.runtime = this.runtime;
54
- state.set(value);
55
- }
56
- }
@@ -1,10 +0,0 @@
1
- import { StateService } from "./InMemoryStateService";
2
- export declare class StateServiceProvider {
3
- private currentStateService;
4
- private readonly defaultStateService;
5
- constructor(currentStateService: StateService);
6
- get stateService(): StateService;
7
- setCurrentStateService(service: StateService): void;
8
- resetToDefault(): void;
9
- }
10
- //# sourceMappingURL=StateServiceProvider.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"StateServiceProvider.d.ts","sourceRoot":"","sources":["../../src/state/StateServiceProvider.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAC;AAEtD,qBACa,oBAAoB;IAIL,OAAO,CAAC,mBAAmB;IAHrD,OAAO,CAAC,QAAQ,CAAC,mBAAmB,CAA0C;gBAG5C,mBAAmB,EAAE,YAAY;IAGnE,IAAW,YAAY,IAAI,YAAY,CAEtC;IAEM,sBAAsB,CAAC,OAAO,EAAE,YAAY;IAI5C,cAAc;CAGtB"}
@@ -1,34 +0,0 @@
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 { inject, injectable } from "tsyringe";
14
- let StateServiceProvider = class StateServiceProvider {
15
- constructor(currentStateService) {
16
- this.currentStateService = currentStateService;
17
- this.defaultStateService = this.currentStateService;
18
- }
19
- get stateService() {
20
- return this.currentStateService;
21
- }
22
- setCurrentStateService(service) {
23
- this.currentStateService = service;
24
- }
25
- resetToDefault() {
26
- this.currentStateService = this.defaultStateService;
27
- }
28
- };
29
- StateServiceProvider = __decorate([
30
- injectable(),
31
- __param(0, inject("StateService")),
32
- __metadata("design:paramtypes", [Object])
33
- ], StateServiceProvider);
34
- export { StateServiceProvider };
@@ -1,70 +0,0 @@
1
- /* eslint-disable no-underscore-dangle */
2
- import { Field } from "snarkyjs";
3
-
4
- import { RuntimeModule } from "../runtime/RuntimeModule";
5
-
6
- export interface Fieldable {
7
- toFields: () => Field[];
8
- }
9
-
10
- export interface FromFieldClass {
11
- new: (...args: any[]) => any;
12
- fromFields: (fields: Field[]) => Fieldable;
13
- name: string;
14
- // Maybe this is wrong IDK
15
- prototype: {
16
- _fields?: any[];
17
- };
18
- sizeInFields?: () => number;
19
- }
20
-
21
- const errors = {
22
- fieldLengthNotMatching: (expected: number, actual: number) =>
23
- new Error(`Expected ${expected} field elements, got ${actual}`),
24
-
25
- typeNotCompatible: (name: string) =>
26
- new Error(
27
- `Cannot decode type ${name}, it has to be either a Struct, CircuitValue or built-in snarkyjs type`
28
- ),
29
- };
30
-
31
- export class MethodParameterDecoder {
32
- public static fromMethod(target: RuntimeModule<unknown>, methodName: string) {
33
- const paramtypes = Reflect.getMetadata(
34
- "design:paramtypes",
35
- target,
36
- methodName
37
- );
38
-
39
- return new MethodParameterDecoder(paramtypes);
40
- }
41
-
42
- private constructor(private readonly types: FromFieldClass[]) {}
43
-
44
- public fromFields(fields: Field[]): Fieldable[] {
45
- if (fields.length < this.fieldSize) {
46
- throw errors.fieldLengthNotMatching(this.fieldSize, fields.length);
47
- }
48
-
49
- let stack = fields.slice();
50
-
51
- return this.types.map((type) => {
52
- const numberFieldsNeeded =
53
- type.prototype._fields?.length ?? type.sizeInFields?.() ?? -1;
54
- if (numberFieldsNeeded === -1) {
55
- throw errors.typeNotCompatible(type.name);
56
- }
57
- const structFields = stack.slice(0, numberFieldsNeeded);
58
- stack = stack.slice(numberFieldsNeeded);
59
- return type.fromFields(structFields);
60
- });
61
- }
62
-
63
- public get fieldSize(): number {
64
- return this.types
65
- .map(
66
- (type) => type.prototype._fields?.length ?? type.sizeInFields?.() ?? 0
67
- )
68
- .reduce((a, b) => a + b, 0);
69
- }
70
- }
@@ -1,63 +0,0 @@
1
- import { Path, State } from "@proto-kit/protocol";
2
-
3
- import type { RuntimeModule } from "../runtime/RuntimeModule.js";
4
-
5
- const errors = {
6
- missingName: (className: string) =>
7
- new Error(
8
- `Unable to provide a unique identifier for state, ${className} is missing a name.
9
- Did you forget to extend your runtime module with 'extends RuntimeModule'?`
10
- ),
11
-
12
- missingRuntime: (className: string) =>
13
- new Error(
14
- `Unable to provide 'runtime' for state, ${className} is missing a name.
15
- Did you forget to extend your runtime module with 'extends RuntimeModule'?`
16
- ),
17
- };
18
-
19
- /**
20
- * Decorates a runtime module property as state, passing down some
21
- * underlying values to improve developer experience.
22
- */
23
- export function state() {
24
- return <TargetRuntimeModule extends RuntimeModule<unknown>>(
25
- target: TargetRuntimeModule,
26
- propertyKey: string
27
- ) => {
28
- // eslint-disable-next-line @typescript-eslint/init-declarations
29
- let value: State<unknown> | undefined;
30
-
31
- Object.defineProperty(target, propertyKey, {
32
- enumerable: true,
33
-
34
- get: function get() {
35
- // eslint-disable-next-line max-len
36
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
37
- const self = this as TargetRuntimeModule;
38
-
39
- if (self.name === undefined) {
40
- throw errors.missingName(self.constructor.name);
41
- }
42
-
43
- if (!self.runtime) {
44
- throw errors.missingRuntime(self.constructor.name);
45
- }
46
-
47
- const path = Path.fromProperty(self.name, propertyKey);
48
- if (value) {
49
- value.path = path;
50
- // eslint-disable-next-line no-warning-comments
51
- // TODO: why is this complaining about `any`?
52
-
53
- value.stateServiceProvider = self.runtime.stateServiceProvider;
54
- }
55
- return value;
56
- },
57
-
58
- set: (newValue: State<unknown>) => {
59
- value = newValue;
60
- },
61
- });
62
- };
63
- }
@@ -1,95 +0,0 @@
1
- import {
2
- CachedMerkleTreeStore,
3
- InMemoryMerkleTreeStorage,
4
- RollupMerkleTree,
5
- } from "@proto-kit/protocol";
6
- import { MockAsyncMerkleTreeStore } from "./MockAsyncMerkleStore";
7
- import { beforeEach } from "@jest/globals";
8
- import { Field, Poseidon } from "snarkyjs";
9
- import { log } from "@proto-kit/common";
10
-
11
- describe("cachedMerkleTree", () => {
12
- let store: MockAsyncMerkleTreeStore;
13
- let syncStore: InMemoryMerkleTreeStorage;
14
- let tree: RollupMerkleTree;
15
-
16
- let cached: CachedMerkleTreeStore;
17
- let cachedTree: RollupMerkleTree;
18
-
19
- beforeEach(async () => {
20
- log.setLevel("DEBUG");
21
-
22
- store = new MockAsyncMerkleTreeStore();
23
- syncStore = store.store;
24
- tree = new RollupMerkleTree(syncStore);
25
-
26
- tree.setLeaf(1n, Field(10));
27
- tree.setLeaf(3n, Field(30));
28
- tree.setLeaf(5n, Field(50));
29
-
30
- cached = new CachedMerkleTreeStore(store);
31
- await cached.preloadKey(1n);
32
- await cached.preloadKey(3n);
33
- await cached.preloadKey(5n);
34
- cachedTree = new RollupMerkleTree(cached);
35
- });
36
-
37
- it("should have the same root", async () => {
38
- expect(cached.getNode(1n, 0)).toBe(10n);
39
- expect(cached.getNode(3n, 0)).toBe(30n);
40
- expect(cached.getNode(5n, 0)).toBe(50n);
41
- expect(syncStore.getNode(5n, 0)).toBe(50n);
42
-
43
- expect(cached.getNode(0n, 1)).toBe(
44
- Poseidon.hash([Field(0), Field(10)]).toBigInt()
45
- );
46
-
47
- expect(cached.getNode(0n, 254)).toBe(await store.getNode(0n, 254));
48
- expect(cached.getNode(0n, 254)).toBe(syncStore.getNode(0n, 254));
49
-
50
- expect(cachedTree.getRoot().toBigInt()).toBe(tree.getRoot().toBigInt());
51
- });
52
-
53
- it("should load the correct root when only loading a subset of keys", async () => {
54
- await cached.preloadKey(3n);
55
-
56
- const correctRoot = tree.getRoot();
57
- expect(cachedTree.getRoot().toBigInt()).toBe(correctRoot.toBigInt());
58
- });
59
-
60
- it("should generate correct witnesses when only loading a subset of keys", async () => {
61
- await cached.preloadKey(5n);
62
-
63
- const correctRoot = tree.getRoot();
64
- const witness = tree.getWitness(5n);
65
- expect(witness.calculateRoot(Field(50)).toBigInt()).toBe(
66
- correctRoot.toBigInt()
67
- );
68
- });
69
-
70
- it("should generate correct witnesses after merging", async () => {
71
- expect(cachedTree.getRoot().toBigInt()).toBe(tree.getRoot().toBigInt());
72
-
73
- await cached.preloadKey(5n);
74
- cachedTree.setLeaf(5n, Field(100));
75
-
76
- const correctRoot = cachedTree.getRoot();
77
-
78
- await cached.mergeIntoParent();
79
-
80
- const cached2 = new CachedMerkleTreeStore(store);
81
- await cached2.preloadKey(1n);
82
- await cached2.preloadKey(3n);
83
- await cached2.preloadKey(5n);
84
- expect(cached2.getNode(1n, 0)).toBe(10n);
85
- expect(cached2.getNode(3n, 0)).toBe(30n);
86
- expect(cached2.getNode(5n, 0)).toBe(100n);
87
- const tree2 = new RollupMerkleTree(cached2);
88
-
89
- const witness = tree2.getWitness(3n);
90
-
91
- expect(witness.calculateRoot(Field(30)).toBigInt()).toBe(
92
- correctRoot.toBigInt()
93
- );
94
- });
95
- });
@@ -1,28 +0,0 @@
1
- import { AsyncMerkleTreeStore, InMemoryMerkleTreeStorage, noop } from "@proto-kit/protocol";
2
-
3
- export class MockAsyncMerkleTreeStore implements AsyncMerkleTreeStore {
4
- public readonly store = new InMemoryMerkleTreeStorage();
5
-
6
- public commit(): void {
7
- noop();
8
- }
9
-
10
- public openTransaction(): void {
11
- noop();
12
- }
13
-
14
- public async getNode(
15
- key: bigint,
16
- level: number
17
- ): Promise<bigint | undefined> {
18
- return this.store.getNode(key, level);
19
- }
20
-
21
- public async setNode(
22
- key: bigint,
23
- level: number,
24
- value: bigint
25
- ): Promise<void> {
26
- this.store.setNode(key, level, value);
27
- }
28
- }
@@ -1,82 +0,0 @@
1
- import "reflect-metadata";
2
- import { PrivateKey, Proof, PublicKey, UInt64 } from "snarkyjs";
3
- import { container } from "tsyringe";
4
- import {
5
- InMemoryStateService,
6
- MethodPublicOutput,
7
- Runtime,
8
- runtimeMethod,
9
- RuntimeMethodExecutionContext,
10
- } from "../src";
11
- import { runtimeModule } from "../src/module/decorator";
12
- import { RuntimeModule } from "../src/runtime/RuntimeModule";
13
- import { state } from "../src/state/decorator";
14
- import { StateMap } from "@proto-kit/protocol";
15
-
16
- interface BalancesConfig {}
17
- @runtimeModule()
18
- class Balances extends RuntimeModule<BalancesConfig> {
19
- @state() public balances = StateMap.from<PublicKey, UInt64>(
20
- PublicKey,
21
- UInt64
22
- );
23
-
24
- @runtimeMethod()
25
- public setBalance(to: PublicKey, amount: UInt64) {
26
- this.balances.set(to, amount);
27
- }
28
-
29
- @runtimeMethod()
30
- public transfer(from: PublicKey, to: PublicKey, amount: UInt64) {
31
- const fromBalance = this.balances.get(from);
32
- const toBalance = this.balances.get(to);
33
-
34
- this.balances.set(from, fromBalance.value.sub(amount));
35
- this.balances.set(to, toBalance.value.add(amount));
36
- }
37
- }
38
-
39
- describe("transaction", () => {
40
- it("should update the state", async () => {
41
- expect.assertions(0);
42
-
43
- const runtime = Runtime.from({
44
- modules: {
45
- Balances,
46
- },
47
-
48
- config: {
49
- Balances: {},
50
- },
51
-
52
- state: new InMemoryStateService(),
53
- });
54
-
55
- const alice = PrivateKey.random().toPublicKey();
56
- const bob = PrivateKey.random().toPublicKey();
57
-
58
- const balances = runtime.resolve("Balances");
59
-
60
- runtime.transaction(() => {
61
- balances.setBalance(alice, UInt64.from(1000));
62
- });
63
-
64
- runtime.transaction(() => {
65
- balances.transfer(alice, bob, UInt64.from(100));
66
- });
67
-
68
- const executionContext = container.resolve<RuntimeMethodExecutionContext>(
69
- RuntimeMethodExecutionContext
70
- );
71
-
72
- const balanceAlice = balances.balances.get(alice);
73
- const balanceBob = balances.balances.get(bob);
74
-
75
- console.log("balances", {
76
- // 900
77
- alice: balanceAlice.value.toString(),
78
- // 100
79
- bob: balanceBob.value.toString(),
80
- });
81
- });
82
- });
@@ -1,9 +0,0 @@
1
- {
2
- "extends": "./../../tsconfig.json",
3
- "include": [
4
- "./src/**/*.test.ts",
5
- "./test/**/*.ts",
6
- "./test/*.ts",
7
- "./src/**/*.ts"
8
- ]
9
- }