From: Chris Duncan Date: Mon, 7 Jul 2025 13:13:58 +0000 (-0700) Subject: Create type guard from validate function. Compare lock and unlock password with insta... X-Git-Tag: v0.10.5~101 X-Git-Url: https://git.codecow.com/?a=commitdiff_plain;h=fa476c90117da2616f189d36908813373c79da40;p=libnemo.git Create type guard from validate function. Compare lock and unlock password with instanceof instead of constructor name. Update JSdoc comment. --- diff --git a/src/lib/account.ts b/src/lib/account.ts index 7c6452b..e235481 100644 --- a/src/lib/account.ts +++ b/src/lib/account.ts @@ -126,7 +126,7 @@ export class Account { * Instantiates an Account object from its private key. The corresponding * public key will automatically be derived and saved. * - * @param {string} privateKey - Private key of the account + * @param {(string|Uint8Array)} privateKey - Private key of the account * @param {number} [index] - Account number used when deriving the key * @returns {Account} A new Account object */ @@ -156,10 +156,8 @@ export class Account { * @returns True if successfully locked */ async lock (password: string | Uint8Array): Promise { - if (typeof password === 'string') { - password = utf8.toBytes(password) - } - if (password == null || password.constructor.name !== 'Uint8Array') { + if (typeof password === 'string') password = utf8.toBytes(password) + if (password == null || !(password instanceof Uint8Array)) { throw new Error('Failed to lock account') } try { @@ -195,10 +193,8 @@ export class Account { * @returns True if successfully unlocked */ async unlock (password: string | Uint8Array): Promise { - if (typeof password === 'string') { - password = utf8.toBytes(password) - } - if (password == null || password.constructor.name !== 'Uint8Array') { + if (typeof password === 'string') password = utf8.toBytes(password) + if (password == null || !(password instanceof Uint8Array)) { throw new Error('Failed to unlock account') } try { @@ -229,15 +225,14 @@ export class Account { * @param {string} address - Nano address to validate * @throws Error if address is undefined, not a string, or an invalid format */ - static validate (address: string): void { + static validate (address: unknown): asserts address is string { if (address === undefined) { throw new ReferenceError('Address is undefined.') } if (typeof address !== 'string') { throw new TypeError('Address must be a string.') } - const pattern = new RegExp(`^(${PREFIX}|${PREFIX_LEGACY})[13]{1}[${ALPHABET}]{59}$`, - ) + const pattern = new RegExp(`^(${PREFIX}|${PREFIX_LEGACY})[13]{1}[${ALPHABET}]{59}$`) if (!pattern.test(address)) { throw new RangeError('Invalid address format') }