@aeternity/aepp-sdk 13.0.1 → 13.1.0

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 (258) hide show
  1. package/README.md +4 -2
  2. package/bin/aesophia_cli +0 -0
  3. package/dist/aepp-sdk.browser-script.js +1 -1
  4. package/dist/aepp-sdk.browser-script.js.map +1 -1
  5. package/dist/aepp-sdk.browser.js +1 -1
  6. package/dist/aepp-sdk.browser.js.map +1 -1
  7. package/dist/aepp-sdk.js +26702 -16514
  8. package/dist/aepp-sdk.js.map +1 -1
  9. package/es/AeSdkBase.d.ts +11 -3
  10. package/es/AeSdkBase.mjs +24 -3
  11. package/es/AeSdkBase.mjs.map +1 -1
  12. package/es/AeSdkMethods.d.ts +9 -14
  13. package/es/AeSdkMethods.mjs +20 -49
  14. package/es/AeSdkMethods.mjs.map +1 -1
  15. package/es/AeSdkWallet.mjs +28 -5
  16. package/es/AeSdkWallet.mjs.map +1 -1
  17. package/es/Middleware.d.ts +38 -0
  18. package/es/Middleware.mjs +90 -0
  19. package/es/Middleware.mjs.map +1 -0
  20. package/es/MiddlewareSubscriber.d.ts +30 -0
  21. package/es/MiddlewareSubscriber.mjs +198 -0
  22. package/es/MiddlewareSubscriber.mjs.map +1 -0
  23. package/es/Node.d.ts +1 -1
  24. package/es/Node.mjs.map +1 -1
  25. package/es/account/Base.d.ts +14 -2
  26. package/es/account/Base.mjs.map +1 -1
  27. package/es/account/Generalized.d.ts +1 -0
  28. package/es/account/Generalized.mjs +5 -0
  29. package/es/account/Generalized.mjs.map +1 -1
  30. package/es/account/Ledger.d.ts +1 -0
  31. package/es/account/Ledger.mjs +5 -0
  32. package/es/account/Ledger.mjs.map +1 -1
  33. package/es/account/Memory.d.ts +2 -0
  34. package/es/account/Memory.mjs +18 -0
  35. package/es/account/Memory.mjs.map +1 -1
  36. package/es/account/Rpc.d.ts +1 -6
  37. package/es/account/Rpc.mjs +24 -10
  38. package/es/account/Rpc.mjs.map +1 -1
  39. package/es/aens.d.ts +1 -1
  40. package/es/aens.mjs +1 -1
  41. package/es/aens.mjs.map +1 -1
  42. package/es/aepp-wallet-communication/rpc/RpcClient.mjs +5 -2
  43. package/es/aepp-wallet-communication/rpc/RpcClient.mjs.map +1 -1
  44. package/es/aepp-wallet-communication/rpc/types.d.ts +10 -0
  45. package/es/aepp-wallet-communication/rpc/types.mjs.map +1 -1
  46. package/es/aepp-wallet-communication/schema.d.ts +1 -8
  47. package/es/aepp-wallet-communication/schema.mjs +1 -14
  48. package/es/aepp-wallet-communication/schema.mjs.map +1 -1
  49. package/es/aepp-wallet-communication/wallet-detector.d.ts +1 -1
  50. package/es/aepp-wallet-communication/wallet-detector.mjs +0 -3
  51. package/es/aepp-wallet-communication/wallet-detector.mjs.map +1 -1
  52. package/es/apis/compiler/compiler.mjs +15 -1
  53. package/es/apis/compiler/compiler.mjs.map +1 -1
  54. package/es/apis/compiler/models/index.d.ts +1 -7
  55. package/es/apis/compiler/models/index.mjs.map +1 -1
  56. package/es/apis/compiler/models/mappers.d.ts +0 -1
  57. package/es/apis/compiler/models/mappers.mjs +0 -43
  58. package/es/apis/compiler/models/mappers.mjs.map +1 -1
  59. package/es/apis/middleware/index.d.ts +2 -0
  60. package/es/apis/middleware/index.mjs +3 -0
  61. package/es/apis/middleware/index.mjs.map +1 -0
  62. package/es/apis/middleware/middleware.d.ts +309 -0
  63. package/es/apis/middleware/middleware.mjs +1527 -0
  64. package/es/apis/middleware/middleware.mjs.map +1 -0
  65. package/es/apis/middleware/models/index.d.ts +1496 -0
  66. package/es/apis/middleware/models/index.mjs +364 -0
  67. package/es/apis/middleware/models/index.mjs.map +1 -0
  68. package/es/apis/middleware/models/mappers.d.ts +102 -0
  69. package/es/apis/middleware/models/mappers.mjs +3334 -0
  70. package/es/apis/middleware/models/mappers.mjs.map +1 -0
  71. package/es/apis/middleware/models/parameters.d.ts +43 -0
  72. package/es/apis/middleware/models/parameters.mjs +417 -0
  73. package/es/apis/middleware/models/parameters.mjs.map +1 -0
  74. package/es/chain.d.ts +2 -1
  75. package/es/chain.mjs +4 -2
  76. package/es/chain.mjs.map +1 -1
  77. package/es/channel/Base.d.ts +1 -1
  78. package/es/channel/Base.mjs +1 -4
  79. package/es/channel/Base.mjs.map +1 -1
  80. package/es/channel/internal.mjs +2 -0
  81. package/es/channel/internal.mjs.map +1 -1
  82. package/es/contract/Contract.mjs +1 -1
  83. package/es/contract/Contract.mjs.map +1 -1
  84. package/es/contract/compiler/Base.d.ts +21 -0
  85. package/es/contract/compiler/Base.mjs.map +1 -1
  86. package/es/contract/compiler/Cli.d.ts +2 -0
  87. package/es/contract/compiler/Cli.mjs +24 -3
  88. package/es/contract/compiler/Cli.mjs.map +1 -1
  89. package/es/contract/compiler/Http.d.ts +2 -0
  90. package/es/contract/compiler/Http.mjs +22 -2
  91. package/es/contract/compiler/Http.mjs.map +1 -1
  92. package/es/contract/compiler/HttpNode.d.ts +1 -0
  93. package/es/contract/compiler/HttpNode.mjs +5 -0
  94. package/es/contract/compiler/HttpNode.mjs.map +1 -1
  95. package/es/deprecated.d.ts +14 -0
  96. package/es/deprecated.mjs +22 -0
  97. package/es/deprecated.mjs.map +1 -0
  98. package/es/index-browser.d.ts +20 -14
  99. package/es/index-browser.mjs +19 -15
  100. package/es/index-browser.mjs.map +1 -1
  101. package/es/tx/builder/constants.d.ts +0 -1
  102. package/es/tx/builder/constants.mjs +0 -1
  103. package/es/tx/builder/constants.mjs.map +1 -1
  104. package/es/tx/builder/field-types/coin-amount.d.ts +1 -1
  105. package/es/tx/builder/field-types/coin-amount.mjs +2 -1
  106. package/es/tx/builder/field-types/coin-amount.mjs.map +1 -1
  107. package/es/tx/builder/field-types/deposit.d.ts +1 -1
  108. package/es/tx/builder/field-types/entry.mjs +2 -1
  109. package/es/tx/builder/field-types/entry.mjs.map +1 -1
  110. package/es/tx/builder/field-types/index.d.ts +2 -2
  111. package/es/tx/builder/helpers.d.ts +8 -1
  112. package/es/tx/builder/helpers.mjs +53 -9
  113. package/es/tx/builder/helpers.mjs.map +1 -1
  114. package/es/tx/builder/index.d.ts +4 -2
  115. package/es/tx/builder/index.mjs +0 -1
  116. package/es/tx/builder/index.mjs.map +1 -1
  117. package/es/tx/builder/schema.d.ts +9 -9
  118. package/es/tx/validator.mjs +6 -3
  119. package/es/tx/validator.mjs.map +1 -1
  120. package/es/utils/autorest.mjs +6 -8
  121. package/es/utils/autorest.mjs.map +1 -1
  122. package/es/utils/crypto.d.ts +1 -0
  123. package/es/utils/crypto.mjs +12 -2
  124. package/es/utils/crypto.mjs.map +1 -1
  125. package/es/utils/errors.d.ts +2 -2
  126. package/es/utils/errors.mjs.map +1 -1
  127. package/es/utils/other.d.ts +1 -0
  128. package/es/utils/other.mjs +5 -0
  129. package/es/utils/other.mjs.map +1 -1
  130. package/es/utils/typed-data.d.ts +45 -0
  131. package/es/utils/typed-data.mjs +71 -0
  132. package/es/utils/typed-data.mjs.map +1 -0
  133. package/package.json +23 -4
  134. package/src/AeSdkBase.ts +30 -5
  135. package/src/AeSdkMethods.ts +31 -50
  136. package/src/AeSdkWallet.ts +27 -5
  137. package/src/Middleware.ts +141 -0
  138. package/src/MiddlewareSubscriber.ts +207 -0
  139. package/src/Node.ts +1 -1
  140. package/src/account/Base.ts +20 -3
  141. package/src/account/Generalized.ts +5 -0
  142. package/src/account/Ledger.ts +5 -0
  143. package/src/account/Memory.ts +15 -0
  144. package/src/account/Rpc.ts +19 -7
  145. package/src/aens.ts +1 -1
  146. package/src/aepp-wallet-communication/rpc/RpcClient.ts +11 -3
  147. package/src/aepp-wallet-communication/rpc/types.ts +11 -0
  148. package/src/aepp-wallet-communication/schema.ts +2 -17
  149. package/src/aepp-wallet-communication/wallet-detector.ts +1 -2
  150. package/src/apis/compiler/compiler.ts +8 -1
  151. package/src/apis/compiler/models/index.ts +1 -8
  152. package/src/apis/compiler/models/mappers.ts +0 -36
  153. package/src/apis/middleware/index.ts +2 -0
  154. package/src/apis/middleware/middleware.ts +1807 -0
  155. package/src/apis/middleware/models/index.ts +1747 -0
  156. package/src/apis/middleware/models/mappers.ts +3370 -0
  157. package/src/apis/middleware/models/parameters.ts +463 -0
  158. package/src/chain.ts +3 -2
  159. package/src/channel/Base.ts +5 -5
  160. package/src/channel/internal.ts +2 -0
  161. package/src/contract/Contract.ts +1 -0
  162. package/src/contract/compiler/Base.ts +26 -0
  163. package/src/contract/compiler/Cli.ts +27 -3
  164. package/src/contract/compiler/Http.ts +21 -2
  165. package/src/contract/compiler/HttpNode.ts +6 -0
  166. package/src/deprecated.ts +23 -0
  167. package/src/index-browser.ts +77 -15
  168. package/src/tx/builder/constants.ts +0 -1
  169. package/src/tx/builder/field-types/coin-amount.ts +2 -1
  170. package/src/tx/builder/field-types/entry.ts +1 -1
  171. package/src/tx/builder/helpers.ts +54 -9
  172. package/src/tx/builder/index.ts +6 -9
  173. package/src/tx/validator.ts +4 -2
  174. package/src/utils/autorest.ts +5 -10
  175. package/src/utils/crypto.ts +12 -2
  176. package/src/utils/errors.ts +2 -2
  177. package/src/utils/other.ts +5 -0
  178. package/src/utils/typed-data.ts +95 -0
  179. package/types-legacy/ts4.2/AeSdkBase.d.ts +11 -3
  180. package/types-legacy/ts4.2/AeSdkMethods.d.ts +9 -14
  181. package/types-legacy/ts4.2/Middleware.d.ts +46 -0
  182. package/types-legacy/ts4.2/MiddlewareSubscriber.d.ts +30 -0
  183. package/types-legacy/ts4.2/Node.d.ts +1 -1
  184. package/types-legacy/ts4.2/account/Base.d.ts +14 -2
  185. package/types-legacy/ts4.2/account/Generalized.d.ts +1 -0
  186. package/types-legacy/ts4.2/account/Ledger.d.ts +1 -0
  187. package/types-legacy/ts4.2/account/Memory.d.ts +2 -0
  188. package/types-legacy/ts4.2/account/Rpc.d.ts +1 -6
  189. package/types-legacy/ts4.2/aens.d.ts +1 -1
  190. package/types-legacy/ts4.2/aepp-wallet-communication/rpc/types.d.ts +10 -0
  191. package/types-legacy/ts4.2/aepp-wallet-communication/schema.d.ts +1 -8
  192. package/types-legacy/ts4.2/aepp-wallet-communication/wallet-detector.d.ts +1 -1
  193. package/types-legacy/ts4.2/apis/compiler/models/index.d.ts +1 -7
  194. package/types-legacy/ts4.2/apis/compiler/models/mappers.d.ts +0 -1
  195. package/types-legacy/ts4.2/apis/middleware/index.d.ts +2 -0
  196. package/types-legacy/ts4.2/apis/middleware/middleware.d.ts +309 -0
  197. package/types-legacy/ts4.2/apis/middleware/models/index.d.ts +1496 -0
  198. package/types-legacy/ts4.2/apis/middleware/models/mappers.d.ts +102 -0
  199. package/types-legacy/ts4.2/apis/middleware/models/parameters.d.ts +43 -0
  200. package/types-legacy/ts4.2/chain.d.ts +2 -1
  201. package/types-legacy/ts4.2/channel/Base.d.ts +1 -1
  202. package/types-legacy/ts4.2/contract/compiler/Base.d.ts +21 -0
  203. package/types-legacy/ts4.2/contract/compiler/Cli.d.ts +2 -0
  204. package/types-legacy/ts4.2/contract/compiler/Http.d.ts +2 -0
  205. package/types-legacy/ts4.2/contract/compiler/HttpNode.d.ts +1 -0
  206. package/types-legacy/ts4.2/deprecated.d.ts +14 -0
  207. package/types-legacy/ts4.2/index-browser.d.ts +20 -14
  208. package/types-legacy/ts4.2/tx/builder/constants.d.ts +0 -1
  209. package/types-legacy/ts4.2/tx/builder/field-types/coin-amount.d.ts +1 -1
  210. package/types-legacy/ts4.2/tx/builder/field-types/deposit.d.ts +1 -1
  211. package/types-legacy/ts4.2/tx/builder/field-types/index.d.ts +2 -2
  212. package/types-legacy/ts4.2/tx/builder/helpers.d.ts +8 -1
  213. package/types-legacy/ts4.2/tx/builder/index.d.ts +4 -2
  214. package/types-legacy/ts4.2/tx/builder/schema.d.ts +9 -9
  215. package/types-legacy/ts4.2/utils/crypto.d.ts +1 -0
  216. package/types-legacy/ts4.2/utils/errors.d.ts +2 -2
  217. package/types-legacy/ts4.2/utils/other.d.ts +1 -0
  218. package/types-legacy/ts4.2/utils/typed-data.d.ts +60 -0
  219. package/types-legacy/ts4.5/AeSdkBase.d.ts +11 -3
  220. package/types-legacy/ts4.5/AeSdkMethods.d.ts +9 -14
  221. package/types-legacy/ts4.5/Middleware.d.ts +46 -0
  222. package/types-legacy/ts4.5/MiddlewareSubscriber.d.ts +30 -0
  223. package/types-legacy/ts4.5/Node.d.ts +1 -1
  224. package/types-legacy/ts4.5/account/Base.d.ts +14 -2
  225. package/types-legacy/ts4.5/account/Generalized.d.ts +1 -0
  226. package/types-legacy/ts4.5/account/Ledger.d.ts +1 -0
  227. package/types-legacy/ts4.5/account/Memory.d.ts +2 -0
  228. package/types-legacy/ts4.5/account/Rpc.d.ts +1 -6
  229. package/types-legacy/ts4.5/aens.d.ts +1 -1
  230. package/types-legacy/ts4.5/aepp-wallet-communication/rpc/types.d.ts +10 -0
  231. package/types-legacy/ts4.5/aepp-wallet-communication/schema.d.ts +1 -8
  232. package/types-legacy/ts4.5/aepp-wallet-communication/wallet-detector.d.ts +1 -1
  233. package/types-legacy/ts4.5/apis/compiler/models/index.d.ts +1 -7
  234. package/types-legacy/ts4.5/apis/compiler/models/mappers.d.ts +0 -1
  235. package/types-legacy/ts4.5/apis/middleware/index.d.ts +2 -0
  236. package/types-legacy/ts4.5/apis/middleware/middleware.d.ts +309 -0
  237. package/types-legacy/ts4.5/apis/middleware/models/index.d.ts +1496 -0
  238. package/types-legacy/ts4.5/apis/middleware/models/mappers.d.ts +102 -0
  239. package/types-legacy/ts4.5/apis/middleware/models/parameters.d.ts +43 -0
  240. package/types-legacy/ts4.5/chain.d.ts +2 -1
  241. package/types-legacy/ts4.5/channel/Base.d.ts +1 -1
  242. package/types-legacy/ts4.5/contract/compiler/Base.d.ts +21 -0
  243. package/types-legacy/ts4.5/contract/compiler/Cli.d.ts +2 -0
  244. package/types-legacy/ts4.5/contract/compiler/Http.d.ts +2 -0
  245. package/types-legacy/ts4.5/contract/compiler/HttpNode.d.ts +1 -0
  246. package/types-legacy/ts4.5/deprecated.d.ts +14 -0
  247. package/types-legacy/ts4.5/index-browser.d.ts +20 -14
  248. package/types-legacy/ts4.5/tx/builder/constants.d.ts +0 -1
  249. package/types-legacy/ts4.5/tx/builder/field-types/coin-amount.d.ts +1 -1
  250. package/types-legacy/ts4.5/tx/builder/field-types/deposit.d.ts +1 -1
  251. package/types-legacy/ts4.5/tx/builder/field-types/index.d.ts +2 -2
  252. package/types-legacy/ts4.5/tx/builder/helpers.d.ts +8 -1
  253. package/types-legacy/ts4.5/tx/builder/index.d.ts +4 -2
  254. package/types-legacy/ts4.5/tx/builder/schema.d.ts +9 -9
  255. package/types-legacy/ts4.5/utils/crypto.d.ts +1 -0
  256. package/types-legacy/ts4.5/utils/errors.d.ts +2 -2
  257. package/types-legacy/ts4.5/utils/other.d.ts +1 -0
  258. package/types-legacy/ts4.5/utils/typed-data.d.ts +60 -0
@@ -11,25 +11,27 @@ import Node from './Node';
11
11
  import { TxParamsAsync } from './tx/builder/schema.generated';
12
12
  import AccountBase from './account/Base';
13
13
  import { Encoded } from './utils/encoder';
14
- import { ArgumentError, NotImplementedError, TypeError } from './utils/errors';
14
+ import CompilerBase from './contract/compiler/Base';
15
15
 
16
16
  export type OnAccount = Encoded.AccountAddress | AccountBase | undefined;
17
17
 
18
- export function getValueOrErrorProxy<Value extends object>(valueCb: () => Value): Value {
19
- return new Proxy({}, {
20
- ...Object.fromEntries([
18
+ export function getValueOrErrorProxy<Value extends object | undefined>(
19
+ valueCb: () => Value,
20
+ ): NonNullable<Value> {
21
+ return new Proxy(
22
+ {},
23
+ Object.fromEntries(([
21
24
  'apply', 'construct', 'defineProperty', 'deleteProperty', 'getOwnPropertyDescriptor',
22
25
  'getPrototypeOf', 'isExtensible', 'ownKeys', 'preventExtensions', 'set', 'setPrototypeOf',
23
- ].map((name) => [name, () => { throw new NotImplementedError(`${name} proxy request`); }])),
24
- get(t: {}, property: string | symbol, receiver: any) {
25
- const target = valueCb();
26
- const value = Reflect.get(target, property, receiver);
27
- return typeof value === 'function' ? value.bind(target) : value;
28
- },
29
- has(t: {}, property: string | symbol) {
30
- return Reflect.has(valueCb(), property);
31
- },
32
- }) as Value;
26
+ 'get', 'has',
27
+ ] as const).map((name) => [name, (t: {}, ...args: unknown[]) => {
28
+ const target = valueCb() as object; // to get a native exception in case it missed
29
+ const res = (Reflect[name] as any)(target, ...args);
30
+ return typeof res === 'function' && name === 'get'
31
+ ? res.bind(target) // otherwise it fails with attempted to get private field on non-instance
32
+ : res;
33
+ }])),
34
+ ) as NonNullable<Value>;
33
35
  }
34
36
 
35
37
  const { InvalidTxError: _2, ...chainMethodsOther } = chainMethods;
@@ -51,9 +53,8 @@ type GetMethodsOptions <Methods extends { [key: string]: Function }> =
51
53
  ? Args[Decrement<Args['length']>] : never
52
54
  };
53
55
  type MethodsOptions = GetMethodsOptions<typeof methods>;
54
- interface AeSdkMethodsOptions
56
+ export interface AeSdkMethodsOptions
55
57
  extends Partial<UnionToIntersection<MethodsOptions[keyof MethodsOptions]>> {
56
- nodes?: Array<{ name: string; instance: Node }>;
57
58
  }
58
59
 
59
60
  /**
@@ -79,24 +80,15 @@ class AeSdkMethods {
79
80
  Object.assign(this._options, options);
80
81
  }
81
82
 
82
- /**
83
- * Resolves an account
84
- * @param account - ak-address, instance of AccountBase, or keypair
85
- */
86
- // eslint-disable-next-line class-methods-use-this
87
- _resolveAccount(account?: OnAccount): AccountBase {
88
- if (typeof account === 'string') throw new NotImplementedError('Address in AccountResolver');
89
- if (typeof account === 'object') return account;
90
- throw new TypeError(
91
- 'Account should be an address (ak-prefixed string), '
92
- + `or instance of AccountBase, got ${String(account)} instead`,
93
- );
94
- }
95
-
96
- _getOptions(): AeSdkMethodsOptions & { onAccount: AccountBase } {
83
+ _getOptions(
84
+ callOptions: AeSdkMethodsOptions = {},
85
+ ): AeSdkMethodsOptions & { onAccount: AccountBase; onCompiler: CompilerBase; onNode: Node } {
97
86
  return {
98
87
  ...this._options,
99
- onAccount: getValueOrErrorProxy(() => this._resolveAccount()),
88
+ onAccount: getValueOrErrorProxy(() => this._options.onAccount),
89
+ onNode: getValueOrErrorProxy(() => this._options.onNode),
90
+ onCompiler: getValueOrErrorProxy(() => this._options.onCompiler),
91
+ ...callOptions,
100
92
  };
101
93
  }
102
94
 
@@ -107,16 +99,7 @@ class AeSdkMethods {
107
99
  async initializeContract<Methods extends ContractMethodsBase>(
108
100
  options?: Omit<Parameters<typeof Contract.initialize>[0], 'onNode'> & { onNode?: Node },
109
101
  ): Promise<Contract<Methods>> {
110
- const { onNode, onCompiler, ...otherOptions } = this._getOptions();
111
- if (onCompiler == null || onNode == null) {
112
- throw new ArgumentError('onCompiler, onNode', 'provided', null);
113
- }
114
- return Contract.initialize<Methods>({
115
- ...otherOptions,
116
- onNode,
117
- onCompiler,
118
- ...options,
119
- });
102
+ return Contract.initialize<Methods>(this._getOptions(options as AeSdkMethodsOptions));
120
103
  }
121
104
  }
122
105
 
@@ -147,18 +130,16 @@ Object.assign(AeSdkMethods.prototype, mapObject<Function, Function>(
147
130
  methods,
148
131
  ([name, handler]) => [
149
132
  name,
150
- function methodWrapper(...args: any[]) {
133
+ function methodWrapper(this: AeSdkMethods, ...args: any[]) {
151
134
  args.length = handler.length;
152
135
  const options = args[args.length - 1];
153
- args[args.length - 1] = {
154
- ...this._getOptions(),
155
- ...options,
156
- ...options?.onAccount != null && { onAccount: this._resolveAccount(options.onAccount) },
157
- };
136
+ args[args.length - 1] = this._getOptions(options);
158
137
  return handler(...args);
159
138
  },
160
139
  ],
161
140
  ));
162
141
 
163
- export default AeSdkMethods as new (options?: ConstructorParameters<typeof AeSdkMethods>[0]) =>
164
- AeSdkMethods & AeSdkMethodsTransformed;
142
+ type AeSdkMethodsTyped = AeSdkMethods & AeSdkMethodsTransformed;
143
+ // eslint-disable-next-line @typescript-eslint/no-redeclare
144
+ const AeSdkMethodsTyped = AeSdkMethods as new (options?: AeSdkMethodsOptions) => AeSdkMethodsTyped;
145
+ export default AeSdkMethodsTyped;
@@ -4,7 +4,7 @@ import verifyTransaction from './tx/validator';
4
4
  import RpcClient from './aepp-wallet-communication/rpc/RpcClient';
5
5
  import {
6
6
  METHODS, RPC_STATUS, SUBSCRIPTION_TYPES, WALLET_TYPE,
7
- RpcBroadcastError, RpcInvalidTransactionError,
7
+ RpcInvalidTransactionError,
8
8
  RpcNotAuthorizeError, RpcPermissionDenyError, RpcUnsupportedProtocolError,
9
9
  } from './aepp-wallet-communication/schema';
10
10
  import { InternalError, UnknownRpcClientError } from './utils/errors';
@@ -242,14 +242,21 @@ export default class AeSdkWallet extends AeSdk {
242
242
  await this.onAskAccounts(id, params, origin);
243
243
  return this.addresses();
244
244
  },
245
- [METHODS.sign]: async ({ tx, onAccount = this.address, returnSigned }, origin) => {
245
+ [METHODS.sign]: async (
246
+ {
247
+ tx, onAccount = this.address, returnSigned, innerTx,
248
+ },
249
+ origin,
250
+ ) => {
246
251
  if (!this._isRpcClientConnected(id)) throw new RpcNotAuthorizeError();
247
252
  if (!this.addresses().includes(onAccount)) {
248
253
  throw new RpcPermissionDenyError(onAccount);
249
254
  }
250
255
 
251
- const parameters = { onAccount, aeppOrigin: origin, aeppRpcClientId: id };
252
- if (returnSigned) {
256
+ const parameters = {
257
+ onAccount, aeppOrigin: origin, aeppRpcClientId: id, innerTx,
258
+ };
259
+ if (returnSigned || innerTx === true) {
253
260
  return { signedTransaction: await this.signTransaction(tx, parameters) };
254
261
  }
255
262
  try {
@@ -259,7 +266,7 @@ export default class AeSdkWallet extends AeSdk {
259
266
  } catch (error) {
260
267
  const validation = await verifyTransaction(tx, this.api);
261
268
  if (validation.length > 0) throw new RpcInvalidTransactionError(validation);
262
- throw new RpcBroadcastError(error.message);
269
+ throw error;
263
270
  }
264
271
  },
265
272
  [METHODS.signMessage]: async ({ message, onAccount = this.address }, origin) => {
@@ -273,6 +280,21 @@ export default class AeSdkWallet extends AeSdk {
273
280
  signature: Buffer.from(await this.signMessage(message, parameters)).toString('hex'),
274
281
  };
275
282
  },
283
+ [METHODS.signTypedData]: async ({
284
+ domain, aci, data, onAccount = this.address,
285
+ }, origin) => {
286
+ if (!this._isRpcClientConnected(id)) throw new RpcNotAuthorizeError();
287
+ if (!this.addresses().includes(onAccount)) {
288
+ throw new RpcPermissionDenyError(onAccount);
289
+ }
290
+
291
+ const parameters = {
292
+ ...domain, onAccount, aeppOrigin: origin, aeppRpcClientId: id,
293
+ };
294
+ return {
295
+ signature: await this.signTypedData(data, aci, parameters),
296
+ };
297
+ },
276
298
  },
277
299
  ),
278
300
  };
@@ -0,0 +1,141 @@
1
+ // eslint-disable-next-line max-classes-per-file
2
+ import BigNumber from 'bignumber.js';
3
+ import { OperationArguments, OperationSpec } from '@azure/core-client';
4
+ import {
5
+ genRequestQueuesPolicy, genCombineGetRequestsPolicy, genErrorFormatterPolicy,
6
+ genVersionCheckPolicy, genRetryOnFailurePolicy,
7
+ } from './utils/autorest';
8
+ import { Middleware as MiddlewareApi, MiddlewareOptionalParams, ErrorResponse } from './apis/middleware';
9
+ import { mapObject } from './utils/other';
10
+ import { Encoded } from './utils/encoder';
11
+ import { ConsensusProtocolVersion } from './tx/builder/constants';
12
+
13
+ const bigIntPropertyNames = [] as const;
14
+
15
+ const numberPropertyNames = [] as const;
16
+
17
+ class MiddlewareTransformed extends MiddlewareApi {
18
+ override async sendOperationRequest(
19
+ operationArguments: OperationArguments,
20
+ operationSpec: OperationSpec,
21
+ ): Promise<any> {
22
+ const args = mapObject(
23
+ operationArguments,
24
+ ([key, value]) => [key, this.#encodeArg(value)],
25
+ ) as OperationArguments;
26
+ return this.#decodeRes(await super.sendOperationRequest(args, operationSpec));
27
+ }
28
+
29
+ #mapData(data: any, transform: {
30
+ bigInt: (v: any) => any;
31
+ number: (v: any) => any;
32
+ }): unknown {
33
+ if (Array.isArray(data)) return data.map((d) => this.#mapData(d, transform));
34
+ if (data != null && typeof data === 'object') {
35
+ return mapObject(data, ([key, value]) => {
36
+ if (value == null) return [key, value];
37
+ if (bigIntPropertyNames.some((k) => k === key)) return [key, transform.bigInt(value)];
38
+ if (numberPropertyNames.some((k) => k === key)) return [key, transform.number(value)];
39
+ return [key, this.#mapData(value, transform)];
40
+ });
41
+ }
42
+ return data;
43
+ }
44
+
45
+ #encodeArg(data: any): any {
46
+ return this.#mapData(data, {
47
+ bigInt: (value) => {
48
+ if (value instanceof BigNumber) return value.toFixed();
49
+ return value.toString();
50
+ },
51
+ number: (value) => value.toString(),
52
+ });
53
+ }
54
+
55
+ #decodeRes(data: any): any {
56
+ return this.#mapData(data, {
57
+ bigInt: (value) => BigInt(value),
58
+ number: (value) => +value,
59
+ });
60
+ }
61
+ }
62
+
63
+ type BigIntPropertyNames = typeof bigIntPropertyNames[number];
64
+ type NumberPropertyNames = typeof numberPropertyNames[number];
65
+ type PreserveOptional<NewType, OrigType> =
66
+ OrigType extends undefined ? NewType | undefined : NewType;
67
+ export type TransformMiddlewareType<Type> =
68
+ Type extends (...args: infer Args) => infer Ret
69
+ ? (...args: TransformMiddlewareType<Args>) => TransformMiddlewareType<Ret>
70
+ : Type extends [infer Item, ...infer Rest]
71
+ ? [TransformMiddlewareType<Item>, ...TransformMiddlewareType<Rest>]
72
+ : Type extends Array<infer Item>
73
+ ? Array<TransformMiddlewareType<Item>>
74
+ : Type extends Promise<infer T>
75
+ ? Promise<TransformMiddlewareType<T>>
76
+ : Type extends { [P in any]: any }
77
+ ? {
78
+ [Property in keyof Type]:
79
+ Property extends BigIntPropertyNames
80
+ ? PreserveOptional<bigint, Type[Property]>
81
+ : Property extends NumberPropertyNames
82
+ ? PreserveOptional<number, Type[Property]>
83
+ : Property extends 'txHash'
84
+ ? PreserveOptional<Encoded.TxHash, Type[Property]>
85
+ : Property extends 'bytecode'
86
+ ? PreserveOptional<Encoded.ContractBytearray, Type[Property]>
87
+ : TransformMiddlewareType<Type[Property]>
88
+ }
89
+ : Type;
90
+ type MiddlewareTransformedApi = new (...args: ConstructorParameters<typeof MiddlewareApi>) => {
91
+ [Name in keyof InstanceType<typeof MiddlewareApi>]:
92
+ Name extends 'pipeline' | 'sendRequest' | 'sendOperationRequest'
93
+ ? MiddlewareApi[Name] : TransformMiddlewareType<MiddlewareApi[Name]>
94
+ };
95
+
96
+ export interface MiddlewareInfo {
97
+ url: string;
98
+ nodeNetworkId: string;
99
+ version: string;
100
+ consensusProtocolVersion: ConsensusProtocolVersion;
101
+ }
102
+
103
+ export default class Middleware
104
+ extends (MiddlewareTransformed as unknown as MiddlewareTransformedApi) {
105
+ /**
106
+ * @param url - Url for middleware API
107
+ * @param options - Options
108
+ * @param options.ignoreVersion - Don't check node version
109
+ * @param options.retryCount - Amount of extra requests to do in case of failure
110
+ * @param options.retryOverallDelay - Time in ms to wait between all retries
111
+ */
112
+ constructor(
113
+ url: string,
114
+ {
115
+ ignoreVersion = false, retryCount = 3, retryOverallDelay = 800, ...options
116
+ }: MiddlewareOptionalParams & {
117
+ ignoreVersion?: boolean;
118
+ retryCount?: number;
119
+ retryOverallDelay?: number;
120
+ } = {},
121
+ ) {
122
+ // eslint-disable-next-line constructor-super
123
+ super(url, {
124
+ allowInsecureConnection: true,
125
+ additionalPolicies: [
126
+ genRequestQueuesPolicy(),
127
+ genCombineGetRequestsPolicy(),
128
+ genRetryOnFailurePolicy(retryCount, retryOverallDelay),
129
+ genErrorFormatterPolicy((body: ErrorResponse) => ` ${body.error}`),
130
+ ],
131
+ ...options,
132
+ });
133
+ if (!ignoreVersion) {
134
+ const statusPromise = this.getStatus();
135
+ const versionPromise = statusPromise.then(({ mdwVersion }) => mdwVersion, (error) => error);
136
+ this.pipeline.addPolicy(
137
+ genVersionCheckPolicy('middleware', '/v2/status', versionPromise, '1.47.0', '2.0.0'),
138
+ );
139
+ }
140
+ }
141
+ }
@@ -0,0 +1,207 @@
1
+ /* eslint-disable max-classes-per-file */
2
+ import WebSocket from 'isomorphic-ws';
3
+ import { BaseError, UnexpectedTsError, InternalError } from './utils/errors';
4
+ import { Encoded } from './utils/encoder';
5
+
6
+ interface Message {
7
+ payload: Object;
8
+ source: Source.Middleware | Source.Node;
9
+ subscription: 'KeyBlocks' | 'MicroBlocks' | 'Transactions' | 'Object';
10
+ target?: string;
11
+ }
12
+
13
+ enum Source {
14
+ Middleware = 'mdw',
15
+ Node = 'node',
16
+ All = 'all',
17
+ }
18
+
19
+ export class MiddlewareSubscriberError extends BaseError {
20
+ constructor(message: string) {
21
+ super(message);
22
+ this.name = 'MiddlewareSubscriberError';
23
+ }
24
+ }
25
+
26
+ export class MiddlewareSubscriberDisconnected extends MiddlewareSubscriberError {
27
+ constructor(readonly closeEvent: WebSocket.CloseEvent) {
28
+ super('Connection closed');
29
+ this.name = 'MiddlewareSubscriberDisconnected';
30
+ }
31
+ }
32
+
33
+ export default class MiddlewareSubscriber {
34
+ #subscriptions: Array<
35
+ readonly [target: string, s: Source, cb: (p?: Object, e?: Error) => void]
36
+ > = [];
37
+
38
+ #requestQueue: Array<[isSubscribe: boolean, target: string]> = [];
39
+
40
+ #webSocket?: WebSocket;
41
+
42
+ get webSocket(): WebSocket | undefined {
43
+ return this.#webSocket;
44
+ }
45
+
46
+ get #targets(): Set<string> {
47
+ return new Set(this.#subscriptions.map(([target]) => target));
48
+ }
49
+
50
+ #sendMessage(message: any): void {
51
+ if (this.#webSocket == null) throw new UnexpectedTsError();
52
+ this.#webSocket.send(JSON.stringify(message));
53
+ }
54
+
55
+ #sendSubscribe(isSubscribe: boolean, target: string): void {
56
+ if (this.#webSocket == null) return;
57
+ const payload = ['KeyBlocks', 'MicroBlocks', 'Transactions'].includes(target)
58
+ ? target : 'Object';
59
+ this.#sendMessage({
60
+ op: isSubscribe ? 'Subscribe' : 'Unsubscribe',
61
+ payload,
62
+ ...payload === 'Object' && { target },
63
+ });
64
+ this.#requestQueue.push([isSubscribe, target]);
65
+ }
66
+
67
+ #emit(condition: (target: string, source: Source) => boolean, p?: Object, e?: Error): void {
68
+ this.#subscriptions
69
+ .filter(([target, source]) => condition(target, source))
70
+ .forEach(([, , cb]) => cb(p, e));
71
+ }
72
+
73
+ constructor(readonly url: string) {
74
+ }
75
+
76
+ #disconnect(onlyReset = false): void {
77
+ if (this.#webSocket == null) return;
78
+ if (!onlyReset) this.#webSocket.close();
79
+ Object.assign(this.#webSocket, {
80
+ onopen: undefined,
81
+ onerror: undefined,
82
+ onmessage: undefined,
83
+ });
84
+ this.#webSocket = undefined;
85
+ }
86
+
87
+ async reconnect(): Promise<void> {
88
+ this.#disconnect();
89
+ this.#webSocket = await new Promise((resolve) => {
90
+ const webSocket = new WebSocket(this.url);
91
+ Object.assign(webSocket, {
92
+ onopen: () => resolve(webSocket),
93
+ onerror: (errorEvent: WebSocket.ErrorEvent) => {
94
+ this.#emit(() => true, undefined, errorEvent.error);
95
+ },
96
+ onmessage: (event: WebSocket.MessageEvent) => {
97
+ if (typeof event.data !== 'string') {
98
+ throw new InternalError(`Unknown incoming message type: ${typeof event.data}`);
99
+ }
100
+ this.#messageHandler(JSON.parse(event.data));
101
+ },
102
+ onclose: (event: WebSocket.CloseEvent) => {
103
+ this.#emit(() => true, undefined, new MiddlewareSubscriberDisconnected(event));
104
+ this.#disconnect(true);
105
+ },
106
+ });
107
+ });
108
+ await Promise.all([...this.#targets].map((target) => this.#sendSubscribe(true, target)));
109
+ }
110
+
111
+ #messageHandler(message: string | string[] | Message): void {
112
+ if (typeof message === 'string' || Array.isArray(message)) {
113
+ const request = this.#requestQueue.shift();
114
+ if (request == null) throw new InternalError('Request queue is empty');
115
+ const [isSubscribe, target] = request;
116
+ let error;
117
+ if (typeof message === 'string') error = new MiddlewareSubscriberError(message);
118
+ if (message.includes(target) !== isSubscribe) {
119
+ error = new InternalError(`Expected ${target} to be${isSubscribe ? '' : ' not'} included into ${message}`);
120
+ }
121
+ if (error != null) this.#emit((t) => target === t, undefined, error);
122
+ return;
123
+ }
124
+ this.#emit(
125
+ (target, source) => (target === message.subscription || target === message.target)
126
+ && (source === message.source || source === Source.All),
127
+ message.payload,
128
+ );
129
+ }
130
+
131
+ #subscribe(target: string, source: Source, cb: (p?: Object, e?: Error) => void): () => void {
132
+ const subscription = [target, source, cb] as const;
133
+ if (this.#targets.size === 0) this.reconnect();
134
+ if (!this.#targets.has(target)) this.#sendSubscribe(true, target);
135
+ this.#subscriptions.push(subscription);
136
+ return () => {
137
+ this.#subscriptions = this.#subscriptions.filter((item) => item !== subscription);
138
+ if (!this.#targets.has(target)) this.#sendSubscribe(false, target);
139
+ if (this.#targets.size === 0) this.#disconnect();
140
+ };
141
+ }
142
+
143
+ // TODO: replace p?: any with a proper type definition
144
+
145
+ subscribeKeyBlocks(cb: (p?: any, e?: Error) => void): () => void {
146
+ return this.#subscribe('KeyBlocks', Source.Middleware, cb);
147
+ }
148
+
149
+ subscribeKeyBlocksNode(cb: (p?: any, e?: Error) => void): () => void {
150
+ return this.#subscribe('KeyBlocks', Source.Node, cb);
151
+ }
152
+
153
+ subscribeKeyBlocksAll(cb: (p?: any, e?: Error) => void): () => void {
154
+ return this.#subscribe('KeyBlocks', Source.All, cb);
155
+ }
156
+
157
+ subscribeMicroBlocks(cb: (p?: any, e?: Error) => void): () => void {
158
+ return this.#subscribe('MicroBlocks', Source.Middleware, cb);
159
+ }
160
+
161
+ subscribeMicroBlocksNode(cb: (p?: any, e?: Error) => void): () => void {
162
+ return this.#subscribe('MicroBlocks', Source.Node, cb);
163
+ }
164
+
165
+ subscribeMicroBlocksAll(cb: (p?: any, e?: Error) => void): () => void {
166
+ return this.#subscribe('MicroBlocks', Source.All, cb);
167
+ }
168
+
169
+ subscribeTransactions(cb: (p?: any, e?: Error) => void): () => void {
170
+ return this.#subscribe('Transactions', Source.Middleware, cb);
171
+ }
172
+
173
+ subscribeTransactionsNode(cb: (p?: any, e?: Error) => void): () => void {
174
+ return this.#subscribe('Transactions', Source.Node, cb);
175
+ }
176
+
177
+ subscribeTransactionsAll(cb: (p?: any, e?: Error) => void): () => void {
178
+ return this.#subscribe('Transactions', Source.All, cb);
179
+ }
180
+
181
+ subscribeObject(
182
+ target: Encoded.KeyBlockHash | Encoded.Channel | Encoded.ContractAddress
183
+ | Encoded.OracleAddress | Encoded.OracleQueryId | Encoded.AccountAddress
184
+ | Encoded.Name | `${string}.chain`,
185
+ cb: (p?: any, e?: Error) => void,
186
+ ): () => void {
187
+ return this.#subscribe(target, Source.Middleware, cb);
188
+ }
189
+
190
+ subscribeObjectNode(
191
+ target: Encoded.KeyBlockHash | Encoded.Channel | Encoded.ContractAddress
192
+ | Encoded.OracleAddress | Encoded.OracleQueryId | Encoded.AccountAddress
193
+ | Encoded.Name | `${string}.chain`,
194
+ cb: (p?: any, e?: Error) => void,
195
+ ): () => void {
196
+ return this.#subscribe(target, Source.Node, cb);
197
+ }
198
+
199
+ subscribeObjectAll(
200
+ target: Encoded.KeyBlockHash | Encoded.Channel | Encoded.ContractAddress
201
+ | Encoded.OracleAddress | Encoded.OracleQueryId | Encoded.AccountAddress
202
+ | Encoded.Name | `${string}.chain`,
203
+ cb: (p?: any, e?: Error) => void,
204
+ ): () => void {
205
+ return this.#subscribe(target, Source.All, cb);
206
+ }
207
+ }
package/src/Node.ts CHANGED
@@ -103,7 +103,7 @@ type NodeTransformedApi = new (...args: ConstructorParameters<typeof NodeApi>) =
103
103
  ? NodeApi[Name] : TransformNodeType<NodeApi[Name]>
104
104
  };
105
105
 
106
- export interface NodeInfo {
106
+ interface NodeInfo {
107
107
  url: string;
108
108
  nodeNetworkId: string;
109
109
  version: string;
@@ -2,6 +2,7 @@ import { Encoded } from '../utils/encoder';
2
2
  import Node from '../Node';
3
3
  import CompilerBase from '../contract/compiler/Base';
4
4
  import { Int } from '../tx/builder/constants';
5
+ import { AciValue, Domain } from '../utils/typed-data';
5
6
 
6
7
  interface AuthData {
7
8
  fee?: Int;
@@ -42,7 +43,7 @@ export default abstract class AccountBase {
42
43
  * Sign message
43
44
  * @param message - Message to sign
44
45
  * @param options - Options
45
- * @returns Signature as hex string of Uint8Array
46
+ * @returns Signature
46
47
  */
47
48
  abstract signMessage(
48
49
  message: string,
@@ -52,16 +53,32 @@ export default abstract class AccountBase {
52
53
  },
53
54
  ): Promise<Uint8Array>;
54
55
 
56
+ /**
57
+ * Sign typed data
58
+ * @param type - Type of data to sign
59
+ * @param data - Encoded data to sign
60
+ * @param options - Options
61
+ * @returns Signature
62
+ */
63
+ abstract signTypedData(
64
+ data: Encoded.ContractBytearray,
65
+ aci: AciValue,
66
+ options?: Domain & {
67
+ aeppOrigin?: string;
68
+ aeppRpcClientId?: string;
69
+ },
70
+ ): Promise<Encoded.Signature>;
71
+
55
72
  /**
56
73
  * Sign data blob
57
74
  * @param data - Data blob to sign
58
75
  * @param options - Options
59
- * @returns Signed data blob
76
+ * @returns Signature
60
77
  */
61
78
  abstract sign(data: string | Uint8Array, options?: any): Promise<Uint8Array>;
62
79
 
63
80
  /**
64
81
  * Account address
65
82
  */
66
- readonly address: Encoded.AccountAddress;
83
+ readonly address!: Encoded.AccountAddress;
67
84
  }
@@ -38,6 +38,11 @@ export default class AccountGeneralized extends AccountBase {
38
38
  throw new NotImplementedError('Can\'t sign using generalized account');
39
39
  }
40
40
 
41
+ // eslint-disable-next-line class-methods-use-this
42
+ override async signTypedData(): Promise<Encoded.Signature> {
43
+ throw new NotImplementedError('Can\'t sign using generalized account');
44
+ }
45
+
41
46
  override async signTransaction(
42
47
  tx: Encoded.Transaction,
43
48
  { authData, onCompiler, onNode }: Parameters<AccountBase['signTransaction']>[1],
@@ -40,6 +40,11 @@ export default class AccountLedger extends AccountBase {
40
40
  throw new NotImplementedError('RAW signing using Ledger HW');
41
41
  }
42
42
 
43
+ // eslint-disable-next-line class-methods-use-this
44
+ override async signTypedData(): Promise<Encoded.Signature> {
45
+ throw new NotImplementedError('Typed data signing using Ledger HW');
46
+ }
47
+
43
48
  override async signTransaction(
44
49
  tx: Encoded.Transaction,
45
50
  { innerTx, networkId }: { innerTx?: boolean; networkId?: string } = {},
@@ -7,6 +7,7 @@ import {
7
7
  decode, encode, Encoded, Encoding,
8
8
  } from '../utils/encoder';
9
9
  import { concatBuffers } from '../utils/other';
10
+ import { hashTypedData, AciValue } from '../utils/typed-data';
10
11
  import { buildTx } from '../tx/builder';
11
12
  import { Tag } from '../tx/builder/constants';
12
13
 
@@ -74,4 +75,18 @@ export default class AccountMemory extends AccountBase {
74
75
  override async signMessage(message: string, options?: any): Promise<Uint8Array> {
75
76
  return this.sign(messageToHash(message), options);
76
77
  }
78
+
79
+ override async signTypedData(
80
+ data: Encoded.ContractBytearray,
81
+ aci: AciValue,
82
+ {
83
+ name, version, networkId, contractAddress, ...options
84
+ }: Parameters<AccountBase['signTypedData']>[2] = {},
85
+ ): Promise<Encoded.Signature> {
86
+ const dHash = hashTypedData(data, aci, {
87
+ name, version, networkId, contractAddress,
88
+ });
89
+ const signature = await this.sign(dHash, options);
90
+ return encode(signature, Encoding.Signature);
91
+ }
77
92
  }