Skip to content

Commit

Permalink
feat(utils): add validateAndParseAddress function
Browse files Browse the repository at this point in the history
  • Loading branch information
dhruvkelawala committed Jan 22, 2022
1 parent fe8b1a5 commit c067fc4
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 0 deletions.
15 changes: 15 additions & 0 deletions __tests__/utils/address.test.ts
Original file line number Diff line number Diff line change
@@ -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}`);
});
});
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
14 changes: 14 additions & 0 deletions src/utils/address.ts
Original file line number Diff line number Diff line change
@@ -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;
}

0 comments on commit c067fc4

Please sign in to comment.