Functions for validating and type-checking binary data formats commonly used in Ethereum applications.
Checks if a value can be treated as byte-like data (either a valid Bytes array or hex string).
/**
* Type guard to check if value is BytesLike (valid hex string or Bytes array)
* @param value - Value to check
* @returns True if value is BytesLike, false otherwise
*/
function isBytesLike(value: any): value is BytesLike;Usage Examples:
import { isBytesLike } from "@ethersproject/bytes";
console.log(isBytesLike("0x1234")); // true - valid hex string
console.log(isBytesLike("0x12345")); // false - odd length hex
console.log(isBytesLike([1, 2, 3, 4])); // true - valid bytes array
console.log(isBytesLike(new Uint8Array([1]))); // true - Uint8Array
console.log(isBytesLike("hello")); // false - not hex string
console.log(isBytesLike(123)); // false - not bytes-likeChecks if a value is a valid Bytes array (array-like structure containing valid byte values).
/**
* Type guard to check if value is a valid Bytes array
* @param value - Value to check
* @returns True if value is Bytes array, false otherwise
*/
function isBytes(value: any): value is Bytes;Usage Examples:
import { isBytes } from "@ethersproject/bytes";
console.log(isBytes([0, 255, 128])); // true - valid byte values
console.log(isBytes(new Uint8Array([1, 2]))); // true - Uint8Array
console.log(isBytes([256])); // false - byte value too large
console.log(isBytes([-1])); // false - negative byte value
console.log(isBytes("0x1234")); // false - string, not bytes
console.log(isBytes({ length: 2, 0: 1, 1: 2 })); // true - array-like with valid bytesChecks if a string is a valid hexadecimal string, optionally with a specific byte length.
/**
* Check if string is valid hexadecimal format
* @param value - Value to check
* @param length - Optional expected byte length (string length should be 2 + 2*length)
* @returns True if value is valid hex string, false otherwise
*/
function isHexString(value: any, length?: number): boolean;Usage Examples:
import { isHexString } from "@ethersproject/bytes";
// Basic hex string validation
console.log(isHexString("0x1234")); // true - valid hex
console.log(isHexString("0x")); // true - empty hex string
console.log(isHexString("0x12345")); // true - odd length allowed without length param
console.log(isHexString("1234")); // false - missing 0x prefix
console.log(isHexString("0xghij")); // false - invalid hex characters
// Length-specific validation
console.log(isHexString("0x1234", 2)); // true - exactly 2 bytes (4 hex chars)
console.log(isHexString("0x1234", 3)); // false - expected 3 bytes (6 hex chars)
console.log(isHexString("0x123456", 3)); // true - exactly 3 bytestype Bytes = ArrayLike<number>;
type BytesLike = Bytes | string;