Skip to content

Commit

Permalink
refactor(common-scripts): friendly error message
Browse files Browse the repository at this point in the history
  • Loading branch information
homura committed Jun 14, 2024
1 parent 1737c2f commit b6845ac
Showing 1 changed file with 19 additions and 11 deletions.
30 changes: 19 additions & 11 deletions packages/common-scripts/src/omnilock-bitcoin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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<string[]>;
signMessage(message: string, type?: "ecdsa"): Promise<string>;
Expand Down

0 comments on commit b6845ac

Please sign in to comment.