import { bech32 } from "bech32"; import { HexUtils } from "./hex"; import { NETWORK } from "./enums"; import { Buffer } from "buffer"; import { NetworkUtils } from "./network"; const toStakeAddress = ( paymentAddress: string, network: NETWORK = NetworkUtils.get() ) => { const value = bech32.decode(paymentAddress, 120); const bechWords = bech32.fromWords(value.words); const hexCodes = bechWords.map((w) => w.toString(16).padStart(2, "0")); const hexAddress = hexCodes.join(""); const stakeHexAddress = hexAddress.substring(58); const stakeHexBytes = HexUtils.hexToBytes( (network === NETWORK.MAINNET ? "e1" : "e0") + stakeHexAddress ); const bech32Words = bech32.toWords(stakeHexBytes); return bech32.encode( network === NETWORK.MAINNET ? "stake" : "stake_test", bech32Words, 120 ); }; const compareAddresses = (paymentAddress1: string, paymentAddress2: string) => { return toStakeAddress(paymentAddress1) === toStakeAddress(paymentAddress2); }; /** * Converts an address in hex format to bech32 * @param {string} address Example input: 00e922e8166852073d6c1c9be0736530404c9c26d9ba1773e11d32d11c0f7b2c7f8924528d797a8f86d8210d6276e09f47b82ecd53a24900e7 * @returns {string} Bech32 encoded address */ const convertFromHexAddressToBech32 = (address: string) => { const buffer = Buffer.from(address, "hex"); const bechWords = bech32.toWords(buffer); const value = bech32.encode( NetworkUtils.get() === NETWORK.MAINNET ? "addr" : "addr_test", bechWords, 120 ); return value; }; /** * Converts a hex nami wallet address to a pubkeyhash * @param address * @returns {string} */ const convertToPubKeyHash = (address: string) => { return address.substring(2, 58); }; /** * Converts a payment address to hex */ const convertFromPaymentAddressToHex = (address: string) => { const decoded = bech32.decode(address, 120); const fromWords = bech32.fromWords(decoded.words); return HexUtils.toHex(fromWords); }; const convertFromPaymentAddressToPubKeyHash = (address: string) => { const hex = convertFromPaymentAddressToHex(address); return convertToPubKeyHash(hex); }; export const AddressUtils = { toStakeAddress, compareAddresses, convertFromHexAddressToBech32, convertFromPaymentAddressToHex, convertFromPaymentAddressToPubKeyHash, convertToPubKeyHash, };