Skip to content

Commit

Permalink
refactor(address): remove unnecessary switch statement
Browse files Browse the repository at this point in the history
the statement is replaced using the function in utils kvSwap
  • Loading branch information
kronolynx committed Jun 14, 2018
1 parent ce1a479 commit cc20f79
Showing 1 changed file with 16 additions and 17 deletions.
33 changes: 16 additions & 17 deletions app/lib/crypto/address/p2pkh.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,27 +3,34 @@ import {PublicKey} from "../key/publicKey"
import {sha256} from "../hash"
import {ChainType} from "../../chain/chainType"
import {Errors} from "../errors"
import {kvSwap} from "../../utils/utils"

/**
* Witnet chain prefix
* This object maps Witnet address prefixes to chain types.
*/
enum Prefix {
twit = ChainType.test,
wit = ChainType.main
const prefixToChainType: { [key: string]: number } = {
twit: ChainType.test,
wit: ChainType.main
}

/**
* This object maps chain types to Witnet address prefixes.
* @type {{ [key: number]: string }}
*/
const chainTypeToPrefix = kvSwap(prefixToChainType)

/**
* Encode pay-to-public-key-hash (P2PKH) address
* @param {PublicKey} pubKey public key
* @param chain
* @returns {string} address
*/
export const encode = (pubKey: PublicKey, chain: ChainType): string => {
if (!(chain in Prefix)) {
if (!(chain in chainTypeToPrefix)) {
throw new Error(Errors.UNSUPPORTED_CHAIN_TYPE)
}
const b32 = Bech32.toWords(Buffer.concat([Buffer.from([0]), sha256(pubKey.bytes).slice(0, 20)]))
const hrp: string = Prefix[chain]
const hrp: string = chainTypeToPrefix[chain]

return Bech32.encode(hrp, b32)
}
Expand All @@ -37,18 +44,10 @@ export const decode = (address: string): [ChainType, Buffer] => {
const {prefix, words} = Bech32.decode(address)
const keyHash = Buffer.from(Bech32.fromWords(words))

let chainType: ChainType

switch (prefix) {
case "twit":
chainType = ChainType.test
break
case "wit":
chainType = ChainType.main
break
default:
throw new Error(Errors.UNSUPPORTED_CHAIN_TYPE)
if (!(prefix in prefixToChainType)) {
throw new Error(Errors.UNSUPPORTED_CHAIN_TYPE)
}
const chainType: ChainType = prefixToChainType[prefix]

return [chainType, keyHash.slice(1)]
}

0 comments on commit cc20f79

Please sign in to comment.