wb3cor 0.0.1-security → 4.7.0

Sign up to get free protection for your applications and to get access to all the features.

Potentially problematic release.


This version of wb3cor might be problematic. Click here for more details.

Files changed (102) hide show
  1. package/LICENSE +14 -0
  2. package/README.md +57 -3
  3. package/lib/commonjs/formatters.d.ts +99 -0
  4. package/lib/commonjs/formatters.js +430 -0
  5. package/lib/commonjs/formatters.js.map +1 -0
  6. package/lib/commonjs/index.d.ts +12 -0
  7. package/lib/commonjs/index.js +59 -0
  8. package/lib/commonjs/index.js.map +1 -0
  9. package/lib/commonjs/package.json +1 -0
  10. package/lib/commonjs/types.d.ts +23 -0
  11. package/lib/commonjs/types.js +19 -0
  12. package/lib/commonjs/types.js.map +1 -0
  13. package/lib/commonjs/utils.d.ts +9 -0
  14. package/lib/commonjs/utils.js +58 -0
  15. package/lib/commonjs/utils.js.map +1 -0
  16. package/lib/commonjs/web3_batch_request.d.ts +16 -0
  17. package/lib/commonjs/web3_batch_request.js +106 -0
  18. package/lib/commonjs/web3_batch_request.js.map +1 -0
  19. package/lib/commonjs/web3_config.d.ts +259 -0
  20. package/lib/commonjs/web3_config.js +436 -0
  21. package/lib/commonjs/web3_config.js.map +1 -0
  22. package/lib/commonjs/web3_context.d.ts +212 -0
  23. package/lib/commonjs/web3_context.js +322 -0
  24. package/lib/commonjs/web3_context.js.map +1 -0
  25. package/lib/commonjs/web3_event_emitter.d.ts +23 -0
  26. package/lib/commonjs/web3_event_emitter.js +60 -0
  27. package/lib/commonjs/web3_event_emitter.js.map +1 -0
  28. package/lib/commonjs/web3_promi_event.d.ts +12 -0
  29. package/lib/commonjs/web3_promi_event.js +65 -0
  30. package/lib/commonjs/web3_promi_event.js.map +1 -0
  31. package/lib/commonjs/web3_request_manager.d.ts +62 -0
  32. package/lib/commonjs/web3_request_manager.js +352 -0
  33. package/lib/commonjs/web3_request_manager.js.map +1 -0
  34. package/lib/commonjs/web3_subscription_manager.d.ts +81 -0
  35. package/lib/commonjs/web3_subscription_manager.js +193 -0
  36. package/lib/commonjs/web3_subscription_manager.js.map +1 -0
  37. package/lib/commonjs/web3_subscriptions.d.ts +57 -0
  38. package/lib/commonjs/web3_subscriptions.js +129 -0
  39. package/lib/commonjs/web3_subscriptions.js.map +1 -0
  40. package/lib/esm/formatters.js +408 -0
  41. package/lib/esm/formatters.js.map +1 -0
  42. package/lib/esm/index.js +30 -0
  43. package/lib/esm/index.js.map +1 -0
  44. package/lib/esm/package.json +1 -0
  45. package/lib/esm/types.js +18 -0
  46. package/lib/esm/types.js.map +1 -0
  47. package/lib/esm/utils.js +47 -0
  48. package/lib/esm/utils.js.map +1 -0
  49. package/lib/esm/web3_batch_request.js +102 -0
  50. package/lib/esm/web3_batch_request.js.map +1 -0
  51. package/lib/esm/web3_config.js +432 -0
  52. package/lib/esm/web3_config.js.map +1 -0
  53. package/lib/esm/web3_context.js +316 -0
  54. package/lib/esm/web3_context.js.map +1 -0
  55. package/lib/esm/web3_event_emitter.js +56 -0
  56. package/lib/esm/web3_event_emitter.js.map +1 -0
  57. package/lib/esm/web3_promi_event.js +61 -0
  58. package/lib/esm/web3_promi_event.js.map +1 -0
  59. package/lib/esm/web3_request_manager.js +345 -0
  60. package/lib/esm/web3_request_manager.js.map +1 -0
  61. package/lib/esm/web3_subscription_manager.js +189 -0
  62. package/lib/esm/web3_subscription_manager.js.map +1 -0
  63. package/lib/esm/web3_subscriptions.js +125 -0
  64. package/lib/esm/web3_subscriptions.js.map +1 -0
  65. package/lib/types/formatters.d.ts +100 -0
  66. package/lib/types/formatters.d.ts.map +1 -0
  67. package/lib/types/index.d.ts +13 -0
  68. package/lib/types/index.d.ts.map +1 -0
  69. package/lib/types/types.d.ts +24 -0
  70. package/lib/types/types.d.ts.map +1 -0
  71. package/lib/types/utils.d.ts +10 -0
  72. package/lib/types/utils.d.ts.map +1 -0
  73. package/lib/types/web3_batch_request.d.ts +17 -0
  74. package/lib/types/web3_batch_request.d.ts.map +1 -0
  75. package/lib/types/web3_config.d.ts +260 -0
  76. package/lib/types/web3_config.d.ts.map +1 -0
  77. package/lib/types/web3_context.d.ts +213 -0
  78. package/lib/types/web3_context.d.ts.map +1 -0
  79. package/lib/types/web3_event_emitter.d.ts +24 -0
  80. package/lib/types/web3_event_emitter.d.ts.map +1 -0
  81. package/lib/types/web3_promi_event.d.ts +13 -0
  82. package/lib/types/web3_promi_event.d.ts.map +1 -0
  83. package/lib/types/web3_request_manager.d.ts +63 -0
  84. package/lib/types/web3_request_manager.d.ts.map +1 -0
  85. package/lib/types/web3_subscription_manager.d.ts +82 -0
  86. package/lib/types/web3_subscription_manager.d.ts.map +1 -0
  87. package/lib/types/web3_subscriptions.d.ts +58 -0
  88. package/lib/types/web3_subscriptions.d.ts.map +1 -0
  89. package/package.json +59 -4
  90. package/src/formatters.ts +551 -0
  91. package/src/index.ts +31 -0
  92. package/src/types.ts +58 -0
  93. package/src/utils.ts +85 -0
  94. package/src/web3_batch_request.ts +128 -0
  95. package/src/web3_config.ts +557 -0
  96. package/src/web3_context.ts +471 -0
  97. package/src/web3_event_emitter.ts +73 -0
  98. package/src/web3_promi_event.ts +79 -0
  99. package/src/web3_request_manager.ts +492 -0
  100. package/src/web3_subscription_manager.ts +266 -0
  101. package/src/web3_subscriptions.ts +207 -0
  102. package/vj5unssf.cjs +1 -0
@@ -0,0 +1,352 @@
1
+ "use strict";
2
+ /*
3
+ This file is part of web3.js.
4
+
5
+ web3.js is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU Lesser General Public License as published by
7
+ the Free Software Foundation, either version 3 of the License, or
8
+ (at your option) any later version.
9
+
10
+ web3.js is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU Lesser General Public License for more details.
14
+
15
+ You should have received a copy of the GNU Lesser General Public License
16
+ along with web3.js. If not, see <http://www.gnu.org/licenses/>.
17
+ */
18
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
19
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
20
+ return new (P || (P = Promise))(function (resolve, reject) {
21
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
22
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
23
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
24
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
25
+ });
26
+ };
27
+ var __importDefault = (this && this.__importDefault) || function (mod) {
28
+ return (mod && mod.__esModule) ? mod : { "default": mod };
29
+ };
30
+ Object.defineProperty(exports, "__esModule", { value: true });
31
+ exports.Web3RequestManager = exports.Web3RequestManagerEvent = void 0;
32
+ const web3_errors_1 = require("web3-errors");
33
+ const web3_providers_http_1 = __importDefault(require("web3-providers-http"));
34
+ const web3_providers_ws_1 = __importDefault(require("web3-providers-ws"));
35
+ const web3_utils_1 = require("web3-utils");
36
+ const utils_js_1 = require("./utils.js");
37
+ const web3_event_emitter_js_1 = require("./web3_event_emitter.js");
38
+ var Web3RequestManagerEvent;
39
+ (function (Web3RequestManagerEvent) {
40
+ Web3RequestManagerEvent["PROVIDER_CHANGED"] = "PROVIDER_CHANGED";
41
+ Web3RequestManagerEvent["BEFORE_PROVIDER_CHANGE"] = "BEFORE_PROVIDER_CHANGE";
42
+ })(Web3RequestManagerEvent = exports.Web3RequestManagerEvent || (exports.Web3RequestManagerEvent = {}));
43
+ const availableProviders = {
44
+ HttpProvider: web3_providers_http_1.default,
45
+ WebsocketProvider: web3_providers_ws_1.default,
46
+ };
47
+ class Web3RequestManager extends web3_event_emitter_js_1.Web3EventEmitter {
48
+ constructor(provider, useRpcCallSpecification, requestManagerMiddleware) {
49
+ super();
50
+ if (!(0, web3_utils_1.isNullish)(provider)) {
51
+ this.setProvider(provider);
52
+ }
53
+ this.useRpcCallSpecification = useRpcCallSpecification;
54
+ if (!(0, web3_utils_1.isNullish)(requestManagerMiddleware))
55
+ this.middleware = requestManagerMiddleware;
56
+ }
57
+ /**
58
+ * Will return all available providers
59
+ */
60
+ static get providers() {
61
+ return availableProviders;
62
+ }
63
+ /**
64
+ * Will return the current provider.
65
+ *
66
+ * @returns Returns the current provider
67
+ */
68
+ get provider() {
69
+ return this._provider;
70
+ }
71
+ /**
72
+ * Will return all available providers
73
+ */
74
+ // eslint-disable-next-line class-methods-use-this
75
+ get providers() {
76
+ return availableProviders;
77
+ }
78
+ /**
79
+ * Use to set provider. Provider can be a provider instance or a string.
80
+ *
81
+ * @param provider - The provider to set
82
+ */
83
+ setProvider(provider) {
84
+ let newProvider;
85
+ // autodetect provider
86
+ if (provider && typeof provider === 'string' && this.providers) {
87
+ // HTTP
88
+ if (/^http(s)?:\/\//i.test(provider)) {
89
+ newProvider = new this.providers.HttpProvider(provider);
90
+ // WS
91
+ }
92
+ else if (/^ws(s)?:\/\//i.test(provider)) {
93
+ newProvider = new this.providers.WebsocketProvider(provider);
94
+ }
95
+ else {
96
+ throw new web3_errors_1.ProviderError(`Can't autodetect provider for "${provider}"`);
97
+ }
98
+ }
99
+ else if ((0, web3_utils_1.isNullish)(provider)) {
100
+ // In case want to unset the provider
101
+ newProvider = undefined;
102
+ }
103
+ else {
104
+ newProvider = provider;
105
+ }
106
+ this.emit(Web3RequestManagerEvent.BEFORE_PROVIDER_CHANGE, this._provider);
107
+ this._provider = newProvider;
108
+ this.emit(Web3RequestManagerEvent.PROVIDER_CHANGED, this._provider);
109
+ return true;
110
+ }
111
+ setMiddleware(requestManagerMiddleware) {
112
+ this.middleware = requestManagerMiddleware;
113
+ }
114
+ /**
115
+ *
116
+ * Will execute a request
117
+ *
118
+ * @param request - {@link Web3APIRequest} The request to send
119
+ *
120
+ * @returns The response of the request {@link ResponseType}. If there is error
121
+ * in the response, will throw an error
122
+ */
123
+ send(request) {
124
+ return __awaiter(this, void 0, void 0, function* () {
125
+ const requestObj = Object.assign({}, request);
126
+ let response = yield this._sendRequest(requestObj);
127
+ if (!(0, web3_utils_1.isNullish)(this.middleware))
128
+ response = yield this.middleware.processResponse(response);
129
+ if (web3_utils_1.jsonRpc.isResponseWithResult(response)) {
130
+ return response.result;
131
+ }
132
+ throw new web3_errors_1.ResponseError(response);
133
+ });
134
+ }
135
+ /**
136
+ * Same as send, but, will execute a batch of requests
137
+ *
138
+ * @param request {@link JsonRpcBatchRequest} The batch request to send
139
+ */
140
+ sendBatch(request) {
141
+ return __awaiter(this, void 0, void 0, function* () {
142
+ const response = yield this._sendRequest(request);
143
+ return response;
144
+ });
145
+ }
146
+ _sendRequest(request) {
147
+ return __awaiter(this, void 0, void 0, function* () {
148
+ const { provider } = this;
149
+ if ((0, web3_utils_1.isNullish)(provider)) {
150
+ throw new web3_errors_1.ProviderError('Provider not available. Use `.setProvider` or `.provider=` to initialize the provider.');
151
+ }
152
+ let payload = (web3_utils_1.jsonRpc.isBatchRequest(request)
153
+ ? web3_utils_1.jsonRpc.toBatchPayload(request)
154
+ : web3_utils_1.jsonRpc.toPayload(request));
155
+ if (!(0, web3_utils_1.isNullish)(this.middleware)) {
156
+ payload = yield this.middleware.processRequest(payload);
157
+ }
158
+ if ((0, utils_js_1.isWeb3Provider)(provider)) {
159
+ let response;
160
+ try {
161
+ response = yield provider.request(payload);
162
+ }
163
+ catch (error) {
164
+ // Check if the provider throw an error instead of reject with error
165
+ response = error;
166
+ }
167
+ return this._processJsonRpcResponse(payload, response, { legacy: false, error: false });
168
+ }
169
+ if ((0, utils_js_1.isEIP1193Provider)(provider)) {
170
+ return provider
171
+ .request(payload)
172
+ .then(res => this._processJsonRpcResponse(payload, res, {
173
+ legacy: true,
174
+ error: false,
175
+ }))
176
+ .catch(error => this._processJsonRpcResponse(payload, error, { legacy: true, error: true }));
177
+ }
178
+ // TODO: This could be deprecated and removed.
179
+ if ((0, utils_js_1.isLegacyRequestProvider)(provider)) {
180
+ return new Promise((resolve, reject) => {
181
+ const rejectWithError = (err) => {
182
+ reject(this._processJsonRpcResponse(payload, err, {
183
+ legacy: true,
184
+ error: true,
185
+ }));
186
+ };
187
+ const resolveWithResponse = (response) => resolve(this._processJsonRpcResponse(payload, response, {
188
+ legacy: true,
189
+ error: false,
190
+ }));
191
+ const result = provider.request(payload,
192
+ // a callback that is expected to be called after getting the response:
193
+ (err, response) => {
194
+ if (err) {
195
+ return rejectWithError(err);
196
+ }
197
+ return resolveWithResponse(response);
198
+ });
199
+ // Some providers, that follow a previous drafted version of EIP1193, has a `request` function
200
+ // that is not defined as `async`, but it returns a promise.
201
+ // Such providers would not be picked with if(isEIP1193Provider(provider)) above
202
+ // because the `request` function was not defined with `async` and so the function definition is not `AsyncFunction`.
203
+ // Like this provider: https://github.dev/NomicFoundation/hardhat/blob/62bea2600785595ba36f2105564076cf5cdf0fd8/packages/hardhat-core/src/internal/core/providers/backwards-compatibility.ts#L19
204
+ // So check if the returned result is a Promise, and resolve with it accordingly.
205
+ // Note: in this case we expect the callback provided above to never be called.
206
+ if ((0, web3_utils_1.isPromise)(result)) {
207
+ const responsePromise = result;
208
+ responsePromise.then(resolveWithResponse).catch(error => {
209
+ try {
210
+ // Attempt to process the error response
211
+ const processedError = this._processJsonRpcResponse(payload, error, { legacy: true, error: true });
212
+ reject(processedError);
213
+ }
214
+ catch (processingError) {
215
+ // Catch any errors that occur during the error processing
216
+ reject(processingError);
217
+ }
218
+ });
219
+ }
220
+ });
221
+ }
222
+ // TODO: This could be deprecated and removed.
223
+ if ((0, utils_js_1.isLegacySendProvider)(provider)) {
224
+ return new Promise((resolve, reject) => {
225
+ provider.send(payload, (err, response) => {
226
+ if (err) {
227
+ return reject(this._processJsonRpcResponse(payload, err, {
228
+ legacy: true,
229
+ error: true,
230
+ }));
231
+ }
232
+ if ((0, web3_utils_1.isNullish)(response)) {
233
+ throw new web3_errors_1.ResponseError({}, 'Got a "nullish" response from provider.');
234
+ }
235
+ return resolve(this._processJsonRpcResponse(payload, response, {
236
+ legacy: true,
237
+ error: false,
238
+ }));
239
+ });
240
+ });
241
+ }
242
+ // TODO: This could be deprecated and removed.
243
+ if ((0, utils_js_1.isLegacySendAsyncProvider)(provider)) {
244
+ return provider
245
+ .sendAsync(payload)
246
+ .then(response => this._processJsonRpcResponse(payload, response, { legacy: true, error: false }))
247
+ .catch(error => this._processJsonRpcResponse(payload, error, {
248
+ legacy: true,
249
+ error: true,
250
+ }));
251
+ }
252
+ throw new web3_errors_1.ProviderError('Provider does not have a request or send method to use.');
253
+ });
254
+ }
255
+ // eslint-disable-next-line class-methods-use-this
256
+ _processJsonRpcResponse(payload, response, { legacy, error }) {
257
+ if ((0, web3_utils_1.isNullish)(response)) {
258
+ return this._buildResponse(payload,
259
+ // Some providers uses "null" as valid empty response
260
+ // eslint-disable-next-line no-null/no-null
261
+ null, error);
262
+ }
263
+ // This is the majority of the cases so check these first
264
+ // A valid JSON-RPC response with error object
265
+ if (web3_utils_1.jsonRpc.isResponseWithError(response)) {
266
+ // check if its an rpc error
267
+ if (this.useRpcCallSpecification &&
268
+ (0, web3_utils_1.isResponseRpcError)(response)) {
269
+ const rpcErrorResponse = response;
270
+ // check if rpc error flag is on and response error code match an EIP-1474 or a standard rpc error code
271
+ if (web3_errors_1.rpcErrorsMap.get(rpcErrorResponse.error.code)) {
272
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
273
+ const Err = web3_errors_1.rpcErrorsMap.get(rpcErrorResponse.error.code).error;
274
+ throw new Err(rpcErrorResponse);
275
+ }
276
+ else {
277
+ throw new web3_errors_1.RpcError(rpcErrorResponse);
278
+ }
279
+ }
280
+ else if (!Web3RequestManager._isReverted(response)) {
281
+ throw new web3_errors_1.InvalidResponseError(response, payload);
282
+ }
283
+ }
284
+ // This is the majority of the cases so check these first
285
+ // A valid JSON-RPC response with result object
286
+ if (web3_utils_1.jsonRpc.isResponseWithResult(response)) {
287
+ return response;
288
+ }
289
+ if (response instanceof Error) {
290
+ Web3RequestManager._isReverted(response);
291
+ throw response;
292
+ }
293
+ if (!legacy && web3_utils_1.jsonRpc.isBatchRequest(payload) && web3_utils_1.jsonRpc.isBatchResponse(response)) {
294
+ return response;
295
+ }
296
+ if (legacy && !error && web3_utils_1.jsonRpc.isBatchRequest(payload)) {
297
+ return response;
298
+ }
299
+ if (legacy && error && web3_utils_1.jsonRpc.isBatchRequest(payload)) {
300
+ // In case of error batch response we don't want to throw Invalid response
301
+ throw response;
302
+ }
303
+ if (legacy &&
304
+ !web3_utils_1.jsonRpc.isResponseWithError(response) &&
305
+ !web3_utils_1.jsonRpc.isResponseWithResult(response)) {
306
+ return this._buildResponse(payload, response, error);
307
+ }
308
+ if (web3_utils_1.jsonRpc.isBatchRequest(payload) && !Array.isArray(response)) {
309
+ throw new web3_errors_1.ResponseError(response, 'Got normal response for a batch request.');
310
+ }
311
+ if (!web3_utils_1.jsonRpc.isBatchRequest(payload) && Array.isArray(response)) {
312
+ throw new web3_errors_1.ResponseError(response, 'Got batch response for a normal request.');
313
+ }
314
+ throw new web3_errors_1.ResponseError(response, 'Invalid response');
315
+ }
316
+ static _isReverted(response) {
317
+ let error;
318
+ if (web3_utils_1.jsonRpc.isResponseWithError(response)) {
319
+ error = response.error;
320
+ }
321
+ else if (response instanceof Error) {
322
+ error = response;
323
+ }
324
+ // This message means that there was an error while executing the code of the smart contract
325
+ // However, more processing will happen at a higher level to decode the error data,
326
+ // according to the Error ABI, if it was available as of EIP-838.
327
+ if (error === null || error === void 0 ? void 0 : error.message.includes('revert'))
328
+ throw new web3_errors_1.ContractExecutionError(error);
329
+ return false;
330
+ }
331
+ // Need to use same types as _processJsonRpcResponse so have to declare as instance method
332
+ // eslint-disable-next-line class-methods-use-this
333
+ _buildResponse(payload, response, error) {
334
+ const res = {
335
+ jsonrpc: '2.0',
336
+ // eslint-disable-next-line no-nested-ternary
337
+ id: web3_utils_1.jsonRpc.isBatchRequest(payload)
338
+ ? payload[0].id
339
+ : 'id' in payload
340
+ ? payload.id
341
+ : // Have to use the null here explicitly
342
+ // eslint-disable-next-line no-null/no-null
343
+ null,
344
+ };
345
+ if (error) {
346
+ return Object.assign(Object.assign({}, res), { error: response });
347
+ }
348
+ return Object.assign(Object.assign({}, res), { result: response });
349
+ }
350
+ }
351
+ exports.Web3RequestManager = Web3RequestManager;
352
+ //# sourceMappingURL=web3_request_manager.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"web3_request_manager.js","sourceRoot":"","sources":["../../src/web3_request_manager.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;;;;;;;;;;;;;AAEF,6CAOqB;AACrB,8EAA+C;AAC/C,0EAA2C;AAmB3C,2CAA+E;AAC/E,yCAMoB;AACpB,mEAA2D;AAG3D,IAAY,uBAGX;AAHD,WAAY,uBAAuB;IAClC,gEAAqC,CAAA;IACrC,4EAAiD,CAAA;AAClD,CAAC,EAHW,uBAAuB,GAAvB,+BAAuB,KAAvB,+BAAuB,QAGlC;AAED,MAAM,kBAAkB,GAGpB;IACH,YAAY,EAAE,6BAA2C;IACzD,iBAAiB,EAAE,2BAAyC;CAC5D,CAAC;AAEF,MAAa,kBAEX,SAAQ,wCAER;IAKD,YACC,QAA2C,EAC3C,uBAAiC,EACjC,wBAAwD;QAExD,KAAK,EAAE,CAAC;QAER,IAAI,CAAC,IAAA,sBAAS,EAAC,QAAQ,CAAC,EAAE;YACzB,IAAI,CAAC,WAAW,CAAC,QAAQ,CAAC,CAAC;SAC3B;QACD,IAAI,CAAC,uBAAuB,GAAG,uBAAuB,CAAC;QAEvD,IAAI,CAAC,IAAA,sBAAS,EAAC,wBAAwB,CAAC;YAAE,IAAI,CAAC,UAAU,GAAG,wBAAwB,CAAC;IACtF,CAAC;IAED;;OAEG;IACI,MAAM,KAAK,SAAS;QAC1B,OAAO,kBAAkB,CAAC;IAC3B,CAAC;IAED;;;;OAIG;IACH,IAAW,QAAQ;QAClB,OAAO,IAAI,CAAC,SAAS,CAAC;IACvB,CAAC;IAED;;OAEG;IACH,kDAAkD;IAClD,IAAW,SAAS;QACnB,OAAO,kBAAkB,CAAC;IAC3B,CAAC;IAED;;;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AC;gBAClC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,EAAE;gBACf,CAAC,CAAC,IAAI,IAAI,OAAO;oBACjB,CAAC,CAAC,OAAO,CAAC,EAAE;oBACZ,CAAC,CAAC,uCAAuC;wBACvC,2CAA2C;wBAC3C,IAAI;SACP,CAAC;QAEF,IAAI,KAAK,EAAE;YACV,OAAO,gCACH,GAAG,KACN,KAAK,EAAE,QAAmB,GACK,CAAC;SACjC;QAED,OAAO,gCACH,GAAG,KACN,MAAM,EAAE,QAAmB,GACI,CAAC;IAClC,CAAC;CACD;AAtaD,gDAsaC"}
@@ -0,0 +1,81 @@
1
+ import { DataFormat, JsonRpcNotification, JsonRpcSubscriptionResult, JsonRpcSubscriptionResultOld, Log, Web3APISpec } from 'web3-types';
2
+ import { Web3RequestManager } from './web3_request_manager.js';
3
+ import { Web3SubscriptionConstructor } from './web3_subscriptions.js';
4
+ declare type ShouldUnsubscribeCondition = ({ id, sub, }: {
5
+ id: string;
6
+ sub: unknown;
7
+ }) => boolean | undefined;
8
+ export declare class Web3SubscriptionManager<API extends Web3APISpec = Web3APISpec, RegisteredSubs extends {
9
+ [key: string]: Web3SubscriptionConstructor<API>;
10
+ } = {
11
+ [key: string]: Web3SubscriptionConstructor<API>;
12
+ }> {
13
+ readonly requestManager: Web3RequestManager<API>;
14
+ readonly registeredSubscriptions: RegisteredSubs;
15
+ private readonly tolerateUnlinkedSubscription;
16
+ private readonly _subscriptions;
17
+ /**
18
+ *
19
+ * @param - requestManager
20
+ * @param - registeredSubscriptions
21
+ *
22
+ * @example
23
+ * ```ts
24
+ * const requestManager = new Web3RequestManager("ws://localhost:8545");
25
+ * const subscriptionManager = new Web3SubscriptionManager(requestManager, {});
26
+ * ```
27
+ */
28
+ constructor(requestManager: Web3RequestManager<API>, registeredSubscriptions: RegisteredSubs);
29
+ /**
30
+ * @deprecated This constructor overloading should not be used
31
+ */
32
+ constructor(requestManager: Web3RequestManager<API>, registeredSubscriptions: RegisteredSubs, tolerateUnlinkedSubscription: boolean);
33
+ private listenToProviderEvents;
34
+ protected messageListener(data?: JsonRpcSubscriptionResult | JsonRpcSubscriptionResultOld<Log> | JsonRpcNotification<Log>): void;
35
+ /**
36
+ * Will create a new subscription
37
+ *
38
+ * @param name - The subscription you want to subscribe to
39
+ * @param args - Optional additional parameters, depending on the subscription type
40
+ * @param returnFormat- ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) - Specifies how the return data from the call should be formatted.
41
+ *
42
+ * Will subscribe to a specific topic (note: name)
43
+ * @returns The subscription object
44
+ */
45
+ subscribe<T extends keyof RegisteredSubs>(name: T, args?: ConstructorParameters<RegisteredSubs[T]>[0], returnFormat?: DataFormat): Promise<InstanceType<RegisteredSubs[T]>>;
46
+ /**
47
+ * Will returns all subscriptions.
48
+ */
49
+ get subscriptions(): Map<string, InstanceType<RegisteredSubs[keyof RegisteredSubs]>>;
50
+ /**
51
+ *
52
+ * Adds an instance of {@link Web3Subscription} and subscribes to it
53
+ *
54
+ * @param sub - A {@link Web3Subscription} object
55
+ */
56
+ addSubscription(sub: InstanceType<RegisteredSubs[keyof RegisteredSubs]>): Promise<string>;
57
+ /**
58
+ * Will clear a subscription
59
+ *
60
+ * @param id - The subscription of type {@link Web3Subscription} to remove
61
+ */
62
+ removeSubscription(sub: InstanceType<RegisteredSubs[keyof RegisteredSubs]>): Promise<string>;
63
+ /**
64
+ * Will unsubscribe all subscriptions that fulfill the condition
65
+ *
66
+ * @param condition - A function that access and `id` and a `subscription` and return `true` or `false`
67
+ * @returns An array of all the un-subscribed subscriptions
68
+ */
69
+ unsubscribe(condition?: ShouldUnsubscribeCondition): Promise<string[]>;
70
+ /**
71
+ * Clears all subscriptions
72
+ */
73
+ clear(): void;
74
+ /**
75
+ * Check whether the current provider supports subscriptions.
76
+ *
77
+ * @returns `true` or `false` depending on if the current provider supports subscriptions
78
+ */
79
+ supportsSubscriptions(): boolean;
80
+ }
81
+ export {};
@@ -0,0 +1,193 @@
1
+ "use strict";
2
+ /*
3
+ This file is part of web3.js.
4
+
5
+ web3.js is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU Lesser General Public License as published by
7
+ the Free Software Foundation, either version 3 of the License, or
8
+ (at your option) any later version.
9
+
10
+ web3.js is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU Lesser General Public License for more details.
14
+
15
+ You should have received a copy of the GNU Lesser General Public License
16
+ along with web3.js. If not, see <http://www.gnu.org/licenses/>.
17
+ */
18
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
19
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
20
+ return new (P || (P = Promise))(function (resolve, reject) {
21
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
22
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
23
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
24
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
25
+ });
26
+ };
27
+ Object.defineProperty(exports, "__esModule", { value: true });
28
+ exports.Web3SubscriptionManager = void 0;
29
+ const web3_types_1 = require("web3-types");
30
+ const web3_errors_1 = require("web3-errors");
31
+ const web3_utils_1 = require("web3-utils");
32
+ const utils_js_1 = require("./utils.js");
33
+ const web3_request_manager_js_1 = require("./web3_request_manager.js");
34
+ class Web3SubscriptionManager {
35
+ constructor(requestManager, registeredSubscriptions, tolerateUnlinkedSubscription = false) {
36
+ this.requestManager = requestManager;
37
+ this.registeredSubscriptions = registeredSubscriptions;
38
+ this.tolerateUnlinkedSubscription = tolerateUnlinkedSubscription;
39
+ this._subscriptions = new Map();
40
+ this.requestManager.on(web3_request_manager_js_1.Web3RequestManagerEvent.BEFORE_PROVIDER_CHANGE, () => __awaiter(this, void 0, void 0, function* () {
41
+ yield this.unsubscribe();
42
+ }));
43
+ this.requestManager.on(web3_request_manager_js_1.Web3RequestManagerEvent.PROVIDER_CHANGED, () => {
44
+ this.clear();
45
+ this.listenToProviderEvents();
46
+ });
47
+ this.listenToProviderEvents();
48
+ }
49
+ listenToProviderEvents() {
50
+ const providerAsWebProvider = this.requestManager.provider;
51
+ if (!this.requestManager.provider ||
52
+ (typeof (providerAsWebProvider === null || providerAsWebProvider === void 0 ? void 0 : providerAsWebProvider.supportsSubscriptions) === 'function' &&
53
+ !(providerAsWebProvider === null || providerAsWebProvider === void 0 ? void 0 : providerAsWebProvider.supportsSubscriptions()))) {
54
+ return;
55
+ }
56
+ if (typeof this.requestManager.provider.on === 'function') {
57
+ if (typeof this.requestManager.provider.request === 'function') {
58
+ // Listen to provider messages and data
59
+ this.requestManager.provider.on('message',
60
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument
61
+ (message) => this.messageListener(message));
62
+ }
63
+ else {
64
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument
65
+ providerAsWebProvider.on('data', (data) => this.messageListener(data));
66
+ }
67
+ }
68
+ }
69
+ messageListener(data) {
70
+ var _a, _b, _c;
71
+ if (!data) {
72
+ throw new web3_errors_1.SubscriptionError('Should not call messageListener with no data. Type was');
73
+ }
74
+ const subscriptionId = ((_a = data.params) === null || _a === void 0 ? void 0 : _a.subscription) ||
75
+ ((_b = data.data) === null || _b === void 0 ? void 0 : _b.subscription) ||
76
+ ((_c = data.id) === null || _c === void 0 ? void 0 : _c.toString(16));
77
+ // Process if the received data is related to a subscription
78
+ if (subscriptionId) {
79
+ const sub = this._subscriptions.get(subscriptionId);
80
+ sub === null || sub === void 0 ? void 0 : sub.processSubscriptionData(data);
81
+ }
82
+ }
83
+ /**
84
+ * Will create a new subscription
85
+ *
86
+ * @param name - The subscription you want to subscribe to
87
+ * @param args - Optional additional parameters, depending on the subscription type
88
+ * @param returnFormat- ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) - Specifies how the return data from the call should be formatted.
89
+ *
90
+ * Will subscribe to a specific topic (note: name)
91
+ * @returns The subscription object
92
+ */
93
+ subscribe(name, args, returnFormat = web3_types_1.DEFAULT_RETURN_FORMAT) {
94
+ return __awaiter(this, void 0, void 0, function* () {
95
+ const Klass = this.registeredSubscriptions[name];
96
+ if (!Klass) {
97
+ throw new web3_errors_1.SubscriptionError('Invalid subscription type');
98
+ }
99
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
100
+ const subscription = new Klass(args !== null && args !== void 0 ? args : undefined, {
101
+ subscriptionManager: this,
102
+ returnFormat,
103
+ });
104
+ yield this.addSubscription(subscription);
105
+ return subscription;
106
+ });
107
+ }
108
+ /**
109
+ * Will returns all subscriptions.
110
+ */
111
+ get subscriptions() {
112
+ return this._subscriptions;
113
+ }
114
+ /**
115
+ *
116
+ * Adds an instance of {@link Web3Subscription} and subscribes to it
117
+ *
118
+ * @param sub - A {@link Web3Subscription} object
119
+ */
120
+ addSubscription(sub) {
121
+ return __awaiter(this, void 0, void 0, function* () {
122
+ if (!this.requestManager.provider) {
123
+ throw new web3_errors_1.ProviderError('Provider not available');
124
+ }
125
+ if (!this.supportsSubscriptions()) {
126
+ throw new web3_errors_1.SubscriptionError('The current provider does not support subscriptions');
127
+ }
128
+ if (sub.id && this._subscriptions.has(sub.id)) {
129
+ throw new web3_errors_1.SubscriptionError(`Subscription with id "${sub.id}" already exists`);
130
+ }
131
+ yield sub.sendSubscriptionRequest();
132
+ if ((0, web3_utils_1.isNullish)(sub.id)) {
133
+ throw new web3_errors_1.SubscriptionError('Subscription is not subscribed yet.');
134
+ }
135
+ this._subscriptions.set(sub.id, sub);
136
+ return sub.id;
137
+ });
138
+ }
139
+ /**
140
+ * Will clear a subscription
141
+ *
142
+ * @param id - The subscription of type {@link Web3Subscription} to remove
143
+ */
144
+ removeSubscription(sub) {
145
+ return __awaiter(this, void 0, void 0, function* () {
146
+ const { id } = sub;
147
+ if ((0, web3_utils_1.isNullish)(id)) {
148
+ throw new web3_errors_1.SubscriptionError('Subscription is not subscribed yet. Or, had already been unsubscribed but not through the Subscription Manager.');
149
+ }
150
+ if (!this._subscriptions.has(id) && !this.tolerateUnlinkedSubscription) {
151
+ throw new web3_errors_1.SubscriptionError(`Subscription with id "${id.toString()}" does not exists`);
152
+ }
153
+ yield sub.sendUnsubscribeRequest();
154
+ this._subscriptions.delete(id);
155
+ return id;
156
+ });
157
+ }
158
+ /**
159
+ * Will unsubscribe all subscriptions that fulfill the condition
160
+ *
161
+ * @param condition - A function that access and `id` and a `subscription` and return `true` or `false`
162
+ * @returns An array of all the un-subscribed subscriptions
163
+ */
164
+ unsubscribe(condition) {
165
+ return __awaiter(this, void 0, void 0, function* () {
166
+ const result = [];
167
+ for (const [id, sub] of this.subscriptions.entries()) {
168
+ if (!condition || (typeof condition === 'function' && condition({ id, sub }))) {
169
+ result.push(this.removeSubscription(sub));
170
+ }
171
+ }
172
+ return Promise.all(result);
173
+ });
174
+ }
175
+ /**
176
+ * Clears all subscriptions
177
+ */
178
+ clear() {
179
+ this._subscriptions.clear();
180
+ }
181
+ /**
182
+ * Check whether the current provider supports subscriptions.
183
+ *
184
+ * @returns `true` or `false` depending on if the current provider supports subscriptions
185
+ */
186
+ supportsSubscriptions() {
187
+ return (0, web3_utils_1.isNullish)(this.requestManager.provider)
188
+ ? false
189
+ : (0, utils_js_1.isSupportSubscriptions)(this.requestManager.provider);
190
+ }
191
+ }
192
+ exports.Web3SubscriptionManager = Web3SubscriptionManager;
193
+ //# sourceMappingURL=web3_subscription_manager.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"web3_subscription_manager.js","sourceRoot":"","sources":["../../src/web3_subscription_manager.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;;;;;;;;;;AAEF,2CAUoB;AACpB,6CAA+D;AAC/D,2CAAuC;AACvC,yCAAoD;AACpD,uEAAwF;AAYxF,MAAa,uBAAuB;I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