44 * Use `toOutputScriptTryFormats()` instead of `toOutputScript()` to parse addresses in
55 * non-canonical formats
66 */
7- import { getMainnet , getNetworkName , Network , networks } from './networks' ;
7+ import { getMainnet , getNetworkName , isValidNetwork , Network , networks } from './networks' ;
88import { fromOutputScript , toOutputScript } from './address' ;
99
1010import { bcashAddress } from './bitgo' ;
@@ -13,6 +13,10 @@ export const addressFormats = ['default', 'cashaddr'] as const;
1313
1414export type AddressFormat = ( typeof addressFormats ) [ number ] ;
1515
16+ function isCashaddrNetwork ( network : Network ) : boolean {
17+ return isValidNetwork ( network ) && [ networks . bitcoincash , networks . ecash ] . includes ( getMainnet ( network ) ) ;
18+ }
19+
1620/**
1721 * @param format
1822 * @param network
@@ -23,7 +27,7 @@ export function isSupportedAddressFormat(format: AddressFormat, network: Network
2327 case 'default' :
2428 return true ;
2529 case 'cashaddr' :
26- return [ networks . bitcoincash , networks . ecash ] . includes ( getMainnet ( network ) ) ;
30+ return isCashaddrNetwork ( network ) ;
2731 }
2832 throw new Error ( `unknown address format ${ format } ` ) ;
2933}
@@ -39,13 +43,9 @@ export function fromOutputScriptWithFormat(outputScript: Buffer, format: Address
3943 throw new Error ( `unsupported address format ${ format } for network ${ getNetworkName ( network ) } ` ) ;
4044 }
4145
42- switch ( getMainnet ( network ) ) {
43- case networks . bitcoincash :
44- case networks . ecash :
45- return bcashAddress . fromOutputScriptWithFormat ( outputScript , format , network ) ;
46- default :
47- return fromOutputScript ( outputScript , network ) ;
48- }
46+ return isCashaddrNetwork ( network )
47+ ? bcashAddress . fromOutputScriptWithFormat ( outputScript , format , network )
48+ : fromOutputScript ( outputScript , network ) ;
4949}
5050
5151/**
@@ -59,13 +59,9 @@ export function toOutputScriptWithFormat(address: string, format: AddressFormat,
5959 throw new Error ( `unsupported address format ${ format } for network ${ getNetworkName ( network ) } ` ) ;
6060 }
6161
62- switch ( getMainnet ( network ) ) {
63- case networks . bitcoincash :
64- case networks . ecash :
65- return bcashAddress . toOutputScriptWithFormat ( address , format , network ) ;
66- default :
67- return toOutputScript ( address , network ) ;
68- }
62+ return isCashaddrNetwork ( network )
63+ ? bcashAddress . toOutputScriptWithFormat ( address , format , network )
64+ : toOutputScript ( address , network ) ;
6965}
7066
7167/**
0 commit comments