Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix an issue with detecting Uint8Array #6486

Merged
Show file tree
Hide file tree
Changes from 18 commits
Commits
Show all changes
41 commits
Select commit Hold shift + click to select a range
4fb927f
implement `EventEmitter` compatible with browsers
Muhammad-Altabba Aug 31, 2023
0e9ce5d
some fixes at InBrowserEventEmitter
Muhammad-Altabba Sep 4, 2023
28ba5dc
some renaming inside event_emitter.ts
Muhammad-Altabba Sep 4, 2023
87b2b86
Merge branch '4.x' into 6371-uncaught-typeerror-class-extends-value-u…
Muhammad-Altabba Sep 7, 2023
ae40b19
Merge branch '4.x' into 6371-uncaught-typeerror-class-extends-value-u…
Muhammad-Altabba Sep 17, 2023
8913307
Merge branch '4.x' into 6371-uncaught-typeerror-class-extends-value-u…
Muhammad-Altabba Sep 19, 2023
6d0bd23
Merge branch '4.x' into 6371-uncaught-typeerror-class-extends-value-u…
Muhammad-Altabba Sep 26, 2023
cb742c7
Merge branch '4.x' into 6371-uncaught-typeerror-class-extends-value-u…
Muhammad-Altabba Oct 4, 2023
3766eec
Merge branch '4.x' into 6371-uncaught-typeerror-class-extends-value-u…
Muhammad-Altabba Oct 4, 2023
195463d
export EventEmitter as a class
Muhammad-Altabba Oct 4, 2023
1808058
add unit tests for EventEmitter
Muhammad-Altabba Oct 4, 2023
607f4b2
disable lint rule in a file and update yarn.lock
Muhammad-Altabba Oct 4, 2023
4c8bc1b
apply fixes and add tests for EventEmitter
Muhammad-Altabba Oct 4, 2023
e4d7317
configure `EventEmitter` test to run inside `jsdom`
Muhammad-Altabba Oct 4, 2023
9b0ba51
Merge branch '4.x' into 6371-uncaught-typeerror-class-extends-value-u…
Muhammad-Altabba Oct 4, 2023
1eed66d
fix issue with detecting Uint8Array
Muhammad-Altabba Oct 6, 2023
5f195bb
prevent throwing if value is null when checking value.constructor.name
Muhammad-Altabba Oct 6, 2023
37b6617
Merge branch '6371-uncaught-typeerror-class-extends-value-undefined-i…
Muhammad-Altabba Oct 6, 2023
59e4246
Merge branch '4.x' into 6393-web3validatorerror-error-value-at-0-must…
Muhammad-Altabba Oct 9, 2023
67251b5
Merge branch '4.x' into 6393-web3validatorerror-error-value-at-0-must…
Muhammad-Altabba Oct 9, 2023
4b5d6cf
improve type checking for Uint8Array
Muhammad-Altabba Oct 9, 2023
c5a7154
remove a white space
Muhammad-Altabba Oct 9, 2023
d110b4c
Merge branch '4.x' into 6393-web3validatorerror-error-value-at-0-must…
Muhammad-Altabba Oct 11, 2023
ae588a4
Merge branch '4.x' into 6393-web3validatorerror-error-value-at-0-must…
Muhammad-Altabba Oct 16, 2023
a4ca344
Merge branch '4.x' into 6393-web3validatorerror-error-value-at-0-must…
Muhammad-Altabba Oct 17, 2023
52950f0
Merge branch '4.x' into 6393-web3validatorerror-error-value-at-0-must…
Muhammad-Altabba Oct 18, 2023
2eb3671
Merge branch '4.x' into 6393-web3validatorerror-error-value-at-0-must…
Muhammad-Altabba Oct 31, 2023
f4df5f8
Merge branch '4.x' into 6393-web3validatorerror-error-value-at-0-must…
Muhammad-Altabba Nov 13, 2023
1725b3a
Merge branch '4.x' into 6393-web3validatorerror-error-value-at-0-must…
Muhammad-Altabba Nov 20, 2023
45d7012
Merge branch '4.x' into 6393-web3validatorerror-error-value-at-0-must…
Muhammad-Altabba Dec 3, 2023
f5e3102
Merge branch '4.x' into 6393-web3validatorerror-error-value-at-0-must…
Muhammad-Altabba Dec 4, 2023
1cca075
Merge branch '4.x' into 6393-web3validatorerror-error-value-at-0-must…
Muhammad-Altabba Dec 12, 2023
55f9d94
Merge branch '4.x' into 6393-web3validatorerror-error-value-at-0-must…
Muhammad-Altabba Dec 13, 2023
ca1a402
Merge branch '4.x' into 6393-web3validatorerror-error-value-at-0-must…
Muhammad-Altabba Jan 3, 2024
992d5bf
remove a comment that was left be mistake
Muhammad-Altabba Jan 3, 2024
62c8c85
add tests for Uint8Array in jsdom
Muhammad-Altabba Jan 3, 2024
3ffad96
Merge branch '4.x' into 6393-web3validatorerror-error-value-at-0-must…
Muhammad-Altabba Jan 3, 2024
f865290
update CHANGELOG.md files
Muhammad-Altabba Jan 3, 2024
557132b
move `ensureIfUint8Array` to `web3-validator`
Muhammad-Altabba Jan 3, 2024
d2618e2
Merge branch '4.x' into 6393-web3validatorerror-error-value-at-0-must…
Muhammad-Altabba Jan 4, 2024
7ec6a95
Merge branch '4.x' into 6393-web3validatorerror-error-value-at-0-must…
Muhammad-Altabba Jan 5, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/web3-core/src/web3_event_emitter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ You should have received a copy of the GNU Lesser General Public License
along with web3.js. If not, see <http://www.gnu.org/licenses/>.
*/

import { EventEmitter } from 'events';
import { EventEmitter } from 'web3-utils';

export type Web3EventMap = Record<string, unknown>;
export type Web3EventKey<T extends Web3EventMap> = string & keyof T;
Expand Down
5 changes: 4 additions & 1 deletion packages/web3-eth-accounts/src/account.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,10 @@ export const parseAndValidatePrivateKey = (data: Bytes, ignoreLength?: boolean):
}

try {
privateKeyUint8Array = data instanceof Uint8Array ? data : bytesToUint8Array(data);
privateKeyUint8Array =
data instanceof Uint8Array || data?.constructor?.name === 'Uint8Array'
? (data as Uint8Array)
: bytesToUint8Array(data);
} catch {
throw new InvalidPrivateKeyError();
}
Expand Down
3 changes: 1 addition & 2 deletions packages/web3-eth-accounts/src/common/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,8 @@ You should have received a copy of the GNU Lesser General Public License
along with web3.js. If not, see <http://www.gnu.org/licenses/>.
*/
import pkg from 'crc-32';
import { EventEmitter } from 'events';
import { EventEmitter, bytesToHex, hexToBytes, uint8ArrayConcat } from 'web3-utils';
import type { Numbers } from 'web3-types';
import { bytesToHex, hexToBytes, uint8ArrayConcat } from 'web3-utils';
import { TypeOutput } from './types.js';
import { intToUint8Array, toType, parseGethGenesis } from './utils.js';
import goerli from './chains/goerli.js';
Expand Down
4 changes: 2 additions & 2 deletions packages/web3-eth-accounts/src/tx/transactionFactory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,8 +104,8 @@ export class TransactionFactory {
* @param txOptions - The transaction options
*/
public static fromBlockBodyData(data: Uint8Array | Uint8Array[], txOptions: TxOptions = {}) {
if (data instanceof Uint8Array) {
return this.fromSerializedData(data, txOptions);
if (data instanceof Uint8Array || data?.constructor?.name === 'Uint8Array') {
return this.fromSerializedData(data as Uint8Array, txOptions);
}
if (Array.isArray(data)) {
// It is a legacy transaction
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ You should have received a copy of the GNU Lesser General Public License
along with web3.js. If not, see <http://www.gnu.org/licenses/>.
*/

import { EventEmitter } from 'events';
import { EventEmitter } from 'web3-utils';

export default class WebSocket extends EventEmitter {
public readyState: number;
Expand Down
1 change: 1 addition & 0 deletions packages/web3-utils/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@
"eslint-config-prettier": "^8.5.0",
"eslint-plugin-import": "^2.26.0",
"jest": "^28.1.3",
"jest-environment-jsdom": "^29.7.0",
"jest-extended": "^3.0.1",
"js-sha3": "^0.8.0",
"prettier": "^2.7.1",
Expand Down
10 changes: 7 additions & 3 deletions packages/web3-utils/src/converters.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,8 +88,8 @@ export type EtherUnits = keyof typeof ethUnitMap;
export const bytesToUint8Array = (data: Bytes): Uint8Array | never => {
validator.validate(['bytes'], [data]);

if (data instanceof Uint8Array) {
return data;
if (data instanceof Uint8Array || data?.constructor?.name === 'Uint8Array') {
return data as Uint8Array;
}

if (Array.isArray(data)) {
Expand Down Expand Up @@ -585,7 +585,11 @@ export const toChecksumAddress = (address: Address): string => {

const lowerCaseAddress = address.toLowerCase().replace(/^0x/i, '');

const hash = utils.uint8ArrayToHexString(keccak256(utf8ToBytes(lowerCaseAddress)));
// calling `Uint8Array.from` because `noble-hashes` checks with `instanceof Uint8Array` that fails in some edge cases:
// https://github.com/paulmillr/noble-hashes/issues/25#issuecomment-1750106284
const hash = utils.uint8ArrayToHexString(
keccak256(Uint8Array.from(utf8ToBytes(lowerCaseAddress))),
);

if (
isNullish(hash) ||
Expand Down
128 changes: 128 additions & 0 deletions packages/web3-utils/src/event_emitter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
/*
This file is part of web3.js.

web3.js is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

web3.js is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License
along with web3.js. If not, see <http://www.gnu.org/licenses/>.
*/
/* eslint-disable max-classes-per-file */

import { EventEmitter as EventEmitterAtNode } from 'events';

// eslint-disable-next-line @typescript-eslint/no-explicit-any
type Callback = (params: any) => void | Promise<void>;

type EventTargetCallback = (params: CustomEvent) => void;

const wrapFunction =
(fn: Callback): EventTargetCallback =>
(params: CustomEvent) =>
fn(params.detail);

/**
* This class copy the behavior of Node.js EventEmitter class.
* It is used to provide the same interface for the browser environment.
*/
class EventEmitterAtBrowser extends EventTarget {
private _listeners: Record<string, [key: Callback, value: EventTargetCallback][]> = {};
private maxListeners = Number.MAX_SAFE_INTEGER;

public on(eventName: string, fn: Callback) {
this.addEventListener(eventName, fn);
return this;
}

public once(eventName: string, fn: Callback) {
const onceCallback = async (params: Callback) => {
this.off(eventName, onceCallback);
await fn(params);
};
return this.on(eventName, onceCallback);
}

public off(eventName: string, fn: Callback) {
this.removeEventListener(eventName, fn);
return this;
}

public emit(eventName: string, params: unknown) {
const event = new CustomEvent(eventName, { detail: params });
return super.dispatchEvent(event);
}

public listenerCount(eventName: string): number {
const eventListeners = this._listeners[eventName];
return eventListeners ? eventListeners.length : 0;
}

public listeners(eventName: string): Callback[] {
return this._listeners[eventName].map(value => value[0]) || [];
}

public eventNames(): string[] {
return Object.keys(this._listeners);
}

public removeAllListeners() {
Object.keys(this._listeners).forEach(event => {
this._listeners[event].forEach(
(listener: [key: Callback, value: EventTargetCallback]) => {
super.removeEventListener(event, listener[1] as EventListener);
},
);
});

this._listeners = {};
return this;
}

public setMaxListeners(maxListeners: number) {
this.maxListeners = maxListeners;
return this;
}

public getMaxListeners(): number {
return this.maxListeners;
}

public addEventListener(eventName: string, fn: Callback) {
const wrappedFn = wrapFunction(fn);
super.addEventListener(eventName, wrappedFn as EventListener);
if (!this._listeners[eventName]) {
this._listeners[eventName] = [];
}
this._listeners[eventName].push([fn, wrappedFn]);
}

public removeEventListener(eventName: string, fn: Callback) {
const eventListeners = this._listeners[eventName];
if (eventListeners) {
const index = eventListeners.findIndex(item => item[0] === fn);
if (index !== -1) {
super.removeEventListener(eventName, eventListeners[index][1] as EventListener);
eventListeners.splice(index, 1);
}
}
}
}

// eslint-disable-next-line import/no-mutable-exports
let EventEmitterType: typeof EventEmitterAtNode;
// Check if the code is running in a Node.js environment
if (typeof window === 'undefined') {
EventEmitterType = EventEmitterAtNode;
} else {
// Fallback for the browser environment
EventEmitterType = EventEmitterAtBrowser as unknown as typeof EventEmitterAtNode;
}

export class EventEmitter extends EventEmitterType {}
1 change: 1 addition & 0 deletions packages/web3-utils/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ along with web3.js. If not, see <http://www.gnu.org/licenses/>.
*/

export * from './converters.js';
export * from './event_emitter.js';
export * from './validation.js';
export * from './formatter.js';
export * from './hash.js';
Expand Down
128 changes: 128 additions & 0 deletions packages/web3-utils/test/unit/event_emitter_dom.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
/**
* @jest-environment jsdom
*/

/*
This file is part of web3.js.

web3.js is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

web3.js is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License
along with web3.js. If not, see <http://www.gnu.org/licenses/>.
*/

// this file contains the unit test for the event emitter in the DOM environment
// it is executed in the jsdom environment (see "@jest-environment jsdom" in the top comment of this file)

// ignore the following rule to allow keeping `@jest-environment jsdom` on top:
// eslint-disable-next-line header/header
import { EventEmitter } from '../../src/event_emitter';

describe('EventEmitter with DOM', () => {
let emitter: EventEmitter;

beforeEach(() => {
emitter = new EventEmitter();
});

describe('on', () => {
it('should add a listener for the specified event', () => {
const callback = jest.fn();
emitter.on('test', callback);
emitter.emit('test', 'hello');
expect(callback).toHaveBeenCalledWith('hello');
});
});

describe('once', () => {
it('should add a listener for the specified event that is only called once', () => {
const callback = jest.fn();
emitter.once('test', callback);
emitter.emit('test', 'hello');
emitter.emit('test', 'world');
expect(callback).toHaveBeenCalledTimes(1);
expect(callback).toHaveBeenCalledWith('hello');
});
});

describe('off', () => {
it('should remove a listener for the specified event', () => {
const callback = jest.fn();
emitter.on('test', callback);
emitter.off('test', callback);
emitter.emit('test', 'hello');
expect(callback).not.toHaveBeenCalled();
});
});

describe('emit', () => {
it('should call all listeners for the specified event', () => {
const callback1 = jest.fn();
const callback2 = jest.fn();
emitter.on('test', callback1);
emitter.on('test', callback2);
emitter.emit('test', 'hello');
expect(callback1).toHaveBeenCalledWith('hello');
expect(callback2).toHaveBeenCalledWith('hello');
});
});

describe('listenerCount', () => {
it('should return the number of listeners for the specified event', () => {
const callback1 = jest.fn();
const callback2 = jest.fn();
emitter.on('test', callback1);
emitter.on('test', callback2);
expect(emitter.listenerCount('test')).toBe(2);
});
});

describe('listeners', () => {
it('should return an array of listeners for the specified event', () => {
const callback1 = jest.fn();
const callback2 = jest.fn();
emitter.on('test', callback1);
emitter.on('test', callback2);
expect(emitter.listeners('test')).toEqual([callback1, callback2]);
});
});

describe('eventNames', () => {
it('should return an array of event names that have listeners', () => {
const callback1 = jest.fn();
const callback2 = jest.fn();
emitter.on('test1', callback1);
emitter.on('test2', callback2);
expect(emitter.eventNames()).toEqual(['test1', 'test2']);
});
});

describe('removeAllListeners', () => {
it('should remove all listeners for all events', () => {
const callback1 = jest.fn();
const callback2 = jest.fn();
emitter.on('test1', callback1);
emitter.on('test2', callback2);
emitter.removeAllListeners();
emitter.emit('test1', 'hello');
emitter.emit('test2', 'world');
expect(callback1).not.toHaveBeenCalled();
expect(callback2).not.toHaveBeenCalled();
});
});

describe('setMaxListeners', () => {
it('should set the maximum number of listeners for an event', () => {
emitter.setMaxListeners(2);
expect(emitter.getMaxListeners()).toBe(2);
});
});
});
Loading