CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-web3-utils

Collection of utility functions used in web3.js for Ethereum dApp development

Pending
Overview
Eval results
Files

random-validation.mddocs/

Random Generation and Validation

Secure random value generation and validation utilities for cryptographic applications and data validation. These functions provide essential security and validation capabilities.

Capabilities

Random Value Generation

Random Bytes

/**
 * Returns random byte array of given size
 * Uses cryptographically secure random number generation
 * @param size - Number of bytes to generate
 * @returns Cryptographically secure random Uint8Array
 */
function randomBytes(size: number): Uint8Array;

Random Hex

/**
 * Returns random hex string of given byte size
 * Uses cryptographically secure random number generation
 * @param byteSize - Number of bytes for the random value
 * @returns Hex string prefixed with "0x"
 */
function randomHex(byteSize: number): string;

UUID Generation

Version 4 UUID

/**
 * Generates version 4 (random) UUID
 * Follows RFC 4122 specification for random UUIDs
 * @returns UUID string in standard format (xxxxxxxx-xxxx-4xxx-xxxx-xxxxxxxxxxxx)
 */
function uuidV4(): string;

Data Validation

Type Guards

/**
 * Type guard for Uint8Array (including Node.js Buffer)
 * Checks if data is Uint8Array or Buffer instance
 * @param data - Data to check
 * @returns true if data is Uint8Array or Buffer
 */
function isUint8Array(data: unknown | Uint8Array): data is Uint8Array;

Deprecated Validation Functions

Note: Most validation functions are deprecated and will be removed in the next release. Use the web3-validator package instead.

/**
 * @deprecated Will be removed in next release. Use web3-validator package instead.
 * Checks if value is strict hex string
 */
const isHexStrict: (value: unknown) => boolean;

/**
 * @deprecated Will be removed in next release. Use web3-validator package instead.
 * Checks if value is hex, number or bigint
 */
const isHex: (value: unknown) => boolean;

/**
 * @deprecated Will be removed in next release. Use web3-validator package instead.
 * Validates address checksum
 */
const checkAddressCheckSum: (address: string) => boolean;

/**
 * @deprecated Will be removed in next release. Use web3-validator package instead.
 * Checks if value is valid Ethereum address
 */
const isAddress: (address: unknown) => boolean;

/**
 * @deprecated Will be removed in next release. Use web3-validator package instead.
 * Checks if value is bloom filter
 */
const isBloom: (bloom: unknown) => boolean;

/**
 * @deprecated Will be removed in next release. Use web3-validator package instead.
 * Checks if value is in bloom filter
 */
const isInBloom: (bloom: string, value: string) => boolean;

/**
 * @deprecated Will be removed in next release. Use web3-validator package instead.
 * Checks if user Ethereum address is in bloom filter
 */
const isUserEthereumAddressInBloom: (bloom: string, address: string) => boolean;

/**
 * @deprecated Will be removed in next release. Use web3-validator package instead.
 * Checks if contract address is in bloom filter
 */
const isContractAddressInBloom: (bloom: string, address: string) => boolean;

/**
 * @deprecated Will be removed in next release. Use web3-validator package instead.
 * Checks if value is valid topic
 */
const isTopic: (topic: unknown) => boolean;

/**
 * @deprecated Will be removed in next release. Use web3-validator package instead.
 * Checks if topic is in bloom filter
 */
const isTopicInBloom: (bloom: string, topic: string) => boolean;

Active Validation Functions

Block Number Comparison

/**
 * Compares block numbers/tags, returns comparison result
 * Handles both numeric block numbers and special tags like 'latest', 'pending'
 * @param blockA - First block number or tag
 * @param blockB - Second block number or tag
 * @returns -1 if blockA < blockB, 0 if equal, 1 if blockA > blockB
 */
function compareBlockNumbers(blockA: BlockNumberOrTag, blockB: BlockNumberOrTag): number;

Type Guards

/**
 * Type guard for contract initialization options
 * @param options - Object to check
 * @returns true if options match ContractInitOptions interface
 */
function isContractInitOptions(options: unknown): options is ContractInitOptions;

/**
 * Re-exported from web3-validator
 * Checks if value is null or undefined
 */
const isNullish: (value: unknown) => value is null | undefined;

Usage Examples

Random Value Generation

import { randomBytes, randomHex, uuidV4 } from "web3-utils";

// Generate random bytes for cryptographic use
const entropy = randomBytes(32); // 32 bytes of entropy
console.log(entropy); // Uint8Array(32) [45, 123, 78, ...]

// Generate random hex for nonces, salts, etc.
const nonce = randomHex(8); // 8 bytes = 16 hex chars + "0x"
console.log(nonce); // "0x1a2b3c4d5e6f7890"

const salt = randomHex(16); // 16 bytes for salt
console.log(salt); // "0x1a2b3c4d5e6f78901a2b3c4d5e6f7890"

// Generate UUID for unique identifiers
const requestId = uuidV4();
console.log(requestId); // "123e4567-e89b-12d3-a456-426614174000"

const sessionId = uuidV4();
console.log(sessionId); // "987fcdeb-51d2-43a1-b456-426614174123"

Cryptographic Applications

import { randomBytes, randomHex } from "web3-utils";

// Generate private key (32 bytes)
function generatePrivateKey(): Uint8Array {
  return randomBytes(32);
}

// Generate random IV for encryption
function generateIV(): Uint8Array {
  return randomBytes(16); // 128-bit IV
}

// Generate random challenge for authentication
function generateChallenge(): string {
  return randomHex(32); // 32 bytes challenge
}

// Generate random seed for deterministic operations
function generateSeed(): Uint8Array {
  return randomBytes(64); // 512-bit seed
}

// Usage
const privateKey = generatePrivateKey();
const iv = generateIV();
const challenge = generateChallenge();
const seed = generateSeed();

console.log('Private key:', Array.from(privateKey, b => b.toString(16).padStart(2, '0')).join(''));
console.log('IV:', Array.from(iv, b => b.toString(16).padStart(2, '0')).join(''));
console.log('Challenge:', challenge);
console.log('Seed length:', seed.length);

Data Validation

import { isUint8Array, compareBlockNumbers, isContractInitOptions } from "web3-utils";

// Type checking for binary data
function processData(data: unknown) {
  if (isUint8Array(data)) {
    console.log('Processing binary data of length:', data.length);
    // Safe to use Uint8Array methods
    return data.slice(0, 10);
  } else {
    throw new Error('Expected Uint8Array');
  }
}

// Block number comparison
function isNewerBlock(blockA: string | number, blockB: string | number): boolean {
  return compareBlockNumbers(blockA, blockB) > 0;
}

// Usage examples
const buffer = Buffer.from([1, 2, 3, 4]);
const uint8 = new Uint8Array([5, 6, 7, 8]);
const array = [9, 10, 11, 12];

console.log(isUint8Array(buffer)); // true (Buffer extends Uint8Array)
console.log(isUint8Array(uint8)); // true
console.log(isUint8Array(array)); // false

// Block comparisons
console.log(compareBlockNumbers(100, 200)); // -1 (100 < 200)
console.log(compareBlockNumbers(200, 100)); // 1 (200 > 100)
console.log(compareBlockNumbers(150, 150)); // 0 (equal)
console.log(compareBlockNumbers('latest', 100)); // 1 ('latest' > any number)
console.log(compareBlockNumbers('pending', 'latest')); // 1 ('pending' > 'latest')

// Contract options validation
const options1 = { gasLimit: 21000, gasPrice: '20000000000' };
const options2 = { invalidOption: true };

if (isContractInitOptions(options1)) {
  console.log('Valid contract options');
} else {
  console.log('Invalid contract options');
}

Security Best Practices

import { randomBytes, randomHex, uuidV4 } from "web3-utils";

class SecurityUtils {
  // Generate secure session token
  static generateSessionToken(): string {
    return randomHex(32); // 256-bit token
  }

  // Generate secure API key
  static generateApiKey(): string {
    const randomPart = randomHex(16);
    const timestamp = Date.now().toString(16);
    return `${randomPart.slice(2)}${timestamp}`; // Remove "0x" prefix
  }

  // Generate secure nonce for replay protection
  static generateNonce(): string {
    return randomBytes(8).reduce((acc, byte) => acc + byte.toString(16).padStart(2, '0'), '');
  }

  // Generate correlation ID for distributed tracing
  static generateCorrelationId(): string {
    return uuidV4();
  }

  // Generate secure random password
  static generatePassword(length: number = 32): string {
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*';
    const randomData = randomBytes(length);
    
    return Array.from(randomData, byte => chars[byte % chars.length]).join('');
  }
}

// Usage
const sessionToken = SecurityUtils.generateSessionToken();
const apiKey = SecurityUtils.generateApiKey();
const nonce = SecurityUtils.generateNonce();
const correlationId = SecurityUtils.generateCorrelationId();
const password = SecurityUtils.generatePassword(16);

console.log('Session token:', sessionToken);
console.log('API key:', apiKey);
console.log('Nonce:', nonce);
console.log('Correlation ID:', correlationId);
console.log('Password:', password);

Random Data for Testing

import { randomBytes, randomHex, uuidV4 } from "web3-utils";

class TestDataGenerator {
  // Generate random Ethereum address format (not a real address)
  static generateMockAddress(): string {
    return '0x' + randomBytes(20).reduce((acc, byte) => 
      acc + byte.toString(16).padStart(2, '0'), ''
    );
  }

  // Generate random transaction hash format
  static generateMockTxHash(): string {
    return randomHex(32);
  }

  // Generate random block hash format
  static generateMockBlockHash(): string {
    return randomHex(32);
  }

  // Generate test data with random UUIDs
  static generateTestRecord() {
    return {
      id: uuidV4(),
      address: this.generateMockAddress(),
      txHash: this.generateMockTxHash(),
      blockHash: this.generateMockBlockHash(),
      timestamp: Date.now(),
      nonce: randomHex(4)
    };
  }
}

// Generate test data
const testRecords = Array.from({ length: 5 }, () => 
  TestDataGenerator.generateTestRecord()
);

console.log('Test records:', testRecords);

Migration Guide

For applications currently using the deprecated validation functions, migrate to the web3-validator package:

// Old (deprecated)
import { isHex, isAddress } from "web3-utils";

// New (recommended)
import { isHex, isAddress } from "web3-validator";

// The API is the same, just import from web3-validator instead
const hexValue = "0x1234";
const address = "0x742E4C5b469F50A4a8b399D4915C1fc93d15651B";

console.log(isHex(hexValue)); // true
console.log(isAddress(address)); // true

Types

// Block number and tag types
type BlockNumberOrTag = number | bigint | string;
type BlockTags = 'latest' | 'earliest' | 'pending' | 'safe' | 'finalized';

// Contract initialization options
interface ContractInitOptions {
  gasLimit?: number;
  gasPrice?: string;
  maxFeePerGas?: string;
  maxPriorityFeePerGas?: string;
  nonce?: number;
  // ... other contract options
}

Install with Tessl CLI

npx tessl i tessl/npm-web3-utils

docs

conversion.md

data-manipulation.md

events.md

hashing.md

index.md

json-rpc.md

promises.md

providers.md

random-validation.md

tile.json