From c067fc443e4dc9c22b78ed6c093978a2f37debde Mon Sep 17 00:00:00 2001 From: dhruvkelawala Date: Mon, 10 Jan 2022 16:21:30 +0530 Subject: [PATCH] feat(utils): add validateAndParseAddress function --- __tests__/utils/address.test.ts | 15 +++++++++++++++ src/index.ts | 1 + src/utils/address.ts | 14 ++++++++++++++ 3 files changed, 30 insertions(+) create mode 100644 __tests__/utils/address.test.ts create mode 100644 src/utils/address.ts diff --git a/__tests__/utils/address.test.ts b/__tests__/utils/address.test.ts new file mode 100644 index 000000000..f891537bc --- /dev/null +++ b/__tests__/utils/address.test.ts @@ -0,0 +1,15 @@ +import { validateAndParseAddress } from '../../src/utils/address'; + +describe('validateAndParseAddress', () => { + test('should pass when correct starknet address is passed', () => { + const addr = '0x07ee790591d9fa3efc87067d95a643f8455e0b8190eb8cb7bfd39e4fb7571fdf'; + + return expect(validateAndParseAddress(addr)).toEqual(addr); + }); + + test('should add 0x prefix if not provided', () => { + const addr = '07ee790591d9fa3efc87067d95a643f8455e0b8190eb8cb7bfd39e4fb7571fdf'; + + return expect(validateAndParseAddress(addr)).toEqual(`0x${addr}`); + }); +}); diff --git a/src/index.ts b/src/index.ts index 33a61fb73..0e09b3f1d 100644 --- a/src/index.ts +++ b/src/index.ts @@ -19,3 +19,4 @@ export * as ec from './utils/ellipticCurve'; export * as uint256 from './utils/uint256'; export * as shortString from './utils/shortString'; export * as typedData from './utils/typedData'; +export * from './utils/address'; diff --git a/src/utils/address.ts b/src/utils/address.ts new file mode 100644 index 000000000..ade568c16 --- /dev/null +++ b/src/utils/address.ts @@ -0,0 +1,14 @@ +export function validateAndParseAddress(address: string): string { + let result = null; + if (typeof address !== 'string') { + throw new Error('Invalid Address Type'); + } + + if (!address.match(/^(0x)?[0-9a-fA-F]{63,64}$/)) { + throw new Error('Invalid Address Format'); + } + + result = address.substring(0, 2) === '0x' ? address : `0x${address}`; + + return result; +}