mainnet-js 2.7.24 → 2.7.27
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.
- package/dist/index.html +1 -1
- package/dist/{mainnet-2.7.24.js → mainnet-2.7.27.js} +13 -13
- package/dist/module/config.d.ts +1 -0
- package/dist/module/config.d.ts.map +1 -1
- package/dist/module/config.js +2 -0
- package/dist/module/config.js.map +1 -1
- package/dist/module/network/ElectrumNetworkProvider.d.ts +0 -6
- package/dist/module/network/ElectrumNetworkProvider.d.ts.map +1 -1
- package/dist/module/network/ElectrumNetworkProvider.js +3 -43
- package/dist/module/network/ElectrumNetworkProvider.js.map +1 -1
- package/dist/module/rate/ExchangeRate.d.ts.map +1 -1
- package/dist/module/rate/ExchangeRate.js +4 -0
- package/dist/module/rate/ExchangeRate.js.map +1 -1
- package/dist/module/wallet/Base.d.ts +7 -7
- package/dist/module/wallet/Base.d.ts.map +1 -1
- package/dist/module/wallet/Base.js +5 -0
- package/dist/module/wallet/Base.js.map +1 -1
- package/dist/module/wallet/Wif.d.ts +22 -13
- package/dist/module/wallet/Wif.d.ts.map +1 -1
- package/dist/module/wallet/Wif.js +56 -5
- package/dist/module/wallet/Wif.js.map +1 -1
- package/dist/module/wallet/enum.d.ts +1 -0
- package/dist/module/wallet/enum.d.ts.map +1 -1
- package/dist/module/wallet/enum.js +1 -0
- package/dist/module/wallet/enum.js.map +1 -1
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/package.json +1 -3
- package/src/config.ts +5 -0
- package/src/network/ElectrumNetworkProvider.ts +3 -52
- package/src/rate/ExchangeRate.test.ts +20 -1
- package/src/rate/ExchangeRate.ts +5 -0
- package/src/util/derivePublicKeyHash.test.ts +1 -0
- package/src/wallet/Base.ts +12 -7
- package/src/wallet/Wif.ts +81 -18
- package/src/wallet/enum.ts +1 -0
|
@@ -94,7 +94,7 @@ eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harm
|
|
|
94
94
|
\***********************/
|
|
95
95
|
/***/ ((module, __webpack_exports__, __webpack_require__) => {
|
|
96
96
|
|
|
97
|
-
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 */ \"Config\": () => (/* binding */ Config)\n/* harmony export */ });\n/* harmony import */ var _scure_bip39_wordlists_english__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @scure/bip39/wordlists/english */ \"../../node_modules/@scure/bip39/esm/wordlists/english.js\");\n/* harmony import */ var _constant_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./constant.js */ \"./src/constant.ts\");\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\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__]);\n_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__ = (__webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__)[0];\n\n\n\nclass Config {\n // enforces all token-related methods to specify tokenaddr as recepient and change cashaddr\n static { this.EnforceCashTokenReceiptAddresses = false; }\n static { this.DefaultParentDerivationPath = \"m/44'/0'/0'\"; }\n static { this.DefaultIpfsGateway = \"https://dweb.link/ipfs/\"; }\n // default currency for balance and rate conversions\n static { this.DefaultCurrency = \"usd\"; }\n // caches the raw transactions in browser's local storage instead of memory\n static { this.UseLocalStorageCache = false; }\n // caches the raw transactions in browser's indexedDB instead of memory\n static { this.UseIndexedDBCache = false; }\n // caches the raw transactions in browser's memory\n static { this.UseMemoryCache = false; }\n static { this.DefaultWordlist = _scure_bip39_wordlists_english__WEBPACK_IMPORTED_MODULE_0__.wordlist; }\n static setIpfsGateway(ipfsGateway) {\n this.DefaultIpfsGateway = ipfsGateway;\n }\n static setWordlist(wordlist) {\n let checksum = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.binToHex)(_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.sha256.hash((0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.utf8ToBin)(wordlist.join(\" \"))));\n if (!Object.values(_constant_js__WEBPACK_IMPORTED_MODULE_4__.WORDLIST_CHECKSUMS).includes(checksum))\n throw Error(\"Error matching provided wordlist to a known list, see @scure/bip39/wordlists\");\n Config.DefaultWordlist = wordlist;\n }\n static getWordlist() {\n return [...Config.DefaultWordlist];\n }\n}\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/config.ts?");
|
|
97
|
+
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 */ \"Config\": () => (/* binding */ Config)\n/* harmony export */ });\n/* harmony import */ var _scure_bip39_wordlists_english__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @scure/bip39/wordlists/english */ \"../../node_modules/@scure/bip39/esm/wordlists/english.js\");\n/* harmony import */ var _constant_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./constant.js */ \"./src/constant.ts\");\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\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__]);\n_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__ = (__webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__)[0];\n\n\n\nclass Config {\n // enforces all token-related methods to specify tokenaddr as recepient and change cashaddr\n static { this.EnforceCashTokenReceiptAddresses = false; }\n static { this.DefaultParentDerivationPath = \"m/44'/0'/0'\"; }\n static { this.DefaultIpfsGateway = \"https://dweb.link/ipfs/\"; }\n // default currency for balance and rate conversions\n static { this.DefaultCurrency = \"usd\"; }\n // caches the raw transactions in browser's local storage instead of memory\n static { this.UseLocalStorageCache = false; }\n // caches the raw transactions in browser's indexedDB instead of memory\n static { this.UseIndexedDBCache = false; }\n // caches the raw transactions in browser's memory\n static { this.UseMemoryCache = false; }\n static { this.DefaultWordlist = _scure_bip39_wordlists_english__WEBPACK_IMPORTED_MODULE_0__.wordlist; }\n static setIpfsGateway(ipfsGateway) {\n this.DefaultIpfsGateway = ipfsGateway;\n }\n static setWordlist(wordlist) {\n let checksum = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.binToHex)(_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.sha256.hash((0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.utf8ToBin)(wordlist.join(\" \"))));\n if (!Object.values(_constant_js__WEBPACK_IMPORTED_MODULE_4__.WORDLIST_CHECKSUMS).includes(checksum))\n throw Error(\"Error matching provided wordlist to a known list, see @scure/bip39/wordlists\");\n Config.DefaultWordlist = wordlist;\n }\n static getWordlist() {\n return [...Config.DefaultWordlist];\n }\n // custom exchange rate function\n static { this.GetExchangeRateFn = undefined; }\n}\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/config.ts?");
|
|
98
98
|
|
|
99
99
|
/***/ }),
|
|
100
100
|
|
|
@@ -234,7 +234,7 @@ eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__
|
|
|
234
234
|
\************************************************/
|
|
235
235
|
/***/ ((module, __webpack_exports__, __webpack_require__) => {
|
|
236
236
|
|
|
237
|
-
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 */ \"default\": () => (/* binding */ ElectrumNetworkProvider)\n/* harmony export */ });\n/* harmony import */ var _electrum_cash_network__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @electrum-cash/network */ \"../../node_modules/@electrum-cash/network/dist/index.mjs\");\n/* harmony import */ var _interface_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../interface.js */ \"./src/interface.ts\");\n/* harmony import */ var _util_delay_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../util/delay.js */ \"./src/util/delay.ts\");\n/* harmony import */ var _util_transaction_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../util/transaction.js */ \"./src/util/transaction.ts\");\n/* harmony import */ var _config_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../config.js */ \"./src/config.ts\");\n/* harmony import */ var _util_header_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../util/header.js */ \"./src/util/header.ts\");\n/* harmony import */ var _cache_IndexedDbCache_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../cache/IndexedDbCache.js */ \"./src/cache/IndexedDbCache.ts\");\n/* harmony import */ var _cache_WebStorageCache_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../cache/WebStorageCache.js */ \"./src/cache/WebStorageCache.ts\");\n/* harmony import */ var _cache_MemoryCache_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../cache/MemoryCache.js */ \"./src/cache/MemoryCache.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_config_js__WEBPACK_IMPORTED_MODULE_1__, _util_header_js__WEBPACK_IMPORTED_MODULE_6__, _util_transaction_js__WEBPACK_IMPORTED_MODULE_7__]);\n([_config_js__WEBPACK_IMPORTED_MODULE_1__, _util_header_js__WEBPACK_IMPORTED_MODULE_6__, _util_transaction_js__WEBPACK_IMPORTED_MODULE_7__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\n\n\n\n\n\n\n\nclass ElectrumNetworkProvider {\n get cache() {\n if (!_config_js__WEBPACK_IMPORTED_MODULE_1__.Config.UseMemoryCache &&\n !_config_js__WEBPACK_IMPORTED_MODULE_1__.Config.UseLocalStorageCache &&\n !_config_js__WEBPACK_IMPORTED_MODULE_1__.Config.UseIndexedDBCache) {\n this._cache = undefined;\n return this._cache;\n }\n if (_config_js__WEBPACK_IMPORTED_MODULE_1__.Config.UseMemoryCache && !(this._cache instanceof _cache_MemoryCache_js__WEBPACK_IMPORTED_MODULE_2__.MemoryCache)) {\n this._cache = new _cache_IndexedDbCache_js__WEBPACK_IMPORTED_MODULE_3__.IndexedDbCache();\n return this._cache;\n }\n if (_config_js__WEBPACK_IMPORTED_MODULE_1__.Config.UseLocalStorageCache &&\n !(this._cache instanceof _cache_WebStorageCache_js__WEBPACK_IMPORTED_MODULE_4__.WebStorageCache)) {\n this._cache = new _cache_WebStorageCache_js__WEBPACK_IMPORTED_MODULE_4__.WebStorageCache();\n return this._cache;\n }\n if (_config_js__WEBPACK_IMPORTED_MODULE_1__.Config.UseIndexedDBCache && !(this._cache instanceof _cache_IndexedDbCache_js__WEBPACK_IMPORTED_MODULE_3__.IndexedDbCache)) {\n this._cache = new _cache_IndexedDbCache_js__WEBPACK_IMPORTED_MODULE_3__.IndexedDbCache();\n return this._cache;\n }\n return this._cache;\n }\n constructor(electrum, network = _interface_js__WEBPACK_IMPORTED_MODULE_5__.Network.MAINNET, manualConnectionManagement) {\n this.network = network;\n this.manualConnectionManagement = manualConnectionManagement;\n this.subscriptions = 0;\n this.subscribedToHeaders = false;\n this.subscriptionMap = {};\n if (electrum) {\n this.electrum = electrum;\n this.connectPromise = this.getConnectPromise();\n this.version = this.electrum.version;\n }\n else {\n throw new Error(`A electrum-cash client is required.`);\n }\n }\n async getConnectPromise(_timeout = 3000) {\n // connects to the electrum cash and waits until the connection is ready to accept requests\n let timeoutHandle;\n await Promise.race([\n new Promise(async (resolve) => {\n this.connectPromise = undefined;\n resolve(await this.connectClient());\n }),\n ]);\n clearTimeout(timeoutHandle);\n }\n async getUtxos(cashaddr) {\n const result = await this.performRequest(\"blockchain.address.listunspent\", cashaddr, \"include_tokens\");\n return result.map((utxo) => ({\n txid: utxo.tx_hash,\n vout: utxo.tx_pos,\n satoshis: utxo.value,\n height: utxo.height,\n token: utxo.token_data\n ? {\n amount: BigInt(utxo.token_data.amount),\n tokenId: utxo.token_data.category,\n capability: utxo.token_data.nft?.capability,\n commitment: utxo.token_data.nft?.commitment,\n }\n : undefined,\n }));\n }\n async getBalance(cashaddr) {\n const result = await this.performRequest(\"blockchain.address.get_balance\", cashaddr);\n return result.confirmed + result.unconfirmed;\n }\n async getHeader(height, verbose = false) {\n const key = `header-${this.network}-${height}-${verbose}`;\n if (this.cache) {\n const cached = await this.cache.getItem(key);\n if (cached) {\n return verbose ? (0,_util_header_js__WEBPACK_IMPORTED_MODULE_6__.decodeHeader)(JSON.parse(cached)) : JSON.parse(cached);\n }\n }\n const result = await this.performRequest(\"blockchain.header.get\", height);\n if (this.cache) {\n await this.cache.setItem(key, JSON.stringify(result));\n }\n return verbose ? (0,_util_header_js__WEBPACK_IMPORTED_MODULE_6__.decodeHeader)(result) : result;\n }\n async getBlockHeight() {\n return (await this.performRequest(\"blockchain.headers.get_tip\"))\n .height;\n }\n async getRawTransaction(txHash, verbose = false, loadInputValues = false) {\n const key = `tx-${this.network}-${txHash}-${verbose}-${loadInputValues}`;\n if (this.cache) {\n const cached = await this.cache.getItem(key);\n if (cached) {\n return verbose ? JSON.parse(cached) : cached;\n }\n }\n try {\n const transaction = (await this.performRequest(\"blockchain.transaction.get\", txHash, verbose));\n if (this.cache) {\n await this.cache.setItem(key, verbose\n ? JSON.stringify(transaction)\n : transaction);\n }\n if (verbose && loadInputValues) {\n // get unique transaction hashes\n const hashes = [...new Set(transaction.vin.map((val) => val.txid))];\n const transactions = await Promise.all(hashes.map((hash) => this.getRawTransactionObject(hash, false)));\n const transactionMap = new Map();\n transactions.forEach((val) => transactionMap.set(val.hash, val));\n transaction.vin.forEach((input) => {\n const output = transactionMap\n .get(input.txid)\n .vout.find((val) => val.n === input.vout);\n input.address = output.scriptPubKey.addresses[0];\n input.value = output.value;\n input.tokenData = output.tokenData;\n });\n }\n return transaction;\n }\n catch (error) {\n if (error.message.indexOf(\"No such mempool or blockchain transaction.\") > -1)\n throw Error(`Could not decode transaction ${txHash}. It might not exist on the current blockchain (${this.network}).`);\n else\n throw error;\n }\n }\n // gets the decoded transaction in human readable form\n async getRawTransactionObject(txHash, loadInputValues = false) {\n return (await this.getRawTransaction(txHash, true, loadInputValues));\n }\n async sendRawTransaction(txHex, awaitPropagation = true) {\n return new Promise(async (resolve, reject) => {\n let txHash = await (0,_util_transaction_js__WEBPACK_IMPORTED_MODULE_7__.getTransactionHash)(txHex);\n if (!awaitPropagation) {\n this.performRequest(\"blockchain.transaction.broadcast\", txHex);\n resolve(txHash);\n }\n else {\n let cancel;\n const waitForTransactionCallback = async (data) => {\n if (data && data[0] === txHash && data[1] !== null) {\n await cancel?.();\n resolve(txHash);\n }\n };\n cancel = await this.subscribeToTransaction(txHash, waitForTransactionCallback);\n this.performRequest(\"blockchain.transaction.broadcast\", txHex).catch(async (error) => {\n await cancel?.();\n reject(error);\n });\n }\n });\n }\n // Get transaction history of a given cashaddr\n async getHistory(cashaddr, fromHeight = 0, toHeight = -1) {\n const result = await this.performRequest(\"blockchain.address.get_history\", cashaddr, fromHeight, toHeight);\n return result;\n }\n // Get the minimum fee a low-priority transaction must pay in order to be accepted to the daemon's memory pool.\n async getRelayFee() {\n const result = (await this.performRequest(\"blockchain.relayfee\"));\n return result;\n }\n async watchAddressStatus(cashaddr, callback) {\n const watchAddressStatusCallback = async (data) => {\n // subscription acknowledgement is the latest known status or null if no status is known\n // status is an array: [ cashaddr, statusHash ]\n if (data instanceof Array) {\n const addr = data[0];\n if (addr !== cashaddr) {\n return;\n }\n const status = data[1];\n callback(status);\n }\n };\n return this.subscribeToAddress(cashaddr, watchAddressStatusCallback);\n }\n async watchAddress(cashaddr, callback) {\n const historyMap = {};\n this.getHistory(cashaddr).then((history) => history.forEach((val) => (historyMap[val.tx_hash] = true)));\n const watchAddressStatusCallback = async () => {\n const newHistory = await this.getHistory(cashaddr);\n // sort history to put unconfirmed transactions in the beginning, then transactions in block height descenting order\n const txHashes = newHistory\n .sort((a, b) => a.height <= 0 || b.height <= 0 ? -1 : b.height - a.height)\n .map((val) => val.tx_hash);\n for (const hash of txHashes) {\n if (!(hash in historyMap)) {\n historyMap[hash] = true;\n callback(hash);\n // exit early to prevent further map lookups\n break;\n }\n }\n };\n return this.watchAddressStatus(cashaddr, watchAddressStatusCallback);\n }\n async watchAddressTransactions(cashaddr, callback) {\n return this.watchAddress(cashaddr, async (txHash) => {\n const tx = await this.getRawTransactionObject(txHash);\n callback(tx);\n });\n }\n async watchAddressTokenTransactions(cashaddr, callback) {\n return this.watchAddress(cashaddr, async (txHash) => {\n const tx = await this.getRawTransactionObject(txHash, true);\n if (tx.vin.some((val) => val.tokenData) ||\n tx.vout.some((val) => val.tokenData)) {\n callback(tx);\n }\n });\n }\n // watch for block headers and block height, if `skipCurrentHeight` is set, the notification about current block will not arrive\n async watchBlocks(callback, skipCurrentHeight = true) {\n let acknowledged = !skipCurrentHeight;\n const waitForBlockCallback = (_header) => {\n if (!acknowledged) {\n acknowledged = true;\n return;\n }\n _header = _header instanceof Array ? _header[0] : _header;\n callback(_header);\n };\n return this.subscribeToHeaders(waitForBlockCallback);\n }\n // Wait for the next block or a block at given blockchain height.\n async waitForBlock(height) {\n return new Promise(async (resolve) => {\n let cancelWatch;\n if (this.electrum.chainHeight && !height) {\n height = this.electrum.chainHeight + 1;\n }\n cancelWatch = await this.watchBlocks(async (header) => {\n if (!height) {\n height = header.height + 1;\n return;\n }\n if (header.height >= height) {\n await cancelWatch?.();\n resolve(header);\n return;\n }\n });\n });\n }\n // subscribe to notifications sent when new block is found, the block header is sent to callback\n async subscribeToHeaders(callback) {\n return this.subscribeRequest(\"blockchain.headers.subscribe\", callback);\n }\n async subscribeToAddress(cashaddr, callback) {\n return this.subscribeRequest(\"blockchain.address.subscribe\", callback, cashaddr);\n }\n async subscribeToTransaction(txHash, callback) {\n return this.subscribeRequest(\"blockchain.transaction.subscribe\", callback, txHash);\n }\n async performRequest(name, ...parameters) {\n await this.ready();\n const requestTimeout = new Promise(function (_resolve, reject) {\n setTimeout(function () {\n reject(\"electrum-cash request timed out, retrying\");\n }, 30000);\n }).catch(function (e) {\n throw e;\n });\n const request = this.electrum.request(name, ...parameters);\n return await Promise.race([request, requestTimeout])\n .then((value) => {\n if (value instanceof Error)\n throw value;\n let result = value;\n return result;\n })\n .catch(async () => {\n // console.warn(\n // \"initial electrum-cash request attempt timed out, retrying...\"\n // );\n return await Promise.race([request, requestTimeout])\n .then((value) => {\n if (value instanceof Error)\n throw value;\n let result = value;\n return result;\n })\n .catch(function (e) {\n throw e;\n });\n });\n }\n async trackSubscription(methodName, ...parameters) {\n const key = `${methodName}-${this.network}-${JSON.stringify(parameters)}`;\n if (this.subscriptionMap[key]) {\n this.subscriptionMap[key]++;\n }\n else {\n this.subscriptionMap[key] = 1;\n }\n await this.electrum.subscribe(methodName, ...parameters);\n }\n async untrackSubscription(methodName, ...parameters) {\n const key = `${methodName}-${this.network}-${JSON.stringify(parameters)}`;\n if (this.subscriptionMap[key]) {\n this.subscriptionMap[key]--;\n if (this.subscriptionMap[key] <= 0) {\n // only really unsubscribe if there are no more subscriptions for this `key`\n delete this.subscriptionMap[key];\n try {\n await this.electrum.unsubscribe(methodName, ...parameters);\n }\n catch { }\n }\n }\n }\n async subscribeRequest(methodName, callback, ...parameters) {\n await this.ready();\n const handler = (data) => {\n if (data.method === methodName) {\n callback(data.params);\n }\n };\n this.electrum.on(\"notification\", handler);\n // safeguard against multiple subscriptions to headers\n if (methodName === \"blockhain.headers.subscribe\") {\n if (!this.subscribedToHeaders) {\n this.subscribedToHeaders = true;\n await this.trackSubscription(methodName, ...parameters);\n }\n }\n else {\n await this.trackSubscription(methodName, ...parameters);\n }\n this.subscriptions++;\n return async () => {\n this.electrum.off(\"notification\", handler);\n this.subscriptions--;\n // there are no blockchain.headers.unsubscribe method, so let's safeguard against it\n if (methodName !== \"blockchain.headers.subscribe\") {\n await this.untrackSubscription(methodName, ...parameters);\n }\n };\n }\n async ready() {\n return this.connect();\n }\n async connect() {\n await this.cache?.init();\n return await this.connectPromise;\n }\n disconnect() {\n if (this.subscriptions > 0) {\n // console.warn(\n // `Trying to disconnect a network provider with ${this.subscriptions} active subscriptions. This is in most cases a bad idea.`\n // );\n }\n return this.disconnectClient();\n }\n async readyClient(timeout) {\n timeout = typeof timeout !== \"undefined\" ? timeout : 3000;\n let connectPromise = async () => {\n while (this.electrum.status !== _electrum_cash_network__WEBPACK_IMPORTED_MODULE_0__.ConnectionStatus.CONNECTED) {\n await (0,_util_delay_js__WEBPACK_IMPORTED_MODULE_8__.delay)(100);\n }\n return true;\n };\n return connectPromise;\n }\n async connectClient() {\n let connectionPromise = async () => {\n try {\n return await this.electrum.connect();\n }\n catch (e) {\n console.warn(`Warning: Failed to connect to client on ${this.network} at ${this.electrum.hostIdentifier}.`, e);\n return;\n }\n };\n return connectionPromise();\n }\n async disconnectClient() {\n return this.electrum.disconnect(true, false);\n }\n}\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/network/ElectrumNetworkProvider.ts?");
|
|
237
|
+
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 */ \"default\": () => (/* binding */ ElectrumNetworkProvider)\n/* harmony export */ });\n/* harmony import */ var _electrum_cash_network__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @electrum-cash/network */ \"../../node_modules/@electrum-cash/network/dist/index.mjs\");\n/* harmony import */ var _interface_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../interface.js */ \"./src/interface.ts\");\n/* harmony import */ var _util_transaction_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../util/transaction.js */ \"./src/util/transaction.ts\");\n/* harmony import */ var _config_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../config.js */ \"./src/config.ts\");\n/* harmony import */ var _util_header_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../util/header.js */ \"./src/util/header.ts\");\n/* harmony import */ var _cache_IndexedDbCache_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../cache/IndexedDbCache.js */ \"./src/cache/IndexedDbCache.ts\");\n/* harmony import */ var _cache_WebStorageCache_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../cache/WebStorageCache.js */ \"./src/cache/WebStorageCache.ts\");\n/* harmony import */ var _cache_MemoryCache_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../cache/MemoryCache.js */ \"./src/cache/MemoryCache.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_config_js__WEBPACK_IMPORTED_MODULE_1__, _util_header_js__WEBPACK_IMPORTED_MODULE_6__, _util_transaction_js__WEBPACK_IMPORTED_MODULE_7__]);\n([_config_js__WEBPACK_IMPORTED_MODULE_1__, _util_header_js__WEBPACK_IMPORTED_MODULE_6__, _util_transaction_js__WEBPACK_IMPORTED_MODULE_7__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\n\n\n\n\n\n\nclass ElectrumNetworkProvider {\n get cache() {\n if (!_config_js__WEBPACK_IMPORTED_MODULE_1__.Config.UseMemoryCache &&\n !_config_js__WEBPACK_IMPORTED_MODULE_1__.Config.UseLocalStorageCache &&\n !_config_js__WEBPACK_IMPORTED_MODULE_1__.Config.UseIndexedDBCache) {\n this._cache = undefined;\n return this._cache;\n }\n if (_config_js__WEBPACK_IMPORTED_MODULE_1__.Config.UseMemoryCache && !(this._cache instanceof _cache_MemoryCache_js__WEBPACK_IMPORTED_MODULE_2__.MemoryCache)) {\n this._cache = new _cache_IndexedDbCache_js__WEBPACK_IMPORTED_MODULE_3__.IndexedDbCache();\n return this._cache;\n }\n if (_config_js__WEBPACK_IMPORTED_MODULE_1__.Config.UseLocalStorageCache &&\n !(this._cache instanceof _cache_WebStorageCache_js__WEBPACK_IMPORTED_MODULE_4__.WebStorageCache)) {\n this._cache = new _cache_WebStorageCache_js__WEBPACK_IMPORTED_MODULE_4__.WebStorageCache();\n return this._cache;\n }\n if (_config_js__WEBPACK_IMPORTED_MODULE_1__.Config.UseIndexedDBCache && !(this._cache instanceof _cache_IndexedDbCache_js__WEBPACK_IMPORTED_MODULE_3__.IndexedDbCache)) {\n this._cache = new _cache_IndexedDbCache_js__WEBPACK_IMPORTED_MODULE_3__.IndexedDbCache();\n return this._cache;\n }\n return this._cache;\n }\n constructor(electrum, network = _interface_js__WEBPACK_IMPORTED_MODULE_5__.Network.MAINNET, manualConnectionManagement) {\n this.network = network;\n this.manualConnectionManagement = manualConnectionManagement;\n this.subscriptions = 0;\n this.subscribedToHeaders = false;\n this.subscriptionMap = {};\n if (electrum) {\n this.electrum = electrum;\n }\n else {\n throw new Error(`A electrum-cash client is required.`);\n }\n }\n async getUtxos(cashaddr) {\n const result = await this.performRequest(\"blockchain.address.listunspent\", cashaddr, \"include_tokens\");\n return result.map((utxo) => ({\n txid: utxo.tx_hash,\n vout: utxo.tx_pos,\n satoshis: utxo.value,\n height: utxo.height,\n token: utxo.token_data\n ? {\n amount: BigInt(utxo.token_data.amount),\n tokenId: utxo.token_data.category,\n capability: utxo.token_data.nft?.capability,\n commitment: utxo.token_data.nft?.commitment,\n }\n : undefined,\n }));\n }\n async getBalance(cashaddr) {\n const result = await this.performRequest(\"blockchain.address.get_balance\", cashaddr);\n return result.confirmed + result.unconfirmed;\n }\n async getHeader(height, verbose = false) {\n const key = `header-${this.network}-${height}-${verbose}`;\n if (this.cache) {\n const cached = await this.cache.getItem(key);\n if (cached) {\n return verbose ? (0,_util_header_js__WEBPACK_IMPORTED_MODULE_6__.decodeHeader)(JSON.parse(cached)) : JSON.parse(cached);\n }\n }\n const result = await this.performRequest(\"blockchain.header.get\", height);\n if (this.cache) {\n await this.cache.setItem(key, JSON.stringify(result));\n }\n return verbose ? (0,_util_header_js__WEBPACK_IMPORTED_MODULE_6__.decodeHeader)(result) : result;\n }\n async getBlockHeight() {\n return (await this.performRequest(\"blockchain.headers.get_tip\"))\n .height;\n }\n async getRawTransaction(txHash, verbose = false, loadInputValues = false) {\n const key = `tx-${this.network}-${txHash}-${verbose}-${loadInputValues}`;\n if (this.cache) {\n const cached = await this.cache.getItem(key);\n if (cached) {\n return verbose ? JSON.parse(cached) : cached;\n }\n }\n try {\n const transaction = (await this.performRequest(\"blockchain.transaction.get\", txHash, verbose));\n if (this.cache) {\n await this.cache.setItem(key, verbose\n ? JSON.stringify(transaction)\n : transaction);\n }\n if (verbose && loadInputValues) {\n // get unique transaction hashes\n const hashes = [...new Set(transaction.vin.map((val) => val.txid))];\n const transactions = await Promise.all(hashes.map((hash) => this.getRawTransactionObject(hash, false)));\n const transactionMap = new Map();\n transactions.forEach((val) => transactionMap.set(val.hash, val));\n transaction.vin.forEach((input) => {\n const output = transactionMap\n .get(input.txid)\n .vout.find((val) => val.n === input.vout);\n input.address = output.scriptPubKey.addresses[0];\n input.value = output.value;\n input.tokenData = output.tokenData;\n });\n }\n return transaction;\n }\n catch (error) {\n if (error.message.indexOf(\"No such mempool or blockchain transaction.\") > -1)\n throw Error(`Could not decode transaction ${txHash}. It might not exist on the current blockchain (${this.network}).`);\n else\n throw error;\n }\n }\n // gets the decoded transaction in human readable form\n async getRawTransactionObject(txHash, loadInputValues = false) {\n return (await this.getRawTransaction(txHash, true, loadInputValues));\n }\n async sendRawTransaction(txHex, awaitPropagation = true) {\n return new Promise(async (resolve, reject) => {\n let txHash = await (0,_util_transaction_js__WEBPACK_IMPORTED_MODULE_7__.getTransactionHash)(txHex);\n if (!awaitPropagation) {\n this.performRequest(\"blockchain.transaction.broadcast\", txHex);\n resolve(txHash);\n }\n else {\n let cancel;\n const waitForTransactionCallback = async (data) => {\n if (data && data[0] === txHash && data[1] !== null) {\n await cancel?.();\n resolve(txHash);\n }\n };\n cancel = await this.subscribeToTransaction(txHash, waitForTransactionCallback);\n this.performRequest(\"blockchain.transaction.broadcast\", txHex).catch(async (error) => {\n await cancel?.();\n reject(error);\n });\n }\n });\n }\n // Get transaction history of a given cashaddr\n async getHistory(cashaddr, fromHeight = 0, toHeight = -1) {\n const result = await this.performRequest(\"blockchain.address.get_history\", cashaddr, fromHeight, toHeight);\n return result;\n }\n // Get the minimum fee a low-priority transaction must pay in order to be accepted to the daemon's memory pool.\n async getRelayFee() {\n const result = (await this.performRequest(\"blockchain.relayfee\"));\n return result;\n }\n async watchAddressStatus(cashaddr, callback) {\n const watchAddressStatusCallback = async (data) => {\n // subscription acknowledgement is the latest known status or null if no status is known\n // status is an array: [ cashaddr, statusHash ]\n if (data instanceof Array) {\n const addr = data[0];\n if (addr !== cashaddr) {\n return;\n }\n const status = data[1];\n callback(status);\n }\n };\n return this.subscribeToAddress(cashaddr, watchAddressStatusCallback);\n }\n async watchAddress(cashaddr, callback) {\n const historyMap = {};\n this.getHistory(cashaddr).then((history) => history.forEach((val) => (historyMap[val.tx_hash] = true)));\n const watchAddressStatusCallback = async () => {\n const newHistory = await this.getHistory(cashaddr);\n // sort history to put unconfirmed transactions in the beginning, then transactions in block height descenting order\n const txHashes = newHistory\n .sort((a, b) => a.height <= 0 || b.height <= 0 ? -1 : b.height - a.height)\n .map((val) => val.tx_hash);\n for (const hash of txHashes) {\n if (!(hash in historyMap)) {\n historyMap[hash] = true;\n callback(hash);\n // exit early to prevent further map lookups\n break;\n }\n }\n };\n return this.watchAddressStatus(cashaddr, watchAddressStatusCallback);\n }\n async watchAddressTransactions(cashaddr, callback) {\n return this.watchAddress(cashaddr, async (txHash) => {\n const tx = await this.getRawTransactionObject(txHash);\n callback(tx);\n });\n }\n async watchAddressTokenTransactions(cashaddr, callback) {\n return this.watchAddress(cashaddr, async (txHash) => {\n const tx = await this.getRawTransactionObject(txHash, true);\n if (tx.vin.some((val) => val.tokenData) ||\n tx.vout.some((val) => val.tokenData)) {\n callback(tx);\n }\n });\n }\n // watch for block headers and block height, if `skipCurrentHeight` is set, the notification about current block will not arrive\n async watchBlocks(callback, skipCurrentHeight = true) {\n let acknowledged = !skipCurrentHeight;\n const waitForBlockCallback = (_header) => {\n if (!acknowledged) {\n acknowledged = true;\n return;\n }\n _header = _header instanceof Array ? _header[0] : _header;\n callback(_header);\n };\n return this.subscribeToHeaders(waitForBlockCallback);\n }\n // Wait for the next block or a block at given blockchain height.\n async waitForBlock(height) {\n return new Promise(async (resolve) => {\n let cancelWatch;\n if (this.electrum.chainHeight && !height) {\n height = this.electrum.chainHeight + 1;\n }\n cancelWatch = await this.watchBlocks(async (header) => {\n if (!height) {\n height = header.height + 1;\n return;\n }\n if (header.height >= height) {\n await cancelWatch?.();\n resolve(header);\n return;\n }\n });\n });\n }\n // subscribe to notifications sent when new block is found, the block header is sent to callback\n async subscribeToHeaders(callback) {\n return this.subscribeRequest(\"blockchain.headers.subscribe\", callback);\n }\n async subscribeToAddress(cashaddr, callback) {\n return this.subscribeRequest(\"blockchain.address.subscribe\", callback, cashaddr);\n }\n async subscribeToTransaction(txHash, callback) {\n return this.subscribeRequest(\"blockchain.transaction.subscribe\", callback, txHash);\n }\n async performRequest(name, ...parameters) {\n await this.ready();\n const requestTimeout = new Promise(function (_resolve, reject) {\n setTimeout(function () {\n reject(\"electrum-cash request timed out, retrying\");\n }, 30000);\n }).catch(function (e) {\n throw e;\n });\n const request = this.electrum.request(name, ...parameters);\n return await Promise.race([request, requestTimeout])\n .then((value) => {\n if (value instanceof Error)\n throw value;\n let result = value;\n return result;\n })\n .catch(async () => {\n return await Promise.race([request, requestTimeout])\n .then((value) => {\n if (value instanceof Error)\n throw value;\n let result = value;\n return result;\n })\n .catch(function (e) {\n throw e;\n });\n });\n }\n async trackSubscription(methodName, ...parameters) {\n const key = `${methodName}-${this.network}-${JSON.stringify(parameters)}`;\n if (this.subscriptionMap[key]) {\n this.subscriptionMap[key]++;\n }\n else {\n this.subscriptionMap[key] = 1;\n }\n await this.electrum.subscribe(methodName, ...parameters);\n }\n async untrackSubscription(methodName, ...parameters) {\n const key = `${methodName}-${this.network}-${JSON.stringify(parameters)}`;\n if (this.subscriptionMap[key]) {\n this.subscriptionMap[key]--;\n if (this.subscriptionMap[key] <= 0) {\n // only really unsubscribe if there are no more subscriptions for this `key`\n delete this.subscriptionMap[key];\n try {\n await this.electrum.unsubscribe(methodName, ...parameters);\n }\n catch { }\n }\n }\n }\n async subscribeRequest(methodName, callback, ...parameters) {\n await this.ready();\n const handler = (data) => {\n if (data.method === methodName) {\n callback(data.params);\n }\n };\n this.electrum.on(\"notification\", handler);\n // safeguard against multiple subscriptions to headers\n if (methodName === \"blockhain.headers.subscribe\") {\n if (!this.subscribedToHeaders) {\n this.subscribedToHeaders = true;\n await this.trackSubscription(methodName, ...parameters);\n }\n }\n else {\n await this.trackSubscription(methodName, ...parameters);\n }\n this.subscriptions++;\n return async () => {\n this.electrum.off(\"notification\", handler);\n this.subscriptions--;\n // there are no blockchain.headers.unsubscribe method, so let's safeguard against it\n if (methodName !== \"blockchain.headers.subscribe\") {\n await this.untrackSubscription(methodName, ...parameters);\n }\n };\n }\n async ready() {\n return this.connect();\n }\n async connect() {\n await this.cache?.init();\n if (this.electrum.status !== _electrum_cash_network__WEBPACK_IMPORTED_MODULE_0__.ConnectionStatus.CONNECTED) {\n await this.electrum.connect();\n }\n }\n disconnect() {\n if (this.subscriptions > 0) {\n // console.warn(\n // `Trying to disconnect a network provider with ${this.subscriptions} active subscriptions. This is in most cases a bad idea.`\n // );\n }\n return this.electrum.disconnect(true, false);\n }\n}\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/network/ElectrumNetworkProvider.ts?");
|
|
238
238
|
|
|
239
239
|
/***/ }),
|
|
240
240
|
|
|
@@ -302,9 +302,9 @@ eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harm
|
|
|
302
302
|
/*!**********************************!*\
|
|
303
303
|
!*** ./src/rate/ExchangeRate.ts ***!
|
|
304
304
|
\**********************************/
|
|
305
|
-
/***/ ((
|
|
305
|
+
/***/ ((module, __webpack_exports__, __webpack_require__) => {
|
|
306
306
|
|
|
307
|
-
eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"ExchangeRate\": () => (/* binding */ ExchangeRate)\n/* harmony export */ });\n/* unused harmony exports getTtl, getRateFromExchange */\n/* harmony import */ var _constant_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../constant.js */ \"./src/constant.ts\");\n/* harmony import */ var _util_getRuntimePlatform_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../util/getRuntimePlatform.js */ \"./src/util/getRuntimePlatform.ts\");\n/* harmony import */ var _db_ExchangeRateProvider_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../db/ExchangeRateProvider.js */ \"./src/db/ExchangeRateProvider.ts\");\n\n\n\nclass ExchangeRate {\n constructor({ symbol, rate, ttl, }) {\n this.symbol = symbol;\n this.rate = rate;\n this.ttl = ttl;\n }\n toString() {\n this.rate.toFixed(2);\n }\n static async get(symbol, useCache = true) {\n const platform = (0,_util_getRuntimePlatform_js__WEBPACK_IMPORTED_MODULE_0__.getRuntimePlatform)();\n if (platform === _util_getRuntimePlatform_js__WEBPACK_IMPORTED_MODULE_0__.RuntimePlatform.browser) {\n try {\n return await this.getRateFromLocalStorage(symbol, useCache);\n }\n catch {\n return await this.getRateFromGlobalScope(symbol, useCache);\n }\n }\n else {\n return await this.getRateFromGlobalScope(symbol, useCache);\n }\n }\n static async getRateFromLocalStorage(symbol, useCache = true) {\n if (!useCache) {\n return await getRateFromExchange(symbol);\n }\n let cache = new _db_ExchangeRateProvider_js__WEBPACK_IMPORTED_MODULE_1__[\"default\"]();\n let cacheRate = await cache.getRate(symbol);\n if (cacheRate) {\n // if the cache is still good, return it\n if (cacheRate.ttl > Date.now()) {\n return cacheRate.rate;\n }\n // else fall through\n }\n let freshRate = await getRateFromExchange(symbol);\n cache.setRate(symbol, freshRate, getTtl());\n return freshRate;\n }\n static async getRateFromGlobalScope(symbol, useCache = true) {\n if (!useCache) {\n return await getRateFromExchange(symbol);\n }\n if (globalThis.RATE) {\n let rateObject = globalThis.RATE;\n if (symbol in rateObject) {\n let cachedRate = rateObject[symbol];\n // If the cache is still good return ie\n if (cachedRate.ttl > Date.now()) {\n return cachedRate.rate;\n }\n }\n }\n let freshRate = await getRateFromExchange(symbol);\n this.cacheRateInGlobalScope(symbol, freshRate);\n return freshRate;\n }\n static cacheRateInGlobalScope(symbol, rate) {\n if (!globalThis.RATE) {\n globalThis.RATE = {};\n }\n else {\n globalThis.RATE[symbol] = {\n symbol: symbol,\n rate: rate,\n ttl: getTtl(),\n };\n }\n }\n}\nfunction getTtl() {\n return Math.trunc(Date.now() + _constant_js__WEBPACK_IMPORTED_MODULE_2__.EXCHANGE_RATE_TTL);\n}\n// Attempt to get the usd rate from some web app\nasync function getRateFromExchange(symbol) {\n if (symbol.length > 0) {\n symbol = symbol.toLocaleLowerCase();\n }\n if (symbol === \"usd\") {\n try {\n const response = await fetch(\"https://markets.api.bitcoin.com/live/bitcoin\");\n const data = await response.json();\n return data[\"data\"][\"BCH\"];\n }\n catch { }\n }\n const response = await fetch(\"https://bitpay.com/rates/BCH\");\n const data = (await response.json());\n const rates = data.data.reduce((acc, rate) => ({ ...acc, [rate.code.toLocaleLowerCase()]: rate.rate }), {});\n if (symbol in rates) {\n return rates[symbol];\n }\n throw Error(`Currency '${symbol}' is not supported.`);\n}\n// do not await and do not throw in case we are offline\nExchangeRate.get(\"usd\").catch(() => { });\n\n\n//# sourceURL=webpack://mainnet-js/./src/rate/ExchangeRate.ts?");
|
|
307
|
+
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 */ \"ExchangeRate\": () => (/* binding */ ExchangeRate)\n/* harmony export */ });\n/* unused harmony exports getTtl, getRateFromExchange */\n/* harmony import */ var _constant_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../constant.js */ \"./src/constant.ts\");\n/* harmony import */ var _util_getRuntimePlatform_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../util/getRuntimePlatform.js */ \"./src/util/getRuntimePlatform.ts\");\n/* harmony import */ var _db_ExchangeRateProvider_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../db/ExchangeRateProvider.js */ \"./src/db/ExchangeRateProvider.ts\");\n/* harmony import */ var _config_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../config.js */ \"./src/config.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_config_js__WEBPACK_IMPORTED_MODULE_3__]);\n_config_js__WEBPACK_IMPORTED_MODULE_3__ = (__webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__)[0];\n\n\n\n\nclass ExchangeRate {\n constructor({ symbol, rate, ttl, }) {\n this.symbol = symbol;\n this.rate = rate;\n this.ttl = ttl;\n }\n toString() {\n this.rate.toFixed(2);\n }\n static async get(symbol, useCache = true) {\n const platform = (0,_util_getRuntimePlatform_js__WEBPACK_IMPORTED_MODULE_0__.getRuntimePlatform)();\n if (platform === _util_getRuntimePlatform_js__WEBPACK_IMPORTED_MODULE_0__.RuntimePlatform.browser) {\n try {\n return await this.getRateFromLocalStorage(symbol, useCache);\n }\n catch {\n return await this.getRateFromGlobalScope(symbol, useCache);\n }\n }\n else {\n return await this.getRateFromGlobalScope(symbol, useCache);\n }\n }\n static async getRateFromLocalStorage(symbol, useCache = true) {\n if (!useCache) {\n return await getRateFromExchange(symbol);\n }\n let cache = new _db_ExchangeRateProvider_js__WEBPACK_IMPORTED_MODULE_1__[\"default\"]();\n let cacheRate = await cache.getRate(symbol);\n if (cacheRate) {\n // if the cache is still good, return it\n if (cacheRate.ttl > Date.now()) {\n return cacheRate.rate;\n }\n // else fall through\n }\n let freshRate = await getRateFromExchange(symbol);\n cache.setRate(symbol, freshRate, getTtl());\n return freshRate;\n }\n static async getRateFromGlobalScope(symbol, useCache = true) {\n if (!useCache) {\n return await getRateFromExchange(symbol);\n }\n if (globalThis.RATE) {\n let rateObject = globalThis.RATE;\n if (symbol in rateObject) {\n let cachedRate = rateObject[symbol];\n // If the cache is still good return ie\n if (cachedRate.ttl > Date.now()) {\n return cachedRate.rate;\n }\n }\n }\n let freshRate = await getRateFromExchange(symbol);\n this.cacheRateInGlobalScope(symbol, freshRate);\n return freshRate;\n }\n static cacheRateInGlobalScope(symbol, rate) {\n if (!globalThis.RATE) {\n globalThis.RATE = {};\n }\n else {\n globalThis.RATE[symbol] = {\n symbol: symbol,\n rate: rate,\n ttl: getTtl(),\n };\n }\n }\n}\nfunction getTtl() {\n return Math.trunc(Date.now() + _constant_js__WEBPACK_IMPORTED_MODULE_2__.EXCHANGE_RATE_TTL);\n}\n// Attempt to get the usd rate from some web app\nasync function getRateFromExchange(symbol) {\n if (_config_js__WEBPACK_IMPORTED_MODULE_3__.Config.GetExchangeRateFn) {\n return await _config_js__WEBPACK_IMPORTED_MODULE_3__.Config.GetExchangeRateFn(symbol);\n }\n if (symbol.length > 0) {\n symbol = symbol.toLocaleLowerCase();\n }\n if (symbol === \"usd\") {\n try {\n const response = await fetch(\"https://markets.api.bitcoin.com/live/bitcoin\");\n const data = await response.json();\n return data[\"data\"][\"BCH\"];\n }\n catch { }\n }\n const response = await fetch(\"https://bitpay.com/rates/BCH\");\n const data = (await response.json());\n const rates = data.data.reduce((acc, rate) => ({ ...acc, [rate.code.toLocaleLowerCase()]: rate.rate }), {});\n if (symbol in rates) {\n return rates[symbol];\n }\n throw Error(`Currency '${symbol}' is not supported.`);\n}\n// do not await and do not throw in case we are offline\nExchangeRate.get(\"usd\").catch(() => { });\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/rate/ExchangeRate.ts?");
|
|
308
308
|
|
|
309
309
|
/***/ }),
|
|
310
310
|
|
|
@@ -354,7 +354,7 @@ eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__
|
|
|
354
354
|
\*************************************/
|
|
355
355
|
/***/ ((module, __webpack_exports__, __webpack_require__) => {
|
|
356
356
|
|
|
357
|
-
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 */ \"amountInSatoshi\": () => (/* binding */ amountInSatoshi)\n/* harmony export */ });\n/* harmony import */ var _chain_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../chain.js */ \"./src/chain.ts\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../enum.js */ \"./src/enum.ts\");\n/* harmony import */ var _rate_ExchangeRate_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../rate/ExchangeRate.js */ \"./src/rate/ExchangeRate.ts\");\n/* harmony import */ var _util_sanitizeUnit_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/sanitizeUnit.js */ \"./src/util/sanitizeUnit.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_enum_js__WEBPACK_IMPORTED_MODULE_2__]);\
|
|
357
|
+
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 */ \"amountInSatoshi\": () => (/* binding */ amountInSatoshi)\n/* harmony export */ });\n/* harmony import */ var _chain_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../chain.js */ \"./src/chain.ts\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../enum.js */ \"./src/enum.ts\");\n/* harmony import */ var _rate_ExchangeRate_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../rate/ExchangeRate.js */ \"./src/rate/ExchangeRate.ts\");\n/* harmony import */ var _util_sanitizeUnit_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/sanitizeUnit.js */ \"./src/util/sanitizeUnit.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_rate_ExchangeRate_js__WEBPACK_IMPORTED_MODULE_0__, _enum_js__WEBPACK_IMPORTED_MODULE_2__]);\n([_rate_ExchangeRate_js__WEBPACK_IMPORTED_MODULE_0__, _enum_js__WEBPACK_IMPORTED_MODULE_2__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\n\n\n/**\n * converts given value and unit into satoshi\n *\n * @param {value} number some value\n * @param {rawUnit} any the unit of value\n *\n * @returns a promise to the value in satoshi\n */\nasync function amountInSatoshi(value, rawUnit) {\n const unit = (0,_util_sanitizeUnit_js__WEBPACK_IMPORTED_MODULE_1__.sanitizeUnit)(rawUnit);\n switch (unit) {\n case _enum_js__WEBPACK_IMPORTED_MODULE_2__.UnitEnum.BCH:\n return Math.round(value * _chain_js__WEBPACK_IMPORTED_MODULE_3__.bchParam.subUnits);\n case _enum_js__WEBPACK_IMPORTED_MODULE_2__.UnitEnum.SATOSHI:\n return value;\n case _enum_js__WEBPACK_IMPORTED_MODULE_2__.UnitEnum.SAT:\n return value;\n case _enum_js__WEBPACK_IMPORTED_MODULE_2__.UnitEnum.SATS:\n return value;\n case _enum_js__WEBPACK_IMPORTED_MODULE_2__.UnitEnum.SATOSHIS:\n return value;\n default:\n const Currency_over_BCH = await _rate_ExchangeRate_js__WEBPACK_IMPORTED_MODULE_0__.ExchangeRate.get(rawUnit);\n const SAT_over_BCH = _chain_js__WEBPACK_IMPORTED_MODULE_3__.bchParam.subUnits;\n return Math.round(Number(value * (SAT_over_BCH / Currency_over_BCH)));\n }\n}\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/util/amountInSatoshi.ts?");
|
|
358
358
|
|
|
359
359
|
/***/ }),
|
|
360
360
|
|
|
@@ -374,7 +374,7 @@ eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__
|
|
|
374
374
|
\**********************************************/
|
|
375
375
|
/***/ ((module, __webpack_exports__, __webpack_require__) => {
|
|
376
376
|
|
|
377
|
-
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 */ \"balanceFromSatoshi\": () => (/* binding */ balanceFromSatoshi),\n/* harmony export */ \"balanceResponseFromSatoshi\": () => (/* binding */ balanceResponseFromSatoshi)\n/* harmony export */ });\n/* harmony import */ var _chain_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../chain.js */ \"./src/chain.ts\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../enum.js */ \"./src/enum.ts\");\n/* harmony import */ var _floor_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./floor.js */ \"./src/util/floor.ts\");\n/* harmony import */ var _rate_ExchangeRate_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../rate/ExchangeRate.js */ \"./src/rate/ExchangeRate.ts\");\n/* harmony import */ var _sanitizeUnit_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./sanitizeUnit.js */ \"./src/util/sanitizeUnit.ts\");\n/* harmony import */ var _config_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../config.js */ \"./src/config.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_config_js__WEBPACK_IMPORTED_MODULE_2__, _enum_js__WEBPACK_IMPORTED_MODULE_5__]);\n([_config_js__WEBPACK_IMPORTED_MODULE_2__, _enum_js__WEBPACK_IMPORTED_MODULE_5__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\n\n\n\n\nasync function balanceResponseFromSatoshi(value, priceCache = true) {\n const response = {};\n response.bch = value / _chain_js__WEBPACK_IMPORTED_MODULE_1__.bchParam.subUnits;\n response.sat = value;\n const currencyValue = (value / _chain_js__WEBPACK_IMPORTED_MODULE_1__.bchParam.subUnits) *\n (await _rate_ExchangeRate_js__WEBPACK_IMPORTED_MODULE_0__.ExchangeRate.get(_config_js__WEBPACK_IMPORTED_MODULE_2__.Config.DefaultCurrency, priceCache));\n response[_config_js__WEBPACK_IMPORTED_MODULE_2__.Config.DefaultCurrency] = (0,_floor_js__WEBPACK_IMPORTED_MODULE_3__.floor)(currencyValue, 2);\n return response;\n}\nasync function balanceFromSatoshi(value, rawUnit, priceCache = true) {\n const unit = (0,_sanitizeUnit_js__WEBPACK_IMPORTED_MODULE_4__.sanitizeUnit)(rawUnit);\n switch (unit) {\n case _enum_js__WEBPACK_IMPORTED_MODULE_5__.UnitEnum.BCH:\n return value / _chain_js__WEBPACK_IMPORTED_MODULE_1__.bchParam.subUnits;\n case _enum_js__WEBPACK_IMPORTED_MODULE_5__.UnitEnum.SAT:\n return value;\n case _enum_js__WEBPACK_IMPORTED_MODULE_5__.UnitEnum.SATS:\n return value;\n case _enum_js__WEBPACK_IMPORTED_MODULE_5__.UnitEnum.SATOSHI:\n return value;\n case _enum_js__WEBPACK_IMPORTED_MODULE_5__.UnitEnum.SATOSHIS:\n return value;\n default:\n const currencyValue = (value / _chain_js__WEBPACK_IMPORTED_MODULE_1__.bchParam.subUnits) *\n (await _rate_ExchangeRate_js__WEBPACK_IMPORTED_MODULE_0__.ExchangeRate.get(_config_js__WEBPACK_IMPORTED_MODULE_2__.Config.DefaultCurrency, priceCache));\n return Number(currencyValue.toFixed(2));\n }\n}\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/util/balanceObjectFromSatoshi.ts?");
|
|
377
|
+
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 */ \"balanceFromSatoshi\": () => (/* binding */ balanceFromSatoshi),\n/* harmony export */ \"balanceResponseFromSatoshi\": () => (/* binding */ balanceResponseFromSatoshi)\n/* harmony export */ });\n/* harmony import */ var _chain_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../chain.js */ \"./src/chain.ts\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../enum.js */ \"./src/enum.ts\");\n/* harmony import */ var _floor_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./floor.js */ \"./src/util/floor.ts\");\n/* harmony import */ var _rate_ExchangeRate_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../rate/ExchangeRate.js */ \"./src/rate/ExchangeRate.ts\");\n/* harmony import */ var _sanitizeUnit_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./sanitizeUnit.js */ \"./src/util/sanitizeUnit.ts\");\n/* harmony import */ var _config_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../config.js */ \"./src/config.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_rate_ExchangeRate_js__WEBPACK_IMPORTED_MODULE_0__, _config_js__WEBPACK_IMPORTED_MODULE_2__, _enum_js__WEBPACK_IMPORTED_MODULE_5__]);\n([_rate_ExchangeRate_js__WEBPACK_IMPORTED_MODULE_0__, _config_js__WEBPACK_IMPORTED_MODULE_2__, _enum_js__WEBPACK_IMPORTED_MODULE_5__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\n\n\n\n\nasync function balanceResponseFromSatoshi(value, priceCache = true) {\n const response = {};\n response.bch = value / _chain_js__WEBPACK_IMPORTED_MODULE_1__.bchParam.subUnits;\n response.sat = value;\n const currencyValue = (value / _chain_js__WEBPACK_IMPORTED_MODULE_1__.bchParam.subUnits) *\n (await _rate_ExchangeRate_js__WEBPACK_IMPORTED_MODULE_0__.ExchangeRate.get(_config_js__WEBPACK_IMPORTED_MODULE_2__.Config.DefaultCurrency, priceCache));\n response[_config_js__WEBPACK_IMPORTED_MODULE_2__.Config.DefaultCurrency] = (0,_floor_js__WEBPACK_IMPORTED_MODULE_3__.floor)(currencyValue, 2);\n return response;\n}\nasync function balanceFromSatoshi(value, rawUnit, priceCache = true) {\n const unit = (0,_sanitizeUnit_js__WEBPACK_IMPORTED_MODULE_4__.sanitizeUnit)(rawUnit);\n switch (unit) {\n case _enum_js__WEBPACK_IMPORTED_MODULE_5__.UnitEnum.BCH:\n return value / _chain_js__WEBPACK_IMPORTED_MODULE_1__.bchParam.subUnits;\n case _enum_js__WEBPACK_IMPORTED_MODULE_5__.UnitEnum.SAT:\n return value;\n case _enum_js__WEBPACK_IMPORTED_MODULE_5__.UnitEnum.SATS:\n return value;\n case _enum_js__WEBPACK_IMPORTED_MODULE_5__.UnitEnum.SATOSHI:\n return value;\n case _enum_js__WEBPACK_IMPORTED_MODULE_5__.UnitEnum.SATOSHIS:\n return value;\n default:\n const currencyValue = (value / _chain_js__WEBPACK_IMPORTED_MODULE_1__.bchParam.subUnits) *\n (await _rate_ExchangeRate_js__WEBPACK_IMPORTED_MODULE_0__.ExchangeRate.get(_config_js__WEBPACK_IMPORTED_MODULE_2__.Config.DefaultCurrency, priceCache));\n return Number(currencyValue.toFixed(2));\n }\n}\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/util/balanceObjectFromSatoshi.ts?");
|
|
378
378
|
|
|
379
379
|
/***/ }),
|
|
380
380
|
|
|
@@ -502,9 +502,9 @@ eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harm
|
|
|
502
502
|
/*!********************************!*\
|
|
503
503
|
!*** ./src/util/getUsdRate.ts ***!
|
|
504
504
|
\********************************/
|
|
505
|
-
/***/ ((
|
|
505
|
+
/***/ ((module, __webpack_exports__, __webpack_require__) => {
|
|
506
506
|
|
|
507
|
-
eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"getUsdRate\": () => (/* binding */ getUsdRate)\n/* harmony export */ });\n/* harmony import */ var _rate_ExchangeRate_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../rate/ExchangeRate.js */ \"./src/rate/ExchangeRate.ts\");\n\nfunction getUsdRate() {\n return _rate_ExchangeRate_js__WEBPACK_IMPORTED_MODULE_0__.ExchangeRate.get(\"usd\");\n}\n\n\n//# sourceURL=webpack://mainnet-js/./src/util/getUsdRate.ts?");
|
|
507
|
+
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 */ \"getUsdRate\": () => (/* binding */ getUsdRate)\n/* harmony export */ });\n/* harmony import */ var _rate_ExchangeRate_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../rate/ExchangeRate.js */ \"./src/rate/ExchangeRate.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_rate_ExchangeRate_js__WEBPACK_IMPORTED_MODULE_0__]);\n_rate_ExchangeRate_js__WEBPACK_IMPORTED_MODULE_0__ = (__webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__)[0];\n\nfunction getUsdRate() {\n return _rate_ExchangeRate_js__WEBPACK_IMPORTED_MODULE_0__.ExchangeRate.get(\"usd\");\n}\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/util/getUsdRate.ts?");
|
|
508
508
|
|
|
509
509
|
/***/ }),
|
|
510
510
|
|
|
@@ -544,7 +544,7 @@ eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__
|
|
|
544
544
|
\***************************/
|
|
545
545
|
/***/ ((module, __webpack_exports__, __webpack_require__) => {
|
|
546
546
|
|
|
547
|
-
eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"ExchangeRate\": () => (/* reexport safe */ _rate_ExchangeRate_js__WEBPACK_IMPORTED_MODULE_16__.ExchangeRate),\n/* harmony export */ \"RuntimePlatform\": () => (/* reexport safe */ _getRuntimePlatform_js__WEBPACK_IMPORTED_MODULE_13__.RuntimePlatform),\n/* harmony export */ \"amountInSatoshi\": () => (/* reexport safe */ _amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_0__.amountInSatoshi),\n/* harmony export */ \"asSendRequestObject\": () => (/* reexport safe */ _asSendRequestObject_js__WEBPACK_IMPORTED_MODULE_1__.asSendRequestObject),\n/* harmony export */ \"atob\": () => (/* reexport safe */ _base64_js__WEBPACK_IMPORTED_MODULE_2__.atob),\n/* harmony export */ \"balanceFromSatoshi\": () => (/* reexport safe */ _balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_22__.balanceFromSatoshi),\n/* harmony export */ \"balanceResponseFromSatoshi\": () => (/* reexport safe */ _balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_22__.balanceResponseFromSatoshi),\n/* harmony export */ \"binToBase64\": () => (/* reexport safe */ _bitauth_libauth__WEBPACK_IMPORTED_MODULE_5__.binToBase64),\n/* harmony export */ \"binToHex\": () => (/* reexport safe */ _bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.binToHex),\n/* harmony export */ \"btoa\": () => (/* reexport safe */ _base64_js__WEBPACK_IMPORTED_MODULE_2__.btoa),\n/* harmony export */ \"checkTokenaddr\": () => (/* reexport safe */ _deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_11__.checkTokenaddr),\n/* harmony export */ \"convert\": () => (/* reexport safe */ _convert_js__WEBPACK_IMPORTED_MODULE_7__.convert),\n/* harmony export */ \"convertAddress\": () => (/* reexport safe */ _deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_11__.convertAddress),\n/* harmony export */ \"convertObject\": () => (/* reexport safe */ _convert_js__WEBPACK_IMPORTED_MODULE_7__.convertObject),\n/* harmony export */ \"decodeHeader\": () => (/* reexport safe */ _header_js__WEBPACK_IMPORTED_MODULE_23__.decodeHeader),\n/* harmony export */ \"delay\": () => (/* reexport safe */ _delay_js__WEBPACK_IMPORTED_MODULE_8__.delay),\n/* harmony export */ \"deriveCashaddr\": () => (/* reexport safe */ _deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_11__.deriveCashaddr),\n/* harmony export */ \"derivePublicKeyHash\": () => (/* reexport safe */ _derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_10__.derivePublicKeyHash),\n/* harmony export */ \"deriveTokenaddr\": () => (/* reexport safe */ _deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_11__.deriveTokenaddr),\n/* harmony export */ \"derivedNetwork\": () => (/* reexport safe */ _deriveNetwork_js__WEBPACK_IMPORTED_MODULE_9__.derivedNetwork),\n/* harmony export */ \"getAddrsByXpubKey\": () => (/* reexport safe */ _util_getAddrsByXpubKey_js__WEBPACK_IMPORTED_MODULE_12__.getAddrsByXpubKey),\n/* harmony export */ \"getAddrsByXpubKeyObject\": () => (/* reexport safe */ _util_getAddrsByXpubKey_js__WEBPACK_IMPORTED_MODULE_12__.getAddrsByXpubKeyObject),\n/* harmony export */ \"getRuntimePlatform\": () => (/* reexport safe */ _getRuntimePlatform_js__WEBPACK_IMPORTED_MODULE_13__.getRuntimePlatform),\n/* harmony export */ \"getUsdRate\": () => (/* reexport safe */ _getUsdRate_js__WEBPACK_IMPORTED_MODULE_14__.getUsdRate),\n/* harmony export */ \"getWeakRandomInt\": () => (/* reexport safe */ _randomInt_js__WEBPACK_IMPORTED_MODULE_19__.getWeakRandomInt),\n/* harmony export */ \"getXPubKey\": () => (/* reexport safe */ _util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_20__.getXPubKey),\n/* harmony export */ \"getXpubKeyInfo\": () => (/* reexport safe */ _util_getAddrsByXpubKey_js__WEBPACK_IMPORTED_MODULE_12__.getXpubKeyInfo),\n/* harmony export */ \"getXpubKeyInfoObject\": () => (/* reexport safe */ _util_getAddrsByXpubKey_js__WEBPACK_IMPORTED_MODULE_12__.getXpubKeyInfoObject),\n/* harmony export */ \"hash160\": () => (/* reexport safe */ _hash160_js__WEBPACK_IMPORTED_MODULE_15__.hash160),\n/* harmony export */ \"hexToBin\": () => (/* reexport safe */ _bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.hexToBin),\n/* harmony export */ \"isTokenaddr\": () => (/* reexport safe */ _deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_11__.isTokenaddr),\n/* harmony export */ \"isValidAddress\": () => (/* reexport safe */ _deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_11__.isValidAddress),\n/* harmony export */ \"sanitizeAddress\": () => (/* reexport safe */ _sanitizeAddress_js__WEBPACK_IMPORTED_MODULE_17__.sanitizeAddress),\n/* harmony export */ \"sanitizeUnit\": () => (/* reexport safe */ _sanitizeUnit_js__WEBPACK_IMPORTED_MODULE_18__.sanitizeUnit),\n/* harmony export */ \"sha256\": () => (/* reexport safe */ _bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__.sha256),\n/* harmony export */ \"sumTokenAmounts\": () => (/* reexport safe */ _sumUtxoValue_js__WEBPACK_IMPORTED_MODULE_21__.sumTokenAmounts),\n/* harmony export */ \"sumUtxoValue\": () => (/* reexport safe */ _sumUtxoValue_js__WEBPACK_IMPORTED_MODULE_21__.sumUtxoValue),\n/* harmony export */ \"toCashaddr\": () => (/* reexport safe */ _deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_11__.toCashaddr),\n/* harmony export */ \"toTokenaddr\": () => (/* reexport safe */ _deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_11__.toTokenaddr),\n/* harmony export */ \"utf8ToBin\": () => (/* reexport safe */ _bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__.utf8ToBin)\n/* harmony export */ });\n/* harmony import */ var _amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./amountInSatoshi.js */ \"./src/util/amountInSatoshi.ts\");\n/* harmony import */ var _asSendRequestObject_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./asSendRequestObject.js */ \"./src/util/asSendRequestObject.ts\");\n/* harmony import */ var _base64_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./base64.js */ \"./src/util/base64.ts\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @bitauth/libauth */ \"./node_modules/@bitauth/libauth/build/lib/format/hex.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @bitauth/libauth */ \"./node_modules/@bitauth/libauth/build/lib/format/utf8.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @bitauth/libauth */ \"./node_modules/@bitauth/libauth/build/lib/format/base64.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @bitauth/libauth */ \"./node_modules/@bitauth/libauth/build/lib/crypto/default-crypto-instances.js\");\n/* harmony import */ var _convert_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./convert.js */ \"./src/util/convert.ts\");\n/* harmony import */ var _delay_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./delay.js */ \"./src/util/delay.ts\");\n/* harmony import */ var _deriveNetwork_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./deriveNetwork.js */ \"./src/util/deriveNetwork.ts\");\n/* harmony import */ var _derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./derivePublicKeyHash.js */ \"./src/util/derivePublicKeyHash.ts\");\n/* harmony import */ var _deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./deriveCashaddr.js */ \"./src/util/deriveCashaddr.ts\");\n/* harmony import */ var _util_getAddrsByXpubKey_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../util/getAddrsByXpubKey.js */ \"./src/util/getAddrsByXpubKey.ts\");\n/* harmony import */ var _getRuntimePlatform_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./getRuntimePlatform.js */ \"./src/util/getRuntimePlatform.ts\");\n/* harmony import */ var _getUsdRate_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./getUsdRate.js */ \"./src/util/getUsdRate.ts\");\n/* harmony import */ var _hash160_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./hash160.js */ \"./src/util/hash160.ts\");\n/* harmony import */ var _rate_ExchangeRate_js__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../rate/ExchangeRate.js */ \"./src/rate/ExchangeRate.ts\");\n/* harmony import */ var _sanitizeAddress_js__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./sanitizeAddress.js */ \"./src/util/sanitizeAddress.ts\");\n/* harmony import */ var _sanitizeUnit_js__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./sanitizeUnit.js */ \"./src/util/sanitizeUnit.ts\");\n/* harmony import */ var _randomInt_js__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./randomInt.js */ \"./src/util/randomInt.ts\");\n/* harmony import */ var _util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ../util/getXPubKey.js */ \"./src/util/getXPubKey.ts\");\n/* harmony import */ var _sumUtxoValue_js__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ./sumUtxoValue.js */ \"./src/util/sumUtxoValue.ts\");\n/* harmony import */ var _balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ./balanceObjectFromSatoshi.js */ \"./src/util/balanceObjectFromSatoshi.ts\");\n/* harmony import */ var _header_js__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! ./header.js */ \"./src/util/header.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_0__, _asSendRequestObject_js__WEBPACK_IMPORTED_MODULE_1__, _base64_js__WEBPACK_IMPORTED_MODULE_2__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__, _convert_js__WEBPACK_IMPORTED_MODULE_7__, _deriveNetwork_js__WEBPACK_IMPORTED_MODULE_9__, _derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_10__, _deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_11__, _util_getAddrsByXpubKey_js__WEBPACK_IMPORTED_MODULE_12__, _hash160_js__WEBPACK_IMPORTED_MODULE_15__, _sanitizeAddress_js__WEBPACK_IMPORTED_MODULE_17__, _util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_20__, _balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_22__, _header_js__WEBPACK_IMPORTED_MODULE_23__]);\n([_amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_0__, _asSendRequestObject_js__WEBPACK_IMPORTED_MODULE_1__, _base64_js__WEBPACK_IMPORTED_MODULE_2__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__, _convert_js__WEBPACK_IMPORTED_MODULE_7__, _deriveNetwork_js__WEBPACK_IMPORTED_MODULE_9__, _derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_10__, _deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_11__, _util_getAddrsByXpubKey_js__WEBPACK_IMPORTED_MODULE_12__, _hash160_js__WEBPACK_IMPORTED_MODULE_15__, _sanitizeAddress_js__WEBPACK_IMPORTED_MODULE_17__, _util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_20__, _balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_22__, _header_js__WEBPACK_IMPORTED_MODULE_23__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/util/index.ts?");
|
|
547
|
+
eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"ExchangeRate\": () => (/* reexport safe */ _rate_ExchangeRate_js__WEBPACK_IMPORTED_MODULE_16__.ExchangeRate),\n/* harmony export */ \"RuntimePlatform\": () => (/* reexport safe */ _getRuntimePlatform_js__WEBPACK_IMPORTED_MODULE_13__.RuntimePlatform),\n/* harmony export */ \"amountInSatoshi\": () => (/* reexport safe */ _amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_0__.amountInSatoshi),\n/* harmony export */ \"asSendRequestObject\": () => (/* reexport safe */ _asSendRequestObject_js__WEBPACK_IMPORTED_MODULE_1__.asSendRequestObject),\n/* harmony export */ \"atob\": () => (/* reexport safe */ _base64_js__WEBPACK_IMPORTED_MODULE_2__.atob),\n/* harmony export */ \"balanceFromSatoshi\": () => (/* reexport safe */ _balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_22__.balanceFromSatoshi),\n/* harmony export */ \"balanceResponseFromSatoshi\": () => (/* reexport safe */ _balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_22__.balanceResponseFromSatoshi),\n/* harmony export */ \"binToBase64\": () => (/* reexport safe */ _bitauth_libauth__WEBPACK_IMPORTED_MODULE_5__.binToBase64),\n/* harmony export */ \"binToHex\": () => (/* reexport safe */ _bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.binToHex),\n/* harmony export */ \"btoa\": () => (/* reexport safe */ _base64_js__WEBPACK_IMPORTED_MODULE_2__.btoa),\n/* harmony export */ \"checkTokenaddr\": () => (/* reexport safe */ _deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_11__.checkTokenaddr),\n/* harmony export */ \"convert\": () => (/* reexport safe */ _convert_js__WEBPACK_IMPORTED_MODULE_7__.convert),\n/* harmony export */ \"convertAddress\": () => (/* reexport safe */ _deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_11__.convertAddress),\n/* harmony export */ \"convertObject\": () => (/* reexport safe */ _convert_js__WEBPACK_IMPORTED_MODULE_7__.convertObject),\n/* harmony export */ \"decodeHeader\": () => (/* reexport safe */ _header_js__WEBPACK_IMPORTED_MODULE_23__.decodeHeader),\n/* harmony export */ \"delay\": () => (/* reexport safe */ _delay_js__WEBPACK_IMPORTED_MODULE_8__.delay),\n/* harmony export */ \"deriveCashaddr\": () => (/* reexport safe */ _deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_11__.deriveCashaddr),\n/* harmony export */ \"derivePublicKeyHash\": () => (/* reexport safe */ _derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_10__.derivePublicKeyHash),\n/* harmony export */ \"deriveTokenaddr\": () => (/* reexport safe */ _deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_11__.deriveTokenaddr),\n/* harmony export */ \"derivedNetwork\": () => (/* reexport safe */ _deriveNetwork_js__WEBPACK_IMPORTED_MODULE_9__.derivedNetwork),\n/* harmony export */ \"getAddrsByXpubKey\": () => (/* reexport safe */ _util_getAddrsByXpubKey_js__WEBPACK_IMPORTED_MODULE_12__.getAddrsByXpubKey),\n/* harmony export */ \"getAddrsByXpubKeyObject\": () => (/* reexport safe */ _util_getAddrsByXpubKey_js__WEBPACK_IMPORTED_MODULE_12__.getAddrsByXpubKeyObject),\n/* harmony export */ \"getRuntimePlatform\": () => (/* reexport safe */ _getRuntimePlatform_js__WEBPACK_IMPORTED_MODULE_13__.getRuntimePlatform),\n/* harmony export */ \"getUsdRate\": () => (/* reexport safe */ _getUsdRate_js__WEBPACK_IMPORTED_MODULE_14__.getUsdRate),\n/* harmony export */ \"getWeakRandomInt\": () => (/* reexport safe */ _randomInt_js__WEBPACK_IMPORTED_MODULE_19__.getWeakRandomInt),\n/* harmony export */ \"getXPubKey\": () => (/* reexport safe */ _util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_20__.getXPubKey),\n/* harmony export */ \"getXpubKeyInfo\": () => (/* reexport safe */ _util_getAddrsByXpubKey_js__WEBPACK_IMPORTED_MODULE_12__.getXpubKeyInfo),\n/* harmony export */ \"getXpubKeyInfoObject\": () => (/* reexport safe */ _util_getAddrsByXpubKey_js__WEBPACK_IMPORTED_MODULE_12__.getXpubKeyInfoObject),\n/* harmony export */ \"hash160\": () => (/* reexport safe */ _hash160_js__WEBPACK_IMPORTED_MODULE_15__.hash160),\n/* harmony export */ \"hexToBin\": () => (/* reexport safe */ _bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.hexToBin),\n/* harmony export */ \"isTokenaddr\": () => (/* reexport safe */ _deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_11__.isTokenaddr),\n/* harmony export */ \"isValidAddress\": () => (/* reexport safe */ _deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_11__.isValidAddress),\n/* harmony export */ \"sanitizeAddress\": () => (/* reexport safe */ _sanitizeAddress_js__WEBPACK_IMPORTED_MODULE_17__.sanitizeAddress),\n/* harmony export */ \"sanitizeUnit\": () => (/* reexport safe */ _sanitizeUnit_js__WEBPACK_IMPORTED_MODULE_18__.sanitizeUnit),\n/* harmony export */ \"sha256\": () => (/* reexport safe */ _bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__.sha256),\n/* harmony export */ \"sumTokenAmounts\": () => (/* reexport safe */ _sumUtxoValue_js__WEBPACK_IMPORTED_MODULE_21__.sumTokenAmounts),\n/* harmony export */ \"sumUtxoValue\": () => (/* reexport safe */ _sumUtxoValue_js__WEBPACK_IMPORTED_MODULE_21__.sumUtxoValue),\n/* harmony export */ \"toCashaddr\": () => (/* reexport safe */ _deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_11__.toCashaddr),\n/* harmony export */ \"toTokenaddr\": () => (/* reexport safe */ _deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_11__.toTokenaddr),\n/* harmony export */ \"utf8ToBin\": () => (/* reexport safe */ _bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__.utf8ToBin)\n/* harmony export */ });\n/* harmony import */ var _amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./amountInSatoshi.js */ \"./src/util/amountInSatoshi.ts\");\n/* harmony import */ var _asSendRequestObject_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./asSendRequestObject.js */ \"./src/util/asSendRequestObject.ts\");\n/* harmony import */ var _base64_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./base64.js */ \"./src/util/base64.ts\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @bitauth/libauth */ \"./node_modules/@bitauth/libauth/build/lib/format/hex.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @bitauth/libauth */ \"./node_modules/@bitauth/libauth/build/lib/format/utf8.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @bitauth/libauth */ \"./node_modules/@bitauth/libauth/build/lib/format/base64.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @bitauth/libauth */ \"./node_modules/@bitauth/libauth/build/lib/crypto/default-crypto-instances.js\");\n/* harmony import */ var _convert_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./convert.js */ \"./src/util/convert.ts\");\n/* harmony import */ var _delay_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./delay.js */ \"./src/util/delay.ts\");\n/* harmony import */ var _deriveNetwork_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./deriveNetwork.js */ \"./src/util/deriveNetwork.ts\");\n/* harmony import */ var _derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./derivePublicKeyHash.js */ \"./src/util/derivePublicKeyHash.ts\");\n/* harmony import */ var _deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./deriveCashaddr.js */ \"./src/util/deriveCashaddr.ts\");\n/* harmony import */ var _util_getAddrsByXpubKey_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../util/getAddrsByXpubKey.js */ \"./src/util/getAddrsByXpubKey.ts\");\n/* harmony import */ var _getRuntimePlatform_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./getRuntimePlatform.js */ \"./src/util/getRuntimePlatform.ts\");\n/* harmony import */ var _getUsdRate_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./getUsdRate.js */ \"./src/util/getUsdRate.ts\");\n/* harmony import */ var _hash160_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./hash160.js */ \"./src/util/hash160.ts\");\n/* harmony import */ var _rate_ExchangeRate_js__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../rate/ExchangeRate.js */ \"./src/rate/ExchangeRate.ts\");\n/* harmony import */ var _sanitizeAddress_js__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./sanitizeAddress.js */ \"./src/util/sanitizeAddress.ts\");\n/* harmony import */ var _sanitizeUnit_js__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./sanitizeUnit.js */ \"./src/util/sanitizeUnit.ts\");\n/* harmony import */ var _randomInt_js__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./randomInt.js */ \"./src/util/randomInt.ts\");\n/* harmony import */ var _util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ../util/getXPubKey.js */ \"./src/util/getXPubKey.ts\");\n/* harmony import */ var _sumUtxoValue_js__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ./sumUtxoValue.js */ \"./src/util/sumUtxoValue.ts\");\n/* harmony import */ var _balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ./balanceObjectFromSatoshi.js */ \"./src/util/balanceObjectFromSatoshi.ts\");\n/* harmony import */ var _header_js__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! ./header.js */ \"./src/util/header.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_0__, _asSendRequestObject_js__WEBPACK_IMPORTED_MODULE_1__, _base64_js__WEBPACK_IMPORTED_MODULE_2__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__, _convert_js__WEBPACK_IMPORTED_MODULE_7__, _deriveNetwork_js__WEBPACK_IMPORTED_MODULE_9__, _derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_10__, _deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_11__, _util_getAddrsByXpubKey_js__WEBPACK_IMPORTED_MODULE_12__, _getUsdRate_js__WEBPACK_IMPORTED_MODULE_14__, _hash160_js__WEBPACK_IMPORTED_MODULE_15__, _rate_ExchangeRate_js__WEBPACK_IMPORTED_MODULE_16__, _sanitizeAddress_js__WEBPACK_IMPORTED_MODULE_17__, _util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_20__, _balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_22__, _header_js__WEBPACK_IMPORTED_MODULE_23__]);\n([_amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_0__, _asSendRequestObject_js__WEBPACK_IMPORTED_MODULE_1__, _base64_js__WEBPACK_IMPORTED_MODULE_2__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__, _convert_js__WEBPACK_IMPORTED_MODULE_7__, _deriveNetwork_js__WEBPACK_IMPORTED_MODULE_9__, _derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_10__, _deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_11__, _util_getAddrsByXpubKey_js__WEBPACK_IMPORTED_MODULE_12__, _getUsdRate_js__WEBPACK_IMPORTED_MODULE_14__, _hash160_js__WEBPACK_IMPORTED_MODULE_15__, _rate_ExchangeRate_js__WEBPACK_IMPORTED_MODULE_16__, _sanitizeAddress_js__WEBPACK_IMPORTED_MODULE_17__, _util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_20__, _balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_22__, _header_js__WEBPACK_IMPORTED_MODULE_23__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/util/index.ts?");
|
|
548
548
|
|
|
549
549
|
/***/ }),
|
|
550
550
|
|
|
@@ -594,7 +594,7 @@ eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harm
|
|
|
594
594
|
\*************************************/
|
|
595
595
|
/***/ ((module, __webpack_exports__, __webpack_require__) => {
|
|
596
596
|
|
|
597
|
-
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 */ \"satoshiToAmount\": () => (/* binding */ satoshiToAmount)\n/* harmony export */ });\n/* harmony import */ var _chain_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../chain.js */ \"./src/chain.ts\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../enum.js */ \"./src/enum.ts\");\n/* harmony import */ var _rate_ExchangeRate_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../rate/ExchangeRate.js */ \"./src/rate/ExchangeRate.ts\");\n/* harmony import */ var _util_sanitizeUnit_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/sanitizeUnit.js */ \"./src/util/sanitizeUnit.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_enum_js__WEBPACK_IMPORTED_MODULE_2__]);\
|
|
597
|
+
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 */ \"satoshiToAmount\": () => (/* binding */ satoshiToAmount)\n/* harmony export */ });\n/* harmony import */ var _chain_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../chain.js */ \"./src/chain.ts\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../enum.js */ \"./src/enum.ts\");\n/* harmony import */ var _rate_ExchangeRate_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../rate/ExchangeRate.js */ \"./src/rate/ExchangeRate.ts\");\n/* harmony import */ var _util_sanitizeUnit_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/sanitizeUnit.js */ \"./src/util/sanitizeUnit.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_rate_ExchangeRate_js__WEBPACK_IMPORTED_MODULE_0__, _enum_js__WEBPACK_IMPORTED_MODULE_2__]);\n([_rate_ExchangeRate_js__WEBPACK_IMPORTED_MODULE_0__, _enum_js__WEBPACK_IMPORTED_MODULE_2__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\n\n\n/**\n * converts given value and unit from satoshi\n *\n * @param {value} number some value in satoshi\n * @param {rawUnit} any the target unit\n *\n * @returns a promise to the value in the unit of account given by rawUnit\n */\nasync function satoshiToAmount(value, rawUnit) {\n const unit = (0,_util_sanitizeUnit_js__WEBPACK_IMPORTED_MODULE_1__.sanitizeUnit)(rawUnit);\n switch (unit) {\n case _enum_js__WEBPACK_IMPORTED_MODULE_2__.UnitEnum.BCH:\n return value / _chain_js__WEBPACK_IMPORTED_MODULE_3__.bchParam.subUnits;\n case _enum_js__WEBPACK_IMPORTED_MODULE_2__.UnitEnum.SATOSHI:\n return value;\n case _enum_js__WEBPACK_IMPORTED_MODULE_2__.UnitEnum.SAT:\n return value;\n case _enum_js__WEBPACK_IMPORTED_MODULE_2__.UnitEnum.SATS:\n return value;\n case _enum_js__WEBPACK_IMPORTED_MODULE_2__.UnitEnum.SATOSHIS:\n return value;\n default:\n const Currency_over_BCH = await _rate_ExchangeRate_js__WEBPACK_IMPORTED_MODULE_0__.ExchangeRate.get(rawUnit);\n // truncate currency amounts to fixed precision (2),\n // then return the fixed value string as a float.\n const currencyValue = Number(value * (Currency_over_BCH / _chain_js__WEBPACK_IMPORTED_MODULE_3__.bchParam.subUnits)).toFixed(2);\n return Number.parseFloat(currencyValue);\n }\n}\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/util/satoshiToAmount.ts?");
|
|
598
598
|
|
|
599
599
|
/***/ }),
|
|
600
600
|
|
|
@@ -634,7 +634,7 @@ eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__
|
|
|
634
634
|
\****************************/
|
|
635
635
|
/***/ ((module, __webpack_exports__, __webpack_require__) => {
|
|
636
636
|
|
|
637
|
-
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 */ \"BaseWallet\": () => (/* binding */ BaseWallet),\n/* harmony export */ \"RegTestWatchWallet\": () => (/* binding */ RegTestWatchWallet),\n/* harmony export */ \"TestNetWatchWallet\": () => (/* binding */ TestNetWatchWallet),\n/* harmony export */ \"WatchWallet\": () => (/* binding */ WatchWallet),\n/* harmony export */ \"getNamedWalletId\": () => (/* binding */ getNamedWalletId)\n/* harmony export */ });\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../util/index.js */ \"./node_modules/@bitauth/libauth/build/lib/format/hex.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @bitauth/libauth */ \"./node_modules/@bitauth/libauth/build/lib/address/cash-address.js\");\n/* harmony import */ var _constant_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../constant.js */ \"./src/constant.ts\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../enum.js */ \"./src/enum.ts\");\n/* harmony import */ var _history_electrumTransformer_js__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ../history/electrumTransformer.js */ \"./src/history/electrumTransformer.ts\");\n/* harmony import */ var _interface_js__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ../interface.js */ \"./src/interface.ts\");\n/* harmony import */ var _message_signed_js__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ../message/signed.js */ \"./src/message/signed.ts\");\n/* harmony import */ var _network_default_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../network/default.js */ \"./src/network/default.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 _transaction_Wif_js__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../transaction/Wif.js */ \"./src/transaction/Wif.ts\");\n/* harmony import */ var _util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../util/balanceObjectFromSatoshi.js */ \"./src/util/balanceObjectFromSatoshi.ts\");\n/* harmony import */ var _util_checkUtxos_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../util/checkUtxos.js */ \"./src/util/checkUtxos.ts\");\n/* harmony import */ var _util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../util/derivePublicKeyHash.js */ \"./src/util/derivePublicKeyHash.ts\");\n/* harmony import */ var _util_index_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../util/index.js */ \"./src/util/deriveCashaddr.ts\");\n/* harmony import */ var _util_index_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../util/index.js */ \"./src/util/sumUtxoValue.ts\");\n/* harmony import */ var _util_index_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../util/index.js */ \"./src/util/amountInSatoshi.ts\");\n/* harmony import */ var _util_index_js__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ../util/index.js */ \"./src/util/asSendRequestObject.ts\");\n/* harmony import */ var _util_index_js__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ../util/index.js */ \"./src/util/getRuntimePlatform.ts\");\n/* harmony import */ var _util_sanitizeUnit_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../util/sanitizeUnit.js */ \"./src/util/sanitizeUnit.ts\");\n/* harmony import */ var _util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ../util/sumSendRequestAmounts.js */ \"./src/util/sumSendRequestAmounts.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_15__ = __webpack_require__(/*! ./model.js */ \"./src/wallet/model.ts\");\n/* harmony import */ var _Util_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Util.js */ \"./src/wallet/Util.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_network_default_js__WEBPACK_IMPORTED_MODULE_0__, _enum_js__WEBPACK_IMPORTED_MODULE_2__, _Util_js__WEBPACK_IMPORTED_MODULE_3__, _util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_6__, _util_index_js__WEBPACK_IMPORTED_MODULE_8__, _util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_10__, _util_index_js__WEBPACK_IMPORTED_MODULE_13__, _model_js__WEBPACK_IMPORTED_MODULE_15__, _transaction_Wif_js__WEBPACK_IMPORTED_MODULE_16__, _util_index_js__WEBPACK_IMPORTED_MODULE_17__, _util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_18__, _history_electrumTransformer_js__WEBPACK_IMPORTED_MODULE_19__, _message_signed_js__WEBPACK_IMPORTED_MODULE_20__]);\n([_network_default_js__WEBPACK_IMPORTED_MODULE_0__, _enum_js__WEBPACK_IMPORTED_MODULE_2__, _Util_js__WEBPACK_IMPORTED_MODULE_3__, _util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_6__, _util_index_js__WEBPACK_IMPORTED_MODULE_8__, _util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_10__, _util_index_js__WEBPACK_IMPORTED_MODULE_13__, _model_js__WEBPACK_IMPORTED_MODULE_15__, _transaction_Wif_js__WEBPACK_IMPORTED_MODULE_16__, _util_index_js__WEBPACK_IMPORTED_MODULE_17__, _util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_18__, _history_electrumTransformer_js__WEBPACK_IMPORTED_MODULE_19__, _message_signed_js__WEBPACK_IMPORTED_MODULE_20__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nconst placeholderPrivateKey = \"0000000000000000000000000000000000000000000000000000000000000001\";\n/**\n * A class to hold features used by all wallets\n * @class BaseWallet\n */\nclass BaseWallet {\n get networkPrefix() {\n return _enum_js__WEBPACK_IMPORTED_MODULE_2__.prefixFromNetworkMap[this.network];\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_3__.Util(this.network);\n }\n return this._util;\n }\n // interface to util util. see Util.Util\n static get util() {\n return new this().util;\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 publicKeyHash: (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__.binToHex)(this.publicKeyHash),\n walletId: this.toString(),\n walletDbEntry: this.toDbString(),\n };\n }\n slpSemiAware(value = true) {\n this._slpSemiAware = value;\n return this;\n }\n //#region Accessors\n getNetworkProvider(\n // @ts-ignore\n network = _enum_js__WEBPACK_IMPORTED_MODULE_2__.NetworkType.Mainnet) {\n return (0,_network_default_js__WEBPACK_IMPORTED_MODULE_0__.getNetworkProvider)(network);\n }\n /**\n * getDepositAddress - get a wallet deposit address\n *\n * a high-level function,\n *\n * @see {@link https://rest-unstable.mainnet.cash/api-docs/#/wallet/depositAddress|/wallet/deposit_address} for REST endpoint\n *\n * @returns The deposit address as a string\n */\n getDepositAddress() {\n return this.cashaddr;\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 //#endregion Accessors\n //#region Constructors and Statics\n /**\n * constructor for a new wallet\n * @param network network for wallet\n *\n * @throws {Error} if called on BaseWallet\n */\n constructor(network = _enum_js__WEBPACK_IMPORTED_MODULE_2__.NetworkType.Mainnet) {\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.name = \"\";\n this.network = network;\n this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Watch;\n this.provider = this.getNetworkProvider(this.network);\n this.isTestnet = this.network === _enum_js__WEBPACK_IMPORTED_MODULE_2__.NetworkType.Mainnet ? false : true;\n }\n /**\n * watchOnly - create a watch-only wallet\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, token aware cashaddress of a wallet\n *\n * @returns instantiated wallet\n */\n static async watchOnly(address) {\n return new this().watchOnly(address);\n }\n //#endregion Constructors\n /**\n * named (internal) get a named wallet from the database or create a new one.\n * Note: this function should behave identically if\n *\n * @param {string} name name of the wallet\n * @param {string} dbName database name the wallet is stored in\n * @param {boolean} forceNew attempt to overwrite an existing wallet\n *\n * @throws {Error} if forceNew is true and the wallet already exists\n * @returns a promise to a named wallet\n */\n async named(name, dbName, forceNew = false) {\n if (name.length === 0) {\n throw Error(\"Named wallets must have a non-empty name\");\n }\n _checkContextSafety(this);\n this.name = name;\n dbName = dbName ? dbName : _enum_js__WEBPACK_IMPORTED_MODULE_2__.prefixFromNetworkMap[this.network];\n const db = getStorageProvider(dbName);\n // If there is a database, force saving or error\n if (db) {\n await db.init();\n const savedWalletRecord = await db.getWallet(name);\n if (savedWalletRecord) {\n await db.close();\n if (forceNew) {\n throw Error(`A wallet with the name ${name} already exists in ${dbName}`);\n }\n const recoveredWallet = await this.fromId(savedWalletRecord.wallet);\n recoveredWallet.name = savedWalletRecord.name;\n return recoveredWallet;\n }\n else {\n const wallet = await this.generate();\n await db.addWallet(wallet.name, wallet.toDbString());\n await db.close();\n return wallet;\n }\n }\n else {\n throw Error(\"No database was available or configured to store the named wallet.\");\n }\n }\n /**\n * replaceNamed - Replace (recover) named wallet with a new walletId\n *\n * If wallet with a provided name does not exist yet, it will be created with a `walletId` supplied\n * If wallet exists it will be overwritten without exception\n *\n * @param name user friendly wallet alias\n * @param walletId walletId options to steer the creation process\n * @param dbName name under which the wallet will be stored in the database\n *\n * @returns instantiated wallet\n */\n async replaceNamed(name, walletId, dbName) {\n if (name.length === 0) {\n throw Error(\"Named wallets must have a non-empty name\");\n }\n _checkContextSafety(this);\n this.name = name;\n dbName = dbName ? dbName : _enum_js__WEBPACK_IMPORTED_MODULE_2__.prefixFromNetworkMap[this.network];\n let db = getStorageProvider(dbName);\n if (db) {\n await db.init();\n let savedWalletRecord = await db.getWallet(name);\n await this.fromId(walletId);\n if (savedWalletRecord) {\n await db.updateWallet(name, walletId);\n }\n else {\n await db.addWallet(name, walletId);\n }\n await db.close();\n return this;\n }\n else {\n throw Error(\"No database was available or configured to store the named wallet.\");\n }\n }\n /**\n * namedExists - check if a named wallet already exists\n *\n * @param name user friendly wallet alias\n * @param dbName name under which the wallet will be stored in the database\n *\n * @returns boolean\n */\n async namedExists(name, dbName) {\n if (name.length === 0) {\n throw Error(\"Named wallets must have a non-empty name\");\n }\n _checkContextSafety(this);\n dbName = dbName ? dbName : _enum_js__WEBPACK_IMPORTED_MODULE_2__.prefixFromNetworkMap[this.network];\n let db = getStorageProvider(dbName);\n if (db) {\n await db.init();\n let savedWalletRecord = await db.getWallet(name);\n await db.close();\n return savedWalletRecord !== undefined;\n }\n else {\n throw Error(\"No database was available or configured to store the named wallet.\");\n }\n }\n async generate() {\n return this;\n }\n //#region Serialization\n /**\n * toDbString - store the serialized version of the wallet in the database, not just the name\n *\n * @throws {Error} if called on BaseWallet\n */\n toDbString() {\n return `${this.walletType}:${this.network}:${this.getDepositAddress()}`;\n }\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 return `${this.walletType}:${this.network}:${this.getDepositAddress()}`;\n }\n //#endregion Serialization\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 // 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_4__.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 * 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_6__.derivePrefix)(address);\n const networkType = _enum_js__WEBPACK_IMPORTED_MODULE_2__.networkPrefixMap[prefix];\n return new this(networkType).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_6__.derivePrefix)(address);\n const networkType = _enum_js__WEBPACK_IMPORTED_MODULE_2__.networkPrefixMap[prefix];\n return new this(networkType).watchOnly(address);\n }\n /**\n * named - create a named wallet\n *\n * @param name user friendly wallet alias\n * @param dbName name under which the wallet will be stored in the database\n * @param force force recreate wallet in the database if a record already exist\n *\n * @returns instantiated wallet\n */\n static async named(name, dbName, force) {\n return new this().named(name, dbName, force);\n }\n /**\n * replaceNamed - replace (recover) named wallet with a new walletId\n *\n * If wallet with a provided name does not exist yet, it will be created with a `walletId` supplied\n * If wallet exists it will be overwritten without exception\n *\n * @param name user friendly wallet alias\n * @param walletId walletId options to steer the creation process\n * @param dbName name under which the wallet will be stored in the database\n *\n * @returns instantiated wallet\n */\n static async replaceNamed(name, walletId, dbName) {\n return new this().replaceNamed(name, walletId, dbName);\n }\n /**\n * namedExists - check if a named wallet already exists\n *\n * @param name user friendly wallet alias\n * @param dbName name under which the wallet will be stored in the database\n *\n * @returns boolean\n */\n static async namedExists(name, dbName) {\n return new this().namedExists(name, dbName);\n }\n fromId(walletId) {\n const [walletType, networkGiven, arg1, arg2] = walletId.split(\":\");\n if (walletType !== _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Watch) {\n throw Error(`fromId called on a ${walletType} wallet, expected a ${_enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Watch} wallet`);\n }\n if (this.network != networkGiven) {\n throw Error(`Network prefix ${networkGiven} to a ${this.network} wallet`);\n }\n if (arg2) {\n return this.watchOnly(`${arg1}:${arg2}`);\n }\n return this.watchOnly(arg1);\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 const addressComponents = address.split(\":\");\n let addressPrefix;\n let addressBase;\n if (addressComponents.length === 1) {\n addressBase = addressComponents.shift();\n addressPrefix = (0,_util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_6__.derivePrefix)(addressBase);\n }\n else {\n addressPrefix = addressComponents.shift();\n addressBase = addressComponents.shift();\n if (addressPrefix in _enum_js__WEBPACK_IMPORTED_MODULE_2__.networkPrefixMap) {\n if (_enum_js__WEBPACK_IMPORTED_MODULE_2__.networkPrefixMap[addressPrefix] !== this.network) {\n throw Error(`a ${addressPrefix} address cannot be watched from a ${this.network} Wallet`);\n }\n }\n }\n const prefixedAddress = `${addressPrefix}:${addressBase}`;\n // check if a token aware address was provided\n const addressData = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__.decodeCashAddress)(prefixedAddress);\n if (typeof addressData === \"string\")\n throw addressData;\n this.publicKeyHash = addressData.payload;\n let nonTokenAwareType = addressData.type;\n if (nonTokenAwareType == _bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__.CashAddressType.p2pkhWithTokens)\n nonTokenAwareType = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__.CashAddressType.p2pkh;\n if (nonTokenAwareType == _bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__.CashAddressType.p2shWithTokens)\n nonTokenAwareType = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__.CashAddressType.p2sh;\n if (nonTokenAwareType == _bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__.CashAddressType.p2pkh)\n this.publicKeyHash = addressData.payload;\n this.cashaddr = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__.encodeCashAddress)({\n prefix: addressData.prefix,\n type: nonTokenAwareType,\n payload: addressData.payload,\n }).address;\n this.tokenaddr = (0,_util_index_js__WEBPACK_IMPORTED_MODULE_8__.deriveTokenaddr)(addressData.payload, this.networkPrefix);\n return this;\n }\n //#region Funds\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 currency\n async getBalance(rawUnit, priceCache = true) {\n if (rawUnit) {\n const unit = (0,_util_sanitizeUnit_js__WEBPACK_IMPORTED_MODULE_9__.sanitizeUnit)(rawUnit);\n return await (0,_util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_10__.balanceFromSatoshi)(await this.getBalanceFromProvider(), unit, priceCache);\n }\n else {\n return await (0,_util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_10__.balanceResponseFromSatoshi)(await this.getBalanceFromProvider(), priceCache);\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_index_js__WEBPACK_IMPORTED_MODULE_11__.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 async getAddressUtxos(address) {\n if (!address) {\n address = this.cashaddr;\n }\n if (this._slpSemiAware) {\n const bchUtxos = await this.provider.getUtxos(address);\n return bchUtxos.filter((bchutxo) => bchutxo.satoshis > _constant_js__WEBPACK_IMPORTED_MODULE_12__.DUST_UTXO_THRESHOLD);\n }\n else {\n return await this.provider.getUtxos(address);\n }\n }\n // watching for any transaction hash of this wallet\n async watchAddress(callback) {\n return this.provider.watchAddress(this.getDepositAddress(), callback);\n }\n // watching for any transaction of this wallet\n async watchAddressTransactions(callback) {\n return this.provider.watchAddressTransactions(this.getDepositAddress(), callback);\n }\n // watching for cashtoken transaction of this wallet\n async 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 async 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 async 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 = await 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_2__.UnitEnum.BCH) {\n return new Promise(async (resolve) => {\n let watchCancel;\n watchCancel = await this.watchBalance(async (balance) => {\n const satoshiBalance = await (0,_util_index_js__WEBPACK_IMPORTED_MODULE_13__.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 async watchTokenBalance(tokenId, callback) {\n let previous = undefined;\n return await 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 let watchCancel;\n watchCancel = await this.watchTokenBalance(tokenId, async (balance) => {\n if (balance >= amount) {\n await watchCancel?.();\n resolve(balance);\n }\n });\n });\n }\n async _getMaxAmountToSend(params = {\n outputCount: 1,\n options: {},\n }) {\n if (!params.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.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 = await (0,_util_checkUtxos_js__WEBPACK_IMPORTED_MODULE_14__.checkUtxos)(params.options.utxoIds.map((utxoId) => typeof utxoId === \"string\" ? (0,_model_js__WEBPACK_IMPORTED_MODULE_15__.fromUtxoId)(utxoId) : utxoId), this);\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_15__.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_16__.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_16__.getFeeAmountSimple)({\n utxos: fundingUtxos,\n sendRequests: sendRequests,\n privateKey: params.privateKey ?? (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__.hexToBin)(placeholderPrivateKey),\n sourceAddress: this.cashaddr,\n relayFeePerByteInSatoshi: relayFeePerByteInSatoshi,\n feePaidBy: feePaidBy,\n });\n const spendableAmount = (0,_util_index_js__WEBPACK_IMPORTED_MODULE_11__.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_10__.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_15__.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_4__.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, privateKey) {\n const { value: maxSpendableAmount, utxos } = await this._getMaxAmountToSend({\n outputCount: 1,\n options: options,\n privateKey: privateKey,\n });\n if (!options) {\n options = {};\n }\n options.utxoIds = utxos;\n const sendRequest = new _model_js__WEBPACK_IMPORTED_MODULE_15__.SendRequest({\n cashaddr: cashaddr,\n value: maxSpendableAmount,\n unit: \"sat\",\n });\n const { encodedTransaction, tokenIds, sourceOutputs } = await this.encodeTransaction([sendRequest], true, options, privateKey);\n const resp = new _model_js__WEBPACK_IMPORTED_MODULE_15__.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_4__.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, privateKey) {\n let sendRequests = (0,_util_index_js__WEBPACK_IMPORTED_MODULE_17__.asSendRequestObject)(requests);\n if (!privateKey && options?.buildUnsigned !== true) {\n throw new Error(`Missing private key`);\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 = await (0,_util_checkUtxos_js__WEBPACK_IMPORTED_MODULE_14__.checkUtxos)(options.utxoIds.map((utxoId) => typeof utxoId === \"string\" ? (0,_model_js__WEBPACK_IMPORTED_MODULE_15__.fromUtxoId)(utxoId) : utxoId), this);\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_15__.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_15__.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, 0n);\n const tokenOutputs = allTokenOutputs.filter((val) => val.tokenId === tokenId);\n const outputAmountSum = tokenOutputs.reduce((prev, cur) => prev + cur.amount, 0n);\n const diff = inputAmountSum - outputAmountSum;\n if (diff < 0) {\n throw new Error(\"Not enough token amount to send\");\n }\n if (diff >= 0) {\n let available = 0n;\n let change = 0n;\n const ensureUtxos = [];\n for (const token of tokenInputs.filter((val) => val.token?.amount)) {\n ensureUtxos.push(token);\n available += token.token.amount;\n if (available >= outputAmountSum) {\n change = available - outputAmountSum;\n //break;\n }\n }\n if (ensureUtxos.length) {\n if (!options) {\n options = {};\n }\n options.ensureUtxos = [\n ...(options.ensureUtxos ?? []),\n ...ensureUtxos,\n ].filter((val, index, array) => array.findIndex((other) => other.txid === val.txid && other.vout === val.vout) === index);\n }\n if (change > 0) {\n outputs.push(new _model_js__WEBPACK_IMPORTED_MODULE_15__.TokenSendRequest({\n cashaddr: (0,_util_index_js__WEBPACK_IMPORTED_MODULE_8__.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 };\n addTokenChangeOutputs(utxos, sendRequests);\n const bestHeight = await this.provider.getBlockHeight();\n const spendAmount = await (0,_util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_18__.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_16__.getFeeAmountSimple)({\n utxos: utxos,\n sendRequests: sendRequests,\n privateKey: privateKey ?? (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__.hexToBin)(placeholderPrivateKey),\n sourceAddress: this.cashaddr,\n relayFeePerByteInSatoshi: relayFeePerByteInSatoshi,\n feePaidBy: feePaidBy,\n });\n const fundingUtxos = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_16__.getSuitableUtxos)(utxos, BigInt(spendAmount) + BigInt(Math.ceil(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_16__.getFeeAmount)({\n utxos: fundingUtxos,\n sendRequests: sendRequests,\n privateKey: privateKey ?? (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__.hexToBin)(placeholderPrivateKey),\n sourceAddress: this.cashaddr,\n relayFeePerByteInSatoshi: relayFeePerByteInSatoshi,\n feePaidBy: feePaidBy,\n });\n const { encodedTransaction, sourceOutputs } = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_16__.buildEncodedTransaction)({\n inputs: fundingUtxos,\n outputs: sendRequests,\n signingKey: privateKey ?? (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__.hexToBin)(placeholderPrivateKey),\n sourceAddress: this.cashaddr,\n fee,\n discardChange,\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_15__.TokenSendRequest)\n .map((val) => val.tokenId),\n ].filter((value, index, array) => array.indexOf(value) === index);\n return { encodedTransaction, tokenIds, sourceOutputs };\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_4__.binToHex)(transaction);\n return await this.provider.sendRawTransaction(rawTransaction, awaitPropagation);\n }\n // gets transaction history of this wallet\n async getRawHistory(fromHeight = 0, toHeight = -1) {\n return await this.provider.getHistory(this.cashaddr, fromHeight, toHeight);\n }\n /**\n * getHistory gets transaction history of this wallet with most data decoded and ready to present to user\n * @note balance calculations are valid only if querying to the blockchain tip (`toHeight` === -1, `count` === -1)\n * @note this method is heavy on network calls, if invoked in browser use of cache is advised, @see `Config.UseLocalStorageCache`\n * @note this method tries to recreate the history tab view of Electron Cash wallet, however, it may not be 100% accurate if the tnransaction value changes are the same in the same block (ordering)\n *\n * @param unit optional, BCH or currency unit to present balance and balance changes. If unit is currency like USD or EUR, balances will be subject to possible rounding errors. Default 0\n * @param fromHeight optional, if set, history will be limited. Default 0\n * @param toHeight optional, if set, history will be limited. Default -1, meaning that all history items will be returned, including mempool\n * @param start optional, if set, the result set will be paginated with offset `start`\n * @param count optional, if set, the result set will be paginated with `count`. Default -1, meaning that all history items will be returned\n *\n * @returns an array of transaction history items, with input values and addresses encoded in cashaddress format. @see `TransactionHistoryItem` type\n */\n async getHistory({ unit = \"sat\", fromHeight = 0, toHeight = -1, start = 0, count = -1, }) {\n return (0,_history_electrumTransformer_js__WEBPACK_IMPORTED_MODULE_19__.getAddressHistory)({\n address: this.cashaddr,\n provider: this.provider,\n unit,\n fromHeight,\n toHeight,\n start,\n count,\n });\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 let cancel;\n const waitForTransactionCallback = async (data) => {\n if (data && data[0] === options.txHash && data[1] !== null) {\n txHashSeen = true;\n await cancel?.();\n resolve(makeResponse(options.txHash));\n }\n };\n cancel = await this.provider.subscribeToTransaction(options.txHash, waitForTransactionCallback);\n return;\n }\n // waiting for any address transaction\n let watchCancel;\n let initialResponseSeen = false;\n watchCancel = await this.provider.watchAddressStatus(this.getDepositAddress(), async (_status) => {\n if (initialResponseSeen) {\n await watchCancel?.();\n resolve(makeResponse());\n return;\n }\n initialResponseSeen = true;\n });\n });\n }\n /**\n * watchBlocks Watch network blocks\n *\n * @param callback callback with a block header object\n * @param skipCurrentHeight if set, the notification about current block will not arrive\n *\n * @returns a function which will cancel watching upon evaluation\n */\n async watchBlocks(callback, skipCurrentHeight = true) {\n return this.provider.watchBlocks(callback, skipCurrentHeight);\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 // Convenience wrapper to verify interface\n async verify(message, sig, publicKey) {\n return await new _message_signed_js__WEBPACK_IMPORTED_MODULE_20__.SignedMessage().verify(message, sig, this.cashaddr, publicKey);\n }\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 = await (0,_util_checkUtxos_js__WEBPACK_IMPORTED_MODULE_14__.checkUtxos)(options.utxoIds.map((utxoId) => typeof utxoId === \"string\" ? (0,_model_js__WEBPACK_IMPORTED_MODULE_15__.fromUtxoId)(utxoId) : utxoId), this);\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_15__.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_21__.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 - BigInt(mintRequests.length)\n : nftUtxos[0].token.amount;\n const safeNewAmount = newAmount < 0n ? 0n : newAmount;\n const mintingInput = new _model_js__WEBPACK_IMPORTED_MODULE_15__.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_15__.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 || 0n), 0n);\n let fungibleBurnAmount = burnRequest.amount && burnRequest.amount > 0 ? burnRequest.amount : 0n;\n fungibleBurnAmount = BigInt(fungibleBurnAmount);\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 === 0n) {\n changeSendRequests = [];\n utxoIds.push(tokenUtxos[0]);\n }\n else {\n // add utxos to spend from\n let available = 0n;\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 = newAmount < 0n ? 0n : newAmount;\n changeSendRequests = [\n new _model_js__WEBPACK_IMPORTED_MODULE_15__.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 fungible tokens, let us destroy the token completely\n if (totalFungibleAmount === fungibleBurnAmount) {\n changeSendRequests = [];\n utxoIds.push(...tokenUtxos);\n }\n else {\n // add utxos to spend from\n let available = 0n;\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 = available - fungibleBurnAmount;\n const safeNewAmount = newAmount < 0n ? 0n : newAmount;\n changeSendRequests = [\n new _model_js__WEBPACK_IMPORTED_MODULE_15__.TokenSendRequest({\n cashaddr: burnRequest.cashaddr || this.tokenaddr,\n tokenId: burnRequest.tokenId,\n amount: safeNewAmount,\n value: tokenUtxos.reduce((a, c) => a + c.satoshis, 0),\n }),\n ];\n }\n }\n const opReturn = _model_js__WEBPACK_IMPORTED_MODULE_15__.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.cashaddr);\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 {bigint} fungible token balance\n */\n async getTokenBalance(tokenId) {\n const utxos = (await this.getTokenUtxos(tokenId)).filter((val) => val.token?.amount);\n return (0,_util_index_js__WEBPACK_IMPORTED_MODULE_11__.sumTokenAmounts)(utxos, tokenId);\n }\n /**\n * getNftTokenBalance Gets non-fungible token (NFT) balance for a particular 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] = 0n;\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}\n/**\n * Class to manage a mainnet watch wallet.\n */\nclass WatchWallet extends BaseWallet {\n static { this.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__.CashAddressNetworkPrefix.mainnet; }\n static { this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Watch; }\n constructor() {\n super(_enum_js__WEBPACK_IMPORTED_MODULE_2__.NetworkType.Mainnet);\n }\n}\n/**\n * Class to manage a testnet watch wallet.\n */\nclass TestNetWatchWallet extends BaseWallet {\n static { this.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__.CashAddressNetworkPrefix.testnet; }\n static { this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Watch; }\n constructor() {\n super(_enum_js__WEBPACK_IMPORTED_MODULE_2__.NetworkType.Testnet);\n }\n}\n/**\n * Class to manage a regtest watch wallet.\n */\nclass RegTestWatchWallet extends BaseWallet {\n static { this.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__.CashAddressNetworkPrefix.regtest; }\n static { this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Watch; }\n constructor() {\n super(_enum_js__WEBPACK_IMPORTED_MODULE_2__.NetworkType.Regtest);\n }\n}\n/**\n * _checkContextSafety (internal) if running in nodejs, will disable saving\n * mainnet wallets on public servers if ALLOW_MAINNET_USER_WALLETS is set to false\n * @param {BaseWallet} wallet a wallet\n */\nconst _checkContextSafety = function (wallet) {\n if ((0,_util_index_js__WEBPACK_IMPORTED_MODULE_22__.getRuntimePlatform)() === \"node\") {\n if (process.env.ALLOW_MAINNET_USER_WALLETS === `false`) {\n if (wallet.network === _enum_js__WEBPACK_IMPORTED_MODULE_2__.NetworkType.Mainnet) {\n throw Error(`Refusing to save wallet in an open public database, remove ALLOW_MAINNET_USER_WALLETS=\"false\", if this service is secure and private`);\n }\n }\n }\n};\n/**\n * getNamedWalletId - get the full wallet id from the database\n *\n * @param name user friendly wallet alias\n * @param dbName name under which the wallet will be stored in the database\n *\n * @returns boolean\n */\nasync function getNamedWalletId(name, dbName) {\n if (name.length === 0) {\n throw Error(\"Named wallets must have a non-empty name\");\n }\n dbName = dbName ? dbName : dbName;\n let db = getStorageProvider(dbName);\n if (db) {\n await db.init();\n let savedWalletRecord = await db.getWallet(name);\n await db.close();\n if (savedWalletRecord !== undefined) {\n return savedWalletRecord.wallet;\n }\n else {\n throw Error(`No record was found for ${name} in db: ${dbName}`);\n }\n }\n else {\n throw Error(\"No database was available or configured to store the named wallet.\");\n }\n}\nfunction getStorageProvider(dbName) {\n if (!BaseWallet.StorageProvider) {\n return undefined;\n }\n return new BaseWallet.StorageProvider(dbName);\n}\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/wallet/Base.ts?");
|
|
637
|
+
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 */ \"BaseWallet\": () => (/* binding */ BaseWallet),\n/* harmony export */ \"RegTestWatchWallet\": () => (/* binding */ RegTestWatchWallet),\n/* harmony export */ \"TestNetWatchWallet\": () => (/* binding */ TestNetWatchWallet),\n/* harmony export */ \"WatchWallet\": () => (/* binding */ WatchWallet),\n/* harmony export */ \"getNamedWalletId\": () => (/* binding */ getNamedWalletId)\n/* harmony export */ });\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../util/index.js */ \"./node_modules/@bitauth/libauth/build/lib/format/hex.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @bitauth/libauth */ \"./node_modules/@bitauth/libauth/build/lib/address/cash-address.js\");\n/* harmony import */ var _constant_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../constant.js */ \"./src/constant.ts\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../enum.js */ \"./src/enum.ts\");\n/* harmony import */ var _history_electrumTransformer_js__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ../history/electrumTransformer.js */ \"./src/history/electrumTransformer.ts\");\n/* harmony import */ var _interface_js__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ../interface.js */ \"./src/interface.ts\");\n/* harmony import */ var _message_signed_js__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ../message/signed.js */ \"./src/message/signed.ts\");\n/* harmony import */ var _network_default_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../network/default.js */ \"./src/network/default.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 _transaction_Wif_js__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../transaction/Wif.js */ \"./src/transaction/Wif.ts\");\n/* harmony import */ var _util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../util/balanceObjectFromSatoshi.js */ \"./src/util/balanceObjectFromSatoshi.ts\");\n/* harmony import */ var _util_checkUtxos_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../util/checkUtxos.js */ \"./src/util/checkUtxos.ts\");\n/* harmony import */ var _util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../util/derivePublicKeyHash.js */ \"./src/util/derivePublicKeyHash.ts\");\n/* harmony import */ var _util_index_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../util/index.js */ \"./src/util/deriveCashaddr.ts\");\n/* harmony import */ var _util_index_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../util/index.js */ \"./src/util/sumUtxoValue.ts\");\n/* harmony import */ var _util_index_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../util/index.js */ \"./src/util/amountInSatoshi.ts\");\n/* harmony import */ var _util_index_js__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ../util/index.js */ \"./src/util/asSendRequestObject.ts\");\n/* harmony import */ var _util_index_js__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ../util/index.js */ \"./src/util/getRuntimePlatform.ts\");\n/* harmony import */ var _util_sanitizeUnit_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../util/sanitizeUnit.js */ \"./src/util/sanitizeUnit.ts\");\n/* harmony import */ var _util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ../util/sumSendRequestAmounts.js */ \"./src/util/sumSendRequestAmounts.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_15__ = __webpack_require__(/*! ./model.js */ \"./src/wallet/model.ts\");\n/* harmony import */ var _Util_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Util.js */ \"./src/wallet/Util.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_network_default_js__WEBPACK_IMPORTED_MODULE_0__, _enum_js__WEBPACK_IMPORTED_MODULE_2__, _Util_js__WEBPACK_IMPORTED_MODULE_3__, _util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_6__, _util_index_js__WEBPACK_IMPORTED_MODULE_8__, _util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_10__, _util_index_js__WEBPACK_IMPORTED_MODULE_13__, _model_js__WEBPACK_IMPORTED_MODULE_15__, _transaction_Wif_js__WEBPACK_IMPORTED_MODULE_16__, _util_index_js__WEBPACK_IMPORTED_MODULE_17__, _util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_18__, _history_electrumTransformer_js__WEBPACK_IMPORTED_MODULE_19__, _message_signed_js__WEBPACK_IMPORTED_MODULE_20__]);\n([_network_default_js__WEBPACK_IMPORTED_MODULE_0__, _enum_js__WEBPACK_IMPORTED_MODULE_2__, _Util_js__WEBPACK_IMPORTED_MODULE_3__, _util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_6__, _util_index_js__WEBPACK_IMPORTED_MODULE_8__, _util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_10__, _util_index_js__WEBPACK_IMPORTED_MODULE_13__, _model_js__WEBPACK_IMPORTED_MODULE_15__, _transaction_Wif_js__WEBPACK_IMPORTED_MODULE_16__, _util_index_js__WEBPACK_IMPORTED_MODULE_17__, _util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_18__, _history_electrumTransformer_js__WEBPACK_IMPORTED_MODULE_19__, _message_signed_js__WEBPACK_IMPORTED_MODULE_20__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nconst placeholderPrivateKey = \"0000000000000000000000000000000000000000000000000000000000000001\";\n/**\n * A class to hold features used by all wallets\n * @class BaseWallet\n */\nclass BaseWallet {\n get networkPrefix() {\n return _enum_js__WEBPACK_IMPORTED_MODULE_2__.prefixFromNetworkMap[this.network];\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_3__.Util(this.network);\n }\n return this._util;\n }\n // interface to util util. see Util.Util\n static get util() {\n return new this().util;\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 publicKeyHash: (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__.binToHex)(this.publicKeyHash),\n walletId: this.toString(),\n walletDbEntry: this.toDbString(),\n };\n }\n slpSemiAware(value = true) {\n this._slpSemiAware = value;\n return this;\n }\n //#region Accessors\n getNetworkProvider(\n // @ts-ignore\n network = _enum_js__WEBPACK_IMPORTED_MODULE_2__.NetworkType.Mainnet) {\n return (0,_network_default_js__WEBPACK_IMPORTED_MODULE_0__.getNetworkProvider)(network);\n }\n /**\n * getDepositAddress - get a wallet deposit address\n *\n * a high-level function,\n *\n * @see {@link https://rest-unstable.mainnet.cash/api-docs/#/wallet/depositAddress|/wallet/deposit_address} for REST endpoint\n *\n * @returns The deposit address as a string\n */\n getDepositAddress() {\n return this.cashaddr;\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 //#endregion Accessors\n //#region Constructors and Statics\n /**\n * constructor for a new wallet\n * @param network network for wallet\n *\n * @throws {Error} if called on BaseWallet\n */\n constructor(network = _enum_js__WEBPACK_IMPORTED_MODULE_2__.NetworkType.Mainnet) {\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.name = \"\";\n this.network = network;\n this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Watch;\n this.provider = this.getNetworkProvider(this.network);\n this.isTestnet = this.network === _enum_js__WEBPACK_IMPORTED_MODULE_2__.NetworkType.Mainnet ? false : true;\n }\n /**\n * watchOnly - create a watch-only wallet\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, token aware cashaddress of a wallet\n *\n * @returns instantiated wallet\n */\n static async watchOnly(address) {\n return new this().watchOnly(address);\n }\n //#endregion Constructors\n /**\n * named (internal) get a named wallet from the database or create a new one.\n * Note: this function should behave identically if\n *\n * @param {string} name name of the wallet\n * @param {string} dbName database name the wallet is stored in\n * @param {boolean} forceNew attempt to overwrite an existing wallet\n *\n * @throws {Error} if forceNew is true and the wallet already exists\n * @returns a promise to a named wallet\n */\n async named(name, dbName, forceNew = false) {\n if (name.length === 0) {\n throw Error(\"Named wallets must have a non-empty name\");\n }\n _checkContextSafety(this);\n this.name = name;\n dbName = dbName ? dbName : _enum_js__WEBPACK_IMPORTED_MODULE_2__.prefixFromNetworkMap[this.network];\n const db = getStorageProvider(dbName);\n // If there is a database, force saving or error\n if (db) {\n await db.init();\n const savedWalletRecord = await db.getWallet(name);\n if (savedWalletRecord) {\n await db.close();\n if (forceNew) {\n throw Error(`A wallet with the name ${name} already exists in ${dbName}`);\n }\n const recoveredWallet = await this.fromId(savedWalletRecord.wallet);\n recoveredWallet.name = savedWalletRecord.name;\n return recoveredWallet;\n }\n else {\n const wallet = await this.generate();\n await db.addWallet(wallet.name, wallet.toDbString());\n await db.close();\n return wallet;\n }\n }\n else {\n throw Error(\"No database was available or configured to store the named wallet.\");\n }\n }\n /**\n * replaceNamed - Replace (recover) named wallet with a new walletId\n *\n * If wallet with a provided name does not exist yet, it will be created with a `walletId` supplied\n * If wallet exists it will be overwritten without exception\n *\n * @param name user friendly wallet alias\n * @param walletId walletId options to steer the creation process\n * @param dbName name under which the wallet will be stored in the database\n *\n * @returns instantiated wallet\n */\n async replaceNamed(name, walletId, dbName) {\n if (name.length === 0) {\n throw Error(\"Named wallets must have a non-empty name\");\n }\n _checkContextSafety(this);\n this.name = name;\n dbName = dbName ? dbName : _enum_js__WEBPACK_IMPORTED_MODULE_2__.prefixFromNetworkMap[this.network];\n let db = getStorageProvider(dbName);\n if (db) {\n await db.init();\n let savedWalletRecord = await db.getWallet(name);\n await this.fromId(walletId);\n if (savedWalletRecord) {\n await db.updateWallet(name, walletId);\n }\n else {\n await db.addWallet(name, walletId);\n }\n await db.close();\n return this;\n }\n else {\n throw Error(\"No database was available or configured to store the named wallet.\");\n }\n }\n /**\n * namedExists - check if a named wallet already exists\n *\n * @param name user friendly wallet alias\n * @param dbName name under which the wallet will be stored in the database\n *\n * @returns boolean\n */\n async namedExists(name, dbName) {\n if (name.length === 0) {\n throw Error(\"Named wallets must have a non-empty name\");\n }\n _checkContextSafety(this);\n dbName = dbName ? dbName : _enum_js__WEBPACK_IMPORTED_MODULE_2__.prefixFromNetworkMap[this.network];\n let db = getStorageProvider(dbName);\n if (db) {\n await db.init();\n let savedWalletRecord = await db.getWallet(name);\n await db.close();\n return savedWalletRecord !== undefined;\n }\n else {\n throw Error(\"No database was available or configured to store the named wallet.\");\n }\n }\n async generate() {\n return this;\n }\n //#region Serialization\n /**\n * toDbString - store the serialized version of the wallet in the database, not just the name\n *\n * @throws {Error} if called on BaseWallet\n */\n toDbString() {\n return `${this.walletType}:${this.network}:${this.getDepositAddress()}`;\n }\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 return `${this.walletType}:${this.network}:${this.getDepositAddress()}`;\n }\n //#endregion Serialization\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 // 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_4__.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 * 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_6__.derivePrefix)(address);\n const networkType = _enum_js__WEBPACK_IMPORTED_MODULE_2__.networkPrefixMap[prefix];\n return new this(networkType).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_6__.derivePrefix)(address);\n const networkType = _enum_js__WEBPACK_IMPORTED_MODULE_2__.networkPrefixMap[prefix];\n return new this(networkType).watchOnly(address);\n }\n /**\n * named - create a named wallet\n *\n * @param name user friendly wallet alias\n * @param dbName name under which the wallet will be stored in the database\n * @param force force recreate wallet in the database if a record already exist\n *\n * @returns instantiated wallet\n */\n static async named(name, dbName, force) {\n return new this().named(name, dbName, force);\n }\n /**\n * replaceNamed - replace (recover) named wallet with a new walletId\n *\n * If wallet with a provided name does not exist yet, it will be created with a `walletId` supplied\n * If wallet exists it will be overwritten without exception\n *\n * @param name user friendly wallet alias\n * @param walletId walletId options to steer the creation process\n * @param dbName name under which the wallet will be stored in the database\n *\n * @returns instantiated wallet\n */\n static async replaceNamed(name, walletId, dbName) {\n return new this().replaceNamed(name, walletId, dbName);\n }\n /**\n * namedExists - check if a named wallet already exists\n *\n * @param name user friendly wallet alias\n * @param dbName name under which the wallet will be stored in the database\n *\n * @returns boolean\n */\n static async namedExists(name, dbName) {\n return new this().namedExists(name, dbName);\n }\n fromId(walletId) {\n const [walletType, networkGiven, arg1, arg2] = walletId.split(\":\");\n if (walletType !== _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Watch) {\n throw Error(`fromId called on a ${walletType} wallet, expected a ${_enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Watch} wallet`);\n }\n if (this.network != networkGiven) {\n throw Error(`Network prefix ${networkGiven} to a ${this.network} wallet`);\n }\n if (arg2) {\n return this.watchOnly(`${arg1}:${arg2}`);\n }\n return this.watchOnly(arg1);\n }\n // Initialize a watch only wallet from a cash addr\n async watchOnly(address) {\n // @ts-ignore\n this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Watch;\n const addressComponents = address.split(\":\");\n let addressPrefix;\n let addressBase;\n if (addressComponents.length === 1) {\n addressBase = addressComponents.shift();\n addressPrefix = (0,_util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_6__.derivePrefix)(addressBase);\n }\n else {\n addressPrefix = addressComponents.shift();\n addressBase = addressComponents.shift();\n if (addressPrefix in _enum_js__WEBPACK_IMPORTED_MODULE_2__.networkPrefixMap) {\n if (_enum_js__WEBPACK_IMPORTED_MODULE_2__.networkPrefixMap[addressPrefix] !== this.network) {\n throw Error(`a ${addressPrefix} address cannot be watched from a ${this.network} Wallet`);\n }\n }\n }\n const prefixedAddress = `${addressPrefix}:${addressBase}`;\n // check if a token aware address was provided\n const addressData = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__.decodeCashAddress)(prefixedAddress);\n if (typeof addressData === \"string\")\n throw addressData;\n // @ts-ignore\n this.publicKeyHash = addressData.payload;\n let nonTokenAwareType = addressData.type;\n if (nonTokenAwareType == _bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__.CashAddressType.p2pkhWithTokens)\n nonTokenAwareType = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__.CashAddressType.p2pkh;\n if (nonTokenAwareType == _bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__.CashAddressType.p2shWithTokens)\n nonTokenAwareType = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__.CashAddressType.p2sh;\n if (nonTokenAwareType == _bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__.CashAddressType.p2pkh)\n // @ts-ignore\n this.publicKeyHash = addressData.payload;\n // @ts-ignore\n this.cashaddr = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__.encodeCashAddress)({\n prefix: addressData.prefix,\n type: nonTokenAwareType,\n payload: addressData.payload,\n }).address;\n // @ts-ignore\n this.tokenaddr = (0,_util_index_js__WEBPACK_IMPORTED_MODULE_8__.deriveTokenaddr)(addressData.payload, this.networkPrefix);\n return this;\n }\n //#region Funds\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 currency\n async getBalance(rawUnit, priceCache = true) {\n if (rawUnit) {\n const unit = (0,_util_sanitizeUnit_js__WEBPACK_IMPORTED_MODULE_9__.sanitizeUnit)(rawUnit);\n return await (0,_util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_10__.balanceFromSatoshi)(await this.getBalanceFromProvider(), unit, priceCache);\n }\n else {\n return await (0,_util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_10__.balanceResponseFromSatoshi)(await this.getBalanceFromProvider(), priceCache);\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_index_js__WEBPACK_IMPORTED_MODULE_11__.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 async getAddressUtxos(address) {\n if (!address) {\n address = this.cashaddr;\n }\n if (this._slpSemiAware) {\n const bchUtxos = await this.provider.getUtxos(address);\n return bchUtxos.filter((bchutxo) => bchutxo.satoshis > _constant_js__WEBPACK_IMPORTED_MODULE_12__.DUST_UTXO_THRESHOLD);\n }\n else {\n return await this.provider.getUtxos(address);\n }\n }\n // watching for any transaction hash of this wallet\n async watchAddress(callback) {\n return this.provider.watchAddress(this.getDepositAddress(), callback);\n }\n // watching for any transaction of this wallet\n async watchAddressTransactions(callback) {\n return this.provider.watchAddressTransactions(this.getDepositAddress(), callback);\n }\n // watching for cashtoken transaction of this wallet\n async 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 async 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 async 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 = await 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_2__.UnitEnum.BCH) {\n return new Promise(async (resolve) => {\n let watchCancel;\n watchCancel = await this.watchBalance(async (balance) => {\n const satoshiBalance = await (0,_util_index_js__WEBPACK_IMPORTED_MODULE_13__.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 async watchTokenBalance(tokenId, callback) {\n let previous = undefined;\n return await 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 let watchCancel;\n watchCancel = await this.watchTokenBalance(tokenId, async (balance) => {\n if (balance >= amount) {\n await watchCancel?.();\n resolve(balance);\n }\n });\n });\n }\n async _getMaxAmountToSend(params = {\n outputCount: 1,\n options: {},\n }) {\n if (!params.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.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 = await (0,_util_checkUtxos_js__WEBPACK_IMPORTED_MODULE_14__.checkUtxos)(params.options.utxoIds.map((utxoId) => typeof utxoId === \"string\" ? (0,_model_js__WEBPACK_IMPORTED_MODULE_15__.fromUtxoId)(utxoId) : utxoId), this);\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_15__.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_16__.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_16__.getFeeAmountSimple)({\n utxos: fundingUtxos,\n sendRequests: sendRequests,\n privateKey: params.privateKey ?? (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__.hexToBin)(placeholderPrivateKey),\n sourceAddress: this.cashaddr,\n relayFeePerByteInSatoshi: relayFeePerByteInSatoshi,\n feePaidBy: feePaidBy,\n });\n const spendableAmount = (0,_util_index_js__WEBPACK_IMPORTED_MODULE_11__.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_10__.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_15__.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_4__.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, privateKey) {\n const { value: maxSpendableAmount, utxos } = await this._getMaxAmountToSend({\n outputCount: 1,\n options: options,\n privateKey: privateKey,\n });\n if (!options) {\n options = {};\n }\n options.utxoIds = utxos;\n const sendRequest = new _model_js__WEBPACK_IMPORTED_MODULE_15__.SendRequest({\n cashaddr: cashaddr,\n value: maxSpendableAmount,\n unit: \"sat\",\n });\n const { encodedTransaction, tokenIds, sourceOutputs } = await this.encodeTransaction([sendRequest], true, options, privateKey);\n const resp = new _model_js__WEBPACK_IMPORTED_MODULE_15__.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_4__.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, privateKey) {\n let sendRequests = (0,_util_index_js__WEBPACK_IMPORTED_MODULE_17__.asSendRequestObject)(requests);\n if (!privateKey && options?.buildUnsigned !== true) {\n throw new Error(`Missing private key`);\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 = await (0,_util_checkUtxos_js__WEBPACK_IMPORTED_MODULE_14__.checkUtxos)(options.utxoIds.map((utxoId) => typeof utxoId === \"string\" ? (0,_model_js__WEBPACK_IMPORTED_MODULE_15__.fromUtxoId)(utxoId) : utxoId), this);\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_15__.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_15__.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, 0n);\n const tokenOutputs = allTokenOutputs.filter((val) => val.tokenId === tokenId);\n const outputAmountSum = tokenOutputs.reduce((prev, cur) => prev + cur.amount, 0n);\n const diff = inputAmountSum - outputAmountSum;\n if (diff < 0) {\n throw new Error(\"Not enough token amount to send\");\n }\n if (diff >= 0) {\n let available = 0n;\n let change = 0n;\n const ensureUtxos = [];\n for (const token of tokenInputs.filter((val) => val.token?.amount)) {\n ensureUtxos.push(token);\n available += token.token.amount;\n if (available >= outputAmountSum) {\n change = available - outputAmountSum;\n //break;\n }\n }\n if (ensureUtxos.length) {\n if (!options) {\n options = {};\n }\n options.ensureUtxos = [\n ...(options.ensureUtxos ?? []),\n ...ensureUtxos,\n ].filter((val, index, array) => array.findIndex((other) => other.txid === val.txid && other.vout === val.vout) === index);\n }\n if (change > 0) {\n outputs.push(new _model_js__WEBPACK_IMPORTED_MODULE_15__.TokenSendRequest({\n cashaddr: (0,_util_index_js__WEBPACK_IMPORTED_MODULE_8__.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 };\n addTokenChangeOutputs(utxos, sendRequests);\n const bestHeight = await this.provider.getBlockHeight();\n const spendAmount = await (0,_util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_18__.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_16__.getFeeAmountSimple)({\n utxos: utxos,\n sendRequests: sendRequests,\n privateKey: privateKey ?? (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__.hexToBin)(placeholderPrivateKey),\n sourceAddress: this.cashaddr,\n relayFeePerByteInSatoshi: relayFeePerByteInSatoshi,\n feePaidBy: feePaidBy,\n });\n const fundingUtxos = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_16__.getSuitableUtxos)(utxos, BigInt(spendAmount) + BigInt(Math.ceil(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_16__.getFeeAmount)({\n utxos: fundingUtxos,\n sendRequests: sendRequests,\n privateKey: privateKey ?? (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__.hexToBin)(placeholderPrivateKey),\n sourceAddress: this.cashaddr,\n relayFeePerByteInSatoshi: relayFeePerByteInSatoshi,\n feePaidBy: feePaidBy,\n });\n const { encodedTransaction, sourceOutputs } = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_16__.buildEncodedTransaction)({\n inputs: fundingUtxos,\n outputs: sendRequests,\n signingKey: privateKey ?? (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__.hexToBin)(placeholderPrivateKey),\n sourceAddress: this.cashaddr,\n fee,\n discardChange,\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_15__.TokenSendRequest)\n .map((val) => val.tokenId),\n ].filter((value, index, array) => array.indexOf(value) === index);\n return { encodedTransaction, tokenIds, sourceOutputs };\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_4__.binToHex)(transaction);\n return await this.provider.sendRawTransaction(rawTransaction, awaitPropagation);\n }\n // gets transaction history of this wallet\n async getRawHistory(fromHeight = 0, toHeight = -1) {\n return await this.provider.getHistory(this.cashaddr, fromHeight, toHeight);\n }\n /**\n * getHistory gets transaction history of this wallet with most data decoded and ready to present to user\n * @note balance calculations are valid only if querying to the blockchain tip (`toHeight` === -1, `count` === -1)\n * @note this method is heavy on network calls, if invoked in browser use of cache is advised, @see `Config.UseLocalStorageCache`\n * @note this method tries to recreate the history tab view of Electron Cash wallet, however, it may not be 100% accurate if the tnransaction value changes are the same in the same block (ordering)\n *\n * @param unit optional, BCH or currency unit to present balance and balance changes. If unit is currency like USD or EUR, balances will be subject to possible rounding errors. Default 0\n * @param fromHeight optional, if set, history will be limited. Default 0\n * @param toHeight optional, if set, history will be limited. Default -1, meaning that all history items will be returned, including mempool\n * @param start optional, if set, the result set will be paginated with offset `start`\n * @param count optional, if set, the result set will be paginated with `count`. Default -1, meaning that all history items will be returned\n *\n * @returns an array of transaction history items, with input values and addresses encoded in cashaddress format. @see `TransactionHistoryItem` type\n */\n async getHistory({ unit = \"sat\", fromHeight = 0, toHeight = -1, start = 0, count = -1, }) {\n return (0,_history_electrumTransformer_js__WEBPACK_IMPORTED_MODULE_19__.getAddressHistory)({\n address: this.cashaddr,\n provider: this.provider,\n unit,\n fromHeight,\n toHeight,\n start,\n count,\n });\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 let cancel;\n const waitForTransactionCallback = async (data) => {\n if (data && data[0] === options.txHash && data[1] !== null) {\n txHashSeen = true;\n await cancel?.();\n resolve(makeResponse(options.txHash));\n }\n };\n cancel = await this.provider.subscribeToTransaction(options.txHash, waitForTransactionCallback);\n return;\n }\n // waiting for any address transaction\n let watchCancel;\n let initialResponseSeen = false;\n watchCancel = await this.provider.watchAddressStatus(this.getDepositAddress(), async (_status) => {\n if (initialResponseSeen) {\n await watchCancel?.();\n resolve(makeResponse());\n return;\n }\n initialResponseSeen = true;\n });\n });\n }\n /**\n * watchBlocks Watch network blocks\n *\n * @param callback callback with a block header object\n * @param skipCurrentHeight if set, the notification about current block will not arrive\n *\n * @returns a function which will cancel watching upon evaluation\n */\n async watchBlocks(callback, skipCurrentHeight = true) {\n return this.provider.watchBlocks(callback, skipCurrentHeight);\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 // Convenience wrapper to verify interface\n async verify(message, sig, publicKey) {\n return await new _message_signed_js__WEBPACK_IMPORTED_MODULE_20__.SignedMessage().verify(message, sig, this.cashaddr, publicKey);\n }\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 = await (0,_util_checkUtxos_js__WEBPACK_IMPORTED_MODULE_14__.checkUtxos)(options.utxoIds.map((utxoId) => typeof utxoId === \"string\" ? (0,_model_js__WEBPACK_IMPORTED_MODULE_15__.fromUtxoId)(utxoId) : utxoId), this);\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_15__.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_21__.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 - BigInt(mintRequests.length)\n : nftUtxos[0].token.amount;\n const safeNewAmount = newAmount < 0n ? 0n : newAmount;\n const mintingInput = new _model_js__WEBPACK_IMPORTED_MODULE_15__.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_15__.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 || 0n), 0n);\n let fungibleBurnAmount = burnRequest.amount && burnRequest.amount > 0 ? burnRequest.amount : 0n;\n fungibleBurnAmount = BigInt(fungibleBurnAmount);\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 === 0n) {\n changeSendRequests = [];\n utxoIds.push(tokenUtxos[0]);\n }\n else {\n // add utxos to spend from\n let available = 0n;\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 = newAmount < 0n ? 0n : newAmount;\n changeSendRequests = [\n new _model_js__WEBPACK_IMPORTED_MODULE_15__.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 fungible tokens, let us destroy the token completely\n if (totalFungibleAmount === fungibleBurnAmount) {\n changeSendRequests = [];\n utxoIds.push(...tokenUtxos);\n }\n else {\n // add utxos to spend from\n let available = 0n;\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 = available - fungibleBurnAmount;\n const safeNewAmount = newAmount < 0n ? 0n : newAmount;\n changeSendRequests = [\n new _model_js__WEBPACK_IMPORTED_MODULE_15__.TokenSendRequest({\n cashaddr: burnRequest.cashaddr || this.tokenaddr,\n tokenId: burnRequest.tokenId,\n amount: safeNewAmount,\n value: tokenUtxos.reduce((a, c) => a + c.satoshis, 0),\n }),\n ];\n }\n }\n const opReturn = _model_js__WEBPACK_IMPORTED_MODULE_15__.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.cashaddr);\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 {bigint} fungible token balance\n */\n async getTokenBalance(tokenId) {\n const utxos = (await this.getTokenUtxos(tokenId)).filter((val) => val.token?.amount);\n return (0,_util_index_js__WEBPACK_IMPORTED_MODULE_11__.sumTokenAmounts)(utxos, tokenId);\n }\n /**\n * getNftTokenBalance Gets non-fungible token (NFT) balance for a particular 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] = 0n;\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}\n/**\n * Class to manage a mainnet watch wallet.\n */\nclass WatchWallet extends BaseWallet {\n static { this.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__.CashAddressNetworkPrefix.mainnet; }\n static { this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Watch; }\n constructor() {\n super(_enum_js__WEBPACK_IMPORTED_MODULE_2__.NetworkType.Mainnet);\n }\n}\n/**\n * Class to manage a testnet watch wallet.\n */\nclass TestNetWatchWallet extends BaseWallet {\n static { this.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__.CashAddressNetworkPrefix.testnet; }\n static { this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Watch; }\n constructor() {\n super(_enum_js__WEBPACK_IMPORTED_MODULE_2__.NetworkType.Testnet);\n }\n}\n/**\n * Class to manage a regtest watch wallet.\n */\nclass RegTestWatchWallet extends BaseWallet {\n static { this.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__.CashAddressNetworkPrefix.regtest; }\n static { this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Watch; }\n constructor() {\n super(_enum_js__WEBPACK_IMPORTED_MODULE_2__.NetworkType.Regtest);\n }\n}\n/**\n * _checkContextSafety (internal) if running in nodejs, will disable saving\n * mainnet wallets on public servers if ALLOW_MAINNET_USER_WALLETS is set to false\n * @param {BaseWallet} wallet a wallet\n */\nconst _checkContextSafety = function (wallet) {\n if ((0,_util_index_js__WEBPACK_IMPORTED_MODULE_22__.getRuntimePlatform)() === \"node\") {\n if (process.env.ALLOW_MAINNET_USER_WALLETS === `false`) {\n if (wallet.network === _enum_js__WEBPACK_IMPORTED_MODULE_2__.NetworkType.Mainnet) {\n throw Error(`Refusing to save wallet in an open public database, remove ALLOW_MAINNET_USER_WALLETS=\"false\", if this service is secure and private`);\n }\n }\n }\n};\n/**\n * getNamedWalletId - get the full wallet id from the database\n *\n * @param name user friendly wallet alias\n * @param dbName name under which the wallet will be stored in the database\n *\n * @returns boolean\n */\nasync function getNamedWalletId(name, dbName) {\n if (name.length === 0) {\n throw Error(\"Named wallets must have a non-empty name\");\n }\n dbName = dbName ? dbName : dbName;\n let db = getStorageProvider(dbName);\n if (db) {\n await db.init();\n let savedWalletRecord = await db.getWallet(name);\n await db.close();\n if (savedWalletRecord !== undefined) {\n return savedWalletRecord.wallet;\n }\n else {\n throw Error(`No record was found for ${name} in db: ${dbName}`);\n }\n }\n else {\n throw Error(\"No database was available or configured to store the named wallet.\");\n }\n}\nfunction getStorageProvider(dbName) {\n if (!BaseWallet.StorageProvider) {\n return undefined;\n }\n return new BaseWallet.StorageProvider(dbName);\n}\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/wallet/Base.ts?");
|
|
638
638
|
|
|
639
639
|
/***/ }),
|
|
640
640
|
|
|
@@ -654,7 +654,7 @@ eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__
|
|
|
654
654
|
\***************************/
|
|
655
655
|
/***/ ((module, __webpack_exports__, __webpack_require__) => {
|
|
656
656
|
|
|
657
|
-
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 */ \"RegTestWifWallet\": () => (/* binding */ RegTestWifWallet),\n/* harmony export */ \"TestNetWallet\": () => (/* binding */ TestNetWallet),\n/* harmony export */ \"TestNetWifWallet\": () => (/* binding */ TestNetWifWallet),\n/* harmony export */ \"Wallet\": () => (/* binding */ Wallet),\n/* harmony export */ \"WifWallet\": () => (/* binding */ WifWallet)\n/* harmony export */ });\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! @bitauth/libauth */ \"./node_modules/@bitauth/libauth/build/lib/key/hd-key.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_18__ = __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/hex.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @bitauth/libauth */ \"./node_modules/@bitauth/libauth/build/lib/key/key-utils.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! @bitauth/libauth */ \"./node_modules/@bitauth/libauth/build/lib/key/wallet-import-format.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! @bitauth/libauth */ \"./node_modules/@bitauth/libauth/build/lib/address/cash-address.js\");\n/* harmony import */ var _scure_bip39__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @scure/bip39 */ \"../../node_modules/@scure/bip39/esm/index.js\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../enum.js */ \"./src/enum.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_13__ = __webpack_require__(/*! ./model.js */ \"./src/wallet/model.ts\");\n/* harmony import */ var _transaction_Wif_js__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ../transaction/Wif.js */ \"./src/transaction/Wif.ts\");\n/* harmony import */ var _constant_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../constant.js */ \"./src/constant.ts\");\n/* harmony import */ var _message_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../message/index.js */ \"./src/message/signed.ts\");\n/* harmony import */ var _util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../util/checkForEmptySeed.js */ \"./src/util/checkForEmptySeed.ts\");\n/* harmony import */ var _util_checkWifNetwork_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../util/checkWifNetwork.js */ \"./src/util/checkWifNetwork.ts\");\n/* harmony import */ var _util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ../util/deriveCashaddr.js */ \"./src/util/deriveCashaddr.ts\");\n/* harmony import */ var _util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ../util/derivePublicKeyHash.js */ \"./src/util/derivePublicKeyHash.ts\");\n/* harmony import */ var _util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../util/getXPubKey.js */ \"./src/util/getXPubKey.ts\");\n/* harmony import */ var _util_randomBytes_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../util/randomBytes.js */ \"./src/util/randomBytes.ts\");\n/* harmony import */ var _config_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../config.js */ \"./src/config.ts\");\n/* harmony import */ var _util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../util/balanceObjectFromSatoshi.js */ \"./src/util/balanceObjectFromSatoshi.ts\");\n/* harmony import */ var _Base_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Base.js */ \"./src/wallet/Base.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_Base_js__WEBPACK_IMPORTED_MODULE_1__, _message_index_js__WEBPACK_IMPORTED_MODULE_2__, _enum_js__WEBPACK_IMPORTED_MODULE_4__, _config_js__WEBPACK_IMPORTED_MODULE_6__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__, _util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_9__, _util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_10__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__, _model_js__WEBPACK_IMPORTED_MODULE_13__, _util_checkWifNetwork_js__WEBPACK_IMPORTED_MODULE_14__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_15__, _util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_16__, _transaction_Wif_js__WEBPACK_IMPORTED_MODULE_17__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_18__, _util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_19__, _util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_20__]);\n([_Base_js__WEBPACK_IMPORTED_MODULE_1__, _message_index_js__WEBPACK_IMPORTED_MODULE_2__, _enum_js__WEBPACK_IMPORTED_MODULE_4__, _config_js__WEBPACK_IMPORTED_MODULE_6__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__, _util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_9__, _util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_10__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__, _model_js__WEBPACK_IMPORTED_MODULE_13__, _util_checkWifNetwork_js__WEBPACK_IMPORTED_MODULE_14__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_15__, _util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_16__, _transaction_Wif_js__WEBPACK_IMPORTED_MODULE_17__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_18__, _util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_19__, _util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_20__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n//#region Imports\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_1__.BaseWallet {\n static { this.signedMessage = new _message_index_js__WEBPACK_IMPORTED_MODULE_2__.SignedMessage(); }\n //#region Accessors\n // Get mnemonic and derivation path for wallet\n getSeed() {\n if (!this.mnemonic) {\n throw Error(\"Wallet mnemonic seed phrase not set\");\n }\n if (!this.derivationPath) {\n throw Error(\"Wallet derivation path not set\");\n }\n return {\n seed: this.mnemonic,\n derivationPath: this.derivationPath,\n parentDerivationPath: this.parentDerivationPath,\n };\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_3__.binToHex)(this.publicKey) : undefined,\n publicKeyHash: (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.binToHex)(this.publicKeyHash),\n privateKey: this.privateKey ? (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.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_3__.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_3__.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 //#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(network);\n this.derivationPath = _config_js__WEBPACK_IMPORTED_MODULE_6__.Config.DefaultParentDerivationPath + \"/0/0\";\n this.parentDerivationPath = _config_js__WEBPACK_IMPORTED_MODULE_6__.Config.DefaultParentDerivationPath;\n this.fromId = async (walletId) => {\n const [walletType, networkGiven, arg1, arg2] = walletId.split(\":\");\n if (this.network !== networkGiven) {\n throw Error(`Network prefix ${networkGiven} to a ${this.network} wallet`);\n }\n // \"wif:regtest:cNfsPtqN2bMRS7vH5qd8tR8GMvgXyL5BjnGAKgZ8DYEiCrCCQcP6\"\n switch (walletType) {\n case \"wif\":\n return this.fromWIF(arg1);\n case \"watch\":\n if (arg2) {\n // watch:testnet:bchtest:qq1234567\n return this.watchOnly(`${arg1}:${arg2}`);\n }\n // watch:testnet:qq1234567\n return this.watchOnly(`${arg1}`);\n case \"named\":\n if (arg2) {\n // named:testnet:wallet_1:my_database\n return this.named(arg1, arg2);\n }\n else {\n // named:testnet:wallet_1\n return this.named(arg1);\n }\n case \"seed\":\n if (arg2) {\n // seed:testnet:table later ... stove kitten pluck:m/44'/0'/0'/0/0\n return this.fromSeed(arg1, arg2);\n }\n // seed:testnet:table later ... stove kitten pluck\n return this.fromSeed(arg1);\n default:\n throw Error(`Unknown wallet type '${walletType}'`);\n }\n };\n this.name = name;\n this.walletType = walletType;\n }\n //#region Statics\n /**\n * fromId - create a wallet from encoded walletId string\n *\n * @param walletId walletId options to steer the creation process\n *\n * @returns wallet instantiated accordingly to the walletId rules\n */\n static async fromId(walletId) {\n return new this().fromId(walletId);\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 * fromSeed - create a wallet using the seed phrase and derivation path\n *\n * unless specified the derivation path m/44'/245'/0'/0/0 will be userd\n * this derivation path is standard for Electron Cash SLP and other SLP enabled wallets\n *\n * @param seed BIP39 12 word seed phrase\n * @param derivationPath BIP44 HD wallet derivation path to get a single the private key from hierarchy\n *\n * @returns instantiated wallet\n */\n static async fromSeed(seed, derivationPath) {\n return new this().fromSeed(seed, derivationPath);\n }\n /**\n * newRandom - create a random wallet\n *\n * if `name` parameter is specified, the wallet will also be persisted to DB\n *\n * @param name user friendly wallet alias\n * @param dbName name under which the wallet will be stored in the database\n *\n * @returns instantiated wallet\n */\n static async newRandom(name = \"\", dbName) {\n return new this().newRandom(name, dbName);\n }\n //#endregion Constructors\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_7__.generatePrivateKey)(() => (0,_util_randomBytes_js__WEBPACK_IMPORTED_MODULE_8__.generateRandomBytes)(32));\n }\n return this.deriveInfo();\n }\n async _generateMnemonic() {\n this.mnemonic = (0,_scure_bip39__WEBPACK_IMPORTED_MODULE_0__.generateMnemonic)(_config_js__WEBPACK_IMPORTED_MODULE_6__.Config.getWordlist());\n if (this.mnemonic.length == 0)\n throw Error(\"refusing to create wallet from empty mnemonic\");\n const seed = (0,_scure_bip39__WEBPACK_IMPORTED_MODULE_0__.mnemonicToSeedSync)(this.mnemonic);\n (0,_util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_9__.checkForEmptySeed)(seed);\n const network = this.isTestnet ? \"testnet\" : \"mainnet\";\n this.parentXPubKey = (0,_util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_10__.getXPubKey)(seed, this.parentDerivationPath, network);\n const hdNode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.deriveHdPrivateNodeFromSeed)(seed, {\n assumeValidity: true, // TODO: we should switch to libauth's BIP39 implementation and set this to false\n throwErrors: true,\n });\n const zerothChild = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.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_12__.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 const seed = (0,_scure_bip39__WEBPACK_IMPORTED_MODULE_0__.mnemonicToSeedSync)(this.mnemonic);\n (0,_util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_9__.checkForEmptySeed)(seed);\n const hdNode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.deriveHdPrivateNodeFromSeed)(seed, {\n assumeValidity: true, // TODO: we should switch to libauth's BIP39 implementation and set this to false\n throwErrors: true,\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 const path = derivationPath.split(\"/\");\n if (path.slice(-2).join(\"/\") == \"0/0\") {\n this.parentDerivationPath = path.slice(0, -2).join(\"/\");\n }\n }\n const zerothChild = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.deriveHdPath)(hdNode, this.derivationPath);\n if (typeof zerothChild === \"string\") {\n throw Error(zerothChild);\n }\n this.privateKey = zerothChild.privateKey;\n const network = this.isTestnet ? \"testnet\" : \"mainnet\";\n this.parentXPubKey = await (0,_util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_10__.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 const seed = (0,_scure_bip39__WEBPACK_IMPORTED_MODULE_0__.mnemonicToSeedSync)(this.mnemonic);\n (0,_util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_9__.checkForEmptySeed)(seed);\n const hdNode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.deriveHdPrivateNodeFromSeed)(seed, {\n assumeValidity: true, // TODO: we should switch to libauth's BIP39 implementation and set this to false\n throwErrors: true,\n });\n const 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 const childNode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.deriveHdPath)(hdNode, path);\n if (typeof childNode === \"string\") {\n throw Error(childNode);\n }\n const node = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.deriveHdPublicNode)(childNode);\n if (typeof node === \"string\") {\n throw Error(node);\n }\n const xPubKey = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.encodeHdPublicKey)({\n network: this.network,\n node: node,\n }, {\n throwErrors: true,\n }).hdPublicKey;\n const key = new _model_js__WEBPACK_IMPORTED_MODULE_13__.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 wallet from Wallet Import Format\n async fromWIF(secret) {\n (0,_util_checkWifNetwork_js__WEBPACK_IMPORTED_MODULE_14__.checkWifNetwork)(secret, this.network);\n let wifResult = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_15__.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 /**\n * newRandom (internal) if the wallet is named, get or create it; otherwise create a random\n * unnamed wallet\n * @param {string} name name of the wallet\n * @param {string} dbName database name the wallet is stored in\n */\n async newRandom(name, dbName) {\n dbName = dbName ? dbName : this.networkPrefix;\n if (name.length > 0) {\n return this.named(name, dbName);\n }\n else {\n return this.generate();\n }\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 if (this.name) {\n return `named:${this.network}:${this.name}`;\n }\n else if (this.walletType == _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Seed) {\n return `${this.walletType}:${this.network}:${this.mnemonic}:${this.derivationPath}`;\n }\n else if (this.walletType === _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Wif) {\n return `${this.walletType}:${this.network}:${this.privateKeyWif}`;\n }\n else if (this.walletType == _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Watch) {\n return super.toString();\n }\n throw Error(\"toString unsupported wallet type\");\n }\n /**\n * toDbString - store the serialized version of the wallet in the database, not just the name\n *\n * @throws {Error} if called on BaseWallet\n */\n toDbString() {\n if (this.walletType == _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Seed) {\n return `${this.walletType}:${this.network}:${this.mnemonic}:${this.derivationPath}`;\n }\n else if (this.walletType === _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Wif) {\n return `${this.walletType}:${this.network}:${this.privateKeyWif}`;\n }\n else if (this.walletType == _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Watch) {\n return super.toDbString();\n }\n throw Error(\"toDbString unsupported wallet type\");\n }\n //#endregion Serialization\n //#region Funds\n async getMaxAmountToSend(params = {\n outputCount: 1,\n options: {},\n }) {\n const { value: result } = await this._getMaxAmountToSend({\n options: params.options,\n outputCount: params.outputCount,\n privateKey: this.privateKey,\n });\n return await (0,_util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_16__.balanceResponseFromSatoshi)(result);\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 this.sendMaxRaw(cashaddr, options, this.privateKey);\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, privateKey) {\n return super.encodeTransaction(requests, discardChange, options, this.privateKey);\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_17__.signUnsignedTransaction)(transaction, sourceOutputs, this.privateKey);\n }\n //#endregion Funds\n //#region Private implementation details\n async deriveInfo() {\n const publicKey = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_18__.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_18__.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_15__.encodePrivateKeyWif)(this.privateKey, networkType);\n (0,_util_checkWifNetwork_js__WEBPACK_IMPORTED_MODULE_14__.checkWifNetwork)(this.privateKeyWif, this.network);\n this.cashaddr = (0,_util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_19__.deriveCashaddr)(this.privateKey, this.networkPrefix);\n this.tokenaddr = (0,_util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_19__.deriveTokenaddr)(this.privateKey, this.networkPrefix);\n this.publicKeyHash = (0,_util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_20__.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}\n/**\n * Class to manage a testnet wallet.\n */\nclass TestNetWallet extends Wallet {\n static { this.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_21__.CashAddressNetworkPrefix.testnet; }\n static { this.faucetServer = \"https://rest-unstable.mainnet.cash\"; }\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_4__.NetworkType.Testnet);\n }\n}\n/**\n * Class to manage a regtest wallet.\n */\nclass RegTestWallet extends Wallet {\n static { this.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_21__.CashAddressNetworkPrefix.regtest; }\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_4__.NetworkType.Regtest);\n }\n}\n/**\n * Class to manage a bitcoin cash wif wallet.\n */\nclass WifWallet extends Wallet {\n static { this.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_21__.CashAddressNetworkPrefix.mainnet; }\n static { this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Wif; }\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_4__.NetworkType.Mainnet, _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Wif);\n }\n}\n/**\n * Class to manage a testnet wif wallet.\n */\nclass TestNetWifWallet extends Wallet {\n static { this.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_21__.CashAddressNetworkPrefix.testnet; }\n static { this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Wif; }\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_4__.NetworkType.Testnet, _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Wif);\n }\n}\n/**\n * Class to manage a regtest wif wallet.\n */\nclass RegTestWifWallet extends Wallet {\n static { this.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_21__.CashAddressNetworkPrefix.regtest; }\n static { this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Wif; }\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_4__.NetworkType.Regtest, _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Wif);\n }\n}\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/wallet/Wif.ts?");
|
|
657
|
+
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 */ \"RegTestWifWallet\": () => (/* binding */ RegTestWifWallet),\n/* harmony export */ \"TestNetWallet\": () => (/* binding */ TestNetWallet),\n/* harmony export */ \"TestNetWifWallet\": () => (/* binding */ TestNetWifWallet),\n/* harmony export */ \"Wallet\": () => (/* binding */ Wallet),\n/* harmony export */ \"WifWallet\": () => (/* binding */ WifWallet)\n/* harmony export */ });\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! @bitauth/libauth */ \"./node_modules/@bitauth/libauth/build/lib/key/hd-key.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @bitauth/libauth */ \"./node_modules/@bitauth/libauth/build/lib/format/hex.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! @bitauth/libauth */ \"./node_modules/@bitauth/libauth/build/lib/crypto/default-crypto-instances.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @bitauth/libauth */ \"./node_modules/@bitauth/libauth/build/lib/key/key-utils.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! @bitauth/libauth */ \"./node_modules/@bitauth/libauth/build/lib/key/wallet-import-format.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! @bitauth/libauth */ \"./node_modules/@bitauth/libauth/build/lib/address/cash-address.js\");\n/* harmony import */ var _scure_bip39__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @scure/bip39 */ \"../../node_modules/@scure/bip39/esm/index.js\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../enum.js */ \"./src/enum.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_13__ = __webpack_require__(/*! ./model.js */ \"./src/wallet/model.ts\");\n/* harmony import */ var _transaction_Wif_js__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ../transaction/Wif.js */ \"./src/transaction/Wif.ts\");\n/* harmony import */ var _constant_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../constant.js */ \"./src/constant.ts\");\n/* harmony import */ var _message_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../message/index.js */ \"./src/message/signed.ts\");\n/* harmony import */ var _util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../util/checkForEmptySeed.js */ \"./src/util/checkForEmptySeed.ts\");\n/* harmony import */ var _util_checkWifNetwork_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../util/checkWifNetwork.js */ \"./src/util/checkWifNetwork.ts\");\n/* harmony import */ var _util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ../util/deriveCashaddr.js */ \"./src/util/deriveCashaddr.ts\");\n/* harmony import */ var _util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ../util/derivePublicKeyHash.js */ \"./src/util/derivePublicKeyHash.ts\");\n/* harmony import */ var _util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../util/getXPubKey.js */ \"./src/util/getXPubKey.ts\");\n/* harmony import */ var _util_randomBytes_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../util/randomBytes.js */ \"./src/util/randomBytes.ts\");\n/* harmony import */ var _config_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../config.js */ \"./src/config.ts\");\n/* harmony import */ var _util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../util/balanceObjectFromSatoshi.js */ \"./src/util/balanceObjectFromSatoshi.ts\");\n/* harmony import */ var _Base_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Base.js */ \"./src/wallet/Base.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_Base_js__WEBPACK_IMPORTED_MODULE_1__, _message_index_js__WEBPACK_IMPORTED_MODULE_2__, _enum_js__WEBPACK_IMPORTED_MODULE_4__, _config_js__WEBPACK_IMPORTED_MODULE_6__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__, _util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_9__, _util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_10__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__, _model_js__WEBPACK_IMPORTED_MODULE_13__, _util_checkWifNetwork_js__WEBPACK_IMPORTED_MODULE_14__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_15__, _util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_16__, _transaction_Wif_js__WEBPACK_IMPORTED_MODULE_17__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_18__, _util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_19__, _util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_20__]);\n([_Base_js__WEBPACK_IMPORTED_MODULE_1__, _message_index_js__WEBPACK_IMPORTED_MODULE_2__, _enum_js__WEBPACK_IMPORTED_MODULE_4__, _config_js__WEBPACK_IMPORTED_MODULE_6__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__, _util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_9__, _util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_10__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__, _model_js__WEBPACK_IMPORTED_MODULE_13__, _util_checkWifNetwork_js__WEBPACK_IMPORTED_MODULE_14__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_15__, _util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_16__, _transaction_Wif_js__WEBPACK_IMPORTED_MODULE_17__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_18__, _util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_19__, _util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_20__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n//#region Imports\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_1__.BaseWallet {\n static { this.signedMessage = new _message_index_js__WEBPACK_IMPORTED_MODULE_2__.SignedMessage(); }\n //#region Accessors\n // Get mnemonic and derivation path for wallet\n getSeed() {\n if (!this.mnemonic) {\n throw Error(\"Wallet mnemonic seed phrase not set\");\n }\n if (!this.derivationPath) {\n throw Error(\"Wallet derivation path not set\");\n }\n return {\n seed: this.mnemonic,\n derivationPath: this.derivationPath,\n parentDerivationPath: this.parentDerivationPath,\n };\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_3__.binToHex)(this.publicKey) : undefined,\n publicKeyHash: (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.binToHex)(this.publicKeyHash),\n privateKey: this.privateKey ? (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.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_3__.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_3__.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 //#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(network);\n this.derivationPath = _config_js__WEBPACK_IMPORTED_MODULE_6__.Config.DefaultParentDerivationPath + \"/0/0\";\n this.parentDerivationPath = _config_js__WEBPACK_IMPORTED_MODULE_6__.Config.DefaultParentDerivationPath;\n this.fromId = async (walletId) => {\n const [walletType, networkGiven, arg1, arg2] = walletId.split(\":\");\n if (this.network !== networkGiven) {\n throw Error(`Network prefix ${networkGiven} to a ${this.network} wallet`);\n }\n // \"wif:regtest:cNfsPtqN2bMRS7vH5qd8tR8GMvgXyL5BjnGAKgZ8DYEiCrCCQcP6\"\n switch (walletType) {\n case _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.PrivateKey:\n return this.fromPrivateKey(arg1);\n case _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Wif:\n return this.fromWIF(arg1);\n case _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Watch:\n if (arg2) {\n // watch:testnet:bchtest:qq1234567\n return this.watchOnly(`${arg1}:${arg2}`);\n }\n // watch:testnet:qq1234567\n return this.watchOnly(`${arg1}`);\n case _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Named:\n if (arg2) {\n // named:testnet:wallet_1:my_database\n return this.named(arg1, arg2);\n }\n else {\n // named:testnet:wallet_1\n return this.named(arg1);\n }\n case _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Seed:\n if (arg2) {\n // seed:testnet:table later ... stove kitten pluck:m/44'/0'/0'/0/0\n return this.fromSeed(arg1, arg2);\n }\n // seed:testnet:table later ... stove kitten pluck\n return this.fromSeed(arg1);\n default:\n throw Error(`Unknown wallet type '${walletType}'`);\n }\n };\n this.name = name;\n // @ts-ignore\n this.walletType = walletType;\n }\n //#region Statics\n /**\n * fromId - create a wallet from encoded walletId string\n *\n * @param walletId walletId options to steer the creation process\n *\n * @returns wallet instantiated accordingly to the walletId rules\n */\n static async fromId(walletId) {\n return new this().fromId(walletId);\n }\n /**\n * fromPrivateKey - create a wallet using the private key supplied in hex or Uint8Array\n *\n * @param wif WIF encoded private key string\n *\n * @returns instantiated wallet\n */\n static async fromPrivateKey(privateKey) {\n return new this().fromPrivateKey(privateKey);\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 * fromSeed - create a wallet using the seed phrase and derivation path\n *\n * unless specified the derivation path m/44'/245'/0'/0/0 will be userd\n * this derivation path is standard for Electron Cash SLP and other SLP enabled wallets\n *\n * @param seed BIP39 12 word seed phrase\n * @param derivationPath BIP44 HD wallet derivation path to get a single the private key from hierarchy\n *\n * @returns instantiated wallet\n */\n static async fromSeed(seed, derivationPath) {\n return new this().fromSeed(seed, derivationPath);\n }\n /**\n * newRandom - create a random wallet\n *\n * if `name` parameter is specified, the wallet will also be persisted to DB\n *\n * @param name user friendly wallet alias\n * @param dbName name under which the wallet will be stored in the database\n *\n * @returns instantiated wallet\n */\n static async newRandom(name = \"\", dbName) {\n return new this().newRandom(name, dbName);\n }\n //#endregion Constructors\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 // @ts-ignore\n this.privateKey = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__.generatePrivateKey)(() => (0,_util_randomBytes_js__WEBPACK_IMPORTED_MODULE_8__.generateRandomBytes)(32));\n }\n return this.deriveInfo();\n }\n async _generateMnemonic() {\n // @ts-ignore\n this.mnemonic = (0,_scure_bip39__WEBPACK_IMPORTED_MODULE_0__.generateMnemonic)(_config_js__WEBPACK_IMPORTED_MODULE_6__.Config.getWordlist());\n if (this.mnemonic.length == 0)\n throw Error(\"refusing to create wallet from empty mnemonic\");\n const seed = (0,_scure_bip39__WEBPACK_IMPORTED_MODULE_0__.mnemonicToSeedSync)(this.mnemonic);\n (0,_util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_9__.checkForEmptySeed)(seed);\n const network = this.isTestnet ? \"testnet\" : \"mainnet\";\n // @ts-ignore\n this.parentXPubKey = (0,_util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_10__.getXPubKey)(seed, this.parentDerivationPath, network);\n const hdNode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.deriveHdPrivateNodeFromSeed)(seed, {\n assumeValidity: true, // TODO: we should switch to libauth's BIP39 implementation and set this to false\n throwErrors: true,\n });\n const zerothChild = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.deriveHdPath)(hdNode, this.derivationPath);\n if (typeof zerothChild === \"string\") {\n throw Error(zerothChild);\n }\n // @ts-ignore\n this.privateKey = zerothChild.privateKey;\n // @ts-ignore\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_12__.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 // @ts-ignore\n this.mnemonic = mnemonic.trim().toLowerCase();\n if (this.mnemonic.length == 0)\n throw Error(\"refusing to create wallet from empty mnemonic\");\n const seed = (0,_scure_bip39__WEBPACK_IMPORTED_MODULE_0__.mnemonicToSeedSync)(this.mnemonic);\n (0,_util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_9__.checkForEmptySeed)(seed);\n const hdNode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.deriveHdPrivateNodeFromSeed)(seed, {\n assumeValidity: true, // TODO: we should switch to libauth's BIP39 implementation and set this to false\n throwErrors: true,\n });\n if (derivationPath) {\n // @ts-ignore\n this.derivationPath = derivationPath;\n // If the derivation path is for the first account child, set the parent derivation path\n const path = derivationPath.split(\"/\");\n if (path.slice(-2).join(\"/\") == \"0/0\") {\n // @ts-ignore\n this.parentDerivationPath = path.slice(0, -2).join(\"/\");\n }\n }\n const zerothChild = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.deriveHdPath)(hdNode, this.derivationPath);\n if (typeof zerothChild === \"string\") {\n throw Error(zerothChild);\n }\n // @ts-ignore\n this.privateKey = zerothChild.privateKey;\n const network = this.isTestnet ? \"testnet\" : \"mainnet\";\n // @ts-ignore\n this.parentXPubKey = await (0,_util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_10__.getXPubKey)(seed, this.parentDerivationPath, network);\n // @ts-ignore\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 const seed = (0,_scure_bip39__WEBPACK_IMPORTED_MODULE_0__.mnemonicToSeedSync)(this.mnemonic);\n (0,_util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_9__.checkForEmptySeed)(seed);\n const hdNode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.deriveHdPrivateNodeFromSeed)(seed, {\n assumeValidity: true, // TODO: we should switch to libauth's BIP39 implementation and set this to false\n throwErrors: true,\n });\n const 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 const childNode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.deriveHdPath)(hdNode, path);\n if (typeof childNode === \"string\") {\n throw Error(childNode);\n }\n const node = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.deriveHdPublicNode)(childNode);\n if (typeof node === \"string\") {\n throw Error(node);\n }\n const xPubKey = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.encodeHdPublicKey)({\n network: this.network,\n node: node,\n }, {\n throwErrors: true,\n }).hdPublicKey;\n const key = new _model_js__WEBPACK_IMPORTED_MODULE_13__.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 wallet from private key in hex or Uint8Array\n async fromPrivateKey(privateKey) {\n if (typeof privateKey === \"string\") {\n privateKey = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.hexToBin)(privateKey);\n }\n // @ts-ignore\n this.privateKey = privateKey;\n // @ts-ignore\n this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.PrivateKey;\n await this.deriveInfo();\n return this;\n }\n // Initialize wallet from Wallet Import Format\n async fromWIF(secret) {\n (0,_util_checkWifNetwork_js__WEBPACK_IMPORTED_MODULE_14__.checkWifNetwork)(secret, this.network);\n let wifResult = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_15__.decodePrivateKeyWif)(secret);\n if (typeof wifResult === \"string\") {\n throw Error(wifResult);\n }\n let resultData = wifResult;\n // @ts-ignore\n this.privateKey = resultData.privateKey;\n // @ts-ignore\n this.privateKeyWif = secret;\n // @ts-ignore\n this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Wif;\n await this.deriveInfo();\n return this;\n }\n /**\n * newRandom (internal) if the wallet is named, get or create it; otherwise create a random\n * unnamed wallet\n * @param {string} name name of the wallet\n * @param {string} dbName database name the wallet is stored in\n */\n async newRandom(name, dbName) {\n dbName = dbName ? dbName : this.networkPrefix;\n if (name.length > 0) {\n return this.named(name, dbName);\n }\n else {\n return this.generate();\n }\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 if (this.name) {\n return `named:${this.network}:${this.name}`;\n }\n else if (this.walletType == _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.PrivateKey) {\n return `${this.walletType}:${this.network}:${(0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.binToHex)(this.privateKey)}`;\n }\n else if (this.walletType == _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Seed) {\n return `${this.walletType}:${this.network}:${this.mnemonic}:${this.derivationPath}`;\n }\n else if (this.walletType === _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Wif) {\n return `${this.walletType}:${this.network}:${this.privateKeyWif}`;\n }\n else if (this.walletType == _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Watch) {\n return super.toString();\n }\n throw Error(\"toString unsupported wallet type\");\n }\n /**\n * toDbString - store the serialized version of the wallet in the database, not just the name\n *\n * @throws {Error} if called on BaseWallet\n */\n toDbString() {\n if (this.walletType == _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Seed) {\n return `${this.walletType}:${this.network}:${this.mnemonic}:${this.derivationPath}`;\n }\n else if (this.walletType == _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.PrivateKey) {\n return `${this.walletType}:${this.network}:${(0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.binToHex)(this.privateKey)}`;\n }\n else if (this.walletType === _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Wif) {\n return `${this.walletType}:${this.network}:${this.privateKeyWif}`;\n }\n else if (this.walletType == _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Watch) {\n return super.toDbString();\n }\n throw Error(\"toDbString unsupported wallet type\");\n }\n //#endregion Serialization\n //#region Funds\n async getMaxAmountToSend(params = {\n outputCount: 1,\n options: {},\n }) {\n const { value: result } = await this._getMaxAmountToSend({\n options: params.options,\n outputCount: params.outputCount,\n privateKey: this.privateKey,\n });\n return await (0,_util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_16__.balanceResponseFromSatoshi)(result);\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 this.sendMaxRaw(cashaddr, options, this.privateKey);\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, privateKey) {\n return super.encodeTransaction(requests, discardChange, options, this.privateKey);\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_17__.signUnsignedTransaction)(transaction, sourceOutputs, this.privateKey);\n }\n //#endregion Funds\n //#region Private implementation details\n async deriveInfo() {\n const publicKey = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_18__.secp256k1.derivePublicKeyUncompressed(this.privateKey);\n if (typeof publicKey === \"string\") {\n throw new Error(publicKey);\n }\n // @ts-ignore\n this.publicKey = publicKey;\n const publicKeyCompressed = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_18__.secp256k1.derivePublicKeyCompressed(this.privateKey);\n if (typeof publicKeyCompressed === \"string\") {\n throw new Error(publicKeyCompressed);\n }\n // @ts-ignore\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 // @ts-ignore\n this.privateKeyWif = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_15__.encodePrivateKeyWif)(this.privateKey, networkType);\n (0,_util_checkWifNetwork_js__WEBPACK_IMPORTED_MODULE_14__.checkWifNetwork)(this.privateKeyWif, this.network);\n // @ts-ignore\n this.cashaddr = (0,_util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_19__.deriveCashaddr)(this.privateKey, this.networkPrefix);\n // @ts-ignore\n this.tokenaddr = (0,_util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_19__.deriveTokenaddr)(this.privateKey, this.networkPrefix);\n // @ts-ignore\n this.publicKeyHash = (0,_util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_20__.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}\n/**\n * Class to manage a testnet wallet.\n */\nclass TestNetWallet extends Wallet {\n static { this.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_21__.CashAddressNetworkPrefix.testnet; }\n static { this.faucetServer = \"https://rest-unstable.mainnet.cash\"; }\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_4__.NetworkType.Testnet);\n }\n}\n/**\n * Class to manage a regtest wallet.\n */\nclass RegTestWallet extends Wallet {\n static { this.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_21__.CashAddressNetworkPrefix.regtest; }\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_4__.NetworkType.Regtest);\n }\n}\n/**\n * Class to manage a bitcoin cash wif wallet.\n */\nclass WifWallet extends Wallet {\n static { this.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_21__.CashAddressNetworkPrefix.mainnet; }\n static { this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Wif; }\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_4__.NetworkType.Mainnet, _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Wif);\n }\n}\n/**\n * Class to manage a testnet wif wallet.\n */\nclass TestNetWifWallet extends Wallet {\n static { this.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_21__.CashAddressNetworkPrefix.testnet; }\n static { this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Wif; }\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_4__.NetworkType.Testnet, _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Wif);\n }\n}\n/**\n * Class to manage a regtest wif wallet.\n */\nclass RegTestWifWallet extends Wallet {\n static { this.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_21__.CashAddressNetworkPrefix.regtest; }\n static { this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Wif; }\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_4__.NetworkType.Regtest, _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Wif);\n }\n}\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/wallet/Wif.ts?");
|
|
658
658
|
|
|
659
659
|
/***/ }),
|
|
660
660
|
|
|
@@ -674,7 +674,7 @@ eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__
|
|
|
674
674
|
\****************************/
|
|
675
675
|
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
|
|
676
676
|
|
|
677
|
-
eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"FeePaidByEnum\": () => (/* binding */ FeePaidByEnum),\n/* harmony export */ \"WalletTypeEnum\": () => (/* binding */ WalletTypeEnum)\n/* harmony export */ });\nvar WalletTypeEnum;\n(function (WalletTypeEnum) {\n WalletTypeEnum[\"Wif\"] = \"wif\";\n WalletTypeEnum[\"Seed\"] = \"seed\";\n WalletTypeEnum[\"Hd\"] = \"hd\";\n WalletTypeEnum[\"Watch\"] = \"watch\";\n WalletTypeEnum[\"PrivateKey\"] = \"privkey\";\n})(WalletTypeEnum || (WalletTypeEnum = {}));\nvar FeePaidByEnum;\n(function (FeePaidByEnum) {\n FeePaidByEnum[\"change\"] = \"change\";\n FeePaidByEnum[\"first\"] = \"firstOutput\";\n FeePaidByEnum[\"any\"] = \"anyOutputs\";\n FeePaidByEnum[\"last\"] = \"lastOutput\";\n FeePaidByEnum[\"changeThenFirst\"] = \"changeThenFirst\";\n FeePaidByEnum[\"changeThenAny\"] = \"changeThenAny\";\n FeePaidByEnum[\"changeThenLast\"] = \"changeThenLast\";\n})(FeePaidByEnum || (FeePaidByEnum = {}));\n\n\n//# sourceURL=webpack://mainnet-js/./src/wallet/enum.ts?");
|
|
677
|
+
eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"FeePaidByEnum\": () => (/* binding */ FeePaidByEnum),\n/* harmony export */ \"WalletTypeEnum\": () => (/* binding */ WalletTypeEnum)\n/* harmony export */ });\nvar WalletTypeEnum;\n(function (WalletTypeEnum) {\n WalletTypeEnum[\"Named\"] = \"named\";\n WalletTypeEnum[\"Wif\"] = \"wif\";\n WalletTypeEnum[\"Seed\"] = \"seed\";\n WalletTypeEnum[\"Hd\"] = \"hd\";\n WalletTypeEnum[\"Watch\"] = \"watch\";\n WalletTypeEnum[\"PrivateKey\"] = \"privkey\";\n})(WalletTypeEnum || (WalletTypeEnum = {}));\nvar FeePaidByEnum;\n(function (FeePaidByEnum) {\n FeePaidByEnum[\"change\"] = \"change\";\n FeePaidByEnum[\"first\"] = \"firstOutput\";\n FeePaidByEnum[\"any\"] = \"anyOutputs\";\n FeePaidByEnum[\"last\"] = \"lastOutput\";\n FeePaidByEnum[\"changeThenFirst\"] = \"changeThenFirst\";\n FeePaidByEnum[\"changeThenAny\"] = \"changeThenAny\";\n FeePaidByEnum[\"changeThenLast\"] = \"changeThenLast\";\n})(FeePaidByEnum || (FeePaidByEnum = {}));\n\n\n//# sourceURL=webpack://mainnet-js/./src/wallet/enum.ts?");
|
|
678
678
|
|
|
679
679
|
/***/ }),
|
|
680
680
|
|