Skip to content

Commit

Permalink
Merge pull request #368 from juliancwirko/address-validator
Browse files Browse the repository at this point in the history
Add address validator static method without throwing errors
  • Loading branch information
andreibancioiu authored Jan 8, 2024
2 parents 87a774e + 6129034 commit 435675b
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
6 changes: 6 additions & 0 deletions src/address.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,4 +44,10 @@ describe("test address", () => {
assert.throw(() => new Address("erd1l453hd0gt5gzdp7czpuall8ggt2dcv5zwmfdf3sd3lguxseux2"), errors.ErrAddressCannotCreate);
assert.throw(() => new Address("xerd1l453hd0gt5gzdp7czpuall8ggt2dcv5zwmfdf3sd3lguxseux2fsmsgldz"), errors.ErrAddressCannotCreate);
});

it("should validate the address without throwing the error", () => {
assert.isTrue(Address.isValid(aliceBech32));
assert.isFalse(Address.isValid('xerd1l453hd0gt5gzdp7czpuall8ggt2dcv5zwmfdf3sd3lguxseux2fsmsgldz'));
assert.isFalse(Address.isValid('erd1l453hd0gt5gzdp7czpuall8ggt2dcv5zwmfdf3sd3lguxseux2'))
})
});
17 changes: 17 additions & 0 deletions src/address.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,23 @@ export class Address {
return Address.fromValidHex(pubkey.toString("hex"));
}

/**
* Performs address validation without throwing errors
*/
static isValid(value: string): boolean {
const decoded = bech32.decodeUnsafe(value);
const prefix = decoded?.prefix;
const pubkey = decoded
? Buffer.from(bech32.fromWords(decoded.words))
: undefined;

if (prefix !== HRP || pubkey?.length !== PUBKEY_LENGTH) {
return false;
}

return true;
}

/**
* Returns the hex representation of the address (pubkey)
*/
Expand Down

0 comments on commit 435675b

Please sign in to comment.