mainnet-js 1.1.8 → 1.1.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1424,7 +1424,7 @@ eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harm
1424
1424
  \************************************/
1425
1425
  /***/ ((module, __webpack_exports__, __webpack_require__) => {
1426
1426
 
1427
- eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"checkTokenaddr\": () => (/* binding */ checkTokenaddr),\n/* harmony export */ \"deriveCashaddr\": () => (/* binding */ deriveCashaddr),\n/* harmony export */ \"deriveTokenaddr\": () => (/* binding */ deriveTokenaddr),\n/* harmony export */ \"isTokenaddr\": () => (/* binding */ isTokenaddr),\n/* harmony export */ \"toCashaddr\": () => (/* binding */ toCashaddr),\n/* harmony export */ \"toTokenaddr\": () => (/* binding */ toTokenaddr)\n/* harmony export */ });\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/crypto/default-crypto-instances.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/address/cash-address.js\");\n/* harmony import */ var _hash160_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./hash160.js */ \"./src/util/hash160.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__, _hash160_js__WEBPACK_IMPORTED_MODULE_1__]);\n([_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__, _hash160_js__WEBPACK_IMPORTED_MODULE_1__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\nfunction deriveCashaddr(privateKey, networkPrefix) {\n let publicKey = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.secp256k1.derivePublicKeyCompressed(privateKey);\n if (typeof publicKey === \"string\") {\n throw new Error(publicKey);\n }\n let pkh = (0,_hash160_js__WEBPACK_IMPORTED_MODULE_1__.hash160)(publicKey);\n return (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.encodeCashAddress)(networkPrefix, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.CashAddressType.p2pkh, pkh);\n}\nfunction deriveTokenaddr(key, networkPrefix) {\n let publicKeyHash;\n // private key\n if (key.length === 32) {\n let publicKeyCompressed = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.secp256k1.derivePublicKeyCompressed(key);\n if (typeof publicKeyCompressed === \"string\") {\n throw new Error(publicKeyCompressed);\n }\n publicKeyHash = (0,_hash160_js__WEBPACK_IMPORTED_MODULE_1__.hash160)(publicKeyCompressed);\n }\n else if (key.length === 65) {\n // uncompressed public key\n let publicKeyCompressed = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.secp256k1.compressPublicKey(key);\n if (typeof publicKeyCompressed === \"string\") {\n throw new Error(publicKeyCompressed);\n }\n publicKeyHash = (0,_hash160_js__WEBPACK_IMPORTED_MODULE_1__.hash160)(publicKeyCompressed);\n }\n else if (key.length === 33) {\n // compressed public key\n publicKeyHash = (0,_hash160_js__WEBPACK_IMPORTED_MODULE_1__.hash160)(key);\n }\n else if (key.length === 20) {\n // public key hash\n publicKeyHash = key;\n }\n else {\n throw new Error(\"Unsupported type of key\");\n }\n return (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.encodeCashAddress)(networkPrefix, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.CashAddressType.p2pkhWithTokens, publicKeyHash);\n}\nfunction toCashaddr(tokenaddr) {\n let result;\n // If the address has a prefix decode it as is\n if (tokenaddr.includes(\":\")) {\n result = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.decodeCashAddressFormat)(tokenaddr);\n }\n // otherwise, derive the network from the tokenaddr without prefix\n else {\n result = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.decodeCashAddressFormatWithoutPrefix)(tokenaddr);\n }\n if (typeof result === \"string\")\n throw new Error(result);\n return (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.encodeCashAddress)(result.prefix, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.CashAddressType.p2pkh, result.payload);\n}\nfunction toTokenaddr(cashaddr) {\n let result;\n // If the address has a prefix decode it as is\n if (cashaddr.includes(\":\")) {\n result = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.decodeCashAddressFormat)(cashaddr);\n }\n // otherwise, derive the network from the cashaddr without prefix\n else {\n result = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.decodeCashAddressFormatWithoutPrefix)(cashaddr);\n }\n if (typeof result === \"string\")\n throw new Error(result);\n return (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.encodeCashAddress)(result.prefix, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.CashAddressType.p2pkhWithTokens, result.payload);\n}\nfunction isTokenaddr(address) {\n let result;\n // If the address has a prefix decode it as is\n if (address.includes(\":\")) {\n result = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.decodeCashAddressFormat)(address);\n }\n // otherwise, derive the network from the address without prefix\n else {\n result = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.decodeCashAddressFormatWithoutPrefix)(address);\n }\n if (typeof result === \"string\")\n throw new Error(result);\n return ([\n _bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.CashAddressVersionByte.p2pkhWithTokens,\n _bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.CashAddressVersionByte.p2sh20WithTokens,\n _bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.CashAddressVersionByte.p2sh32WithTokens,\n ].indexOf(result.version) !== -1);\n}\nfunction checkTokenaddr(cashaddr, enforce) {\n if (enforce && !isTokenaddr(cashaddr)) {\n throw new Error(\"Error trying to send to a non-tokenaware cash address\");\n }\n}\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/util/deriveCashaddr.ts?");
1427
+ eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"checkTokenaddr\": () => (/* binding */ checkTokenaddr),\n/* harmony export */ \"deriveCashaddr\": () => (/* binding */ deriveCashaddr),\n/* harmony export */ \"deriveTokenaddr\": () => (/* binding */ deriveTokenaddr),\n/* harmony export */ \"isTokenaddr\": () => (/* binding */ isTokenaddr),\n/* harmony export */ \"toCashaddr\": () => (/* binding */ toCashaddr),\n/* harmony export */ \"toTokenaddr\": () => (/* binding */ toTokenaddr)\n/* harmony export */ });\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/crypto/default-crypto-instances.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/address/cash-address.js\");\n/* harmony import */ var _hash160_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./hash160.js */ \"./src/util/hash160.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__, _hash160_js__WEBPACK_IMPORTED_MODULE_1__]);\n([_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__, _hash160_js__WEBPACK_IMPORTED_MODULE_1__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\nfunction deriveCashaddr(privateKey, networkPrefix) {\n let publicKey = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.secp256k1.derivePublicKeyCompressed(privateKey);\n if (typeof publicKey === \"string\") {\n throw new Error(publicKey);\n }\n let pkh = (0,_hash160_js__WEBPACK_IMPORTED_MODULE_1__.hash160)(publicKey);\n return (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.encodeCashAddress)(networkPrefix, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.CashAddressType.p2pkh, pkh);\n}\nfunction deriveTokenaddr(key, networkPrefix) {\n let publicKeyHash;\n // private key\n if (key.length === 32) {\n let publicKeyCompressed = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.secp256k1.derivePublicKeyCompressed(key);\n if (typeof publicKeyCompressed === \"string\") {\n throw new Error(publicKeyCompressed);\n }\n publicKeyHash = (0,_hash160_js__WEBPACK_IMPORTED_MODULE_1__.hash160)(publicKeyCompressed);\n }\n else if (key.length === 65) {\n // uncompressed public key\n let publicKeyCompressed = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.secp256k1.compressPublicKey(key);\n if (typeof publicKeyCompressed === \"string\") {\n throw new Error(publicKeyCompressed);\n }\n publicKeyHash = (0,_hash160_js__WEBPACK_IMPORTED_MODULE_1__.hash160)(publicKeyCompressed);\n }\n else if (key.length === 33) {\n // compressed public key\n publicKeyHash = (0,_hash160_js__WEBPACK_IMPORTED_MODULE_1__.hash160)(key);\n }\n else if (key.length === 20) {\n // public key hash\n publicKeyHash = key;\n }\n else {\n throw new Error(\"Unsupported type of key\");\n }\n return (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.encodeCashAddress)(networkPrefix, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.CashAddressType.p2pkhWithTokens, publicKeyHash);\n}\nfunction toCashaddr(tokenaddr) {\n let result;\n // If the address has a prefix decode it as is\n if (tokenaddr.includes(\":\")) {\n result = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.decodeCashAddressFormat)(tokenaddr);\n }\n // otherwise, derive the network from the tokenaddr without prefix\n else {\n result = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.decodeCashAddressFormatWithoutPrefix)(tokenaddr);\n }\n if (typeof result === \"string\")\n throw new Error(result);\n return (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.encodeCashAddress)(result.prefix, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.CashAddressType.p2pkh, result.payload);\n}\nfunction toTokenaddr(cashaddr) {\n let result;\n // If the address has a prefix decode it as is\n if (cashaddr.includes(\":\")) {\n result = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.decodeCashAddressFormat)(cashaddr);\n }\n // otherwise, derive the network from the cashaddr without prefix\n else {\n result = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.decodeCashAddressFormatWithoutPrefix)(cashaddr);\n }\n if (typeof result === \"string\")\n throw new Error(result);\n return (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.encodeCashAddress)(result.prefix, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.CashAddressType.p2pkhWithTokens, result.payload);\n}\nfunction isTokenaddr(address) {\n let result;\n // If the address has a prefix decode it as is\n if (address.includes(\":\")) {\n result = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.decodeCashAddressFormat)(address);\n }\n else {\n // otherwise, derive the network from the address without prefix\n result = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.decodeCashAddressFormatWithoutPrefix)(address);\n }\n if (typeof result === \"string\")\n throw new Error(result);\n const info = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.decodeCashAddressVersionByte)(result.version);\n if (typeof info === \"string\")\n throw new Error(info);\n const type = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.cashAddressTypeBitsToType[info.typeBits];\n if (type === undefined) {\n throw Error(\"Wrong cashaddress type\");\n }\n return ([_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.CashAddressType.p2pkhWithTokens, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.CashAddressType.p2shWithTokens].indexOf(type) !== -1);\n}\nfunction checkTokenaddr(cashaddr, enforce) {\n if (enforce && !isTokenaddr(cashaddr)) {\n throw new Error(\"Error trying to send to a non-tokenaware cash address\");\n }\n}\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/util/deriveCashaddr.ts?");
1428
1428
 
1429
1429
  /***/ }),
1430
1430
 
@@ -1634,7 +1634,7 @@ eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__
1634
1634
  \****************************/
1635
1635
  /***/ ((module, __webpack_exports__, __webpack_require__) => {
1636
1636
 
1637
- eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"BCMR\": () => (/* binding */ BCMR)\n/* harmony export */ });\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/hex.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/crypto/default-crypto-instances.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/utf8.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/number.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/message/transaction-encoding.js\");\n/* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! axios */ \"../../node_modules/axios/index.js\");\n/* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(axios__WEBPACK_IMPORTED_MODULE_0__);\n/* harmony import */ var _interface_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../interface.js */ \"./src/interface.ts\");\n/* harmony import */ var _network_Connection_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../network/Connection.js */ \"./src/network/Connection.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__, _network_Connection_js__WEBPACK_IMPORTED_MODULE_5__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__]);\n([_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__, _network_Connection_js__WEBPACK_IMPORTED_MODULE_5__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\n\n\n// Implementation of CHIP-BCMR v1.0.0, refer to https://github.com/bitjson/chip-bcmr\nclass BCMR {\n static getRegistries() {\n return this.metadataRegistries;\n }\n static resetRegistries() {\n this.metadataRegistries = [];\n }\n /**\n * fetchMetadataRegistry Fetch the BCMR registry JSON file from a remote URI, optionally verifying its content hash\n *\n * @param {string} uri URI of the registry to fetch from\n * @param {string?} contentHash SHA256 hash of the resource the `uri` parameter points at.\n * If specified, calculates the hash of the data fetched from `uri` and matches it with provided one.\n * Yields an error upon mismatch.\n *\n * @returns {Registry} resolved registry\n */\n static async fetchMetadataRegistry(uri, contentHash) {\n if (uri.indexOf(\"https://\") < 0) {\n uri = `https://${uri}`;\n }\n // content hashes HTTPS Publication Outputs per spec\n if (contentHash) {\n // request as text and verify hash\n const response = await axios__WEBPACK_IMPORTED_MODULE_0___default().get(uri, {\n responseType: \"text\",\n transformResponse: (val) => {\n return val;\n },\n });\n const hash = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.binToHex)(_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.sha256.hash((0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.utf8ToBin)(response.data)));\n if (contentHash != hash) {\n throw new Error(`Content hash mismatch for URI: ${uri}\\nreceived: ${hash}\\nrequired: ${contentHash}`);\n }\n return JSON.parse(response.data);\n }\n // request as JSON\n const response = await axios__WEBPACK_IMPORTED_MODULE_0___default().get(uri);\n return response.data;\n }\n /**\n * addMetadataRegistry Add the metadata registry to the list of tracked registries\n *\n * @param {Registry} registry Registry object per schema specification, see https://raw.githubusercontent.com/bitjson/chip-bcmr/master/bcmr-v1.schema.json\n *\n */\n static addMetadataRegistry(registry) {\n if (this.metadataRegistries.some((val) => JSON.stringify(val) === JSON.stringify(registry))) {\n return;\n }\n this.metadataRegistries.push(registry);\n }\n /**\n * addMetadataRegistryFromUri Add the metadata registry by fetching a JSON file from a remote URI, optionally verifying its content hash\n *\n * @param {string} uri URI of the registry to fetch from\n * @param {string?} contentHash SHA256 hash of the resource the `uri` parameter points at.\n * If specified, calculates the hash of the data fetched from `uri` and matches it with provided one.\n * Yields an error upon mismatch.\n *\n */\n static async addMetadataRegistryFromUri(uri, contentHash) {\n const registry = await this.fetchMetadataRegistry(uri, contentHash);\n this.addMetadataRegistry(registry);\n }\n /**\n * buildAuthChain Build an authchain - Zeroth-Descendant Transaction Chain, refer to https://github.com/bitjson/chip-bcmr#zeroth-descendant-transaction-chains\n * The authchain in this implementation is specific to resolve to a valid metadata registry\n *\n * @param {string} options.transactionHash (required) transaction hash from which to build the auth chain\n * @param {Network?} options.network (default=mainnet) network to query the data from\n * @param {boolean?} options.resolveBase (default=false) boolean flag to indicate that autchain building should resolve and verify elements back to base or be stopped at this exact chain element\n * @param {boolean?} options.followToHead (default=true) boolean flag to indicate that autchain building should progress to head or be stopped at this exact chain element\n * @param {ElectrumRawTransaction?} options.rawTx cached raw transaction obtained previously, spares a Fulcrum call\n * @param {TxI[]?} options.historyCache cached address history to be reused if authchain building proceeds with the same address, spares a flurry of Fulcrum calls\n *\n * @returns {AuthChain} returns the resolved authchain\n */\n static async buildAuthChain(options) {\n if (options.network === undefined) {\n options.network = _interface_js__WEBPACK_IMPORTED_MODULE_4__.Network.MAINNET;\n }\n if (options.followToHead === undefined) {\n options.followToHead = true;\n }\n if (options.resolveBase === undefined) {\n options.resolveBase = false;\n }\n const provider = (await (0,_network_Connection_js__WEBPACK_IMPORTED_MODULE_5__.initProvider)(options.network));\n if (options.rawTx === undefined) {\n options.rawTx = await provider.getRawTransactionObject(options.transactionHash);\n }\n // figure out the autchain by moving towards authhead\n const getAuthChainChild = async () => {\n const history = options.historyCache ||\n (await provider.getHistory(options.rawTx.vout[0].scriptPubKey.addresses[0]));\n const thisTx = history.find((val) => val.tx_hash === options.transactionHash);\n let filteredHistory = history.filter((val) => val.height > 0\n ? val.height >= thisTx.height || val.height <= 0\n : val.height <= 0 && val.tx_hash !== thisTx.tx_hash);\n for (const historyTx of filteredHistory) {\n const historyRawTx = await provider.getRawTransactionObject(historyTx.tx_hash);\n const authChainVin = historyRawTx.vin.find((val) => val.txid === options.transactionHash && val.vout === 0);\n // if we've found continuation of authchain, we shall recurse into it\n if (authChainVin) {\n // reuse queried address history if the next element in chain is the same address\n const historyCache = options.rawTx.vout[0].scriptPubKey.addresses[0] ===\n historyRawTx.vout[0].scriptPubKey.addresses[0]\n ? filteredHistory\n : undefined;\n // combine the authchain element with the rest obtained\n return { rawTx: historyRawTx, historyCache };\n }\n }\n return undefined;\n };\n // helper function to enforce the constraints on the 0th output, decode the BCMR's OP_RETURN data\n // returns resolved AuthChainElement\n const makeAuthChainElement = (rawTx, hash) => {\n let opReturns;\n let spends0thOutput = false;\n if (rawTx.hasOwnProperty(\"vout\")) {\n const electrumTransaction = rawTx;\n opReturns = electrumTransaction.vout\n .filter((val) => val.scriptPubKey.type === \"nulldata\")\n .map((val) => val.scriptPubKey.hex);\n spends0thOutput = electrumTransaction.vin.some((val) => val.vout === 0);\n }\n else {\n const libauthTransaction = rawTx;\n opReturns = libauthTransaction.outputs\n .map((val) => (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.binToHex)(val.lockingBytecode))\n .filter((val) => val.indexOf(\"6a\") === 0);\n spends0thOutput = libauthTransaction.inputs.some((val) => val.outpointIndex === 0);\n }\n if (!spends0thOutput) {\n throw new Error(\"Invalid authchain transaction (does not spend 0th output of previous transaction)\");\n }\n const bcmrOpReturns = opReturns.filter((val) => val.indexOf(\"6a0442434d52\") === 0 ||\n val.indexOf(\"6a4c0442434d52\") === 0 ||\n val.indexOf(\"6a4d040042434d52\") === 0 ||\n val.indexOf(\"6a4e0400000042434d52\") === 0);\n if (bcmrOpReturns.length === 0) {\n return {\n txHash: hash,\n contentHash: \"\",\n uri: \"\",\n };\n }\n const opReturnHex = opReturns[0];\n const opReturn = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.hexToBin)(opReturnHex);\n const chunks = [];\n let position = 1;\n // handle direct push, OP_PUSHDATA1, OP_PUSHDATA2;\n // OP_PUSHDATA4 is not supported in OP_RETURNs by consensus\n while (opReturn[position]) {\n let length = 0;\n if (opReturn[position] === 0x4c) {\n length = opReturn[position + 1];\n position += 2;\n }\n else if (opReturn[position] === 0x4d) {\n length = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__.binToNumberUint16LE)(opReturn.slice(position + 1, position + 3));\n position += 3;\n }\n else {\n length = opReturn[position];\n position += 1;\n }\n chunks.push(opReturn.slice(position, position + length));\n position += length;\n }\n if (chunks.length < 2 || chunks.length > 3) {\n throw new Error(`Malformed BCMR output: ${opReturnHex}`);\n }\n const result = {\n txHash: hash,\n contentHash: \"\",\n uri: \"\",\n };\n if (chunks.length === 2) {\n // IPFS Publication Output\n result.contentHash = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.binToHex)(chunks[1]);\n const ipfsCid = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.binToUtf8)(chunks[1]);\n result.uri = `https://dweb.link/ipfs/${ipfsCid}`;\n }\n else {\n // HTTPS Publication Output\n // content hash is in OP_SHA256 byte order per spec\n result.contentHash = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.binToHex)(chunks[1].slice().reverse());\n result.uri = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.binToUtf8)(chunks[2]);\n if (result.uri.indexOf(\"https://\") < 0) {\n result.uri = `https://${result.uri}`;\n }\n }\n return result;\n };\n // make authchain element and combine with the rest obtained\n let element;\n try {\n element = makeAuthChainElement(options.rawTx, options.rawTx.hash);\n }\n catch (error) {\n // special case for cashtoken authchain lookup by categoryId - allow to fail first lookup and inspect the genesis transaction\n // follow authchain to head and look for BCMR outputs\n const child = await getAuthChainChild();\n if (child) {\n return await BCMR.buildAuthChain({\n ...options,\n transactionHash: child.rawTx.hash,\n rawTx: child.rawTx,\n historyCache: child.historyCache,\n });\n }\n else {\n throw error;\n }\n }\n let chainBase = [];\n if (options.resolveBase) {\n // check for accelerated path if \"authchain\" extension is in registry\n const registry = await this.fetchMetadataRegistry(element.uri, element.contentHash);\n if (registry.extensions &&\n registry.extensions[\"authchain\"] &&\n (Object.keys(registry.extensions[\"authchain\"])).length) {\n const chainTxArray = Object.values(registry.extensions[\"authchain\"]);\n chainBase = chainTxArray\n .map((tx) => {\n const transactionBin = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.hexToBin)(tx);\n const decoded = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__.decodeTransaction)(transactionBin);\n if (typeof decoded === \"string\") {\n throw new Error(`Error decoding transaction ${JSON.stringify(tx)}, ${decoded}`);\n }\n const hash = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.binToHex)(_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.sha256.hash(_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.sha256.hash(transactionBin)).reverse());\n return { decoded, hash };\n })\n .map(({ decoded, hash }) => makeAuthChainElement(decoded, hash));\n }\n else {\n // simply go back in history towards authhead\n let stop = false;\n let tx = { ...options.rawTx };\n let maxElements = 10;\n while (stop == false || maxElements === 0) {\n const vin = tx.vin.find((val) => val.vout === 0);\n tx = await provider.getRawTransactionObject(vin.txid);\n try {\n const pastElement = makeAuthChainElement(tx, tx.hash);\n chainBase.unshift(pastElement);\n maxElements--;\n }\n catch {\n stop = true;\n }\n }\n }\n }\n // if we follow to head, we need to locate the next transaction spending our 0th output\n // and repeat the building process recursively\n if (options.followToHead) {\n const child = await getAuthChainChild();\n if (child) {\n const chainHead = await BCMR.buildAuthChain({\n transactionHash: child.rawTx.hash,\n network: options.network,\n rawTx: child.rawTx,\n historyCache: child.historyCache,\n followToHead: options.followToHead,\n resolveBase: false,\n });\n // combine the authchain element with the rest obtained\n return [...chainBase, element, ...chainHead].filter((val) => val.uri.length);\n }\n }\n // return the last chain element (or the only found in an edge case)\n return [...chainBase, element].filter((val) => val.uri.length);\n }\n /**\n * addMetadataRegistryAuthChain Add BCMR metadata registry by resolving an authchain\n *\n * @param {string} options.transactionHash (required) transaction hash from which to build the auth chain\n * @param {Network?} options.network (default=mainnet) network to query the data from\n * @param {boolean?} options.followToHead (default=true) boolean flag to indicate that autchain building should progress to head (most recent registry version) or be stopped at this exact chain element\n * @param {ElectrumRawTransaction?} options.rawTx cached raw transaction obtained previously, spares a Fulcrum call\n *\n * @returns {AuthChain} returns the resolved authchain\n */\n static async addMetadataRegistryAuthChain(options) {\n const authChain = await this.buildAuthChain({\n ...options,\n resolveBase: false,\n });\n if (!authChain.length) {\n throw new Error(`There were no BCMR entries in the resolved authchain ${JSON.stringify(authChain, null, 2)}`);\n }\n const registry = await this.fetchMetadataRegistry(authChain.reverse()[0].uri);\n this.addMetadataRegistry(registry);\n return authChain;\n }\n /**\n * getTokenInfo Return the token info (or the identity snapshot as per spec)\n *\n * @param {string} tokenId token id to look up\n *\n * @returns {IdentitySnapshot?} return the info for the token found, otherwise undefined\n */\n static getTokenInfo(tokenId) {\n for (const registry of this.metadataRegistries.slice().reverse()) {\n const history = registry.identities?.[tokenId];\n if (!history) {\n continue;\n }\n const latestIdentityIndex = Object.keys(history)[0];\n if (latestIdentityIndex === undefined) {\n continue;\n }\n return history[latestIdentityIndex];\n }\n return undefined;\n }\n}\n// List of tracked registries\nBCMR.metadataRegistries = [];\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/wallet/Bcmr.ts?");
1637
+ eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"BCMR\": () => (/* binding */ BCMR)\n/* harmony export */ });\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/hex.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/crypto/default-crypto-instances.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/utf8.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/number.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/message/transaction-encoding.js\");\n/* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! axios */ \"../../node_modules/axios/index.js\");\n/* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(axios__WEBPACK_IMPORTED_MODULE_0__);\n/* harmony import */ var _interface_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../interface.js */ \"./src/interface.ts\");\n/* harmony import */ var _network_Connection_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../network/Connection.js */ \"./src/network/Connection.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__, _network_Connection_js__WEBPACK_IMPORTED_MODULE_5__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__]);\n([_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__, _network_Connection_js__WEBPACK_IMPORTED_MODULE_5__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\n\n\n// Implementation of CHIP-BCMR v1.0.0, refer to https://github.com/bitjson/chip-bcmr\nclass BCMR {\n static getRegistries() {\n return this.metadataRegistries;\n }\n static resetRegistries() {\n this.metadataRegistries = [];\n }\n /**\n * fetchMetadataRegistry Fetch the BCMR registry JSON file from a remote URI, optionally verifying its content hash\n *\n * @param {string} uri URI of the registry to fetch from\n * @param {string?} contentHash SHA256 hash of the resource the `uri` parameter points at.\n * If specified, calculates the hash of the data fetched from `uri` and matches it with provided one.\n * Yields an error upon mismatch.\n *\n * @returns {Registry} resolved registry\n */\n static async fetchMetadataRegistry(uri, contentHash) {\n if (uri.indexOf(\"https://\") < 0) {\n uri = `https://${uri}`;\n }\n // content hashes HTTPS Publication Outputs per spec\n if (contentHash) {\n // request as text and verify hash\n const response = await axios__WEBPACK_IMPORTED_MODULE_0___default().get(uri, {\n responseType: \"text\",\n transformResponse: (val) => {\n return val;\n },\n });\n const hash = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.binToHex)(_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.sha256.hash((0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.utf8ToBin)(response.data)));\n if (contentHash != hash) {\n throw new Error(`Content hash mismatch for URI: ${uri}\\nreceived: ${hash}\\nrequired: ${contentHash}`);\n }\n return JSON.parse(response.data);\n }\n // request as JSON\n const response = await axios__WEBPACK_IMPORTED_MODULE_0___default().get(uri);\n return response.data;\n }\n /**\n * addMetadataRegistry Add the metadata registry to the list of tracked registries\n *\n * @param {Registry} registry Registry object per schema specification, see https://raw.githubusercontent.com/bitjson/chip-bcmr/master/bcmr-v1.schema.json\n *\n */\n static addMetadataRegistry(registry) {\n if (this.metadataRegistries.some((val) => JSON.stringify(val) === JSON.stringify(registry))) {\n return;\n }\n this.metadataRegistries.push(registry);\n }\n /**\n * addMetadataRegistryFromUri Add the metadata registry by fetching a JSON file from a remote URI, optionally verifying its content hash\n *\n * @param {string} uri URI of the registry to fetch from\n * @param {string?} contentHash SHA256 hash of the resource the `uri` parameter points at.\n * If specified, calculates the hash of the data fetched from `uri` and matches it with provided one.\n * Yields an error upon mismatch.\n *\n */\n static async addMetadataRegistryFromUri(uri, contentHash) {\n const registry = await this.fetchMetadataRegistry(uri, contentHash);\n this.addMetadataRegistry(registry);\n }\n /**\n * buildAuthChain Build an authchain - Zeroth-Descendant Transaction Chain, refer to https://github.com/bitjson/chip-bcmr#zeroth-descendant-transaction-chains\n * The authchain in this implementation is specific to resolve to a valid metadata registry\n *\n * @param {string} options.transactionHash (required) transaction hash from which to build the auth chain\n * @param {Network?} options.network (default=mainnet) network to query the data from\n * @param {boolean?} options.resolveBase (default=false) boolean flag to indicate that autchain building should resolve and verify elements back to base or be stopped at this exact chain element\n * @param {boolean?} options.followToHead (default=true) boolean flag to indicate that autchain building should progress to head or be stopped at this exact chain element\n * @param {ElectrumRawTransaction?} options.rawTx cached raw transaction obtained previously, spares a Fulcrum call\n * @param {TxI[]?} options.historyCache cached address history to be reused if authchain building proceeds with the same address, spares a flurry of Fulcrum calls\n *\n * @returns {AuthChain} returns the resolved authchain\n */\n static async buildAuthChain(options) {\n if (options.network === undefined) {\n options.network = _interface_js__WEBPACK_IMPORTED_MODULE_4__.Network.MAINNET;\n }\n if (options.followToHead === undefined) {\n options.followToHead = true;\n }\n if (options.resolveBase === undefined) {\n options.resolveBase = false;\n }\n const provider = (await (0,_network_Connection_js__WEBPACK_IMPORTED_MODULE_5__.initProvider)(options.network));\n if (options.rawTx === undefined) {\n options.rawTx = await provider.getRawTransactionObject(options.transactionHash);\n }\n // figure out the autchain by moving towards authhead\n const getAuthChainChild = async () => {\n const history = options.historyCache ||\n (await provider.getHistory(options.rawTx.vout[0].scriptPubKey.addresses[0]));\n const thisTx = history.find((val) => val.tx_hash === options.transactionHash);\n let filteredHistory = history.filter((val) => val.height > 0\n ? val.height >= thisTx.height || val.height <= 0\n : val.height <= 0 && val.tx_hash !== thisTx.tx_hash);\n for (const historyTx of filteredHistory) {\n const historyRawTx = await provider.getRawTransactionObject(historyTx.tx_hash);\n const authChainVin = historyRawTx.vin.find((val) => val.txid === options.transactionHash && val.vout === 0);\n // if we've found continuation of authchain, we shall recurse into it\n if (authChainVin) {\n // reuse queried address history if the next element in chain is the same address\n const historyCache = options.rawTx.vout[0].scriptPubKey.addresses[0] ===\n historyRawTx.vout[0].scriptPubKey.addresses[0]\n ? filteredHistory\n : undefined;\n // combine the authchain element with the rest obtained\n return { rawTx: historyRawTx, historyCache };\n }\n }\n return undefined;\n };\n // helper function to enforce the constraints on the 0th output, decode the BCMR's OP_RETURN data\n // returns resolved AuthChainElement\n const makeAuthChainElement = (rawTx, hash) => {\n let opReturns;\n let spends0thOutput = false;\n if (rawTx.hasOwnProperty(\"vout\")) {\n const electrumTransaction = rawTx;\n opReturns = electrumTransaction.vout\n .filter((val) => val.scriptPubKey.type === \"nulldata\")\n .map((val) => val.scriptPubKey.hex);\n spends0thOutput = electrumTransaction.vin.some((val) => val.vout === 0);\n }\n else {\n const libauthTransaction = rawTx;\n opReturns = libauthTransaction.outputs\n .map((val) => (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.binToHex)(val.lockingBytecode))\n .filter((val) => val.indexOf(\"6a\") === 0);\n spends0thOutput = libauthTransaction.inputs.some((val) => val.outpointIndex === 0);\n }\n if (!spends0thOutput) {\n throw new Error(\"Invalid authchain transaction (does not spend 0th output of previous transaction)\");\n }\n const bcmrOpReturns = opReturns.filter((val) => val.indexOf(\"6a0442434d52\") === 0 ||\n val.indexOf(\"6a4c0442434d52\") === 0 ||\n val.indexOf(\"6a4d040042434d52\") === 0 ||\n val.indexOf(\"6a4e0400000042434d52\") === 0);\n if (bcmrOpReturns.length === 0) {\n return {\n txHash: hash,\n contentHash: \"\",\n uri: \"\",\n };\n }\n const opReturnHex = opReturns[0];\n const opReturn = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.hexToBin)(opReturnHex);\n const chunks = [];\n let position = 1;\n // handle direct push, OP_PUSHDATA1, OP_PUSHDATA2;\n // OP_PUSHDATA4 is not supported in OP_RETURNs by consensus\n while (opReturn[position]) {\n let length = 0;\n if (opReturn[position] === 0x4c) {\n length = opReturn[position + 1];\n position += 2;\n }\n else if (opReturn[position] === 0x4d) {\n length = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__.binToNumberUint16LE)(opReturn.slice(position + 1, position + 3));\n position += 3;\n }\n else {\n length = opReturn[position];\n position += 1;\n }\n chunks.push(opReturn.slice(position, position + length));\n position += length;\n }\n if (chunks.length < 2 || chunks.length > 3) {\n throw new Error(`Malformed BCMR output: ${opReturnHex}`);\n }\n const result = {\n txHash: hash,\n contentHash: \"\",\n uri: \"\",\n };\n if (chunks.length === 2) {\n // IPFS Publication Output\n result.contentHash = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.binToHex)(chunks[1]);\n const ipfsCid = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.binToUtf8)(chunks[1]);\n result.uri = `https://dweb.link/ipfs/${ipfsCid}`;\n }\n else {\n // HTTPS Publication Output\n // content hash is in OP_SHA256 byte order per spec\n result.contentHash = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.binToHex)(chunks[1].slice().reverse());\n result.uri = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.binToUtf8)(chunks[2]);\n if (result.uri.indexOf(\"https://\") < 0) {\n result.uri = `https://${result.uri}`;\n }\n }\n return result;\n };\n // make authchain element and combine with the rest obtained\n let element;\n try {\n element = makeAuthChainElement(options.rawTx, options.rawTx.hash);\n }\n catch (error) {\n // special case for cashtoken authchain lookup by categoryId - allow to fail first lookup and inspect the genesis transaction\n // follow authchain to head and look for BCMR outputs\n const child = await getAuthChainChild();\n if (child) {\n return await BCMR.buildAuthChain({\n ...options,\n transactionHash: child.rawTx.hash,\n rawTx: child.rawTx,\n historyCache: child.historyCache,\n });\n }\n else {\n throw error;\n }\n }\n let chainBase = [];\n if (options.resolveBase) {\n // check for accelerated path if \"authchain\" extension is in registry\n const registry = await this.fetchMetadataRegistry(element.uri, element.contentHash);\n if (registry.extensions &&\n registry.extensions[\"authchain\"] &&\n Object.keys(registry.extensions[\"authchain\"]).length) {\n const chainTxArray = Object.values(registry.extensions[\"authchain\"]);\n chainBase = chainTxArray\n .map((tx) => {\n const transactionBin = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.hexToBin)(tx);\n const decoded = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__.decodeTransaction)(transactionBin);\n if (typeof decoded === \"string\") {\n throw new Error(`Error decoding transaction ${JSON.stringify(tx)}, ${decoded}`);\n }\n const hash = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.binToHex)(_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.sha256.hash(_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.sha256.hash(transactionBin)).reverse());\n return { decoded, hash };\n })\n .map(({ decoded, hash }) => makeAuthChainElement(decoded, hash));\n }\n else {\n // simply go back in history towards authhead\n let stop = false;\n let tx = { ...options.rawTx };\n let maxElements = 10;\n while (stop == false || maxElements === 0) {\n const vin = tx.vin.find((val) => val.vout === 0);\n tx = await provider.getRawTransactionObject(vin.txid);\n try {\n const pastElement = makeAuthChainElement(tx, tx.hash);\n chainBase.unshift(pastElement);\n maxElements--;\n }\n catch {\n stop = true;\n }\n }\n }\n }\n // if we follow to head, we need to locate the next transaction spending our 0th output\n // and repeat the building process recursively\n if (options.followToHead) {\n const child = await getAuthChainChild();\n if (child) {\n const chainHead = await BCMR.buildAuthChain({\n transactionHash: child.rawTx.hash,\n network: options.network,\n rawTx: child.rawTx,\n historyCache: child.historyCache,\n followToHead: options.followToHead,\n resolveBase: false,\n });\n // combine the authchain element with the rest obtained\n return [...chainBase, element, ...chainHead].filter((val) => val.uri.length);\n }\n }\n // return the last chain element (or the only found in an edge case)\n return [...chainBase, element].filter((val) => val.uri.length);\n }\n /**\n * addMetadataRegistryAuthChain Add BCMR metadata registry by resolving an authchain\n *\n * @param {string} options.transactionHash (required) transaction hash from which to build the auth chain\n * @param {Network?} options.network (default=mainnet) network to query the data from\n * @param {boolean?} options.followToHead (default=true) boolean flag to indicate that autchain building should progress to head (most recent registry version) or be stopped at this exact chain element\n * @param {ElectrumRawTransaction?} options.rawTx cached raw transaction obtained previously, spares a Fulcrum call\n *\n * @returns {AuthChain} returns the resolved authchain\n */\n static async addMetadataRegistryAuthChain(options) {\n const authChain = await this.buildAuthChain({\n ...options,\n resolveBase: false,\n });\n if (!authChain.length) {\n throw new Error(`There were no BCMR entries in the resolved authchain ${JSON.stringify(authChain, null, 2)}`);\n }\n const registry = await this.fetchMetadataRegistry(authChain.reverse()[0].uri);\n this.addMetadataRegistry(registry);\n return authChain;\n }\n /**\n * getTokenInfo Return the token info (or the identity snapshot as per spec)\n *\n * @param {string} tokenId token id to look up\n *\n * @returns {IdentitySnapshot?} return the info for the token found, otherwise undefined\n */\n static getTokenInfo(tokenId) {\n for (const registry of this.metadataRegistries.slice().reverse()) {\n const history = registry.identities?.[tokenId];\n if (!history) {\n continue;\n }\n const latestIdentityIndex = Object.keys(history)[0];\n if (latestIdentityIndex === undefined) {\n continue;\n }\n return history[latestIdentityIndex];\n }\n return undefined;\n }\n}\n// List of tracked registries\nBCMR.metadataRegistries = [];\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/wallet/Bcmr.ts?");
1638
1638
 
1639
1639
  /***/ }),
1640
1640
 
@@ -1664,7 +1664,7 @@ eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__
1664
1664
  \***************************/
1665
1665
  /***/ ((module, __webpack_exports__, __webpack_require__) => {
1666
1666
 
1667
- eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"RegTestWallet\": () => (/* binding */ RegTestWallet),\n/* harmony export */ \"RegTestWatchWallet\": () => (/* binding */ RegTestWatchWallet),\n/* harmony export */ \"RegTestWifWallet\": () => (/* binding */ RegTestWifWallet),\n/* harmony export */ \"TestNetWallet\": () => (/* binding */ TestNetWallet),\n/* harmony export */ \"TestNetWatchWallet\": () => (/* binding */ TestNetWatchWallet),\n/* harmony export */ \"TestNetWifWallet\": () => (/* binding */ TestNetWifWallet),\n/* harmony export */ \"Wallet\": () => (/* binding */ Wallet),\n/* harmony export */ \"WatchWallet\": () => (/* binding */ WatchWallet),\n/* harmony export */ \"WifWallet\": () => (/* binding */ WifWallet)\n/* harmony export */ });\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/key/hd-key.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_33__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/crypto/default-crypto-instances.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/hex.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/key/key-utils.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/key/wallet-import-format.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_35__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/address/cash-address.js\");\n/* harmony import */ var bip39__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! bip39 */ \"../../node_modules/bip39/src/index.js\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../enum.js */ \"./src/enum.ts\");\n/* harmony import */ var _interface_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../interface.js */ \"./src/interface.ts\");\n/* harmony import */ var _Base_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Base.js */ \"./src/wallet/Base.ts\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./enum.js */ \"./src/wallet/enum.ts\");\n/* harmony import */ var _model_js__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ./model.js */ \"./src/wallet/model.ts\");\n/* harmony import */ var _transaction_Wif_js__WEBPACK_IMPORTED_MODULE_29__ = __webpack_require__(/*! ../transaction/Wif.js */ \"./src/transaction/Wif.ts\");\n/* harmony import */ var _util_asSendRequestObject_js__WEBPACK_IMPORTED_MODULE_30__ = __webpack_require__(/*! ../util/asSendRequestObject.js */ \"./src/util/asSendRequestObject.ts\");\n/* harmony import */ var _util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(/*! ../util/balanceObjectFromSatoshi.js */ \"./src/util/balanceObjectFromSatoshi.ts\");\n/* harmony import */ var _util_checkWifNetwork_js__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ../util/checkWifNetwork.js */ \"./src/util/checkWifNetwork.ts\");\n/* harmony import */ var _util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ../util/deriveCashaddr.js */ \"./src/util/deriveCashaddr.ts\");\n/* harmony import */ var _util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../util/derivePublicKeyHash.js */ \"./src/util/derivePublicKeyHash.ts\");\n/* harmony import */ var _util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../util/checkForEmptySeed.js */ \"./src/util/checkForEmptySeed.ts\");\n/* harmony import */ var _util_sanitizeUnit_js__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(/*! ../util/sanitizeUnit.js */ \"./src/util/sanitizeUnit.ts\");\n/* harmony import */ var _util_sumUtxoValue_js__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(/*! ../util/sumUtxoValue.js */ \"./src/util/sumUtxoValue.ts\");\n/* harmony import */ var _util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_31__ = __webpack_require__(/*! ../util/sumSendRequestAmounts.js */ \"./src/util/sumSendRequestAmounts.ts\");\n/* harmony import */ var _network_getRelayFeeCache_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../network/getRelayFeeCache.js */ \"./src/network/getRelayFeeCache.ts\");\n/* harmony import */ var _Slp_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./Slp.js */ \"./src/wallet/Slp.ts\");\n/* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! axios */ \"../../node_modules/axios/index.js\");\n/* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(axios__WEBPACK_IMPORTED_MODULE_2__);\n/* harmony import */ var _util_bchaddr_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../util/bchaddr.js */ \"../../node_modules/bchaddrjs-slp/src/bchaddr.js\");\n/* harmony import */ var _util_bchaddr_js__WEBPACK_IMPORTED_MODULE_13___default = /*#__PURE__*/__webpack_require__.n(_util_bchaddr_js__WEBPACK_IMPORTED_MODULE_13__);\n/* harmony import */ var _Util_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./Util.js */ \"./src/wallet/Util.ts\");\n/* harmony import */ var _network_index_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../network/index.js */ \"./src/network/default.ts\");\n/* harmony import */ var _util_randomBytes_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../util/randomBytes.js */ \"./src/util/randomBytes.ts\");\n/* harmony import */ var _message_index_js__WEBPACK_IMPORTED_MODULE_34__ = __webpack_require__(/*! ../message/index.js */ \"./src/message/signed.ts\");\n/* harmony import */ var _util_amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(/*! ../util/amountInSatoshi.js */ \"./src/util/amountInSatoshi.ts\");\n/* harmony import */ var _util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ../util/getXPubKey.js */ \"./src/util/getXPubKey.ts\");\n/* harmony import */ var _constant_js__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ../constant.js */ \"./src/constant.ts\");\n/* harmony import */ var _history_electrumTransformer_js__WEBPACK_IMPORTED_MODULE_32__ = __webpack_require__(/*! ../history/electrumTransformer.js */ \"./src/history/electrumTransformer.ts\");\n/* harmony import */ var _Bcmr_js__WEBPACK_IMPORTED_MODULE_28__ = __webpack_require__(/*! ./Bcmr.js */ \"./src/wallet/Bcmr.ts\");\n/* harmony import */ var _qr_Qr_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../qr/Qr.js */ \"./src/qr/Qr.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_Base_js__WEBPACK_IMPORTED_MODULE_3__, _enum_js__WEBPACK_IMPORTED_MODULE_4__, _Slp_js__WEBPACK_IMPORTED_MODULE_6__, _Util_js__WEBPACK_IMPORTED_MODULE_7__, _network_index_js__WEBPACK_IMPORTED_MODULE_9__, _qr_Qr_js__WEBPACK_IMPORTED_MODULE_10__, _util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_12__, _util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_16__, _util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_17__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_18__, _model_js__WEBPACK_IMPORTED_MODULE_20__, _util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_21__, _util_checkWifNetwork_js__WEBPACK_IMPORTED_MODULE_22__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_23__, _util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_25__, _util_amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_27__, _Bcmr_js__WEBPACK_IMPORTED_MODULE_28__, _transaction_Wif_js__WEBPACK_IMPORTED_MODULE_29__, _util_asSendRequestObject_js__WEBPACK_IMPORTED_MODULE_30__, _util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_31__, _history_electrumTransformer_js__WEBPACK_IMPORTED_MODULE_32__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_33__, _message_index_js__WEBPACK_IMPORTED_MODULE_34__]);\n([_Base_js__WEBPACK_IMPORTED_MODULE_3__, _enum_js__WEBPACK_IMPORTED_MODULE_4__, _Slp_js__WEBPACK_IMPORTED_MODULE_6__, _Util_js__WEBPACK_IMPORTED_MODULE_7__, _network_index_js__WEBPACK_IMPORTED_MODULE_9__, _qr_Qr_js__WEBPACK_IMPORTED_MODULE_10__, _util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_12__, _util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_16__, _util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_17__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_18__, _model_js__WEBPACK_IMPORTED_MODULE_20__, _util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_21__, _util_checkWifNetwork_js__WEBPACK_IMPORTED_MODULE_22__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_23__, _util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_25__, _util_amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_27__, _Bcmr_js__WEBPACK_IMPORTED_MODULE_28__, _transaction_Wif_js__WEBPACK_IMPORTED_MODULE_29__, _util_asSendRequestObject_js__WEBPACK_IMPORTED_MODULE_30__, _util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_31__, _history_electrumTransformer_js__WEBPACK_IMPORTED_MODULE_32__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_33__, _message_index_js__WEBPACK_IMPORTED_MODULE_34__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n//#region Imports\n// Stable\n\n// Unstable?\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n//#endregion Imports\n/**\n * Class to manage a bitcoin cash wallet.\n */\nclass Wallet extends _Base_js__WEBPACK_IMPORTED_MODULE_3__.BaseWallet {\n //#endregion\n //#region Constructors and Statics\n constructor(name = \"\", network = _enum_js__WEBPACK_IMPORTED_MODULE_4__.NetworkType.Mainnet, walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Seed) {\n super(name, network, walletType);\n this.derivationPath = \"m/44'/0'/0'/0/0\";\n this.parentDerivationPath = \"m/44'/0'/0'\";\n this._slpAware = false; // a flag which activates utxo checking against an external slp indexer\n this._slpSemiAware = false; // a flag which requires an utxo to have more than 546 sats to be spendable and counted in the balance\n this.fromId = async (walletId) => {\n let [walletType, networkGiven, arg1] = walletId.split(\":\");\n if (this.network != networkGiven) {\n throw Error(`Network prefix ${networkGiven} to a ${this.network} wallet`);\n }\n // \"wif:regtest:cNfsPtqN2bMRS7vH5qd8tR8GMvgXyL5BjnGAKgZ8DYEiCrCCQcP6\"\n if (walletType === \"wif\") {\n return this.fromWIF(arg1);\n }\n return super.fromId(walletId);\n };\n this.networkPrefix = _enum_js__WEBPACK_IMPORTED_MODULE_4__.prefixFromNetworkMap[this.network];\n }\n //#region Accessors\n // interface to slp functions. see Slp.ts\n get slp() {\n if (!this._slp) {\n this._slp = new _Slp_js__WEBPACK_IMPORTED_MODULE_6__.Slp(this);\n this._slpAware = true;\n }\n return this._slp;\n }\n // interface to slp functions. see Slp.ts\n static get slp() {\n return _Slp_js__WEBPACK_IMPORTED_MODULE_6__.Slp;\n }\n // interface to util functions. see Util.ts\n get util() {\n if (!this._util) {\n this._util = new _Util_js__WEBPACK_IMPORTED_MODULE_7__.Util(this);\n }\n return this._util;\n }\n // interface to util util. see Util.Util\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_7__.Util;\n }\n slpAware(value = true) {\n this._slpAware = value;\n return this;\n }\n slpSemiAware(value = true) {\n this._slpSemiAware = value;\n return this;\n }\n getNetworkProvider(network = _interface_js__WEBPACK_IMPORTED_MODULE_8__.Network.MAINNET) {\n return (0,_network_index_js__WEBPACK_IMPORTED_MODULE_9__.getNetworkProvider)(network);\n }\n /**\n * getTokenDepositAddress - get a cashtoken aware wallet deposit address\n *\n * @returns The cashtoken aware deposit address as a string\n */\n getTokenDepositAddress() {\n return this.tokenaddr;\n }\n /**\n * getDepositQr - get an address qrcode, encoded for display on the web\n *\n * @returns The qrcode for the token aware address\n */\n getTokenDepositQr() {\n return (0,_qr_Qr_js__WEBPACK_IMPORTED_MODULE_10__.qrAddress)(this.getTokenDepositAddress());\n }\n /**\n * explorerUrl Web url to a transaction on a block explorer\n *\n * @param txId transaction Id\n * @returns Url string\n */\n explorerUrl(txId) {\n const explorerUrlMap = {\n mainnet: \"https://blockchair.com/bitcoin-cash/transaction/\",\n testnet: \"https://www.blockchain.com/bch-testnet/tx/\",\n regtest: \"\",\n };\n return explorerUrlMap[this.network] + txId;\n }\n // Return wallet info\n getInfo() {\n return {\n cashaddr: this.cashaddr,\n tokenaddr: this.tokenaddr,\n isTestnet: this.isTestnet,\n name: this.name,\n network: this.network,\n seed: this.mnemonic ? this.getSeed().seed : undefined,\n derivationPath: this.mnemonic ? this.getSeed().derivationPath : undefined,\n parentDerivationPath: this.mnemonic\n ? this.getSeed().parentDerivationPath\n : undefined,\n parentXPubKey: this.parentXPubKey ? this.parentXPubKey : undefined,\n publicKey: this.publicKey ? (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.binToHex)(this.publicKey) : undefined,\n publicKeyHash: (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.binToHex)(this.publicKeyHash),\n privateKey: this.privateKey ? (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.binToHex)(this.privateKey) : undefined,\n privateKeyWif: this.privateKeyWif,\n walletId: this.toString(),\n walletDbEntry: this.toDbString(),\n };\n }\n // returns the public key hash for an address\n getPublicKey(hex = false) {\n if (this.publicKey) {\n return hex ? (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.binToHex)(this.publicKey) : this.publicKey;\n }\n else {\n throw Error(\"The public key for this wallet is not known, perhaps the wallet was created to watch the *hash* of a public key? i.e. a cashaddress.\");\n }\n }\n // returns the public key hash for an address\n getPublicKeyCompressed(hex = false) {\n if (this.publicKeyCompressed) {\n return hex\n ? (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.binToHex)(this.publicKeyCompressed)\n : this.publicKeyCompressed;\n }\n else {\n throw Error(\"The compressed public key for this wallet is not known, perhaps the wallet was created to watch the *hash* of a public key? i.e. a cashaddress.\");\n }\n }\n // returns the public key hash for an address\n getPublicKeyHash(hex = false) {\n if (this.publicKeyHash) {\n return hex ? (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.binToHex)(this.publicKeyHash) : this.publicKeyHash;\n }\n else {\n throw Error(\"The public key hash for this wallet is not known. If this wallet was created from the constructor directly, calling the deriveInfo() function may help. \");\n }\n }\n /**\n * fromWIF - create a wallet using the private key supplied in `Wallet Import Format`\n *\n * @param wif WIF encoded private key string\n *\n * @returns instantiated wallet\n */\n static async fromWIF(wif) {\n return new this().fromWIF(wif);\n }\n /**\n * fromCashaddr - create a watch-only wallet in the network derived from the address\n *\n * such kind of wallet does not have a private key and is unable to spend any funds\n * however it still allows to use many utility functions such as getting and watching balance, etc.\n *\n * @param address cashaddress of a wallet\n *\n * @returns instantiated wallet\n */\n static async fromCashaddr(address) {\n const prefix = (0,_util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_12__.derivePrefix)(address);\n const networkType = _enum_js__WEBPACK_IMPORTED_MODULE_4__.networkPrefixMap[prefix];\n return new this(\"\", networkType, _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Watch).watchOnly(address);\n }\n /**\n * fromTokenaddr - create a watch-only wallet in the network derived from the address\n *\n * such kind of wallet does not have a private key and is unable to spend any funds\n * however it still allows to use many utility functions such as getting and watching balance, etc.\n *\n * @param address token aware cashaddress of a wallet\n *\n * @returns instantiated wallet\n */\n static async fromTokenaddr(address) {\n const prefix = (0,_util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_12__.derivePrefix)(address);\n const networkType = _enum_js__WEBPACK_IMPORTED_MODULE_4__.networkPrefixMap[prefix];\n return new this(\"\", networkType, _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Watch).watchOnly(address);\n }\n /**\n * fromSlpaddr - create an SLP aware watch-only wallet in the network derived from the address\n *\n * such kind of wallet does not have a private key and is unable to spend any funds\n * however it still allows to use many utility functions such as getting and watching balance, etc.\n *\n * @param address slpaddress of a wallet\n *\n * @returns instantiated wallet\n */\n static async fromSlpaddr(address) {\n return this.fromCashaddr((0,_util_bchaddr_js__WEBPACK_IMPORTED_MODULE_13__.toCashAddress)(address));\n }\n //#endregion Constructors and Statics\n //#region Protected implementations\n async generate() {\n if (this.walletType === _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Wif) {\n return await this._generateWif();\n }\n else if (this.walletType === _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Watch) {\n return this;\n }\n else if (this.walletType === _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Hd) {\n throw Error(\"Not implemented\");\n }\n else if (this.walletType === _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Seed) {\n return await this._generateMnemonic();\n }\n else {\n console.log(this.walletType);\n throw Error(`Could not determine walletType: ${this.walletType}`);\n }\n }\n async _generateWif() {\n if (!this.privateKey) {\n this.privateKey = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_14__.generatePrivateKey)(() => (0,_util_randomBytes_js__WEBPACK_IMPORTED_MODULE_15__.generateRandomBytes)(32));\n }\n return this.deriveInfo();\n }\n async _generateMnemonic() {\n this.mnemonic = (0,bip39__WEBPACK_IMPORTED_MODULE_0__.generateMnemonic)();\n if (this.mnemonic.length == 0)\n throw Error(\"refusing to create wallet from empty mnemonic\");\n let seed = (0,bip39__WEBPACK_IMPORTED_MODULE_0__.mnemonicToSeedSync)(this.mnemonic);\n (0,_util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_16__.checkForEmptySeed)(seed);\n let network = this.isTestnet ? \"testnet\" : \"mainnet\";\n this.parentXPubKey = await (0,_util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_17__.getXPubKey)(seed, this.parentDerivationPath, network);\n let hdNode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_18__.deriveHdPrivateNodeFromSeed)(seed);\n if (!hdNode.valid) {\n throw Error(\"Invalid private key derived from mnemonic seed\");\n }\n let zerothChild = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_18__.deriveHdPath)(hdNode, this.derivationPath);\n if (typeof zerothChild === \"string\") {\n throw Error(zerothChild);\n }\n this.privateKey = zerothChild.privateKey;\n this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Seed;\n return await this.deriveInfo();\n }\n async getXPubKeys(paths) {\n if (this.mnemonic) {\n if (paths) {\n let xPubKeys = await this.deriveHdPaths(paths);\n return [xPubKeys];\n }\n else {\n return await this.deriveHdPaths(_constant_js__WEBPACK_IMPORTED_MODULE_19__.DERIVATION_PATHS);\n }\n }\n else {\n throw Error(\"xpubkeys can only be derived from seed type wallets.\");\n }\n }\n // Initialize wallet from a mnemonic phrase\n async fromSeed(mnemonic, derivationPath) {\n this.mnemonic = mnemonic.trim().toLowerCase();\n if (this.mnemonic.length == 0)\n throw Error(\"refusing to create wallet from empty mnemonic\");\n let seed = (0,bip39__WEBPACK_IMPORTED_MODULE_0__.mnemonicToSeedSync)(this.mnemonic);\n (0,_util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_16__.checkForEmptySeed)(seed);\n let hdNode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_18__.deriveHdPrivateNodeFromSeed)(seed);\n if (!hdNode.valid) {\n throw Error(\"Invalid private key derived from mnemonic seed\");\n }\n if (derivationPath) {\n this.derivationPath = derivationPath;\n // If the derivation path is for the first account child, set the parent derivation path\n let path = derivationPath.split(\"/\");\n if (path.slice(-2).join(\"/\") == \"0/0\") {\n this.parentDerivationPath = path.slice(0, -2).join(\"/\");\n }\n }\n let zerothChild = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_18__.deriveHdPath)(hdNode, this.derivationPath);\n if (typeof zerothChild === \"string\") {\n throw Error(zerothChild);\n }\n this.privateKey = zerothChild.privateKey;\n let network = this.isTestnet ? \"testnet\" : \"mainnet\";\n this.parentXPubKey = await (0,_util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_17__.getXPubKey)(seed, this.parentDerivationPath, network);\n this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Seed;\n await this.deriveInfo();\n return this;\n }\n // Get common xpub paths from zerothChild privateKey\n async deriveHdPaths(hdPaths) {\n if (!this.mnemonic)\n throw Error(\"refusing to create wallet from empty mnemonic\");\n let seed = (0,bip39__WEBPACK_IMPORTED_MODULE_0__.mnemonicToSeedSync)(this.mnemonic);\n (0,_util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_16__.checkForEmptySeed)(seed);\n let hdNode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_18__.deriveHdPrivateNodeFromSeed)(seed);\n if (!hdNode.valid) {\n throw Error(\"Invalid private key derived from mnemonic seed\");\n }\n let result = [];\n for (const path of hdPaths) {\n if (path === \"m\") {\n throw Error(\"Storing or sharing of parent public key may lead to loss of funds. Storing or sharing *root* parent public keys is strongly discouraged, although all parent keys have risk. See: https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#implications\");\n }\n let childNode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_18__.deriveHdPath)(hdNode, path);\n if (typeof childNode === \"string\") {\n throw Error(childNode);\n }\n let node = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_18__.deriveHdPublicNode)(childNode);\n if (typeof node === \"string\") {\n throw Error(node);\n }\n let xPubKey = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_18__.encodeHdPublicKey)({\n network: this.network,\n node: node,\n });\n let key = new _model_js__WEBPACK_IMPORTED_MODULE_20__.XPubKey({\n path: path,\n xPubKey: xPubKey,\n });\n result.push(await key.ready());\n }\n return await Promise.all(result).then((result) => {\n return result;\n });\n }\n // Initialize a watch only wallet from a cash addr\n async watchOnly(address) {\n this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Watch;\n let addressComponents = address.split(\":\");\n let addressPrefix, addressBase;\n if (addressComponents.length === 1) {\n addressBase = addressComponents.shift();\n addressPrefix = (0,_util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_12__.derivePrefix)(addressBase);\n }\n else {\n addressPrefix = addressComponents.shift();\n addressBase = addressComponents.shift();\n if (addressPrefix in _enum_js__WEBPACK_IMPORTED_MODULE_4__.networkPrefixMap) {\n if (_enum_js__WEBPACK_IMPORTED_MODULE_4__.networkPrefixMap[addressPrefix] != this.network) {\n throw Error(`a ${addressPrefix} address cannot be watched from a ${this.network} Wallet`);\n }\n }\n }\n this.cashaddr = `${addressPrefix}:${addressBase}`;\n this.address = this.cashaddr;\n this.publicKeyHash = (0,_util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_12__.derivePublicKeyHash)(this.cashaddr);\n this.tokenaddr = (0,_util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_21__.deriveTokenaddr)(this.publicKeyHash, this.networkPrefix);\n return this;\n }\n // Initialize wallet from Wallet Import Format\n async fromWIF(secret) {\n (0,_util_checkWifNetwork_js__WEBPACK_IMPORTED_MODULE_22__.checkWifNetwork)(secret, this.network);\n let wifResult = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_23__.decodePrivateKeyWif)(secret);\n if (typeof wifResult === \"string\") {\n throw Error(wifResult);\n }\n let resultData = wifResult;\n this.privateKey = resultData.privateKey;\n this.privateKeyWif = secret;\n this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Wif;\n await this.deriveInfo();\n return this;\n }\n async newRandom(name, dbName) {\n dbName = dbName ? dbName : this.networkPrefix;\n return super.newRandom(name, dbName);\n }\n async named(name, dbName, forceNew = false) {\n dbName = dbName ? dbName : this.networkPrefix;\n return super.named(name, dbName, forceNew);\n }\n async replaceNamed(name, walletId, dbName) {\n dbName = dbName ? dbName : this.networkPrefix;\n return super.replaceNamed(name, walletId, dbName);\n }\n async namedExists(name, dbName) {\n dbName = dbName ? dbName : this.networkPrefix;\n return super.namedExists(name, dbName);\n }\n //#endregion Protected Implementations\n //#region Serialization\n // Returns the serialized wallet as a string\n // If storing in a database, set asNamed to false to store secrets\n // In all other cases, the a named wallet is deserialized from the database\n // by the name key\n toString() {\n const result = super.toString();\n if (result)\n return result;\n if (this.walletType === _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Wif) {\n return `${this.walletType}:${this.network}:${this.privateKeyWif}`;\n }\n throw Error(\"toString unsupported wallet type\");\n }\n //\n toDbString() {\n const result = super.toDbString();\n if (result)\n return result;\n if (this.walletType === _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Wif) {\n return `${this.walletType}:${this.network}:${this.privateKeyWif}`;\n }\n throw Error(\"toDbString unsupported wallet type\");\n }\n //#endregion Serialization\n //#region Funds\n //\n async getAddressUtxos(address) {\n if (!address) {\n address = this.cashaddr;\n }\n if (this._slpAware) {\n const [bchUtxos, slpOutpoints] = await Promise.all([\n this.provider.getUtxos(address),\n this.slp.getSlpOutpoints(),\n ]);\n return bchUtxos.filter((bchutxo) => slpOutpoints.findIndex((slpOutpoint) => `${bchutxo.txid}:${bchutxo.vout}` === slpOutpoint) === -1);\n }\n else if (this._slpSemiAware) {\n const bchUtxos = await this.provider.getUtxos(address);\n return bchUtxos.filter((bchutxo) => bchutxo.satoshis > _constant_js__WEBPACK_IMPORTED_MODULE_19__.DUST_UTXO_THRESHOLD);\n }\n else {\n return await this.provider.getUtxos(address);\n }\n }\n /**\n * utxos Get unspent outputs for the wallet\n *\n */\n async getUtxos() {\n if (!this.cashaddr) {\n throw Error(\"Attempted to get utxos without an address\");\n }\n return await this.getAddressUtxos(this.cashaddr);\n }\n // gets wallet balance in sats, bch and usd\n async getBalance(rawUnit, usdPriceCache = true) {\n if (rawUnit) {\n const unit = (0,_util_sanitizeUnit_js__WEBPACK_IMPORTED_MODULE_24__.sanitizeUnit)(rawUnit);\n return await (0,_util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_25__.balanceFromSatoshi)(await this.getBalanceFromProvider(), unit, usdPriceCache);\n }\n else {\n return await (0,_util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_25__.balanceResponseFromSatoshi)(await this.getBalanceFromProvider(), usdPriceCache);\n }\n }\n // Gets balance by summing value in all utxos in stats\n async getBalanceFromUtxos() {\n const utxos = (await this.getAddressUtxos(this.cashaddr)).filter((val) => val.token === undefined);\n return (0,_util_sumUtxoValue_js__WEBPACK_IMPORTED_MODULE_26__.sumUtxoValue)(utxos);\n }\n // Gets balance from fulcrum\n async getBalanceFromProvider() {\n // Fulcrum reports balance of all utxos, including tokens, which is undesirable\n // // TODO not sure why getting the balance from a provider doesn't work\n // if (this._slpAware || this._slpSemiAware) {\n // return await this.getBalanceFromUtxos();\n // } else {\n // return await this.provider!.getBalance(this.cashaddr!);\n // }\n // FIXME\n return this.getBalanceFromUtxos();\n }\n // watching for any transaction hash of this wallet\n watchAddress(callback) {\n return this.provider.watchAddress(this.getDepositAddress(), callback);\n }\n // watching for any transaction of this wallet\n watchAddressTransactions(callback) {\n return this.provider.watchAddressTransactions(this.getDepositAddress(), callback);\n }\n // watching for cashtoken transaction of this wallet\n watchAddressTokenTransactions(callback) {\n return this.provider.watchAddressTokenTransactions(this.getDepositAddress(), callback);\n }\n // sets up a callback to be called upon wallet's balance change\n // can be cancelled by calling the function returned from this one\n watchBalance(callback) {\n return this.provider.watchAddressStatus(this.getDepositAddress(), async (_status) => {\n const balance = (await this.getBalance());\n callback(balance);\n });\n }\n // sets up a callback to be called upon wallet's BCH or USD balance change\n // if BCH balance does not change, the callback will be triggered every\n // @param `usdPriceRefreshInterval` milliseconds by polling for new BCH USD price\n // Since we want to be most sensitive to usd value change, we do not use the cached exchange rates\n // can be cancelled by calling the function returned from this one\n watchBalanceUsd(callback, usdPriceRefreshInterval = 30000) {\n let usdPrice = -1;\n const _callback = async () => {\n const balance = (await this.getBalance(undefined, false));\n if (usdPrice !== balance.usd) {\n usdPrice = balance.usd;\n callback(balance);\n }\n };\n const watchCancel = this.provider.watchAddressStatus(this.getDepositAddress(), _callback);\n const interval = setInterval(_callback, usdPriceRefreshInterval);\n return async () => {\n await watchCancel();\n clearInterval(interval);\n };\n }\n // waits for address balance to be greater than or equal to the target value\n // this call halts the execution\n async waitForBalance(value, rawUnit = _enum_js__WEBPACK_IMPORTED_MODULE_4__.UnitEnum.BCH) {\n return new Promise(async (resolve) => {\n const watchCancel = this.watchBalance(async (balance) => {\n const satoshiBalance = await (0,_util_amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_27__.amountInSatoshi)(value, rawUnit);\n if (balance.sat >= satoshiBalance) {\n await watchCancel();\n resolve(balance);\n }\n });\n });\n }\n // sets up a callback to be called upon wallet's token balance change\n // can be cancelled by calling the function returned from this one\n watchTokenBalance(tokenId, callback) {\n let previous = undefined;\n return this.provider.watchAddressStatus(this.getDepositAddress(), async (_status) => {\n const balance = await this.getTokenBalance(tokenId);\n if (previous != balance) {\n callback(balance);\n }\n previous = balance;\n });\n }\n // waits for address token balance to be greater than or equal to the target amount\n // this call halts the execution\n async waitForTokenBalance(tokenId, amount) {\n return new Promise(async (resolve) => {\n const watchCancel = this.watchTokenBalance(tokenId, async (balance) => {\n if (balance >= amount) {\n await watchCancel();\n resolve(balance);\n }\n });\n });\n }\n async getTokenInfo(tokenId) {\n return _Bcmr_js__WEBPACK_IMPORTED_MODULE_28__.BCMR.getTokenInfo(tokenId);\n }\n async _getMaxAmountToSend(params = {\n outputCount: 1,\n options: {},\n }) {\n if (!this.privateKey && params.options?.buildUnsigned !== true) {\n throw Error(\"Couldn't get network or private key for wallet.\");\n }\n if (!this.cashaddr) {\n throw Error(\"attempted to send without a cashaddr\");\n }\n if (params.options && params.options.slpAware) {\n this._slpAware = true;\n }\n if (params.options && params.options.slpSemiAware) {\n this._slpSemiAware = true;\n }\n let feePaidBy;\n if (params.options && params.options.feePaidBy) {\n feePaidBy = params.options.feePaidBy;\n }\n else {\n feePaidBy = _enum_js__WEBPACK_IMPORTED_MODULE_5__.FeePaidByEnum.change;\n }\n // get inputs\n let utxos;\n if (params.options && params.options.utxoIds) {\n utxos = params.options.utxoIds.map((utxoId) => typeof utxoId === \"string\" ? (0,_model_js__WEBPACK_IMPORTED_MODULE_20__.fromUtxoId)(utxoId) : utxoId);\n }\n else {\n utxos = (await this.getAddressUtxos(this.cashaddr)).filter((utxo) => !utxo.token);\n }\n // Get current height to assure recently mined coins are not spent.\n const bestHeight = await this.provider.getBlockHeight();\n // simulate outputs using the sender's address\n const sendRequest = new _model_js__WEBPACK_IMPORTED_MODULE_20__.SendRequest({\n cashaddr: this.cashaddr,\n value: 100,\n unit: \"sat\",\n });\n const sendRequests = Array(params.outputCount)\n .fill(0)\n .map(() => sendRequest);\n const fundingUtxos = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_29__.getSuitableUtxos)(utxos, undefined, bestHeight, feePaidBy, sendRequests);\n const relayFeePerByteInSatoshi = await (0,_network_getRelayFeeCache_js__WEBPACK_IMPORTED_MODULE_1__.getRelayFeeCache)(this.provider);\n const fee = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_29__.getFeeAmount)({\n utxos: fundingUtxos,\n sendRequests: sendRequests,\n privateKey: this.privateKey ?? Uint8Array.from([]),\n sourceAddress: this.cashaddr,\n relayFeePerByteInSatoshi: relayFeePerByteInSatoshi,\n slpOutputs: [],\n feePaidBy: feePaidBy,\n });\n const spendableAmount = (0,_util_sumUtxoValue_js__WEBPACK_IMPORTED_MODULE_26__.sumUtxoValue)(fundingUtxos);\n let result = spendableAmount - fee;\n if (result < 0) {\n result = 0;\n }\n return { value: result, utxos: fundingUtxos };\n }\n async getMaxAmountToSend(params = {\n outputCount: 1,\n options: {},\n }) {\n const { value: result } = await this._getMaxAmountToSend(params);\n return await (0,_util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_25__.balanceResponseFromSatoshi)(result);\n }\n /**\n * send Send some amount to an address\n * this function processes the send requests, encodes the transaction, sends it to the network\n * @returns (depending on the options parameter) the transaction id, new address balance and a link to the transaction on the blockchain explorer\n *\n * This is a first class function with REST analog, maintainers should strive to keep backward-compatibility\n *\n */\n async send(requests, options) {\n const { encodedTransaction, tokenIds, sourceOutputs } = await this.encodeTransaction(requests, undefined, options);\n const resp = new _model_js__WEBPACK_IMPORTED_MODULE_20__.SendResponse({});\n resp.tokenIds = tokenIds;\n if (options?.buildUnsigned !== true) {\n const txId = await this.submitTransaction(encodedTransaction, options?.awaitTransactionPropagation === undefined ||\n options?.awaitTransactionPropagation === true);\n resp.txId = txId;\n resp.explorerUrl = this.explorerUrl(resp.txId);\n if (options?.queryBalance === undefined ||\n options?.queryBalance === true) {\n resp.balance = (await this.getBalance());\n }\n }\n else {\n resp.unsignedTransaction = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.binToHex)(encodedTransaction);\n resp.sourceOutputs = sourceOutputs;\n }\n return resp;\n }\n /**\n * sendMax Send all available funds to a destination cash address\n *\n * @param {string} cashaddr destination cash address\n * @param {SendRequestOptionsI} options Options of the send requests\n *\n * @returns (depending on the options parameter) the transaction id, new address balance and a link to the transaction on the blockchain explorer\n */\n async sendMax(cashaddr, options) {\n return await this.sendMaxRaw(cashaddr, options);\n }\n /**\n * sendMaxRaw (internal) Send all available funds to a destination cash address\n *\n * @param {string} cashaddr destination cash address\n * @param {SendRequestOptionsI} options Options of the send requests\n *\n * @returns the transaction id sent to the network\n */\n async sendMaxRaw(cashaddr, options) {\n const { value: maxSpendableAmount, utxos } = await this._getMaxAmountToSend({\n outputCount: 1,\n options: options,\n });\n if (!options) {\n options = {};\n }\n options.utxoIds = utxos;\n const sendRequest = new _model_js__WEBPACK_IMPORTED_MODULE_20__.SendRequest({\n cashaddr: cashaddr,\n value: maxSpendableAmount,\n unit: \"sat\",\n });\n const { encodedTransaction, tokenIds, sourceOutputs } = await this.encodeTransaction([sendRequest], true, options);\n const resp = new _model_js__WEBPACK_IMPORTED_MODULE_20__.SendResponse({});\n resp.tokenIds = tokenIds;\n if (options?.buildUnsigned !== true) {\n const txId = await this.submitTransaction(encodedTransaction, options?.awaitTransactionPropagation === undefined ||\n options?.awaitTransactionPropagation === true);\n resp.txId = txId;\n resp.explorerUrl = this.explorerUrl(resp.txId);\n if (options?.queryBalance === undefined ||\n options?.queryBalance === true) {\n resp.balance = (await this.getBalance());\n }\n }\n else {\n resp.unsignedTransaction = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.binToHex)(encodedTransaction);\n resp.sourceOutputs = sourceOutputs;\n }\n return resp;\n }\n /**\n * encodeTransaction Encode and sign a transaction given a list of sendRequests, options and estimate fees.\n * @param {SendRequest[]} sendRequests SendRequests\n * @param {boolean} discardChange=false\n * @param {SendRequestOptionsI} options Options of the send requests\n */\n async encodeTransaction(requests, discardChange = false, options) {\n let sendRequests = (0,_util_asSendRequestObject_js__WEBPACK_IMPORTED_MODULE_30__.asSendRequestObject)(requests);\n if (!this.privateKey && options?.buildUnsigned !== true) {\n throw new Error(`Wallet ${this.name} is missing either a network or private key`);\n }\n if (!this.cashaddr) {\n throw Error(\"attempted to send without a cashaddr\");\n }\n if (options && options.slpAware) {\n this._slpAware = true;\n }\n if (options && options.slpSemiAware) {\n this._slpSemiAware = true;\n }\n let feePaidBy;\n if (options && options.feePaidBy) {\n feePaidBy = options.feePaidBy;\n }\n else {\n feePaidBy = _enum_js__WEBPACK_IMPORTED_MODULE_5__.FeePaidByEnum.change;\n }\n let changeAddress;\n if (options && options.changeAddress) {\n changeAddress = options.changeAddress;\n }\n else {\n changeAddress = this.cashaddr;\n }\n let checkTokenQuantities = true;\n if (options && options.checkTokenQuantities === false) {\n checkTokenQuantities = false;\n }\n // get inputs from options or query all inputs\n let utxos;\n if (options && options.utxoIds) {\n utxos = options.utxoIds.map((utxoId) => typeof utxoId === \"string\" ? (0,_model_js__WEBPACK_IMPORTED_MODULE_20__.fromUtxoId)(utxoId) : utxoId);\n }\n else {\n utxos = await this.getAddressUtxos(this.cashaddr);\n }\n // filter out token utxos if there are no token requests\n if (checkTokenQuantities &&\n !sendRequests.some((val) => val instanceof _model_js__WEBPACK_IMPORTED_MODULE_20__.TokenSendRequest)) {\n utxos = utxos.filter((val) => !val.token);\n }\n const addTokenChangeOutputs = (inputs, outputs) => {\n // allow for implicit token burn if the total amount sent is less than user had\n // allow for token genesis, creating more tokens than we had before (0)\n if (!checkTokenQuantities) {\n return;\n }\n const allTokenInputs = inputs.filter((val) => val.token);\n const allTokenOutputs = outputs.filter((val) => val instanceof _model_js__WEBPACK_IMPORTED_MODULE_20__.TokenSendRequest);\n const tokenIds = allTokenOutputs\n .map((val) => val.tokenId)\n .filter((val, idx, arr) => arr.indexOf(val) === idx);\n for (let tokenId of tokenIds) {\n const tokenInputs = allTokenInputs.filter((val) => val.token?.tokenId === tokenId);\n const inputAmountSum = tokenInputs.reduce((prev, cur) => prev + cur.token.amount, 0);\n const tokenOutputs = allTokenOutputs.filter((val) => val.tokenId === tokenId);\n const outputAmountSum = tokenOutputs.reduce((prev, cur) => prev + cur.amount, 0);\n const change = inputAmountSum - outputAmountSum;\n if (change < 0) {\n throw new Error(\"Not enough token amount to send\");\n }\n if (change > 0) {\n outputs.push(new _model_js__WEBPACK_IMPORTED_MODULE_20__.TokenSendRequest({\n cashaddr: changeAddress || this.tokenaddr,\n amount: change,\n tokenId: tokenId,\n commitment: tokenOutputs[0].commitment,\n capability: tokenOutputs[0].capability,\n value: tokenOutputs[0].value,\n }));\n }\n }\n };\n addTokenChangeOutputs(utxos, sendRequests);\n const bestHeight = await this.provider.getBlockHeight();\n const spendAmount = await (0,_util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_31__.sumSendRequestAmounts)(sendRequests);\n if (utxos.length === 0) {\n throw Error(\"There were no Unspent Outputs\");\n }\n if (typeof spendAmount !== \"bigint\") {\n throw Error(\"Couldn't get spend amount when building transaction\");\n }\n const relayFeePerByteInSatoshi = await (0,_network_getRelayFeeCache_js__WEBPACK_IMPORTED_MODULE_1__.getRelayFeeCache)(this.provider);\n const feeEstimate = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_29__.getFeeAmount)({\n utxos: utxos,\n sendRequests: sendRequests,\n privateKey: this.privateKey ?? Uint8Array.from([]),\n sourceAddress: this.cashaddr,\n relayFeePerByteInSatoshi: relayFeePerByteInSatoshi,\n slpOutputs: [],\n feePaidBy: feePaidBy,\n });\n const fundingUtxos = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_29__.getSuitableUtxos)(utxos, BigInt(spendAmount) + BigInt(feeEstimate), bestHeight, feePaidBy, sendRequests, options?.ensureUtxos || [], options?.tokenOperation);\n if (fundingUtxos.length === 0) {\n throw Error(\"The available inputs couldn't satisfy the request with fees\");\n }\n const fee = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_29__.getFeeAmount)({\n utxos: fundingUtxos,\n sendRequests: sendRequests,\n privateKey: this.privateKey ?? Uint8Array.from([]),\n sourceAddress: this.cashaddr,\n relayFeePerByteInSatoshi: relayFeePerByteInSatoshi,\n slpOutputs: [],\n feePaidBy: feePaidBy,\n });\n const { encodedTransaction, sourceOutputs } = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_29__.buildEncodedTransaction)({\n inputs: fundingUtxos,\n outputs: sendRequests,\n signingKey: this.privateKey ?? Uint8Array.from([]),\n sourceAddress: this.cashaddr,\n fee,\n discardChange,\n slpOutputs: [],\n feePaidBy,\n changeAddress,\n buildUnsigned: options?.buildUnsigned === true,\n });\n const tokenIds = [\n ...fundingUtxos\n .filter((val) => val.token?.tokenId)\n .map((val) => val.token.tokenId),\n ...sendRequests\n .filter((val) => val instanceof _model_js__WEBPACK_IMPORTED_MODULE_20__.TokenSendRequest)\n .map((val) => val.tokenId),\n ].filter((value, index, array) => array.indexOf(value) === index);\n return { encodedTransaction, tokenIds, sourceOutputs };\n }\n async signUnsignedTransaction(transaction, sourceOutputs) {\n if (!this.privateKey) {\n throw Error(\"Can not sign a transaction with watch-only wallet.\");\n }\n return (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_29__.signUnsignedTransaction)(transaction, sourceOutputs, this.privateKey);\n }\n // Submit a raw transaction\n async submitTransaction(transaction, awaitPropagation = true) {\n if (!this.provider) {\n throw Error(\"Wallet network provider was not initialized\");\n }\n let rawTransaction = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.binToHex)(transaction);\n return await this.provider.sendRawTransaction(rawTransaction, awaitPropagation);\n }\n // gets transaction history of this wallet\n async getRawHistory() {\n return await this.provider.getHistory(this.cashaddr);\n }\n // gets transaction history of this wallet\n async getHistory(unit, start, count, collapseChange) {\n return (0,_history_electrumTransformer_js__WEBPACK_IMPORTED_MODULE_32__.getAddressHistory)(this.cashaddr, this.provider, unit, start, count, collapseChange);\n }\n // gets last transaction of this wallet\n async getLastTransaction(confirmedOnly = false) {\n let history = await this.getRawHistory();\n if (confirmedOnly) {\n history = history.filter((val) => val.height > 0);\n }\n if (!history.length) {\n return null;\n }\n const [lastTx] = history.slice(-1);\n return this.provider.getRawTransactionObject(lastTx.tx_hash);\n }\n // waits for next transaction, program execution is halted\n async waitForTransaction(options = {\n getTransactionInfo: true,\n getBalance: false,\n txHash: undefined,\n }) {\n if (options.getTransactionInfo === undefined) {\n options.getTransactionInfo = true;\n }\n return new Promise(async (resolve) => {\n let txHashSeen = false;\n const makeResponse = async (txHash) => {\n const response = {};\n const promises = [undefined, undefined];\n if (options.getBalance === true) {\n promises[0] = this.getBalance();\n }\n if (options.getTransactionInfo === true) {\n if (!txHash) {\n promises[1] = this.getLastTransaction();\n }\n else {\n promises[1] = this.provider.getRawTransactionObject(txHash);\n }\n }\n const result = await Promise.all(promises);\n response.balance = result[0];\n response.transactionInfo = result[1];\n return response;\n };\n // waiting for a specific transaction to propagate\n if (options.txHash) {\n const waitForTransactionCallback = async (data) => {\n if (data && data[0] === options.txHash) {\n txHashSeen = true;\n this.provider.unsubscribeFromTransaction(options.txHash, waitForTransactionCallback);\n resolve(makeResponse(options.txHash));\n }\n };\n this.provider.subscribeToTransaction(options.txHash, waitForTransactionCallback);\n return;\n }\n // waiting for any address transaction\n const watchCancel = this.provider.watchAddressStatus(this.getDepositAddress(), async (_status) => {\n watchCancel();\n resolve(makeResponse());\n });\n });\n }\n /**\n * watchBlocks Watch network blocks\n *\n * @param callback callback with a block header object\n *\n * @returns a function which will cancel watching upon evaluation\n */\n watchBlocks(callback) {\n return this.provider.watchBlocks(callback);\n }\n /**\n * waitForBlock Wait for a network block\n *\n * @param height if specified waits for this exact blockchain height, otherwise resolves with the next block\n *\n */\n async waitForBlock(height) {\n return this.provider.waitForBlock(height);\n }\n //#endregion Funds\n //#region Private implementation details\n async deriveInfo() {\n const publicKey = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_33__.secp256k1.derivePublicKeyUncompressed(this.privateKey);\n if (typeof publicKey === \"string\") {\n throw new Error(publicKey);\n }\n this.publicKey = publicKey;\n const publicKeyCompressed = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_33__.secp256k1.derivePublicKeyCompressed(this.privateKey);\n if (typeof publicKeyCompressed === \"string\") {\n throw new Error(publicKeyCompressed);\n }\n this.publicKeyCompressed = publicKeyCompressed;\n const networkType = this.network === _enum_js__WEBPACK_IMPORTED_MODULE_4__.NetworkType.Regtest ? _enum_js__WEBPACK_IMPORTED_MODULE_4__.NetworkType.Testnet : this.network;\n this.privateKeyWif = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_23__.encodePrivateKeyWif)(this.privateKey, networkType);\n (0,_util_checkWifNetwork_js__WEBPACK_IMPORTED_MODULE_22__.checkWifNetwork)(this.privateKeyWif, this.network);\n this.cashaddr = (0,_util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_21__.deriveCashaddr)(this.privateKey, this.networkPrefix);\n this.tokenaddr = (0,_util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_21__.deriveTokenaddr)(this.privateKey, this.networkPrefix);\n this.address = this.cashaddr;\n this.publicKeyHash = (0,_util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_12__.derivePublicKeyHash)(this.cashaddr);\n return this;\n }\n //#endregion Private implementation details\n //#region Signing\n // Convenience wrapper to sign interface\n async sign(message) {\n return await Wallet.signedMessage.sign(message, this.privateKey);\n }\n // Convenience wrapper to verify interface\n async verify(message, sig, publicKey) {\n return await Wallet.signedMessage.verify(message, sig, this.cashaddr, publicKey);\n }\n //#endregion Signing\n //#region Cashtokens\n /**\n * Create new cashtoken, both funglible and/or non-fungible (NFT)\n * Refer to spec https://github.com/bitjson/cashtokens\n * @param {number} genesisRequest.amount amount of *fungible* tokens to create\n * @param {NFTCapability?} genesisRequest.capability capability of new NFT\n * @param {string?} genesisRequest.commitment NFT commitment message\n * @param {string?} genesisRequest.cashaddr cash address to send the created token UTXO to; if undefined will default to your address\n * @param {number?} genesisRequest.value satoshi value to send alongside with tokens; if undefined will default to 1000 satoshi\n * @param {SendRequestType | SendRequestType[]} sendRequests single or an array of extra send requests (OP_RETURN, value transfer, etc.) to include in genesis transaction\n * @param {SendRequestOptionsI} options Options of the send requests\n */\n async tokenGenesis(genesisRequest, sendRequests = [], options) {\n if (!Array.isArray(sendRequests)) {\n sendRequests = [sendRequests];\n }\n let utxos;\n if (options && options.utxoIds) {\n utxos = options.utxoIds.map((utxoId) => typeof utxoId === \"string\" ? (0,_model_js__WEBPACK_IMPORTED_MODULE_20__.fromUtxoId)(utxoId) : utxoId);\n }\n else {\n utxos = await this.getAddressUtxos(this.cashaddr);\n }\n const genesisInputs = utxos.filter((val) => val.vout === 0 && !val.token);\n if (genesisInputs.length === 0) {\n throw new Error(\"No suitable inputs with vout=0 available for new token genesis\");\n }\n const genesisSendRequest = new _model_js__WEBPACK_IMPORTED_MODULE_20__.TokenSendRequest({\n cashaddr: genesisRequest.cashaddr || this.tokenaddr,\n amount: genesisRequest.amount,\n value: genesisRequest.value || 1000,\n capability: genesisRequest.capability,\n commitment: genesisRequest.commitment,\n tokenId: genesisInputs[0].txid,\n });\n return this.send([genesisSendRequest, ...sendRequests], {\n ...options,\n utxoIds: utxos,\n ensureUtxos: [genesisInputs[0]],\n checkTokenQuantities: false,\n queryBalance: false,\n tokenOperation: \"genesis\",\n });\n }\n /**\n * Mint new NFT cashtokens using an existing minting token\n * Refer to spec https://github.com/bitjson/cashtokens\n * @param {string} tokenId tokenId of an NFT to mint\n * @param {TokenMintRequest | TokenMintRequest[]} mintRequests mint requests with new token properties and recipients\n * @param {NFTCapability?} mintRequest.capability capability of new NFT\n * @param {string?} mintRequest.commitment NFT commitment message\n * @param {string?} mintRequest.cashaddr cash address to send the created token UTXO to; if undefined will default to your address\n * @param {number?} mintRequest.value satoshi value to send alongside with tokens; if undefined will default to 1000 satoshi\n * @param {boolean?} deductTokenAmount if minting token contains fungible amount, deduct from it by amount of minted tokens\n * @param {SendRequestOptionsI} options Options of the send requests\n */\n async tokenMint(tokenId, mintRequests, deductTokenAmount = false, options) {\n if (tokenId?.length !== 64) {\n throw Error(`Invalid tokenId supplied: ${tokenId}`);\n }\n if (!Array.isArray(mintRequests)) {\n mintRequests = [mintRequests];\n }\n const utxos = await this.getAddressUtxos(this.cashaddr);\n const nftUtxos = utxos.filter((val) => val.token?.tokenId === tokenId &&\n val.token?.capability === _interface_js__WEBPACK_IMPORTED_MODULE_8__.NFTCapability.minting);\n if (!nftUtxos.length) {\n throw new Error(\"You do not have any token UTXOs with minting capability for specified tokenId\");\n }\n const newAmount = deductTokenAmount && nftUtxos[0].token.amount > 0\n ? nftUtxos[0].token.amount - mintRequests.length\n : nftUtxos[0].token.amount;\n const safeNewAmount = Math.max(0, newAmount);\n const mintingInput = new _model_js__WEBPACK_IMPORTED_MODULE_20__.TokenSendRequest({\n cashaddr: this.tokenaddr,\n tokenId: tokenId,\n capability: nftUtxos[0].token.capability,\n commitment: nftUtxos[0].token.commitment,\n amount: safeNewAmount,\n value: nftUtxos[0].satoshis,\n });\n return this.send([\n mintingInput,\n ...mintRequests.map((val) => new _model_js__WEBPACK_IMPORTED_MODULE_20__.TokenSendRequest({\n cashaddr: val.cashaddr || this.tokenaddr,\n amount: 0,\n tokenId: tokenId,\n value: val.value,\n capability: val.capability,\n commitment: val.commitment,\n })),\n ], {\n ...options,\n ensureUtxos: [nftUtxos[0]],\n checkTokenQuantities: false,\n queryBalance: false,\n tokenOperation: \"mint\",\n });\n }\n /**\n * Perform an explicit token burning by spending a token utxo to an OP_RETURN\n *\n * Behaves differently for fungible and non-fungible tokens:\n * * NFTs are always \"destroyed\"\n * * FTs' amount is reduced by the amount specified, if 0 FT amount is left and no NFT present, the token is \"destroyed\"\n *\n * Refer to spec https://github.com/bitjson/cashtokens\n * @param {string} burnRequest.tokenId tokenId of a token to burn\n * @param {NFTCapability} burnRequest.capability capability of the NFT token to select, optional\n * @param {string?} burnRequest.commitment commitment of the NFT token to select, optional\n * @param {number?} burnRequest.amount amount of fungible tokens to burn, optional\n * @param {string?} burnRequest.cashaddr address to return token and satoshi change to\n * @param {string?} message optional message to include in OP_RETURN\n * @param {SendRequestOptionsI} options Options of the send requests\n */\n async tokenBurn(burnRequest, message, options) {\n if (burnRequest.tokenId?.length !== 64) {\n throw Error(`Invalid tokenId supplied: ${burnRequest.tokenId}`);\n }\n const utxos = await this.getAddressUtxos(this.cashaddr);\n const tokenUtxos = utxos.filter((val) => val.token?.tokenId === burnRequest.tokenId &&\n val.token?.capability === burnRequest.capability &&\n val.token?.commitment === burnRequest.commitment);\n if (!tokenUtxos.length) {\n throw new Error(\"You do not have suitable token UTXOs to perform burn\");\n }\n const totalFungibleAmount = tokenUtxos.reduce((prev, cur) => prev + (cur.token?.amount || 0), 0);\n const fungibleBurnAmount = burnRequest.amount && burnRequest.amount > 0 ? burnRequest.amount : 0;\n const hasNFT = burnRequest.capability || burnRequest.commitment;\n let utxoIds = [];\n let changeSendRequests;\n if (hasNFT) {\n // does not have FT tokens, let us destroy the token completely\n if (totalFungibleAmount === 0) {\n changeSendRequests = [];\n utxoIds.push(tokenUtxos[0]);\n }\n else {\n // add utxos to spend from\n let available = 0;\n for (const token of tokenUtxos.filter((val) => val.token?.amount)) {\n utxoIds.push(token);\n available += token.token?.amount;\n if (available >= fungibleBurnAmount) {\n break;\n }\n }\n // if there are FT, reduce their amount\n const newAmount = totalFungibleAmount - fungibleBurnAmount;\n const safeNewAmount = Math.max(0, newAmount);\n changeSendRequests = [\n new _model_js__WEBPACK_IMPORTED_MODULE_20__.TokenSendRequest({\n cashaddr: burnRequest.cashaddr || this.tokenaddr,\n tokenId: burnRequest.tokenId,\n capability: burnRequest.capability,\n commitment: burnRequest.commitment,\n amount: safeNewAmount,\n value: tokenUtxos[0].satoshis,\n }),\n ];\n }\n }\n else {\n // if we are burning last fughible tokens, let us destroy the token completely\n if (totalFungibleAmount === fungibleBurnAmount) {\n changeSendRequests = [];\n utxoIds.push(tokenUtxos[0]);\n }\n else {\n // add utxos to spend from\n let available = 0;\n for (const token of tokenUtxos.filter((val) => val.token?.amount)) {\n utxoIds.push(token);\n available += token.token?.amount;\n if (available >= fungibleBurnAmount) {\n break;\n }\n }\n // reduce the FT amount\n const newAmount = totalFungibleAmount - fungibleBurnAmount;\n const safeNewAmount = Math.max(0, newAmount);\n changeSendRequests = [\n new _model_js__WEBPACK_IMPORTED_MODULE_20__.TokenSendRequest({\n cashaddr: burnRequest.cashaddr || this.tokenaddr,\n tokenId: burnRequest.tokenId,\n amount: safeNewAmount,\n value: tokenUtxos[0].satoshis,\n }),\n ];\n }\n }\n const opReturn = _model_js__WEBPACK_IMPORTED_MODULE_20__.OpReturnData.fromString(message || \"\");\n return this.send([opReturn, ...changeSendRequests], {\n ...options,\n checkTokenQuantities: false,\n queryBalance: false,\n ensureUtxos: utxoIds.length > 0 ? utxoIds : undefined,\n tokenOperation: \"burn\",\n });\n }\n /**\n * getTokenUtxos Get unspent token outputs for the wallet\n * will return utxos only for the specified token if `tokenId` provided\n * @param {string?} tokenId tokenId (category) to filter utxos by, if not set will return utxos from all tokens\n * @returns {UtxoI[]} token utxos\n */\n async getTokenUtxos(tokenId) {\n const utxos = await this.getAddressUtxos(this.address);\n return utxos.filter((val) => tokenId ? val.token?.tokenId === tokenId : val.token);\n }\n /**\n * getTokenBalance Gets fungible token balance\n * for NFT token balance see @ref getNftTokenBalance\n * @param {string} tokenId tokenId to get balance for\n * @returns {number} fungible token balance\n */\n async getTokenBalance(tokenId) {\n const utxos = (await this.getTokenUtxos(tokenId)).filter((val) => val.token?.amount);\n return (0,_util_sumUtxoValue_js__WEBPACK_IMPORTED_MODULE_26__.sumTokenAmounts)(utxos, tokenId);\n }\n /**\n * getNftTokenBalance Gets non-fungible token (NFT) balance for a particula tokenId\n * disregards fungible token balances\n * for fungible token balance see @ref getTokenBalance\n * @param {string} tokenId tokenId to get balance for\n * @returns {number} non-fungible token balance\n */\n async getNftTokenBalance(tokenId) {\n const utxos = (await this.getTokenUtxos(tokenId)).filter((val) => val.token?.commitment !== undefined);\n return utxos.length;\n }\n /**\n * getAllTokenBalances Gets all fungible token balances in this wallet\n * @returns {Object} a map [tokenId => balance] for all tokens in this wallet\n */\n async getAllTokenBalances() {\n const result = {};\n const utxos = (await this.getTokenUtxos()).filter((val) => val.token?.amount);\n for (const utxo of utxos) {\n if (!result[utxo.token.tokenId]) {\n result[utxo.token.tokenId] = 0;\n }\n result[utxo.token.tokenId] += utxo.token.amount;\n }\n return result;\n }\n /**\n * getAllNftTokenBalances Gets all non-fungible token (NFT) balances in this wallet\n * @returns {Object} a map [tokenId => balance] for all NFTs in this wallet\n */\n async getAllNftTokenBalances() {\n const result = {};\n const utxos = (await this.getTokenUtxos()).filter((val) => val.token?.commitment !== undefined);\n for (const utxo of utxos) {\n if (!result[utxo.token.tokenId]) {\n result[utxo.token.tokenId] = 0;\n }\n result[utxo.token.tokenId] += 1;\n }\n return result;\n }\n}\nWallet.signedMessage = new _message_index_js__WEBPACK_IMPORTED_MODULE_34__.SignedMessage();\n/**\n * Class to manage a testnet wallet.\n */\nclass TestNetWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_4__.NetworkType.Testnet);\n }\n // will receive 10000 testnet satoshi, rate limits apply\n async getTestnetSatoshis() {\n try {\n const response = await axios__WEBPACK_IMPORTED_MODULE_2___default().post(`${TestNetWallet.faucetServer}/faucet/get_testnet_bch`, { cashaddr: this.cashaddr });\n const data = response.data;\n return data.txId;\n }\n catch (e) {\n // console.log(e);\n // console.log(e.response ? e.response.data : \"\");\n throw e;\n }\n }\n // be nice and return them back\n async returnTestnetSatoshis() {\n try {\n const response = await axios__WEBPACK_IMPORTED_MODULE_2___default().post(`${TestNetWallet.faucetServer}/faucet/get_addresses`);\n const data = response.data;\n return await this.slpAware().sendMax(data.bchtest);\n }\n catch (e) {\n console.log(e);\n console.log(e.response ? e.response.data : \"\");\n throw e;\n }\n }\n // will receive 10 testnet tokens, rate limits apply\n async getTestnetSlp(tokenId) {\n try {\n const response = await axios__WEBPACK_IMPORTED_MODULE_2___default().post(`${TestNetWallet.faucetServer}/faucet/get_testnet_slp`, { slpaddr: this.slp.slpaddr, tokenId: tokenId });\n const data = response.data;\n return data.txId;\n }\n catch (e) {\n //console.log(e);\n //console.log(e.response ? e.response.data : \"\");\n throw e;\n }\n }\n // be nice and return them back\n async returnTestnetSlp(tokenId) {\n try {\n const response = await axios__WEBPACK_IMPORTED_MODULE_2___default().post(`${TestNetWallet.faucetServer}/faucet/get_addresses`);\n const data = response.data;\n return await this.slp.sendMax(data.slptest, tokenId);\n }\n catch (e) {\n console.log(e);\n console.log(e.response ? e.response.data : \"\");\n throw e;\n }\n }\n // interface to static slp functions. see Slp.ts\n static get slp() {\n return _Slp_js__WEBPACK_IMPORTED_MODULE_6__.TestNetSlp;\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_7__.TestNetUtil;\n }\n}\nTestNetWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_35__.CashAddressNetworkPrefix.testnet;\nTestNetWallet.faucetServer = \"https://rest-unstable.mainnet.cash\";\n/**\n * Class to manage a regtest wallet.\n */\nclass RegTestWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_4__.NetworkType.Regtest);\n }\n // interface to static slp functions. see Slp.ts\n static get slp() {\n return _Slp_js__WEBPACK_IMPORTED_MODULE_6__.RegTestSlp;\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_7__.RegTestUtil;\n }\n}\nRegTestWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_35__.CashAddressNetworkPrefix.regtest;\n/**\n * Class to manage a bitcoin cash wif wallet.\n */\nclass WifWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_4__.NetworkType.Mainnet, _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Wif);\n }\n // interface to static slp functions. see Slp.ts\n static get slp() {\n return _Slp_js__WEBPACK_IMPORTED_MODULE_6__.WifSlp;\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_7__.WifUtil;\n }\n}\nWifWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_35__.CashAddressNetworkPrefix.mainnet;\nWifWallet.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Wif;\n/**\n * Class to manage a testnet wif wallet.\n */\nclass TestNetWifWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_4__.NetworkType.Testnet, _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Wif);\n }\n // interface to static slp functions. see Slp.ts\n static get slp() {\n return _Slp_js__WEBPACK_IMPORTED_MODULE_6__.TestNetWifSlp;\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_7__.TestNetWifUtil;\n }\n}\nTestNetWifWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_35__.CashAddressNetworkPrefix.testnet;\nTestNetWifWallet.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Wif;\n/**\n * Class to manage a regtest wif wallet.\n */\nclass RegTestWifWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_4__.NetworkType.Regtest, _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Wif);\n }\n // interface to static slp functions. see Slp.ts\n static get slp() {\n return _Slp_js__WEBPACK_IMPORTED_MODULE_6__.RegTestWifSlp;\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_7__.RegTestWifUtil;\n }\n}\nRegTestWifWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_35__.CashAddressNetworkPrefix.regtest;\nRegTestWifWallet.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Wif;\n/**\n * Class to manage a bitcoin cash watch wallet.\n */\nclass WatchWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_4__.NetworkType.Mainnet, _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Watch);\n }\n // interface to static slp functions. see Slp.ts\n static get slp() {\n return _Slp_js__WEBPACK_IMPORTED_MODULE_6__.WatchSlp;\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_7__.WatchUtil;\n }\n}\nWatchWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_35__.CashAddressNetworkPrefix.mainnet;\nWatchWallet.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Watch;\n/**\n * Class to manage a testnet watch wallet.\n */\nclass TestNetWatchWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_4__.NetworkType.Testnet, _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Watch);\n }\n // interface to static slp functions. see Slp.ts\n static get slp() {\n return _Slp_js__WEBPACK_IMPORTED_MODULE_6__.TestNetWatchSlp;\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_7__.TestNetWatchUtil;\n }\n}\nTestNetWatchWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_35__.CashAddressNetworkPrefix.testnet;\nTestNetWatchWallet.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Watch;\n/**\n * Class to manage a regtest watch wallet.\n */\nclass RegTestWatchWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_4__.NetworkType.Regtest, _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Watch);\n }\n // interface to static slp functions. see Slp.ts\n static get slp() {\n return _Slp_js__WEBPACK_IMPORTED_MODULE_6__.RegTestWatchSlp;\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_7__.RegTestWatchUtil;\n }\n}\nRegTestWatchWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_35__.CashAddressNetworkPrefix.regtest;\nRegTestWatchWallet.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Watch;\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/wallet/Wif.ts?");
1667
+ eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"RegTestWallet\": () => (/* binding */ RegTestWallet),\n/* harmony export */ \"RegTestWatchWallet\": () => (/* binding */ RegTestWatchWallet),\n/* harmony export */ \"RegTestWifWallet\": () => (/* binding */ RegTestWifWallet),\n/* harmony export */ \"TestNetWallet\": () => (/* binding */ TestNetWallet),\n/* harmony export */ \"TestNetWatchWallet\": () => (/* binding */ TestNetWatchWallet),\n/* harmony export */ \"TestNetWifWallet\": () => (/* binding */ TestNetWifWallet),\n/* harmony export */ \"Wallet\": () => (/* binding */ Wallet),\n/* harmony export */ \"WatchWallet\": () => (/* binding */ WatchWallet),\n/* harmony export */ \"WifWallet\": () => (/* binding */ WifWallet)\n/* harmony export */ });\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/key/hd-key.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_33__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/crypto/default-crypto-instances.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/hex.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/key/key-utils.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/key/wallet-import-format.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_35__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/address/cash-address.js\");\n/* harmony import */ var bip39__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! bip39 */ \"../../node_modules/bip39/src/index.js\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../enum.js */ \"./src/enum.ts\");\n/* harmony import */ var _interface_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../interface.js */ \"./src/interface.ts\");\n/* harmony import */ var _Base_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Base.js */ \"./src/wallet/Base.ts\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./enum.js */ \"./src/wallet/enum.ts\");\n/* harmony import */ var _model_js__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ./model.js */ \"./src/wallet/model.ts\");\n/* harmony import */ var _transaction_Wif_js__WEBPACK_IMPORTED_MODULE_29__ = __webpack_require__(/*! ../transaction/Wif.js */ \"./src/transaction/Wif.ts\");\n/* harmony import */ var _util_asSendRequestObject_js__WEBPACK_IMPORTED_MODULE_30__ = __webpack_require__(/*! ../util/asSendRequestObject.js */ \"./src/util/asSendRequestObject.ts\");\n/* harmony import */ var _util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(/*! ../util/balanceObjectFromSatoshi.js */ \"./src/util/balanceObjectFromSatoshi.ts\");\n/* harmony import */ var _util_checkWifNetwork_js__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ../util/checkWifNetwork.js */ \"./src/util/checkWifNetwork.ts\");\n/* harmony import */ var _util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ../util/deriveCashaddr.js */ \"./src/util/deriveCashaddr.ts\");\n/* harmony import */ var _util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../util/derivePublicKeyHash.js */ \"./src/util/derivePublicKeyHash.ts\");\n/* harmony import */ var _util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../util/checkForEmptySeed.js */ \"./src/util/checkForEmptySeed.ts\");\n/* harmony import */ var _util_sanitizeUnit_js__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(/*! ../util/sanitizeUnit.js */ \"./src/util/sanitizeUnit.ts\");\n/* harmony import */ var _util_sumUtxoValue_js__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(/*! ../util/sumUtxoValue.js */ \"./src/util/sumUtxoValue.ts\");\n/* harmony import */ var _util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_31__ = __webpack_require__(/*! ../util/sumSendRequestAmounts.js */ \"./src/util/sumSendRequestAmounts.ts\");\n/* harmony import */ var _network_getRelayFeeCache_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../network/getRelayFeeCache.js */ \"./src/network/getRelayFeeCache.ts\");\n/* harmony import */ var _Slp_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./Slp.js */ \"./src/wallet/Slp.ts\");\n/* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! axios */ \"../../node_modules/axios/index.js\");\n/* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(axios__WEBPACK_IMPORTED_MODULE_2__);\n/* harmony import */ var _util_bchaddr_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../util/bchaddr.js */ \"../../node_modules/bchaddrjs-slp/src/bchaddr.js\");\n/* harmony import */ var _util_bchaddr_js__WEBPACK_IMPORTED_MODULE_13___default = /*#__PURE__*/__webpack_require__.n(_util_bchaddr_js__WEBPACK_IMPORTED_MODULE_13__);\n/* harmony import */ var _Util_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./Util.js */ \"./src/wallet/Util.ts\");\n/* harmony import */ var _network_index_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../network/index.js */ \"./src/network/default.ts\");\n/* harmony import */ var _util_randomBytes_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../util/randomBytes.js */ \"./src/util/randomBytes.ts\");\n/* harmony import */ var _message_index_js__WEBPACK_IMPORTED_MODULE_34__ = __webpack_require__(/*! ../message/index.js */ \"./src/message/signed.ts\");\n/* harmony import */ var _util_amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(/*! ../util/amountInSatoshi.js */ \"./src/util/amountInSatoshi.ts\");\n/* harmony import */ var _util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ../util/getXPubKey.js */ \"./src/util/getXPubKey.ts\");\n/* harmony import */ var _constant_js__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ../constant.js */ \"./src/constant.ts\");\n/* harmony import */ var _history_electrumTransformer_js__WEBPACK_IMPORTED_MODULE_32__ = __webpack_require__(/*! ../history/electrumTransformer.js */ \"./src/history/electrumTransformer.ts\");\n/* harmony import */ var _Bcmr_js__WEBPACK_IMPORTED_MODULE_28__ = __webpack_require__(/*! ./Bcmr.js */ \"./src/wallet/Bcmr.ts\");\n/* harmony import */ var _qr_Qr_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../qr/Qr.js */ \"./src/qr/Qr.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_Base_js__WEBPACK_IMPORTED_MODULE_3__, _enum_js__WEBPACK_IMPORTED_MODULE_4__, _Slp_js__WEBPACK_IMPORTED_MODULE_6__, _Util_js__WEBPACK_IMPORTED_MODULE_7__, _network_index_js__WEBPACK_IMPORTED_MODULE_9__, _qr_Qr_js__WEBPACK_IMPORTED_MODULE_10__, _util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_12__, _util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_16__, _util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_17__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_18__, _model_js__WEBPACK_IMPORTED_MODULE_20__, _util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_21__, _util_checkWifNetwork_js__WEBPACK_IMPORTED_MODULE_22__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_23__, _util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_25__, _util_amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_27__, _Bcmr_js__WEBPACK_IMPORTED_MODULE_28__, _transaction_Wif_js__WEBPACK_IMPORTED_MODULE_29__, _util_asSendRequestObject_js__WEBPACK_IMPORTED_MODULE_30__, _util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_31__, _history_electrumTransformer_js__WEBPACK_IMPORTED_MODULE_32__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_33__, _message_index_js__WEBPACK_IMPORTED_MODULE_34__]);\n([_Base_js__WEBPACK_IMPORTED_MODULE_3__, _enum_js__WEBPACK_IMPORTED_MODULE_4__, _Slp_js__WEBPACK_IMPORTED_MODULE_6__, _Util_js__WEBPACK_IMPORTED_MODULE_7__, _network_index_js__WEBPACK_IMPORTED_MODULE_9__, _qr_Qr_js__WEBPACK_IMPORTED_MODULE_10__, _util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_12__, _util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_16__, _util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_17__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_18__, _model_js__WEBPACK_IMPORTED_MODULE_20__, _util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_21__, _util_checkWifNetwork_js__WEBPACK_IMPORTED_MODULE_22__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_23__, _util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_25__, _util_amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_27__, _Bcmr_js__WEBPACK_IMPORTED_MODULE_28__, _transaction_Wif_js__WEBPACK_IMPORTED_MODULE_29__, _util_asSendRequestObject_js__WEBPACK_IMPORTED_MODULE_30__, _util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_31__, _history_electrumTransformer_js__WEBPACK_IMPORTED_MODULE_32__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_33__, _message_index_js__WEBPACK_IMPORTED_MODULE_34__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n//#region Imports\n// Stable\n\n// Unstable?\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n//#endregion Imports\n/**\n * Class to manage a bitcoin cash wallet.\n */\nclass Wallet extends _Base_js__WEBPACK_IMPORTED_MODULE_3__.BaseWallet {\n //#endregion\n //#region Constructors and Statics\n constructor(name = \"\", network = _enum_js__WEBPACK_IMPORTED_MODULE_4__.NetworkType.Mainnet, walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Seed) {\n super(name, network, walletType);\n this.derivationPath = \"m/44'/0'/0'/0/0\";\n this.parentDerivationPath = \"m/44'/0'/0'\";\n this._slpAware = false; // a flag which activates utxo checking against an external slp indexer\n this._slpSemiAware = false; // a flag which requires an utxo to have more than 546 sats to be spendable and counted in the balance\n this.fromId = async (walletId) => {\n let [walletType, networkGiven, arg1] = walletId.split(\":\");\n if (this.network != networkGiven) {\n throw Error(`Network prefix ${networkGiven} to a ${this.network} wallet`);\n }\n // \"wif:regtest:cNfsPtqN2bMRS7vH5qd8tR8GMvgXyL5BjnGAKgZ8DYEiCrCCQcP6\"\n if (walletType === \"wif\") {\n return this.fromWIF(arg1);\n }\n return super.fromId(walletId);\n };\n this.networkPrefix = _enum_js__WEBPACK_IMPORTED_MODULE_4__.prefixFromNetworkMap[this.network];\n }\n //#region Accessors\n // interface to slp functions. see Slp.ts\n get slp() {\n if (!this._slp) {\n this._slp = new _Slp_js__WEBPACK_IMPORTED_MODULE_6__.Slp(this);\n this._slpAware = true;\n }\n return this._slp;\n }\n // interface to slp functions. see Slp.ts\n static get slp() {\n return _Slp_js__WEBPACK_IMPORTED_MODULE_6__.Slp;\n }\n // interface to util functions. see Util.ts\n get util() {\n if (!this._util) {\n this._util = new _Util_js__WEBPACK_IMPORTED_MODULE_7__.Util(this);\n }\n return this._util;\n }\n // interface to util util. see Util.Util\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_7__.Util;\n }\n slpAware(value = true) {\n this._slpAware = value;\n return this;\n }\n slpSemiAware(value = true) {\n this._slpSemiAware = value;\n return this;\n }\n getNetworkProvider(network = _interface_js__WEBPACK_IMPORTED_MODULE_8__.Network.MAINNET) {\n return (0,_network_index_js__WEBPACK_IMPORTED_MODULE_9__.getNetworkProvider)(network);\n }\n /**\n * getTokenDepositAddress - get a cashtoken aware wallet deposit address\n *\n * @returns The cashtoken aware deposit address as a string\n */\n getTokenDepositAddress() {\n return this.tokenaddr;\n }\n /**\n * getDepositQr - get an address qrcode, encoded for display on the web\n *\n * @returns The qrcode for the token aware address\n */\n getTokenDepositQr() {\n return (0,_qr_Qr_js__WEBPACK_IMPORTED_MODULE_10__.qrAddress)(this.getTokenDepositAddress());\n }\n /**\n * explorerUrl Web url to a transaction on a block explorer\n *\n * @param txId transaction Id\n * @returns Url string\n */\n explorerUrl(txId) {\n const explorerUrlMap = {\n mainnet: \"https://blockchair.com/bitcoin-cash/transaction/\",\n testnet: \"https://www.blockchain.com/bch-testnet/tx/\",\n regtest: \"\",\n };\n return explorerUrlMap[this.network] + txId;\n }\n // Return wallet info\n getInfo() {\n return {\n cashaddr: this.cashaddr,\n tokenaddr: this.tokenaddr,\n isTestnet: this.isTestnet,\n name: this.name,\n network: this.network,\n seed: this.mnemonic ? this.getSeed().seed : undefined,\n derivationPath: this.mnemonic ? this.getSeed().derivationPath : undefined,\n parentDerivationPath: this.mnemonic\n ? this.getSeed().parentDerivationPath\n : undefined,\n parentXPubKey: this.parentXPubKey ? this.parentXPubKey : undefined,\n publicKey: this.publicKey ? (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.binToHex)(this.publicKey) : undefined,\n publicKeyHash: (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.binToHex)(this.publicKeyHash),\n privateKey: this.privateKey ? (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.binToHex)(this.privateKey) : undefined,\n privateKeyWif: this.privateKeyWif,\n walletId: this.toString(),\n walletDbEntry: this.toDbString(),\n };\n }\n // returns the public key hash for an address\n getPublicKey(hex = false) {\n if (this.publicKey) {\n return hex ? (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.binToHex)(this.publicKey) : this.publicKey;\n }\n else {\n throw Error(\"The public key for this wallet is not known, perhaps the wallet was created to watch the *hash* of a public key? i.e. a cashaddress.\");\n }\n }\n // returns the public key hash for an address\n getPublicKeyCompressed(hex = false) {\n if (this.publicKeyCompressed) {\n return hex\n ? (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.binToHex)(this.publicKeyCompressed)\n : this.publicKeyCompressed;\n }\n else {\n throw Error(\"The compressed public key for this wallet is not known, perhaps the wallet was created to watch the *hash* of a public key? i.e. a cashaddress.\");\n }\n }\n // returns the public key hash for an address\n getPublicKeyHash(hex = false) {\n if (this.publicKeyHash) {\n return hex ? (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.binToHex)(this.publicKeyHash) : this.publicKeyHash;\n }\n else {\n throw Error(\"The public key hash for this wallet is not known. If this wallet was created from the constructor directly, calling the deriveInfo() function may help. \");\n }\n }\n /**\n * fromWIF - create a wallet using the private key supplied in `Wallet Import Format`\n *\n * @param wif WIF encoded private key string\n *\n * @returns instantiated wallet\n */\n static async fromWIF(wif) {\n return new this().fromWIF(wif);\n }\n /**\n * fromCashaddr - create a watch-only wallet in the network derived from the address\n *\n * such kind of wallet does not have a private key and is unable to spend any funds\n * however it still allows to use many utility functions such as getting and watching balance, etc.\n *\n * @param address cashaddress of a wallet\n *\n * @returns instantiated wallet\n */\n static async fromCashaddr(address) {\n const prefix = (0,_util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_12__.derivePrefix)(address);\n const networkType = _enum_js__WEBPACK_IMPORTED_MODULE_4__.networkPrefixMap[prefix];\n return new this(\"\", networkType, _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Watch).watchOnly(address);\n }\n /**\n * fromTokenaddr - create a watch-only wallet in the network derived from the address\n *\n * such kind of wallet does not have a private key and is unable to spend any funds\n * however it still allows to use many utility functions such as getting and watching balance, etc.\n *\n * @param address token aware cashaddress of a wallet\n *\n * @returns instantiated wallet\n */\n static async fromTokenaddr(address) {\n const prefix = (0,_util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_12__.derivePrefix)(address);\n const networkType = _enum_js__WEBPACK_IMPORTED_MODULE_4__.networkPrefixMap[prefix];\n return new this(\"\", networkType, _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Watch).watchOnly(address);\n }\n /**\n * fromSlpaddr - create an SLP aware watch-only wallet in the network derived from the address\n *\n * such kind of wallet does not have a private key and is unable to spend any funds\n * however it still allows to use many utility functions such as getting and watching balance, etc.\n *\n * @param address slpaddress of a wallet\n *\n * @returns instantiated wallet\n */\n static async fromSlpaddr(address) {\n return this.fromCashaddr((0,_util_bchaddr_js__WEBPACK_IMPORTED_MODULE_13__.toCashAddress)(address));\n }\n //#endregion Constructors and Statics\n //#region Protected implementations\n async generate() {\n if (this.walletType === _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Wif) {\n return await this._generateWif();\n }\n else if (this.walletType === _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Watch) {\n return this;\n }\n else if (this.walletType === _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Hd) {\n throw Error(\"Not implemented\");\n }\n else if (this.walletType === _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Seed) {\n return await this._generateMnemonic();\n }\n else {\n console.log(this.walletType);\n throw Error(`Could not determine walletType: ${this.walletType}`);\n }\n }\n async _generateWif() {\n if (!this.privateKey) {\n this.privateKey = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_14__.generatePrivateKey)(() => (0,_util_randomBytes_js__WEBPACK_IMPORTED_MODULE_15__.generateRandomBytes)(32));\n }\n return this.deriveInfo();\n }\n async _generateMnemonic() {\n this.mnemonic = (0,bip39__WEBPACK_IMPORTED_MODULE_0__.generateMnemonic)();\n if (this.mnemonic.length == 0)\n throw Error(\"refusing to create wallet from empty mnemonic\");\n let seed = (0,bip39__WEBPACK_IMPORTED_MODULE_0__.mnemonicToSeedSync)(this.mnemonic);\n (0,_util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_16__.checkForEmptySeed)(seed);\n let network = this.isTestnet ? \"testnet\" : \"mainnet\";\n this.parentXPubKey = await (0,_util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_17__.getXPubKey)(seed, this.parentDerivationPath, network);\n let hdNode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_18__.deriveHdPrivateNodeFromSeed)(seed);\n if (!hdNode.valid) {\n throw Error(\"Invalid private key derived from mnemonic seed\");\n }\n let zerothChild = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_18__.deriveHdPath)(hdNode, this.derivationPath);\n if (typeof zerothChild === \"string\") {\n throw Error(zerothChild);\n }\n this.privateKey = zerothChild.privateKey;\n this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Seed;\n return await this.deriveInfo();\n }\n async getXPubKeys(paths) {\n if (this.mnemonic) {\n if (paths) {\n let xPubKeys = await this.deriveHdPaths(paths);\n return [xPubKeys];\n }\n else {\n return await this.deriveHdPaths(_constant_js__WEBPACK_IMPORTED_MODULE_19__.DERIVATION_PATHS);\n }\n }\n else {\n throw Error(\"xpubkeys can only be derived from seed type wallets.\");\n }\n }\n // Initialize wallet from a mnemonic phrase\n async fromSeed(mnemonic, derivationPath) {\n this.mnemonic = mnemonic.trim().toLowerCase();\n if (this.mnemonic.length == 0)\n throw Error(\"refusing to create wallet from empty mnemonic\");\n let seed = (0,bip39__WEBPACK_IMPORTED_MODULE_0__.mnemonicToSeedSync)(this.mnemonic);\n (0,_util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_16__.checkForEmptySeed)(seed);\n let hdNode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_18__.deriveHdPrivateNodeFromSeed)(seed);\n if (!hdNode.valid) {\n throw Error(\"Invalid private key derived from mnemonic seed\");\n }\n if (derivationPath) {\n this.derivationPath = derivationPath;\n // If the derivation path is for the first account child, set the parent derivation path\n let path = derivationPath.split(\"/\");\n if (path.slice(-2).join(\"/\") == \"0/0\") {\n this.parentDerivationPath = path.slice(0, -2).join(\"/\");\n }\n }\n let zerothChild = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_18__.deriveHdPath)(hdNode, this.derivationPath);\n if (typeof zerothChild === \"string\") {\n throw Error(zerothChild);\n }\n this.privateKey = zerothChild.privateKey;\n let network = this.isTestnet ? \"testnet\" : \"mainnet\";\n this.parentXPubKey = await (0,_util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_17__.getXPubKey)(seed, this.parentDerivationPath, network);\n this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Seed;\n await this.deriveInfo();\n return this;\n }\n // Get common xpub paths from zerothChild privateKey\n async deriveHdPaths(hdPaths) {\n if (!this.mnemonic)\n throw Error(\"refusing to create wallet from empty mnemonic\");\n let seed = (0,bip39__WEBPACK_IMPORTED_MODULE_0__.mnemonicToSeedSync)(this.mnemonic);\n (0,_util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_16__.checkForEmptySeed)(seed);\n let hdNode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_18__.deriveHdPrivateNodeFromSeed)(seed);\n if (!hdNode.valid) {\n throw Error(\"Invalid private key derived from mnemonic seed\");\n }\n let result = [];\n for (const path of hdPaths) {\n if (path === \"m\") {\n throw Error(\"Storing or sharing of parent public key may lead to loss of funds. Storing or sharing *root* parent public keys is strongly discouraged, although all parent keys have risk. See: https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#implications\");\n }\n let childNode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_18__.deriveHdPath)(hdNode, path);\n if (typeof childNode === \"string\") {\n throw Error(childNode);\n }\n let node = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_18__.deriveHdPublicNode)(childNode);\n if (typeof node === \"string\") {\n throw Error(node);\n }\n let xPubKey = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_18__.encodeHdPublicKey)({\n network: this.network,\n node: node,\n });\n let key = new _model_js__WEBPACK_IMPORTED_MODULE_20__.XPubKey({\n path: path,\n xPubKey: xPubKey,\n });\n result.push(await key.ready());\n }\n return await Promise.all(result).then((result) => {\n return result;\n });\n }\n // Initialize a watch only wallet from a cash addr\n async watchOnly(address) {\n this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Watch;\n let addressComponents = address.split(\":\");\n let addressPrefix, addressBase;\n if (addressComponents.length === 1) {\n addressBase = addressComponents.shift();\n addressPrefix = (0,_util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_12__.derivePrefix)(addressBase);\n }\n else {\n addressPrefix = addressComponents.shift();\n addressBase = addressComponents.shift();\n if (addressPrefix in _enum_js__WEBPACK_IMPORTED_MODULE_4__.networkPrefixMap) {\n if (_enum_js__WEBPACK_IMPORTED_MODULE_4__.networkPrefixMap[addressPrefix] != this.network) {\n throw Error(`a ${addressPrefix} address cannot be watched from a ${this.network} Wallet`);\n }\n }\n }\n this.cashaddr = `${addressPrefix}:${addressBase}`;\n this.address = this.cashaddr;\n this.publicKeyHash = (0,_util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_12__.derivePublicKeyHash)(this.cashaddr);\n this.tokenaddr = (0,_util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_21__.deriveTokenaddr)(this.publicKeyHash, this.networkPrefix);\n return this;\n }\n // Initialize wallet from Wallet Import Format\n async fromWIF(secret) {\n (0,_util_checkWifNetwork_js__WEBPACK_IMPORTED_MODULE_22__.checkWifNetwork)(secret, this.network);\n let wifResult = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_23__.decodePrivateKeyWif)(secret);\n if (typeof wifResult === \"string\") {\n throw Error(wifResult);\n }\n let resultData = wifResult;\n this.privateKey = resultData.privateKey;\n this.privateKeyWif = secret;\n this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Wif;\n await this.deriveInfo();\n return this;\n }\n async newRandom(name, dbName) {\n dbName = dbName ? dbName : this.networkPrefix;\n return super.newRandom(name, dbName);\n }\n async named(name, dbName, forceNew = false) {\n dbName = dbName ? dbName : this.networkPrefix;\n return super.named(name, dbName, forceNew);\n }\n async replaceNamed(name, walletId, dbName) {\n dbName = dbName ? dbName : this.networkPrefix;\n return super.replaceNamed(name, walletId, dbName);\n }\n async namedExists(name, dbName) {\n dbName = dbName ? dbName : this.networkPrefix;\n return super.namedExists(name, dbName);\n }\n //#endregion Protected Implementations\n //#region Serialization\n // Returns the serialized wallet as a string\n // If storing in a database, set asNamed to false to store secrets\n // In all other cases, the a named wallet is deserialized from the database\n // by the name key\n toString() {\n const result = super.toString();\n if (result)\n return result;\n if (this.walletType === _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Wif) {\n return `${this.walletType}:${this.network}:${this.privateKeyWif}`;\n }\n throw Error(\"toString unsupported wallet type\");\n }\n //\n toDbString() {\n const result = super.toDbString();\n if (result)\n return result;\n if (this.walletType === _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Wif) {\n return `${this.walletType}:${this.network}:${this.privateKeyWif}`;\n }\n throw Error(\"toDbString unsupported wallet type\");\n }\n //#endregion Serialization\n //#region Funds\n //\n async getAddressUtxos(address) {\n if (!address) {\n address = this.cashaddr;\n }\n if (this._slpAware) {\n const [bchUtxos, slpOutpoints] = await Promise.all([\n this.provider.getUtxos(address),\n this.slp.getSlpOutpoints(),\n ]);\n return bchUtxos.filter((bchutxo) => slpOutpoints.findIndex((slpOutpoint) => `${bchutxo.txid}:${bchutxo.vout}` === slpOutpoint) === -1);\n }\n else if (this._slpSemiAware) {\n const bchUtxos = await this.provider.getUtxos(address);\n return bchUtxos.filter((bchutxo) => bchutxo.satoshis > _constant_js__WEBPACK_IMPORTED_MODULE_19__.DUST_UTXO_THRESHOLD);\n }\n else {\n return await this.provider.getUtxos(address);\n }\n }\n /**\n * utxos Get unspent outputs for the wallet\n *\n */\n async getUtxos() {\n if (!this.cashaddr) {\n throw Error(\"Attempted to get utxos without an address\");\n }\n return await this.getAddressUtxos(this.cashaddr);\n }\n // gets wallet balance in sats, bch and usd\n async getBalance(rawUnit, usdPriceCache = true) {\n if (rawUnit) {\n const unit = (0,_util_sanitizeUnit_js__WEBPACK_IMPORTED_MODULE_24__.sanitizeUnit)(rawUnit);\n return await (0,_util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_25__.balanceFromSatoshi)(await this.getBalanceFromProvider(), unit, usdPriceCache);\n }\n else {\n return await (0,_util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_25__.balanceResponseFromSatoshi)(await this.getBalanceFromProvider(), usdPriceCache);\n }\n }\n // Gets balance by summing value in all utxos in stats\n async getBalanceFromUtxos() {\n const utxos = (await this.getAddressUtxos(this.cashaddr)).filter((val) => val.token === undefined);\n return (0,_util_sumUtxoValue_js__WEBPACK_IMPORTED_MODULE_26__.sumUtxoValue)(utxos);\n }\n // Gets balance from fulcrum\n async getBalanceFromProvider() {\n // Fulcrum reports balance of all utxos, including tokens, which is undesirable\n // // TODO not sure why getting the balance from a provider doesn't work\n // if (this._slpAware || this._slpSemiAware) {\n // return await this.getBalanceFromUtxos();\n // } else {\n // return await this.provider!.getBalance(this.cashaddr!);\n // }\n // FIXME\n return this.getBalanceFromUtxos();\n }\n // watching for any transaction hash of this wallet\n watchAddress(callback) {\n return this.provider.watchAddress(this.getDepositAddress(), callback);\n }\n // watching for any transaction of this wallet\n watchAddressTransactions(callback) {\n return this.provider.watchAddressTransactions(this.getDepositAddress(), callback);\n }\n // watching for cashtoken transaction of this wallet\n watchAddressTokenTransactions(callback) {\n return this.provider.watchAddressTokenTransactions(this.getDepositAddress(), callback);\n }\n // sets up a callback to be called upon wallet's balance change\n // can be cancelled by calling the function returned from this one\n watchBalance(callback) {\n return this.provider.watchAddressStatus(this.getDepositAddress(), async (_status) => {\n const balance = (await this.getBalance());\n callback(balance);\n });\n }\n // sets up a callback to be called upon wallet's BCH or USD balance change\n // if BCH balance does not change, the callback will be triggered every\n // @param `usdPriceRefreshInterval` milliseconds by polling for new BCH USD price\n // Since we want to be most sensitive to usd value change, we do not use the cached exchange rates\n // can be cancelled by calling the function returned from this one\n watchBalanceUsd(callback, usdPriceRefreshInterval = 30000) {\n let usdPrice = -1;\n const _callback = async () => {\n const balance = (await this.getBalance(undefined, false));\n if (usdPrice !== balance.usd) {\n usdPrice = balance.usd;\n callback(balance);\n }\n };\n const watchCancel = this.provider.watchAddressStatus(this.getDepositAddress(), _callback);\n const interval = setInterval(_callback, usdPriceRefreshInterval);\n return async () => {\n await watchCancel();\n clearInterval(interval);\n };\n }\n // waits for address balance to be greater than or equal to the target value\n // this call halts the execution\n async waitForBalance(value, rawUnit = _enum_js__WEBPACK_IMPORTED_MODULE_4__.UnitEnum.BCH) {\n return new Promise(async (resolve) => {\n const watchCancel = this.watchBalance(async (balance) => {\n const satoshiBalance = await (0,_util_amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_27__.amountInSatoshi)(value, rawUnit);\n if (balance.sat >= satoshiBalance) {\n await watchCancel();\n resolve(balance);\n }\n });\n });\n }\n // sets up a callback to be called upon wallet's token balance change\n // can be cancelled by calling the function returned from this one\n watchTokenBalance(tokenId, callback) {\n let previous = undefined;\n return this.provider.watchAddressStatus(this.getDepositAddress(), async (_status) => {\n const balance = await this.getTokenBalance(tokenId);\n if (previous != balance) {\n callback(balance);\n }\n previous = balance;\n });\n }\n // waits for address token balance to be greater than or equal to the target amount\n // this call halts the execution\n async waitForTokenBalance(tokenId, amount) {\n return new Promise(async (resolve) => {\n const watchCancel = this.watchTokenBalance(tokenId, async (balance) => {\n if (balance >= amount) {\n await watchCancel();\n resolve(balance);\n }\n });\n });\n }\n async getTokenInfo(tokenId) {\n return _Bcmr_js__WEBPACK_IMPORTED_MODULE_28__.BCMR.getTokenInfo(tokenId);\n }\n async _getMaxAmountToSend(params = {\n outputCount: 1,\n options: {},\n }) {\n if (!this.privateKey && params.options?.buildUnsigned !== true) {\n throw Error(\"Couldn't get network or private key for wallet.\");\n }\n if (!this.cashaddr) {\n throw Error(\"attempted to send without a cashaddr\");\n }\n if (params.options && params.options.slpAware) {\n this._slpAware = true;\n }\n if (params.options && params.options.slpSemiAware) {\n this._slpSemiAware = true;\n }\n let feePaidBy;\n if (params.options && params.options.feePaidBy) {\n feePaidBy = params.options.feePaidBy;\n }\n else {\n feePaidBy = _enum_js__WEBPACK_IMPORTED_MODULE_5__.FeePaidByEnum.change;\n }\n // get inputs\n let utxos;\n if (params.options && params.options.utxoIds) {\n utxos = params.options.utxoIds.map((utxoId) => typeof utxoId === \"string\" ? (0,_model_js__WEBPACK_IMPORTED_MODULE_20__.fromUtxoId)(utxoId) : utxoId);\n }\n else {\n utxos = (await this.getAddressUtxos(this.cashaddr)).filter((utxo) => !utxo.token);\n }\n // Get current height to assure recently mined coins are not spent.\n const bestHeight = await this.provider.getBlockHeight();\n // simulate outputs using the sender's address\n const sendRequest = new _model_js__WEBPACK_IMPORTED_MODULE_20__.SendRequest({\n cashaddr: this.cashaddr,\n value: 100,\n unit: \"sat\",\n });\n const sendRequests = Array(params.outputCount)\n .fill(0)\n .map(() => sendRequest);\n const fundingUtxos = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_29__.getSuitableUtxos)(utxos, undefined, bestHeight, feePaidBy, sendRequests);\n const relayFeePerByteInSatoshi = await (0,_network_getRelayFeeCache_js__WEBPACK_IMPORTED_MODULE_1__.getRelayFeeCache)(this.provider);\n const fee = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_29__.getFeeAmount)({\n utxos: fundingUtxos,\n sendRequests: sendRequests,\n privateKey: this.privateKey ?? Uint8Array.from([]),\n sourceAddress: this.cashaddr,\n relayFeePerByteInSatoshi: relayFeePerByteInSatoshi,\n slpOutputs: [],\n feePaidBy: feePaidBy,\n });\n const spendableAmount = (0,_util_sumUtxoValue_js__WEBPACK_IMPORTED_MODULE_26__.sumUtxoValue)(fundingUtxos);\n let result = spendableAmount - fee;\n if (result < 0) {\n result = 0;\n }\n return { value: result, utxos: fundingUtxos };\n }\n async getMaxAmountToSend(params = {\n outputCount: 1,\n options: {},\n }) {\n const { value: result } = await this._getMaxAmountToSend(params);\n return await (0,_util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_25__.balanceResponseFromSatoshi)(result);\n }\n /**\n * send Send some amount to an address\n * this function processes the send requests, encodes the transaction, sends it to the network\n * @returns (depending on the options parameter) the transaction id, new address balance and a link to the transaction on the blockchain explorer\n *\n * This is a first class function with REST analog, maintainers should strive to keep backward-compatibility\n *\n */\n async send(requests, options) {\n const { encodedTransaction, tokenIds, sourceOutputs } = await this.encodeTransaction(requests, undefined, options);\n const resp = new _model_js__WEBPACK_IMPORTED_MODULE_20__.SendResponse({});\n resp.tokenIds = tokenIds;\n if (options?.buildUnsigned !== true) {\n const txId = await this.submitTransaction(encodedTransaction, options?.awaitTransactionPropagation === undefined ||\n options?.awaitTransactionPropagation === true);\n resp.txId = txId;\n resp.explorerUrl = this.explorerUrl(resp.txId);\n if (options?.queryBalance === undefined ||\n options?.queryBalance === true) {\n resp.balance = (await this.getBalance());\n }\n }\n else {\n resp.unsignedTransaction = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.binToHex)(encodedTransaction);\n resp.sourceOutputs = sourceOutputs;\n }\n return resp;\n }\n /**\n * sendMax Send all available funds to a destination cash address\n *\n * @param {string} cashaddr destination cash address\n * @param {SendRequestOptionsI} options Options of the send requests\n *\n * @returns (depending on the options parameter) the transaction id, new address balance and a link to the transaction on the blockchain explorer\n */\n async sendMax(cashaddr, options) {\n return await this.sendMaxRaw(cashaddr, options);\n }\n /**\n * sendMaxRaw (internal) Send all available funds to a destination cash address\n *\n * @param {string} cashaddr destination cash address\n * @param {SendRequestOptionsI} options Options of the send requests\n *\n * @returns the transaction id sent to the network\n */\n async sendMaxRaw(cashaddr, options) {\n const { value: maxSpendableAmount, utxos } = await this._getMaxAmountToSend({\n outputCount: 1,\n options: options,\n });\n if (!options) {\n options = {};\n }\n options.utxoIds = utxos;\n const sendRequest = new _model_js__WEBPACK_IMPORTED_MODULE_20__.SendRequest({\n cashaddr: cashaddr,\n value: maxSpendableAmount,\n unit: \"sat\",\n });\n const { encodedTransaction, tokenIds, sourceOutputs } = await this.encodeTransaction([sendRequest], true, options);\n const resp = new _model_js__WEBPACK_IMPORTED_MODULE_20__.SendResponse({});\n resp.tokenIds = tokenIds;\n if (options?.buildUnsigned !== true) {\n const txId = await this.submitTransaction(encodedTransaction, options?.awaitTransactionPropagation === undefined ||\n options?.awaitTransactionPropagation === true);\n resp.txId = txId;\n resp.explorerUrl = this.explorerUrl(resp.txId);\n if (options?.queryBalance === undefined ||\n options?.queryBalance === true) {\n resp.balance = (await this.getBalance());\n }\n }\n else {\n resp.unsignedTransaction = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.binToHex)(encodedTransaction);\n resp.sourceOutputs = sourceOutputs;\n }\n return resp;\n }\n /**\n * encodeTransaction Encode and sign a transaction given a list of sendRequests, options and estimate fees.\n * @param {SendRequest[]} sendRequests SendRequests\n * @param {boolean} discardChange=false\n * @param {SendRequestOptionsI} options Options of the send requests\n */\n async encodeTransaction(requests, discardChange = false, options) {\n let sendRequests = (0,_util_asSendRequestObject_js__WEBPACK_IMPORTED_MODULE_30__.asSendRequestObject)(requests);\n if (!this.privateKey && options?.buildUnsigned !== true) {\n throw new Error(`Wallet ${this.name} is missing either a network or private key`);\n }\n if (!this.cashaddr) {\n throw Error(\"attempted to send without a cashaddr\");\n }\n if (options && options.slpAware) {\n this._slpAware = true;\n }\n if (options && options.slpSemiAware) {\n this._slpSemiAware = true;\n }\n let feePaidBy;\n if (options && options.feePaidBy) {\n feePaidBy = options.feePaidBy;\n }\n else {\n feePaidBy = _enum_js__WEBPACK_IMPORTED_MODULE_5__.FeePaidByEnum.change;\n }\n let changeAddress;\n if (options && options.changeAddress) {\n changeAddress = options.changeAddress;\n }\n else {\n changeAddress = this.cashaddr;\n }\n let checkTokenQuantities = true;\n if (options && options.checkTokenQuantities === false) {\n checkTokenQuantities = false;\n }\n // get inputs from options or query all inputs\n let utxos;\n if (options && options.utxoIds) {\n utxos = options.utxoIds.map((utxoId) => typeof utxoId === \"string\" ? (0,_model_js__WEBPACK_IMPORTED_MODULE_20__.fromUtxoId)(utxoId) : utxoId);\n }\n else {\n utxos = await this.getAddressUtxos(this.cashaddr);\n }\n // filter out token utxos if there are no token requests\n if (checkTokenQuantities &&\n !sendRequests.some((val) => val instanceof _model_js__WEBPACK_IMPORTED_MODULE_20__.TokenSendRequest)) {\n utxos = utxos.filter((val) => !val.token);\n }\n const addTokenChangeOutputs = (inputs, outputs) => {\n // allow for implicit token burn if the total amount sent is less than user had\n // allow for token genesis, creating more tokens than we had before (0)\n if (!checkTokenQuantities) {\n return;\n }\n const allTokenInputs = inputs.filter((val) => val.token);\n const allTokenOutputs = outputs.filter((val) => val instanceof _model_js__WEBPACK_IMPORTED_MODULE_20__.TokenSendRequest);\n const tokenIds = allTokenOutputs\n .map((val) => val.tokenId)\n .filter((val, idx, arr) => arr.indexOf(val) === idx);\n for (let tokenId of tokenIds) {\n const tokenInputs = allTokenInputs.filter((val) => val.token?.tokenId === tokenId);\n const inputAmountSum = tokenInputs.reduce((prev, cur) => prev + cur.token.amount, 0);\n const tokenOutputs = allTokenOutputs.filter((val) => val.tokenId === tokenId);\n const outputAmountSum = tokenOutputs.reduce((prev, cur) => prev + cur.amount, 0);\n const change = inputAmountSum - outputAmountSum;\n if (change < 0) {\n throw new Error(\"Not enough token amount to send\");\n }\n if (change > 0) {\n outputs.push(new _model_js__WEBPACK_IMPORTED_MODULE_20__.TokenSendRequest({\n cashaddr: (0,_util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_21__.toTokenaddr)(changeAddress) || this.tokenaddr,\n amount: change,\n tokenId: tokenId,\n commitment: tokenOutputs[0].commitment,\n capability: tokenOutputs[0].capability,\n value: tokenOutputs[0].value,\n }));\n }\n }\n };\n addTokenChangeOutputs(utxos, sendRequests);\n const bestHeight = await this.provider.getBlockHeight();\n const spendAmount = await (0,_util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_31__.sumSendRequestAmounts)(sendRequests);\n if (utxos.length === 0) {\n throw Error(\"There were no Unspent Outputs\");\n }\n if (typeof spendAmount !== \"bigint\") {\n throw Error(\"Couldn't get spend amount when building transaction\");\n }\n const relayFeePerByteInSatoshi = await (0,_network_getRelayFeeCache_js__WEBPACK_IMPORTED_MODULE_1__.getRelayFeeCache)(this.provider);\n const feeEstimate = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_29__.getFeeAmount)({\n utxos: utxos,\n sendRequests: sendRequests,\n privateKey: this.privateKey ?? Uint8Array.from([]),\n sourceAddress: this.cashaddr,\n relayFeePerByteInSatoshi: relayFeePerByteInSatoshi,\n slpOutputs: [],\n feePaidBy: feePaidBy,\n });\n const fundingUtxos = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_29__.getSuitableUtxos)(utxos, BigInt(spendAmount) + BigInt(feeEstimate), bestHeight, feePaidBy, sendRequests, options?.ensureUtxos || [], options?.tokenOperation);\n if (fundingUtxos.length === 0) {\n throw Error(\"The available inputs couldn't satisfy the request with fees\");\n }\n const fee = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_29__.getFeeAmount)({\n utxos: fundingUtxos,\n sendRequests: sendRequests,\n privateKey: this.privateKey ?? Uint8Array.from([]),\n sourceAddress: this.cashaddr,\n relayFeePerByteInSatoshi: relayFeePerByteInSatoshi,\n slpOutputs: [],\n feePaidBy: feePaidBy,\n });\n const { encodedTransaction, sourceOutputs } = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_29__.buildEncodedTransaction)({\n inputs: fundingUtxos,\n outputs: sendRequests,\n signingKey: this.privateKey ?? Uint8Array.from([]),\n sourceAddress: this.cashaddr,\n fee,\n discardChange,\n slpOutputs: [],\n feePaidBy,\n changeAddress,\n buildUnsigned: options?.buildUnsigned === true,\n });\n const tokenIds = [\n ...fundingUtxos\n .filter((val) => val.token?.tokenId)\n .map((val) => val.token.tokenId),\n ...sendRequests\n .filter((val) => val instanceof _model_js__WEBPACK_IMPORTED_MODULE_20__.TokenSendRequest)\n .map((val) => val.tokenId),\n ].filter((value, index, array) => array.indexOf(value) === index);\n return { encodedTransaction, tokenIds, sourceOutputs };\n }\n async signUnsignedTransaction(transaction, sourceOutputs) {\n if (!this.privateKey) {\n throw Error(\"Can not sign a transaction with watch-only wallet.\");\n }\n return (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_29__.signUnsignedTransaction)(transaction, sourceOutputs, this.privateKey);\n }\n // Submit a raw transaction\n async submitTransaction(transaction, awaitPropagation = true) {\n if (!this.provider) {\n throw Error(\"Wallet network provider was not initialized\");\n }\n let rawTransaction = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.binToHex)(transaction);\n return await this.provider.sendRawTransaction(rawTransaction, awaitPropagation);\n }\n // gets transaction history of this wallet\n async getRawHistory() {\n return await this.provider.getHistory(this.cashaddr);\n }\n // gets transaction history of this wallet\n async getHistory(unit, start, count, collapseChange) {\n return (0,_history_electrumTransformer_js__WEBPACK_IMPORTED_MODULE_32__.getAddressHistory)(this.cashaddr, this.provider, unit, start, count, collapseChange);\n }\n // gets last transaction of this wallet\n async getLastTransaction(confirmedOnly = false) {\n let history = await this.getRawHistory();\n if (confirmedOnly) {\n history = history.filter((val) => val.height > 0);\n }\n if (!history.length) {\n return null;\n }\n const [lastTx] = history.slice(-1);\n return this.provider.getRawTransactionObject(lastTx.tx_hash);\n }\n // waits for next transaction, program execution is halted\n async waitForTransaction(options = {\n getTransactionInfo: true,\n getBalance: false,\n txHash: undefined,\n }) {\n if (options.getTransactionInfo === undefined) {\n options.getTransactionInfo = true;\n }\n return new Promise(async (resolve) => {\n let txHashSeen = false;\n const makeResponse = async (txHash) => {\n const response = {};\n const promises = [undefined, undefined];\n if (options.getBalance === true) {\n promises[0] = this.getBalance();\n }\n if (options.getTransactionInfo === true) {\n if (!txHash) {\n promises[1] = this.getLastTransaction();\n }\n else {\n promises[1] = this.provider.getRawTransactionObject(txHash);\n }\n }\n const result = await Promise.all(promises);\n response.balance = result[0];\n response.transactionInfo = result[1];\n return response;\n };\n // waiting for a specific transaction to propagate\n if (options.txHash) {\n const waitForTransactionCallback = async (data) => {\n if (data && data[0] === options.txHash) {\n txHashSeen = true;\n this.provider.unsubscribeFromTransaction(options.txHash, waitForTransactionCallback);\n resolve(makeResponse(options.txHash));\n }\n };\n this.provider.subscribeToTransaction(options.txHash, waitForTransactionCallback);\n return;\n }\n // waiting for any address transaction\n const watchCancel = this.provider.watchAddressStatus(this.getDepositAddress(), async (_status) => {\n watchCancel();\n resolve(makeResponse());\n });\n });\n }\n /**\n * watchBlocks Watch network blocks\n *\n * @param callback callback with a block header object\n *\n * @returns a function which will cancel watching upon evaluation\n */\n watchBlocks(callback) {\n return this.provider.watchBlocks(callback);\n }\n /**\n * waitForBlock Wait for a network block\n *\n * @param height if specified waits for this exact blockchain height, otherwise resolves with the next block\n *\n */\n async waitForBlock(height) {\n return this.provider.waitForBlock(height);\n }\n //#endregion Funds\n //#region Private implementation details\n async deriveInfo() {\n const publicKey = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_33__.secp256k1.derivePublicKeyUncompressed(this.privateKey);\n if (typeof publicKey === \"string\") {\n throw new Error(publicKey);\n }\n this.publicKey = publicKey;\n const publicKeyCompressed = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_33__.secp256k1.derivePublicKeyCompressed(this.privateKey);\n if (typeof publicKeyCompressed === \"string\") {\n throw new Error(publicKeyCompressed);\n }\n this.publicKeyCompressed = publicKeyCompressed;\n const networkType = this.network === _enum_js__WEBPACK_IMPORTED_MODULE_4__.NetworkType.Regtest ? _enum_js__WEBPACK_IMPORTED_MODULE_4__.NetworkType.Testnet : this.network;\n this.privateKeyWif = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_23__.encodePrivateKeyWif)(this.privateKey, networkType);\n (0,_util_checkWifNetwork_js__WEBPACK_IMPORTED_MODULE_22__.checkWifNetwork)(this.privateKeyWif, this.network);\n this.cashaddr = (0,_util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_21__.deriveCashaddr)(this.privateKey, this.networkPrefix);\n this.tokenaddr = (0,_util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_21__.deriveTokenaddr)(this.privateKey, this.networkPrefix);\n this.address = this.cashaddr;\n this.publicKeyHash = (0,_util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_12__.derivePublicKeyHash)(this.cashaddr);\n return this;\n }\n //#endregion Private implementation details\n //#region Signing\n // Convenience wrapper to sign interface\n async sign(message) {\n return await Wallet.signedMessage.sign(message, this.privateKey);\n }\n // Convenience wrapper to verify interface\n async verify(message, sig, publicKey) {\n return await Wallet.signedMessage.verify(message, sig, this.cashaddr, publicKey);\n }\n //#endregion Signing\n //#region Cashtokens\n /**\n * Create new cashtoken, both funglible and/or non-fungible (NFT)\n * Refer to spec https://github.com/bitjson/cashtokens\n * @param {number} genesisRequest.amount amount of *fungible* tokens to create\n * @param {NFTCapability?} genesisRequest.capability capability of new NFT\n * @param {string?} genesisRequest.commitment NFT commitment message\n * @param {string?} genesisRequest.cashaddr cash address to send the created token UTXO to; if undefined will default to your address\n * @param {number?} genesisRequest.value satoshi value to send alongside with tokens; if undefined will default to 1000 satoshi\n * @param {SendRequestType | SendRequestType[]} sendRequests single or an array of extra send requests (OP_RETURN, value transfer, etc.) to include in genesis transaction\n * @param {SendRequestOptionsI} options Options of the send requests\n */\n async tokenGenesis(genesisRequest, sendRequests = [], options) {\n if (!Array.isArray(sendRequests)) {\n sendRequests = [sendRequests];\n }\n let utxos;\n if (options && options.utxoIds) {\n utxos = options.utxoIds.map((utxoId) => typeof utxoId === \"string\" ? (0,_model_js__WEBPACK_IMPORTED_MODULE_20__.fromUtxoId)(utxoId) : utxoId);\n }\n else {\n utxos = await this.getAddressUtxos(this.cashaddr);\n }\n const genesisInputs = utxos.filter((val) => val.vout === 0 && !val.token);\n if (genesisInputs.length === 0) {\n throw new Error(\"No suitable inputs with vout=0 available for new token genesis\");\n }\n const genesisSendRequest = new _model_js__WEBPACK_IMPORTED_MODULE_20__.TokenSendRequest({\n cashaddr: genesisRequest.cashaddr || this.tokenaddr,\n amount: genesisRequest.amount,\n value: genesisRequest.value || 1000,\n capability: genesisRequest.capability,\n commitment: genesisRequest.commitment,\n tokenId: genesisInputs[0].txid,\n });\n return this.send([genesisSendRequest, ...sendRequests], {\n ...options,\n utxoIds: utxos,\n ensureUtxos: [genesisInputs[0]],\n checkTokenQuantities: false,\n queryBalance: false,\n tokenOperation: \"genesis\",\n });\n }\n /**\n * Mint new NFT cashtokens using an existing minting token\n * Refer to spec https://github.com/bitjson/cashtokens\n * @param {string} tokenId tokenId of an NFT to mint\n * @param {TokenMintRequest | TokenMintRequest[]} mintRequests mint requests with new token properties and recipients\n * @param {NFTCapability?} mintRequest.capability capability of new NFT\n * @param {string?} mintRequest.commitment NFT commitment message\n * @param {string?} mintRequest.cashaddr cash address to send the created token UTXO to; if undefined will default to your address\n * @param {number?} mintRequest.value satoshi value to send alongside with tokens; if undefined will default to 1000 satoshi\n * @param {boolean?} deductTokenAmount if minting token contains fungible amount, deduct from it by amount of minted tokens\n * @param {SendRequestOptionsI} options Options of the send requests\n */\n async tokenMint(tokenId, mintRequests, deductTokenAmount = false, options) {\n if (tokenId?.length !== 64) {\n throw Error(`Invalid tokenId supplied: ${tokenId}`);\n }\n if (!Array.isArray(mintRequests)) {\n mintRequests = [mintRequests];\n }\n const utxos = await this.getAddressUtxos(this.cashaddr);\n const nftUtxos = utxos.filter((val) => val.token?.tokenId === tokenId &&\n val.token?.capability === _interface_js__WEBPACK_IMPORTED_MODULE_8__.NFTCapability.minting);\n if (!nftUtxos.length) {\n throw new Error(\"You do not have any token UTXOs with minting capability for specified tokenId\");\n }\n const newAmount = deductTokenAmount && nftUtxos[0].token.amount > 0\n ? nftUtxos[0].token.amount - mintRequests.length\n : nftUtxos[0].token.amount;\n const safeNewAmount = Math.max(0, newAmount);\n const mintingInput = new _model_js__WEBPACK_IMPORTED_MODULE_20__.TokenSendRequest({\n cashaddr: this.tokenaddr,\n tokenId: tokenId,\n capability: nftUtxos[0].token.capability,\n commitment: nftUtxos[0].token.commitment,\n amount: safeNewAmount,\n value: nftUtxos[0].satoshis,\n });\n return this.send([\n mintingInput,\n ...mintRequests.map((val) => new _model_js__WEBPACK_IMPORTED_MODULE_20__.TokenSendRequest({\n cashaddr: val.cashaddr || this.tokenaddr,\n amount: 0,\n tokenId: tokenId,\n value: val.value,\n capability: val.capability,\n commitment: val.commitment,\n })),\n ], {\n ...options,\n ensureUtxos: [nftUtxos[0]],\n checkTokenQuantities: false,\n queryBalance: false,\n tokenOperation: \"mint\",\n });\n }\n /**\n * Perform an explicit token burning by spending a token utxo to an OP_RETURN\n *\n * Behaves differently for fungible and non-fungible tokens:\n * * NFTs are always \"destroyed\"\n * * FTs' amount is reduced by the amount specified, if 0 FT amount is left and no NFT present, the token is \"destroyed\"\n *\n * Refer to spec https://github.com/bitjson/cashtokens\n * @param {string} burnRequest.tokenId tokenId of a token to burn\n * @param {NFTCapability} burnRequest.capability capability of the NFT token to select, optional\n * @param {string?} burnRequest.commitment commitment of the NFT token to select, optional\n * @param {number?} burnRequest.amount amount of fungible tokens to burn, optional\n * @param {string?} burnRequest.cashaddr address to return token and satoshi change to\n * @param {string?} message optional message to include in OP_RETURN\n * @param {SendRequestOptionsI} options Options of the send requests\n */\n async tokenBurn(burnRequest, message, options) {\n if (burnRequest.tokenId?.length !== 64) {\n throw Error(`Invalid tokenId supplied: ${burnRequest.tokenId}`);\n }\n const utxos = await this.getAddressUtxos(this.cashaddr);\n const tokenUtxos = utxos.filter((val) => val.token?.tokenId === burnRequest.tokenId &&\n val.token?.capability === burnRequest.capability &&\n val.token?.commitment === burnRequest.commitment);\n if (!tokenUtxos.length) {\n throw new Error(\"You do not have suitable token UTXOs to perform burn\");\n }\n const totalFungibleAmount = tokenUtxos.reduce((prev, cur) => prev + (cur.token?.amount || 0), 0);\n const fungibleBurnAmount = burnRequest.amount && burnRequest.amount > 0 ? burnRequest.amount : 0;\n const hasNFT = burnRequest.capability || burnRequest.commitment;\n let utxoIds = [];\n let changeSendRequests;\n if (hasNFT) {\n // does not have FT tokens, let us destroy the token completely\n if (totalFungibleAmount === 0) {\n changeSendRequests = [];\n utxoIds.push(tokenUtxos[0]);\n }\n else {\n // add utxos to spend from\n let available = 0;\n for (const token of tokenUtxos.filter((val) => val.token?.amount)) {\n utxoIds.push(token);\n available += token.token?.amount;\n if (available >= fungibleBurnAmount) {\n break;\n }\n }\n // if there are FT, reduce their amount\n const newAmount = totalFungibleAmount - fungibleBurnAmount;\n const safeNewAmount = Math.max(0, newAmount);\n changeSendRequests = [\n new _model_js__WEBPACK_IMPORTED_MODULE_20__.TokenSendRequest({\n cashaddr: burnRequest.cashaddr || this.tokenaddr,\n tokenId: burnRequest.tokenId,\n capability: burnRequest.capability,\n commitment: burnRequest.commitment,\n amount: safeNewAmount,\n value: tokenUtxos[0].satoshis,\n }),\n ];\n }\n }\n else {\n // if we are burning last fughible tokens, let us destroy the token completely\n if (totalFungibleAmount === fungibleBurnAmount) {\n changeSendRequests = [];\n utxoIds.push(tokenUtxos[0]);\n }\n else {\n // add utxos to spend from\n let available = 0;\n for (const token of tokenUtxos.filter((val) => val.token?.amount)) {\n utxoIds.push(token);\n available += token.token?.amount;\n if (available >= fungibleBurnAmount) {\n break;\n }\n }\n // reduce the FT amount\n const newAmount = totalFungibleAmount - fungibleBurnAmount;\n const safeNewAmount = Math.max(0, newAmount);\n changeSendRequests = [\n new _model_js__WEBPACK_IMPORTED_MODULE_20__.TokenSendRequest({\n cashaddr: burnRequest.cashaddr || this.tokenaddr,\n tokenId: burnRequest.tokenId,\n amount: safeNewAmount,\n value: tokenUtxos[0].satoshis,\n }),\n ];\n }\n }\n const opReturn = _model_js__WEBPACK_IMPORTED_MODULE_20__.OpReturnData.fromString(message || \"\");\n return this.send([opReturn, ...changeSendRequests], {\n ...options,\n checkTokenQuantities: false,\n queryBalance: false,\n ensureUtxos: utxoIds.length > 0 ? utxoIds : undefined,\n tokenOperation: \"burn\",\n });\n }\n /**\n * getTokenUtxos Get unspent token outputs for the wallet\n * will return utxos only for the specified token if `tokenId` provided\n * @param {string?} tokenId tokenId (category) to filter utxos by, if not set will return utxos from all tokens\n * @returns {UtxoI[]} token utxos\n */\n async getTokenUtxos(tokenId) {\n const utxos = await this.getAddressUtxos(this.address);\n return utxos.filter((val) => tokenId ? val.token?.tokenId === tokenId : val.token);\n }\n /**\n * getTokenBalance Gets fungible token balance\n * for NFT token balance see @ref getNftTokenBalance\n * @param {string} tokenId tokenId to get balance for\n * @returns {number} fungible token balance\n */\n async getTokenBalance(tokenId) {\n const utxos = (await this.getTokenUtxos(tokenId)).filter((val) => val.token?.amount);\n return (0,_util_sumUtxoValue_js__WEBPACK_IMPORTED_MODULE_26__.sumTokenAmounts)(utxos, tokenId);\n }\n /**\n * getNftTokenBalance Gets non-fungible token (NFT) balance for a particula tokenId\n * disregards fungible token balances\n * for fungible token balance see @ref getTokenBalance\n * @param {string} tokenId tokenId to get balance for\n * @returns {number} non-fungible token balance\n */\n async getNftTokenBalance(tokenId) {\n const utxos = (await this.getTokenUtxos(tokenId)).filter((val) => val.token?.commitment !== undefined);\n return utxos.length;\n }\n /**\n * getAllTokenBalances Gets all fungible token balances in this wallet\n * @returns {Object} a map [tokenId => balance] for all tokens in this wallet\n */\n async getAllTokenBalances() {\n const result = {};\n const utxos = (await this.getTokenUtxos()).filter((val) => val.token?.amount);\n for (const utxo of utxos) {\n if (!result[utxo.token.tokenId]) {\n result[utxo.token.tokenId] = 0;\n }\n result[utxo.token.tokenId] += utxo.token.amount;\n }\n return result;\n }\n /**\n * getAllNftTokenBalances Gets all non-fungible token (NFT) balances in this wallet\n * @returns {Object} a map [tokenId => balance] for all NFTs in this wallet\n */\n async getAllNftTokenBalances() {\n const result = {};\n const utxos = (await this.getTokenUtxos()).filter((val) => val.token?.commitment !== undefined);\n for (const utxo of utxos) {\n if (!result[utxo.token.tokenId]) {\n result[utxo.token.tokenId] = 0;\n }\n result[utxo.token.tokenId] += 1;\n }\n return result;\n }\n}\nWallet.signedMessage = new _message_index_js__WEBPACK_IMPORTED_MODULE_34__.SignedMessage();\n/**\n * Class to manage a testnet wallet.\n */\nclass TestNetWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_4__.NetworkType.Testnet);\n }\n // will receive 10000 testnet satoshi, rate limits apply\n async getTestnetSatoshis() {\n try {\n const response = await axios__WEBPACK_IMPORTED_MODULE_2___default().post(`${TestNetWallet.faucetServer}/faucet/get_testnet_bch`, { cashaddr: this.cashaddr });\n const data = response.data;\n return data.txId;\n }\n catch (e) {\n // console.log(e);\n // console.log(e.response ? e.response.data : \"\");\n throw e;\n }\n }\n // be nice and return them back\n async returnTestnetSatoshis() {\n try {\n const response = await axios__WEBPACK_IMPORTED_MODULE_2___default().post(`${TestNetWallet.faucetServer}/faucet/get_addresses`);\n const data = response.data;\n return await this.slpAware().sendMax(data.bchtest);\n }\n catch (e) {\n console.log(e);\n console.log(e.response ? e.response.data : \"\");\n throw e;\n }\n }\n // will receive 10 testnet tokens, rate limits apply\n async getTestnetSlp(tokenId) {\n try {\n const response = await axios__WEBPACK_IMPORTED_MODULE_2___default().post(`${TestNetWallet.faucetServer}/faucet/get_testnet_slp`, { slpaddr: this.slp.slpaddr, tokenId: tokenId });\n const data = response.data;\n return data.txId;\n }\n catch (e) {\n //console.log(e);\n //console.log(e.response ? e.response.data : \"\");\n throw e;\n }\n }\n // be nice and return them back\n async returnTestnetSlp(tokenId) {\n try {\n const response = await axios__WEBPACK_IMPORTED_MODULE_2___default().post(`${TestNetWallet.faucetServer}/faucet/get_addresses`);\n const data = response.data;\n return await this.slp.sendMax(data.slptest, tokenId);\n }\n catch (e) {\n console.log(e);\n console.log(e.response ? e.response.data : \"\");\n throw e;\n }\n }\n // interface to static slp functions. see Slp.ts\n static get slp() {\n return _Slp_js__WEBPACK_IMPORTED_MODULE_6__.TestNetSlp;\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_7__.TestNetUtil;\n }\n}\nTestNetWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_35__.CashAddressNetworkPrefix.testnet;\nTestNetWallet.faucetServer = \"https://rest-unstable.mainnet.cash\";\n/**\n * Class to manage a regtest wallet.\n */\nclass RegTestWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_4__.NetworkType.Regtest);\n }\n // interface to static slp functions. see Slp.ts\n static get slp() {\n return _Slp_js__WEBPACK_IMPORTED_MODULE_6__.RegTestSlp;\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_7__.RegTestUtil;\n }\n}\nRegTestWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_35__.CashAddressNetworkPrefix.regtest;\n/**\n * Class to manage a bitcoin cash wif wallet.\n */\nclass WifWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_4__.NetworkType.Mainnet, _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Wif);\n }\n // interface to static slp functions. see Slp.ts\n static get slp() {\n return _Slp_js__WEBPACK_IMPORTED_MODULE_6__.WifSlp;\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_7__.WifUtil;\n }\n}\nWifWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_35__.CashAddressNetworkPrefix.mainnet;\nWifWallet.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Wif;\n/**\n * Class to manage a testnet wif wallet.\n */\nclass TestNetWifWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_4__.NetworkType.Testnet, _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Wif);\n }\n // interface to static slp functions. see Slp.ts\n static get slp() {\n return _Slp_js__WEBPACK_IMPORTED_MODULE_6__.TestNetWifSlp;\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_7__.TestNetWifUtil;\n }\n}\nTestNetWifWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_35__.CashAddressNetworkPrefix.testnet;\nTestNetWifWallet.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Wif;\n/**\n * Class to manage a regtest wif wallet.\n */\nclass RegTestWifWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_4__.NetworkType.Regtest, _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Wif);\n }\n // interface to static slp functions. see Slp.ts\n static get slp() {\n return _Slp_js__WEBPACK_IMPORTED_MODULE_6__.RegTestWifSlp;\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_7__.RegTestWifUtil;\n }\n}\nRegTestWifWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_35__.CashAddressNetworkPrefix.regtest;\nRegTestWifWallet.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Wif;\n/**\n * Class to manage a bitcoin cash watch wallet.\n */\nclass WatchWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_4__.NetworkType.Mainnet, _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Watch);\n }\n // interface to static slp functions. see Slp.ts\n static get slp() {\n return _Slp_js__WEBPACK_IMPORTED_MODULE_6__.WatchSlp;\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_7__.WatchUtil;\n }\n}\nWatchWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_35__.CashAddressNetworkPrefix.mainnet;\nWatchWallet.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Watch;\n/**\n * Class to manage a testnet watch wallet.\n */\nclass TestNetWatchWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_4__.NetworkType.Testnet, _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Watch);\n }\n // interface to static slp functions. see Slp.ts\n static get slp() {\n return _Slp_js__WEBPACK_IMPORTED_MODULE_6__.TestNetWatchSlp;\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_7__.TestNetWatchUtil;\n }\n}\nTestNetWatchWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_35__.CashAddressNetworkPrefix.testnet;\nTestNetWatchWallet.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Watch;\n/**\n * Class to manage a regtest watch wallet.\n */\nclass RegTestWatchWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_4__.NetworkType.Regtest, _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Watch);\n }\n // interface to static slp functions. see Slp.ts\n static get slp() {\n return _Slp_js__WEBPACK_IMPORTED_MODULE_6__.RegTestWatchSlp;\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_7__.RegTestWatchUtil;\n }\n}\nRegTestWatchWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_35__.CashAddressNetworkPrefix.regtest;\nRegTestWatchWallet.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Watch;\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/wallet/Wif.ts?");
1668
1668
 
1669
1669
  /***/ }),
1670
1670
 
@@ -1894,7 +1894,7 @@ eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harm
1894
1894
  \*****************************************************************************/
1895
1895
  /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
1896
1896
 
1897
- eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"CashAddressEncodingError\": () => (/* binding */ CashAddressEncodingError),\n/* harmony export */ \"CashAddressNetworkPrefix\": () => (/* binding */ CashAddressNetworkPrefix),\n/* harmony export */ \"CashAddressType\": () => (/* binding */ CashAddressType),\n/* harmony export */ \"CashAddressVersionByte\": () => (/* binding */ CashAddressVersionByte),\n/* harmony export */ \"decodeCashAddress\": () => (/* binding */ decodeCashAddress),\n/* harmony export */ \"decodeCashAddressFormat\": () => (/* binding */ decodeCashAddressFormat),\n/* harmony export */ \"decodeCashAddressFormatWithoutPrefix\": () => (/* binding */ decodeCashAddressFormatWithoutPrefix),\n/* harmony export */ \"encodeCashAddress\": () => (/* binding */ encodeCashAddress)\n/* harmony export */ });\n/* unused harmony exports CashAddressTypeBits, cashAddressTypeToTypeBits, cashAddressTypeBitsToType, cashAddressSizeBitsToLength, cashAddressLengthToSizeBits, encodeCashAddressVersionByte, CashAddressVersionByteDecodingError, decodeCashAddressVersionByte, maskCashAddressPrefix, cashAddressPolynomialModulo, cashAddressChecksumToUint5Array, encodeCashAddressFormat, isValidCashAddressPayloadLength, encodeCashAddressNonStandard, CashAddressDecodingError, decodeCashAddressNonStandard, cashAddressPolynomialToCashAddress, CashAddressCorrectionError, attemptCashAddressFormatErrorCorrection */\n/* harmony import */ var _format_format_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../format/format.js */ \"../../node_modules/@bitauth/libauth/build/lib/format/error.js\");\n/* harmony import */ var _bech32_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./bech32.js */ \"../../node_modules/@bitauth/libauth/build/lib/address/bech32.js\");\n\n\nvar CashAddressNetworkPrefix;\n(function (CashAddressNetworkPrefix) {\n CashAddressNetworkPrefix[\"mainnet\"] = \"bitcoincash\";\n CashAddressNetworkPrefix[\"testnet\"] = \"bchtest\";\n CashAddressNetworkPrefix[\"regtest\"] = \"bchreg\";\n})(CashAddressNetworkPrefix || (CashAddressNetworkPrefix = {}));\n/**\n * The CashAddress specification standardizes the format of the version byte:\n * - Most significant bit: reserved, must be `0`\n * - next 4 bits: Address Type\n * - 3 least significant bits: Payload Size\n *\n * Two Address Type values are currently standardized:\n * - 0 (`0b0000`): P2PKH\n * - 1 (`0b0001`): P2SH\n *\n * And two are proposed by `CHIP-2022-02-CashTokens`:\n * - 2 (`0b0010`): P2PKH + Token Support\n * - 3 (`0b0011`): P2SH + Token Support\n *\n * The CashAddress specification standardizes expected payload size using\n * {@link CashAddressSizeBits}. Currently, two size bit values are in use by\n * standard CashAddress types:\n * - `0` (`0b000`): 20 bytes (in use by `p2pkh` and `p2sh20`)\n * - `3` (`0b011`): 32 bytes (in use by `p2sh32`)\n */\nvar CashAddressVersionByte;\n(function (CashAddressVersionByte) {\n /**\n * Pay to Public Key Hash (P2PKH): `0b00000000`\n *\n * - Most significant bit: `0` (reserved)\n * - Address Type bits: `0000` (P2PKH)\n * - Size bits: `000` (20 bytes)\n */\n CashAddressVersionByte[CashAddressVersionByte[\"p2pkh\"] = 0] = \"p2pkh\";\n /**\n * 20-byte Pay to Script Hash (P2SH20): `0b00001000`\n *\n * - Most significant bit: `0` (reserved)\n * - Address Type bits: `0001` (P2SH)\n * - Size bits: `000` (20 bytes)\n */\n CashAddressVersionByte[CashAddressVersionByte[\"p2sh20\"] = 8] = \"p2sh20\";\n /**\n * 32-byte Pay to Script Hash (P2SH20): `0b00001000`\n *\n * - Most significant bit: `0` (reserved)\n * - Address Type bits: `0001` (P2SH)\n * - Size bits: `011` (32 bytes)\n */\n CashAddressVersionByte[CashAddressVersionByte[\"p2sh32\"] = 11] = \"p2sh32\";\n /**\n * Pay to Public Key Hash (P2PKH) with token support: `0b00010000`\n *\n * - Most significant bit: `0` (reserved)\n * - Address Type bits: `0010` (P2PKH + Tokens)\n * - Size bits: `000` (20 bytes)\n */\n CashAddressVersionByte[CashAddressVersionByte[\"p2pkhWithTokens\"] = 16] = \"p2pkhWithTokens\";\n /**\n * 20-byte Pay to Script Hash (P2SH20) with token support: `0b00011000`\n * - Most significant bit: `0` (reserved)\n * - Address Type bits: `0011` (P2SH + Tokens)\n * - Size bits: `000` (20 bytes)\n */\n CashAddressVersionByte[CashAddressVersionByte[\"p2sh20WithTokens\"] = 24] = \"p2sh20WithTokens\";\n /**\n * 32-byte Pay to Script Hash (P2SH32) with token support: `0b00011011`\n * - Most significant bit: `0` (reserved)\n * - Address Type bits: `0011` (P2SH + Tokens)\n * - Size bits: `011` (32 bytes)\n */\n CashAddressVersionByte[CashAddressVersionByte[\"p2sh32WithTokens\"] = 27] = \"p2sh32WithTokens\";\n})(CashAddressVersionByte || (CashAddressVersionByte = {}));\n/**\n * The address types currently defined in the CashAddress specification. See\n * also: {@link CashAddressVersionByte}.\n */\nvar CashAddressType;\n(function (CashAddressType) {\n /**\n * Pay to Public Key Hash (P2PKH): `0b0000`\n */\n CashAddressType[\"p2pkh\"] = \"p2pkh\";\n /**\n * Pay to Script Hash (P2SH): `0b0001`\n */\n CashAddressType[\"p2sh\"] = \"p2sh\";\n /**\n * Pay to Public Key Hash (P2PKH) with token support: `0b0010`\n */\n CashAddressType[\"p2pkhWithTokens\"] = \"p2pkhWithTokens\";\n /**\n * Pay to Script Hash (P2SH) with token support: `0b0011`\n */\n CashAddressType[\"p2shWithTokens\"] = \"p2shWithTokens\";\n})(CashAddressType || (CashAddressType = {}));\n/**\n * The address type bits currently defined in the CashAddress specification.\n * These map to: {@link CashAddressType}.\n */\nvar CashAddressTypeBits;\n(function (CashAddressTypeBits) {\n /**\n * Pay to Public Key Hash (P2PKH)\n */\n CashAddressTypeBits[CashAddressTypeBits[\"p2pkh\"] = 0] = \"p2pkh\";\n /**\n * Pay to Script Hash (P2SH)\n */\n CashAddressTypeBits[CashAddressTypeBits[\"p2sh\"] = 1] = \"p2sh\";\n /**\n * Pay to Public Key Hash (P2PKH) with token support\n */\n CashAddressTypeBits[CashAddressTypeBits[\"p2pkhWithTokens\"] = 2] = \"p2pkhWithTokens\";\n /**\n * Pay to Script Hash (P2SH) with token support\n */\n CashAddressTypeBits[CashAddressTypeBits[\"p2shWithTokens\"] = 3] = \"p2shWithTokens\";\n})(CashAddressTypeBits || (CashAddressTypeBits = {}));\nconst cashAddressTypeToTypeBits = {\n [CashAddressType.p2pkh]: CashAddressTypeBits.p2pkh,\n [CashAddressType.p2sh]: CashAddressTypeBits.p2sh,\n [CashAddressType.p2pkhWithTokens]: CashAddressTypeBits.p2pkhWithTokens,\n [CashAddressType.p2shWithTokens]: CashAddressTypeBits.p2shWithTokens,\n};\nconst cashAddressTypeBitsToType = {\n [CashAddressTypeBits.p2pkh]: CashAddressType.p2pkh,\n [CashAddressTypeBits.p2sh]: CashAddressType.p2sh,\n [CashAddressTypeBits.p2pkhWithTokens]: CashAddressType.p2pkhWithTokens,\n [CashAddressTypeBits.p2shWithTokens]: CashAddressType.p2shWithTokens,\n};\n/* eslint-disable @typescript-eslint/naming-convention */\nconst cashAddressSizeBitsToLength = {\n 0: 20,\n 1: 24,\n 2: 28,\n 3: 32,\n 4: 40,\n 5: 48,\n 6: 56,\n 7: 64,\n};\nconst cashAddressLengthToSizeBits = {\n 20: 0,\n 24: 1,\n 28: 2,\n 32: 3,\n 40: 4,\n 48: 5,\n 56: 6,\n 64: 7,\n};\n/**\n * Encode a CashAddress version byte for the given address type and payload\n * length. See {@link CashAddressVersionByte} for more information.\n *\n * The `type` parameter must be a number between `0` and `15`, and `bitLength`\n * must be one of the standardized lengths. To use the contents of a variable,\n * cast it to {@link CashAddressType} or {@link CashAddressSize} respectively,\n * e.g.:\n * ```ts\n * const type = 3 as CashAddressType;\n * const size = 160 as CashAddressSize;\n * getCashAddressVersionByte(type, size);\n * ```\n * @param typeBits - the address type bit of the payload being encoded\n * @param length - the length of the payload being encoded\n */\nconst encodeCashAddressVersionByte = (typeBits, length) => \n// eslint-disable-next-line no-bitwise\n(typeBits << 3 /* Constants.cashAddressTypeBitsShift */) |\n cashAddressLengthToSizeBits[length];\nvar CashAddressVersionByteDecodingError;\n(function (CashAddressVersionByteDecodingError) {\n CashAddressVersionByteDecodingError[\"reservedBitSet\"] = \"Reserved bit is set.\";\n})(CashAddressVersionByteDecodingError || (CashAddressVersionByteDecodingError = {}));\n/**\n * Decode a CashAddress version byte. For a list of known versions, see\n * {@link CashAddressVersionByte}.\n *\n * @param version - the version byte to decode\n */\nconst decodeCashAddressVersionByte = (version) => \n// eslint-disable-next-line no-negated-condition, no-bitwise\n(version & 128 /* Constants.cashAddressReservedBitMask */) !== 0\n ? CashAddressVersionByteDecodingError.reservedBitSet\n : {\n length: cashAddressSizeBitsToLength[\n // eslint-disable-next-line no-bitwise\n (version &\n 7 /* Constants.cashAddressSizeBits */)],\n typeBits: \n // eslint-disable-next-line no-bitwise\n (version >>> 3 /* Constants.cashAddressTypeBitsShift */) &\n 15 /* Constants.cashAddressTypeBits */,\n };\n/**\n * Convert a string into an array of 5-bit numbers, representing the characters\n * in a case-insensitive way.\n * @param prefix - the prefix to mask\n */\nconst maskCashAddressPrefix = (prefix) => {\n const result = [];\n // eslint-disable-next-line functional/no-let, functional/no-loop-statement, no-plusplus\n for (let i = 0; i < prefix.length; i++) {\n // eslint-disable-next-line functional/no-expression-statement, no-bitwise, functional/immutable-data\n result.push(prefix.charCodeAt(i) & 31 /* Constants.asciiCaseInsensitiveBits */);\n }\n return result;\n};\n// prettier-ignore\nconst bech32GeneratorMostSignificantByte = [0x98, 0x79, 0xf3, 0xae, 0x1e]; // eslint-disable-line @typescript-eslint/no-magic-numbers\n// prettier-ignore\nconst bech32GeneratorRemainingBytes = [0xf2bc8e61, 0xb76d99e2, 0x3e5fb3c4, 0x2eabe2a8, 0x4f43e470]; // eslint-disable-line @typescript-eslint/no-magic-numbers\n/**\n * Perform the CashAddress polynomial modulo operation, which is based on the\n * Bech32 polynomial modulo operation, but the returned checksum is 40 bits,\n * rather than 30.\n *\n * A.K.A. `PolyMod`\n *\n * @remarks\n * Notes from C++ implementation:\n * This function will compute what 8 5-bit values to XOR into the last 8 input\n * values, in order to make the checksum 0. These 8 values are packed together\n * in a single 40-bit integer. The higher bits correspond to earlier values.\n *\n * The input is interpreted as a list of coefficients of a polynomial over F\n * = GF(32), with an implicit 1 in front. If the input is [v0,v1,v2,v3,v4],\n * that polynomial is v(x) = 1*x^5 + v0*x^4 + v1*x^3 + v2*x^2 + v3*x + v4.\n * The implicit 1 guarantees that [v0,v1,v2,...] has a distinct checksum\n * from [0,v0,v1,v2,...].\n *\n * The output is a 40-bit integer whose 5-bit groups are the coefficients of\n * the remainder of v(x) mod g(x), where g(x) is the cashaddr generator, x^8\n * + [19]*x^7 + [3]*x^6 + [25]*x^5 + [11]*x^4 + [25]*x^3 + [3]*x^2 + [19]*x\n * + [1]. g(x) is chosen in such a way that the resulting code is a BCH\n * code, guaranteeing detection of up to 4 errors within a window of 1025\n * characters. Among the various possible BCH codes, one was selected to in\n * fact guarantee detection of up to 5 errors within a window of 160\n * characters and 6 errors within a window of 126 characters. In addition,\n * the code guarantee the detection of a burst of up to 8 errors.\n *\n * Note that the coefficients are elements of GF(32), here represented as\n * decimal numbers between []. In this finite field, addition is just XOR of\n * the corresponding numbers. For example, [27] + [13] = [27 ^ 13] = [22].\n * Multiplication is more complicated, and requires treating the bits of\n * values themselves as coefficients of a polynomial over a smaller field,\n * GF(2), and multiplying those polynomials mod a^5 + a^3 + 1. For example,\n * [5] * [26] = (a^2 + 1) * (a^4 + a^3 + a) = (a^4 + a^3 + a) * a^2 + (a^4 +\n * a^3 + a) = a^6 + a^5 + a^4 + a = a^3 + 1 (mod a^5 + a^3 + 1) = [9].\n *\n * During the course of the loop below, `c` contains the bit-packed\n * coefficients of the polynomial constructed from just the values of v that\n * were processed so far, mod g(x). In the above example, `c` initially\n * corresponds to 1 mod (x), and after processing 2 inputs of v, it\n * corresponds to x^2 + v0*x + v1 mod g(x). As 1 mod g(x) = 1, that is the\n * starting value for `c`.\n *\n * @param v - Array of 5-bit integers over which the checksum is to be computed\n */\n// Derived from the `bitcore-lib-cash` implementation (does not require BigInt): https://github.com/bitpay/bitcore\nconst cashAddressPolynomialModulo = (v) => {\n /* eslint-disable functional/no-let, functional/no-loop-statement, functional/no-expression-statement, no-bitwise, @typescript-eslint/no-magic-numbers */\n let mostSignificantByte = 0;\n let lowerBytes = 1;\n let c = 0;\n // eslint-disable-next-line @typescript-eslint/prefer-for-of, no-plusplus\n for (let j = 0; j < v.length; j++) {\n c = mostSignificantByte >>> 3;\n mostSignificantByte &= 0x07;\n mostSignificantByte <<= 5;\n mostSignificantByte |= lowerBytes >>> 27;\n lowerBytes &= 0x07ffffff;\n lowerBytes <<= 5;\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n lowerBytes ^= v[j];\n // eslint-disable-next-line no-plusplus\n for (let i = 0; i < bech32GeneratorMostSignificantByte.length; ++i) {\n // eslint-disable-next-line functional/no-conditional-statement\n if (c & (1 << i)) {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n mostSignificantByte ^= bech32GeneratorMostSignificantByte[i];\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n lowerBytes ^= bech32GeneratorRemainingBytes[i];\n }\n }\n }\n lowerBytes ^= 1;\n // eslint-disable-next-line functional/no-conditional-statement\n if (lowerBytes < 0) {\n lowerBytes ^= 1 << 31;\n lowerBytes += (1 << 30) * 2;\n }\n return mostSignificantByte * (1 << 30) * 4 + lowerBytes;\n /* eslint-enable functional/no-let, functional/no-loop-statement, functional/no-expression-statement, no-bitwise, @typescript-eslint/no-magic-numbers */\n};\n/**\n * Convert the checksum returned by {@link cashAddressPolynomialModulo} to an\n * array of 5-bit positive integers that can be Base32 encoded.\n * @param checksum - a 40 bit checksum returned by\n * {@link cashAddressPolynomialModulo}\n */\nconst cashAddressChecksumToUint5Array = (checksum) => {\n const result = [];\n // eslint-disable-next-line functional/no-let, functional/no-loop-statement, no-plusplus\n for (let i = 0; i < 8 /* Constants.base256WordLength */; ++i) {\n // eslint-disable-next-line functional/no-expression-statement, no-bitwise, @typescript-eslint/no-magic-numbers, functional/immutable-data\n result.push(checksum & 31);\n // eslint-disable-next-line functional/no-expression-statement, @typescript-eslint/no-magic-numbers, no-param-reassign\n checksum /= 32;\n }\n // eslint-disable-next-line functional/immutable-data\n return result.reverse();\n};\n/**\n * Encode a payload as a CashAddress-like string using the CashAddress format.\n *\n * To encode a standard CashAddress, use {@link encodeCashAddress}.\n *\n * @param prefix - a valid prefix indicating the network for which to encode the\n * address – must be only lowercase letters (for standard CashAddress prefixes,\n * see {@link CashAddressNetworkPrefix})\n * @param version - a single byte indicating the version of this address (for\n * standard CashAddress versions, see {@link CashAddressVersionByte})\n * @param payload - the payload to encode\n */\nconst encodeCashAddressFormat = (prefix, version, payload) => {\n const checksum40BitPlaceholder = [0, 0, 0, 0, 0, 0, 0, 0];\n const payloadContents = (0,_bech32_js__WEBPACK_IMPORTED_MODULE_0__.regroupBits)({\n bin: Uint8Array.from([version, ...payload]),\n resultWordLength: 5 /* Constants.base32WordLength */,\n sourceWordLength: 8 /* Constants.base256WordLength */,\n });\n const checksumContents = [\n ...maskCashAddressPrefix(prefix),\n 0 /* Constants.payloadSeparator */,\n ...payloadContents,\n ...checksum40BitPlaceholder,\n ];\n const checksum = cashAddressPolynomialModulo(checksumContents);\n const encoded = [\n ...payloadContents,\n ...cashAddressChecksumToUint5Array(checksum),\n ];\n return `${prefix}:${(0,_bech32_js__WEBPACK_IMPORTED_MODULE_0__.encodeBech32)(encoded)}`;\n};\nvar CashAddressEncodingError;\n(function (CashAddressEncodingError) {\n CashAddressEncodingError[\"unsupportedPayloadLength\"] = \"Error encoding CashAddress: a payload of this length can not be encoded as a valid CashAddress.\";\n CashAddressEncodingError[\"noTypeBitsValueStandardizedForP2pk\"] = \"Error encoding CashAddress: no CashAddress type bit has been standardized for P2PK locking bytecode.\";\n CashAddressEncodingError[\"unknownLockingBytecodeType\"] = \"Error encoding CashAddress: unknown locking bytecode type.\";\n})(CashAddressEncodingError || (CashAddressEncodingError = {}));\nconst isValidCashAddressPayloadLength = (length) => cashAddressLengthToSizeBits[length] !== undefined;\n/**\n * Encode a payload as a CashAddress. This function is similar to\n * {@link encodeCashAddress} but supports non-standard `prefix`es and `type`s.\n *\n * **Note: this function cannot prevent all implementation errors via types.**\n * The function will throw if `payload` is not a valid\n * {@link CashAddressSupportedLength}. Confirm the length of untrusted inputs\n * before providing them to this function.\n *\n * For other address standards that closely follow the CashAddress\n * specification (but have alternative version byte requirements), use\n * {@link encodeCashAddressFormat}.\n *\n * @param prefix - a valid prefix indicating the network for which to encode the\n * address (usually a {@link CashAddressNetworkPrefix}) – must be only lowercase\n * letters\n * @param typeBits - the type bit to encode in the version byte – must be a\n * number between `0` and `15`\n * @param payload - the payload to encode (for P2PKH, the public key hash; for\n * P2SH, the redeem bytecode hash)\n */\nconst encodeCashAddressNonStandard = (prefix, typeBits, payload) => {\n const { length } = payload;\n if (!isValidCashAddressPayloadLength(length)) {\n // eslint-disable-next-line functional/no-throw-statement\n throw new Error((0,_format_format_js__WEBPACK_IMPORTED_MODULE_1__.formatError)(CashAddressEncodingError.unsupportedPayloadLength, `Payload length: ${length}.`));\n }\n return encodeCashAddressFormat(prefix, encodeCashAddressVersionByte(typeBits, length), payload);\n};\n/**\n * Encode a payload as a CashAddress.\n *\n * **Note: this function cannot prevent all implementation errors via types.**\n * The function will throw if `payload` is not a valid\n * {@link CashAddressSupportedLength}. Confirm the length of untrusted inputs\n * before providing them to this function.\n *\n * To encode a CashAddress with a custom/unknown prefix or type bit, see\n * {@link encodeCashAddressNonStandard}. For other address standards that\n * closely follow the CashAddress specification (but have alternative version\n * byte requirements), use {@link encodeCashAddressFormat}.\n *\n * @param prefix - the network for which to encode the address\n * (a {@link CashAddressNetworkPrefix})\n * @param type - the address type (a {@link CashAddressType})\n * @param payload - the payload to encode – for P2PKH, the public key hash; for\n * P2SH, the redeem bytecode hash\n */\nconst encodeCashAddress = (prefix, type, payload) => encodeCashAddressNonStandard(prefix, cashAddressTypeToTypeBits[type], payload);\nvar CashAddressDecodingError;\n(function (CashAddressDecodingError) {\n CashAddressDecodingError[\"improperPadding\"] = \"Error decoding CashAddress: the payload is improperly padded.\";\n CashAddressDecodingError[\"invalidCharacters\"] = \"Error decoding CashAddress: the payload contains non-bech32 characters.\";\n CashAddressDecodingError[\"invalidChecksum\"] = \"Error decoding CashAddress: invalid checksum - please review the address for errors.\";\n CashAddressDecodingError[\"invalidFormat\"] = \"Error decoding CashAddress: CashAddresses should be of the form \\\"prefix:payload\\\".\";\n CashAddressDecodingError[\"mismatchedPayloadLength\"] = \"Error decoding CashAddress: mismatched payload length for specified address version.\";\n CashAddressDecodingError[\"reservedByte\"] = \"Error decoding CashAddress: unknown CashAddress version, reserved byte set.\";\n CashAddressDecodingError[\"unknownAddressType\"] = \"Error decoding CashAddress: unknown CashAddress type.\";\n})(CashAddressDecodingError || (CashAddressDecodingError = {}));\n/**\n * Decode and validate a string using the CashAddress format. This is more\n * lenient than {@link decodeCashAddress}, which also validates the contents of\n * the version byte.\n *\n * Note, this method requires `address` to include a network prefix. To\n * decode a string with an unknown prefix, try\n * {@link decodeCashAddressFormatWithoutPrefix}.\n *\n * @param address - the CashAddress-like string to decode\n */\n// eslint-disable-next-line complexity\nconst decodeCashAddressFormat = (address) => {\n const parts = address.toLowerCase().split(':');\n // eslint-disable-next-line @typescript-eslint/no-magic-numbers\n if (parts.length !== 2 || parts[0] === '' || parts[1] === '') {\n return CashAddressDecodingError.invalidFormat;\n }\n const [prefix, payload] = parts;\n if (!(0,_bech32_js__WEBPACK_IMPORTED_MODULE_0__.isBech32CharacterSet)(payload)) {\n return CashAddressDecodingError.invalidCharacters;\n }\n const decodedPayload = (0,_bech32_js__WEBPACK_IMPORTED_MODULE_0__.decodeBech32)(payload);\n const polynomial = [\n ...maskCashAddressPrefix(prefix),\n 0 /* Constants.payloadSeparator */,\n ...decodedPayload,\n ];\n if (cashAddressPolynomialModulo(polynomial) !== 0) {\n return CashAddressDecodingError.invalidChecksum;\n }\n const checksum40BitPlaceholderLength = 8;\n const payloadContents = (0,_bech32_js__WEBPACK_IMPORTED_MODULE_0__.regroupBits)({\n allowPadding: false,\n bin: decodedPayload.slice(0, -checksum40BitPlaceholderLength),\n resultWordLength: 8 /* Constants.base256WordLength */,\n sourceWordLength: 5 /* Constants.base32WordLength */,\n });\n if (typeof payloadContents === 'string') {\n return CashAddressDecodingError.improperPadding;\n }\n const [version, ...contents] = payloadContents;\n const result = Uint8Array.from(contents);\n return { payload: result, prefix, version };\n};\n/**\n * Decode and validate a CashAddress, strictly checking the version byte\n * according to the CashAddress specification. This is important for error\n * detection in CashAddresses.\n *\n * This function is similar to {@link decodeCashAddress} but supports\n * non-standard `type`s.\n *\n * For other address-like standards that closely follow the CashAddress\n * specification (but have alternative version byte requirements), use\n * {@link decodeCashAddressFormat}.\n *\n * Note, this method requires that CashAddresses include a network prefix. To\n * decode an address with an unknown prefix, try\n * {@link decodeCashAddressFormatWithoutPrefix}.\n *\n * @param address - the CashAddress to decode\n */\nconst decodeCashAddressNonStandard = (address) => {\n const decoded = decodeCashAddressFormat(address);\n if (typeof decoded === 'string') {\n return decoded;\n }\n const info = decodeCashAddressVersionByte(decoded.version);\n if (info === CashAddressVersionByteDecodingError.reservedBitSet) {\n return CashAddressDecodingError.reservedByte;\n }\n if (decoded.payload.length !== info.length) {\n return CashAddressDecodingError.mismatchedPayloadLength;\n }\n return {\n payload: decoded.payload,\n prefix: decoded.prefix,\n typeBits: info.typeBits,\n };\n};\n/**\n * Decode and validate a CashAddress, strictly checking the version byte\n * according to the CashAddress specification. This is important for error\n * detection in CashAddresses.\n *\n * To decode CashAddresses with non-standard `type`s,\n * see {@link decodeCashAddressNonStandard}.\n *\n * For other address-like standards that closely follow the CashAddress\n * specification (but have alternative version byte requirements), use\n * {@link decodeCashAddressFormat}.\n *\n * Note, this method requires that CashAddresses include a network prefix. To\n * decode an address with an unknown prefix, try\n * {@link decodeCashAddressFormatWithoutPrefix}.\n *\n * @param address - the CashAddress to decode\n */\nconst decodeCashAddress = (address) => {\n const decoded = decodeCashAddressNonStandard(address);\n if (typeof decoded === 'string') {\n return decoded;\n }\n const type = cashAddressTypeBitsToType[decoded.typeBits];\n if (type === undefined) {\n return `${CashAddressDecodingError.unknownAddressType} Type bit value: ${decoded.typeBits}.`;\n }\n return {\n payload: decoded.payload,\n prefix: decoded.prefix,\n type,\n };\n};\n/**\n * Attempt to decode and validate a CashAddress against a list of possible\n * prefixes. If the correct prefix is known, use {@link decodeCashAddress}.\n *\n * @param address - the CashAddress to decode\n * @param possiblePrefixes - the network prefixes to try\n */\n// decodeCashAddressWithoutPrefix\nconst decodeCashAddressFormatWithoutPrefix = (address, possiblePrefixes = [\n CashAddressNetworkPrefix.mainnet,\n CashAddressNetworkPrefix.testnet,\n CashAddressNetworkPrefix.regtest,\n]) => {\n // eslint-disable-next-line functional/no-loop-statement\n for (const prefix of possiblePrefixes) {\n const attempt = decodeCashAddressFormat(`${prefix}:${address}`);\n if (attempt !== CashAddressDecodingError.invalidChecksum) {\n return attempt;\n }\n }\n return CashAddressDecodingError.invalidChecksum;\n};\n/**\n * Convert a CashAddress polynomial to CashAddress string format.\n *\n * @remarks\n * CashAddress polynomials take the form:\n *\n * `[lowest 5 bits of each prefix character] 0 [payload + checksum]`\n *\n * This method remaps the 5-bit integers in the prefix location to the matching\n * ASCII lowercase characters, replaces the separator with `:`, and then Bech32\n * encodes the remaining payload and checksum.\n *\n * @param polynomial - an array of 5-bit integers representing the terms of a\n * CashAddress polynomial\n */\nconst cashAddressPolynomialToCashAddress = (polynomial) => {\n const separatorPosition = polynomial.indexOf(0);\n const prefix = polynomial\n .slice(0, separatorPosition)\n .map((integer) => String.fromCharCode(96 /* Constants.asciiLowerCaseStart */ + integer))\n .join('');\n const contents = (0,_bech32_js__WEBPACK_IMPORTED_MODULE_0__.encodeBech32)(polynomial.slice(separatorPosition + 1));\n return `${prefix}:${contents}`;\n};\nvar CashAddressCorrectionError;\n(function (CashAddressCorrectionError) {\n CashAddressCorrectionError[\"tooManyErrors\"] = \"This address has more than 2 errors and cannot be corrected.\";\n})(CashAddressCorrectionError || (CashAddressCorrectionError = {}));\n/**\n * Attempt to correct up to 2 errors in a CashAddress. The CashAddress must be\n * properly formed (include a prefix and only contain Bech32 characters).\n *\n * ## **Improper use of this method carries the risk of lost funds.**\n *\n * It is strongly advised that this method only be used under explicit user\n * control. With enough errors, this method is likely to find a plausible\n * correction for any address (but for which no private key exists). This is\n * effectively equivalent to burning the funds.\n *\n * Only 2 substitution errors can be corrected (or a single swap) – deletions\n * and insertions (errors that shift many other characters and change the\n * length of the payload) can never be safely corrected and will produce an\n * error.\n *\n * Errors can be corrected in both the prefix and the payload, but attempting to\n * correct errors in the prefix prior to this method can improve results, e.g.\n * for `bchtest:qq2azmyyv6dtgczexyalqar70q036yund53jvfde0x`, the string\n * `bchtest:qq2azmyyv6dtgczexyalqar70q036yund53jvfdecc` can be corrected, while\n * `typo:qq2azmyyv6dtgczexyalqar70q036yund53jvfdecc` can not.\n *\n * @param address - the CashAddress on which to attempt error correction\n */\n// Derived from: https://github.com/deadalnix/cashaddressed\n// eslint-disable-next-line complexity\nconst attemptCashAddressFormatErrorCorrection = (address) => {\n const parts = address.toLowerCase().split(':');\n // eslint-disable-next-line @typescript-eslint/no-magic-numbers\n if (parts.length !== 2 || parts[0] === '' || parts[1] === '') {\n return CashAddressDecodingError.invalidFormat;\n }\n const [prefix, payload] = parts;\n if (!(0,_bech32_js__WEBPACK_IMPORTED_MODULE_0__.isBech32CharacterSet)(payload)) {\n return CashAddressDecodingError.invalidCharacters;\n }\n const decodedPayload = (0,_bech32_js__WEBPACK_IMPORTED_MODULE_0__.decodeBech32)(payload);\n const polynomial = [...maskCashAddressPrefix(prefix), 0, ...decodedPayload];\n const originalChecksum = cashAddressPolynomialModulo(polynomial);\n if (originalChecksum === 0) {\n return {\n address: cashAddressPolynomialToCashAddress(polynomial),\n corrections: [],\n };\n }\n const syndromes = {};\n // eslint-disable-next-line functional/no-let, functional/no-loop-statement, no-plusplus\n for (let term = 0; term < polynomial.length; term++) {\n // eslint-disable-next-line functional/no-loop-statement\n for (\n // eslint-disable-next-line functional/no-let\n let errorVector = 1; errorVector < 32 /* Constants.finiteFieldOrder */; \n // eslint-disable-next-line no-plusplus\n errorVector++) {\n // eslint-disable-next-line functional/no-expression-statement, no-bitwise, functional/immutable-data\n polynomial[term] ^= errorVector;\n const correct = cashAddressPolynomialModulo(polynomial);\n if (correct === 0) {\n return {\n address: cashAddressPolynomialToCashAddress(polynomial),\n corrections: [term],\n };\n }\n // eslint-disable-next-line no-bitwise\n const s0 = (BigInt(correct) ^ BigInt(originalChecksum)).toString();\n // eslint-disable-next-line functional/no-expression-statement, functional/immutable-data\n syndromes[s0] = term * 32 /* Constants.finiteFieldOrder */ + errorVector;\n // eslint-disable-next-line functional/no-expression-statement, no-bitwise, functional/immutable-data\n polynomial[term] ^= errorVector;\n }\n }\n // eslint-disable-next-line functional/no-loop-statement\n for (const [s0, pe] of Object.entries(syndromes)) {\n // eslint-disable-next-line no-bitwise\n const s1Location = (BigInt(s0) ^ BigInt(originalChecksum)).toString();\n const s1 = syndromes[s1Location];\n if (s1 !== undefined) {\n const correctionIndex1 = Math.trunc(pe / 32 /* Constants.finiteFieldOrder */);\n const correctionIndex2 = Math.trunc(s1 / 32 /* Constants.finiteFieldOrder */);\n // eslint-disable-next-line functional/no-expression-statement, no-bitwise, functional/immutable-data\n polynomial[correctionIndex1] ^= pe % 32 /* Constants.finiteFieldOrder */;\n // eslint-disable-next-line functional/no-expression-statement, no-bitwise, functional/immutable-data\n polynomial[correctionIndex2] ^= s1 % 32 /* Constants.finiteFieldOrder */;\n return {\n address: cashAddressPolynomialToCashAddress(polynomial),\n corrections: [correctionIndex1, correctionIndex2].sort((a, b) => a - b),\n };\n }\n }\n return CashAddressCorrectionError.tooManyErrors;\n};\n//# sourceMappingURL=cash-address.js.map\n\n//# sourceURL=webpack://mainnet-js/../../node_modules/@bitauth/libauth/build/lib/address/cash-address.js?");
1897
+ eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"CashAddressEncodingError\": () => (/* binding */ CashAddressEncodingError),\n/* harmony export */ \"CashAddressNetworkPrefix\": () => (/* binding */ CashAddressNetworkPrefix),\n/* harmony export */ \"CashAddressType\": () => (/* binding */ CashAddressType),\n/* harmony export */ \"cashAddressTypeBitsToType\": () => (/* binding */ cashAddressTypeBitsToType),\n/* harmony export */ \"decodeCashAddress\": () => (/* binding */ decodeCashAddress),\n/* harmony export */ \"decodeCashAddressFormat\": () => (/* binding */ decodeCashAddressFormat),\n/* harmony export */ \"decodeCashAddressFormatWithoutPrefix\": () => (/* binding */ decodeCashAddressFormatWithoutPrefix),\n/* harmony export */ \"decodeCashAddressVersionByte\": () => (/* binding */ decodeCashAddressVersionByte),\n/* harmony export */ \"encodeCashAddress\": () => (/* binding */ encodeCashAddress)\n/* harmony export */ });\n/* unused harmony exports CashAddressVersionByte, CashAddressTypeBits, cashAddressTypeToTypeBits, cashAddressSizeBitsToLength, cashAddressLengthToSizeBits, encodeCashAddressVersionByte, CashAddressVersionByteDecodingError, maskCashAddressPrefix, cashAddressPolynomialModulo, cashAddressChecksumToUint5Array, encodeCashAddressFormat, isValidCashAddressPayloadLength, encodeCashAddressNonStandard, CashAddressDecodingError, decodeCashAddressNonStandard, cashAddressPolynomialToCashAddress, CashAddressCorrectionError, attemptCashAddressFormatErrorCorrection */\n/* harmony import */ var _format_format_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../format/format.js */ \"../../node_modules/@bitauth/libauth/build/lib/format/error.js\");\n/* harmony import */ var _bech32_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./bech32.js */ \"../../node_modules/@bitauth/libauth/build/lib/address/bech32.js\");\n\n\nvar CashAddressNetworkPrefix;\n(function (CashAddressNetworkPrefix) {\n CashAddressNetworkPrefix[\"mainnet\"] = \"bitcoincash\";\n CashAddressNetworkPrefix[\"testnet\"] = \"bchtest\";\n CashAddressNetworkPrefix[\"regtest\"] = \"bchreg\";\n})(CashAddressNetworkPrefix || (CashAddressNetworkPrefix = {}));\n/**\n * The CashAddress specification standardizes the format of the version byte:\n * - Most significant bit: reserved, must be `0`\n * - next 4 bits: Address Type\n * - 3 least significant bits: Payload Size\n *\n * Two Address Type values are currently standardized:\n * - 0 (`0b0000`): P2PKH\n * - 1 (`0b0001`): P2SH\n *\n * And two are proposed by `CHIP-2022-02-CashTokens`:\n * - 2 (`0b0010`): P2PKH + Token Support\n * - 3 (`0b0011`): P2SH + Token Support\n *\n * The CashAddress specification standardizes expected payload size using\n * {@link CashAddressSizeBits}. Currently, two size bit values are in use by\n * standard CashAddress types:\n * - `0` (`0b000`): 20 bytes (in use by `p2pkh` and `p2sh20`)\n * - `3` (`0b011`): 32 bytes (in use by `p2sh32`)\n */\nvar CashAddressVersionByte;\n(function (CashAddressVersionByte) {\n /**\n * Pay to Public Key Hash (P2PKH): `0b00000000`\n *\n * - Most significant bit: `0` (reserved)\n * - Address Type bits: `0000` (P2PKH)\n * - Size bits: `000` (20 bytes)\n */\n CashAddressVersionByte[CashAddressVersionByte[\"p2pkh\"] = 0] = \"p2pkh\";\n /**\n * 20-byte Pay to Script Hash (P2SH20): `0b00001000`\n *\n * - Most significant bit: `0` (reserved)\n * - Address Type bits: `0001` (P2SH)\n * - Size bits: `000` (20 bytes)\n */\n CashAddressVersionByte[CashAddressVersionByte[\"p2sh20\"] = 8] = \"p2sh20\";\n /**\n * 32-byte Pay to Script Hash (P2SH20): `0b00001000`\n *\n * - Most significant bit: `0` (reserved)\n * - Address Type bits: `0001` (P2SH)\n * - Size bits: `011` (32 bytes)\n */\n CashAddressVersionByte[CashAddressVersionByte[\"p2sh32\"] = 11] = \"p2sh32\";\n /**\n * Pay to Public Key Hash (P2PKH) with token support: `0b00010000`\n *\n * - Most significant bit: `0` (reserved)\n * - Address Type bits: `0010` (P2PKH + Tokens)\n * - Size bits: `000` (20 bytes)\n */\n CashAddressVersionByte[CashAddressVersionByte[\"p2pkhWithTokens\"] = 16] = \"p2pkhWithTokens\";\n /**\n * 20-byte Pay to Script Hash (P2SH20) with token support: `0b00011000`\n * - Most significant bit: `0` (reserved)\n * - Address Type bits: `0011` (P2SH + Tokens)\n * - Size bits: `000` (20 bytes)\n */\n CashAddressVersionByte[CashAddressVersionByte[\"p2sh20WithTokens\"] = 24] = \"p2sh20WithTokens\";\n /**\n * 32-byte Pay to Script Hash (P2SH32) with token support: `0b00011011`\n * - Most significant bit: `0` (reserved)\n * - Address Type bits: `0011` (P2SH + Tokens)\n * - Size bits: `011` (32 bytes)\n */\n CashAddressVersionByte[CashAddressVersionByte[\"p2sh32WithTokens\"] = 27] = \"p2sh32WithTokens\";\n})(CashAddressVersionByte || (CashAddressVersionByte = {}));\n/**\n * The address types currently defined in the CashAddress specification. See\n * also: {@link CashAddressVersionByte}.\n */\nvar CashAddressType;\n(function (CashAddressType) {\n /**\n * Pay to Public Key Hash (P2PKH): `0b0000`\n */\n CashAddressType[\"p2pkh\"] = \"p2pkh\";\n /**\n * Pay to Script Hash (P2SH): `0b0001`\n */\n CashAddressType[\"p2sh\"] = \"p2sh\";\n /**\n * Pay to Public Key Hash (P2PKH) with token support: `0b0010`\n */\n CashAddressType[\"p2pkhWithTokens\"] = \"p2pkhWithTokens\";\n /**\n * Pay to Script Hash (P2SH) with token support: `0b0011`\n */\n CashAddressType[\"p2shWithTokens\"] = \"p2shWithTokens\";\n})(CashAddressType || (CashAddressType = {}));\n/**\n * The address type bits currently defined in the CashAddress specification.\n * These map to: {@link CashAddressType}.\n */\nvar CashAddressTypeBits;\n(function (CashAddressTypeBits) {\n /**\n * Pay to Public Key Hash (P2PKH)\n */\n CashAddressTypeBits[CashAddressTypeBits[\"p2pkh\"] = 0] = \"p2pkh\";\n /**\n * Pay to Script Hash (P2SH)\n */\n CashAddressTypeBits[CashAddressTypeBits[\"p2sh\"] = 1] = \"p2sh\";\n /**\n * Pay to Public Key Hash (P2PKH) with token support\n */\n CashAddressTypeBits[CashAddressTypeBits[\"p2pkhWithTokens\"] = 2] = \"p2pkhWithTokens\";\n /**\n * Pay to Script Hash (P2SH) with token support\n */\n CashAddressTypeBits[CashAddressTypeBits[\"p2shWithTokens\"] = 3] = \"p2shWithTokens\";\n})(CashAddressTypeBits || (CashAddressTypeBits = {}));\nconst cashAddressTypeToTypeBits = {\n [CashAddressType.p2pkh]: CashAddressTypeBits.p2pkh,\n [CashAddressType.p2sh]: CashAddressTypeBits.p2sh,\n [CashAddressType.p2pkhWithTokens]: CashAddressTypeBits.p2pkhWithTokens,\n [CashAddressType.p2shWithTokens]: CashAddressTypeBits.p2shWithTokens,\n};\nconst cashAddressTypeBitsToType = {\n [CashAddressTypeBits.p2pkh]: CashAddressType.p2pkh,\n [CashAddressTypeBits.p2sh]: CashAddressType.p2sh,\n [CashAddressTypeBits.p2pkhWithTokens]: CashAddressType.p2pkhWithTokens,\n [CashAddressTypeBits.p2shWithTokens]: CashAddressType.p2shWithTokens,\n};\n/* eslint-disable @typescript-eslint/naming-convention */\nconst cashAddressSizeBitsToLength = {\n 0: 20,\n 1: 24,\n 2: 28,\n 3: 32,\n 4: 40,\n 5: 48,\n 6: 56,\n 7: 64,\n};\nconst cashAddressLengthToSizeBits = {\n 20: 0,\n 24: 1,\n 28: 2,\n 32: 3,\n 40: 4,\n 48: 5,\n 56: 6,\n 64: 7,\n};\n/**\n * Encode a CashAddress version byte for the given address type and payload\n * length. See {@link CashAddressVersionByte} for more information.\n *\n * The `type` parameter must be a number between `0` and `15`, and `bitLength`\n * must be one of the standardized lengths. To use the contents of a variable,\n * cast it to {@link CashAddressType} or {@link CashAddressSize} respectively,\n * e.g.:\n * ```ts\n * const type = 3 as CashAddressType;\n * const size = 160 as CashAddressSize;\n * getCashAddressVersionByte(type, size);\n * ```\n * @param typeBits - the address type bit of the payload being encoded\n * @param length - the length of the payload being encoded\n */\nconst encodeCashAddressVersionByte = (typeBits, length) => \n// eslint-disable-next-line no-bitwise\n(typeBits << 3 /* Constants.cashAddressTypeBitsShift */) |\n cashAddressLengthToSizeBits[length];\nvar CashAddressVersionByteDecodingError;\n(function (CashAddressVersionByteDecodingError) {\n CashAddressVersionByteDecodingError[\"reservedBitSet\"] = \"Reserved bit is set.\";\n})(CashAddressVersionByteDecodingError || (CashAddressVersionByteDecodingError = {}));\n/**\n * Decode a CashAddress version byte. For a list of known versions, see\n * {@link CashAddressVersionByte}.\n *\n * @param version - the version byte to decode\n */\nconst decodeCashAddressVersionByte = (version) => \n// eslint-disable-next-line no-negated-condition, no-bitwise\n(version & 128 /* Constants.cashAddressReservedBitMask */) !== 0\n ? CashAddressVersionByteDecodingError.reservedBitSet\n : {\n length: cashAddressSizeBitsToLength[\n // eslint-disable-next-line no-bitwise\n (version &\n 7 /* Constants.cashAddressSizeBits */)],\n typeBits: \n // eslint-disable-next-line no-bitwise\n (version >>> 3 /* Constants.cashAddressTypeBitsShift */) &\n 15 /* Constants.cashAddressTypeBits */,\n };\n/**\n * Convert a string into an array of 5-bit numbers, representing the characters\n * in a case-insensitive way.\n * @param prefix - the prefix to mask\n */\nconst maskCashAddressPrefix = (prefix) => {\n const result = [];\n // eslint-disable-next-line functional/no-let, functional/no-loop-statement, no-plusplus\n for (let i = 0; i < prefix.length; i++) {\n // eslint-disable-next-line functional/no-expression-statement, no-bitwise, functional/immutable-data\n result.push(prefix.charCodeAt(i) & 31 /* Constants.asciiCaseInsensitiveBits */);\n }\n return result;\n};\n// prettier-ignore\nconst bech32GeneratorMostSignificantByte = [0x98, 0x79, 0xf3, 0xae, 0x1e]; // eslint-disable-line @typescript-eslint/no-magic-numbers\n// prettier-ignore\nconst bech32GeneratorRemainingBytes = [0xf2bc8e61, 0xb76d99e2, 0x3e5fb3c4, 0x2eabe2a8, 0x4f43e470]; // eslint-disable-line @typescript-eslint/no-magic-numbers\n/**\n * Perform the CashAddress polynomial modulo operation, which is based on the\n * Bech32 polynomial modulo operation, but the returned checksum is 40 bits,\n * rather than 30.\n *\n * A.K.A. `PolyMod`\n *\n * @remarks\n * Notes from C++ implementation:\n * This function will compute what 8 5-bit values to XOR into the last 8 input\n * values, in order to make the checksum 0. These 8 values are packed together\n * in a single 40-bit integer. The higher bits correspond to earlier values.\n *\n * The input is interpreted as a list of coefficients of a polynomial over F\n * = GF(32), with an implicit 1 in front. If the input is [v0,v1,v2,v3,v4],\n * that polynomial is v(x) = 1*x^5 + v0*x^4 + v1*x^3 + v2*x^2 + v3*x + v4.\n * The implicit 1 guarantees that [v0,v1,v2,...] has a distinct checksum\n * from [0,v0,v1,v2,...].\n *\n * The output is a 40-bit integer whose 5-bit groups are the coefficients of\n * the remainder of v(x) mod g(x), where g(x) is the cashaddr generator, x^8\n * + [19]*x^7 + [3]*x^6 + [25]*x^5 + [11]*x^4 + [25]*x^3 + [3]*x^2 + [19]*x\n * + [1]. g(x) is chosen in such a way that the resulting code is a BCH\n * code, guaranteeing detection of up to 4 errors within a window of 1025\n * characters. Among the various possible BCH codes, one was selected to in\n * fact guarantee detection of up to 5 errors within a window of 160\n * characters and 6 errors within a window of 126 characters. In addition,\n * the code guarantee the detection of a burst of up to 8 errors.\n *\n * Note that the coefficients are elements of GF(32), here represented as\n * decimal numbers between []. In this finite field, addition is just XOR of\n * the corresponding numbers. For example, [27] + [13] = [27 ^ 13] = [22].\n * Multiplication is more complicated, and requires treating the bits of\n * values themselves as coefficients of a polynomial over a smaller field,\n * GF(2), and multiplying those polynomials mod a^5 + a^3 + 1. For example,\n * [5] * [26] = (a^2 + 1) * (a^4 + a^3 + a) = (a^4 + a^3 + a) * a^2 + (a^4 +\n * a^3 + a) = a^6 + a^5 + a^4 + a = a^3 + 1 (mod a^5 + a^3 + 1) = [9].\n *\n * During the course of the loop below, `c` contains the bit-packed\n * coefficients of the polynomial constructed from just the values of v that\n * were processed so far, mod g(x). In the above example, `c` initially\n * corresponds to 1 mod (x), and after processing 2 inputs of v, it\n * corresponds to x^2 + v0*x + v1 mod g(x). As 1 mod g(x) = 1, that is the\n * starting value for `c`.\n *\n * @param v - Array of 5-bit integers over which the checksum is to be computed\n */\n// Derived from the `bitcore-lib-cash` implementation (does not require BigInt): https://github.com/bitpay/bitcore\nconst cashAddressPolynomialModulo = (v) => {\n /* eslint-disable functional/no-let, functional/no-loop-statement, functional/no-expression-statement, no-bitwise, @typescript-eslint/no-magic-numbers */\n let mostSignificantByte = 0;\n let lowerBytes = 1;\n let c = 0;\n // eslint-disable-next-line @typescript-eslint/prefer-for-of, no-plusplus\n for (let j = 0; j < v.length; j++) {\n c = mostSignificantByte >>> 3;\n mostSignificantByte &= 0x07;\n mostSignificantByte <<= 5;\n mostSignificantByte |= lowerBytes >>> 27;\n lowerBytes &= 0x07ffffff;\n lowerBytes <<= 5;\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n lowerBytes ^= v[j];\n // eslint-disable-next-line no-plusplus\n for (let i = 0; i < bech32GeneratorMostSignificantByte.length; ++i) {\n // eslint-disable-next-line functional/no-conditional-statement\n if (c & (1 << i)) {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n mostSignificantByte ^= bech32GeneratorMostSignificantByte[i];\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n lowerBytes ^= bech32GeneratorRemainingBytes[i];\n }\n }\n }\n lowerBytes ^= 1;\n // eslint-disable-next-line functional/no-conditional-statement\n if (lowerBytes < 0) {\n lowerBytes ^= 1 << 31;\n lowerBytes += (1 << 30) * 2;\n }\n return mostSignificantByte * (1 << 30) * 4 + lowerBytes;\n /* eslint-enable functional/no-let, functional/no-loop-statement, functional/no-expression-statement, no-bitwise, @typescript-eslint/no-magic-numbers */\n};\n/**\n * Convert the checksum returned by {@link cashAddressPolynomialModulo} to an\n * array of 5-bit positive integers that can be Base32 encoded.\n * @param checksum - a 40 bit checksum returned by\n * {@link cashAddressPolynomialModulo}\n */\nconst cashAddressChecksumToUint5Array = (checksum) => {\n const result = [];\n // eslint-disable-next-line functional/no-let, functional/no-loop-statement, no-plusplus\n for (let i = 0; i < 8 /* Constants.base256WordLength */; ++i) {\n // eslint-disable-next-line functional/no-expression-statement, no-bitwise, @typescript-eslint/no-magic-numbers, functional/immutable-data\n result.push(checksum & 31);\n // eslint-disable-next-line functional/no-expression-statement, @typescript-eslint/no-magic-numbers, no-param-reassign\n checksum /= 32;\n }\n // eslint-disable-next-line functional/immutable-data\n return result.reverse();\n};\n/**\n * Encode a payload as a CashAddress-like string using the CashAddress format.\n *\n * To encode a standard CashAddress, use {@link encodeCashAddress}.\n *\n * @param prefix - a valid prefix indicating the network for which to encode the\n * address – must be only lowercase letters (for standard CashAddress prefixes,\n * see {@link CashAddressNetworkPrefix})\n * @param version - a single byte indicating the version of this address (for\n * standard CashAddress versions, see {@link CashAddressVersionByte})\n * @param payload - the payload to encode\n */\nconst encodeCashAddressFormat = (prefix, version, payload) => {\n const checksum40BitPlaceholder = [0, 0, 0, 0, 0, 0, 0, 0];\n const payloadContents = (0,_bech32_js__WEBPACK_IMPORTED_MODULE_0__.regroupBits)({\n bin: Uint8Array.from([version, ...payload]),\n resultWordLength: 5 /* Constants.base32WordLength */,\n sourceWordLength: 8 /* Constants.base256WordLength */,\n });\n const checksumContents = [\n ...maskCashAddressPrefix(prefix),\n 0 /* Constants.payloadSeparator */,\n ...payloadContents,\n ...checksum40BitPlaceholder,\n ];\n const checksum = cashAddressPolynomialModulo(checksumContents);\n const encoded = [\n ...payloadContents,\n ...cashAddressChecksumToUint5Array(checksum),\n ];\n return `${prefix}:${(0,_bech32_js__WEBPACK_IMPORTED_MODULE_0__.encodeBech32)(encoded)}`;\n};\nvar CashAddressEncodingError;\n(function (CashAddressEncodingError) {\n CashAddressEncodingError[\"unsupportedPayloadLength\"] = \"Error encoding CashAddress: a payload of this length can not be encoded as a valid CashAddress.\";\n CashAddressEncodingError[\"noTypeBitsValueStandardizedForP2pk\"] = \"Error encoding CashAddress: no CashAddress type bit has been standardized for P2PK locking bytecode.\";\n CashAddressEncodingError[\"unknownLockingBytecodeType\"] = \"Error encoding CashAddress: unknown locking bytecode type.\";\n})(CashAddressEncodingError || (CashAddressEncodingError = {}));\nconst isValidCashAddressPayloadLength = (length) => cashAddressLengthToSizeBits[length] !== undefined;\n/**\n * Encode a payload as a CashAddress. This function is similar to\n * {@link encodeCashAddress} but supports non-standard `prefix`es and `type`s.\n *\n * **Note: this function cannot prevent all implementation errors via types.**\n * The function will throw if `payload` is not a valid\n * {@link CashAddressSupportedLength}. Confirm the length of untrusted inputs\n * before providing them to this function.\n *\n * For other address standards that closely follow the CashAddress\n * specification (but have alternative version byte requirements), use\n * {@link encodeCashAddressFormat}.\n *\n * @param prefix - a valid prefix indicating the network for which to encode the\n * address (usually a {@link CashAddressNetworkPrefix}) – must be only lowercase\n * letters\n * @param typeBits - the type bit to encode in the version byte – must be a\n * number between `0` and `15`\n * @param payload - the payload to encode (for P2PKH, the public key hash; for\n * P2SH, the redeem bytecode hash)\n */\nconst encodeCashAddressNonStandard = (prefix, typeBits, payload) => {\n const { length } = payload;\n if (!isValidCashAddressPayloadLength(length)) {\n // eslint-disable-next-line functional/no-throw-statement\n throw new Error((0,_format_format_js__WEBPACK_IMPORTED_MODULE_1__.formatError)(CashAddressEncodingError.unsupportedPayloadLength, `Payload length: ${length}.`));\n }\n return encodeCashAddressFormat(prefix, encodeCashAddressVersionByte(typeBits, length), payload);\n};\n/**\n * Encode a payload as a CashAddress.\n *\n * **Note: this function cannot prevent all implementation errors via types.**\n * The function will throw if `payload` is not a valid\n * {@link CashAddressSupportedLength}. Confirm the length of untrusted inputs\n * before providing them to this function.\n *\n * To encode a CashAddress with a custom/unknown prefix or type bit, see\n * {@link encodeCashAddressNonStandard}. For other address standards that\n * closely follow the CashAddress specification (but have alternative version\n * byte requirements), use {@link encodeCashAddressFormat}.\n *\n * @param prefix - the network for which to encode the address\n * (a {@link CashAddressNetworkPrefix})\n * @param type - the address type (a {@link CashAddressType})\n * @param payload - the payload to encode – for P2PKH, the public key hash; for\n * P2SH, the redeem bytecode hash\n */\nconst encodeCashAddress = (prefix, type, payload) => encodeCashAddressNonStandard(prefix, cashAddressTypeToTypeBits[type], payload);\nvar CashAddressDecodingError;\n(function (CashAddressDecodingError) {\n CashAddressDecodingError[\"improperPadding\"] = \"Error decoding CashAddress: the payload is improperly padded.\";\n CashAddressDecodingError[\"invalidCharacters\"] = \"Error decoding CashAddress: the payload contains non-bech32 characters.\";\n CashAddressDecodingError[\"invalidChecksum\"] = \"Error decoding CashAddress: invalid checksum - please review the address for errors.\";\n CashAddressDecodingError[\"invalidFormat\"] = \"Error decoding CashAddress: CashAddresses should be of the form \\\"prefix:payload\\\".\";\n CashAddressDecodingError[\"mismatchedPayloadLength\"] = \"Error decoding CashAddress: mismatched payload length for specified address version.\";\n CashAddressDecodingError[\"reservedByte\"] = \"Error decoding CashAddress: unknown CashAddress version, reserved byte set.\";\n CashAddressDecodingError[\"unknownAddressType\"] = \"Error decoding CashAddress: unknown CashAddress type.\";\n})(CashAddressDecodingError || (CashAddressDecodingError = {}));\n/**\n * Decode and validate a string using the CashAddress format. This is more\n * lenient than {@link decodeCashAddress}, which also validates the contents of\n * the version byte.\n *\n * Note, this method requires `address` to include a network prefix. To\n * decode a string with an unknown prefix, try\n * {@link decodeCashAddressFormatWithoutPrefix}.\n *\n * @param address - the CashAddress-like string to decode\n */\n// eslint-disable-next-line complexity\nconst decodeCashAddressFormat = (address) => {\n const parts = address.toLowerCase().split(':');\n // eslint-disable-next-line @typescript-eslint/no-magic-numbers\n if (parts.length !== 2 || parts[0] === '' || parts[1] === '') {\n return CashAddressDecodingError.invalidFormat;\n }\n const [prefix, payload] = parts;\n if (!(0,_bech32_js__WEBPACK_IMPORTED_MODULE_0__.isBech32CharacterSet)(payload)) {\n return CashAddressDecodingError.invalidCharacters;\n }\n const decodedPayload = (0,_bech32_js__WEBPACK_IMPORTED_MODULE_0__.decodeBech32)(payload);\n const polynomial = [\n ...maskCashAddressPrefix(prefix),\n 0 /* Constants.payloadSeparator */,\n ...decodedPayload,\n ];\n if (cashAddressPolynomialModulo(polynomial) !== 0) {\n return CashAddressDecodingError.invalidChecksum;\n }\n const checksum40BitPlaceholderLength = 8;\n const payloadContents = (0,_bech32_js__WEBPACK_IMPORTED_MODULE_0__.regroupBits)({\n allowPadding: false,\n bin: decodedPayload.slice(0, -checksum40BitPlaceholderLength),\n resultWordLength: 8 /* Constants.base256WordLength */,\n sourceWordLength: 5 /* Constants.base32WordLength */,\n });\n if (typeof payloadContents === 'string') {\n return CashAddressDecodingError.improperPadding;\n }\n const [version, ...contents] = payloadContents;\n const result = Uint8Array.from(contents);\n return { payload: result, prefix, version };\n};\n/**\n * Decode and validate a CashAddress, strictly checking the version byte\n * according to the CashAddress specification. This is important for error\n * detection in CashAddresses.\n *\n * This function is similar to {@link decodeCashAddress} but supports\n * non-standard `type`s.\n *\n * For other address-like standards that closely follow the CashAddress\n * specification (but have alternative version byte requirements), use\n * {@link decodeCashAddressFormat}.\n *\n * Note, this method requires that CashAddresses include a network prefix. To\n * decode an address with an unknown prefix, try\n * {@link decodeCashAddressFormatWithoutPrefix}.\n *\n * @param address - the CashAddress to decode\n */\nconst decodeCashAddressNonStandard = (address) => {\n const decoded = decodeCashAddressFormat(address);\n if (typeof decoded === 'string') {\n return decoded;\n }\n const info = decodeCashAddressVersionByte(decoded.version);\n if (info === CashAddressVersionByteDecodingError.reservedBitSet) {\n return CashAddressDecodingError.reservedByte;\n }\n if (decoded.payload.length !== info.length) {\n return CashAddressDecodingError.mismatchedPayloadLength;\n }\n return {\n payload: decoded.payload,\n prefix: decoded.prefix,\n typeBits: info.typeBits,\n };\n};\n/**\n * Decode and validate a CashAddress, strictly checking the version byte\n * according to the CashAddress specification. This is important for error\n * detection in CashAddresses.\n *\n * To decode CashAddresses with non-standard `type`s,\n * see {@link decodeCashAddressNonStandard}.\n *\n * For other address-like standards that closely follow the CashAddress\n * specification (but have alternative version byte requirements), use\n * {@link decodeCashAddressFormat}.\n *\n * Note, this method requires that CashAddresses include a network prefix. To\n * decode an address with an unknown prefix, try\n * {@link decodeCashAddressFormatWithoutPrefix}.\n *\n * @param address - the CashAddress to decode\n */\nconst decodeCashAddress = (address) => {\n const decoded = decodeCashAddressNonStandard(address);\n if (typeof decoded === 'string') {\n return decoded;\n }\n const type = cashAddressTypeBitsToType[decoded.typeBits];\n if (type === undefined) {\n return `${CashAddressDecodingError.unknownAddressType} Type bit value: ${decoded.typeBits}.`;\n }\n return {\n payload: decoded.payload,\n prefix: decoded.prefix,\n type,\n };\n};\n/**\n * Attempt to decode and validate a CashAddress against a list of possible\n * prefixes. If the correct prefix is known, use {@link decodeCashAddress}.\n *\n * @param address - the CashAddress to decode\n * @param possiblePrefixes - the network prefixes to try\n */\n// decodeCashAddressWithoutPrefix\nconst decodeCashAddressFormatWithoutPrefix = (address, possiblePrefixes = [\n CashAddressNetworkPrefix.mainnet,\n CashAddressNetworkPrefix.testnet,\n CashAddressNetworkPrefix.regtest,\n]) => {\n // eslint-disable-next-line functional/no-loop-statement\n for (const prefix of possiblePrefixes) {\n const attempt = decodeCashAddressFormat(`${prefix}:${address}`);\n if (attempt !== CashAddressDecodingError.invalidChecksum) {\n return attempt;\n }\n }\n return CashAddressDecodingError.invalidChecksum;\n};\n/**\n * Convert a CashAddress polynomial to CashAddress string format.\n *\n * @remarks\n * CashAddress polynomials take the form:\n *\n * `[lowest 5 bits of each prefix character] 0 [payload + checksum]`\n *\n * This method remaps the 5-bit integers in the prefix location to the matching\n * ASCII lowercase characters, replaces the separator with `:`, and then Bech32\n * encodes the remaining payload and checksum.\n *\n * @param polynomial - an array of 5-bit integers representing the terms of a\n * CashAddress polynomial\n */\nconst cashAddressPolynomialToCashAddress = (polynomial) => {\n const separatorPosition = polynomial.indexOf(0);\n const prefix = polynomial\n .slice(0, separatorPosition)\n .map((integer) => String.fromCharCode(96 /* Constants.asciiLowerCaseStart */ + integer))\n .join('');\n const contents = (0,_bech32_js__WEBPACK_IMPORTED_MODULE_0__.encodeBech32)(polynomial.slice(separatorPosition + 1));\n return `${prefix}:${contents}`;\n};\nvar CashAddressCorrectionError;\n(function (CashAddressCorrectionError) {\n CashAddressCorrectionError[\"tooManyErrors\"] = \"This address has more than 2 errors and cannot be corrected.\";\n})(CashAddressCorrectionError || (CashAddressCorrectionError = {}));\n/**\n * Attempt to correct up to 2 errors in a CashAddress. The CashAddress must be\n * properly formed (include a prefix and only contain Bech32 characters).\n *\n * ## **Improper use of this method carries the risk of lost funds.**\n *\n * It is strongly advised that this method only be used under explicit user\n * control. With enough errors, this method is likely to find a plausible\n * correction for any address (but for which no private key exists). This is\n * effectively equivalent to burning the funds.\n *\n * Only 2 substitution errors can be corrected (or a single swap) – deletions\n * and insertions (errors that shift many other characters and change the\n * length of the payload) can never be safely corrected and will produce an\n * error.\n *\n * Errors can be corrected in both the prefix and the payload, but attempting to\n * correct errors in the prefix prior to this method can improve results, e.g.\n * for `bchtest:qq2azmyyv6dtgczexyalqar70q036yund53jvfde0x`, the string\n * `bchtest:qq2azmyyv6dtgczexyalqar70q036yund53jvfdecc` can be corrected, while\n * `typo:qq2azmyyv6dtgczexyalqar70q036yund53jvfdecc` can not.\n *\n * @param address - the CashAddress on which to attempt error correction\n */\n// Derived from: https://github.com/deadalnix/cashaddressed\n// eslint-disable-next-line complexity\nconst attemptCashAddressFormatErrorCorrection = (address) => {\n const parts = address.toLowerCase().split(':');\n // eslint-disable-next-line @typescript-eslint/no-magic-numbers\n if (parts.length !== 2 || parts[0] === '' || parts[1] === '') {\n return CashAddressDecodingError.invalidFormat;\n }\n const [prefix, payload] = parts;\n if (!(0,_bech32_js__WEBPACK_IMPORTED_MODULE_0__.isBech32CharacterSet)(payload)) {\n return CashAddressDecodingError.invalidCharacters;\n }\n const decodedPayload = (0,_bech32_js__WEBPACK_IMPORTED_MODULE_0__.decodeBech32)(payload);\n const polynomial = [...maskCashAddressPrefix(prefix), 0, ...decodedPayload];\n const originalChecksum = cashAddressPolynomialModulo(polynomial);\n if (originalChecksum === 0) {\n return {\n address: cashAddressPolynomialToCashAddress(polynomial),\n corrections: [],\n };\n }\n const syndromes = {};\n // eslint-disable-next-line functional/no-let, functional/no-loop-statement, no-plusplus\n for (let term = 0; term < polynomial.length; term++) {\n // eslint-disable-next-line functional/no-loop-statement\n for (\n // eslint-disable-next-line functional/no-let\n let errorVector = 1; errorVector < 32 /* Constants.finiteFieldOrder */; \n // eslint-disable-next-line no-plusplus\n errorVector++) {\n // eslint-disable-next-line functional/no-expression-statement, no-bitwise, functional/immutable-data\n polynomial[term] ^= errorVector;\n const correct = cashAddressPolynomialModulo(polynomial);\n if (correct === 0) {\n return {\n address: cashAddressPolynomialToCashAddress(polynomial),\n corrections: [term],\n };\n }\n // eslint-disable-next-line no-bitwise\n const s0 = (BigInt(correct) ^ BigInt(originalChecksum)).toString();\n // eslint-disable-next-line functional/no-expression-statement, functional/immutable-data\n syndromes[s0] = term * 32 /* Constants.finiteFieldOrder */ + errorVector;\n // eslint-disable-next-line functional/no-expression-statement, no-bitwise, functional/immutable-data\n polynomial[term] ^= errorVector;\n }\n }\n // eslint-disable-next-line functional/no-loop-statement\n for (const [s0, pe] of Object.entries(syndromes)) {\n // eslint-disable-next-line no-bitwise\n const s1Location = (BigInt(s0) ^ BigInt(originalChecksum)).toString();\n const s1 = syndromes[s1Location];\n if (s1 !== undefined) {\n const correctionIndex1 = Math.trunc(pe / 32 /* Constants.finiteFieldOrder */);\n const correctionIndex2 = Math.trunc(s1 / 32 /* Constants.finiteFieldOrder */);\n // eslint-disable-next-line functional/no-expression-statement, no-bitwise, functional/immutable-data\n polynomial[correctionIndex1] ^= pe % 32 /* Constants.finiteFieldOrder */;\n // eslint-disable-next-line functional/no-expression-statement, no-bitwise, functional/immutable-data\n polynomial[correctionIndex2] ^= s1 % 32 /* Constants.finiteFieldOrder */;\n return {\n address: cashAddressPolynomialToCashAddress(polynomial),\n corrections: [correctionIndex1, correctionIndex2].sort((a, b) => a - b),\n };\n }\n }\n return CashAddressCorrectionError.tooManyErrors;\n};\n//# sourceMappingURL=cash-address.js.map\n\n//# sourceURL=webpack://mainnet-js/../../node_modules/@bitauth/libauth/build/lib/address/cash-address.js?");
1898
1898
 
1899
1899
  /***/ }),
1900
1900