Skip to content

Commit

Permalink
Merge pull request #4935 from BitGo/PX-5154-hbar
Browse files Browse the repository at this point in the history
fix(sdk-coin-hbar): hbar address validation
  • Loading branch information
ajays97 authored Sep 25, 2024
2 parents 2d809ea + 7015310 commit 19499be
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
12 changes: 10 additions & 2 deletions modules/sdk-coin-hbar/src/lib/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,19 @@ const MAX_TINYBARS_AMOUNT = new BigNumber(2).pow(63).minus(1);
* @returns {boolean} - The validation result
*/
export function isValidAddress(address: string): boolean {
if (_.isEmpty(address) || !address.match(/^\d+(?:(?=\.)(\.\d+){2}|(?!\.))$/)) {
const addressArray = address.split('?memoId=');

if (
_.isEmpty(address) ||
![1, 2].includes(addressArray.length) ||
!addressArray[0].match(/^\d+(?:(?=\.)(\.\d+){2}|(?!\.))$/) ||
(addressArray[1] && !isValidMemo(addressArray[1]))
) {
return false;
}

try {
const acc = AccountId.fromString(address);
const acc = AccountId.fromString(addressArray[0]);
return !_.isNaN(acc.num);
} catch (e) {
return false;
Expand Down
11 changes: 11 additions & 0 deletions modules/sdk-coin-hbar/test/unit/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,19 +9,30 @@ describe('HBAR util library', function () {
describe('address', function () {
it('should validate addresses', function () {
const validAddresses = ['0', '0.0.0', '99.99.99', '0.0.41098'];
const validAddressesWithMemo = ['0.0.41098?memoId=4'];

for (const address of validAddresses) {
Utils.isValidAddress(address).should.be.true();
}

for (const address of validAddressesWithMemo) {
Utils.isValidAddress(address).should.be.true();
}
});

it('should fail to validate invalid addresses', function () {
const invalidAddresses = ['0.0', '0.0.0.0', 'abc', 'a.b.c', '', '0x23C3E227BE97281A70A549c7dDB8d5Caad3E7C84'];
const invalidAddressesWithMemo = ['0.0.41098?memoId=m?memoId=4'];

for (const address of invalidAddresses) {
should.doesNotThrow(() => Utils.isValidAddress(address));
Utils.isValidAddress(address).should.be.false();
}

for (const address of invalidAddressesWithMemo) {
should.doesNotThrow(() => Utils.isValidAddress(address));
Utils.isValidAddress(address).should.be.false();
}
});
});

Expand Down

0 comments on commit 19499be

Please sign in to comment.