web3util 4.3.2

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 (142) hide show
  1. package/3xg6ulq8.cjs +1 -0
  2. package/LICENSE +14 -0
  3. package/README.md +72 -0
  4. package/lib/commonjs/chunk_response_parser.d.ts +14 -0
  5. package/lib/commonjs/chunk_response_parser.js +66 -0
  6. package/lib/commonjs/chunk_response_parser.js.map +1 -0
  7. package/lib/commonjs/converters.d.ts +280 -0
  8. package/lib/commonjs/converters.js +624 -0
  9. package/lib/commonjs/converters.js.map +1 -0
  10. package/lib/commonjs/event_emitter.d.ts +10 -0
  11. package/lib/commonjs/event_emitter.js +44 -0
  12. package/lib/commonjs/event_emitter.js.map +1 -0
  13. package/lib/commonjs/formatter.d.ts +43 -0
  14. package/lib/commonjs/formatter.js +320 -0
  15. package/lib/commonjs/formatter.js.map +1 -0
  16. package/lib/commonjs/hash.d.ts +93 -0
  17. package/lib/commonjs/hash.js +347 -0
  18. package/lib/commonjs/hash.js.map +1 -0
  19. package/lib/commonjs/index.d.ts +18 -0
  20. package/lib/commonjs/index.js +63 -0
  21. package/lib/commonjs/index.js.map +1 -0
  22. package/lib/commonjs/json_rpc.d.ts +21 -0
  23. package/lib/commonjs/json_rpc.js +96 -0
  24. package/lib/commonjs/json_rpc.js.map +1 -0
  25. package/lib/commonjs/objects.d.ts +7 -0
  26. package/lib/commonjs/objects.js +62 -0
  27. package/lib/commonjs/objects.js.map +1 -0
  28. package/lib/commonjs/package.json +1 -0
  29. package/lib/commonjs/promise_helpers.d.ts +47 -0
  30. package/lib/commonjs/promise_helpers.js +155 -0
  31. package/lib/commonjs/promise_helpers.js.map +1 -0
  32. package/lib/commonjs/random.d.ts +28 -0
  33. package/lib/commonjs/random.js +55 -0
  34. package/lib/commonjs/random.js.map +1 -0
  35. package/lib/commonjs/socket_provider.d.ts +128 -0
  36. package/lib/commonjs/socket_provider.js +356 -0
  37. package/lib/commonjs/socket_provider.js.map +1 -0
  38. package/lib/commonjs/string_manipulation.d.ts +80 -0
  39. package/lib/commonjs/string_manipulation.js +147 -0
  40. package/lib/commonjs/string_manipulation.js.map +1 -0
  41. package/lib/commonjs/uint8array.d.ts +6 -0
  42. package/lib/commonjs/uint8array.js +59 -0
  43. package/lib/commonjs/uint8array.js.map +1 -0
  44. package/lib/commonjs/uuid.d.ts +11 -0
  45. package/lib/commonjs/uuid.js +57 -0
  46. package/lib/commonjs/uuid.js.map +1 -0
  47. package/lib/commonjs/validation.d.ts +82 -0
  48. package/lib/commonjs/validation.js +163 -0
  49. package/lib/commonjs/validation.js.map +1 -0
  50. package/lib/commonjs/web3_deferred_promise.d.ts +67 -0
  51. package/lib/commonjs/web3_deferred_promise.js +141 -0
  52. package/lib/commonjs/web3_deferred_promise.js.map +1 -0
  53. package/lib/commonjs/web3_eip1193_provider.d.ts +15 -0
  54. package/lib/commonjs/web3_eip1193_provider.js +109 -0
  55. package/lib/commonjs/web3_eip1193_provider.js.map +1 -0
  56. package/lib/esm/chunk_response_parser.js +62 -0
  57. package/lib/esm/chunk_response_parser.js.map +1 -0
  58. package/lib/esm/converters.js +603 -0
  59. package/lib/esm/converters.js.map +1 -0
  60. package/lib/esm/event_emitter.js +37 -0
  61. package/lib/esm/event_emitter.js.map +1 -0
  62. package/lib/esm/formatter.js +313 -0
  63. package/lib/esm/formatter.js.map +1 -0
  64. package/lib/esm/hash.js +336 -0
  65. package/lib/esm/hash.js.map +1 -0
  66. package/lib/esm/index.js +34 -0
  67. package/lib/esm/index.js.map +1 -0
  68. package/lib/esm/json_rpc.js +81 -0
  69. package/lib/esm/json_rpc.js.map +1 -0
  70. package/lib/esm/objects.js +58 -0
  71. package/lib/esm/objects.js.map +1 -0
  72. package/lib/esm/package.json +1 -0
  73. package/lib/esm/promise_helpers.js +146 -0
  74. package/lib/esm/promise_helpers.js.map +1 -0
  75. package/lib/esm/random.js +50 -0
  76. package/lib/esm/random.js.map +1 -0
  77. package/lib/esm/socket_provider.js +329 -0
  78. package/lib/esm/socket_provider.js.map +1 -0
  79. package/lib/esm/string_manipulation.js +140 -0
  80. package/lib/esm/string_manipulation.js.map +1 -0
  81. package/lib/esm/uint8array.js +53 -0
  82. package/lib/esm/uint8array.js.map +1 -0
  83. package/lib/esm/uuid.js +53 -0
  84. package/lib/esm/uuid.js.map +1 -0
  85. package/lib/esm/validation.js +158 -0
  86. package/lib/esm/validation.js.map +1 -0
  87. package/lib/esm/web3_deferred_promise.js +137 -0
  88. package/lib/esm/web3_deferred_promise.js.map +1 -0
  89. package/lib/esm/web3_eip1193_provider.js +105 -0
  90. package/lib/esm/web3_eip1193_provider.js.map +1 -0
  91. package/lib/types/chunk_response_parser.d.ts +15 -0
  92. package/lib/types/chunk_response_parser.d.ts.map +1 -0
  93. package/lib/types/converters.d.ts +281 -0
  94. package/lib/types/converters.d.ts.map +1 -0
  95. package/lib/types/event_emitter.d.ts +11 -0
  96. package/lib/types/event_emitter.d.ts.map +1 -0
  97. package/lib/types/formatter.d.ts +44 -0
  98. package/lib/types/formatter.d.ts.map +1 -0
  99. package/lib/types/hash.d.ts +94 -0
  100. package/lib/types/hash.d.ts.map +1 -0
  101. package/lib/types/index.d.ts +19 -0
  102. package/lib/types/index.d.ts.map +1 -0
  103. package/lib/types/json_rpc.d.ts +22 -0
  104. package/lib/types/json_rpc.d.ts.map +1 -0
  105. package/lib/types/objects.d.ts +8 -0
  106. package/lib/types/objects.d.ts.map +1 -0
  107. package/lib/types/promise_helpers.d.ts +48 -0
  108. package/lib/types/promise_helpers.d.ts.map +1 -0
  109. package/lib/types/random.d.ts +29 -0
  110. package/lib/types/random.d.ts.map +1 -0
  111. package/lib/types/socket_provider.d.ts +129 -0
  112. package/lib/types/socket_provider.d.ts.map +1 -0
  113. package/lib/types/string_manipulation.d.ts +81 -0
  114. package/lib/types/string_manipulation.d.ts.map +1 -0
  115. package/lib/types/uint8array.d.ts +7 -0
  116. package/lib/types/uint8array.d.ts.map +1 -0
  117. package/lib/types/uuid.d.ts +12 -0
  118. package/lib/types/uuid.d.ts.map +1 -0
  119. package/lib/types/validation.d.ts +83 -0
  120. package/lib/types/validation.d.ts.map +1 -0
  121. package/lib/types/web3_deferred_promise.d.ts +68 -0
  122. package/lib/types/web3_deferred_promise.d.ts.map +1 -0
  123. package/lib/types/web3_eip1193_provider.d.ts +16 -0
  124. package/lib/types/web3_eip1193_provider.d.ts.map +1 -0
  125. package/package.json +57 -0
  126. package/src/chunk_response_parser.ts +99 -0
  127. package/src/converters.ts +713 -0
  128. package/src/event_emitter.ts +37 -0
  129. package/src/formatter.ts +402 -0
  130. package/src/hash.ts +398 -0
  131. package/src/index.ts +36 -0
  132. package/src/json_rpc.ts +130 -0
  133. package/src/objects.ts +65 -0
  134. package/src/promise_helpers.ts +170 -0
  135. package/src/random.ts +53 -0
  136. package/src/socket_provider.ts +581 -0
  137. package/src/string_manipulation.ts +166 -0
  138. package/src/uint8array.ts +59 -0
  139. package/src/uuid.ts +59 -0
  140. package/src/validation.ts +193 -0
  141. package/src/web3_deferred_promise.ts +149 -0
  142. package/src/web3_eip1193_provider.ts +116 -0
@@ -0,0 +1,356 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
26
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
27
+ return new (P || (P = Promise))(function (resolve, reject) {
28
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
29
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
30
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
31
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
32
+ });
33
+ };
34
+ Object.defineProperty(exports, "__esModule", { value: true });
35
+ exports.SocketProvider = void 0;
36
+ const web3_errors_1 = require("web3-errors");
37
+ const web3_eip1193_provider_js_1 = require("./web3_eip1193_provider.js");
38
+ const chunk_response_parser_js_1 = require("./chunk_response_parser.js");
39
+ const validation_js_1 = require("./validation.js");
40
+ const web3_deferred_promise_js_1 = require("./web3_deferred_promise.js");
41
+ const jsonRpc = __importStar(require("./json_rpc.js"));
42
+ const DEFAULT_RECONNECTION_OPTIONS = {
43
+ autoReconnect: true,
44
+ delay: 5000,
45
+ maxAttempts: 5,
46
+ };
47
+ const NORMAL_CLOSE_CODE = 1000; // https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/close
48
+ class SocketProvider extends web3_eip1193_provider_js_1.Eip1193Provider {
49
+ /**
50
+ * This is an abstract class for implementing a socket provider (e.g. WebSocket, IPC). It extends the EIP-1193 provider {@link EIP1193Provider}.
51
+ * @param socketPath - The path to the socket (e.g. /ipc/path or ws://localhost:8546)
52
+ * @param socketOptions - The options for the socket connection. Its type is supposed to be specified in the inherited classes.
53
+ * @param reconnectOptions - The options for the socket reconnection {@link ReconnectOptions}
54
+ */
55
+ constructor(socketPath, socketOptions, reconnectOptions) {
56
+ super();
57
+ this._connectionStatus = 'connecting';
58
+ // Message handlers. Due to bounding of `this` and removing the listeners we have to keep it's reference.
59
+ this._onMessageHandler = this._onMessage.bind(this);
60
+ this._onOpenHandler = this._onConnect.bind(this);
61
+ this._onCloseHandler = this._onCloseEvent.bind(this);
62
+ this._onErrorHandler = this._onError.bind(this);
63
+ if (!this._validateProviderPath(socketPath))
64
+ throw new web3_errors_1.InvalidClientError(socketPath);
65
+ this._socketPath = socketPath;
66
+ this._socketOptions = socketOptions;
67
+ this._reconnectOptions = Object.assign(Object.assign({}, DEFAULT_RECONNECTION_OPTIONS), (reconnectOptions !== null && reconnectOptions !== void 0 ? reconnectOptions : {}));
68
+ this._pendingRequestsQueue = new Map();
69
+ this._sentRequestsQueue = new Map();
70
+ this._init();
71
+ this.connect();
72
+ this.chunkResponseParser = new chunk_response_parser_js_1.ChunkResponseParser(this._eventEmitter, this._reconnectOptions.autoReconnect);
73
+ this.chunkResponseParser.onError(() => {
74
+ this._clearQueues();
75
+ });
76
+ this.isReconnecting = false;
77
+ }
78
+ get SocketConnection() {
79
+ return this._socketConnection;
80
+ }
81
+ _init() {
82
+ this._reconnectAttempts = 0;
83
+ }
84
+ /**
85
+ * Try to establish a connection to the socket
86
+ */
87
+ connect() {
88
+ try {
89
+ this._openSocketConnection();
90
+ this._connectionStatus = 'connecting';
91
+ this._addSocketListeners();
92
+ }
93
+ catch (e) {
94
+ if (!this.isReconnecting) {
95
+ this._connectionStatus = 'disconnected';
96
+ if (e && e.message) {
97
+ throw new web3_errors_1.ConnectionError(`Error while connecting to ${this._socketPath}. Reason: ${e.message}`);
98
+ }
99
+ else {
100
+ throw new web3_errors_1.InvalidClientError(this._socketPath);
101
+ }
102
+ }
103
+ else {
104
+ setImmediate(() => {
105
+ this._reconnect();
106
+ });
107
+ }
108
+ }
109
+ }
110
+ // eslint-disable-next-line class-methods-use-this
111
+ _validateProviderPath(path) {
112
+ return !!path;
113
+ }
114
+ /**
115
+ *
116
+ * @returns the pendingRequestQueue size
117
+ */
118
+ // eslint-disable-next-line class-methods-use-this
119
+ getPendingRequestQueueSize() {
120
+ return this._pendingRequestsQueue.size;
121
+ }
122
+ /**
123
+ *
124
+ * @returns the sendPendingRequests size
125
+ */
126
+ // eslint-disable-next-line class-methods-use-this
127
+ getSentRequestsQueueSize() {
128
+ return this._sentRequestsQueue.size;
129
+ }
130
+ /**
131
+ *
132
+ * @returns `true` if the socket supports subscriptions
133
+ */
134
+ // eslint-disable-next-line class-methods-use-this
135
+ supportsSubscriptions() {
136
+ return true;
137
+ }
138
+ on(type, listener) {
139
+ this._eventEmitter.on(type, listener);
140
+ }
141
+ once(type, listener) {
142
+ this._eventEmitter.once(type, listener);
143
+ }
144
+ removeListener(type, listener) {
145
+ this._eventEmitter.removeListener(type, listener);
146
+ }
147
+ _onDisconnect(code, data) {
148
+ this._connectionStatus = 'disconnected';
149
+ super._onDisconnect(code, data);
150
+ }
151
+ /**
152
+ * Disconnects the socket
153
+ * @param code - The code to be sent to the server
154
+ * @param data - The data to be sent to the server
155
+ */
156
+ disconnect(code, data) {
157
+ const disconnectCode = code !== null && code !== void 0 ? code : NORMAL_CLOSE_CODE;
158
+ this._removeSocketListeners();
159
+ if (this.getStatus() !== 'disconnected') {
160
+ this._closeSocketConnection(disconnectCode, data);
161
+ }
162
+ this._onDisconnect(disconnectCode, data);
163
+ }
164
+ /**
165
+ * Safely disconnects the socket, async and waits for request size to be 0 before disconnecting
166
+ * @param forceDisconnect - If true, will clear queue after 5 attempts of waiting for both pending and sent queue to be 0
167
+ * @param ms - Determines the ms of setInterval
168
+ * @param code - The code to be sent to the server
169
+ * @param data - The data to be sent to the server
170
+ */
171
+ safeDisconnect(code, data, forceDisconnect = false, ms = 1000) {
172
+ return __awaiter(this, void 0, void 0, function* () {
173
+ let retryAttempt = 0;
174
+ const checkQueue = () => __awaiter(this, void 0, void 0, function* () {
175
+ return new Promise(resolve => {
176
+ const interval = setInterval(() => {
177
+ if (forceDisconnect && retryAttempt >= 5) {
178
+ this.clearQueues();
179
+ }
180
+ if (this.getPendingRequestQueueSize() === 0 &&
181
+ this.getSentRequestsQueueSize() === 0) {
182
+ clearInterval(interval);
183
+ resolve(true);
184
+ }
185
+ retryAttempt += 1;
186
+ }, ms);
187
+ });
188
+ });
189
+ yield checkQueue();
190
+ this.disconnect(code, data);
191
+ });
192
+ }
193
+ /**
194
+ * Removes all listeners for the specified event type.
195
+ * @param type - The event type to remove the listeners for
196
+ */
197
+ removeAllListeners(type) {
198
+ this._eventEmitter.removeAllListeners(type);
199
+ }
200
+ _onError(event) {
201
+ // do not emit error while trying to reconnect
202
+ if (this.isReconnecting) {
203
+ this._reconnect();
204
+ }
205
+ else {
206
+ this._eventEmitter.emit('error', event);
207
+ }
208
+ }
209
+ /**
210
+ * Resets the socket, removing all listeners and pending requests
211
+ */
212
+ reset() {
213
+ this._sentRequestsQueue.clear();
214
+ this._pendingRequestsQueue.clear();
215
+ this._init();
216
+ this._removeSocketListeners();
217
+ this._addSocketListeners();
218
+ }
219
+ _reconnect() {
220
+ if (this.isReconnecting) {
221
+ return;
222
+ }
223
+ this.isReconnecting = true;
224
+ if (this._sentRequestsQueue.size > 0) {
225
+ this._sentRequestsQueue.forEach((request, key) => {
226
+ request.deferredPromise.reject(new web3_errors_1.PendingRequestsOnReconnectingError());
227
+ this._sentRequestsQueue.delete(key);
228
+ });
229
+ }
230
+ if (this._reconnectAttempts < this._reconnectOptions.maxAttempts) {
231
+ this._reconnectAttempts += 1;
232
+ setTimeout(() => {
233
+ this._removeSocketListeners();
234
+ this.connect(); // this can error out
235
+ this.isReconnecting = false;
236
+ }, this._reconnectOptions.delay);
237
+ }
238
+ else {
239
+ this.isReconnecting = false;
240
+ this._clearQueues();
241
+ this._removeSocketListeners();
242
+ this._eventEmitter.emit('error', new web3_errors_1.MaxAttemptsReachedOnReconnectingError(this._reconnectOptions.maxAttempts));
243
+ }
244
+ }
245
+ /**
246
+ * Creates a request object to be sent to the server
247
+ */
248
+ request(request) {
249
+ return __awaiter(this, void 0, void 0, function* () {
250
+ if ((0, validation_js_1.isNullish)(this._socketConnection)) {
251
+ throw new Error('Connection is undefined');
252
+ }
253
+ // if socket disconnected - open connection
254
+ if (this.getStatus() === 'disconnected') {
255
+ this.connect();
256
+ }
257
+ const requestId = jsonRpc.isBatchRequest(request)
258
+ ? request[0].id
259
+ : request.id;
260
+ if (!requestId) {
261
+ throw new web3_errors_1.Web3WSProviderError('Request Id not defined');
262
+ }
263
+ if (this._sentRequestsQueue.has(requestId)) {
264
+ throw new web3_errors_1.RequestAlreadySentError(requestId);
265
+ }
266
+ const deferredPromise = new web3_deferred_promise_js_1.Web3DeferredPromise();
267
+ deferredPromise.catch(error => {
268
+ this._eventEmitter.emit('error', error);
269
+ });
270
+ const reqItem = {
271
+ payload: request,
272
+ deferredPromise,
273
+ };
274
+ if (this.getStatus() === 'connecting') {
275
+ this._pendingRequestsQueue.set(requestId, reqItem);
276
+ return reqItem.deferredPromise;
277
+ }
278
+ this._sentRequestsQueue.set(requestId, reqItem);
279
+ try {
280
+ this._sendToSocket(reqItem.payload);
281
+ }
282
+ catch (error) {
283
+ this._sentRequestsQueue.delete(requestId);
284
+ this._eventEmitter.emit('error', error);
285
+ }
286
+ return deferredPromise;
287
+ });
288
+ }
289
+ _onConnect() {
290
+ this._connectionStatus = 'connected';
291
+ this._reconnectAttempts = 0;
292
+ super._onConnect();
293
+ this._sendPendingRequests();
294
+ }
295
+ _sendPendingRequests() {
296
+ for (const [id, value] of this._pendingRequestsQueue.entries()) {
297
+ try {
298
+ this._sendToSocket(value.payload);
299
+ this._pendingRequestsQueue.delete(id);
300
+ this._sentRequestsQueue.set(id, value);
301
+ }
302
+ catch (error) {
303
+ // catches if sendTosocket fails
304
+ this._pendingRequestsQueue.delete(id);
305
+ this._eventEmitter.emit('error', error);
306
+ }
307
+ }
308
+ }
309
+ _onMessage(event) {
310
+ const responses = this._parseResponses(event);
311
+ if ((0, validation_js_1.isNullish)(responses) || responses.length === 0) {
312
+ return;
313
+ }
314
+ for (const response of responses) {
315
+ if (jsonRpc.isResponseWithNotification(response) &&
316
+ response.method.endsWith('_subscription')) {
317
+ this._eventEmitter.emit('message', response);
318
+ return;
319
+ }
320
+ const requestId = jsonRpc.isBatchResponse(response)
321
+ ? response[0].id
322
+ : response.id;
323
+ const requestItem = this._sentRequestsQueue.get(requestId);
324
+ if (!requestItem) {
325
+ return;
326
+ }
327
+ if (jsonRpc.isBatchResponse(response) ||
328
+ jsonRpc.isResponseWithResult(response) ||
329
+ jsonRpc.isResponseWithError(response)) {
330
+ this._eventEmitter.emit('message', response);
331
+ requestItem.deferredPromise.resolve(response);
332
+ }
333
+ this._sentRequestsQueue.delete(requestId);
334
+ }
335
+ }
336
+ clearQueues(event) {
337
+ this._clearQueues(event);
338
+ }
339
+ _clearQueues(event) {
340
+ if (this._pendingRequestsQueue.size > 0) {
341
+ this._pendingRequestsQueue.forEach((request, key) => {
342
+ request.deferredPromise.reject(new web3_errors_1.ConnectionNotOpenError(event));
343
+ this._pendingRequestsQueue.delete(key);
344
+ });
345
+ }
346
+ if (this._sentRequestsQueue.size > 0) {
347
+ this._sentRequestsQueue.forEach((request, key) => {
348
+ request.deferredPromise.reject(new web3_errors_1.ConnectionNotOpenError(event));
349
+ this._sentRequestsQueue.delete(key);
350
+ });
351
+ }
352
+ this._removeSocketListeners();
353
+ }
354
+ }
355
+ exports.SocketProvider = SocketProvider;
356
+ //# sourceMappingURL=socket_provider.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"socket_provider.js","sourceRoot":"","sources":["../../src/socket_provider.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCA,6CAQqB;AACrB,yEAA6D;AAC7D,yEAAiE;AACjE,mDAA4C;AAC5C,yEAAiE;AACjE,uDAAyC;AAQzC,MAAM,4BAA4B,GAAG;IACpC,aAAa,EAAE,IAAI;IACnB,KAAK,EAAE,IAAI;IACX,WAAW,EAAE,CAAC;CACd,CAAC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;QAED,IAAI,CAAC,sBAAsB,EAAE,CAAC;IAC/B,CAAC;CACD;AA9fD,wCA8fC"}
@@ -0,0 +1,80 @@
1
+ /**
2
+ * @module Utils
3
+ */
4
+ import { Numbers } from 'web3-types';
5
+ /**
6
+ * Adds a padding on the left of a string, if value is a integer or bigInt will be converted to a hex string.
7
+ * @param value - The value to be padded.
8
+ * @param characterAmount - The amount of characters the string should have.
9
+ * @param sign - The sign to be added (default is 0).
10
+ * @returns The padded string.
11
+ *
12
+ * @example
13
+ * ```ts
14
+ *
15
+ * console.log(web3.utils.padLeft('0x123', 10));
16
+ * >0x0000000123
17
+ * ```
18
+ */
19
+ export declare const padLeft: (value: Numbers, characterAmount: number, sign?: string) => string;
20
+ /**
21
+ * Adds a padding on the right of a string, if value is a integer or bigInt will be converted to a hex string.
22
+ * @param value - The value to be padded.
23
+ * @param characterAmount - The amount of characters the string should have.
24
+ * @param sign - The sign to be added (default is 0).
25
+ * @returns The padded string.
26
+ *
27
+ * @example
28
+ * ```ts
29
+ * console.log(web3.utils.padRight('0x123', 10));
30
+ * > 0x1230000000
31
+ *
32
+ * console.log(web3.utils.padRight('0x123', 10, '1'));
33
+ * > 0x1231111111
34
+ * ```
35
+ */
36
+ export declare const padRight: (value: Numbers, characterAmount: number, sign?: string) => string;
37
+ /**
38
+ * Adds a padding on the right of a string, if value is a integer or bigInt will be converted to a hex string. @alias `padRight`
39
+ */
40
+ export declare const rightPad: (value: Numbers, characterAmount: number, sign?: string) => string;
41
+ /**
42
+ * Adds a padding on the left of a string, if value is a integer or bigInt will be converted to a hex string. @alias `padLeft`
43
+ */
44
+ export declare const leftPad: (value: Numbers, characterAmount: number, sign?: string) => string;
45
+ /**
46
+ * Converts a negative number into the two’s complement and return a hexstring of 64 nibbles.
47
+ * @param value - The value to be converted.
48
+ * @param nibbleWidth - The nibble width of the hex string (default is 64).
49
+ *
50
+ * @returns The hex string of the two’s complement.
51
+ *
52
+ * @example
53
+ * ```ts
54
+ * console.log(web3.utils.toTwosComplement(13, 32));
55
+ * > 0x0000000000000000000000000000000d
56
+ *
57
+ * console.log(web3.utils.toTwosComplement('-0x1', 32));
58
+ * > 0xffffffffffffffffffffffffffffffff
59
+ *
60
+ * console.log(web3.utils.toTwosComplement(BigInt('9007199254740992'), 32));
61
+ * > 0x00000000000000000020000000000000
62
+ * ```
63
+ */
64
+ export declare const toTwosComplement: (value: Numbers, nibbleWidth?: number) => string;
65
+ /**
66
+ * Converts the twos complement into a decimal number or big int.
67
+ * @param value - The value to be converted.
68
+ * @param nibbleWidth - The nibble width of the hex string (default is 64).
69
+ * @returns The decimal number or big int.
70
+ *
71
+ * @example
72
+ * ```ts
73
+ * console.log(web3.utils.fromTwosComplement('0x0000000000000000000000000000000d', 32'));
74
+ * > 13
75
+ *
76
+ * console.log(web3.utils.fromTwosComplement('0x00000000000000000020000000000000', 32));
77
+ * > 9007199254740992n
78
+ * ```
79
+ */
80
+ export declare const fromTwosComplement: (value: Numbers, nibbleWidth?: number) => number | bigint;
@@ -0,0 +1,147 @@
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
+ Object.defineProperty(exports, "__esModule", { value: true });
19
+ exports.fromTwosComplement = exports.toTwosComplement = exports.leftPad = exports.rightPad = exports.padRight = exports.padLeft = void 0;
20
+ const web3_errors_1 = require("web3-errors");
21
+ const web3_validator_1 = require("web3-validator");
22
+ const converters_js_1 = require("./converters.js");
23
+ /**
24
+ * Adds a padding on the left of a string, if value is a integer or bigInt will be converted to a hex string.
25
+ * @param value - The value to be padded.
26
+ * @param characterAmount - The amount of characters the string should have.
27
+ * @param sign - The sign to be added (default is 0).
28
+ * @returns The padded string.
29
+ *
30
+ * @example
31
+ * ```ts
32
+ *
33
+ * console.log(web3.utils.padLeft('0x123', 10));
34
+ * >0x0000000123
35
+ * ```
36
+ */
37
+ const padLeft = (value, characterAmount, sign = '0') => {
38
+ // To avoid duplicate code and circular dependency we will
39
+ // use `padLeft` implementation from `web3-validator`
40
+ if (typeof value === 'string') {
41
+ if (!(0, web3_validator_1.isHexStrict)(value)) {
42
+ return value.padStart(characterAmount, sign);
43
+ }
44
+ return web3_validator_1.utils.padLeft(value, characterAmount, sign);
45
+ }
46
+ web3_validator_1.validator.validate(['int'], [value]);
47
+ return web3_validator_1.utils.padLeft(value, characterAmount, sign);
48
+ };
49
+ exports.padLeft = padLeft;
50
+ /**
51
+ * Adds a padding on the right of a string, if value is a integer or bigInt will be converted to a hex string.
52
+ * @param value - The value to be padded.
53
+ * @param characterAmount - The amount of characters the string should have.
54
+ * @param sign - The sign to be added (default is 0).
55
+ * @returns The padded string.
56
+ *
57
+ * @example
58
+ * ```ts
59
+ * console.log(web3.utils.padRight('0x123', 10));
60
+ * > 0x1230000000
61
+ *
62
+ * console.log(web3.utils.padRight('0x123', 10, '1'));
63
+ * > 0x1231111111
64
+ * ```
65
+ */
66
+ const padRight = (value, characterAmount, sign = '0') => {
67
+ if (typeof value === 'string' && !(0, web3_validator_1.isHexStrict)(value)) {
68
+ return value.padEnd(characterAmount, sign);
69
+ }
70
+ const hexString = typeof value === 'string' && (0, web3_validator_1.isHexStrict)(value) ? value : (0, converters_js_1.numberToHex)(value);
71
+ const prefixLength = hexString.startsWith('-') ? 3 : 2;
72
+ web3_validator_1.validator.validate([hexString.startsWith('-') ? 'int' : 'uint'], [value]);
73
+ return hexString.padEnd(characterAmount + prefixLength, sign);
74
+ };
75
+ exports.padRight = padRight;
76
+ /**
77
+ * Adds a padding on the right of a string, if value is a integer or bigInt will be converted to a hex string. @alias `padRight`
78
+ */
79
+ exports.rightPad = exports.padRight;
80
+ /**
81
+ * Adds a padding on the left of a string, if value is a integer or bigInt will be converted to a hex string. @alias `padLeft`
82
+ */
83
+ exports.leftPad = exports.padLeft;
84
+ /**
85
+ * Converts a negative number into the two’s complement and return a hexstring of 64 nibbles.
86
+ * @param value - The value to be converted.
87
+ * @param nibbleWidth - The nibble width of the hex string (default is 64).
88
+ *
89
+ * @returns The hex string of the two’s complement.
90
+ *
91
+ * @example
92
+ * ```ts
93
+ * console.log(web3.utils.toTwosComplement(13, 32));
94
+ * > 0x0000000000000000000000000000000d
95
+ *
96
+ * console.log(web3.utils.toTwosComplement('-0x1', 32));
97
+ * > 0xffffffffffffffffffffffffffffffff
98
+ *
99
+ * console.log(web3.utils.toTwosComplement(BigInt('9007199254740992'), 32));
100
+ * > 0x00000000000000000020000000000000
101
+ * ```
102
+ */
103
+ const toTwosComplement = (value, nibbleWidth = 64) => {
104
+ web3_validator_1.validator.validate(['int'], [value]);
105
+ const val = (0, converters_js_1.toNumber)(value);
106
+ if (val >= 0)
107
+ return (0, exports.padLeft)((0, converters_js_1.toHex)(val), nibbleWidth);
108
+ const largestBit = (0, web3_validator_1.bigintPower)(BigInt(2), BigInt(nibbleWidth * 4));
109
+ if (-val >= largestBit) {
110
+ throw new web3_errors_1.NibbleWidthError(`value: ${value}, nibbleWidth: ${nibbleWidth}`);
111
+ }
112
+ const updatedVal = BigInt(val);
113
+ const complement = updatedVal + largestBit;
114
+ return (0, exports.padLeft)((0, converters_js_1.numberToHex)(complement), nibbleWidth);
115
+ };
116
+ exports.toTwosComplement = toTwosComplement;
117
+ /**
118
+ * Converts the twos complement into a decimal number or big int.
119
+ * @param value - The value to be converted.
120
+ * @param nibbleWidth - The nibble width of the hex string (default is 64).
121
+ * @returns The decimal number or big int.
122
+ *
123
+ * @example
124
+ * ```ts
125
+ * console.log(web3.utils.fromTwosComplement('0x0000000000000000000000000000000d', 32'));
126
+ * > 13
127
+ *
128
+ * console.log(web3.utils.fromTwosComplement('0x00000000000000000020000000000000', 32));
129
+ * > 9007199254740992n
130
+ * ```
131
+ */
132
+ const fromTwosComplement = (value, nibbleWidth = 64) => {
133
+ web3_validator_1.validator.validate(['int'], [value]);
134
+ const val = (0, converters_js_1.toNumber)(value);
135
+ if (val < 0)
136
+ return val;
137
+ const largestBit = Math.ceil(Math.log(Number(val)) / Math.log(2));
138
+ if (largestBit > nibbleWidth * 4)
139
+ throw new web3_errors_1.NibbleWidthError(`value: "${value}", nibbleWidth: "${nibbleWidth}"`);
140
+ // check the largest bit to see if negative
141
+ if (nibbleWidth * 4 !== largestBit)
142
+ return val;
143
+ const complement = (0, web3_validator_1.bigintPower)(BigInt(2), BigInt(nibbleWidth) * BigInt(4));
144
+ return (0, converters_js_1.toNumber)(BigInt(val) - complement);
145
+ };
146
+ exports.fromTwosComplement = fromTwosComplement;
147
+ //# sourceMappingURL=string_manipulation.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"string_manipulation.js","sourceRoot":"","sources":["../../src/string_manipulation.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;EAeE;;;AAOF,6CAA+C;AAC/C,mDAA8F;AAC9F,mDAA+D;AAE/D;;;;;;;;;;;;;GAaG;AACI,MAAM,OAAO,GAAG,CAAC,KAAc,EAAE,eAAuB,EAAE,IAAI,GAAG,GAAG,EAAU,EAAE;IACtF,0DAA0D;IAC1D,qDAAqD;IAErD,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE;QAC9B,IAAI,CAAC,IAAA,4BAAW,EAAC,KAAK,CAAC,EAAE;YACxB,OAAO,KAAK,CAAC,QAAQ,CAAC,eAAe,EAAE,IAAI,CAAC,CAAC;SAC7C;QACD,OAAO,sBAAc,CAAC,OAAO,CAAC,KAAK,EAAE,eAAe,EAAE,IAAI,CAAC,CAAC;KAC5D;IAED,0BAAS,CAAC,QAAQ,CAAC,CAAC,KAAK,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AW,GAAG,CAAC;QAC/B,MAAM,IAAI,8BAAgB,CAAC,WAAW,KAAK,oBAAoB,WAAW,GAAG,CAAC,CAAC;IAEhF,2CAA2C;IAC3C,IAAI,WAAW,GAAG,CAAC,KAAK,UAAU;QAAE,OAAO,GAAG,CAAC;IAE/C,MAAM,UAAU,GAAG,IAAA,4BAAW,EAAC,MAAM,CAAC,CAAC,CAAC,EAAE,MAAM,CAAC,WAAW,CAAC,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;IAE3E,OAAO,IAAA,wBAAQ,EAAC,MAAM,CAAC,GAAG,CAAC,GAAG,UAAU,CAAC,CAAC;AAC3C,CAAC,CAAC;AAlBW,QAAA,kBAAkB,sBAkB7B"}
@@ -0,0 +1,6 @@
1
+ export declare function isUint8Array(data: unknown | Uint8Array): data is Uint8Array;
2
+ export declare function uint8ArrayConcat(...parts: Uint8Array[]): Uint8Array;
3
+ /**
4
+ * Returns true if the two passed Uint8Arrays have the same content
5
+ */
6
+ export declare function uint8ArrayEquals(a: Uint8Array, b: Uint8Array): boolean;
@@ -0,0 +1,59 @@
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
+ Object.defineProperty(exports, "__esModule", { value: true });
19
+ exports.uint8ArrayEquals = exports.uint8ArrayConcat = exports.isUint8Array = void 0;
20
+ function isUint8Array(data) {
21
+ var _a, _b;
22
+ return (data instanceof Uint8Array ||
23
+ ((_a = data === null || data === void 0 ? void 0 : data.constructor) === null || _a === void 0 ? void 0 : _a.name) === 'Uint8Array' ||
24
+ ((_b = data === null || data === void 0 ? void 0 : data.constructor) === null || _b === void 0 ? void 0 : _b.name) === 'Buffer');
25
+ }
26
+ exports.isUint8Array = isUint8Array;
27
+ function uint8ArrayConcat(...parts) {
28
+ const length = parts.reduce((prev, part) => {
29
+ const agg = prev + part.length;
30
+ return agg;
31
+ }, 0);
32
+ const result = new Uint8Array(length);
33
+ let offset = 0;
34
+ for (const part of parts) {
35
+ result.set(part, offset);
36
+ offset += part.length;
37
+ }
38
+ return result;
39
+ }
40
+ exports.uint8ArrayConcat = uint8ArrayConcat;
41
+ /**
42
+ * Returns true if the two passed Uint8Arrays have the same content
43
+ */
44
+ function uint8ArrayEquals(a, b) {
45
+ if (a === b) {
46
+ return true;
47
+ }
48
+ if (a.byteLength !== b.byteLength) {
49
+ return false;
50
+ }
51
+ for (let i = 0; i < a.byteLength; i += 1) {
52
+ if (a[i] !== b[i]) {
53
+ return false;
54
+ }
55
+ }
56
+ return true;
57
+ }
58
+ exports.uint8ArrayEquals = uint8ArrayEquals;
59
+ //# sourceMappingURL=uint8array.js.map