From b6845aca394f238055883aaa5c3e137f93b8e5f3 Mon Sep 17 00:00:00 2001 From: homura Date: Fri, 14 Jun 2024 09:41:21 +0900 Subject: [PATCH] refactor(common-scripts): friendly error message --- .../common-scripts/src/omnilock-bitcoin.ts | 30 ++++++++++++------- 1 file changed, 19 insertions(+), 11 deletions(-) diff --git a/packages/common-scripts/src/omnilock-bitcoin.ts b/packages/common-scripts/src/omnilock-bitcoin.ts index 718ba7e96..d576dcee9 100644 --- a/packages/common-scripts/src/omnilock-bitcoin.ts +++ b/packages/common-scripts/src/omnilock-bitcoin.ts @@ -20,26 +20,23 @@ export function decodeAddress( const btcAddressFlagSize = 1; const hashSize = 20; - if (isP2wpkhAddress(address) && allows.includes("P2WPKH")) { + if (isP2wpkhAddress(address)) { + assertAddressType(allows, "P2WPKH"); return bech32.fromWords(bech32.decode(address).words.slice(1)); } - if (isP2pkhAddress(address) && allows.includes("P2PKH")) { + if (isP2pkhAddress(address)) { + assertAddressType(allows, "P2PKH"); return bs58 .decode(address) .slice(btcAddressFlagSize, btcAddressFlagSize + hashSize); } if (isP2shAddress(address)) { - if (allows.includes("P2SH-P2WPKH")) { - return bs58 - .decode(address) - .slice(btcAddressFlagSize, btcAddressFlagSize + hashSize); - } - - throw new Error( - "'P2SH-P2WPKH' must be included in the 'allows' for the P2SH address" - ); + assertAddressType(allows, "P2SH-P2WPKH"); + return bs58 + .decode(address) + .slice(btcAddressFlagSize, btcAddressFlagSize + hashSize); } // https://bitcoin.design/guide/glossary/address/#taproot-address---p2tr @@ -54,6 +51,17 @@ export function decodeAddress( ); } +function assertAddressType( + allows: SupportedBtcAddressType[], + usingAddressType: SupportedBtcAddressType +): void { + if (!allows.includes(usingAddressType)) { + throw new Error( + `'${usingAddressType}' must be included in the 'allows' for the address` + ); + } +} + export interface Provider { requestAccounts(): Promise; signMessage(message: string, type?: "ecdsa"): Promise;