|
| 1 | +import { toHex, fromHex } from '@interchainjs/utils'; |
| 2 | +import { keccak_256 } from '@noble/hashes/sha3'; |
| 3 | + |
| 4 | +/** |
| 5 | + * EIP-55 checksum implementation |
| 6 | + */ |
| 7 | +function toEIP55Checksum(address: string): string { |
| 8 | + const addr = address.toLowerCase().replace('0x', ''); |
| 9 | + const hash = toHex(keccak_256(Buffer.from(addr, 'utf8'))); |
| 10 | + |
| 11 | + let checksumAddress = '0x'; |
| 12 | + for (let i = 0; i < addr.length; i++) { |
| 13 | + if (parseInt(hash[i], 16) >= 8) { |
| 14 | + checksumAddress += addr[i].toUpperCase(); |
| 15 | + } else { |
| 16 | + checksumAddress += addr[i]; |
| 17 | + } |
| 18 | + } |
| 19 | + return checksumAddress; |
| 20 | +} |
| 21 | + |
| 22 | +/** |
| 23 | + * Validate Ethereum address format and checksum |
| 24 | + */ |
| 25 | +export function isValidEthereumAddress(address: string): boolean { |
| 26 | + // Check basic format - accept both 0x and 0X prefixes |
| 27 | + if ((!address.startsWith('0x') && !address.startsWith('0X')) || address.length !== 42) { |
| 28 | + return false; |
| 29 | + } |
| 30 | + |
| 31 | + // Check if it's a valid hex string |
| 32 | + const hex = address.slice(2); |
| 33 | + if (!/^[a-fA-F0-9]{40}$/.test(hex)) { |
| 34 | + return false; |
| 35 | + } |
| 36 | + |
| 37 | + // If it's all lowercase or all uppercase, it's valid (no checksum) |
| 38 | + if (hex === hex.toLowerCase() || hex === hex.toUpperCase()) { |
| 39 | + return true; |
| 40 | + } |
| 41 | + |
| 42 | + // If it has mixed case, validate the checksum |
| 43 | + try { |
| 44 | + // Normalize to lowercase 0x prefix for checksum validation |
| 45 | + const normalizedAddress = '0x' + hex.toLowerCase(); |
| 46 | + const expectedChecksum = toEIP55Checksum(normalizedAddress); |
| 47 | + return '0x' + hex === expectedChecksum; |
| 48 | + } catch { |
| 49 | + return false; |
| 50 | + } |
| 51 | +} |
| 52 | + |
| 53 | +/** |
| 54 | + * Convert an Ethereum address to its checksummed version |
| 55 | + */ |
| 56 | +export function toChecksumAddress(address: string): string { |
| 57 | + if (!address.startsWith('0x') || address.length !== 42) { |
| 58 | + throw new Error('Invalid Ethereum address format'); |
| 59 | + } |
| 60 | + |
| 61 | + const hex = address.slice(2); |
| 62 | + if (!/^[a-fA-F0-9]{40}$/.test(hex)) { |
| 63 | + throw new Error('Invalid Ethereum address format'); |
| 64 | + } |
| 65 | + |
| 66 | + return toEIP55Checksum(address.toLowerCase()); |
| 67 | +} |
0 commit comments