Thanks to visit codestin.com
Credit goes to github.com

Skip to content
This repository was archived by the owner on Mar 5, 2025. It is now read-only.

Commit f76d955

Browse files
author
Dan Forbes
authored
Merge branch '4.x' into chore/docs/formatting
2 parents b76cd7f + 8f62749 commit f76d955

25 files changed

+959
-211
lines changed

.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,3 +47,5 @@ packages/web3/.in3/
4747
benchmark-data.txt
4848

4949
.eslintcache
50+
51+
.history

docs/.snyk

Lines changed: 0 additions & 36 deletions
This file was deleted.

packages/web3-utils/src/converters.ts

Lines changed: 23 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,8 @@ export const ethUnitMap = {
7979
tether: BigInt('1000000000000000000000000000000'),
8080
};
8181

82-
const PrecisionLossWarning = 'Warning: Using type `number` with values that are large or contain many decimals may cause loss of precision, it is recommended to use type `string` or `BigInt` when using conversion methods';
82+
const PrecisionLossWarning =
83+
'Warning: Using type `number` with values that are large or contain many decimals may cause loss of precision, it is recommended to use type `string` or `BigInt` when using conversion methods';
8384

8485
export type EtherUnits = keyof typeof ethUnitMap;
8586
/**
@@ -366,7 +367,7 @@ export const toHex = (
366367
return returnType ? 'bigint' : numberToHex(value);
367368
}
368369

369-
if(isUint8Array(value)) {
370+
if (isUint8Array(value)) {
370371
return returnType ? 'bytes' : bytesToHex(value);
371372
}
372373

@@ -386,6 +387,15 @@ export const toHex = (
386387
return returnType ? 'bytes' : `0x${value}`;
387388
}
388389
if (isHex(value) && !isInt(value) && isUInt(value)) {
390+
// This condition seems problematic because meeting
391+
// both conditions `!isInt(value) && isUInt(value)` should be impossible.
392+
// But a value pass for those conditions: "101611154195520776335741463917853444671577865378275924493376429267637792638729"
393+
// Note that according to the docs: it is supposed to be treated as a string (https://docs.web3js.org/guides/web3_upgrade_guide/x/web3_utils_migration_guide#conversion-to-hex)
394+
// In short, the strange is that isInt(value) is false but isUInt(value) is true for the value above.
395+
// TODO: isUInt(value) should be investigated.
396+
397+
// However, if `toHex('101611154195520776335741463917853444671577865378275924493376429267637792638729', true)` is called, it will return `true`.
398+
// But, if `toHex('101611154195520776335741463917853444671577865378275924493376429267637792638729')` is called, it will throw inside `numberToHex`.
389399
return returnType ? 'uint' : numberToHex(value);
390400
}
391401

@@ -419,14 +429,14 @@ export const toHex = (
419429
*/
420430
export const toNumber = (value: Numbers): number | bigint => {
421431
if (typeof value === 'number') {
422-
if (value > 1e+20) {
423-
console.warn(PrecisionLossWarning)
424-
// JavaScript converts numbers >= 10^21 to scientific notation when coerced to strings,
425-
// leading to potential parsing errors and incorrect representations.
426-
// For instance, String(10000000000000000000000) yields '1e+22'.
427-
// Using BigInt prevents this
428-
return BigInt(value);
429-
}
432+
if (value > 1e20) {
433+
console.warn(PrecisionLossWarning);
434+
// JavaScript converts numbers >= 10^21 to scientific notation when coerced to strings,
435+
// leading to potential parsing errors and incorrect representations.
436+
// For instance, String(10000000000000000000000) yields '1e+22'.
437+
// Using BigInt prevents this
438+
return BigInt(value);
439+
}
430440
return value;
431441
}
432442

@@ -506,10 +516,9 @@ export const fromWei = (number: Numbers, unit: EtherUnits | number): string => {
506516
if (unit < 0 || !Number.isInteger(unit)) {
507517
throw new InvalidIntegerError(unit);
508518
}
509-
denomination = bigintPower(BigInt(10),BigInt(unit));
519+
denomination = bigintPower(BigInt(10), BigInt(unit));
510520
}
511521

512-
513522
// value in wei would always be integer
514523
// 13456789, 1234
515524
const value = String(toNumber(number));
@@ -575,8 +584,8 @@ export const toWei = (number: Numbers, unit: EtherUnits | number): string => {
575584
if (unit < 0 || !Number.isInteger(unit)) {
576585
throw new InvalidIntegerError(unit);
577586
}
578-
579-
denomination = bigintPower(BigInt(10),BigInt(unit));
587+
588+
denomination = bigintPower(BigInt(10), BigInt(unit));
580589
}
581590

582591
let parsedNumber = number;

packages/web3-utils/src/formatter.ts

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -57,10 +57,8 @@ const findSchemaByDataPath = (
5757

5858
for (const dataPart of dataPath) {
5959
if (result.oneOf && previousDataPath) {
60-
const path = oneOfPath.find(function (element: [string, number]) {
61-
return (this as unknown as string) === element[0];
62-
}, previousDataPath ?? '');
63-
60+
const currentDataPath = previousDataPath;
61+
const path = oneOfPath.find(([key]) => key === currentDataPath);
6462
if (path && path[0] === previousDataPath) {
6563
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
6664
result = result.oneOf[path[1]];
@@ -75,10 +73,6 @@ const findSchemaByDataPath = (
7573
} else if (result.items && (result.items as JsonSchema).properties) {
7674
const node = (result.items as JsonSchema).properties as Record<string, JsonSchema>;
7775

78-
if (!node) {
79-
return undefined;
80-
}
81-
8276
result = node[dataPart];
8377
} else if (result.items && isObject(result.items)) {
8478
result = result.items;
@@ -307,7 +301,7 @@ export const convert = (
307301

308302
// If value is an object, recurse into it
309303
if (isObject(value)) {
310-
convert(value, schema, dataPath, format);
304+
convert(value, schema, dataPath, format, oneOfPath);
311305
dataPath.pop();
312306
continue;
313307
}

packages/web3-utils/src/hash.ts

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -17,25 +17,25 @@ along with web3.js. If not, see <http://www.gnu.org/licenses/>.
1717

1818
/**
1919
* This package provides utility functions for Ethereum dapps and other web3.js packages.
20-
*
20+
*
2121
* For using Utils functions, first install Web3 package using `npm i web3` or `yarn add web3`.
22-
* After that, Web3 Utils functions will be available as mentioned below.
22+
* After that, Web3 Utils functions will be available as mentioned below.
2323
* ```ts
2424
* import { Web3 } from 'web3';
2525
* const web3 = new Web3();
26-
*
26+
*
2727
* const value = web3.utils.fromWei("1", "ether")
28-
*
28+
*
2929
* ```
30-
*
30+
*
3131
* For using individual package install `web3-utils` package using `npm i web3-utils` or `yarn add web3-utils` and only import required functions.
32-
* This is more efficient approach for building lightweight applications.
32+
* This is more efficient approach for building lightweight applications.
3333
* ```ts
3434
* import { fromWei, soliditySha3Raw } from 'web3-utils';
35-
*
35+
*
3636
* console.log(fromWei("1", "ether"));
3737
* console.log(soliditySha3Raw({ type: "string", value: "helloworld" }))
38-
*
38+
*
3939
* ```
4040
* @module Utils
4141
*/
@@ -172,7 +172,6 @@ const getType = (arg: Sha3Input): [string, EncodingTypes] => {
172172
if (Array.isArray(arg)) {
173173
throw new Error('Autodetection of array types is not supported.');
174174
}
175-
176175
let type;
177176
let value;
178177
// if type is given

packages/web3-utils/src/json_rpc.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,7 @@ let requestIdSeed: number | undefined;
9999
/**
100100
* Optionally use to make the jsonrpc `id` start from a specific number.
101101
* Without calling this function, the `id` will be filled with a Uuid.
102-
* But after this being called with a number, the `id` will be a number staring from the provided `start` variable.
102+
* But after this being called with a number, the `id` will be a number starting from the provided `start` variable.
103103
* However, if `undefined` was passed to this function, the `id` will be a Uuid again.
104104
* @param start - a number to start incrementing from.
105105
* Or `undefined` to use a new Uuid (this is the default behavior)

packages/web3-utils/src/promise_helpers.ts

Lines changed: 19 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@ import { isNullish } from 'web3-validator';
2020
export type Timer = ReturnType<typeof setInterval>;
2121
export type Timeout = ReturnType<typeof setTimeout>;
2222

23-
2423
/**
2524
* An alternative to the node function `isPromise` that exists in `util/types` because it is not available on the browser.
2625
* @param object - to check if it is a `Promise`
@@ -74,7 +73,6 @@ export async function waitWithTimeout<T>(
7473
return result;
7574
}
7675

77-
7876
/**
7977
* Repeatedly calls an async function with a given interval until the result of the function is defined (not undefined or null),
8078
* or until a timeout is reached. It returns promise and intervalId.
@@ -85,25 +83,27 @@ export function pollTillDefinedAndReturnIntervalId<T>(
8583
func: AsyncFunction<T>,
8684
interval: number,
8785
): [Promise<Exclude<T, undefined>>, Timer] {
88-
8986
let intervalId: Timer | undefined;
9087
const polledRes = new Promise<Exclude<T, undefined>>((resolve, reject) => {
91-
intervalId = setInterval(function intervalCallbackFunc(){
92-
(async () => {
93-
try {
94-
const res = await waitWithTimeout(func, interval);
95-
96-
if (!isNullish(res)) {
88+
intervalId = setInterval(
89+
(function intervalCallbackFunc() {
90+
(async () => {
91+
try {
92+
const res = await waitWithTimeout(func, interval);
93+
94+
if (!isNullish(res)) {
95+
clearInterval(intervalId);
96+
resolve(res as unknown as Exclude<T, undefined>);
97+
}
98+
} catch (error) {
9799
clearInterval(intervalId);
98-
resolve(res as unknown as Exclude<T, undefined>);
100+
reject(error);
99101
}
100-
} catch (error) {
101-
clearInterval(intervalId);
102-
reject(error);
103-
}
104-
})() as unknown;
105-
return intervalCallbackFunc;}() // this will immediate invoke first call
106-
, interval);
102+
})() as unknown;
103+
return intervalCallbackFunc;
104+
})(), // this will immediate invoke first call
105+
interval,
106+
);
107107
});
108108

109109
return [polledRes as unknown as Promise<Exclude<T, undefined>>, intervalId!];
@@ -113,7 +113,7 @@ export function pollTillDefinedAndReturnIntervalId<T>(
113113
* Repeatedly calls an async function with a given interval until the result of the function is defined (not undefined or null),
114114
* or until a timeout is reached.
115115
* pollTillDefinedAndReturnIntervalId() function should be used instead of pollTillDefined if you need IntervalId in result.
116-
* This function will be deprecated in next major release so use pollTillDefinedAndReturnIntervalId().
116+
* This function will be deprecated in next major release so use pollTillDefinedAndReturnIntervalId().
117117
* @param func - The function to call.
118118
* @param interval - The interval in milliseconds.
119119
*/
@@ -146,7 +146,7 @@ export function rejectIfTimeout(timeout: number, error: Error): [Timer, Promise<
146146
/**
147147
* Sets an interval that repeatedly executes the given cond function with the specified interval between each call.
148148
* If the condition is met, the interval is cleared and a Promise that rejects with the returned value is returned.
149-
* @param cond - The function/confition to call.
149+
* @param cond - The function/condition to call.
150150
* @param interval - The interval in milliseconds.
151151
* @returns - an array with the interval ID and the Promise.
152152
*/
@@ -168,4 +168,3 @@ export function rejectIfConditionAtInterval<T>(
168168
});
169169
return [intervalId!, rejectIfCondition];
170170
}
171-

packages/web3-utils/src/socket_provider.ts

Lines changed: 16 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -187,13 +187,13 @@ export abstract class SocketProvider<
187187
protected _validateProviderPath(path: string): boolean {
188188
return !!path;
189189
}
190-
190+
191191
/**
192192
*
193193
* @returns the pendingRequestQueue size
194194
*/
195195
// eslint-disable-next-line class-methods-use-this
196-
public getPendingRequestQueueSize() {
196+
public getPendingRequestQueueSize() {
197197
return this._pendingRequestsQueue.size;
198198
}
199199

@@ -350,32 +350,34 @@ export abstract class SocketProvider<
350350

351351
/**
352352
* Safely disconnects the socket, async and waits for request size to be 0 before disconnecting
353-
* @param forceDisconnect - If true, will clear queue after 5 attempts of waiting for both pending and sent queue to be 0
353+
* @param forceDisconnect - If true, will clear queue after 5 attempts of waiting for both pending and sent queue to be 0
354354
* @param ms - Determines the ms of setInterval
355355
* @param code - The code to be sent to the server
356356
* @param data - The data to be sent to the server
357357
*/
358-
public async safeDisconnect(code?: number, data?: string, forceDisconnect = false,ms = 1000) {
358+
public async safeDisconnect(code?: number, data?: string, forceDisconnect = false, ms = 1000) {
359359
let retryAttempt = 0;
360-
const checkQueue = async () =>
360+
const checkQueue = async () =>
361361
new Promise(resolve => {
362362
const interval = setInterval(() => {
363-
if (forceDisconnect && retryAttempt === 5) {
363+
if (forceDisconnect && retryAttempt >= 5) {
364364
this.clearQueues();
365365
}
366-
if (this.getPendingRequestQueueSize() === 0 && this.getSentRequestsQueueSize() === 0) {
366+
if (
367+
this.getPendingRequestQueueSize() === 0 &&
368+
this.getSentRequestsQueueSize() === 0
369+
) {
367370
clearInterval(interval);
368371
resolve(true);
369372
}
370-
retryAttempt+=1;
371-
}, ms)
372-
})
373-
373+
retryAttempt += 1;
374+
}, ms);
375+
});
376+
374377
await checkQueue();
375378
this.disconnect(code, data);
376379
}
377380

378-
379381
/**
380382
* Removes all listeners for the specified event type.
381383
* @param type - The event type to remove the listeners for
@@ -512,7 +514,7 @@ export abstract class SocketProvider<
512514
if (isNullish(responses) || responses.length === 0) {
513515
return;
514516
}
515-
517+
516518
for (const response of responses) {
517519
if (
518520
jsonRpc.isResponseWithNotification(response as JsonRpcNotification) &&
@@ -544,7 +546,7 @@ export abstract class SocketProvider<
544546
this._sentRequestsQueue.delete(requestId);
545547
}
546548
}
547-
549+
548550
public clearQueues(event?: ConnectionEvent) {
549551
this._clearQueues(event);
550552
}

0 commit comments

Comments
 (0)