mainnet-js 2.3.15 → 2.4.0
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.3.15.js → mainnet-2.4.0.js} +15 -5
- package/dist/module/history/electrumTransformer.d.ts +11 -3
- package/dist/module/history/electrumTransformer.d.ts.map +1 -1
- package/dist/module/history/electrumTransformer.js +199 -195
- package/dist/module/history/electrumTransformer.js.map +1 -1
- package/dist/module/history/interface.d.ts +19 -13
- package/dist/module/history/interface.d.ts.map +1 -1
- package/dist/module/interface.d.ts +10 -1
- package/dist/module/interface.d.ts.map +1 -1
- package/dist/module/interface.js.map +1 -1
- package/dist/module/network/ElectrumNetworkProvider.d.ts +8 -6
- package/dist/module/network/ElectrumNetworkProvider.d.ts.map +1 -1
- package/dist/module/network/ElectrumNetworkProvider.js +28 -6
- package/dist/module/network/ElectrumNetworkProvider.js.map +1 -1
- package/dist/module/network/NetworkProvider.d.ts +8 -3
- package/dist/module/network/NetworkProvider.d.ts.map +1 -1
- package/dist/module/util/header.d.ts +3 -0
- package/dist/module/util/header.d.ts.map +1 -0
- package/dist/module/util/header.js +13 -0
- package/dist/module/util/header.js.map +1 -0
- package/dist/module/util/index.d.ts +1 -0
- package/dist/module/util/index.d.ts.map +1 -1
- package/dist/module/util/index.js +1 -0
- package/dist/module/util/index.js.map +1 -1
- package/dist/module/wallet/Wif.d.ts +27 -6
- package/dist/module/wallet/Wif.d.ts.map +1 -1
- package/dist/module/wallet/Wif.js +29 -7
- package/dist/module/wallet/Wif.js.map +1 -1
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/package.json +1 -1
- package/src/history/electrumTransformer.test.ts +112 -55
- package/src/history/electrumTransformer.ts +279 -284
- package/src/history/interface.ts +19 -13
- package/src/interface.ts +11 -1
- package/src/network/ElectrumNetworkProvider.ts +58 -11
- package/src/network/NetworkProvider.ts +13 -3
- package/src/util/header.test.ts +34 -0
- package/src/util/header.ts +16 -0
- package/src/util/index.ts +1 -0
- package/src/wallet/Wif.ts +55 -21
|
@@ -184,7 +184,7 @@ eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__
|
|
|
184
184
|
\********************************************/
|
|
185
185
|
/***/ ((module, __webpack_exports__, __webpack_require__) => {
|
|
186
186
|
|
|
187
|
-
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 */ \"getAddressHistory\": () => (/* binding */ getAddressHistory)\n/* harmony export */ });\n/* unused harmony export getDetailedHistory */\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @bitauth/libauth */ \"./node_modules/@bitauth/libauth/build/lib/address/locking-bytecode.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @bitauth/libauth */ \"./node_modules/@bitauth/libauth/build/lib/message/transaction-encoding.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @bitauth/libauth */ \"./node_modules/@bitauth/libauth/build/lib/format/hex.js\");\n/* harmony import */ var _util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../util/derivePublicKeyHash.js */ \"./src/util/derivePublicKeyHash.ts\");\n/* harmony import */ var _util_convert_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../util/convert.js */ \"./src/util/convert.ts\");\n/* harmony import */ var _chain_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../chain.js */ \"./src/chain.ts\");\n/* harmony import */ var _util_floor_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../util/floor.js */ \"./src/util/floor.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_util_convert_js__WEBPACK_IMPORTED_MODULE_0__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__, _util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_5__]);\n([_util_convert_js__WEBPACK_IMPORTED_MODULE_0__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__, _util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_5__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\n\n\n\nasync function getAddressHistory(cashaddr, provider, unit = \"sat\", start = 0, count = 25, collapseChange = true) {\n // Get an array of raw transactions as hex\n let txnHashes = await provider.getHistory(cashaddr);\n // Assume transaction hashes will be served in chronological order\n // Slice count in from the end and count to the provided inputs\n let len = txnHashes.length;\n txnHashes = txnHashes.slice(len - start - count, len - start);\n // get the current balance in satoshis\n let currentBalance = await provider.getBalance(cashaddr);\n // Transform the hex transactions to and array of histroy item array promises.\n let txItemPromises = txnHashes.map((tx) => {\n return getDetailedHistory(cashaddr, tx.tx_hash, tx.height, provider, collapseChange);\n });\n // await the history array promises\n let items = await Promise.all(txItemPromises);\n // flatten the array of responses\n let preprocessedTxns = Array.prototype.concat.apply([], items);\n // Reverse chronological order (again), so list appear as newest first.\n preprocessedTxns = preprocessedTxns.reverse();\n // Get the factor to apply the requested unit of measure\n let factor = (await (0,_util_convert_js__WEBPACK_IMPORTED_MODULE_0__.convert)(_chain_js__WEBPACK_IMPORTED_MODULE_1__.bchParam.subUnits, \"sat\", unit)) / _chain_js__WEBPACK_IMPORTED_MODULE_1__.bchParam.subUnits;\n // Apply the unit factor and\n let txns = applyBalance(preprocessedTxns, currentBalance, unit, factor);\n return {\n transactions: txns,\n };\n}\nasync function getDetailedHistory(cashaddr, hash, height, provider, collapseChange) {\n let transactionHex = await provider.getRawTransaction(hash);\n collapseChange;\n let addressBytecode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.cashAddressToLockingBytecode)(cashaddr);\n if (typeof addressBytecode === \"string\")\n throw Error(addressBytecode);\n let transaction = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.decodeTransaction)((0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__.hexToBin)(transactionHex));\n if (typeof transaction === \"string\")\n throw Error(transaction);\n let r = [];\n r.push(...(await getMatchingInputs(transaction, cashaddr, height, hash, provider, collapseChange)));\n return r;\n}\nasync function getMatchingInputs(transaction, cashaddr, height, hash, provider, collapseChange) {\n let addressBytecode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.cashAddressToLockingBytecode)(cashaddr);\n if (typeof addressBytecode === \"string\")\n throw Error(addressBytecode);\n let lockingBytecodeHex = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__.binToHex)(addressBytecode.bytecode);\n let prefix = (0,_util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_5__.derivePrefix)(cashaddr);\n let inputUtxos = await getInputTransactions(transaction, provider);\n let fee = getFee(inputUtxos, transaction.outputs, lockingBytecodeHex, collapseChange);\n let r = [];\n let txIds = [];\n for (let input of transaction.inputs) {\n let outpoint = inputUtxos[transaction.inputs.indexOf(input)];\n // if the utxo of the input matches the address in question\n if ((0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__.binToHex)(outpoint.lockingBytecode) === lockingBytecodeHex) {\n for (let output of transaction.outputs) {\n let idx = transaction.outputs.indexOf(output);\n let from = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.lockingBytecodeToCashAddress)(outpoint.lockingBytecode, prefix);\n // the output was change\n if ((0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__.binToHex)(output.lockingBytecode) === lockingBytecodeHex) {\n if (!collapseChange) {\n r.push({\n from: from,\n to: cashaddr,\n unit: \"sat\",\n index: idx,\n blockheight: height,\n txn: `${hash}`,\n txId: `${hash}:i:${idx}`,\n value: -Number(output.valueSatoshis),\n fee: 0,\n });\n }\n }\n else {\n if (!txIds.find((str) => str === `${hash}:i:${idx}`)) {\n // the utxo was sent to another address\n let to = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.lockingBytecodeToCashAddress)(output.lockingBytecode, prefix);\n r.push({\n from: from,\n to: to,\n unit: \"sat\",\n index: idx,\n blockheight: height,\n txn: `${hash}`,\n txId: `${hash}:i:${idx}`,\n value: -Number(output.valueSatoshis),\n fee: fee,\n });\n txIds.push(`${hash}:i:${idx}`);\n }\n }\n }\n }\n }\n // check the transaction outputs for receiving transactions\n for (let output of transaction.outputs) {\n // the output was a utxo for the address in question\n if ((0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__.binToHex)(output.lockingBytecode) === lockingBytecodeHex) {\n // the input was from a single address\n if (transaction.inputs.length == 1) {\n const input = transaction.inputs[0];\n const inHash = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__.binToHex)(input.outpointTransactionHash);\n const transactionHex = await provider.getRawTransaction(inHash);\n const inTransaction = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.decodeTransaction)((0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__.hexToBin)(transactionHex));\n if (typeof inTransaction === \"string\")\n throw Error(inTransaction);\n let outpoint = inTransaction.outputs[input.outpointIndex];\n let from = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.lockingBytecodeToCashAddress)(outpoint.lockingBytecode, prefix);\n // if the utxo was from a different address and change is not being output...\n if (from !== cashaddr || !collapseChange) {\n r.push({\n from: from,\n to: cashaddr,\n unit: \"sat\",\n index: transaction.outputs.indexOf(output),\n blockheight: height,\n txn: `${hash}`,\n txId: `${hash}:o:${transaction.outputs.indexOf(output)}`,\n value: Number(output.valueSatoshis),\n });\n }\n }\n else {\n let from = transaction.inputs\n .map((i) => `${(0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__.binToHex)(i.outpointTransactionHash)}:o:${i.outpointIndex}`)\n .join(\";\");\n r.push({\n from: from,\n to: cashaddr,\n unit: \"sat\",\n index: transaction.outputs.indexOf(output),\n blockheight: height,\n txn: `${hash}`,\n txId: `${hash}:o:${transaction.outputs.indexOf(output)}`,\n value: Number(output.valueSatoshis),\n // incoming transactions pay no fee.\n fee: 0,\n });\n }\n }\n }\n return r;\n}\nasync function getInputTransactions(transaction, provider) {\n let inputTransactions = [];\n for (let input of transaction.inputs) {\n let inHash = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__.binToHex)(input.outpointTransactionHash);\n let transactionHex = await provider.getRawTransaction(inHash);\n let inTransaction = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.decodeTransaction)((0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__.hexToBin)(transactionHex));\n if (typeof inTransaction === \"string\")\n throw Error(inTransaction);\n inputTransactions.push(inTransaction.outputs[input.outpointIndex]);\n }\n return inputTransactions;\n}\nfunction getFee(inputUtxos, utxos, lockingBytecodeHex, collapseChange) {\n let inValues = 0;\n for (let outpoint of inputUtxos) {\n if ((0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__.binToHex)(outpoint.lockingBytecode)) {\n inValues += Number(outpoint.valueSatoshis);\n }\n }\n const outValues = utxos\n .map((utxo) => Number(utxo.valueSatoshis))\n .reduce((a, b) => a + b, 0);\n let fee = 0;\n if (collapseChange) {\n const nonChangeOutputs = utxos\n .map((output) => (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__.binToHex)(output.lockingBytecode) === lockingBytecodeHex ? 0 : 1)\n .reduce((a, b) => a + b, 0);\n fee = (0,_util_floor_js__WEBPACK_IMPORTED_MODULE_6__.floor)((inValues - outValues) / nonChangeOutputs, 0);\n }\n else {\n fee = (0,_util_floor_js__WEBPACK_IMPORTED_MODULE_6__.floor)((inValues - outValues) / utxos.length, 0);\n }\n return fee;\n}\nfunction applyBalance(preprocessedTxns, currentBalance, unit, factor) {\n // balance in satoshis\n let bal = currentBalance;\n let r = [];\n for (let txn of preprocessedTxns) {\n // set the balance to the current balance in the appropriate unit\n txn.balance = bal;\n // If fee is not defined, configure it to zero.\n txn.fee = txn.fee ? txn.fee : 0;\n // update the running balance in satoshis for the next record\n // a receiving value is positive, a send is negative\n // The sign is reversed in cronological order from the current balance.\n bal -= txn.value;\n bal += txn.fee;\n // transform the value of the transaction\n txn.value = txn.value * factor;\n txn.fee = txn.fee * factor;\n // If unit is usd, round to two decimal places.\n if (unit.toLowerCase() == \"usd\") {\n txn.value = (0,_util_floor_js__WEBPACK_IMPORTED_MODULE_6__.floor)(txn.value, 2);\n txn.fee = (0,_util_floor_js__WEBPACK_IMPORTED_MODULE_6__.floor)(txn.fee, 2);\n }\n // note the unit\n txn.unit = unit;\n r.push(txn);\n }\n return r;\n}\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/history/electrumTransformer.ts?");
|
|
187
|
+
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 */ \"getAddressHistory\": () => (/* binding */ getAddressHistory)\n/* harmony export */ });\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @bitauth/libauth */ \"./node_modules/@bitauth/libauth/build/lib/message/transaction-encoding.js\");\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/address/cash-address.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @bitauth/libauth */ \"./node_modules/@bitauth/libauth/build/lib/address/locking-bytecode.js\");\n/* harmony import */ var _util_convert_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../util/convert.js */ \"./src/util/convert.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__, _util_convert_js__WEBPACK_IMPORTED_MODULE_4__]);\n([_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__, _util_convert_js__WEBPACK_IMPORTED_MODULE_4__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\nconst getAddressHistory = async ({ address, provider, unit = \"sat\", fromHeight = 0, toHeight = -1, start = 0, count = -1, }) => {\n if (count === -1) {\n count = 1e10;\n }\n const history = (await provider.getHistory(address, fromHeight, toHeight))\n .sort((a, b) => a.height <= 0 || b.height <= 0 ? a.height - b.height : b.height - a.height)\n .slice(start, start + count);\n // fill transaction timestamps by requesting headers from network and parsing them\n const heights = history\n .map((tx) => tx.height)\n .filter((height) => height > 0)\n .filter((value, index, array) => array.indexOf(value) === index);\n const timestampMap = (await Promise.all(heights.map(async (height) => [\n height,\n (await provider.getHeader(height, true)).timestamp,\n ]))).reduce((acc, [height, timestamp]) => ({ ...acc, [height]: timestamp }), {});\n // first load all transactions\n const historicTransactions = await Promise.all(history.map(async (tx) => {\n const txHex = (await provider.getRawTransaction(tx.tx_hash));\n const transactionCommon = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.decodeTransaction)((0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.hexToBin)(txHex));\n if (typeof transactionCommon === \"string\") {\n throw transactionCommon;\n }\n const transaction = transactionCommon;\n transaction.blockHeight = tx.height;\n transaction.timestamp = timestampMap[tx.height];\n transaction.hash = tx.tx_hash;\n transaction.size = txHex.length / 2;\n return transaction;\n }));\n // then load their prevout transactions\n const prevoutTransactionHashes = historicTransactions\n .map((tx) => tx.inputs.map((input) => (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.binToHex)(input.outpointTransactionHash)))\n .flat()\n .filter((value, index, array) => array.indexOf(value) === index);\n const prevoutTransactionMap = (await Promise.all(prevoutTransactionHashes.map(async (hash) => {\n const txHex = (await provider.getRawTransaction(hash));\n const transaction = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.decodeTransaction)((0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.hexToBin)(txHex));\n if (typeof transaction === \"string\") {\n throw transaction;\n }\n return [hash, transaction];\n }))).reduce((acc, [hash, transaction]) => ({\n ...acc,\n [hash]: transaction,\n }), {});\n const decoded = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.decodeCashAddress)(address);\n if (typeof decoded === \"string\") {\n throw decoded;\n }\n const addressCache = {};\n // map decoded transaction data to TransactionHistoryItem\n const historyItems = historicTransactions.map((tx) => {\n const result = {};\n let inputTotalValue = 0n;\n let outputTotalValue = 0n;\n result.inputs = tx.inputs.map((input) => {\n const prevoutTx = prevoutTransactionMap[(0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.binToHex)(input.outpointTransactionHash)];\n if (!prevoutTx) {\n throw new Error(\"Could not find prevout transaction\");\n }\n const prevoutOutput = prevoutTx.outputs[input.outpointIndex];\n if (!prevoutOutput) {\n throw new Error(\"Could not find prevout output\");\n }\n const cached = addressCache[prevoutOutput.lockingBytecode];\n let address;\n if (!cached) {\n address = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.lockingBytecodeToCashAddress)(prevoutOutput.lockingBytecode, decoded.prefix);\n addressCache[prevoutOutput.lockingBytecode] = address;\n }\n else {\n address = cached;\n }\n inputTotalValue += prevoutOutput.valueSatoshis;\n return {\n address: address,\n value: Number(prevoutOutput.valueSatoshis),\n token: prevoutOutput.token\n ? {\n tokenId: (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.binToHex)(prevoutOutput.token.category),\n amount: prevoutOutput.token.amount,\n capability: prevoutOutput.token.nft?.capability\n ? prevoutOutput.token.nft.capability\n : undefined,\n commitment: prevoutOutput.token.nft?.capability\n ? (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.binToHex)(prevoutOutput.token.nft.commitment)\n : undefined,\n }\n : undefined,\n };\n });\n result.outputs = tx.outputs.map((output) => {\n const cached = addressCache[output.lockingBytecode];\n let address;\n if (!cached) {\n if (output.valueSatoshis === 0n) {\n address = `OP_RETURN: ${(0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.binToHex)(output.lockingBytecode)}`;\n }\n else {\n address = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.lockingBytecodeToCashAddress)(output.lockingBytecode, decoded.prefix);\n addressCache[output.lockingBytecode] = address;\n }\n }\n else {\n address = cached;\n }\n outputTotalValue += output.valueSatoshis;\n return {\n address: address,\n value: Number(output.valueSatoshis),\n token: output.token\n ? {\n tokenId: (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.binToHex)(output.token.category),\n amount: output.token.amount,\n capability: output.token.nft?.capability\n ? output.token.nft.capability\n : undefined,\n commitment: output.token.nft?.capability\n ? (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.binToHex)(output.token.nft.commitment)\n : undefined,\n }\n : undefined,\n };\n });\n result.blockHeight = tx.blockHeight;\n result.timestamp = tx.timestamp;\n result.hash = tx.hash;\n result.size = tx.size;\n result.fee = Number(inputTotalValue - outputTotalValue);\n return result;\n });\n // compute value changes\n historyItems.forEach((tx) => {\n let satoshiBalance = 0;\n const ftTokenBalances = {};\n const nftTokenBalances = {};\n tx.inputs.forEach((input) => {\n if (input.address === address) {\n satoshiBalance -= input.value;\n if (input.token?.amount) {\n ftTokenBalances[input.token.tokenId] =\n (ftTokenBalances[input.token.tokenId] || BigInt(0)) -\n input.token.amount;\n }\n if (input.token?.capability) {\n nftTokenBalances[input.token.tokenId] =\n (nftTokenBalances[input.token.tokenId] || BigInt(0)) - 1n;\n }\n }\n });\n tx.outputs.forEach((output) => {\n if (output.address === address) {\n satoshiBalance += Number(output.value);\n if (output.token?.amount) {\n ftTokenBalances[output.token.tokenId] =\n (ftTokenBalances[output.token.tokenId] || BigInt(0)) +\n output.token.amount;\n }\n if (output.token?.capability) {\n nftTokenBalances[output.token.tokenId] =\n (nftTokenBalances[output.token.tokenId] || BigInt(0)) + 1n;\n }\n }\n });\n tx.valueChange = satoshiBalance;\n tx.tokenAmountChanges = Object.entries(ftTokenBalances).map(([tokenId, amount]) => ({\n tokenId,\n amount,\n nftAmount: BigInt(0),\n }));\n for (const [tokenId, nftAmount] of Object.entries(nftTokenBalances)) {\n const tokenChange = tx.tokenAmountChanges.find((tokenChange) => tokenChange.tokenId === tokenId);\n if (tokenChange) {\n tokenChange.nftAmount = nftAmount;\n }\n else {\n tx.tokenAmountChanges.push({\n tokenId,\n amount: BigInt(0),\n nftAmount,\n });\n }\n }\n });\n // order transactions in a way such that receives are always ordered before sends, per block\n historyItems.sort((a, b) => (a.blockHeight <= 0 || b.blockHeight <= 0\n ? a.blockHeight - b.blockHeight\n : b.blockHeight - a.blockHeight) || a.valueChange - b.valueChange);\n // backfill the balances\n let prevBalance = await provider.getBalance(address);\n let prevValueChange = 0;\n historyItems.forEach((tx) => {\n tx.balance = prevBalance - prevValueChange;\n prevBalance = tx.balance;\n prevValueChange = tx.valueChange;\n });\n // convert units if needed\n if (!unit.includes(\"sat\")) {\n for (const tx of historyItems) {\n for (const input of tx.inputs) {\n input.value = await (0,_util_convert_js__WEBPACK_IMPORTED_MODULE_4__.convert)(input.value, \"sat\", unit);\n }\n for (const output of tx.outputs) {\n output.value = await (0,_util_convert_js__WEBPACK_IMPORTED_MODULE_4__.convert)(output.value, \"sat\", unit);\n }\n tx.valueChange = await (0,_util_convert_js__WEBPACK_IMPORTED_MODULE_4__.convert)(tx.valueChange, \"sat\", unit);\n tx.balance = await (0,_util_convert_js__WEBPACK_IMPORTED_MODULE_4__.convert)(tx.balance, \"sat\", unit);\n }\n }\n return historyItems;\n};\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/history/electrumTransformer.ts?");
|
|
188
188
|
|
|
189
189
|
/***/ }),
|
|
190
190
|
|
|
@@ -194,7 +194,7 @@ eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__
|
|
|
194
194
|
\**********************/
|
|
195
195
|
/***/ ((module, __webpack_exports__, __webpack_require__) => {
|
|
196
196
|
|
|
197
|
-
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 */ \"BCMR\": () => (/* reexport safe */ _wallet_Bcmr_js__WEBPACK_IMPORTED_MODULE_4__.BCMR),\n/* harmony export */ \"BaseWallet\": () => (/* reexport safe */ _wallet_Base_js__WEBPACK_IMPORTED_MODULE_7__.BaseWallet),\n/* harmony export */ \"CONST\": () => (/* reexport module object */ _constant_js__WEBPACK_IMPORTED_MODULE_18__),\n/* harmony export */ \"Config\": () => (/* reexport safe */ _config_js__WEBPACK_IMPORTED_MODULE_11__.Config),\n/* harmony export */ \"Connection\": () => (/* reexport safe */ _network_index_js__WEBPACK_IMPORTED_MODULE_5__.Connection),\n/* harmony export */ \"DefaultProvider\": () => (/* reexport safe */ _network_configuration_js__WEBPACK_IMPORTED_MODULE_10__.DefaultProvider),\n/* harmony export */ \"ElectrumNetworkProvider\": () => (/* reexport safe */ _network_index_js__WEBPACK_IMPORTED_MODULE_5__.ElectrumNetworkProvider),\n/* harmony export */ \"ExchangeRate\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.ExchangeRate),\n/* harmony export */ \"FeePaidByEnum\": () => (/* reexport safe */ _wallet_enum_js__WEBPACK_IMPORTED_MODULE_13__.FeePaidByEnum),\n/* harmony export */ \"Mainnet\": () => (/* reexport module object */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__),\n/* harmony export */ \"NFTCapability\": () => (/* reexport safe */ _interface_js__WEBPACK_IMPORTED_MODULE_19__.NFTCapability),\n/* harmony export */ \"Network\": () => (/* reexport safe */ _interface_js__WEBPACK_IMPORTED_MODULE_19__.Network),\n/* harmony export */ \"NetworkType\": () => (/* reexport safe */ _enum_js__WEBPACK_IMPORTED_MODULE_12__.NetworkType),\n/* harmony export */ \"OpReturnData\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_14__.OpReturnData),\n/* harmony export */ \"RegTestWallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__.RegTestWallet),\n/* harmony export */ \"RegTestWatchWallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__.RegTestWatchWallet),\n/* harmony export */ \"RegTestWifWallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__.RegTestWifWallet),\n/* harmony export */ \"RuntimePlatform\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.RuntimePlatform),\n/* harmony export */ \"SendRequest\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_14__.SendRequest),\n/* harmony export */ \"SendResponse\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_14__.SendResponse),\n/* harmony export */ \"SignedMessage\": () => (/* reexport safe */ _message_signed_js__WEBPACK_IMPORTED_MODULE_6__.SignedMessage),\n/* harmony export */ \"StorageProvider\": () => (/* reexport safe */ _db_index_js__WEBPACK_IMPORTED_MODULE_2__.StorageProvider),\n/* harmony export */ \"TestNetWallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__.TestNetWallet),\n/* harmony export */ \"TestNetWatchWallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__.TestNetWatchWallet),\n/* harmony export */ \"TestNetWifWallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__.TestNetWifWallet),\n/* harmony export */ \"TokenBurnRequest\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_14__.TokenBurnRequest),\n/* harmony export */ \"TokenGenesisRequest\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_14__.TokenGenesisRequest),\n/* harmony export */ \"TokenMintRequest\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_14__.TokenMintRequest),\n/* harmony export */ \"TokenSendRequest\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_14__.TokenSendRequest),\n/* harmony export */ \"UnitEnum\": () => (/* reexport safe */ _enum_js__WEBPACK_IMPORTED_MODULE_12__.UnitEnum),\n/* harmony export */ \"Wallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__.Wallet),\n/* harmony export */ \"WalletTypeEnum\": () => (/* reexport safe */ _wallet_enum_js__WEBPACK_IMPORTED_MODULE_13__.WalletTypeEnum),\n/* harmony export */ \"WatchWallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__.WatchWallet),\n/* harmony export */ \"WifWallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__.WifWallet),\n/* harmony export */ \"XPubKey\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_14__.XPubKey),\n/* harmony export */ \"amountInSatoshi\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.amountInSatoshi),\n/* harmony export */ \"asSendRequestObject\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.asSendRequestObject),\n/* harmony export */ \"atob\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.atob),\n/* harmony export */ \"balanceFromSatoshi\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.balanceFromSatoshi),\n/* harmony export */ \"balanceResponseFromSatoshi\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.balanceResponseFromSatoshi),\n/* harmony export */ \"binToBase64\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.binToBase64),\n/* harmony export */ \"binToHex\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.binToHex),\n/* harmony export */ \"btoa\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.btoa),\n/* harmony export */ \"checkTokenaddr\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.checkTokenaddr),\n/* harmony export */ \"convert\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.convert),\n/* harmony export */ \"convertObject\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.convertObject),\n/* harmony export */ \"createWallet\": () => (/* reexport safe */ _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_9__.createWallet),\n/* harmony export */ \"createWalletResponse\": () => (/* reexport safe */ _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_9__.createWalletResponse),\n/* harmony export */ \"delay\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.delay),\n/* harmony export */ \"deriveCashaddr\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.deriveCashaddr),\n/* harmony export */ \"derivePublicKeyHash\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.derivePublicKeyHash),\n/* harmony export */ \"deriveTokenaddr\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.deriveTokenaddr),\n/* harmony export */ \"derivedNetwork\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.derivedNetwork),\n/* harmony export */ \"disconnectProviders\": () => (/* reexport safe */ _network_index_js__WEBPACK_IMPORTED_MODULE_5__.disconnectProviders),\n/* harmony export */ \"expect\": () => (/* reexport safe */ _test_expect_js__WEBPACK_IMPORTED_MODULE_1__.expect),\n/* harmony export */ \"fromUtxoId\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_14__.fromUtxoId),\n/* harmony export */ \"getAddrsByXpubKey\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.getAddrsByXpubKey),\n/* harmony export */ \"getAddrsByXpubKeyObject\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.getAddrsByXpubKeyObject),\n/* harmony export */ \"getNetworkProvider\": () => (/* reexport safe */ _network_index_js__WEBPACK_IMPORTED_MODULE_5__.getNetworkProvider),\n/* harmony export */ \"getRuntimePlatform\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.getRuntimePlatform),\n/* harmony export */ \"getUsdRate\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.getUsdRate),\n/* harmony export */ \"getWeakRandomInt\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.getWeakRandomInt),\n/* harmony export */ \"getXPubKey\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.getXPubKey),\n/* harmony export */ \"getXpubKeyInfo\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.getXpubKeyInfo),\n/* harmony export */ \"getXpubKeyInfoObject\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.getXpubKeyInfoObject),\n/* harmony export */ \"hash160\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.hash160),\n/* harmony export */ \"hexToBin\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.hexToBin),\n/* harmony export */ \"initProviders\": () => (/* reexport safe */ _network_index_js__WEBPACK_IMPORTED_MODULE_5__.initProviders),\n/* harmony export */ \"isTokenaddr\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.isTokenaddr),\n/* harmony export */ \"isValidAddress\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.isValidAddress),\n/* harmony export */ \"libauth\": () => (/* reexport module object */ _libauth_js__WEBPACK_IMPORTED_MODULE_16__),\n/* harmony export */ \"mine\": () => (/* reexport safe */ _mine_index_js__WEBPACK_IMPORTED_MODULE_3__.mine),\n/* harmony export */ \"namedWallet\": () => (/* reexport safe */ _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_9__.namedWallet),\n/* harmony export */ \"namedWalletExists\": () => (/* reexport safe */ _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_9__.namedWalletExists),\n/* harmony export */ \"qrAddress\": () => (/* reexport safe */ _qr_Qr_js__WEBPACK_IMPORTED_MODULE_17__.qrAddress),\n/* harmony export */ \"removeFetchMock\": () => (/* reexport safe */ _test_fetch_js__WEBPACK_IMPORTED_MODULE_0__.removeFetchMock),\n/* harmony export */ \"replaceNamedWallet\": () => (/* reexport safe */ _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_9__.replaceNamedWallet),\n/* harmony export */ \"sanitizeAddress\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.sanitizeAddress),\n/* harmony export */ \"sanitizeUnit\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.sanitizeUnit),\n/* harmony export */ \"setupFetchMock\": () => (/* reexport safe */ _test_fetch_js__WEBPACK_IMPORTED_MODULE_0__.setupFetchMock),\n/* harmony export */ \"sha256\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.sha256),\n/* harmony export */ \"sumTokenAmounts\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.sumTokenAmounts),\n/* harmony export */ \"sumUtxoValue\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.sumUtxoValue),\n/* harmony export */ \"toCashaddr\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.toCashaddr),\n/* harmony export */ \"toTokenaddr\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.toTokenaddr),\n/* harmony export */ \"toUtxoId\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_14__.toUtxoId),\n/* harmony export */ \"utf8ToBin\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.utf8ToBin),\n/* harmony export */ \"walletClassMap\": () => (/* reexport safe */ _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_9__.walletClassMap),\n/* harmony export */ \"walletFromId\": () => (/* reexport safe */ _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_9__.walletFromId)\n/* harmony export */ });\n/* harmony import */ var _test_fetch_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./test/fetch.js */ \"./src/test/fetch.ts\");\n/* harmony import */ var _test_expect_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./test/expect.js */ \"./src/test/expect.ts\");\n/* harmony import */ var _db_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./db/index.js */ \"./src/db/index.ts\");\n/* harmony import */ var _mine_index_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./mine/index.js */ \"./src/mine/index.ts\");\n/* harmony import */ var _wallet_Bcmr_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./wallet/Bcmr.js */ \"./src/wallet/Bcmr.ts\");\n/* harmony import */ var _network_index_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./network/index.js */ \"./src/network/index.ts\");\n/* harmony import */ var _message_signed_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./message/signed.js */ \"./src/message/signed.ts\");\n/* harmony import */ var _wallet_Base_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./wallet/Base.js */ \"./src/wallet/Base.ts\");\n/* harmony import */ var _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./wallet/Wif.js */ \"./src/wallet/Wif.ts\");\n/* harmony import */ var _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./wallet/createWallet.js */ \"./src/wallet/createWallet.ts\");\n/* harmony import */ var _network_configuration_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./network/configuration.js */ \"./src/network/configuration.ts\");\n/* harmony import */ var _config_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./config.js */ \"./src/config.ts\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./enum.js */ \"./src/enum.ts\");\n/* harmony import */ var _wallet_enum_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./wallet/enum.js */ \"./src/wallet/enum.ts\");\n/* harmony import */ var _wallet_model_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./wallet/model.js */ \"./src/wallet/model.ts\");\n/* harmony import */ var _util_index_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./util/index.js */ \"./src/util/index.ts\");\n/* harmony import */ var _libauth_js__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./libauth.js */ \"./src/libauth.ts\");\n/* harmony import */ var _qr_Qr_js__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./qr/Qr.js */ \"./src/qr/Qr.ts\");\n/* harmony import */ var _constant_js__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./constant.js */ \"./src/constant.ts\");\n/* harmony import */ var _interface_js__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./interface.js */ \"./src/interface.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_wallet_Bcmr_js__WEBPACK_IMPORTED_MODULE_4__, _network_index_js__WEBPACK_IMPORTED_MODULE_5__, _message_signed_js__WEBPACK_IMPORTED_MODULE_6__, _wallet_Base_js__WEBPACK_IMPORTED_MODULE_7__, _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__, _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_9__, _network_configuration_js__WEBPACK_IMPORTED_MODULE_10__, _config_js__WEBPACK_IMPORTED_MODULE_11__, _enum_js__WEBPACK_IMPORTED_MODULE_12__, _wallet_model_js__WEBPACK_IMPORTED_MODULE_14__, _util_index_js__WEBPACK_IMPORTED_MODULE_15__, _libauth_js__WEBPACK_IMPORTED_MODULE_16__, _qr_Qr_js__WEBPACK_IMPORTED_MODULE_17__]);\n([_wallet_Bcmr_js__WEBPACK_IMPORTED_MODULE_4__, _network_index_js__WEBPACK_IMPORTED_MODULE_5__, _message_signed_js__WEBPACK_IMPORTED_MODULE_6__, _wallet_Base_js__WEBPACK_IMPORTED_MODULE_7__, _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__, _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_9__, _network_configuration_js__WEBPACK_IMPORTED_MODULE_10__, _config_js__WEBPACK_IMPORTED_MODULE_11__, _enum_js__WEBPACK_IMPORTED_MODULE_12__, _wallet_model_js__WEBPACK_IMPORTED_MODULE_14__, _util_index_js__WEBPACK_IMPORTED_MODULE_15__, _libauth_js__WEBPACK_IMPORTED_MODULE_16__, _qr_Qr_js__WEBPACK_IMPORTED_MODULE_17__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\n\n\n\n\n\n\n\n\n\n// provider\n\n// config\n\n// Enum\n\n\n// models\n\n// utils\n\n\n\n// libauth\n\n// qr\n\n// constants\n\n\n// interfaces\n\n\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/index.ts?");
|
|
197
|
+
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 */ \"BCMR\": () => (/* reexport safe */ _wallet_Bcmr_js__WEBPACK_IMPORTED_MODULE_4__.BCMR),\n/* harmony export */ \"BaseWallet\": () => (/* reexport safe */ _wallet_Base_js__WEBPACK_IMPORTED_MODULE_7__.BaseWallet),\n/* harmony export */ \"CONST\": () => (/* reexport module object */ _constant_js__WEBPACK_IMPORTED_MODULE_18__),\n/* harmony export */ \"Config\": () => (/* reexport safe */ _config_js__WEBPACK_IMPORTED_MODULE_11__.Config),\n/* harmony export */ \"Connection\": () => (/* reexport safe */ _network_index_js__WEBPACK_IMPORTED_MODULE_5__.Connection),\n/* harmony export */ \"DefaultProvider\": () => (/* reexport safe */ _network_configuration_js__WEBPACK_IMPORTED_MODULE_10__.DefaultProvider),\n/* harmony export */ \"ElectrumNetworkProvider\": () => (/* reexport safe */ _network_index_js__WEBPACK_IMPORTED_MODULE_5__.ElectrumNetworkProvider),\n/* harmony export */ \"ExchangeRate\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.ExchangeRate),\n/* harmony export */ \"FeePaidByEnum\": () => (/* reexport safe */ _wallet_enum_js__WEBPACK_IMPORTED_MODULE_13__.FeePaidByEnum),\n/* harmony export */ \"Mainnet\": () => (/* reexport module object */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__),\n/* harmony export */ \"NFTCapability\": () => (/* reexport safe */ _interface_js__WEBPACK_IMPORTED_MODULE_19__.NFTCapability),\n/* harmony export */ \"Network\": () => (/* reexport safe */ _interface_js__WEBPACK_IMPORTED_MODULE_19__.Network),\n/* harmony export */ \"NetworkType\": () => (/* reexport safe */ _enum_js__WEBPACK_IMPORTED_MODULE_12__.NetworkType),\n/* harmony export */ \"OpReturnData\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_14__.OpReturnData),\n/* harmony export */ \"RegTestWallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__.RegTestWallet),\n/* harmony export */ \"RegTestWatchWallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__.RegTestWatchWallet),\n/* harmony export */ \"RegTestWifWallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__.RegTestWifWallet),\n/* harmony export */ \"RuntimePlatform\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.RuntimePlatform),\n/* harmony export */ \"SendRequest\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_14__.SendRequest),\n/* harmony export */ \"SendResponse\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_14__.SendResponse),\n/* harmony export */ \"SignedMessage\": () => (/* reexport safe */ _message_signed_js__WEBPACK_IMPORTED_MODULE_6__.SignedMessage),\n/* harmony export */ \"StorageProvider\": () => (/* reexport safe */ _db_index_js__WEBPACK_IMPORTED_MODULE_2__.StorageProvider),\n/* harmony export */ \"TestNetWallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__.TestNetWallet),\n/* harmony export */ \"TestNetWatchWallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__.TestNetWatchWallet),\n/* harmony export */ \"TestNetWifWallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__.TestNetWifWallet),\n/* harmony export */ \"TokenBurnRequest\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_14__.TokenBurnRequest),\n/* harmony export */ \"TokenGenesisRequest\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_14__.TokenGenesisRequest),\n/* harmony export */ \"TokenMintRequest\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_14__.TokenMintRequest),\n/* harmony export */ \"TokenSendRequest\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_14__.TokenSendRequest),\n/* harmony export */ \"UnitEnum\": () => (/* reexport safe */ _enum_js__WEBPACK_IMPORTED_MODULE_12__.UnitEnum),\n/* harmony export */ \"Wallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__.Wallet),\n/* harmony export */ \"WalletTypeEnum\": () => (/* reexport safe */ _wallet_enum_js__WEBPACK_IMPORTED_MODULE_13__.WalletTypeEnum),\n/* harmony export */ \"WatchWallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__.WatchWallet),\n/* harmony export */ \"WifWallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__.WifWallet),\n/* harmony export */ \"XPubKey\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_14__.XPubKey),\n/* harmony export */ \"amountInSatoshi\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.amountInSatoshi),\n/* harmony export */ \"asSendRequestObject\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.asSendRequestObject),\n/* harmony export */ \"atob\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.atob),\n/* harmony export */ \"balanceFromSatoshi\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.balanceFromSatoshi),\n/* harmony export */ \"balanceResponseFromSatoshi\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.balanceResponseFromSatoshi),\n/* harmony export */ \"binToBase64\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.binToBase64),\n/* harmony export */ \"binToHex\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.binToHex),\n/* harmony export */ \"btoa\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.btoa),\n/* harmony export */ \"checkTokenaddr\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.checkTokenaddr),\n/* harmony export */ \"convert\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.convert),\n/* harmony export */ \"convertObject\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.convertObject),\n/* harmony export */ \"createWallet\": () => (/* reexport safe */ _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_9__.createWallet),\n/* harmony export */ \"createWalletResponse\": () => (/* reexport safe */ _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_9__.createWalletResponse),\n/* harmony export */ \"decodeHeader\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.decodeHeader),\n/* harmony export */ \"delay\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.delay),\n/* harmony export */ \"deriveCashaddr\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.deriveCashaddr),\n/* harmony export */ \"derivePublicKeyHash\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.derivePublicKeyHash),\n/* harmony export */ \"deriveTokenaddr\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.deriveTokenaddr),\n/* harmony export */ \"derivedNetwork\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.derivedNetwork),\n/* harmony export */ \"disconnectProviders\": () => (/* reexport safe */ _network_index_js__WEBPACK_IMPORTED_MODULE_5__.disconnectProviders),\n/* harmony export */ \"expect\": () => (/* reexport safe */ _test_expect_js__WEBPACK_IMPORTED_MODULE_1__.expect),\n/* harmony export */ \"fromUtxoId\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_14__.fromUtxoId),\n/* harmony export */ \"getAddrsByXpubKey\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.getAddrsByXpubKey),\n/* harmony export */ \"getAddrsByXpubKeyObject\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.getAddrsByXpubKeyObject),\n/* harmony export */ \"getNetworkProvider\": () => (/* reexport safe */ _network_index_js__WEBPACK_IMPORTED_MODULE_5__.getNetworkProvider),\n/* harmony export */ \"getRuntimePlatform\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.getRuntimePlatform),\n/* harmony export */ \"getUsdRate\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.getUsdRate),\n/* harmony export */ \"getWeakRandomInt\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.getWeakRandomInt),\n/* harmony export */ \"getXPubKey\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.getXPubKey),\n/* harmony export */ \"getXpubKeyInfo\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.getXpubKeyInfo),\n/* harmony export */ \"getXpubKeyInfoObject\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.getXpubKeyInfoObject),\n/* harmony export */ \"hash160\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.hash160),\n/* harmony export */ \"hexToBin\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.hexToBin),\n/* harmony export */ \"initProviders\": () => (/* reexport safe */ _network_index_js__WEBPACK_IMPORTED_MODULE_5__.initProviders),\n/* harmony export */ \"isTokenaddr\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.isTokenaddr),\n/* harmony export */ \"isValidAddress\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.isValidAddress),\n/* harmony export */ \"libauth\": () => (/* reexport module object */ _libauth_js__WEBPACK_IMPORTED_MODULE_16__),\n/* harmony export */ \"mine\": () => (/* reexport safe */ _mine_index_js__WEBPACK_IMPORTED_MODULE_3__.mine),\n/* harmony export */ \"namedWallet\": () => (/* reexport safe */ _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_9__.namedWallet),\n/* harmony export */ \"namedWalletExists\": () => (/* reexport safe */ _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_9__.namedWalletExists),\n/* harmony export */ \"qrAddress\": () => (/* reexport safe */ _qr_Qr_js__WEBPACK_IMPORTED_MODULE_17__.qrAddress),\n/* harmony export */ \"removeFetchMock\": () => (/* reexport safe */ _test_fetch_js__WEBPACK_IMPORTED_MODULE_0__.removeFetchMock),\n/* harmony export */ \"replaceNamedWallet\": () => (/* reexport safe */ _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_9__.replaceNamedWallet),\n/* harmony export */ \"sanitizeAddress\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.sanitizeAddress),\n/* harmony export */ \"sanitizeUnit\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.sanitizeUnit),\n/* harmony export */ \"setupFetchMock\": () => (/* reexport safe */ _test_fetch_js__WEBPACK_IMPORTED_MODULE_0__.setupFetchMock),\n/* harmony export */ \"sha256\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.sha256),\n/* harmony export */ \"sumTokenAmounts\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.sumTokenAmounts),\n/* harmony export */ \"sumUtxoValue\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.sumUtxoValue),\n/* harmony export */ \"toCashaddr\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.toCashaddr),\n/* harmony export */ \"toTokenaddr\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.toTokenaddr),\n/* harmony export */ \"toUtxoId\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_14__.toUtxoId),\n/* harmony export */ \"utf8ToBin\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.utf8ToBin),\n/* harmony export */ \"walletClassMap\": () => (/* reexport safe */ _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_9__.walletClassMap),\n/* harmony export */ \"walletFromId\": () => (/* reexport safe */ _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_9__.walletFromId)\n/* harmony export */ });\n/* harmony import */ var _test_fetch_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./test/fetch.js */ \"./src/test/fetch.ts\");\n/* harmony import */ var _test_expect_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./test/expect.js */ \"./src/test/expect.ts\");\n/* harmony import */ var _db_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./db/index.js */ \"./src/db/index.ts\");\n/* harmony import */ var _mine_index_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./mine/index.js */ \"./src/mine/index.ts\");\n/* harmony import */ var _wallet_Bcmr_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./wallet/Bcmr.js */ \"./src/wallet/Bcmr.ts\");\n/* harmony import */ var _network_index_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./network/index.js */ \"./src/network/index.ts\");\n/* harmony import */ var _message_signed_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./message/signed.js */ \"./src/message/signed.ts\");\n/* harmony import */ var _wallet_Base_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./wallet/Base.js */ \"./src/wallet/Base.ts\");\n/* harmony import */ var _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./wallet/Wif.js */ \"./src/wallet/Wif.ts\");\n/* harmony import */ var _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./wallet/createWallet.js */ \"./src/wallet/createWallet.ts\");\n/* harmony import */ var _network_configuration_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./network/configuration.js */ \"./src/network/configuration.ts\");\n/* harmony import */ var _config_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./config.js */ \"./src/config.ts\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./enum.js */ \"./src/enum.ts\");\n/* harmony import */ var _wallet_enum_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./wallet/enum.js */ \"./src/wallet/enum.ts\");\n/* harmony import */ var _wallet_model_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./wallet/model.js */ \"./src/wallet/model.ts\");\n/* harmony import */ var _util_index_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./util/index.js */ \"./src/util/index.ts\");\n/* harmony import */ var _libauth_js__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./libauth.js */ \"./src/libauth.ts\");\n/* harmony import */ var _qr_Qr_js__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./qr/Qr.js */ \"./src/qr/Qr.ts\");\n/* harmony import */ var _constant_js__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./constant.js */ \"./src/constant.ts\");\n/* harmony import */ var _interface_js__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./interface.js */ \"./src/interface.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_wallet_Bcmr_js__WEBPACK_IMPORTED_MODULE_4__, _network_index_js__WEBPACK_IMPORTED_MODULE_5__, _message_signed_js__WEBPACK_IMPORTED_MODULE_6__, _wallet_Base_js__WEBPACK_IMPORTED_MODULE_7__, _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__, _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_9__, _network_configuration_js__WEBPACK_IMPORTED_MODULE_10__, _config_js__WEBPACK_IMPORTED_MODULE_11__, _enum_js__WEBPACK_IMPORTED_MODULE_12__, _wallet_model_js__WEBPACK_IMPORTED_MODULE_14__, _util_index_js__WEBPACK_IMPORTED_MODULE_15__, _libauth_js__WEBPACK_IMPORTED_MODULE_16__, _qr_Qr_js__WEBPACK_IMPORTED_MODULE_17__]);\n([_wallet_Bcmr_js__WEBPACK_IMPORTED_MODULE_4__, _network_index_js__WEBPACK_IMPORTED_MODULE_5__, _message_signed_js__WEBPACK_IMPORTED_MODULE_6__, _wallet_Base_js__WEBPACK_IMPORTED_MODULE_7__, _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__, _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_9__, _network_configuration_js__WEBPACK_IMPORTED_MODULE_10__, _config_js__WEBPACK_IMPORTED_MODULE_11__, _enum_js__WEBPACK_IMPORTED_MODULE_12__, _wallet_model_js__WEBPACK_IMPORTED_MODULE_14__, _util_index_js__WEBPACK_IMPORTED_MODULE_15__, _libauth_js__WEBPACK_IMPORTED_MODULE_16__, _qr_Qr_js__WEBPACK_IMPORTED_MODULE_17__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\n\n\n\n\n\n\n\n\n\n// provider\n\n// config\n\n// Enum\n\n\n// models\n\n// utils\n\n\n\n// libauth\n\n// qr\n\n// constants\n\n\n// interfaces\n\n\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/index.ts?");
|
|
198
198
|
|
|
199
199
|
/***/ }),
|
|
200
200
|
|
|
@@ -264,7 +264,7 @@ eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__
|
|
|
264
264
|
\************************************************/
|
|
265
265
|
/***/ ((module, __webpack_exports__, __webpack_require__) => {
|
|
266
266
|
|
|
267
|
-
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__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! electrum-cash */ \"../../node_modules/electrum-cash/dist/index.mjs.js\");\n/* harmony import */ var _interface_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../interface.js */ \"./src/interface.ts\");\n/* harmony import */ var _util_delay_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../util/delay.js */ \"./src/util/delay.ts\");\n/* harmony import */ var _util_transaction_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../util/transaction.js */ \"./src/util/transaction.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__, _util_transaction_js__WEBPACK_IMPORTED_MODULE_3__]);\n([_config_js__WEBPACK_IMPORTED_MODULE_2__, _util_transaction_js__WEBPACK_IMPORTED_MODULE_3__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\n\n\n\nclass ElectrumNetworkProvider {\n constructor(electrum, network = _interface_js__WEBPACK_IMPORTED_MODULE_1__.Network.MAINNET, manualConnectionManagement) {\n this.network = network;\n this.manualConnectionManagement = manualConnectionManagement;\n this.subscriptions = 0;\n this.blockHeight = 0;\n if (electrum) {\n this.electrum = electrum;\n this.connectPromise = this.getConnectPromise();\n if (this.electrum instanceof electrum_cash__WEBPACK_IMPORTED_MODULE_0__.ElectrumCluster) {\n this.version = this.electrum.version;\n }\n else {\n this.version = this.electrum.connection.version;\n }\n }\n else {\n throw new Error(`A electrum-cash cluster or 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 if (this.electrum instanceof electrum_cash__WEBPACK_IMPORTED_MODULE_0__.ElectrumCluster) {\n try {\n await this.connectCluster();\n }\n catch (e) {\n console.warn(`Unable to connect to one or more electrum-cash hosts: ${JSON.stringify(e)}`);\n }\n resolve(await this.readyCluster());\n }\n else {\n resolve(await this.connectClient());\n }\n }),\n // new Promise(\n // (_resolve, reject) =>\n // (timeoutHandle = setTimeout(() => {\n // reject(\n // new Error(`Timeout connecting to electrum network: ${this.network}`)\n // );\n // }, _timeout))\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 getBlockHeight() {\n return (await this.performRequest(\"blockchain.headers.get_tip\"))\n .height;\n }\n async getRawTransaction(txHash, verbose = false, loadInputValues = false) {\n const key = `${this.network}-${txHash}-${verbose}-${loadInputValues}`;\n if (_config_js__WEBPACK_IMPORTED_MODULE_2__.Config.UseLocalStorageCache) {\n const cached = localStorage.getItem(key);\n if (cached) {\n return verbose ? JSON.parse(cached) : cached;\n }\n }\n else {\n ElectrumNetworkProvider.rawTransactionCache[key];\n }\n try {\n const transaction = (await this.performRequest(\"blockchain.transaction.get\", txHash, verbose));\n if (_config_js__WEBPACK_IMPORTED_MODULE_2__.Config.UseLocalStorageCache) {\n localStorage.setItem(key, verbose\n ? JSON.stringify(transaction)\n : transaction);\n }\n else {\n ElectrumNetworkProvider.rawTransactionCache[key] = 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_3__.getTransactionHash)(txHex);\n if (!awaitPropagation) {\n this.performRequest(\"blockchain.transaction.broadcast\", txHex);\n resolve(txHash);\n }\n else {\n const waitForTransactionCallback = async (data) => {\n if (data && data[0] === txHash) {\n this.unsubscribeFromTransaction(txHash, waitForTransactionCallback);\n resolve(txHash);\n }\n };\n this.subscribeToTransaction(txHash, waitForTransactionCallback);\n this.performRequest(\"blockchain.transaction.broadcast\", txHex).catch((error) => {\n this.unsubscribeFromTransaction(txHash, waitForTransactionCallback);\n reject(error);\n });\n }\n });\n }\n // Get transaction history of a given cashaddr\n async getHistory(cashaddr) {\n const result = (await this.performRequest(\"blockchain.address.get_history\", cashaddr));\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 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 this.subscribeToAddress(cashaddr, watchAddressStatusCallback);\n return async () => {\n await this.unsubscribeFromAddress(cashaddr, watchAddressStatusCallback);\n };\n }\n 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 watchAddressTransactions(cashaddr, callback) {\n return this.watchAddress(cashaddr, async (txHash) => {\n const tx = await this.getRawTransactionObject(txHash);\n callback(tx);\n });\n }\n 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 // Wait for the next block or a block at given blockchain height.\n watchBlocks(callback) {\n let acknowledged = false;\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 this.subscribeToHeaders(waitForBlockCallback);\n return async () => {\n this.unsubscribeFromHeaders(waitForBlockCallback);\n };\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 const cancelWatch = this.watchBlocks(async (header) => {\n if (height === undefined || header.height >= height) {\n await cancelWatch();\n resolve(header);\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 await this.subscribeRequest(\"blockchain.headers.subscribe\", callback);\n }\n // unsubscribe to notifications sent when new block is found\n async unsubscribeFromHeaders(callback) {\n await this.unsubscribeRequest(\"blockchain.headers.subscribe\", callback);\n }\n async subscribeToAddress(cashaddr, callback) {\n await this.subscribeRequest(\"blockchain.address.subscribe\", callback, cashaddr);\n }\n async unsubscribeFromAddress(cashaddr, callback) {\n await this.unsubscribeRequest(\"blockchain.address.subscribe\", callback, cashaddr);\n }\n async subscribeToAddressTransactions(cashaddr, callback) {\n await this.subscribeRequest(\"blockchain.address.transactions.subscribe\", callback, cashaddr);\n }\n async unsubscribeFromAddressTransactions(cashaddr, callback) {\n await this.unsubscribeRequest(\"blockchain.address.transactions.subscribe\", callback, cashaddr);\n }\n async subscribeToTransaction(txHash, callback) {\n await this.subscribeRequest(\"blockchain.transaction.subscribe\", callback, txHash);\n }\n async unsubscribeFromTransaction(txHash, callback) {\n await this.unsubscribeRequest(\"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 subscribeRequest(methodName, callback, ...parameters) {\n await this.ready();\n const result = await this.electrum.subscribe(callback, methodName, ...parameters);\n this.subscriptions++;\n return result;\n }\n async unsubscribeRequest(methodName, callback, ...parameters) {\n await this.ready();\n const result = this.electrum.unsubscribe(callback, methodName, ...parameters);\n this.subscriptions--;\n return result;\n }\n async ready() {\n return (await this.connect());\n }\n async connect() {\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.isElectrumClient()\n ? this.disconnectClient()\n : this.disconnectCluster();\n }\n isElectrumClient() {\n return this.electrum.hasOwnProperty(\"connection\");\n }\n async readyClient(timeout) {\n timeout = typeof timeout !== \"undefined\" ? timeout : 3000;\n let connectPromise = async () => {\n while (this.electrum.connection.status !==\n electrum_cash__WEBPACK_IMPORTED_MODULE_0__.ConnectionStatus.CONNECTED) {\n await (0,_util_delay_js__WEBPACK_IMPORTED_MODULE_4__.delay)(100);\n }\n return true;\n };\n return connectPromise;\n }\n async readyCluster(timeout) {\n timeout;\n return this.electrum.ready();\n }\n async connectCluster() {\n return this.electrum.startup();\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.connection.host}.`, e);\n return;\n }\n };\n return [await connectionPromise()];\n }\n async disconnectCluster() {\n return this.electrum.shutdown();\n }\n async disconnectClient() {\n return [await this.electrum.disconnect(true)];\n }\n}\nElectrumNetworkProvider.rawTransactionCache = {};\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/network/ElectrumNetworkProvider.ts?");
|
|
267
|
+
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__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! electrum-cash */ \"../../node_modules/electrum-cash/dist/index.mjs.js\");\n/* harmony import */ var _interface_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../interface.js */ \"./src/interface.ts\");\n/* harmony import */ var _util_delay_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../util/delay.js */ \"./src/util/delay.ts\");\n/* harmony import */ var _util_transaction_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../util/transaction.js */ \"./src/util/transaction.ts\");\n/* harmony import */ var _config_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../config.js */ \"./src/config.ts\");\n/* harmony import */ var _util_header_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../util/header.js */ \"./src/util/header.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_config_js__WEBPACK_IMPORTED_MODULE_2__, _util_transaction_js__WEBPACK_IMPORTED_MODULE_4__]);\n([_config_js__WEBPACK_IMPORTED_MODULE_2__, _util_transaction_js__WEBPACK_IMPORTED_MODULE_4__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\n\n\n\n\nclass ElectrumNetworkProvider {\n constructor(electrum, network = _interface_js__WEBPACK_IMPORTED_MODULE_1__.Network.MAINNET, manualConnectionManagement) {\n this.network = network;\n this.manualConnectionManagement = manualConnectionManagement;\n this.subscriptions = 0;\n this.blockHeight = 0;\n if (electrum) {\n this.electrum = electrum;\n this.connectPromise = this.getConnectPromise();\n if (this.electrum instanceof electrum_cash__WEBPACK_IMPORTED_MODULE_0__.ElectrumCluster) {\n this.version = this.electrum.version;\n }\n else {\n this.version = this.electrum.connection.version;\n }\n }\n else {\n throw new Error(`A electrum-cash cluster or 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 if (this.electrum instanceof electrum_cash__WEBPACK_IMPORTED_MODULE_0__.ElectrumCluster) {\n try {\n await this.connectCluster();\n }\n catch (e) {\n console.warn(`Unable to connect to one or more electrum-cash hosts: ${JSON.stringify(e)}`);\n }\n resolve(await this.readyCluster());\n }\n else {\n resolve(await this.connectClient());\n }\n }),\n // new Promise(\n // (_resolve, reject) =>\n // (timeoutHandle = setTimeout(() => {\n // reject(\n // new Error(`Timeout connecting to electrum network: ${this.network}`)\n // );\n // }, _timeout))\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 (_config_js__WEBPACK_IMPORTED_MODULE_2__.Config.UseLocalStorageCache) {\n const cached = localStorage.getItem(key);\n if (cached) {\n return verbose ? (0,_util_header_js__WEBPACK_IMPORTED_MODULE_3__.decodeHeader)(JSON.parse(cached)) : JSON.parse(cached);\n }\n }\n else {\n ElectrumNetworkProvider.rawTransactionCache[key];\n }\n const result = (await this.performRequest(\"blockchain.header.get\", height));\n if (_config_js__WEBPACK_IMPORTED_MODULE_2__.Config.UseLocalStorageCache) {\n localStorage.setItem(key, JSON.stringify(result));\n }\n else {\n ElectrumNetworkProvider.rawTransactionCache[key] = result;\n }\n return verbose ? (0,_util_header_js__WEBPACK_IMPORTED_MODULE_3__.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 (_config_js__WEBPACK_IMPORTED_MODULE_2__.Config.UseLocalStorageCache) {\n const cached = localStorage.getItem(key);\n if (cached) {\n return verbose ? JSON.parse(cached) : cached;\n }\n }\n else {\n ElectrumNetworkProvider.rawTransactionCache[key];\n }\n try {\n const transaction = (await this.performRequest(\"blockchain.transaction.get\", txHash, verbose));\n if (_config_js__WEBPACK_IMPORTED_MODULE_2__.Config.UseLocalStorageCache) {\n localStorage.setItem(key, verbose\n ? JSON.stringify(transaction)\n : transaction);\n }\n else {\n ElectrumNetworkProvider.rawTransactionCache[key] = 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_4__.getTransactionHash)(txHex);\n if (!awaitPropagation) {\n this.performRequest(\"blockchain.transaction.broadcast\", txHex);\n resolve(txHash);\n }\n else {\n const waitForTransactionCallback = async (data) => {\n if (data && data[0] === txHash) {\n this.unsubscribeFromTransaction(txHash, waitForTransactionCallback);\n resolve(txHash);\n }\n };\n this.subscribeToTransaction(txHash, waitForTransactionCallback);\n this.performRequest(\"blockchain.transaction.broadcast\", txHex).catch((error) => {\n this.unsubscribeFromTransaction(txHash, waitForTransactionCallback);\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 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 this.subscribeToAddress(cashaddr, watchAddressStatusCallback);\n return async () => {\n await this.unsubscribeFromAddress(cashaddr, watchAddressStatusCallback);\n };\n }\n 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 watchAddressTransactions(cashaddr, callback) {\n return this.watchAddress(cashaddr, async (txHash) => {\n const tx = await this.getRawTransactionObject(txHash);\n callback(tx);\n });\n }\n 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 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 this.subscribeToHeaders(waitForBlockCallback);\n return async () => {\n this.unsubscribeFromHeaders(waitForBlockCallback);\n };\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 const cancelWatch = this.watchBlocks(async (header) => {\n if (height === undefined || header.height >= height) {\n await cancelWatch();\n resolve(header);\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 await this.subscribeRequest(\"blockchain.headers.subscribe\", callback);\n }\n // unsubscribe to notifications sent when new block is found\n async unsubscribeFromHeaders(callback) {\n await this.unsubscribeRequest(\"blockchain.headers.subscribe\", callback);\n }\n async subscribeToAddress(cashaddr, callback) {\n await this.subscribeRequest(\"blockchain.address.subscribe\", callback, cashaddr);\n }\n async unsubscribeFromAddress(cashaddr, callback) {\n await this.unsubscribeRequest(\"blockchain.address.subscribe\", callback, cashaddr);\n }\n async subscribeToAddressTransactions(cashaddr, callback) {\n await this.subscribeRequest(\"blockchain.address.transactions.subscribe\", callback, cashaddr);\n }\n async unsubscribeFromAddressTransactions(cashaddr, callback) {\n await this.unsubscribeRequest(\"blockchain.address.transactions.subscribe\", callback, cashaddr);\n }\n async subscribeToTransaction(txHash, callback) {\n await this.subscribeRequest(\"blockchain.transaction.subscribe\", callback, txHash);\n }\n async unsubscribeFromTransaction(txHash, callback) {\n await this.unsubscribeRequest(\"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 subscribeRequest(methodName, callback, ...parameters) {\n await this.ready();\n const result = await this.electrum.subscribe(callback, methodName, ...parameters);\n this.subscriptions++;\n return result;\n }\n async unsubscribeRequest(methodName, callback, ...parameters) {\n await this.ready();\n const result = this.electrum.unsubscribe(callback, methodName, ...parameters);\n this.subscriptions--;\n return result;\n }\n async ready() {\n return (await this.connect());\n }\n async connect() {\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.isElectrumClient()\n ? this.disconnectClient()\n : this.disconnectCluster();\n }\n isElectrumClient() {\n return this.electrum.hasOwnProperty(\"connection\");\n }\n async readyClient(timeout) {\n timeout = typeof timeout !== \"undefined\" ? timeout : 3000;\n let connectPromise = async () => {\n while (this.electrum.connection.status !==\n electrum_cash__WEBPACK_IMPORTED_MODULE_0__.ConnectionStatus.CONNECTED) {\n await (0,_util_delay_js__WEBPACK_IMPORTED_MODULE_5__.delay)(100);\n }\n return true;\n };\n return connectPromise;\n }\n async readyCluster(timeout) {\n timeout;\n return this.electrum.ready();\n }\n async connectCluster() {\n return this.electrum.startup();\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.connection.host}.`, e);\n return;\n }\n };\n return [await connectionPromise()];\n }\n async disconnectCluster() {\n return this.electrum.shutdown();\n }\n async disconnectClient() {\n return [await this.electrum.disconnect(true)];\n }\n}\nElectrumNetworkProvider.rawHeaderCache = {};\nElectrumNetworkProvider.rawTransactionCache = {};\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/network/ElectrumNetworkProvider.ts?");
|
|
268
268
|
|
|
269
269
|
/***/ }),
|
|
270
270
|
|
|
@@ -578,13 +578,23 @@ eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__
|
|
|
578
578
|
|
|
579
579
|
/***/ }),
|
|
580
580
|
|
|
581
|
+
/***/ "./src/util/header.ts":
|
|
582
|
+
/*!****************************!*\
|
|
583
|
+
!*** ./src/util/header.ts ***!
|
|
584
|
+
\****************************/
|
|
585
|
+
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
|
|
586
|
+
|
|
587
|
+
eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"decodeHeader\": () => (/* binding */ decodeHeader)\n/* harmony export */ });\n/* provided dependency */ var Buffer = __webpack_require__(/*! buffer */ \"../../node_modules/buffer/index.js\")[\"Buffer\"];\nconst decodeHeader = (hexHeader) => {\n const result = {};\n const header = Buffer.from(hexHeader.hex, \"hex\");\n result.version = header.readUInt32LE(0);\n result.previousBlockHash = header.subarray(4, 36).reverse().toString(\"hex\");\n result.merkleRoot = header.subarray(36, 68).reverse().toString(\"hex\");\n result.timestamp = header.readUInt32LE(68);\n result.bits = header.readUInt32LE(72);\n result.nonce = header.readUInt32LE(76);\n result.height = hexHeader.height;\n return result;\n};\n\n\n//# sourceURL=webpack://mainnet-js/./src/util/header.ts?");
|
|
588
|
+
|
|
589
|
+
/***/ }),
|
|
590
|
+
|
|
581
591
|
/***/ "./src/util/index.ts":
|
|
582
592
|
/*!***************************!*\
|
|
583
593
|
!*** ./src/util/index.ts ***!
|
|
584
594
|
\***************************/
|
|
585
595
|
/***/ ((module, __webpack_exports__, __webpack_require__) => {
|
|
586
596
|
|
|
587
|
-
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 */ \"convertObject\": () => (/* reexport safe */ _convert_js__WEBPACK_IMPORTED_MODULE_7__.convertObject),\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\");\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__]);\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__] = __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__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/util/index.ts?");
|
|
597
|
+
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 */ \"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__]);\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__] = __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?");
|
|
588
598
|
|
|
589
599
|
/***/ }),
|
|
590
600
|
|
|
@@ -704,7 +714,7 @@ eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__
|
|
|
704
714
|
\***************************/
|
|
705
715
|
/***/ ((module, __webpack_exports__, __webpack_require__) => {
|
|
706
716
|
|
|
707
|
-
eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"RegTestWallet\": () => (/* binding */ RegTestWallet),\n/* harmony export */ \"RegTestWatchWallet\": () => (/* binding */ RegTestWatchWallet),\n/* harmony export */ \"RegTestWifWallet\": () => (/* binding */ RegTestWifWallet),\n/* harmony export */ \"TestNetWallet\": () => (/* binding */ TestNetWallet),\n/* harmony export */ \"TestNetWatchWallet\": () => (/* binding */ TestNetWatchWallet),\n/* harmony export */ \"TestNetWifWallet\": () => (/* binding */ TestNetWifWallet),\n/* harmony export */ \"Wallet\": () => (/* binding */ Wallet),\n/* harmony export */ \"WatchWallet\": () => (/* binding */ WatchWallet),\n/* harmony export */ \"WifWallet\": () => (/* binding */ WifWallet)\n/* harmony export */ });\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! @bitauth/libauth */ \"./node_modules/@bitauth/libauth/build/lib/key/hd-key.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! @bitauth/libauth */ \"./node_modules/@bitauth/libauth/build/lib/address/cash-address.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_33__ = __webpack_require__(/*! @bitauth/libauth */ \"./node_modules/@bitauth/libauth/build/lib/crypto/default-crypto-instances.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! @bitauth/libauth */ \"./node_modules/@bitauth/libauth/build/lib/format/hex.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! @bitauth/libauth */ \"./node_modules/@bitauth/libauth/build/lib/key/key-utils.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! @bitauth/libauth */ \"./node_modules/@bitauth/libauth/build/lib/key/wallet-import-format.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_3__ = __webpack_require__(/*! ../enum.js */ \"./src/enum.ts\");\n/* harmony import */ var _interface_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../interface.js */ \"./src/interface.ts\");\n/* harmony import */ var _Base_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Base.js */ \"./src/wallet/Base.ts\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./enum.js */ \"./src/wallet/enum.ts\");\n/* harmony import */ var _model_js__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./model.js */ \"./src/wallet/model.ts\");\n/* harmony import */ var _transaction_Wif_js__WEBPACK_IMPORTED_MODULE_29__ = __webpack_require__(/*! ../transaction/Wif.js */ \"./src/transaction/Wif.ts\");\n/* harmony import */ var _util_asSendRequestObject_js__WEBPACK_IMPORTED_MODULE_30__ = __webpack_require__(/*! ../util/asSendRequestObject.js */ \"./src/util/asSendRequestObject.ts\");\n/* harmony import */ var _util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(/*! ../util/balanceObjectFromSatoshi.js */ \"./src/util/balanceObjectFromSatoshi.ts\");\n/* harmony import */ var _util_checkWifNetwork_js__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ../util/checkWifNetwork.js */ \"./src/util/checkWifNetwork.ts\");\n/* harmony import */ var _util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ../util/deriveCashaddr.js */ \"./src/util/deriveCashaddr.ts\");\n/* harmony import */ var _util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../util/derivePublicKeyHash.js */ \"./src/util/derivePublicKeyHash.ts\");\n/* harmony import */ var _util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../util/checkForEmptySeed.js */ \"./src/util/checkForEmptySeed.ts\");\n/* harmony import */ var _util_sanitizeUnit_js__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! ../util/sanitizeUnit.js */ \"./src/util/sanitizeUnit.ts\");\n/* harmony import */ var _util_sumUtxoValue_js__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(/*! ../util/sumUtxoValue.js */ \"./src/util/sumUtxoValue.ts\");\n/* harmony import */ var _util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_31__ = __webpack_require__(/*! ../util/sumSendRequestAmounts.js */ \"./src/util/sumSendRequestAmounts.ts\");\n/* harmony import */ var _network_getRelayFeeCache_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../network/getRelayFeeCache.js */ \"./src/network/getRelayFeeCache.ts\");\n/* harmony import */ var _Util_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./Util.js */ \"./src/wallet/Util.ts\");\n/* harmony import */ var _network_index_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../network/index.js */ \"./src/network/default.ts\");\n/* harmony import */ var _util_randomBytes_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../util/randomBytes.js */ \"./src/util/randomBytes.ts\");\n/* harmony import */ var _message_index_js__WEBPACK_IMPORTED_MODULE_34__ = __webpack_require__(/*! ../message/index.js */ \"./src/message/signed.ts\");\n/* harmony import */ var _util_amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(/*! ../util/amountInSatoshi.js */ \"./src/util/amountInSatoshi.ts\");\n/* harmony import */ var _util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../util/getXPubKey.js */ \"./src/util/getXPubKey.ts\");\n/* harmony import */ var _constant_js__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ../constant.js */ \"./src/constant.ts\");\n/* harmony import */ var _history_electrumTransformer_js__WEBPACK_IMPORTED_MODULE_32__ = __webpack_require__(/*! ../history/electrumTransformer.js */ \"./src/history/electrumTransformer.ts\");\n/* harmony import */ var _Bcmr_js__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(/*! ./Bcmr.js */ \"./src/wallet/Bcmr.ts\");\n/* harmony import */ var _qr_Qr_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../qr/Qr.js */ \"./src/qr/Qr.ts\");\n/* harmony import */ var _config_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../config.js */ \"./src/config.ts\");\n/* harmony import */ var _util_checkUtxos_js__WEBPACK_IMPORTED_MODULE_28__ = __webpack_require__(/*! ../util/checkUtxos.js */ \"./src/util/checkUtxos.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_Base_js__WEBPACK_IMPORTED_MODULE_2__, _enum_js__WEBPACK_IMPORTED_MODULE_3__, _config_js__WEBPACK_IMPORTED_MODULE_5__, _Util_js__WEBPACK_IMPORTED_MODULE_6__, _network_index_js__WEBPACK_IMPORTED_MODULE_8__, _qr_Qr_js__WEBPACK_IMPORTED_MODULE_9__, _util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_11__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_12__, _util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_14__, _util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_15__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_16__, _model_js__WEBPACK_IMPORTED_MODULE_18__, _util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_20__, _util_checkWifNetwork_js__WEBPACK_IMPORTED_MODULE_21__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_22__, _util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_24__, _util_amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_26__, _Bcmr_js__WEBPACK_IMPORTED_MODULE_27__, _transaction_Wif_js__WEBPACK_IMPORTED_MODULE_29__, _util_asSendRequestObject_js__WEBPACK_IMPORTED_MODULE_30__, _util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_31__, _history_electrumTransformer_js__WEBPACK_IMPORTED_MODULE_32__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_33__, _message_index_js__WEBPACK_IMPORTED_MODULE_34__]);\n([_Base_js__WEBPACK_IMPORTED_MODULE_2__, _enum_js__WEBPACK_IMPORTED_MODULE_3__, _config_js__WEBPACK_IMPORTED_MODULE_5__, _Util_js__WEBPACK_IMPORTED_MODULE_6__, _network_index_js__WEBPACK_IMPORTED_MODULE_8__, _qr_Qr_js__WEBPACK_IMPORTED_MODULE_9__, _util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_11__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_12__, _util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_14__, _util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_15__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_16__, _model_js__WEBPACK_IMPORTED_MODULE_18__, _util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_20__, _util_checkWifNetwork_js__WEBPACK_IMPORTED_MODULE_21__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_22__, _util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_24__, _util_amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_26__, _Bcmr_js__WEBPACK_IMPORTED_MODULE_27__, _transaction_Wif_js__WEBPACK_IMPORTED_MODULE_29__, _util_asSendRequestObject_js__WEBPACK_IMPORTED_MODULE_30__, _util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_31__, _history_electrumTransformer_js__WEBPACK_IMPORTED_MODULE_32__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_33__, _message_index_js__WEBPACK_IMPORTED_MODULE_34__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n//#region Imports\n// Stable\n\n// Unstable?\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n//#endregion Imports\n/**\n * Class to manage a bitcoin cash wallet.\n */\nclass Wallet extends _Base_js__WEBPACK_IMPORTED_MODULE_2__.BaseWallet {\n //#endregion\n //#region Constructors and Statics\n constructor(name = \"\", network = _enum_js__WEBPACK_IMPORTED_MODULE_3__.NetworkType.Mainnet, walletType = _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Seed) {\n super(name, network, walletType);\n this.derivationPath = _config_js__WEBPACK_IMPORTED_MODULE_5__.Config.DefaultParentDerivationPath + \"/0/0\";\n this.parentDerivationPath = _config_js__WEBPACK_IMPORTED_MODULE_5__.Config.DefaultParentDerivationPath;\n this._slpSemiAware = false; // a flag which requires an utxo to have more than 546 sats to be spendable and counted in the balance\n this.fromId = async (walletId) => {\n let [walletType, networkGiven, arg1] = walletId.split(\":\");\n if (this.network != networkGiven) {\n throw Error(`Network prefix ${networkGiven} to a ${this.network} wallet`);\n }\n // \"wif:regtest:cNfsPtqN2bMRS7vH5qd8tR8GMvgXyL5BjnGAKgZ8DYEiCrCCQcP6\"\n if (walletType === \"wif\") {\n return this.fromWIF(arg1);\n }\n return super.fromId(walletId);\n };\n this.networkPrefix = _enum_js__WEBPACK_IMPORTED_MODULE_3__.prefixFromNetworkMap[this.network];\n }\n //#region Accessors\n // interface to util functions. see Util.ts\n get util() {\n if (!this._util) {\n this._util = new _Util_js__WEBPACK_IMPORTED_MODULE_6__.Util(this);\n }\n return this._util;\n }\n // interface to util util. see Util.Util\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_6__.Util;\n }\n slpSemiAware(value = true) {\n this._slpSemiAware = value;\n return this;\n }\n getNetworkProvider(network = _interface_js__WEBPACK_IMPORTED_MODULE_7__.Network.MAINNET) {\n return (0,_network_index_js__WEBPACK_IMPORTED_MODULE_8__.getNetworkProvider)(network);\n }\n /**\n * getTokenDepositAddress - get a cashtoken aware wallet deposit address\n *\n * @returns The cashtoken aware deposit address as a string\n */\n getTokenDepositAddress() {\n return this.tokenaddr;\n }\n /**\n * getDepositQr - get an address qrcode, encoded for display on the web\n *\n * @returns The qrcode for the token aware address\n */\n getTokenDepositQr() {\n return (0,_qr_Qr_js__WEBPACK_IMPORTED_MODULE_9__.qrAddress)(this.getTokenDepositAddress());\n }\n /**\n * explorerUrl Web url to a transaction on a block explorer\n *\n * @param txId transaction Id\n * @returns Url string\n */\n explorerUrl(txId) {\n const explorerUrlMap = {\n mainnet: \"https://blockchair.com/bitcoin-cash/transaction/\",\n testnet: \"https://www.blockchain.com/bch-testnet/tx/\",\n regtest: \"\",\n };\n return explorerUrlMap[this.network] + txId;\n }\n // Return wallet info\n getInfo() {\n return {\n cashaddr: this.cashaddr,\n tokenaddr: this.tokenaddr,\n isTestnet: this.isTestnet,\n name: this.name,\n network: this.network,\n seed: this.mnemonic ? this.getSeed().seed : undefined,\n derivationPath: this.mnemonic ? this.getSeed().derivationPath : undefined,\n parentDerivationPath: this.mnemonic\n ? this.getSeed().parentDerivationPath\n : undefined,\n parentXPubKey: this.parentXPubKey ? this.parentXPubKey : undefined,\n publicKey: this.publicKey ? (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__.binToHex)(this.publicKey) : undefined,\n publicKeyHash: (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__.binToHex)(this.publicKeyHash),\n privateKey: this.privateKey ? (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__.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_10__.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_10__.binToHex)(this.publicKeyCompressed)\n : this.publicKeyCompressed;\n }\n else {\n throw Error(\"The compressed public key for this wallet is not known, perhaps the wallet was created to watch the *hash* of a public key? i.e. a cashaddress.\");\n }\n }\n // returns the public key hash for an address\n getPublicKeyHash(hex = false) {\n if (this.publicKeyHash) {\n return hex ? (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__.binToHex)(this.publicKeyHash) : this.publicKeyHash;\n }\n else {\n throw Error(\"The public key hash for this wallet is not known. If this wallet was created from the constructor directly, calling the deriveInfo() function may help. \");\n }\n }\n /**\n * fromWIF - create a wallet using the private key supplied in `Wallet Import Format`\n *\n * @param wif WIF encoded private key string\n *\n * @returns instantiated wallet\n */\n static async fromWIF(wif) {\n return new this().fromWIF(wif);\n }\n /**\n * fromCashaddr - create a watch-only wallet in the network derived from the address\n *\n * such kind of wallet does not have a private key and is unable to spend any funds\n * however it still allows to use many utility functions such as getting and watching balance, etc.\n *\n * @param address cashaddress of a wallet\n *\n * @returns instantiated wallet\n */\n static async fromCashaddr(address) {\n const prefix = (0,_util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_11__.derivePrefix)(address);\n const networkType = _enum_js__WEBPACK_IMPORTED_MODULE_3__.networkPrefixMap[prefix];\n return new this(\"\", networkType, _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Watch).watchOnly(address);\n }\n /**\n * fromTokenaddr - create a watch-only wallet in the network derived from the address\n *\n * such kind of wallet does not have a private key and is unable to spend any funds\n * however it still allows to use many utility functions such as getting and watching balance, etc.\n *\n * @param address token aware cashaddress of a wallet\n *\n * @returns instantiated wallet\n */\n static async fromTokenaddr(address) {\n const prefix = (0,_util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_11__.derivePrefix)(address);\n const networkType = _enum_js__WEBPACK_IMPORTED_MODULE_3__.networkPrefixMap[prefix];\n return new this(\"\", networkType, _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Watch).watchOnly(address);\n }\n //#endregion Constructors and Statics\n //#region Protected implementations\n async generate() {\n if (this.walletType === _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Wif) {\n return await this._generateWif();\n }\n else if (this.walletType === _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Watch) {\n return this;\n }\n else if (this.walletType === _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Hd) {\n throw Error(\"Not implemented\");\n }\n else if (this.walletType === _enum_js__WEBPACK_IMPORTED_MODULE_4__.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_12__.generatePrivateKey)(() => (0,_util_randomBytes_js__WEBPACK_IMPORTED_MODULE_13__.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_5__.Config.getWordlist());\n if (this.mnemonic.length == 0)\n throw Error(\"refusing to create wallet from empty mnemonic\");\n let seed = (0,_scure_bip39__WEBPACK_IMPORTED_MODULE_0__.mnemonicToSeedSync)(this.mnemonic);\n (0,_util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_14__.checkForEmptySeed)(seed);\n let network = this.isTestnet ? \"testnet\" : \"mainnet\";\n this.parentXPubKey = await (0,_util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_15__.getXPubKey)(seed, this.parentDerivationPath, network);\n let hdNode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_16__.deriveHdPrivateNodeFromSeed)(seed);\n if (!hdNode.valid) {\n throw Error(\"Invalid private key derived from mnemonic seed\");\n }\n let zerothChild = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_16__.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_4__.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_17__.DERIVATION_PATHS);\n }\n }\n else {\n throw Error(\"xpubkeys can only be derived from seed type wallets.\");\n }\n }\n // Initialize wallet from a mnemonic phrase\n async fromSeed(mnemonic, derivationPath) {\n this.mnemonic = mnemonic.trim().toLowerCase();\n if (this.mnemonic.length == 0)\n throw Error(\"refusing to create wallet from empty mnemonic\");\n let seed = (0,_scure_bip39__WEBPACK_IMPORTED_MODULE_0__.mnemonicToSeedSync)(this.mnemonic);\n (0,_util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_14__.checkForEmptySeed)(seed);\n let hdNode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_16__.deriveHdPrivateNodeFromSeed)(seed);\n if (!hdNode.valid) {\n throw Error(\"Invalid private key derived from mnemonic seed\");\n }\n if (derivationPath) {\n this.derivationPath = derivationPath;\n // If the derivation path is for the first account child, set the parent derivation path\n let path = derivationPath.split(\"/\");\n if (path.slice(-2).join(\"/\") == \"0/0\") {\n this.parentDerivationPath = path.slice(0, -2).join(\"/\");\n }\n }\n let zerothChild = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_16__.deriveHdPath)(hdNode, this.derivationPath);\n if (typeof zerothChild === \"string\") {\n throw Error(zerothChild);\n }\n this.privateKey = zerothChild.privateKey;\n let network = this.isTestnet ? \"testnet\" : \"mainnet\";\n this.parentXPubKey = await (0,_util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_15__.getXPubKey)(seed, this.parentDerivationPath, network);\n this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Seed;\n await this.deriveInfo();\n return this;\n }\n // Get common xpub paths from zerothChild privateKey\n async deriveHdPaths(hdPaths) {\n if (!this.mnemonic)\n throw Error(\"refusing to create wallet from empty mnemonic\");\n let seed = (0,_scure_bip39__WEBPACK_IMPORTED_MODULE_0__.mnemonicToSeedSync)(this.mnemonic);\n (0,_util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_14__.checkForEmptySeed)(seed);\n let hdNode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_16__.deriveHdPrivateNodeFromSeed)(seed);\n if (!hdNode.valid) {\n throw Error(\"Invalid private key derived from mnemonic seed\");\n }\n let result = [];\n for (const path of hdPaths) {\n if (path === \"m\") {\n throw Error(\"Storing or sharing of parent public key may lead to loss of funds. Storing or sharing *root* parent public keys is strongly discouraged, although all parent keys have risk. See: https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#implications\");\n }\n let childNode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_16__.deriveHdPath)(hdNode, path);\n if (typeof childNode === \"string\") {\n throw Error(childNode);\n }\n let node = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_16__.deriveHdPublicNode)(childNode);\n if (typeof node === \"string\") {\n throw Error(node);\n }\n let xPubKey = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_16__.encodeHdPublicKey)({\n network: this.network,\n node: node,\n });\n let key = new _model_js__WEBPACK_IMPORTED_MODULE_18__.XPubKey({\n path: path,\n xPubKey: xPubKey,\n });\n result.push(await key.ready());\n }\n return await Promise.all(result).then((result) => {\n return result;\n });\n }\n // Initialize a watch only wallet from a cash addr\n async watchOnly(address) {\n this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Watch;\n let addressComponents = address.split(\":\");\n let addressPrefix, addressBase;\n if (addressComponents.length === 1) {\n addressBase = addressComponents.shift();\n addressPrefix = (0,_util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_11__.derivePrefix)(addressBase);\n }\n else {\n addressPrefix = addressComponents.shift();\n addressBase = addressComponents.shift();\n if (addressPrefix in _enum_js__WEBPACK_IMPORTED_MODULE_3__.networkPrefixMap) {\n if (_enum_js__WEBPACK_IMPORTED_MODULE_3__.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 let addressData = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_19__.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_19__.CashAddressType.p2pkhWithTokens)\n nonTokenAwareType = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_19__.CashAddressType.p2pkh;\n if (nonTokenAwareType == _bitauth_libauth__WEBPACK_IMPORTED_MODULE_19__.CashAddressType.p2shWithTokens)\n nonTokenAwareType = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_19__.CashAddressType.p2sh;\n if (nonTokenAwareType == _bitauth_libauth__WEBPACK_IMPORTED_MODULE_19__.CashAddressType.p2pkh)\n this.publicKeyHash = addressData.payload;\n this.cashaddr = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_19__.encodeCashAddress)(addressData.prefix, nonTokenAwareType, addressData.payload);\n this.address = this.cashaddr;\n this.tokenaddr = (0,_util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_20__.deriveTokenaddr)(addressData.payload, this.networkPrefix);\n return this;\n }\n // Initialize wallet from Wallet Import Format\n async fromWIF(secret) {\n (0,_util_checkWifNetwork_js__WEBPACK_IMPORTED_MODULE_21__.checkWifNetwork)(secret, this.network);\n let wifResult = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_22__.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_4__.WalletTypeEnum.Wif;\n await this.deriveInfo();\n return this;\n }\n async newRandom(name, dbName) {\n dbName = dbName ? dbName : this.networkPrefix;\n return super.newRandom(name, dbName);\n }\n async named(name, dbName, forceNew = false) {\n dbName = dbName ? dbName : this.networkPrefix;\n return super.named(name, dbName, forceNew);\n }\n async replaceNamed(name, walletId, dbName) {\n dbName = dbName ? dbName : this.networkPrefix;\n return super.replaceNamed(name, walletId, dbName);\n }\n async namedExists(name, dbName) {\n dbName = dbName ? dbName : this.networkPrefix;\n return super.namedExists(name, dbName);\n }\n //#endregion Protected Implementations\n //#region Serialization\n // Returns the serialized wallet as a string\n // If storing in a database, set asNamed to false to store secrets\n // In all other cases, the a named wallet is deserialized from the database\n // by the name key\n toString() {\n const result = super.toString();\n if (result)\n return result;\n if (this.walletType === _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Wif) {\n return `${this.walletType}:${this.network}:${this.privateKeyWif}`;\n }\n throw Error(\"toString unsupported wallet type\");\n }\n //\n toDbString() {\n const result = super.toDbString();\n if (result)\n return result;\n if (this.walletType === _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Wif) {\n return `${this.walletType}:${this.network}:${this.privateKeyWif}`;\n }\n throw Error(\"toDbString unsupported wallet type\");\n }\n //#endregion Serialization\n //#region Funds\n //\n async getAddressUtxos(address) {\n if (!address) {\n address = this.cashaddr;\n }\n if (this._slpSemiAware) {\n const bchUtxos = await this.provider.getUtxos(address);\n return bchUtxos.filter((bchutxo) => bchutxo.satoshis > _constant_js__WEBPACK_IMPORTED_MODULE_17__.DUST_UTXO_THRESHOLD);\n }\n else {\n return await this.provider.getUtxos(address);\n }\n }\n /**\n * utxos Get unspent outputs for the wallet\n *\n */\n async getUtxos() {\n if (!this.cashaddr) {\n throw Error(\"Attempted to get utxos without an address\");\n }\n return await this.getAddressUtxos(this.cashaddr);\n }\n // gets wallet balance in sats, bch and currency\n async getBalance(rawUnit, priceCache = true) {\n if (rawUnit) {\n const unit = (0,_util_sanitizeUnit_js__WEBPACK_IMPORTED_MODULE_23__.sanitizeUnit)(rawUnit);\n return await (0,_util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_24__.balanceFromSatoshi)(await this.getBalanceFromProvider(), unit, priceCache);\n }\n else {\n return await (0,_util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_24__.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_sumUtxoValue_js__WEBPACK_IMPORTED_MODULE_25__.sumUtxoValue)(utxos);\n }\n // Gets balance from fulcrum\n async getBalanceFromProvider() {\n // Fulcrum reports balance of all utxos, including tokens, which is undesirable\n // // TODO not sure why getting the balance from a provider doesn't work\n // if (this._slpAware || this._slpSemiAware) {\n // return await this.getBalanceFromUtxos();\n // } else {\n // return await this.provider!.getBalance(this.cashaddr!);\n // }\n // FIXME\n return this.getBalanceFromUtxos();\n }\n // watching for any transaction hash of this wallet\n watchAddress(callback) {\n return this.provider.watchAddress(this.getDepositAddress(), callback);\n }\n // watching for any transaction of this wallet\n watchAddressTransactions(callback) {\n return this.provider.watchAddressTransactions(this.getDepositAddress(), callback);\n }\n // watching for cashtoken transaction of this wallet\n watchAddressTokenTransactions(callback) {\n return this.provider.watchAddressTokenTransactions(this.getDepositAddress(), callback);\n }\n // sets up a callback to be called upon wallet's balance change\n // can be cancelled by calling the function returned from this one\n watchBalance(callback) {\n return this.provider.watchAddressStatus(this.getDepositAddress(), async (_status) => {\n const balance = (await this.getBalance());\n callback(balance);\n });\n }\n // sets up a callback to be called upon wallet's BCH or USD balance change\n // if BCH balance does not change, the callback will be triggered every\n // @param `usdPriceRefreshInterval` milliseconds by polling for new BCH USD price\n // Since we want to be most sensitive to usd value change, we do not use the cached exchange rates\n // can be cancelled by calling the function returned from this one\n watchBalanceUsd(callback, usdPriceRefreshInterval = 30000) {\n let usdPrice = -1;\n const _callback = async () => {\n const balance = (await this.getBalance(undefined, false));\n if (usdPrice !== balance.usd) {\n usdPrice = balance.usd;\n callback(balance);\n }\n };\n const watchCancel = this.provider.watchAddressStatus(this.getDepositAddress(), _callback);\n const interval = setInterval(_callback, usdPriceRefreshInterval);\n return async () => {\n await watchCancel();\n clearInterval(interval);\n };\n }\n // waits for address balance to be greater than or equal to the target value\n // this call halts the execution\n async waitForBalance(value, rawUnit = _enum_js__WEBPACK_IMPORTED_MODULE_3__.UnitEnum.BCH) {\n return new Promise(async (resolve) => {\n const watchCancel = this.watchBalance(async (balance) => {\n const satoshiBalance = await (0,_util_amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_26__.amountInSatoshi)(value, rawUnit);\n if (balance.sat >= satoshiBalance) {\n await watchCancel();\n resolve(balance);\n }\n });\n });\n }\n // sets up a callback to be called upon wallet's token balance change\n // can be cancelled by calling the function returned from this one\n watchTokenBalance(tokenId, callback) {\n let previous = undefined;\n return this.provider.watchAddressStatus(this.getDepositAddress(), async (_status) => {\n const balance = await this.getTokenBalance(tokenId);\n if (previous != balance) {\n callback(balance);\n }\n previous = balance;\n });\n }\n // waits for address token balance to be greater than or equal to the target amount\n // this call halts the execution\n async waitForTokenBalance(tokenId, amount) {\n return new Promise(async (resolve) => {\n const watchCancel = this.watchTokenBalance(tokenId, async (balance) => {\n if (balance >= amount) {\n await watchCancel();\n resolve(balance);\n }\n });\n });\n }\n async getTokenInfo(tokenId) {\n return _Bcmr_js__WEBPACK_IMPORTED_MODULE_27__.BCMR.getTokenInfo(tokenId);\n }\n async _getMaxAmountToSend(params = {\n outputCount: 1,\n options: {},\n }) {\n if (!this.privateKey && params.options?.buildUnsigned !== true) {\n throw Error(\"Couldn't get network or private key for wallet.\");\n }\n if (!this.cashaddr) {\n throw Error(\"attempted to send without a cashaddr\");\n }\n if (params.options && params.options.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_4__.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_28__.checkUtxos)(params.options.utxoIds.map((utxoId) => typeof utxoId === \"string\" ? (0,_model_js__WEBPACK_IMPORTED_MODULE_18__.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_18__.SendRequest({\n cashaddr: this.cashaddr,\n value: 100,\n unit: \"sat\",\n });\n const sendRequests = Array(params.outputCount)\n .fill(0)\n .map(() => sendRequest);\n const fundingUtxos = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_29__.getSuitableUtxos)(utxos, undefined, bestHeight, feePaidBy, sendRequests);\n const relayFeePerByteInSatoshi = await (0,_network_getRelayFeeCache_js__WEBPACK_IMPORTED_MODULE_1__.getRelayFeeCache)(this.provider);\n const fee = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_29__.getFeeAmountSimple)({\n utxos: fundingUtxos,\n sendRequests: sendRequests,\n privateKey: this.privateKey ?? Uint8Array.from([]),\n sourceAddress: this.cashaddr,\n relayFeePerByteInSatoshi: relayFeePerByteInSatoshi,\n feePaidBy: feePaidBy,\n });\n const spendableAmount = (0,_util_sumUtxoValue_js__WEBPACK_IMPORTED_MODULE_25__.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_24__.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_18__.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_10__.binToHex)(encodedTransaction);\n resp.sourceOutputs = sourceOutputs;\n }\n return resp;\n }\n /**\n * sendMax Send all available funds to a destination cash address\n *\n * @param {string} cashaddr destination cash address\n * @param {SendRequestOptionsI} options Options of the send requests\n *\n * @returns (depending on the options parameter) the transaction id, new address balance and a link to the transaction on the blockchain explorer\n */\n async sendMax(cashaddr, options) {\n return await this.sendMaxRaw(cashaddr, options);\n }\n /**\n * sendMaxRaw (internal) Send all available funds to a destination cash address\n *\n * @param {string} cashaddr destination cash address\n * @param {SendRequestOptionsI} options Options of the send requests\n *\n * @returns the transaction id sent to the network\n */\n async sendMaxRaw(cashaddr, options) {\n const { value: maxSpendableAmount, utxos } = await this._getMaxAmountToSend({\n outputCount: 1,\n options: options,\n });\n if (!options) {\n options = {};\n }\n options.utxoIds = utxos;\n const sendRequest = new _model_js__WEBPACK_IMPORTED_MODULE_18__.SendRequest({\n cashaddr: cashaddr,\n value: maxSpendableAmount,\n unit: \"sat\",\n });\n const { encodedTransaction, tokenIds, sourceOutputs } = await this.encodeTransaction([sendRequest], true, options);\n const resp = new _model_js__WEBPACK_IMPORTED_MODULE_18__.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_10__.binToHex)(encodedTransaction);\n resp.sourceOutputs = sourceOutputs;\n }\n return resp;\n }\n /**\n * encodeTransaction Encode and sign a transaction given a list of sendRequests, options and estimate fees.\n * @param {SendRequest[]} sendRequests SendRequests\n * @param {boolean} discardChange=false\n * @param {SendRequestOptionsI} options Options of the send requests\n */\n async encodeTransaction(requests, discardChange = false, options) {\n let sendRequests = (0,_util_asSendRequestObject_js__WEBPACK_IMPORTED_MODULE_30__.asSendRequestObject)(requests);\n if (!this.privateKey && options?.buildUnsigned !== true) {\n throw new Error(`Wallet ${this.name} is missing either a network or private key`);\n }\n if (!this.cashaddr) {\n throw Error(\"attempted to send without a cashaddr\");\n }\n if (options && options.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_4__.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_28__.checkUtxos)(options.utxoIds.map((utxoId) => typeof utxoId === \"string\" ? (0,_model_js__WEBPACK_IMPORTED_MODULE_18__.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_18__.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_18__.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_18__.TokenSendRequest({\n cashaddr: (0,_util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_20__.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_31__.sumSendRequestAmounts)(sendRequests);\n if (utxos.length === 0) {\n throw Error(\"There were no Unspent Outputs\");\n }\n if (typeof spendAmount !== \"bigint\") {\n throw Error(\"Couldn't get spend amount when building transaction\");\n }\n const relayFeePerByteInSatoshi = await (0,_network_getRelayFeeCache_js__WEBPACK_IMPORTED_MODULE_1__.getRelayFeeCache)(this.provider);\n const feeEstimate = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_29__.getFeeAmountSimple)({\n utxos: utxos,\n sendRequests: sendRequests,\n privateKey: this.privateKey ?? Uint8Array.from([]),\n sourceAddress: this.cashaddr,\n relayFeePerByteInSatoshi: relayFeePerByteInSatoshi,\n feePaidBy: feePaidBy,\n });\n const fundingUtxos = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_29__.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_29__.getFeeAmount)({\n utxos: fundingUtxos,\n sendRequests: sendRequests,\n privateKey: this.privateKey ?? Uint8Array.from([]),\n sourceAddress: this.cashaddr,\n relayFeePerByteInSatoshi: relayFeePerByteInSatoshi,\n feePaidBy: feePaidBy,\n });\n const { encodedTransaction, sourceOutputs } = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_29__.buildEncodedTransaction)({\n inputs: fundingUtxos,\n outputs: sendRequests,\n signingKey: this.privateKey ?? Uint8Array.from([]),\n sourceAddress: this.cashaddr,\n fee,\n discardChange,\n 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_18__.TokenSendRequest)\n .map((val) => val.tokenId),\n ].filter((value, index, array) => array.indexOf(value) === index);\n return { encodedTransaction, tokenIds, sourceOutputs };\n }\n async signUnsignedTransaction(transaction, sourceOutputs) {\n if (!this.privateKey) {\n throw Error(\"Can not sign a transaction with watch-only wallet.\");\n }\n return (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_29__.signUnsignedTransaction)(transaction, sourceOutputs, this.privateKey);\n }\n // Submit a raw transaction\n async submitTransaction(transaction, awaitPropagation = true) {\n if (!this.provider) {\n throw Error(\"Wallet network provider was not initialized\");\n }\n let rawTransaction = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__.binToHex)(transaction);\n return await this.provider.sendRawTransaction(rawTransaction, awaitPropagation);\n }\n // gets transaction history of this wallet\n async getRawHistory() {\n return await this.provider.getHistory(this.cashaddr);\n }\n // gets transaction history of this wallet\n async getHistory(unit, start, count, collapseChange) {\n return (0,_history_electrumTransformer_js__WEBPACK_IMPORTED_MODULE_32__.getAddressHistory)(this.cashaddr, this.provider, unit, start, count, collapseChange);\n }\n // gets last transaction of this wallet\n async getLastTransaction(confirmedOnly = false) {\n let history = await this.getRawHistory();\n if (confirmedOnly) {\n history = history.filter((val) => val.height > 0);\n }\n if (!history.length) {\n return null;\n }\n const [lastTx] = history.slice(-1);\n return this.provider.getRawTransactionObject(lastTx.tx_hash);\n }\n // waits for next transaction, program execution is halted\n async waitForTransaction(options = {\n getTransactionInfo: true,\n getBalance: false,\n txHash: undefined,\n }) {\n if (options.getTransactionInfo === undefined) {\n options.getTransactionInfo = true;\n }\n return new Promise(async (resolve) => {\n let txHashSeen = false;\n const makeResponse = async (txHash) => {\n const response = {};\n const promises = [undefined, undefined];\n if (options.getBalance === true) {\n promises[0] = this.getBalance();\n }\n if (options.getTransactionInfo === true) {\n if (!txHash) {\n promises[1] = this.getLastTransaction();\n }\n else {\n promises[1] = this.provider.getRawTransactionObject(txHash);\n }\n }\n const result = await Promise.all(promises);\n response.balance = result[0];\n response.transactionInfo = result[1];\n return response;\n };\n // waiting for a specific transaction to propagate\n if (options.txHash) {\n const waitForTransactionCallback = async (data) => {\n if (data && data[0] === options.txHash) {\n txHashSeen = true;\n this.provider.unsubscribeFromTransaction(options.txHash, waitForTransactionCallback);\n resolve(makeResponse(options.txHash));\n }\n };\n this.provider.subscribeToTransaction(options.txHash, waitForTransactionCallback);\n return;\n }\n // waiting for any address transaction\n const watchCancel = this.provider.watchAddressStatus(this.getDepositAddress(), async (_status) => {\n watchCancel();\n resolve(makeResponse());\n });\n });\n }\n /**\n * watchBlocks Watch network blocks\n *\n * @param callback callback with a block header object\n *\n * @returns a function which will cancel watching upon evaluation\n */\n watchBlocks(callback) {\n return this.provider.watchBlocks(callback);\n }\n /**\n * waitForBlock Wait for a network block\n *\n * @param height if specified waits for this exact blockchain height, otherwise resolves with the next block\n *\n */\n async waitForBlock(height) {\n return this.provider.waitForBlock(height);\n }\n //#endregion Funds\n //#region Private implementation details\n async deriveInfo() {\n const publicKey = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_33__.secp256k1.derivePublicKeyUncompressed(this.privateKey);\n if (typeof publicKey === \"string\") {\n throw new Error(publicKey);\n }\n this.publicKey = publicKey;\n const publicKeyCompressed = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_33__.secp256k1.derivePublicKeyCompressed(this.privateKey);\n if (typeof publicKeyCompressed === \"string\") {\n throw new Error(publicKeyCompressed);\n }\n this.publicKeyCompressed = publicKeyCompressed;\n const networkType = this.network === _enum_js__WEBPACK_IMPORTED_MODULE_3__.NetworkType.Regtest ? _enum_js__WEBPACK_IMPORTED_MODULE_3__.NetworkType.Testnet : this.network;\n this.privateKeyWif = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_22__.encodePrivateKeyWif)(this.privateKey, networkType);\n (0,_util_checkWifNetwork_js__WEBPACK_IMPORTED_MODULE_21__.checkWifNetwork)(this.privateKeyWif, this.network);\n this.cashaddr = (0,_util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_20__.deriveCashaddr)(this.privateKey, this.networkPrefix);\n this.tokenaddr = (0,_util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_20__.deriveTokenaddr)(this.privateKey, this.networkPrefix);\n this.address = this.cashaddr;\n this.publicKeyHash = (0,_util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_11__.derivePublicKeyHash)(this.cashaddr);\n return this;\n }\n //#endregion Private implementation details\n //#region Signing\n // Convenience wrapper to sign interface\n async sign(message) {\n return await Wallet.signedMessage.sign(message, this.privateKey);\n }\n // Convenience wrapper to verify interface\n async verify(message, sig, publicKey) {\n return await Wallet.signedMessage.verify(message, sig, this.cashaddr, publicKey);\n }\n //#endregion Signing\n //#region Cashtokens\n /**\n * Create new cashtoken, both funglible and/or non-fungible (NFT)\n * Refer to spec https://github.com/bitjson/cashtokens\n * @param {number} genesisRequest.amount amount of *fungible* tokens to create\n * @param {NFTCapability?} genesisRequest.capability capability of new NFT\n * @param {string?} genesisRequest.commitment NFT commitment message\n * @param {string?} genesisRequest.cashaddr cash address to send the created token UTXO to; if undefined will default to your address\n * @param {number?} genesisRequest.value satoshi value to send alongside with tokens; if undefined will default to 1000 satoshi\n * @param {SendRequestType | SendRequestType[]} sendRequests single or an array of extra send requests (OP_RETURN, value transfer, etc.) to include in genesis transaction\n * @param {SendRequestOptionsI} options Options of the send requests\n */\n async tokenGenesis(genesisRequest, sendRequests = [], options) {\n if (!Array.isArray(sendRequests)) {\n sendRequests = [sendRequests];\n }\n let utxos;\n if (options && options.utxoIds) {\n utxos = await (0,_util_checkUtxos_js__WEBPACK_IMPORTED_MODULE_28__.checkUtxos)(options.utxoIds.map((utxoId) => typeof utxoId === \"string\" ? (0,_model_js__WEBPACK_IMPORTED_MODULE_18__.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_18__.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_7__.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_18__.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_18__.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_18__.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_18__.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_18__.OpReturnData.fromString(message || \"\");\n return this.send([opReturn, ...changeSendRequests], {\n ...options,\n checkTokenQuantities: false,\n queryBalance: false,\n ensureUtxos: utxoIds.length > 0 ? utxoIds : undefined,\n tokenOperation: \"burn\",\n });\n }\n /**\n * getTokenUtxos Get unspent token outputs for the wallet\n * will return utxos only for the specified token if `tokenId` provided\n * @param {string?} tokenId tokenId (category) to filter utxos by, if not set will return utxos from all tokens\n * @returns {UtxoI[]} token utxos\n */\n async getTokenUtxos(tokenId) {\n const utxos = await this.getAddressUtxos(this.address);\n return utxos.filter((val) => tokenId ? val.token?.tokenId === tokenId : val.token);\n }\n /**\n * getTokenBalance Gets fungible token balance\n * for NFT token balance see @ref getNftTokenBalance\n * @param {string} tokenId tokenId to get balance for\n * @returns {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_sumUtxoValue_js__WEBPACK_IMPORTED_MODULE_25__.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}\nWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_19__.CashAddressNetworkPrefix.mainnet;\nWallet.signedMessage = new _message_index_js__WEBPACK_IMPORTED_MODULE_34__.SignedMessage();\n/**\n * Class to manage a testnet wallet.\n */\nclass TestNetWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_3__.NetworkType.Testnet);\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_6__.TestNetUtil;\n }\n}\nTestNetWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_19__.CashAddressNetworkPrefix.testnet;\nTestNetWallet.faucetServer = \"https://rest-unstable.mainnet.cash\";\n/**\n * Class to manage a regtest wallet.\n */\nclass RegTestWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_3__.NetworkType.Regtest);\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_6__.RegTestUtil;\n }\n}\nRegTestWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_19__.CashAddressNetworkPrefix.regtest;\n/**\n * Class to manage a bitcoin cash wif wallet.\n */\nclass WifWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_3__.NetworkType.Mainnet, _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Wif);\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_6__.WifUtil;\n }\n}\nWifWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_19__.CashAddressNetworkPrefix.mainnet;\nWifWallet.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Wif;\n/**\n * Class to manage a testnet wif wallet.\n */\nclass TestNetWifWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_3__.NetworkType.Testnet, _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Wif);\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_6__.TestNetWifUtil;\n }\n}\nTestNetWifWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_19__.CashAddressNetworkPrefix.testnet;\nTestNetWifWallet.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Wif;\n/**\n * Class to manage a regtest wif wallet.\n */\nclass RegTestWifWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_3__.NetworkType.Regtest, _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Wif);\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_6__.RegTestWifUtil;\n }\n}\nRegTestWifWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_19__.CashAddressNetworkPrefix.regtest;\nRegTestWifWallet.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Wif;\n/**\n * Class to manage a bitcoin cash watch wallet.\n */\nclass WatchWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_3__.NetworkType.Mainnet, _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Watch);\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_6__.WatchUtil;\n }\n}\nWatchWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_19__.CashAddressNetworkPrefix.mainnet;\nWatchWallet.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Watch;\n/**\n * Class to manage a testnet watch wallet.\n */\nclass TestNetWatchWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_3__.NetworkType.Testnet, _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Watch);\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_6__.TestNetWatchUtil;\n }\n}\nTestNetWatchWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_19__.CashAddressNetworkPrefix.testnet;\nTestNetWatchWallet.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Watch;\n/**\n * Class to manage a regtest watch wallet.\n */\nclass RegTestWatchWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_3__.NetworkType.Regtest, _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Watch);\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_6__.RegTestWatchUtil;\n }\n}\nRegTestWatchWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_19__.CashAddressNetworkPrefix.regtest;\nRegTestWatchWallet.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Watch;\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/wallet/Wif.ts?");
|
|
717
|
+
eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"RegTestWallet\": () => (/* binding */ RegTestWallet),\n/* harmony export */ \"RegTestWatchWallet\": () => (/* binding */ RegTestWatchWallet),\n/* harmony export */ \"RegTestWifWallet\": () => (/* binding */ RegTestWifWallet),\n/* harmony export */ \"TestNetWallet\": () => (/* binding */ TestNetWallet),\n/* harmony export */ \"TestNetWatchWallet\": () => (/* binding */ TestNetWatchWallet),\n/* harmony export */ \"TestNetWifWallet\": () => (/* binding */ TestNetWifWallet),\n/* harmony export */ \"Wallet\": () => (/* binding */ Wallet),\n/* harmony export */ \"WatchWallet\": () => (/* binding */ WatchWallet),\n/* harmony export */ \"WifWallet\": () => (/* binding */ WifWallet)\n/* harmony export */ });\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! @bitauth/libauth */ \"./node_modules/@bitauth/libauth/build/lib/key/hd-key.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! @bitauth/libauth */ \"./node_modules/@bitauth/libauth/build/lib/address/cash-address.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_33__ = __webpack_require__(/*! @bitauth/libauth */ \"./node_modules/@bitauth/libauth/build/lib/crypto/default-crypto-instances.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! @bitauth/libauth */ \"./node_modules/@bitauth/libauth/build/lib/format/hex.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! @bitauth/libauth */ \"./node_modules/@bitauth/libauth/build/lib/key/key-utils.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! @bitauth/libauth */ \"./node_modules/@bitauth/libauth/build/lib/key/wallet-import-format.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_3__ = __webpack_require__(/*! ../enum.js */ \"./src/enum.ts\");\n/* harmony import */ var _interface_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../interface.js */ \"./src/interface.ts\");\n/* harmony import */ var _Base_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Base.js */ \"./src/wallet/Base.ts\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./enum.js */ \"./src/wallet/enum.ts\");\n/* harmony import */ var _model_js__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./model.js */ \"./src/wallet/model.ts\");\n/* harmony import */ var _transaction_Wif_js__WEBPACK_IMPORTED_MODULE_29__ = __webpack_require__(/*! ../transaction/Wif.js */ \"./src/transaction/Wif.ts\");\n/* harmony import */ var _util_asSendRequestObject_js__WEBPACK_IMPORTED_MODULE_30__ = __webpack_require__(/*! ../util/asSendRequestObject.js */ \"./src/util/asSendRequestObject.ts\");\n/* harmony import */ var _util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(/*! ../util/balanceObjectFromSatoshi.js */ \"./src/util/balanceObjectFromSatoshi.ts\");\n/* harmony import */ var _util_checkWifNetwork_js__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ../util/checkWifNetwork.js */ \"./src/util/checkWifNetwork.ts\");\n/* harmony import */ var _util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ../util/deriveCashaddr.js */ \"./src/util/deriveCashaddr.ts\");\n/* harmony import */ var _util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../util/derivePublicKeyHash.js */ \"./src/util/derivePublicKeyHash.ts\");\n/* harmony import */ var _util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../util/checkForEmptySeed.js */ \"./src/util/checkForEmptySeed.ts\");\n/* harmony import */ var _util_sanitizeUnit_js__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! ../util/sanitizeUnit.js */ \"./src/util/sanitizeUnit.ts\");\n/* harmony import */ var _util_sumUtxoValue_js__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(/*! ../util/sumUtxoValue.js */ \"./src/util/sumUtxoValue.ts\");\n/* harmony import */ var _util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_31__ = __webpack_require__(/*! ../util/sumSendRequestAmounts.js */ \"./src/util/sumSendRequestAmounts.ts\");\n/* harmony import */ var _network_getRelayFeeCache_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../network/getRelayFeeCache.js */ \"./src/network/getRelayFeeCache.ts\");\n/* harmony import */ var _Util_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./Util.js */ \"./src/wallet/Util.ts\");\n/* harmony import */ var _network_index_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../network/index.js */ \"./src/network/default.ts\");\n/* harmony import */ var _util_randomBytes_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../util/randomBytes.js */ \"./src/util/randomBytes.ts\");\n/* harmony import */ var _message_index_js__WEBPACK_IMPORTED_MODULE_34__ = __webpack_require__(/*! ../message/index.js */ \"./src/message/signed.ts\");\n/* harmony import */ var _util_amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(/*! ../util/amountInSatoshi.js */ \"./src/util/amountInSatoshi.ts\");\n/* harmony import */ var _util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../util/getXPubKey.js */ \"./src/util/getXPubKey.ts\");\n/* harmony import */ var _constant_js__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ../constant.js */ \"./src/constant.ts\");\n/* harmony import */ var _history_electrumTransformer_js__WEBPACK_IMPORTED_MODULE_32__ = __webpack_require__(/*! ../history/electrumTransformer.js */ \"./src/history/electrumTransformer.ts\");\n/* harmony import */ var _Bcmr_js__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(/*! ./Bcmr.js */ \"./src/wallet/Bcmr.ts\");\n/* harmony import */ var _qr_Qr_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../qr/Qr.js */ \"./src/qr/Qr.ts\");\n/* harmony import */ var _config_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../config.js */ \"./src/config.ts\");\n/* harmony import */ var _util_checkUtxos_js__WEBPACK_IMPORTED_MODULE_28__ = __webpack_require__(/*! ../util/checkUtxos.js */ \"./src/util/checkUtxos.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_Base_js__WEBPACK_IMPORTED_MODULE_2__, _enum_js__WEBPACK_IMPORTED_MODULE_3__, _config_js__WEBPACK_IMPORTED_MODULE_5__, _Util_js__WEBPACK_IMPORTED_MODULE_6__, _network_index_js__WEBPACK_IMPORTED_MODULE_8__, _qr_Qr_js__WEBPACK_IMPORTED_MODULE_9__, _util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_11__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_12__, _util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_14__, _util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_15__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_16__, _model_js__WEBPACK_IMPORTED_MODULE_18__, _util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_20__, _util_checkWifNetwork_js__WEBPACK_IMPORTED_MODULE_21__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_22__, _util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_24__, _util_amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_26__, _Bcmr_js__WEBPACK_IMPORTED_MODULE_27__, _transaction_Wif_js__WEBPACK_IMPORTED_MODULE_29__, _util_asSendRequestObject_js__WEBPACK_IMPORTED_MODULE_30__, _util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_31__, _history_electrumTransformer_js__WEBPACK_IMPORTED_MODULE_32__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_33__, _message_index_js__WEBPACK_IMPORTED_MODULE_34__]);\n([_Base_js__WEBPACK_IMPORTED_MODULE_2__, _enum_js__WEBPACK_IMPORTED_MODULE_3__, _config_js__WEBPACK_IMPORTED_MODULE_5__, _Util_js__WEBPACK_IMPORTED_MODULE_6__, _network_index_js__WEBPACK_IMPORTED_MODULE_8__, _qr_Qr_js__WEBPACK_IMPORTED_MODULE_9__, _util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_11__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_12__, _util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_14__, _util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_15__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_16__, _model_js__WEBPACK_IMPORTED_MODULE_18__, _util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_20__, _util_checkWifNetwork_js__WEBPACK_IMPORTED_MODULE_21__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_22__, _util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_24__, _util_amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_26__, _Bcmr_js__WEBPACK_IMPORTED_MODULE_27__, _transaction_Wif_js__WEBPACK_IMPORTED_MODULE_29__, _util_asSendRequestObject_js__WEBPACK_IMPORTED_MODULE_30__, _util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_31__, _history_electrumTransformer_js__WEBPACK_IMPORTED_MODULE_32__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_33__, _message_index_js__WEBPACK_IMPORTED_MODULE_34__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n//#region Imports\n// Stable\n\n// Unstable?\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n//#endregion Imports\n/**\n * Class to manage a bitcoin cash wallet.\n */\nclass Wallet extends _Base_js__WEBPACK_IMPORTED_MODULE_2__.BaseWallet {\n //#endregion\n //#region Constructors and Statics\n constructor(name = \"\", network = _enum_js__WEBPACK_IMPORTED_MODULE_3__.NetworkType.Mainnet, walletType = _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Seed) {\n super(name, network, walletType);\n this.derivationPath = _config_js__WEBPACK_IMPORTED_MODULE_5__.Config.DefaultParentDerivationPath + \"/0/0\";\n this.parentDerivationPath = _config_js__WEBPACK_IMPORTED_MODULE_5__.Config.DefaultParentDerivationPath;\n this._slpSemiAware = false; // a flag which requires an utxo to have more than 546 sats to be spendable and counted in the balance\n this.fromId = async (walletId) => {\n let [walletType, networkGiven, arg1] = walletId.split(\":\");\n if (this.network != networkGiven) {\n throw Error(`Network prefix ${networkGiven} to a ${this.network} wallet`);\n }\n // \"wif:regtest:cNfsPtqN2bMRS7vH5qd8tR8GMvgXyL5BjnGAKgZ8DYEiCrCCQcP6\"\n if (walletType === \"wif\") {\n return this.fromWIF(arg1);\n }\n return super.fromId(walletId);\n };\n this.networkPrefix = _enum_js__WEBPACK_IMPORTED_MODULE_3__.prefixFromNetworkMap[this.network];\n }\n //#region Accessors\n // interface to util functions. see Util.ts\n get util() {\n if (!this._util) {\n this._util = new _Util_js__WEBPACK_IMPORTED_MODULE_6__.Util(this);\n }\n return this._util;\n }\n // interface to util util. see Util.Util\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_6__.Util;\n }\n slpSemiAware(value = true) {\n this._slpSemiAware = value;\n return this;\n }\n getNetworkProvider(network = _interface_js__WEBPACK_IMPORTED_MODULE_7__.Network.MAINNET) {\n return (0,_network_index_js__WEBPACK_IMPORTED_MODULE_8__.getNetworkProvider)(network);\n }\n /**\n * getTokenDepositAddress - get a cashtoken aware wallet deposit address\n *\n * @returns The cashtoken aware deposit address as a string\n */\n getTokenDepositAddress() {\n return this.tokenaddr;\n }\n /**\n * getDepositQr - get an address qrcode, encoded for display on the web\n *\n * @returns The qrcode for the token aware address\n */\n getTokenDepositQr() {\n return (0,_qr_Qr_js__WEBPACK_IMPORTED_MODULE_9__.qrAddress)(this.getTokenDepositAddress());\n }\n /**\n * explorerUrl Web url to a transaction on a block explorer\n *\n * @param txId transaction Id\n * @returns Url string\n */\n explorerUrl(txId) {\n const explorerUrlMap = {\n mainnet: \"https://blockchair.com/bitcoin-cash/transaction/\",\n testnet: \"https://www.blockchain.com/bch-testnet/tx/\",\n regtest: \"\",\n };\n return explorerUrlMap[this.network] + txId;\n }\n // Return wallet info\n getInfo() {\n return {\n cashaddr: this.cashaddr,\n tokenaddr: this.tokenaddr,\n isTestnet: this.isTestnet,\n name: this.name,\n network: this.network,\n seed: this.mnemonic ? this.getSeed().seed : undefined,\n derivationPath: this.mnemonic ? this.getSeed().derivationPath : undefined,\n parentDerivationPath: this.mnemonic\n ? this.getSeed().parentDerivationPath\n : undefined,\n parentXPubKey: this.parentXPubKey ? this.parentXPubKey : undefined,\n publicKey: this.publicKey ? (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__.binToHex)(this.publicKey) : undefined,\n publicKeyHash: (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__.binToHex)(this.publicKeyHash),\n privateKey: this.privateKey ? (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__.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_10__.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_10__.binToHex)(this.publicKeyCompressed)\n : this.publicKeyCompressed;\n }\n else {\n throw Error(\"The compressed public key for this wallet is not known, perhaps the wallet was created to watch the *hash* of a public key? i.e. a cashaddress.\");\n }\n }\n // returns the public key hash for an address\n getPublicKeyHash(hex = false) {\n if (this.publicKeyHash) {\n return hex ? (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__.binToHex)(this.publicKeyHash) : this.publicKeyHash;\n }\n else {\n throw Error(\"The public key hash for this wallet is not known. If this wallet was created from the constructor directly, calling the deriveInfo() function may help. \");\n }\n }\n /**\n * fromWIF - create a wallet using the private key supplied in `Wallet Import Format`\n *\n * @param wif WIF encoded private key string\n *\n * @returns instantiated wallet\n */\n static async fromWIF(wif) {\n return new this().fromWIF(wif);\n }\n /**\n * fromCashaddr - create a watch-only wallet in the network derived from the address\n *\n * such kind of wallet does not have a private key and is unable to spend any funds\n * however it still allows to use many utility functions such as getting and watching balance, etc.\n *\n * @param address cashaddress of a wallet\n *\n * @returns instantiated wallet\n */\n static async fromCashaddr(address) {\n const prefix = (0,_util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_11__.derivePrefix)(address);\n const networkType = _enum_js__WEBPACK_IMPORTED_MODULE_3__.networkPrefixMap[prefix];\n return new this(\"\", networkType, _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Watch).watchOnly(address);\n }\n /**\n * fromTokenaddr - create a watch-only wallet in the network derived from the address\n *\n * such kind of wallet does not have a private key and is unable to spend any funds\n * however it still allows to use many utility functions such as getting and watching balance, etc.\n *\n * @param address token aware cashaddress of a wallet\n *\n * @returns instantiated wallet\n */\n static async fromTokenaddr(address) {\n const prefix = (0,_util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_11__.derivePrefix)(address);\n const networkType = _enum_js__WEBPACK_IMPORTED_MODULE_3__.networkPrefixMap[prefix];\n return new this(\"\", networkType, _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Watch).watchOnly(address);\n }\n //#endregion Constructors and Statics\n //#region Protected implementations\n async generate() {\n if (this.walletType === _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Wif) {\n return await this._generateWif();\n }\n else if (this.walletType === _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Watch) {\n return this;\n }\n else if (this.walletType === _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Hd) {\n throw Error(\"Not implemented\");\n }\n else if (this.walletType === _enum_js__WEBPACK_IMPORTED_MODULE_4__.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_12__.generatePrivateKey)(() => (0,_util_randomBytes_js__WEBPACK_IMPORTED_MODULE_13__.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_5__.Config.getWordlist());\n if (this.mnemonic.length == 0)\n throw Error(\"refusing to create wallet from empty mnemonic\");\n let seed = (0,_scure_bip39__WEBPACK_IMPORTED_MODULE_0__.mnemonicToSeedSync)(this.mnemonic);\n (0,_util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_14__.checkForEmptySeed)(seed);\n let network = this.isTestnet ? \"testnet\" : \"mainnet\";\n this.parentXPubKey = await (0,_util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_15__.getXPubKey)(seed, this.parentDerivationPath, network);\n let hdNode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_16__.deriveHdPrivateNodeFromSeed)(seed);\n if (!hdNode.valid) {\n throw Error(\"Invalid private key derived from mnemonic seed\");\n }\n let zerothChild = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_16__.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_4__.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_17__.DERIVATION_PATHS);\n }\n }\n else {\n throw Error(\"xpubkeys can only be derived from seed type wallets.\");\n }\n }\n // Initialize wallet from a mnemonic phrase\n async fromSeed(mnemonic, derivationPath) {\n this.mnemonic = mnemonic.trim().toLowerCase();\n if (this.mnemonic.length == 0)\n throw Error(\"refusing to create wallet from empty mnemonic\");\n let seed = (0,_scure_bip39__WEBPACK_IMPORTED_MODULE_0__.mnemonicToSeedSync)(this.mnemonic);\n (0,_util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_14__.checkForEmptySeed)(seed);\n let hdNode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_16__.deriveHdPrivateNodeFromSeed)(seed);\n if (!hdNode.valid) {\n throw Error(\"Invalid private key derived from mnemonic seed\");\n }\n if (derivationPath) {\n this.derivationPath = derivationPath;\n // If the derivation path is for the first account child, set the parent derivation path\n let path = derivationPath.split(\"/\");\n if (path.slice(-2).join(\"/\") == \"0/0\") {\n this.parentDerivationPath = path.slice(0, -2).join(\"/\");\n }\n }\n let zerothChild = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_16__.deriveHdPath)(hdNode, this.derivationPath);\n if (typeof zerothChild === \"string\") {\n throw Error(zerothChild);\n }\n this.privateKey = zerothChild.privateKey;\n let network = this.isTestnet ? \"testnet\" : \"mainnet\";\n this.parentXPubKey = await (0,_util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_15__.getXPubKey)(seed, this.parentDerivationPath, network);\n this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Seed;\n await this.deriveInfo();\n return this;\n }\n // Get common xpub paths from zerothChild privateKey\n async deriveHdPaths(hdPaths) {\n if (!this.mnemonic)\n throw Error(\"refusing to create wallet from empty mnemonic\");\n let seed = (0,_scure_bip39__WEBPACK_IMPORTED_MODULE_0__.mnemonicToSeedSync)(this.mnemonic);\n (0,_util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_14__.checkForEmptySeed)(seed);\n let hdNode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_16__.deriveHdPrivateNodeFromSeed)(seed);\n if (!hdNode.valid) {\n throw Error(\"Invalid private key derived from mnemonic seed\");\n }\n let result = [];\n for (const path of hdPaths) {\n if (path === \"m\") {\n throw Error(\"Storing or sharing of parent public key may lead to loss of funds. Storing or sharing *root* parent public keys is strongly discouraged, although all parent keys have risk. See: https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#implications\");\n }\n let childNode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_16__.deriveHdPath)(hdNode, path);\n if (typeof childNode === \"string\") {\n throw Error(childNode);\n }\n let node = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_16__.deriveHdPublicNode)(childNode);\n if (typeof node === \"string\") {\n throw Error(node);\n }\n let xPubKey = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_16__.encodeHdPublicKey)({\n network: this.network,\n node: node,\n });\n let key = new _model_js__WEBPACK_IMPORTED_MODULE_18__.XPubKey({\n path: path,\n xPubKey: xPubKey,\n });\n result.push(await key.ready());\n }\n return await Promise.all(result).then((result) => {\n return result;\n });\n }\n // Initialize a watch only wallet from a cash addr\n async watchOnly(address) {\n this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Watch;\n let addressComponents = address.split(\":\");\n let addressPrefix, addressBase;\n if (addressComponents.length === 1) {\n addressBase = addressComponents.shift();\n addressPrefix = (0,_util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_11__.derivePrefix)(addressBase);\n }\n else {\n addressPrefix = addressComponents.shift();\n addressBase = addressComponents.shift();\n if (addressPrefix in _enum_js__WEBPACK_IMPORTED_MODULE_3__.networkPrefixMap) {\n if (_enum_js__WEBPACK_IMPORTED_MODULE_3__.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 let addressData = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_19__.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_19__.CashAddressType.p2pkhWithTokens)\n nonTokenAwareType = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_19__.CashAddressType.p2pkh;\n if (nonTokenAwareType == _bitauth_libauth__WEBPACK_IMPORTED_MODULE_19__.CashAddressType.p2shWithTokens)\n nonTokenAwareType = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_19__.CashAddressType.p2sh;\n if (nonTokenAwareType == _bitauth_libauth__WEBPACK_IMPORTED_MODULE_19__.CashAddressType.p2pkh)\n this.publicKeyHash = addressData.payload;\n this.cashaddr = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_19__.encodeCashAddress)(addressData.prefix, nonTokenAwareType, addressData.payload);\n this.address = this.cashaddr;\n this.tokenaddr = (0,_util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_20__.deriveTokenaddr)(addressData.payload, this.networkPrefix);\n return this;\n }\n // Initialize wallet from Wallet Import Format\n async fromWIF(secret) {\n (0,_util_checkWifNetwork_js__WEBPACK_IMPORTED_MODULE_21__.checkWifNetwork)(secret, this.network);\n let wifResult = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_22__.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_4__.WalletTypeEnum.Wif;\n await this.deriveInfo();\n return this;\n }\n async newRandom(name, dbName) {\n dbName = dbName ? dbName : this.networkPrefix;\n return super.newRandom(name, dbName);\n }\n async named(name, dbName, forceNew = false) {\n dbName = dbName ? dbName : this.networkPrefix;\n return super.named(name, dbName, forceNew);\n }\n async replaceNamed(name, walletId, dbName) {\n dbName = dbName ? dbName : this.networkPrefix;\n return super.replaceNamed(name, walletId, dbName);\n }\n async namedExists(name, dbName) {\n dbName = dbName ? dbName : this.networkPrefix;\n return super.namedExists(name, dbName);\n }\n //#endregion Protected Implementations\n //#region Serialization\n // Returns the serialized wallet as a string\n // If storing in a database, set asNamed to false to store secrets\n // In all other cases, the a named wallet is deserialized from the database\n // by the name key\n toString() {\n const result = super.toString();\n if (result)\n return result;\n if (this.walletType === _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Wif) {\n return `${this.walletType}:${this.network}:${this.privateKeyWif}`;\n }\n throw Error(\"toString unsupported wallet type\");\n }\n //\n toDbString() {\n const result = super.toDbString();\n if (result)\n return result;\n if (this.walletType === _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Wif) {\n return `${this.walletType}:${this.network}:${this.privateKeyWif}`;\n }\n throw Error(\"toDbString unsupported wallet type\");\n }\n //#endregion Serialization\n //#region Funds\n //\n async getAddressUtxos(address) {\n if (!address) {\n address = this.cashaddr;\n }\n if (this._slpSemiAware) {\n const bchUtxos = await this.provider.getUtxos(address);\n return bchUtxos.filter((bchutxo) => bchutxo.satoshis > _constant_js__WEBPACK_IMPORTED_MODULE_17__.DUST_UTXO_THRESHOLD);\n }\n else {\n return await this.provider.getUtxos(address);\n }\n }\n /**\n * utxos Get unspent outputs for the wallet\n *\n */\n async getUtxos() {\n if (!this.cashaddr) {\n throw Error(\"Attempted to get utxos without an address\");\n }\n return await this.getAddressUtxos(this.cashaddr);\n }\n // gets wallet balance in sats, bch and currency\n async getBalance(rawUnit, priceCache = true) {\n if (rawUnit) {\n const unit = (0,_util_sanitizeUnit_js__WEBPACK_IMPORTED_MODULE_23__.sanitizeUnit)(rawUnit);\n return await (0,_util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_24__.balanceFromSatoshi)(await this.getBalanceFromProvider(), unit, priceCache);\n }\n else {\n return await (0,_util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_24__.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_sumUtxoValue_js__WEBPACK_IMPORTED_MODULE_25__.sumUtxoValue)(utxos);\n }\n // Gets balance from fulcrum\n async getBalanceFromProvider() {\n // Fulcrum reports balance of all utxos, including tokens, which is undesirable\n // // TODO not sure why getting the balance from a provider doesn't work\n // if (this._slpAware || this._slpSemiAware) {\n // return await this.getBalanceFromUtxos();\n // } else {\n // return await this.provider!.getBalance(this.cashaddr!);\n // }\n // FIXME\n return this.getBalanceFromUtxos();\n }\n // watching for any transaction hash of this wallet\n watchAddress(callback) {\n return this.provider.watchAddress(this.getDepositAddress(), callback);\n }\n // watching for any transaction of this wallet\n watchAddressTransactions(callback) {\n return this.provider.watchAddressTransactions(this.getDepositAddress(), callback);\n }\n // watching for cashtoken transaction of this wallet\n watchAddressTokenTransactions(callback) {\n return this.provider.watchAddressTokenTransactions(this.getDepositAddress(), callback);\n }\n // sets up a callback to be called upon wallet's balance change\n // can be cancelled by calling the function returned from this one\n watchBalance(callback) {\n return this.provider.watchAddressStatus(this.getDepositAddress(), async (_status) => {\n const balance = (await this.getBalance());\n callback(balance);\n });\n }\n // sets up a callback to be called upon wallet's BCH or USD balance change\n // if BCH balance does not change, the callback will be triggered every\n // @param `usdPriceRefreshInterval` milliseconds by polling for new BCH USD price\n // Since we want to be most sensitive to usd value change, we do not use the cached exchange rates\n // can be cancelled by calling the function returned from this one\n watchBalanceUsd(callback, usdPriceRefreshInterval = 30000) {\n let usdPrice = -1;\n const _callback = async () => {\n const balance = (await this.getBalance(undefined, false));\n if (usdPrice !== balance.usd) {\n usdPrice = balance.usd;\n callback(balance);\n }\n };\n const watchCancel = this.provider.watchAddressStatus(this.getDepositAddress(), _callback);\n const interval = setInterval(_callback, usdPriceRefreshInterval);\n return async () => {\n await watchCancel();\n clearInterval(interval);\n };\n }\n // waits for address balance to be greater than or equal to the target value\n // this call halts the execution\n async waitForBalance(value, rawUnit = _enum_js__WEBPACK_IMPORTED_MODULE_3__.UnitEnum.BCH) {\n return new Promise(async (resolve) => {\n const watchCancel = this.watchBalance(async (balance) => {\n const satoshiBalance = await (0,_util_amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_26__.amountInSatoshi)(value, rawUnit);\n if (balance.sat >= satoshiBalance) {\n await watchCancel();\n resolve(balance);\n }\n });\n });\n }\n // sets up a callback to be called upon wallet's token balance change\n // can be cancelled by calling the function returned from this one\n watchTokenBalance(tokenId, callback) {\n let previous = undefined;\n return this.provider.watchAddressStatus(this.getDepositAddress(), async (_status) => {\n const balance = await this.getTokenBalance(tokenId);\n if (previous != balance) {\n callback(balance);\n }\n previous = balance;\n });\n }\n // waits for address token balance to be greater than or equal to the target amount\n // this call halts the execution\n async waitForTokenBalance(tokenId, amount) {\n return new Promise(async (resolve) => {\n const watchCancel = this.watchTokenBalance(tokenId, async (balance) => {\n if (balance >= amount) {\n await watchCancel();\n resolve(balance);\n }\n });\n });\n }\n async getTokenInfo(tokenId) {\n return _Bcmr_js__WEBPACK_IMPORTED_MODULE_27__.BCMR.getTokenInfo(tokenId);\n }\n async _getMaxAmountToSend(params = {\n outputCount: 1,\n options: {},\n }) {\n if (!this.privateKey && params.options?.buildUnsigned !== true) {\n throw Error(\"Couldn't get network or private key for wallet.\");\n }\n if (!this.cashaddr) {\n throw Error(\"attempted to send without a cashaddr\");\n }\n if (params.options && params.options.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_4__.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_28__.checkUtxos)(params.options.utxoIds.map((utxoId) => typeof utxoId === \"string\" ? (0,_model_js__WEBPACK_IMPORTED_MODULE_18__.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_18__.SendRequest({\n cashaddr: this.cashaddr,\n value: 100,\n unit: \"sat\",\n });\n const sendRequests = Array(params.outputCount)\n .fill(0)\n .map(() => sendRequest);\n const fundingUtxos = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_29__.getSuitableUtxos)(utxos, undefined, bestHeight, feePaidBy, sendRequests);\n const relayFeePerByteInSatoshi = await (0,_network_getRelayFeeCache_js__WEBPACK_IMPORTED_MODULE_1__.getRelayFeeCache)(this.provider);\n const fee = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_29__.getFeeAmountSimple)({\n utxos: fundingUtxos,\n sendRequests: sendRequests,\n privateKey: this.privateKey ?? Uint8Array.from([]),\n sourceAddress: this.cashaddr,\n relayFeePerByteInSatoshi: relayFeePerByteInSatoshi,\n feePaidBy: feePaidBy,\n });\n const spendableAmount = (0,_util_sumUtxoValue_js__WEBPACK_IMPORTED_MODULE_25__.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_24__.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_18__.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_10__.binToHex)(encodedTransaction);\n resp.sourceOutputs = sourceOutputs;\n }\n return resp;\n }\n /**\n * sendMax Send all available funds to a destination cash address\n *\n * @param {string} cashaddr destination cash address\n * @param {SendRequestOptionsI} options Options of the send requests\n *\n * @returns (depending on the options parameter) the transaction id, new address balance and a link to the transaction on the blockchain explorer\n */\n async sendMax(cashaddr, options) {\n return await this.sendMaxRaw(cashaddr, options);\n }\n /**\n * sendMaxRaw (internal) Send all available funds to a destination cash address\n *\n * @param {string} cashaddr destination cash address\n * @param {SendRequestOptionsI} options Options of the send requests\n *\n * @returns the transaction id sent to the network\n */\n async sendMaxRaw(cashaddr, options) {\n const { value: maxSpendableAmount, utxos } = await this._getMaxAmountToSend({\n outputCount: 1,\n options: options,\n });\n if (!options) {\n options = {};\n }\n options.utxoIds = utxos;\n const sendRequest = new _model_js__WEBPACK_IMPORTED_MODULE_18__.SendRequest({\n cashaddr: cashaddr,\n value: maxSpendableAmount,\n unit: \"sat\",\n });\n const { encodedTransaction, tokenIds, sourceOutputs } = await this.encodeTransaction([sendRequest], true, options);\n const resp = new _model_js__WEBPACK_IMPORTED_MODULE_18__.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_10__.binToHex)(encodedTransaction);\n resp.sourceOutputs = sourceOutputs;\n }\n return resp;\n }\n /**\n * encodeTransaction Encode and sign a transaction given a list of sendRequests, options and estimate fees.\n * @param {SendRequest[]} sendRequests SendRequests\n * @param {boolean} discardChange=false\n * @param {SendRequestOptionsI} options Options of the send requests\n */\n async encodeTransaction(requests, discardChange = false, options) {\n let sendRequests = (0,_util_asSendRequestObject_js__WEBPACK_IMPORTED_MODULE_30__.asSendRequestObject)(requests);\n if (!this.privateKey && options?.buildUnsigned !== true) {\n throw new Error(`Wallet ${this.name} is missing either a network or private key`);\n }\n if (!this.cashaddr) {\n throw Error(\"attempted to send without a cashaddr\");\n }\n if (options && options.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_4__.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_28__.checkUtxos)(options.utxoIds.map((utxoId) => typeof utxoId === \"string\" ? (0,_model_js__WEBPACK_IMPORTED_MODULE_18__.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_18__.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_18__.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_18__.TokenSendRequest({\n cashaddr: (0,_util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_20__.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_31__.sumSendRequestAmounts)(sendRequests);\n if (utxos.length === 0) {\n throw Error(\"There were no Unspent Outputs\");\n }\n if (typeof spendAmount !== \"bigint\") {\n throw Error(\"Couldn't get spend amount when building transaction\");\n }\n const relayFeePerByteInSatoshi = await (0,_network_getRelayFeeCache_js__WEBPACK_IMPORTED_MODULE_1__.getRelayFeeCache)(this.provider);\n const feeEstimate = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_29__.getFeeAmountSimple)({\n utxos: utxos,\n sendRequests: sendRequests,\n privateKey: this.privateKey ?? Uint8Array.from([]),\n sourceAddress: this.cashaddr,\n relayFeePerByteInSatoshi: relayFeePerByteInSatoshi,\n feePaidBy: feePaidBy,\n });\n const fundingUtxos = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_29__.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_29__.getFeeAmount)({\n utxos: fundingUtxos,\n sendRequests: sendRequests,\n privateKey: this.privateKey ?? Uint8Array.from([]),\n sourceAddress: this.cashaddr,\n relayFeePerByteInSatoshi: relayFeePerByteInSatoshi,\n feePaidBy: feePaidBy,\n });\n const { encodedTransaction, sourceOutputs } = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_29__.buildEncodedTransaction)({\n inputs: fundingUtxos,\n outputs: sendRequests,\n signingKey: this.privateKey ?? Uint8Array.from([]),\n sourceAddress: this.cashaddr,\n fee,\n discardChange,\n 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_18__.TokenSendRequest)\n .map((val) => val.tokenId),\n ].filter((value, index, array) => array.indexOf(value) === index);\n return { encodedTransaction, tokenIds, sourceOutputs };\n }\n async signUnsignedTransaction(transaction, sourceOutputs) {\n if (!this.privateKey) {\n throw Error(\"Can not sign a transaction with watch-only wallet.\");\n }\n return (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_29__.signUnsignedTransaction)(transaction, sourceOutputs, this.privateKey);\n }\n // Submit a raw transaction\n async submitTransaction(transaction, awaitPropagation = true) {\n if (!this.provider) {\n throw Error(\"Wallet network provider was not initialized\");\n }\n let rawTransaction = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__.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_32__.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 const waitForTransactionCallback = async (data) => {\n if (data && data[0] === options.txHash) {\n txHashSeen = true;\n this.provider.unsubscribeFromTransaction(options.txHash, waitForTransactionCallback);\n resolve(makeResponse(options.txHash));\n }\n };\n this.provider.subscribeToTransaction(options.txHash, waitForTransactionCallback);\n return;\n }\n // waiting for any address transaction\n const watchCancel = this.provider.watchAddressStatus(this.getDepositAddress(), async (_status) => {\n watchCancel();\n resolve(makeResponse());\n });\n });\n }\n /**\n * watchBlocks Watch network blocks\n *\n * @param callback callback with a block header object\n * @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 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 //#region Private implementation details\n async deriveInfo() {\n const publicKey = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_33__.secp256k1.derivePublicKeyUncompressed(this.privateKey);\n if (typeof publicKey === \"string\") {\n throw new Error(publicKey);\n }\n this.publicKey = publicKey;\n const publicKeyCompressed = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_33__.secp256k1.derivePublicKeyCompressed(this.privateKey);\n if (typeof publicKeyCompressed === \"string\") {\n throw new Error(publicKeyCompressed);\n }\n this.publicKeyCompressed = publicKeyCompressed;\n const networkType = this.network === _enum_js__WEBPACK_IMPORTED_MODULE_3__.NetworkType.Regtest ? _enum_js__WEBPACK_IMPORTED_MODULE_3__.NetworkType.Testnet : this.network;\n this.privateKeyWif = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_22__.encodePrivateKeyWif)(this.privateKey, networkType);\n (0,_util_checkWifNetwork_js__WEBPACK_IMPORTED_MODULE_21__.checkWifNetwork)(this.privateKeyWif, this.network);\n this.cashaddr = (0,_util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_20__.deriveCashaddr)(this.privateKey, this.networkPrefix);\n this.tokenaddr = (0,_util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_20__.deriveTokenaddr)(this.privateKey, this.networkPrefix);\n this.address = this.cashaddr;\n this.publicKeyHash = (0,_util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_11__.derivePublicKeyHash)(this.cashaddr);\n return this;\n }\n //#endregion Private implementation details\n //#region Signing\n // Convenience wrapper to sign interface\n async sign(message) {\n return await Wallet.signedMessage.sign(message, this.privateKey);\n }\n // Convenience wrapper to verify interface\n async verify(message, sig, publicKey) {\n return await Wallet.signedMessage.verify(message, sig, this.cashaddr, publicKey);\n }\n //#endregion Signing\n //#region Cashtokens\n /**\n * Create new cashtoken, both funglible and/or non-fungible (NFT)\n * Refer to spec https://github.com/bitjson/cashtokens\n * @param {number} genesisRequest.amount amount of *fungible* tokens to create\n * @param {NFTCapability?} genesisRequest.capability capability of new NFT\n * @param {string?} genesisRequest.commitment NFT commitment message\n * @param {string?} genesisRequest.cashaddr cash address to send the created token UTXO to; if undefined will default to your address\n * @param {number?} genesisRequest.value satoshi value to send alongside with tokens; if undefined will default to 1000 satoshi\n * @param {SendRequestType | SendRequestType[]} sendRequests single or an array of extra send requests (OP_RETURN, value transfer, etc.) to include in genesis transaction\n * @param {SendRequestOptionsI} options Options of the send requests\n */\n async tokenGenesis(genesisRequest, sendRequests = [], options) {\n if (!Array.isArray(sendRequests)) {\n sendRequests = [sendRequests];\n }\n let utxos;\n if (options && options.utxoIds) {\n utxos = await (0,_util_checkUtxos_js__WEBPACK_IMPORTED_MODULE_28__.checkUtxos)(options.utxoIds.map((utxoId) => typeof utxoId === \"string\" ? (0,_model_js__WEBPACK_IMPORTED_MODULE_18__.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_18__.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_7__.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_18__.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_18__.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_18__.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_18__.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_18__.OpReturnData.fromString(message || \"\");\n return this.send([opReturn, ...changeSendRequests], {\n ...options,\n checkTokenQuantities: false,\n queryBalance: false,\n ensureUtxos: utxoIds.length > 0 ? utxoIds : undefined,\n tokenOperation: \"burn\",\n });\n }\n /**\n * getTokenUtxos Get unspent token outputs for the wallet\n * will return utxos only for the specified token if `tokenId` provided\n * @param {string?} tokenId tokenId (category) to filter utxos by, if not set will return utxos from all tokens\n * @returns {UtxoI[]} token utxos\n */\n async getTokenUtxos(tokenId) {\n const utxos = await this.getAddressUtxos(this.address);\n return utxos.filter((val) => tokenId ? val.token?.tokenId === tokenId : val.token);\n }\n /**\n * getTokenBalance Gets fungible token balance\n * for NFT token balance see @ref getNftTokenBalance\n * @param {string} tokenId tokenId to get balance for\n * @returns {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_sumUtxoValue_js__WEBPACK_IMPORTED_MODULE_25__.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}\nWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_19__.CashAddressNetworkPrefix.mainnet;\nWallet.signedMessage = new _message_index_js__WEBPACK_IMPORTED_MODULE_34__.SignedMessage();\n/**\n * Class to manage a testnet wallet.\n */\nclass TestNetWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_3__.NetworkType.Testnet);\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_6__.TestNetUtil;\n }\n}\nTestNetWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_19__.CashAddressNetworkPrefix.testnet;\nTestNetWallet.faucetServer = \"https://rest-unstable.mainnet.cash\";\n/**\n * Class to manage a regtest wallet.\n */\nclass RegTestWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_3__.NetworkType.Regtest);\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_6__.RegTestUtil;\n }\n}\nRegTestWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_19__.CashAddressNetworkPrefix.regtest;\n/**\n * Class to manage a bitcoin cash wif wallet.\n */\nclass WifWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_3__.NetworkType.Mainnet, _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Wif);\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_6__.WifUtil;\n }\n}\nWifWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_19__.CashAddressNetworkPrefix.mainnet;\nWifWallet.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Wif;\n/**\n * Class to manage a testnet wif wallet.\n */\nclass TestNetWifWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_3__.NetworkType.Testnet, _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Wif);\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_6__.TestNetWifUtil;\n }\n}\nTestNetWifWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_19__.CashAddressNetworkPrefix.testnet;\nTestNetWifWallet.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Wif;\n/**\n * Class to manage a regtest wif wallet.\n */\nclass RegTestWifWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_3__.NetworkType.Regtest, _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Wif);\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_6__.RegTestWifUtil;\n }\n}\nRegTestWifWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_19__.CashAddressNetworkPrefix.regtest;\nRegTestWifWallet.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Wif;\n/**\n * Class to manage a bitcoin cash watch wallet.\n */\nclass WatchWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_3__.NetworkType.Mainnet, _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Watch);\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_6__.WatchUtil;\n }\n}\nWatchWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_19__.CashAddressNetworkPrefix.mainnet;\nWatchWallet.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Watch;\n/**\n * Class to manage a testnet watch wallet.\n */\nclass TestNetWatchWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_3__.NetworkType.Testnet, _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Watch);\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_6__.TestNetWatchUtil;\n }\n}\nTestNetWatchWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_19__.CashAddressNetworkPrefix.testnet;\nTestNetWatchWallet.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Watch;\n/**\n * Class to manage a regtest watch wallet.\n */\nclass RegTestWatchWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_3__.NetworkType.Regtest, _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Watch);\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_6__.RegTestWatchUtil;\n }\n}\nRegTestWatchWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_19__.CashAddressNetworkPrefix.regtest;\nRegTestWatchWallet.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Watch;\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/wallet/Wif.ts?");
|
|
708
718
|
|
|
709
719
|
/***/ }),
|
|
710
720
|
|