Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add address related utils #112

Merged
merged 9 commits into from
Jul 11, 2023
38 changes: 38 additions & 0 deletions src/hex.test.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import {
Hex,
add0x,
assertIsHexString,
assertIsStrictHexString,
isHexString,
isStrictHexString,
isValidHexAddress,
remove0x,
} from './hex';

Expand Down Expand Up @@ -151,6 +153,42 @@ describe('assertIsStrictHexString', () => {
});
});

describe('isValidHexAddress', () => {
it.each([
'0x0000000000000000000000000000000000000000' as Hex,
'0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045' as Hex,
])('returns true for a valid prefixed hex address', (hexString) => {
expect(isValidHexAddress(hexString)).toBe(true);
});

it.each([
'0000000000000000000000000000000000000000',
'd8dA6BF26964aF9D7eEd9e03E53415D37aA96045',
])('returns false for a valid non-prefixed hex address', (hexString) => {
// @ts-expect-error - testing invalid input
expect(isValidHexAddress(hexString)).toBe(false);
});

it.each([
'12345g',
'1234567890abcdefg',
'1234567890abcdefG',
'1234567890abcdefABCDEFg',
'1234567890abcdefABCDEF1234567890abcdefABCDEFg',
'0x',
'0x0',
'0x12345g',
'0x1234567890abcdefg',
'0x1234567890abcdefG',
'0x1234567890abcdefABCDEFg',
'0x1234567890abcdefABCDEF1234567890abcdefABCDEFg',
'0Xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045',
])('returns false for an invalid hex address', (hexString) => {
// @ts-expect-error - testing invalid input
expect(isValidHexAddress(hexString)).toBe(false);
});
});

describe('add0x', () => {
it('adds a 0x-prefix to a string', () => {
expect(add0x('12345')).toBe('0x12345');
Expand Down
14 changes: 14 additions & 0 deletions src/hex.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@ export const StrictHexStruct = pattern(string(), /^0x[0-9a-f]+$/iu) as Struct<
Hex,
null
>;
export const HexAddressStruct = pattern(
string(),
/^0x[0-9a-fA-F]{40}$/u,
) as Struct<Hex, null>;

/**
* Check if a string is a valid hex string.
Expand Down Expand Up @@ -55,6 +59,16 @@ export function assertIsStrictHexString(value: unknown): asserts value is Hex {
);
}

/**
* Validates that the passed prefixed hex string is a valid hex address.
*
* @param possibleAddress - Input parameter to check against.
* @returns Whether or not the input is a valid hex address.
*/
export function isValidHexAddress(possibleAddress: Hex) {
return is(possibleAddress, HexAddressStruct);
}

/**
* Add the `0x`-prefix to a hexadecimal string. If the string already has the
* prefix, it is returned as-is.
Expand Down