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

Add few utility functions like: numberToBytes, concat(Bytes[]) and contractFunctionId #7067

Open
@Muhammad-Altabba

Description

@Muhammad-Altabba

Consider adding helper functions similar to the following:

export const numberToBytes = (number: web3Types.Numbers) =>
	web3Utils.hexToBytes(web3Utils.numberToHex(number));

export function concat(bytes: web3Types.Bytes[]): string {
	return '0x' + bytes.map(d => web3Utils.toHex(d).substring(2)).join('');
}

export function contractFunctionId(value: string): string {
	return web3Utils.keccak256(web3Utils.utf8ToBytes(value));
}

// Check first account.recover?
export function recoverSignerAddress(
	messageOrData: string | web3Types.Eip712TypedData,
	signature: string | EthereumSignature,
) {
	let message;
	if (typeof messageOrData !== 'string') {
		message = web3Abi.getEncodedEip712Data(messageOrData, true);
	} else {
		message = messageOrData;
	}

	const r = web3Accounts.toUint8Array(
		(signature as EthereumSignature).r ?? (signature as string).slice(0, 66),
	);
	const s = web3Accounts.toUint8Array(
		(signature as EthereumSignature).s ?? `0x${(signature as string).slice(66, 130)}`,
	);
	const v = BigInt(
		(signature as EthereumSignature).v ??
			web3Utils.hexToNumber(`0x${(signature as string).slice(130, 132)}`),
	);

	const recoveredPublicKey = web3Utils.bytesToHex(
		web3Accounts.ecrecover(web3Accounts.toUint8Array(message), v, r, s),
	);

	const recoveredAddress = `0x${web3Utils.keccak256(web3Utils.bytesToHex(recoveredPublicKey)).slice(-40)}`;
	return recoveredAddress;
}

For context, check https://github.com/web3/web3-plugin-zksync/blob/c55f043b4c39550422038a004f1e24f236632bb4/src/utils.ts#L242C2-L291C4 and https://github.com/zksync-sdk/zksync-ethers/blob/main/src/utils.ts

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions