Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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 AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ This file serves two audiences: agents integrating the installed npm package, an
4. Pass untrusted addresses directly to `validateAddress`. It accepts `unknown` and returns `ValidationResult`. Check `result.valid` before using an address. For rejected input, use `result.error` and `result.details?.errorCode`, not string comparisons with implementation-specific messages.
5. Validation trims outer ASCII spaces but does not return a normalized address. After successful validation of a string, use `input.trim()` for subsequent operations. Do not lowercase Base58 addresses or silently repair checksums, Unicode, missing characters, or invalid input.
6. `strict: true` requires exact EIP-55 capitalization for EVM addresses, and canonical lowercase AIP-40 representation for Aptos. Mixed-case EVM checksums and mandatory Base58Check/Bech32 checksums are always checked. Choose strict mode deliberately; do not enable it blindly for existing lowercase EVM input flows.
7. `network: 'mainnet' | 'testnet' | 'auto'` and `allowTestnet` only filter networks encoded in an address. EVM, Solana, TRON, Cosmos, Sui, Aptos, and NEAR cannot establish mainnet/testnet from address syntax. An absent `details.network` means unknown, not mainnet.
7. `network: 'mainnet' | 'testnet' | 'auto'` and `allowTestnet` only filter networks encoded in an address. Any other `network` value throws a `RangeError` before input is read, including for an empty batch or empty detection input. EVM, Solana, TRON, Cosmos, Sui, Aptos, and NEAR cannot establish mainnet/testnet from address syntax. An absent `details.network` means unknown, not mainnet.
8. `detectBlockchain` returns a chain, an array of format candidates, or `null`. Never pick the first candidate automatically for a payment. EVM chains, Sui/Aptos, and some UTXO/NEAR formats overlap. Plain NEAR names are deliberately excluded from detection.
9. Validation does not prove ownership, account existence, spendability, token compatibility, or recipient safety. Handle application-specific destination tags, memos, RPC checks, and asset/network selection separately. `allowBurnAddress` only controls the EVM all-zero address.
10. Formatting is display logic. `shortenAddress` output must never become a transaction destination. `formatAddress` does not generally validate input; EVM checksum formatting and Aptos formatting can throw on malformed input. Validate first.
Expand Down
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# Changelog

## Unreleased

- An unsupported `network` option value throws a `RangeError` from validation, batch validation, detection, and validator `validate` methods, before any input is read. Previously it reported `NETWORK_MISMATCH` for addresses that encode a network and was ignored for other chains. `undefined` and `null` still mean `auto`.

## 0.4.0

- JavaScript EVM and Cosmos constructors reject unsupported family identifiers.
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@ validateAddress(address, chain, {
```

- `strict` defaults to `false`. On EVM, `true` requires the exact EIP-55 capitalization, including the rare valid all-lowercase/all-uppercase checksums. Invalid mixed-case EVM checksums are always rejected. On Aptos, strict mode requires lowercase AIP-40 canonical representation. Other formats always verify their mandatory checksums.
- `network` defaults to `auto`. It filters networks **only when encoded in the address**, currently Bitcoin, Litecoin, Dogecoin, and Cardano. `details.network` is omitted for formats that cannot identify mainnet/testnet. Selecting a network never proves an address belongs to it.
- `network` defaults to `auto` (`undefined` and `null` also mean `auto`). Any other value than `'mainnet'`, `'testnet'`, or `'auto'` throws a `RangeError` from `validateAddress`, `validateBatch`, `detectBlockchain`, and validator `validate` methods. The option is checked before any input is read, so an empty batch or empty, blank, or unsafe input still throws. It filters networks **only when encoded in the address**, currently Bitcoin, Litecoin, Dogecoin, and Cardano. `details.network` is omitted for formats that cannot identify mainnet/testnet. Selecting a network never proves an address belongs to it.
- `allowTestnet: false` rejects identifiable testnet addresses, including when `network: 'testnet'` is also supplied. It is not an on-chain network check.
- `allowBurnAddress` defaults to `false` and controls only the EVM all-zero address. It is not a comprehensive burn-address database. Other reserved/program addresses may be syntactically valid.

Expand Down
3 changes: 3 additions & 0 deletions src/detectors/chain-detector.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import { BlockchainType, ValidationOptions, EVM_CHAINS } from '../types';
import { SUPPORTED_CHAINS, getValidator } from '../registry';
import { InputSanitizer } from '../security/sanitizer';
import { assertValidationOptions } from '../validators/base';

/** Format candidates only: never use detection as proof of a destination's chain. */
export function detectBlockchain(address: unknown, options?: ValidationOptions): BlockchainType | BlockchainType[] | null {
// Check options before the input, so empty or unsafe input cannot hide a misconfiguration.
assertValidationOptions(options);
let safe: string;
try { safe = InputSanitizer.sanitize(address); } catch { return null; }
if (!safe) return null;
Expand Down
3 changes: 3 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { shortenAddress, normalizeAddress, addChecksum } from './formatters/inde
import { BlockchainType, ValidationResult, ValidationOptions, FormatOptions } from './types';

import { getValidator } from './registry';
import { assertValidationOptions } from './validators/base';

export function validateAddress(
address: unknown,
Expand All @@ -29,6 +30,8 @@ export function validateBatch(
options?: ValidationOptions
): ValidationResult[] {
const validator = getValidator(blockchain);
// Check options even for an empty batch, so misconfiguration does not depend on the input.
assertValidationOptions(options);
return Array.from(addresses, addr => validator.validate(addr, options));
}

Expand Down
12 changes: 12 additions & 0 deletions src/validators/base.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,25 @@
import { ValidationResult, ValidationOptions, FormatOptions, ValidationError } from '../types';
import { InputSanitizer } from '../security/sanitizer';

/**
* Options come from the caller, not the end user, so a typo fails loudly instead of as NETWORK_MISMATCH.
* Every public entry point calls this before reading input, so the error does not depend on the data.
*/
export function assertValidationOptions(options?: ValidationOptions): void {
const network = options?.network;
if (network != null && network !== 'mainnet' && network !== 'testnet' && network !== 'auto') {
throw new RangeError(`Invalid network option: ${String(network)} (expected 'mainnet', 'testnet' or 'auto')`);
}
}

export abstract class AddressValidator {
/**
* Validates an address.
* @param address - The address string to validate
* @param options - Validation options
*/
public validate(address: unknown, options?: ValidationOptions): ValidationResult {
assertValidationOptions(options);
try {
// Security: Sanitize input first
const safeAddress = InputSanitizer.sanitize(address);
Expand Down
66 changes: 66 additions & 0 deletions tests/network-option.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import { validateAddress, validateBatch, detectBlockchain, BitcoinValidator, EthereumValidator, CardanoValidator, ValidationError } from '../src';

// BIP-173 testnet vector and the genesis-block mainnet address.
const testnet = 'tb1qw508d6qejxtdg4y5r3zarvary0c5xw7kxpjzsx';
const mainnet = '1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa';
const evm = '0x52908400098527886E0F7030069857D2E4169EE7';
const invalidNetworks = ['foo', 'Mainnet', 'main', '', 1, true, {}];

describe('network option', () => {
describe.each(invalidNetworks)('invalid value %j', network => {
const options = { network } as never;

test('throws from single-address validation on every chain family', () => {
for (const [address, chain] of [[mainnet, 'bitcoin'], [testnet, 'bitcoin'], [evm, 'ethereum'], [evm, 'base']] as const) {
expect(() => validateAddress(address, chain, options)).toThrow(RangeError);
}
});

test('throws from direct validators', () => {
expect(() => new BitcoinValidator().validate(mainnet, options)).toThrow(RangeError);
expect(() => new EthereumValidator().validate(evm, options)).toThrow(RangeError);
expect(() => new CardanoValidator().validate('', options)).toThrow(RangeError);
});

test('throws from batches, including an empty batch', () => {
expect(() => validateBatch([mainnet, evm], 'bitcoin', options)).toThrow(RangeError);
expect(() => validateBatch([], 'bitcoin', options)).toThrow(RangeError);
expect(() => validateBatch([], 'ethereum', options)).toThrow(RangeError);
});

test('throws from detection, including empty, blank and unsafe input', () => {
for (const input of [mainnet, evm, '', ' ', 'bad\x00input', null, undefined, 42]) {
expect(() => detectBlockchain(input, options)).toThrow(RangeError);
}
});

test('names the expected values', () => {
expect(() => validateAddress(mainnet, 'bitcoin', options)).toThrow("expected 'mainnet', 'testnet' or 'auto'");
});
});

test.each([undefined, null, 'auto', 'mainnet', 'testnet'] as const)('accepts %j without throwing on empty input', network => {
const options = { network } as never;
expect(validateBatch([], 'bitcoin', options)).toEqual([]);
expect(detectBlockchain('', options)).toBeNull();
expect(detectBlockchain(null, options)).toBeNull();
expect(validateAddress('', 'bitcoin', options).valid).toBe(false);
});

test('a real network mismatch still reports NETWORK_MISMATCH with the decoded network', () => {
expect(validateAddress(testnet, 'bitcoin', { network: 'mainnet' })).toEqual({
valid: false,
error: 'Address network does not match the requested network',
details: { format: 'segwit', network: 'testnet', checksum: true, errorCode: ValidationError.NETWORK_MISMATCH },
});
expect(validateAddress(mainnet, 'bitcoin', { network: 'testnet' }).details).toMatchObject({ network: 'mainnet', errorCode: ValidationError.NETWORK_MISMATCH });
expect(validateBatch([mainnet, testnet], 'bitcoin', { network: 'mainnet' }).map(result => result.details?.errorCode))
.toEqual([undefined, ValidationError.NETWORK_MISMATCH]);
});

test('matching networks and network-less chains still pass', () => {
expect(validateAddress(mainnet, 'bitcoin', { network: 'mainnet' }).valid).toBe(true);
expect(validateAddress(testnet, 'bitcoin', { network: 'testnet' }).valid).toBe(true);
expect(validateAddress(evm, 'ethereum', { network: 'testnet' }).valid).toBe(true);
});
});