mainnet-js 3.0.0-next.1 → 3.0.0-next.2
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-3.0.0-next.1.js → mainnet-3.0.0-next.2.js} +7 -7
- package/dist/module/history/getHistory.js +17 -17
- package/dist/module/history/getHistory.js.map +1 -1
- package/dist/module/history/interface.d.ts +1 -1
- package/dist/module/history/interface.d.ts.map +1 -1
- package/dist/module/interface.d.ts +5 -3
- package/dist/module/interface.d.ts.map +1 -1
- package/dist/module/interface.js.map +1 -1
- package/dist/module/network/ElectrumNetworkProvider.d.ts.map +1 -1
- package/dist/module/network/ElectrumNetworkProvider.js +1 -3
- package/dist/module/network/ElectrumNetworkProvider.js.map +1 -1
- package/dist/module/network/interface.d.ts +2 -2
- package/dist/module/network/interface.d.ts.map +1 -1
- package/dist/module/transaction/Wif.d.ts.map +1 -1
- package/dist/module/transaction/Wif.js +25 -23
- package/dist/module/transaction/Wif.js.map +1 -1
- package/dist/module/util/asSendRequestObject.js +2 -2
- package/dist/module/util/asSendRequestObject.js.map +1 -1
- package/dist/module/util/sumUtxoValue.js +1 -1
- package/dist/module/util/sumUtxoValue.js.map +1 -1
- package/dist/module/wallet/Base.d.ts +18 -18
- package/dist/module/wallet/Base.d.ts.map +1 -1
- package/dist/module/wallet/Base.js +64 -69
- package/dist/module/wallet/Base.js.map +1 -1
- package/dist/module/wallet/HDWallet.d.ts +1 -1
- package/dist/module/wallet/Wif.d.ts +1 -1
- package/dist/module/wallet/model.d.ts +41 -25
- package/dist/module/wallet/model.d.ts.map +1 -1
- package/dist/module/wallet/model.js +10 -14
- package/dist/module/wallet/model.js.map +1 -1
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/package.json +1 -1
- package/src/history/getHistory.ts +17 -17
- package/src/history/interface.ts +1 -1
- package/src/interface.ts +5 -3
- package/src/network/ElectrumNetworkProvider.ts +1 -3
- package/src/network/interface.ts +2 -2
- package/src/transaction/Wif.ts +27 -23
- package/src/util/asSendRequestObject.ts +2 -2
- package/src/util/sumUtxoValue.ts +1 -1
- package/src/wallet/Base.ts +67 -72
- package/src/wallet/Cashtokens.test.headless.js +217 -162
- package/src/wallet/Cashtokens.test.ts +470 -369
- package/src/wallet/HDWallet.test.ts +36 -24
- package/src/wallet/model.ts +49 -41
|
@@ -164,7 +164,7 @@ eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__
|
|
|
164
164
|
\***********************************/
|
|
165
165
|
/***/ ((module, __webpack_exports__, __webpack_require__) => {
|
|
166
166
|
|
|
167
|
-
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 */ \"getHistory\": () => (/* binding */ getHistory)\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/format/error.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/address/cash-address.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/address/locking-bytecode.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/vm/instruction-sets/instruction-sets.js\");\n/* harmony import */ var _util_convert_js__WEBPACK_IMPORTED_MODULE_6__ = __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_4__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_5__, _util_convert_js__WEBPACK_IMPORTED_MODULE_6__]);\n([_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_5__, _util_convert_js__WEBPACK_IMPORTED_MODULE_6__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\nconst getHistory = async ({ addresses, provider, unit = \"sat\", fromHeight = 0, toHeight = -1, start = 0, count = -1, }) => {\n if (!addresses.length) {\n return [];\n }\n if (count === -1) {\n count = 1e10;\n }\n const history = (await Promise.all(addresses.map(async (address) => provider.getHistory(address, fromHeight, toHeight))))\n .flat()\n .filter((value, index, array) => array.findIndex((item) => item.tx_hash === value.tx_hash) === index)\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 uniqueHeights = 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(uniqueHeights.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 if (hash ===\n \"0000000000000000000000000000000000000000000000000000000000000000\") {\n return [hash, undefined];\n }\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__.assertSuccess)((0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.decodeCashAddress)(addresses[0]));\n const prefix = decoded.prefix;\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 const isCoinbase = tx.inputs.length === 1 &&\n tx.inputs[0].outpointTransactionHash.every((b) => b === 0);\n result.inputs = tx.inputs.map((input) => {\n if (isCoinbase) {\n const halvings = Math.floor(tx.blockHeight / 210000);\n const subsidy = Math.floor(5000000000 / 2 ** halvings);\n inputTotalValue += BigInt(subsidy);\n return {\n address: \"coinbase\",\n value: subsidy,\n };\n }\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_2__.assertSuccess)((0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__.lockingBytecodeToCashAddress)({\n bytecode: prevoutOutput.lockingBytecode,\n prefix: prefix,\n })).address;\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.lockingBytecode[0] === _bitauth_libauth__WEBPACK_IMPORTED_MODULE_5__.Opcodes.OP_RETURN) {\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_2__.assertSuccess)((0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__.lockingBytecodeToCashAddress)({\n bytecode: output.lockingBytecode,\n prefix: prefix,\n })).address;\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 if (isCoinbase && result.fee) {\n // will indicate the fees collected by the miner\n result.fee = -result.fee;\n }\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 (addresses.includes(input.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 (addresses.includes(output.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 Promise.all(addresses.map((address) => provider.getBalance(address)))).reduce((a, b) => a + b, 0);\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_6__.convert)(input.value, \"sat\", unit);\n }\n for (const output of tx.outputs) {\n output.value = await (0,_util_convert_js__WEBPACK_IMPORTED_MODULE_6__.convert)(output.value, \"sat\", unit);\n }\n tx.valueChange = await (0,_util_convert_js__WEBPACK_IMPORTED_MODULE_6__.convert)(tx.valueChange, \"sat\", unit);\n tx.balance = await (0,_util_convert_js__WEBPACK_IMPORTED_MODULE_6__.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/getHistory.ts?");
|
|
167
|
+
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 */ \"getHistory\": () => (/* binding */ getHistory)\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/format/error.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/address/cash-address.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/address/locking-bytecode.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/vm/instruction-sets/instruction-sets.js\");\n/* harmony import */ var _util_convert_js__WEBPACK_IMPORTED_MODULE_6__ = __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_4__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_5__, _util_convert_js__WEBPACK_IMPORTED_MODULE_6__]);\n([_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_5__, _util_convert_js__WEBPACK_IMPORTED_MODULE_6__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\nconst getHistory = async ({ addresses, provider, unit = \"sat\", fromHeight = 0, toHeight = -1, start = 0, count = -1, }) => {\n if (!addresses.length) {\n return [];\n }\n if (count === -1) {\n count = 1e10;\n }\n const history = (await Promise.all(addresses.map(async (address) => provider.getHistory(address, fromHeight, toHeight))))\n .flat()\n .filter((value, index, array) => array.findIndex((item) => item.tx_hash === value.tx_hash) === index)\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 uniqueHeights = 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(uniqueHeights.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 if (hash ===\n \"0000000000000000000000000000000000000000000000000000000000000000\") {\n return [hash, undefined];\n }\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__.assertSuccess)((0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.decodeCashAddress)(addresses[0]));\n const prefix = decoded.prefix;\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 const isCoinbase = tx.inputs.length === 1 &&\n tx.inputs[0].outpointTransactionHash.every((b) => b === 0);\n result.inputs = tx.inputs.map((input) => {\n if (isCoinbase) {\n const halvings = Math.floor(tx.blockHeight / 210000);\n const subsidy = Math.floor(5000000000 / 2 ** halvings);\n inputTotalValue += BigInt(subsidy);\n return {\n address: \"coinbase\",\n value: subsidy,\n };\n }\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_2__.assertSuccess)((0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__.lockingBytecodeToCashAddress)({\n bytecode: prevoutOutput.lockingBytecode,\n prefix: prefix,\n })).address;\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 category: (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.lockingBytecode[0] === _bitauth_libauth__WEBPACK_IMPORTED_MODULE_5__.Opcodes.OP_RETURN) {\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_2__.assertSuccess)((0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__.lockingBytecodeToCashAddress)({\n bytecode: output.lockingBytecode,\n prefix: prefix,\n })).address;\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 category: (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 if (isCoinbase && result.fee) {\n // will indicate the fees collected by the miner\n result.fee = -result.fee;\n }\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 (addresses.includes(input.address)) {\n satoshiBalance -= input.value;\n if (input.token?.amount) {\n ftTokenBalances[input.token.category] =\n (ftTokenBalances[input.token.category] || BigInt(0)) -\n input.token.amount;\n }\n if (input.token?.nft?.capability) {\n nftTokenBalances[input.token.category] =\n (nftTokenBalances[input.token.category] || BigInt(0)) - 1n;\n }\n }\n });\n tx.outputs.forEach((output) => {\n if (addresses.includes(output.address)) {\n satoshiBalance += Number(output.value);\n if (output.token?.amount) {\n ftTokenBalances[output.token.category] =\n (ftTokenBalances[output.token.category] || BigInt(0)) +\n output.token.amount;\n }\n if (output.token?.nft?.capability) {\n nftTokenBalances[output.token.category] =\n (nftTokenBalances[output.token.category] || BigInt(0)) + 1n;\n }\n }\n });\n tx.valueChange = satoshiBalance;\n tx.tokenAmountChanges = Object.entries(ftTokenBalances).map(([category, amount]) => ({\n category,\n amount,\n nftAmount: BigInt(0),\n }));\n for (const [category, nftAmount] of Object.entries(nftTokenBalances)) {\n const tokenChange = tx.tokenAmountChanges.find((tokenChange) => tokenChange.category === category);\n if (tokenChange) {\n tokenChange.nftAmount = nftAmount;\n }\n else {\n tx.tokenAmountChanges.push({\n category: category,\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 Promise.all(addresses.map((address) => provider.getBalance(address)))).reduce((a, b) => a + b, 0);\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_6__.convert)(input.value, \"sat\", unit);\n }\n for (const output of tx.outputs) {\n output.value = await (0,_util_convert_js__WEBPACK_IMPORTED_MODULE_6__.convert)(output.value, \"sat\", unit);\n }\n tx.valueChange = await (0,_util_convert_js__WEBPACK_IMPORTED_MODULE_6__.convert)(tx.valueChange, \"sat\", unit);\n tx.balance = await (0,_util_convert_js__WEBPACK_IMPORTED_MODULE_6__.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/getHistory.ts?");
|
|
168
168
|
|
|
169
169
|
/***/ }),
|
|
170
170
|
|
|
@@ -244,7 +244,7 @@ eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__
|
|
|
244
244
|
\************************************************/
|
|
245
245
|
/***/ ((module, __webpack_exports__, __webpack_require__) => {
|
|
246
246
|
|
|
247
|
-
eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"default\": () => (/* binding */ ElectrumNetworkProvider)\n/* harmony export */ });\n/* harmony import */ var _electrum_cash_network__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @electrum-cash/network */ \"../../node_modules/@electrum-cash/network/dist/index.mjs\");\n/* harmony import */ var _interface_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../interface.js */ \"./src/interface.ts\");\n/* harmony import */ var _util_transaction_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../util/transaction.js */ \"./src/util/transaction.ts\");\n/* harmony import */ var _config_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../config.js */ \"./src/config.ts\");\n/* harmony import */ var _util_header_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../util/header.js */ \"./src/util/header.ts\");\n/* harmony import */ var _cache_IndexedDbCache_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../cache/IndexedDbCache.js */ \"./src/cache/IndexedDbCache.ts\");\n/* harmony import */ var _cache_WebStorageCache_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../cache/WebStorageCache.js */ \"./src/cache/WebStorageCache.ts\");\n/* harmony import */ var _cache_MemoryCache_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../cache/MemoryCache.js */ \"./src/cache/MemoryCache.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_util_header_js__WEBPACK_IMPORTED_MODULE_6__, _util_transaction_js__WEBPACK_IMPORTED_MODULE_7__]);\n([_util_header_js__WEBPACK_IMPORTED_MODULE_6__, _util_transaction_js__WEBPACK_IMPORTED_MODULE_7__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\n\n\n\n\n\n\nclass ElectrumNetworkProvider {\n get cache() {\n if (!_config_js__WEBPACK_IMPORTED_MODULE_1__.Config.UseMemoryCache &&\n !_config_js__WEBPACK_IMPORTED_MODULE_1__.Config.UseLocalStorageCache &&\n !_config_js__WEBPACK_IMPORTED_MODULE_1__.Config.UseIndexedDBCache) {\n this._cache = undefined;\n return this._cache;\n }\n if (_config_js__WEBPACK_IMPORTED_MODULE_1__.Config.UseMemoryCache && !(this._cache instanceof _cache_MemoryCache_js__WEBPACK_IMPORTED_MODULE_2__.MemoryCache)) {\n this._cache = new _cache_MemoryCache_js__WEBPACK_IMPORTED_MODULE_2__.MemoryCache();\n return this._cache;\n }\n if (_config_js__WEBPACK_IMPORTED_MODULE_1__.Config.UseLocalStorageCache &&\n !(this._cache instanceof _cache_WebStorageCache_js__WEBPACK_IMPORTED_MODULE_3__.WebStorageCache)) {\n this._cache = new _cache_WebStorageCache_js__WEBPACK_IMPORTED_MODULE_3__.WebStorageCache();\n return this._cache;\n }\n if (_config_js__WEBPACK_IMPORTED_MODULE_1__.Config.UseIndexedDBCache && !(this._cache instanceof _cache_IndexedDbCache_js__WEBPACK_IMPORTED_MODULE_4__.IndexedDbCache)) {\n this._cache = new _cache_IndexedDbCache_js__WEBPACK_IMPORTED_MODULE_4__.IndexedDbCache();\n return this._cache;\n }\n return this._cache;\n }\n constructor(electrum, network = _interface_js__WEBPACK_IMPORTED_MODULE_5__.Network.MAINNET, manualConnectionManagement) {\n this.network = network;\n this.manualConnectionManagement = manualConnectionManagement;\n this.subscriptions = 0;\n this.subscribedToHeaders = false;\n this.subscriptionMap = {};\n if (electrum) {\n this.electrum = electrum;\n }\n else {\n throw new Error(`A electrum-cash client is required.`);\n }\n }\n async getUtxos(cashaddr) {\n const result = await this.performRequest(\"blockchain.address.listunspent\", cashaddr, \"include_tokens\");\n return result.map((utxo) => ({\n address: cashaddr,\n txid: utxo.tx_hash,\n vout: utxo.tx_pos,\n satoshis: BigInt(utxo.value),\n height: utxo.height,\n token: utxo.token_data\n ? {\n amount: BigInt(utxo.token_data.amount),\n tokenId: utxo.token_data.category,\n capability: utxo.token_data.nft?.capability,\n commitment: utxo.token_data.nft?.commitment,\n }\n : undefined,\n }));\n }\n async getBalance(cashaddr) {\n const result = await this.performRequest(\"blockchain.address.get_balance\", cashaddr);\n return result.confirmed + result.unconfirmed;\n }\n async getHeader(height, verbose = false) {\n const key = `header-${this.network}-${height}-${verbose}`;\n if (this.cache) {\n const cached = await this.cache.getItem(key);\n if (cached) {\n return verbose ? (0,_util_header_js__WEBPACK_IMPORTED_MODULE_6__.decodeHeader)(JSON.parse(cached)) : JSON.parse(cached);\n }\n }\n const result = await this.performRequest(\"blockchain.header.get\", height);\n if (this.cache) {\n await this.cache.setItem(key, JSON.stringify(result));\n }\n return verbose ? (0,_util_header_js__WEBPACK_IMPORTED_MODULE_6__.decodeHeader)(result) : result;\n }\n async getBlockHeight() {\n return (await this.performRequest(\"blockchain.headers.get_tip\"))\n .height;\n }\n async getRawTransaction(txHash, verbose = false, loadInputValues = false) {\n const key = `tx-${this.network}-${txHash}-${verbose}-${loadInputValues}`;\n if (this.cache) {\n const cached = await this.cache.getItem(key);\n if (cached) {\n return verbose ? JSON.parse(cached) : cached;\n }\n }\n try {\n const transaction = (await this.performRequest(\"blockchain.transaction.get\", txHash, verbose));\n if (this.cache) {\n await this.cache.setItem(key, verbose\n ? JSON.stringify(transaction)\n : transaction);\n }\n if (verbose && loadInputValues) {\n // get unique transaction hashes\n const hashes = [...new Set(transaction.vin.map((val) => val.txid))];\n const transactions = await Promise.all(hashes.map((hash) => this.getRawTransactionObject(hash, false)));\n const transactionMap = new Map();\n transactions.forEach((val) => transactionMap.set(val.hash, val));\n transaction.vin.forEach((input) => {\n const output = transactionMap\n .get(input.txid)\n .vout.find((val) => val.n === input.vout);\n input.address = output.scriptPubKey.addresses[0];\n input.value = output.value;\n input.tokenData = output.tokenData;\n });\n }\n return transaction;\n }\n catch (error) {\n if (error.message.indexOf(\"No such mempool or blockchain transaction.\") > -1)\n throw Error(`Could not decode transaction ${txHash}. It might not exist on the current blockchain (${this.network}).`);\n else\n throw error;\n }\n }\n // gets the decoded transaction in human readable form\n async getRawTransactionObject(txHash, loadInputValues = false) {\n return (await this.getRawTransaction(txHash, true, loadInputValues));\n }\n async sendRawTransaction(txHex, awaitPropagation = true) {\n return new Promise(async (resolve, reject) => {\n let txHash = await (0,_util_transaction_js__WEBPACK_IMPORTED_MODULE_7__.getTransactionHash)(txHex);\n if (!awaitPropagation) {\n this.performRequest(\"blockchain.transaction.broadcast\", txHex);\n resolve(txHash);\n }\n else {\n let cancel;\n const waitForTransactionCallback = async (data) => {\n if (data && data[0] === txHash && data[1] !== null) {\n await cancel?.();\n resolve(txHash);\n }\n };\n cancel = await this.subscribeToTransaction(txHash, waitForTransactionCallback);\n this.performRequest(\"blockchain.transaction.broadcast\", txHex).catch(async (error) => {\n await cancel?.();\n reject(error);\n });\n }\n });\n }\n // Get transaction history of a given cashaddr\n async getHistory(cashaddr, fromHeight = 0, toHeight = -1) {\n const result = await this.performRequest(\"blockchain.address.get_history\", cashaddr, fromHeight, toHeight);\n return result;\n }\n // Get the minimum fee a low-priority transaction must pay in order to be accepted to the daemon's memory pool.\n async getRelayFee() {\n const result = (await this.performRequest(\"blockchain.relayfee\"));\n return result;\n }\n async watchAddressStatus(cashaddr, callback) {\n const watchAddressStatusCallback = async (data) => {\n // subscription acknowledgement is the latest known status or null if no status is known\n // status is an array: [ cashaddr, statusHash ]\n if (data instanceof Array) {\n const addr = data[0];\n if (addr !== cashaddr) {\n return;\n }\n const status = data[1];\n callback(status);\n }\n };\n return this.subscribeToAddress(cashaddr, watchAddressStatusCallback);\n }\n async watchAddress(cashaddr, callback) {\n const historyMap = {};\n this.getHistory(cashaddr).then((history) => history.forEach((val) => (historyMap[val.tx_hash] = true)));\n const watchAddressStatusCallback = async () => {\n const newHistory = await this.getHistory(cashaddr);\n // sort history to put unconfirmed transactions in the beginning, then transactions in block height descenting order\n const txHashes = newHistory\n .sort((a, b) => a.height <= 0 || b.height <= 0 ? -1 : b.height - a.height)\n .map((val) => val.tx_hash);\n for (const hash of txHashes) {\n if (!(hash in historyMap)) {\n historyMap[hash] = true;\n callback(hash);\n // exit early to prevent further map lookups\n break;\n }\n }\n };\n return this.watchAddressStatus(cashaddr, watchAddressStatusCallback);\n }\n async watchAddressTransactions(cashaddr, callback) {\n return this.watchAddress(cashaddr, async (txHash) => {\n const tx = await this.getRawTransactionObject(txHash);\n callback(tx);\n });\n }\n async watchAddressTokenTransactions(cashaddr, callback) {\n return this.watchAddress(cashaddr, async (txHash) => {\n const tx = await this.getRawTransactionObject(txHash, true);\n if (tx.vin.some((val) => val.tokenData) ||\n tx.vout.some((val) => val.tokenData)) {\n callback(tx);\n }\n });\n }\n // watch for block headers and block height, if `skipCurrentHeight` is set, the notification about current block will not arrive\n async watchBlocks(callback, skipCurrentHeight = true) {\n let acknowledged = !skipCurrentHeight;\n const waitForBlockCallback = (_header) => {\n if (!acknowledged) {\n acknowledged = true;\n return;\n }\n _header = _header instanceof Array ? _header[0] : _header;\n callback(_header);\n };\n return this.subscribeToHeaders(waitForBlockCallback);\n }\n // Wait for the next block or a block at given blockchain height.\n async waitForBlock(height) {\n return new Promise(async (resolve) => {\n let cancelWatch;\n if (this.electrum.chainHeight && !height) {\n height = this.electrum.chainHeight + 1;\n }\n cancelWatch = await this.watchBlocks(async (header) => {\n if (!height) {\n height = header.height + 1;\n return;\n }\n if (header.height >= height) {\n await cancelWatch?.();\n resolve(header);\n return;\n }\n });\n });\n }\n // subscribe to notifications sent when new block is found, the block header is sent to callback\n async subscribeToHeaders(callback) {\n return this.subscribeRequest(\"blockchain.headers.subscribe\", callback);\n }\n async subscribeToAddress(cashaddr, callback) {\n return this.subscribeRequest(\"blockchain.address.subscribe\", callback, cashaddr);\n }\n async subscribeToTransaction(txHash, callback) {\n return this.subscribeRequest(\"blockchain.transaction.subscribe\", callback, txHash);\n }\n async performRequest(name, ...parameters) {\n await this.ready();\n const requestTimeout = new Promise(function (_resolve, reject) {\n setTimeout(function () {\n reject(\"electrum-cash request timed out, retrying\");\n }, 30000);\n }).catch(function (e) {\n throw e;\n });\n const request = this.electrum.request(name, ...parameters);\n return await Promise.race([request, requestTimeout])\n .then((value) => {\n if (value instanceof Error)\n throw value;\n let result = value;\n return result;\n })\n .catch(async () => {\n return await Promise.race([request, requestTimeout])\n .then((value) => {\n if (value instanceof Error)\n throw value;\n let result = value;\n return result;\n })\n .catch(function (e) {\n throw e;\n });\n });\n }\n async trackSubscription(methodName, ...parameters) {\n const key = `${methodName}-${this.network}-${JSON.stringify(parameters)}`;\n if (this.subscriptionMap[key]) {\n this.subscriptionMap[key]++;\n }\n else {\n this.subscriptionMap[key] = 1;\n }\n await this.electrum.subscribe(methodName, ...parameters);\n }\n async untrackSubscription(methodName, ...parameters) {\n const key = `${methodName}-${this.network}-${JSON.stringify(parameters)}`;\n if (this.subscriptionMap[key]) {\n this.subscriptionMap[key]--;\n if (this.subscriptionMap[key] <= 0) {\n // only really unsubscribe if there are no more subscriptions for this `key`\n delete this.subscriptionMap[key];\n try {\n await this.electrum.unsubscribe(methodName, ...parameters);\n }\n catch { }\n }\n }\n }\n async subscribeRequest(methodName, callback, ...parameters) {\n await this.ready();\n const handler = (data) => {\n if (data.method === methodName) {\n callback(data.params);\n }\n };\n this.electrum.on(\"notification\", handler);\n // safeguard against multiple subscriptions to headers\n if (methodName === \"blockhain.headers.subscribe\") {\n if (!this.subscribedToHeaders) {\n this.subscribedToHeaders = true;\n await this.trackSubscription(methodName, ...parameters);\n }\n }\n else {\n await this.trackSubscription(methodName, ...parameters);\n }\n this.subscriptions++;\n return async () => {\n this.electrum.off(\"notification\", handler);\n this.subscriptions--;\n // there are no blockchain.headers.unsubscribe method, so let's safeguard against it\n if (methodName !== \"blockchain.headers.subscribe\") {\n await this.untrackSubscription(methodName, ...parameters);\n }\n };\n }\n async ready() {\n return this.connect();\n }\n async connect() {\n await this.cache?.init();\n if (this.electrum.status !== _electrum_cash_network__WEBPACK_IMPORTED_MODULE_0__.ConnectionStatus.CONNECTED) {\n await this.electrum.connect();\n }\n }\n disconnect() {\n if (this.subscriptions > 0) {\n // console.warn(\n // `Trying to disconnect a network provider with ${this.subscriptions} active subscriptions. This is in most cases a bad idea.`\n // );\n }\n return this.electrum.disconnect(true, false);\n }\n}\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/network/ElectrumNetworkProvider.ts?");
|
|
247
|
+
eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"default\": () => (/* binding */ ElectrumNetworkProvider)\n/* harmony export */ });\n/* harmony import */ var _electrum_cash_network__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @electrum-cash/network */ \"../../node_modules/@electrum-cash/network/dist/index.mjs\");\n/* harmony import */ var _interface_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../interface.js */ \"./src/interface.ts\");\n/* harmony import */ var _util_transaction_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../util/transaction.js */ \"./src/util/transaction.ts\");\n/* harmony import */ var _config_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../config.js */ \"./src/config.ts\");\n/* harmony import */ var _util_header_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../util/header.js */ \"./src/util/header.ts\");\n/* harmony import */ var _cache_IndexedDbCache_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../cache/IndexedDbCache.js */ \"./src/cache/IndexedDbCache.ts\");\n/* harmony import */ var _cache_WebStorageCache_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../cache/WebStorageCache.js */ \"./src/cache/WebStorageCache.ts\");\n/* harmony import */ var _cache_MemoryCache_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../cache/MemoryCache.js */ \"./src/cache/MemoryCache.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_util_header_js__WEBPACK_IMPORTED_MODULE_6__, _util_transaction_js__WEBPACK_IMPORTED_MODULE_7__]);\n([_util_header_js__WEBPACK_IMPORTED_MODULE_6__, _util_transaction_js__WEBPACK_IMPORTED_MODULE_7__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\n\n\n\n\n\n\nclass ElectrumNetworkProvider {\n get cache() {\n if (!_config_js__WEBPACK_IMPORTED_MODULE_1__.Config.UseMemoryCache &&\n !_config_js__WEBPACK_IMPORTED_MODULE_1__.Config.UseLocalStorageCache &&\n !_config_js__WEBPACK_IMPORTED_MODULE_1__.Config.UseIndexedDBCache) {\n this._cache = undefined;\n return this._cache;\n }\n if (_config_js__WEBPACK_IMPORTED_MODULE_1__.Config.UseMemoryCache && !(this._cache instanceof _cache_MemoryCache_js__WEBPACK_IMPORTED_MODULE_2__.MemoryCache)) {\n this._cache = new _cache_MemoryCache_js__WEBPACK_IMPORTED_MODULE_2__.MemoryCache();\n return this._cache;\n }\n if (_config_js__WEBPACK_IMPORTED_MODULE_1__.Config.UseLocalStorageCache &&\n !(this._cache instanceof _cache_WebStorageCache_js__WEBPACK_IMPORTED_MODULE_3__.WebStorageCache)) {\n this._cache = new _cache_WebStorageCache_js__WEBPACK_IMPORTED_MODULE_3__.WebStorageCache();\n return this._cache;\n }\n if (_config_js__WEBPACK_IMPORTED_MODULE_1__.Config.UseIndexedDBCache && !(this._cache instanceof _cache_IndexedDbCache_js__WEBPACK_IMPORTED_MODULE_4__.IndexedDbCache)) {\n this._cache = new _cache_IndexedDbCache_js__WEBPACK_IMPORTED_MODULE_4__.IndexedDbCache();\n return this._cache;\n }\n return this._cache;\n }\n constructor(electrum, network = _interface_js__WEBPACK_IMPORTED_MODULE_5__.Network.MAINNET, manualConnectionManagement) {\n this.network = network;\n this.manualConnectionManagement = manualConnectionManagement;\n this.subscriptions = 0;\n this.subscribedToHeaders = false;\n this.subscriptionMap = {};\n if (electrum) {\n this.electrum = electrum;\n }\n else {\n throw new Error(`A electrum-cash client is required.`);\n }\n }\n async getUtxos(cashaddr) {\n const result = await this.performRequest(\"blockchain.address.listunspent\", cashaddr, \"include_tokens\");\n return result.map((utxo) => ({\n address: cashaddr,\n txid: utxo.tx_hash,\n vout: utxo.tx_pos,\n satoshis: BigInt(utxo.value),\n height: utxo.height,\n token: utxo.token_data\n ? {\n ...utxo.token_data,\n amount: BigInt(utxo.token_data.amount),\n }\n : undefined,\n }));\n }\n async getBalance(cashaddr) {\n const result = await this.performRequest(\"blockchain.address.get_balance\", cashaddr);\n return result.confirmed + result.unconfirmed;\n }\n async getHeader(height, verbose = false) {\n const key = `header-${this.network}-${height}-${verbose}`;\n if (this.cache) {\n const cached = await this.cache.getItem(key);\n if (cached) {\n return verbose ? (0,_util_header_js__WEBPACK_IMPORTED_MODULE_6__.decodeHeader)(JSON.parse(cached)) : JSON.parse(cached);\n }\n }\n const result = await this.performRequest(\"blockchain.header.get\", height);\n if (this.cache) {\n await this.cache.setItem(key, JSON.stringify(result));\n }\n return verbose ? (0,_util_header_js__WEBPACK_IMPORTED_MODULE_6__.decodeHeader)(result) : result;\n }\n async getBlockHeight() {\n return (await this.performRequest(\"blockchain.headers.get_tip\"))\n .height;\n }\n async getRawTransaction(txHash, verbose = false, loadInputValues = false) {\n const key = `tx-${this.network}-${txHash}-${verbose}-${loadInputValues}`;\n if (this.cache) {\n const cached = await this.cache.getItem(key);\n if (cached) {\n return verbose ? JSON.parse(cached) : cached;\n }\n }\n try {\n const transaction = (await this.performRequest(\"blockchain.transaction.get\", txHash, verbose));\n if (this.cache) {\n await this.cache.setItem(key, verbose\n ? JSON.stringify(transaction)\n : transaction);\n }\n if (verbose && loadInputValues) {\n // get unique transaction hashes\n const hashes = [...new Set(transaction.vin.map((val) => val.txid))];\n const transactions = await Promise.all(hashes.map((hash) => this.getRawTransactionObject(hash, false)));\n const transactionMap = new Map();\n transactions.forEach((val) => transactionMap.set(val.hash, val));\n transaction.vin.forEach((input) => {\n const output = transactionMap\n .get(input.txid)\n .vout.find((val) => val.n === input.vout);\n input.address = output.scriptPubKey.addresses[0];\n input.value = output.value;\n input.tokenData = output.tokenData;\n });\n }\n return transaction;\n }\n catch (error) {\n if (error.message.indexOf(\"No such mempool or blockchain transaction.\") > -1)\n throw Error(`Could not decode transaction ${txHash}. It might not exist on the current blockchain (${this.network}).`);\n else\n throw error;\n }\n }\n // gets the decoded transaction in human readable form\n async getRawTransactionObject(txHash, loadInputValues = false) {\n return (await this.getRawTransaction(txHash, true, loadInputValues));\n }\n async sendRawTransaction(txHex, awaitPropagation = true) {\n return new Promise(async (resolve, reject) => {\n let txHash = await (0,_util_transaction_js__WEBPACK_IMPORTED_MODULE_7__.getTransactionHash)(txHex);\n if (!awaitPropagation) {\n this.performRequest(\"blockchain.transaction.broadcast\", txHex);\n resolve(txHash);\n }\n else {\n let cancel;\n const waitForTransactionCallback = async (data) => {\n if (data && data[0] === txHash && data[1] !== null) {\n await cancel?.();\n resolve(txHash);\n }\n };\n cancel = await this.subscribeToTransaction(txHash, waitForTransactionCallback);\n this.performRequest(\"blockchain.transaction.broadcast\", txHex).catch(async (error) => {\n await cancel?.();\n reject(error);\n });\n }\n });\n }\n // Get transaction history of a given cashaddr\n async getHistory(cashaddr, fromHeight = 0, toHeight = -1) {\n const result = await this.performRequest(\"blockchain.address.get_history\", cashaddr, fromHeight, toHeight);\n return result;\n }\n // Get the minimum fee a low-priority transaction must pay in order to be accepted to the daemon's memory pool.\n async getRelayFee() {\n const result = (await this.performRequest(\"blockchain.relayfee\"));\n return result;\n }\n async watchAddressStatus(cashaddr, callback) {\n const watchAddressStatusCallback = async (data) => {\n // subscription acknowledgement is the latest known status or null if no status is known\n // status is an array: [ cashaddr, statusHash ]\n if (data instanceof Array) {\n const addr = data[0];\n if (addr !== cashaddr) {\n return;\n }\n const status = data[1];\n callback(status);\n }\n };\n return this.subscribeToAddress(cashaddr, watchAddressStatusCallback);\n }\n async watchAddress(cashaddr, callback) {\n const historyMap = {};\n this.getHistory(cashaddr).then((history) => history.forEach((val) => (historyMap[val.tx_hash] = true)));\n const watchAddressStatusCallback = async () => {\n const newHistory = await this.getHistory(cashaddr);\n // sort history to put unconfirmed transactions in the beginning, then transactions in block height descenting order\n const txHashes = newHistory\n .sort((a, b) => a.height <= 0 || b.height <= 0 ? -1 : b.height - a.height)\n .map((val) => val.tx_hash);\n for (const hash of txHashes) {\n if (!(hash in historyMap)) {\n historyMap[hash] = true;\n callback(hash);\n // exit early to prevent further map lookups\n break;\n }\n }\n };\n return this.watchAddressStatus(cashaddr, watchAddressStatusCallback);\n }\n async watchAddressTransactions(cashaddr, callback) {\n return this.watchAddress(cashaddr, async (txHash) => {\n const tx = await this.getRawTransactionObject(txHash);\n callback(tx);\n });\n }\n async watchAddressTokenTransactions(cashaddr, callback) {\n return this.watchAddress(cashaddr, async (txHash) => {\n const tx = await this.getRawTransactionObject(txHash, true);\n if (tx.vin.some((val) => val.tokenData) ||\n tx.vout.some((val) => val.tokenData)) {\n callback(tx);\n }\n });\n }\n // watch for block headers and block height, if `skipCurrentHeight` is set, the notification about current block will not arrive\n async watchBlocks(callback, skipCurrentHeight = true) {\n let acknowledged = !skipCurrentHeight;\n const waitForBlockCallback = (_header) => {\n if (!acknowledged) {\n acknowledged = true;\n return;\n }\n _header = _header instanceof Array ? _header[0] : _header;\n callback(_header);\n };\n return this.subscribeToHeaders(waitForBlockCallback);\n }\n // Wait for the next block or a block at given blockchain height.\n async waitForBlock(height) {\n return new Promise(async (resolve) => {\n let cancelWatch;\n if (this.electrum.chainHeight && !height) {\n height = this.electrum.chainHeight + 1;\n }\n cancelWatch = await this.watchBlocks(async (header) => {\n if (!height) {\n height = header.height + 1;\n return;\n }\n if (header.height >= height) {\n await cancelWatch?.();\n resolve(header);\n return;\n }\n });\n });\n }\n // subscribe to notifications sent when new block is found, the block header is sent to callback\n async subscribeToHeaders(callback) {\n return this.subscribeRequest(\"blockchain.headers.subscribe\", callback);\n }\n async subscribeToAddress(cashaddr, callback) {\n return this.subscribeRequest(\"blockchain.address.subscribe\", callback, cashaddr);\n }\n async subscribeToTransaction(txHash, callback) {\n return this.subscribeRequest(\"blockchain.transaction.subscribe\", callback, txHash);\n }\n async performRequest(name, ...parameters) {\n await this.ready();\n const requestTimeout = new Promise(function (_resolve, reject) {\n setTimeout(function () {\n reject(\"electrum-cash request timed out, retrying\");\n }, 30000);\n }).catch(function (e) {\n throw e;\n });\n const request = this.electrum.request(name, ...parameters);\n return await Promise.race([request, requestTimeout])\n .then((value) => {\n if (value instanceof Error)\n throw value;\n let result = value;\n return result;\n })\n .catch(async () => {\n return await Promise.race([request, requestTimeout])\n .then((value) => {\n if (value instanceof Error)\n throw value;\n let result = value;\n return result;\n })\n .catch(function (e) {\n throw e;\n });\n });\n }\n async trackSubscription(methodName, ...parameters) {\n const key = `${methodName}-${this.network}-${JSON.stringify(parameters)}`;\n if (this.subscriptionMap[key]) {\n this.subscriptionMap[key]++;\n }\n else {\n this.subscriptionMap[key] = 1;\n }\n await this.electrum.subscribe(methodName, ...parameters);\n }\n async untrackSubscription(methodName, ...parameters) {\n const key = `${methodName}-${this.network}-${JSON.stringify(parameters)}`;\n if (this.subscriptionMap[key]) {\n this.subscriptionMap[key]--;\n if (this.subscriptionMap[key] <= 0) {\n // only really unsubscribe if there are no more subscriptions for this `key`\n delete this.subscriptionMap[key];\n try {\n await this.electrum.unsubscribe(methodName, ...parameters);\n }\n catch { }\n }\n }\n }\n async subscribeRequest(methodName, callback, ...parameters) {\n await this.ready();\n const handler = (data) => {\n if (data.method === methodName) {\n callback(data.params);\n }\n };\n this.electrum.on(\"notification\", handler);\n // safeguard against multiple subscriptions to headers\n if (methodName === \"blockhain.headers.subscribe\") {\n if (!this.subscribedToHeaders) {\n this.subscribedToHeaders = true;\n await this.trackSubscription(methodName, ...parameters);\n }\n }\n else {\n await this.trackSubscription(methodName, ...parameters);\n }\n this.subscriptions++;\n return async () => {\n this.electrum.off(\"notification\", handler);\n this.subscriptions--;\n // there are no blockchain.headers.unsubscribe method, so let's safeguard against it\n if (methodName !== \"blockchain.headers.subscribe\") {\n await this.untrackSubscription(methodName, ...parameters);\n }\n };\n }\n async ready() {\n return this.connect();\n }\n async connect() {\n await this.cache?.init();\n if (this.electrum.status !== _electrum_cash_network__WEBPACK_IMPORTED_MODULE_0__.ConnectionStatus.CONNECTED) {\n await this.electrum.connect();\n }\n }\n disconnect() {\n if (this.subscriptions > 0) {\n // console.warn(\n // `Trying to disconnect a network provider with ${this.subscriptions} active subscriptions. This is in most cases a bad idea.`\n // );\n }\n return this.electrum.disconnect(true, false);\n }\n}\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/network/ElectrumNetworkProvider.ts?");
|
|
248
248
|
|
|
249
249
|
/***/ }),
|
|
250
250
|
|
|
@@ -344,7 +344,7 @@ eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harm
|
|
|
344
344
|
\********************************/
|
|
345
345
|
/***/ ((module, __webpack_exports__, __webpack_require__) => {
|
|
346
346
|
|
|
347
|
-
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 */ \"buildEncodedTransaction\": () => (/* binding */ buildEncodedTransaction),\n/* harmony export */ \"getFeeAmount\": () => (/* binding */ getFeeAmount),\n/* harmony export */ \"getFeeAmountSimple\": () => (/* binding */ getFeeAmountSimple),\n/* harmony export */ \"getSuitableUtxos\": () => (/* binding */ getSuitableUtxos),\n/* harmony export */ \"placeholderPrivateKeyBin\": () => (/* binding */ placeholderPrivateKeyBin),\n/* harmony export */ \"signUnsignedTransaction\": () => (/* binding */ signUnsignedTransaction)\n/* harmony export */ });\n/* unused harmony exports placeholderPrivateKey, buildP2pkhNonHdTransaction, prepareInputs, prepareOutputs, prepareOpReturnOutput, prepareTokenOutputs */\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__ = __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/schema/wallet-template.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/compiler/standard/p2pkh.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/compiler/compiler-bch/compiler-bch.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/address/locking-bytecode.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/transaction/generate-transaction.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/vm/instruction-sets/bch/2023/bch-2023-tokens.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/message/transaction-encoding.js\");\n/* harmony import */ var _interface_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../interface.js */ \"./src/interface.ts\");\n/* harmony import */ var _allocateFee_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./allocateFee.js */ \"./src/transaction/allocateFee.ts\");\n/* harmony import */ var _constant_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../constant.js */ \"./src/constant.ts\");\n/* harmony import */ var _wallet_model_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../wallet/model.js */ \"./src/wallet/model.ts\");\n/* harmony import */ var _util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../util/sumSendRequestAmounts.js */ \"./src/util/sumSendRequestAmounts.ts\");\n/* harmony import */ var _util_sumUtxoValue_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../util/sumUtxoValue.js */ \"./src/util/sumUtxoValue.ts\");\n/* harmony import */ var _wallet_enum_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../wallet/enum.js */ \"./src/wallet/enum.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__, _util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_6__, _allocateFee_js__WEBPACK_IMPORTED_MODULE_7__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_9__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__, _wallet_model_js__WEBPACK_IMPORTED_MODULE_12__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_14__]);\n([_bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__, _util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_6__, _allocateFee_js__WEBPACK_IMPORTED_MODULE_7__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_9__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__, _wallet_model_js__WEBPACK_IMPORTED_MODULE_12__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_14__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\n\n\n\n\n\n\nconst placeholderPrivateKey = \"0000000000000000000000000000000000000000000000000000000000000001\";\nconst placeholderPrivateKeyBin = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.hexToBin)(placeholderPrivateKey);\n// Build a transaction for a p2pkh transaction for a non HD wallet\nasync function buildP2pkhNonHdTransaction({ inputs, outputs, signingKey, fee = 0n, discardChange = false, feePaidBy = _wallet_enum_js__WEBPACK_IMPORTED_MODULE_1__.FeePaidByEnum.change, changeAddress = \"\", walletCache, }) {\n if (!signingKey) {\n throw new Error(\"Missing signing key when building transaction\");\n }\n const template = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.importWalletTemplate)(_bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.walletTemplateP2pkhNonHd);\n if (typeof template === \"string\") {\n throw new Error(\"Transaction template error\");\n }\n const compiler = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__.walletTemplateToCompilerBch)(template);\n const inputAmount = (0,_util_sumUtxoValue_js__WEBPACK_IMPORTED_MODULE_5__.sumUtxoValue)(inputs);\n const sendAmount = await (0,_util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_6__.sumSendRequestAmounts)(outputs);\n const changeAmount = BigInt(inputAmount) - BigInt(sendAmount) - BigInt(fee);\n outputs = (0,_allocateFee_js__WEBPACK_IMPORTED_MODULE_7__.allocateFee)(outputs, fee, feePaidBy, changeAmount);\n const lockedOutputs = await prepareOutputs(outputs);\n if (!changeAddress) {\n changeAddress = inputs[0].address;\n }\n if (discardChange !== true) {\n if (changeAmount > _constant_js__WEBPACK_IMPORTED_MODULE_8__.DUST_UTXO_THRESHOLD) {\n const changeLockingBytecode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_9__.cashAddressToLockingBytecode)(changeAddress);\n if (typeof changeLockingBytecode === \"string\") {\n throw Error(changeLockingBytecode);\n }\n lockedOutputs.push({\n lockingBytecode: changeLockingBytecode.bytecode,\n valueSatoshis: BigInt(changeAmount),\n });\n }\n }\n const { preparedInputs, sourceOutputs } = prepareInputs({\n inputs,\n compiler,\n signingKey,\n walletCache,\n });\n const result = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__.generateTransaction)({\n inputs: preparedInputs,\n locktime: 0,\n outputs: lockedOutputs,\n version: 2,\n });\n if (!result.success) {\n throw Error(\"Error building transaction with fee\");\n }\n const tokenValidationResult = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.verifyTransactionTokens)(result.transaction, sourceOutputs, { maximumTokenCommitmentLength: 40 });\n if (tokenValidationResult !== true && fee > 0) {\n throw tokenValidationResult;\n }\n return { transaction: result.transaction, sourceOutputs: sourceOutputs };\n}\nfunction prepareInputs({ inputs, compiler, signingKey, walletCache, }) {\n const preparedInputs = [];\n const sourceOutputs = [];\n for (const i of inputs) {\n const utxoTxnValue = i.satoshis;\n const utxoIndex = i.vout;\n // slice will create a clone of the array\n const utxoOutpointTransactionHash = new Uint8Array(i.txid.match(/.{1,2}/g).map((byte) => parseInt(byte, 16)));\n // reverse the cloned copy\n // utxoOutpointTransactionHash.reverse();\n if (!utxoOutpointTransactionHash || utxoIndex === undefined) {\n throw new Error(\"Missing unspent outpoint when building transaction\");\n }\n const libAuthToken = i.token && {\n amount: BigInt(i.token.amount),\n category: (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.hexToBin)(i.token.tokenId),\n nft: i.token.capability !== undefined || i.token.commitment !== undefined\n ? {\n capability: i.token.capability,\n commitment: i.token.commitment !== undefined &&\n (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.hexToBin)(i.token.commitment),\n }\n : undefined,\n };\n const key = walletCache?.get(i.address)?.privateKey ??\n (signingKey?.length ? signingKey : Uint8Array.from(Array(32)));\n const newInput = {\n outpointIndex: utxoIndex,\n outpointTransactionHash: utxoOutpointTransactionHash,\n sequenceNumber: 0,\n unlockingBytecode: {\n compiler,\n data: {\n keys: { privateKeys: { key: key } },\n },\n valueSatoshis: BigInt(utxoTxnValue),\n script: \"unlock\",\n token: libAuthToken,\n },\n };\n preparedInputs.push(newInput);\n const lockingBytecode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_9__.cashAddressToLockingBytecode)(i.address);\n if (typeof lockingBytecode === \"string\") {\n throw lockingBytecode;\n }\n sourceOutputs.push({\n outpointIndex: utxoIndex,\n outpointTransactionHash: utxoOutpointTransactionHash,\n sequenceNumber: 0,\n unlockingBytecode: Uint8Array.from([]),\n // additional info for sourceOutputs\n lockingBytecode: lockingBytecode.bytecode,\n valueSatoshis: BigInt(utxoTxnValue),\n token: libAuthToken,\n });\n }\n return { preparedInputs, sourceOutputs };\n}\n/**\n * prepareOutputs - create outputs for a transaction from a list of send requests\n *\n * a wrapper function\n *\n * @returns A promise to a list of unspent outputs\n */\nasync function prepareOutputs(outputs) {\n const lockedOutputs = [];\n for (const output of outputs) {\n if (output instanceof _wallet_model_js__WEBPACK_IMPORTED_MODULE_12__.TokenSendRequest) {\n lockedOutputs.push(prepareTokenOutputs(output));\n continue;\n }\n if (output instanceof _wallet_model_js__WEBPACK_IMPORTED_MODULE_12__.OpReturnData) {\n lockedOutputs.push(prepareOpReturnOutput(output));\n continue;\n }\n const outputLockingBytecode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_9__.cashAddressToLockingBytecode)(output.cashaddr);\n if (typeof outputLockingBytecode === \"string\")\n throw new Error(outputLockingBytecode);\n const sendAmount = Number(output.value);\n if (sendAmount % 1 !== 0) {\n throw Error(`Cannot send ${sendAmount} satoshis, (fractional sats do not exist, yet), please use an integer number.`);\n }\n const lockedOutput = {\n lockingBytecode: outputLockingBytecode.bytecode,\n valueSatoshis: BigInt(sendAmount),\n };\n lockedOutputs.push(lockedOutput);\n }\n return lockedOutputs;\n}\n/**\n * prepareOpReturnOutput - create an output for OP_RETURN data\n *\n * @returns A promise to a list of unspent outputs\n */\nfunction prepareOpReturnOutput(request) {\n return {\n lockingBytecode: request.buffer,\n valueSatoshis: BigInt(0),\n };\n}\n/**\n * prepareOpReturnOutput - create an output for token data\n *\n * @returns A libauth Output\n */\nfunction prepareTokenOutputs(request) {\n const token = request;\n const outputLockingBytecode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_9__.cashAddressToLockingBytecode)(request.cashaddr);\n if (typeof outputLockingBytecode === \"string\")\n throw new Error(outputLockingBytecode);\n const libAuthToken = {\n amount: BigInt(token.amount),\n category: (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.hexToBin)(token.tokenId),\n nft: token.capability !== undefined || token.commitment !== undefined\n ? {\n capability: token.capability,\n commitment: token.commitment !== undefined && (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.hexToBin)(token.commitment),\n }\n : undefined,\n };\n return {\n lockingBytecode: outputLockingBytecode.bytecode,\n valueSatoshis: BigInt(request.value || 1000),\n token: libAuthToken,\n };\n}\n/**\n * getSuitableUtxos - Filter a list of unspent transaction outputs to the minimum needed to complete a transaction\n *\n * a intermediate function\n *\n * @param unspentOutputs An unfiltered list of available unspent transaction outputs\n *\n * @returns A promise to a list of unspent outputs\n */\nasync function getSuitableUtxos(inputs, amountRequired, bestHeight, feePaidBy, requests, ensureUtxos = [], tokenOperation = \"send\") {\n const suitableUtxos = [...ensureUtxos];\n let amountAvailable = BigInt(0);\n const tokenRequests = requests.filter((val) => val instanceof _wallet_model_js__WEBPACK_IMPORTED_MODULE_12__.TokenSendRequest);\n const availableInputs = inputs.slice();\n const selectedInputs = [];\n // find matching utxos for token transfers\n if (tokenOperation === \"send\") {\n for (const request of tokenRequests) {\n const tokenInputs = availableInputs.filter((val) => val.token?.tokenId === request.tokenId);\n const sameCommitmentTokens = [...suitableUtxos, ...tokenInputs]\n .filter((val) => val.token?.capability === request.capability &&\n val.token?.commitment === request.commitment)\n .filter((val) => selectedInputs.find((selected) => val.txid === selected.txid && val.vout === selected.vout) === undefined);\n if (sameCommitmentTokens.length) {\n const input = sameCommitmentTokens[0];\n const index = availableInputs.indexOf(input);\n if (index !== -1) {\n suitableUtxos.push(input);\n selectedInputs.push(input);\n availableInputs.splice(index, 1);\n amountAvailable += BigInt(input.satoshis);\n }\n continue;\n }\n if (request.capability === _interface_js__WEBPACK_IMPORTED_MODULE_13__.NFTCapability.minting ||\n request.capability === _interface_js__WEBPACK_IMPORTED_MODULE_13__.NFTCapability.mutable) {\n const changeCommitmentTokens = [\n ...suitableUtxos,\n ...tokenInputs,\n ].filter((val) => val.token?.capability === request.capability);\n if (changeCommitmentTokens.length) {\n const input = changeCommitmentTokens[0];\n const index = availableInputs.indexOf(input);\n if (index !== -1) {\n suitableUtxos.push(input);\n availableInputs.splice(index, 1);\n amountAvailable += BigInt(input.satoshis);\n }\n continue;\n }\n }\n // handle splitting the hybrid (FT+NFT) token into its parts\n if (request.capability === undefined &&\n request.commitment === undefined &&\n [...suitableUtxos, ...tokenInputs]\n .map((val) => val.token?.tokenId)\n .includes(request.tokenId)) {\n continue;\n }\n throw Error(`No suitable token utxos available to send token with id \"${request.tokenId}\", capability \"${request.capability}\", commitment \"${request.commitment}\"`);\n }\n }\n // find plain bch outputs\n for (const u of availableInputs) {\n if (u.token) {\n continue;\n }\n if (u.coinbase && u.height && bestHeight) {\n const age = bestHeight - u.height;\n if (age > 100) {\n suitableUtxos.push(u);\n amountAvailable += BigInt(u.satoshis);\n }\n }\n else {\n suitableUtxos.push(u);\n amountAvailable += BigInt(u.satoshis);\n }\n // if amountRequired is not given, assume it is a max spend request, skip this condition\n if (amountRequired && amountAvailable > amountRequired) {\n break;\n }\n }\n const addEnsured = (suitableUtxos) => {\n return [...ensureUtxos, ...suitableUtxos].filter((val, index, array) => array.findIndex((other) => other.txid === val.txid && other.vout === val.vout) === index);\n };\n // if the fee is split with a feePaidBy option, skip checking change.\n if (feePaidBy && feePaidBy != _wallet_enum_js__WEBPACK_IMPORTED_MODULE_1__.FeePaidByEnum.change) {\n return addEnsured(suitableUtxos);\n }\n // If the amount needed is met, or no amount is given, return\n if (typeof amountRequired === \"undefined\") {\n return addEnsured(suitableUtxos);\n }\n else if (amountAvailable < amountRequired) {\n const e = Error(`Amount required was not met, ${amountRequired} satoshis needed, ${amountAvailable} satoshis available`);\n e[\"data\"] = {\n required: amountRequired,\n available: amountAvailable,\n };\n throw e;\n }\n else {\n return addEnsured(suitableUtxos);\n }\n}\n// model-based imprecise and fast fee estimation\nasync function getFeeAmountSimple({ utxos, sendRequests, relayFeePerByteInSatoshi, discardChange, }) {\n const inputSizeP2pkh = 148;\n const outputSizeP2pkh = 34;\n const inputTotalSize = utxos.reduce((prev, curr) => prev +\n (curr.token\n ? inputSizeP2pkh +\n 1 +\n 34 +\n Math.round(1 + (curr.token.commitment?.length ?? 0) / 2) +\n (curr.token.amount ? 9 : 0)\n : inputSizeP2pkh), 0);\n const outputSize = (sendRequest) => {\n if (sendRequest.hasOwnProperty(\"tokenId\")) {\n const tokenRequest = sendRequest;\n return (outputSizeP2pkh +\n 1 +\n 34 +\n Math.round(1 + (tokenRequest.commitment?.length ?? 0) / 2) +\n (tokenRequest.amount ? 9 : 0));\n }\n else if (sendRequest.hasOwnProperty(\"buffer\")) {\n return 9 + sendRequest.buffer.length;\n }\n else {\n return outputSizeP2pkh;\n }\n };\n const outputTotalSize = sendRequests.reduce((prev, curr) => prev + outputSize(curr), 0) +\n (discardChange ? 0 : outputSizeP2pkh);\n return BigInt(Math.ceil((inputTotalSize + outputTotalSize + 16) * relayFeePerByteInSatoshi));\n}\n// precise fee estimation\nasync function getFeeAmount({ utxos, sendRequests, sourceAddress, relayFeePerByteInSatoshi, feePaidBy, discardChange, walletCache, }) {\n // build transaction\n if (utxos) {\n // Build the transaction to get the approximate size\n const { encodedTransaction: draftTransaction } = await buildEncodedTransaction({\n inputs: utxos,\n outputs: sendRequests,\n signingKey: placeholderPrivateKeyBin,\n fee: 0n, //DUST_UTXO_THRESHOLD\n discardChange: discardChange ?? false,\n feePaidBy,\n changeAddress: \"\",\n walletCache,\n });\n return BigInt(Math.ceil(draftTransaction.length * relayFeePerByteInSatoshi + 1));\n }\n else {\n throw Error(\"The available inputs in the wallet cannot satisfy this send request\");\n }\n}\n// Build encoded transaction\nasync function buildEncodedTransaction({ inputs, outputs, signingKey, fee = 0n, discardChange = false, feePaidBy = _wallet_enum_js__WEBPACK_IMPORTED_MODULE_1__.FeePaidByEnum.change, changeAddress = \"\", buildUnsigned = false, walletCache, }) {\n const { transaction, sourceOutputs } = await buildP2pkhNonHdTransaction({\n inputs,\n outputs,\n signingKey,\n fee,\n discardChange,\n feePaidBy,\n changeAddress,\n walletCache,\n });\n if (buildUnsigned === true) {\n transaction.inputs.forEach((input) => (input.unlockingBytecode = Uint8Array.from([])));\n }\n return { encodedTransaction: (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_14__.encodeTransaction)(transaction), sourceOutputs };\n}\nasync function signUnsignedTransaction(transaction, sourceOutputs, signingKey) {\n if (typeof transaction === \"string\") {\n transaction = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.hexToBin)(transaction);\n }\n const decoded = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_14__.decodeTransaction)(transaction);\n if (typeof decoded === \"string\") {\n throw decoded;\n }\n const template = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.importWalletTemplate)(_bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.walletTemplateP2pkhNonHd);\n if (typeof template === \"string\") {\n throw new Error(\"Transaction template error\");\n }\n const compiler = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__.walletTemplateToCompilerBch)(template);\n const transactionTemplate = { ...decoded };\n for (const [index, input] of decoded.inputs.entries()) {\n const sourceOutput = sourceOutputs[index];\n transactionTemplate.inputs[index] = {\n ...input,\n unlockingBytecode: {\n compiler,\n data: {\n keys: { privateKeys: { key: signingKey } },\n },\n valueSatoshis: sourceOutput.valueSatoshis,\n script: \"unlock\",\n token: sourceOutput.token,\n },\n };\n }\n const result = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__.generateTransaction)(transactionTemplate);\n if (!result.success) {\n throw result.errors;\n }\n return (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_14__.encodeTransaction)(result.transaction);\n}\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/transaction/Wif.ts?");
|
|
347
|
+
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 */ \"buildEncodedTransaction\": () => (/* binding */ buildEncodedTransaction),\n/* harmony export */ \"getFeeAmount\": () => (/* binding */ getFeeAmount),\n/* harmony export */ \"getFeeAmountSimple\": () => (/* binding */ getFeeAmountSimple),\n/* harmony export */ \"getSuitableUtxos\": () => (/* binding */ getSuitableUtxos),\n/* harmony export */ \"placeholderPrivateKeyBin\": () => (/* binding */ placeholderPrivateKeyBin),\n/* harmony export */ \"signUnsignedTransaction\": () => (/* binding */ signUnsignedTransaction)\n/* harmony export */ });\n/* unused harmony exports placeholderPrivateKey, buildP2pkhNonHdTransaction, prepareInputs, prepareOutputs, prepareOpReturnOutput, prepareTokenOutputs */\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__ = __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/schema/wallet-template.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/compiler/standard/p2pkh.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/compiler/compiler-bch/compiler-bch.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/address/locking-bytecode.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/transaction/generate-transaction.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/vm/instruction-sets/bch/2023/bch-2023-tokens.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/message/transaction-encoding.js\");\n/* harmony import */ var _interface_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../interface.js */ \"./src/interface.ts\");\n/* harmony import */ var _allocateFee_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./allocateFee.js */ \"./src/transaction/allocateFee.ts\");\n/* harmony import */ var _constant_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../constant.js */ \"./src/constant.ts\");\n/* harmony import */ var _wallet_model_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../wallet/model.js */ \"./src/wallet/model.ts\");\n/* harmony import */ var _util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../util/sumSendRequestAmounts.js */ \"./src/util/sumSendRequestAmounts.ts\");\n/* harmony import */ var _util_sumUtxoValue_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../util/sumUtxoValue.js */ \"./src/util/sumUtxoValue.ts\");\n/* harmony import */ var _wallet_enum_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../wallet/enum.js */ \"./src/wallet/enum.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__, _util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_6__, _allocateFee_js__WEBPACK_IMPORTED_MODULE_7__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_9__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__, _wallet_model_js__WEBPACK_IMPORTED_MODULE_12__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_14__]);\n([_bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__, _util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_6__, _allocateFee_js__WEBPACK_IMPORTED_MODULE_7__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_9__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__, _wallet_model_js__WEBPACK_IMPORTED_MODULE_12__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_14__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\n\n\n\n\n\n\nconst placeholderPrivateKey = \"0000000000000000000000000000000000000000000000000000000000000001\";\nconst placeholderPrivateKeyBin = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.hexToBin)(placeholderPrivateKey);\n// Build a transaction for a p2pkh transaction for a non HD wallet\nasync function buildP2pkhNonHdTransaction({ inputs, outputs, signingKey, fee = 0n, discardChange = false, feePaidBy = _wallet_enum_js__WEBPACK_IMPORTED_MODULE_1__.FeePaidByEnum.change, changeAddress = \"\", walletCache, }) {\n if (!signingKey) {\n throw new Error(\"Missing signing key when building transaction\");\n }\n const template = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.importWalletTemplate)(_bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.walletTemplateP2pkhNonHd);\n if (typeof template === \"string\") {\n throw new Error(\"Transaction template error\");\n }\n const compiler = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__.walletTemplateToCompilerBch)(template);\n const inputAmount = (0,_util_sumUtxoValue_js__WEBPACK_IMPORTED_MODULE_5__.sumUtxoValue)(inputs);\n const sendAmount = await (0,_util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_6__.sumSendRequestAmounts)(outputs);\n const changeAmount = BigInt(inputAmount) - BigInt(sendAmount) - BigInt(fee);\n outputs = (0,_allocateFee_js__WEBPACK_IMPORTED_MODULE_7__.allocateFee)(outputs, fee, feePaidBy, changeAmount);\n const lockedOutputs = await prepareOutputs(outputs);\n if (!changeAddress) {\n changeAddress = inputs[0].address;\n }\n if (discardChange !== true) {\n if (changeAmount > _constant_js__WEBPACK_IMPORTED_MODULE_8__.DUST_UTXO_THRESHOLD) {\n const changeLockingBytecode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_9__.cashAddressToLockingBytecode)(changeAddress);\n if (typeof changeLockingBytecode === \"string\") {\n throw Error(changeLockingBytecode);\n }\n lockedOutputs.push({\n lockingBytecode: changeLockingBytecode.bytecode,\n valueSatoshis: BigInt(changeAmount),\n });\n }\n }\n const { preparedInputs, sourceOutputs } = prepareInputs({\n inputs,\n compiler,\n signingKey,\n walletCache,\n });\n const result = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__.generateTransaction)({\n inputs: preparedInputs,\n locktime: 0,\n outputs: lockedOutputs,\n version: 2,\n });\n if (!result.success) {\n throw Error(\"Error building transaction with fee\");\n }\n const tokenValidationResult = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.verifyTransactionTokens)(result.transaction, sourceOutputs, { maximumTokenCommitmentLength: 40 });\n if (tokenValidationResult !== true && fee > 0) {\n throw tokenValidationResult;\n }\n return { transaction: result.transaction, sourceOutputs: sourceOutputs };\n}\nfunction prepareInputs({ inputs, compiler, signingKey, walletCache, }) {\n const preparedInputs = [];\n const sourceOutputs = [];\n for (const i of inputs) {\n const utxoTxnValue = i.satoshis;\n const utxoIndex = i.vout;\n // slice will create a clone of the array\n const utxoOutpointTransactionHash = new Uint8Array(i.txid.match(/.{1,2}/g).map((byte) => parseInt(byte, 16)));\n // reverse the cloned copy\n // utxoOutpointTransactionHash.reverse();\n if (!utxoOutpointTransactionHash || utxoIndex === undefined) {\n throw new Error(\"Missing unspent outpoint when building transaction\");\n }\n const libAuthToken = i.token && {\n amount: BigInt(i.token.amount),\n category: (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.hexToBin)(i.token.category),\n nft: i.token.nft?.capability !== undefined ||\n i.token.nft?.commitment !== undefined\n ? {\n capability: i.token.nft?.capability,\n commitment: i.token.nft?.commitment !== undefined &&\n (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.hexToBin)(i.token.nft?.commitment),\n }\n : undefined,\n };\n const key = walletCache?.get(i.address)?.privateKey ??\n (signingKey?.length ? signingKey : Uint8Array.from(Array(32)));\n const newInput = {\n outpointIndex: utxoIndex,\n outpointTransactionHash: utxoOutpointTransactionHash,\n sequenceNumber: 0,\n unlockingBytecode: {\n compiler,\n data: {\n keys: { privateKeys: { key: key } },\n },\n valueSatoshis: BigInt(utxoTxnValue),\n script: \"unlock\",\n token: libAuthToken,\n },\n };\n preparedInputs.push(newInput);\n const lockingBytecode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_9__.cashAddressToLockingBytecode)(i.address);\n if (typeof lockingBytecode === \"string\") {\n throw lockingBytecode;\n }\n sourceOutputs.push({\n outpointIndex: utxoIndex,\n outpointTransactionHash: utxoOutpointTransactionHash,\n sequenceNumber: 0,\n unlockingBytecode: Uint8Array.from([]),\n // additional info for sourceOutputs\n lockingBytecode: lockingBytecode.bytecode,\n valueSatoshis: BigInt(utxoTxnValue),\n token: libAuthToken,\n });\n }\n return { preparedInputs, sourceOutputs };\n}\n/**\n * prepareOutputs - create outputs for a transaction from a list of send requests\n *\n * a wrapper function\n *\n * @returns A promise to a list of unspent outputs\n */\nasync function prepareOutputs(outputs) {\n const lockedOutputs = [];\n for (const output of outputs) {\n if (output instanceof _wallet_model_js__WEBPACK_IMPORTED_MODULE_12__.TokenSendRequest) {\n lockedOutputs.push(prepareTokenOutputs(output));\n continue;\n }\n if (output instanceof _wallet_model_js__WEBPACK_IMPORTED_MODULE_12__.OpReturnData) {\n lockedOutputs.push(prepareOpReturnOutput(output));\n continue;\n }\n const outputLockingBytecode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_9__.cashAddressToLockingBytecode)(output.cashaddr);\n if (typeof outputLockingBytecode === \"string\")\n throw new Error(outputLockingBytecode);\n const sendAmount = Number(output.value);\n if (sendAmount % 1 !== 0) {\n throw Error(`Cannot send ${sendAmount} satoshis, (fractional sats do not exist, yet), please use an integer number.`);\n }\n const lockedOutput = {\n lockingBytecode: outputLockingBytecode.bytecode,\n valueSatoshis: BigInt(sendAmount),\n };\n lockedOutputs.push(lockedOutput);\n }\n return lockedOutputs;\n}\n/**\n * prepareOpReturnOutput - create an output for OP_RETURN data\n *\n * @returns A promise to a list of unspent outputs\n */\nfunction prepareOpReturnOutput(request) {\n return {\n lockingBytecode: request.buffer,\n valueSatoshis: BigInt(0),\n };\n}\n/**\n * prepareOpReturnOutput - create an output for token data\n *\n * @returns A libauth Output\n */\nfunction prepareTokenOutputs(request) {\n const token = request;\n const outputLockingBytecode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_9__.cashAddressToLockingBytecode)(request.cashaddr);\n if (typeof outputLockingBytecode === \"string\")\n throw new Error(outputLockingBytecode);\n const libAuthToken = {\n amount: BigInt(token.amount),\n category: (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.hexToBin)(token.category),\n nft: token.nft?.capability !== undefined || token.nft?.commitment !== undefined\n ? {\n capability: token.nft?.capability,\n commitment: token.nft?.commitment !== undefined &&\n (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.hexToBin)(token.nft?.commitment),\n }\n : undefined,\n };\n return {\n lockingBytecode: outputLockingBytecode.bytecode,\n valueSatoshis: BigInt(request.value || 1000),\n token: libAuthToken,\n };\n}\n/**\n * getSuitableUtxos - Filter a list of unspent transaction outputs to the minimum needed to complete a transaction\n *\n * a intermediate function\n *\n * @param unspentOutputs An unfiltered list of available unspent transaction outputs\n *\n * @returns A promise to a list of unspent outputs\n */\nasync function getSuitableUtxos(inputs, amountRequired, bestHeight, feePaidBy, requests, ensureUtxos = [], tokenOperation = \"send\") {\n const suitableUtxos = [...ensureUtxos];\n let amountAvailable = BigInt(0);\n const tokenRequests = requests.filter((val) => val instanceof _wallet_model_js__WEBPACK_IMPORTED_MODULE_12__.TokenSendRequest);\n const availableInputs = inputs.slice();\n const selectedInputs = [];\n // find matching utxos for token transfers\n if (tokenOperation === \"send\") {\n for (const request of tokenRequests) {\n const tokenInputs = availableInputs.filter((val) => val.token?.category === request.category);\n const sameCommitmentTokens = [...suitableUtxos, ...tokenInputs]\n .filter((val) => val.token?.nft?.capability === request.nft?.capability &&\n val.token?.nft?.commitment === request.nft?.commitment)\n .filter((val) => selectedInputs.find((selected) => val.txid === selected.txid && val.vout === selected.vout) === undefined);\n if (sameCommitmentTokens.length) {\n const input = sameCommitmentTokens[0];\n const index = availableInputs.indexOf(input);\n if (index !== -1) {\n suitableUtxos.push(input);\n selectedInputs.push(input);\n availableInputs.splice(index, 1);\n amountAvailable += BigInt(input.satoshis);\n }\n continue;\n }\n if (request.nft?.capability === _interface_js__WEBPACK_IMPORTED_MODULE_13__.NFTCapability.minting ||\n request.nft?.capability === _interface_js__WEBPACK_IMPORTED_MODULE_13__.NFTCapability.mutable) {\n const changeCommitmentTokens = [\n ...suitableUtxos,\n ...tokenInputs,\n ].filter((val) => val.token?.nft?.capability === request.nft?.capability);\n if (changeCommitmentTokens.length) {\n const input = changeCommitmentTokens[0];\n const index = availableInputs.indexOf(input);\n if (index !== -1) {\n suitableUtxos.push(input);\n availableInputs.splice(index, 1);\n amountAvailable += BigInt(input.satoshis);\n }\n continue;\n }\n }\n // handle splitting the hybrid (FT+NFT) token into its parts\n if (request.nft?.capability === undefined &&\n request.nft?.commitment === undefined &&\n [...suitableUtxos, ...tokenInputs]\n .map((val) => val.token?.category)\n .includes(request.category)) {\n continue;\n }\n throw Error(`No suitable token utxos available to send token with id \"${request.category}\", capability \"${request.nft?.capability}\", commitment \"${request.nft?.commitment}\"`);\n }\n }\n // find plain bch outputs\n for (const u of availableInputs) {\n if (u.token) {\n continue;\n }\n if (u.coinbase && u.height && bestHeight) {\n const age = bestHeight - u.height;\n if (age > 100) {\n suitableUtxos.push(u);\n amountAvailable += BigInt(u.satoshis);\n }\n }\n else {\n suitableUtxos.push(u);\n amountAvailable += BigInt(u.satoshis);\n }\n // if amountRequired is not given, assume it is a max spend request, skip this condition\n if (amountRequired && amountAvailable > amountRequired) {\n break;\n }\n }\n const addEnsured = (suitableUtxos) => {\n return [...ensureUtxos, ...suitableUtxos].filter((val, index, array) => array.findIndex((other) => other.txid === val.txid && other.vout === val.vout) === index);\n };\n // if the fee is split with a feePaidBy option, skip checking change.\n if (feePaidBy && feePaidBy != _wallet_enum_js__WEBPACK_IMPORTED_MODULE_1__.FeePaidByEnum.change) {\n return addEnsured(suitableUtxos);\n }\n // If the amount needed is met, or no amount is given, return\n if (typeof amountRequired === \"undefined\") {\n return addEnsured(suitableUtxos);\n }\n else if (amountAvailable < amountRequired) {\n const e = Error(`Amount required was not met, ${amountRequired} satoshis needed, ${amountAvailable} satoshis available`);\n e[\"data\"] = {\n required: amountRequired,\n available: amountAvailable,\n };\n throw e;\n }\n else {\n return addEnsured(suitableUtxos);\n }\n}\n// model-based imprecise and fast fee estimation\nasync function getFeeAmountSimple({ utxos, sendRequests, relayFeePerByteInSatoshi, discardChange, }) {\n const inputSizeP2pkh = 148;\n const outputSizeP2pkh = 34;\n const inputTotalSize = utxos.reduce((prev, curr) => prev +\n (curr.token\n ? inputSizeP2pkh +\n 1 +\n 34 +\n Math.round(1 + (curr.token.nft?.commitment?.length ?? 0) / 2) +\n (curr.token.amount ? 9 : 0)\n : inputSizeP2pkh), 0);\n const outputSize = (sendRequest) => {\n if (sendRequest.hasOwnProperty(\"category\")) {\n const tokenRequest = sendRequest;\n return (outputSizeP2pkh +\n 1 +\n 34 +\n Math.round(1 + (tokenRequest.nft?.commitment?.length ?? 0) / 2) +\n (tokenRequest.amount ? 9 : 0));\n }\n else if (sendRequest.hasOwnProperty(\"buffer\")) {\n return 9 + sendRequest.buffer.length;\n }\n else {\n return outputSizeP2pkh;\n }\n };\n const outputTotalSize = sendRequests.reduce((prev, curr) => prev + outputSize(curr), 0) +\n (discardChange ? 0 : outputSizeP2pkh);\n return BigInt(Math.ceil((inputTotalSize + outputTotalSize + 16) * relayFeePerByteInSatoshi));\n}\n// precise fee estimation\nasync function getFeeAmount({ utxos, sendRequests, sourceAddress, relayFeePerByteInSatoshi, feePaidBy, discardChange, walletCache, }) {\n // build transaction\n if (utxos) {\n // Build the transaction to get the approximate size\n const { encodedTransaction: draftTransaction } = await buildEncodedTransaction({\n inputs: utxos,\n outputs: sendRequests,\n signingKey: placeholderPrivateKeyBin,\n fee: 0n, //DUST_UTXO_THRESHOLD\n discardChange: discardChange ?? false,\n feePaidBy,\n changeAddress: \"\",\n walletCache,\n });\n return BigInt(Math.ceil(draftTransaction.length * relayFeePerByteInSatoshi + 1));\n }\n else {\n throw Error(\"The available inputs in the wallet cannot satisfy this send request\");\n }\n}\n// Build encoded transaction\nasync function buildEncodedTransaction({ inputs, outputs, signingKey, fee = 0n, discardChange = false, feePaidBy = _wallet_enum_js__WEBPACK_IMPORTED_MODULE_1__.FeePaidByEnum.change, changeAddress = \"\", buildUnsigned = false, walletCache, }) {\n const { transaction, sourceOutputs } = await buildP2pkhNonHdTransaction({\n inputs,\n outputs,\n signingKey,\n fee,\n discardChange,\n feePaidBy,\n changeAddress,\n walletCache,\n });\n if (buildUnsigned === true) {\n transaction.inputs.forEach((input) => (input.unlockingBytecode = Uint8Array.from([])));\n }\n return { encodedTransaction: (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_14__.encodeTransaction)(transaction), sourceOutputs };\n}\nasync function signUnsignedTransaction(transaction, sourceOutputs, signingKey) {\n if (typeof transaction === \"string\") {\n transaction = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.hexToBin)(transaction);\n }\n const decoded = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_14__.decodeTransaction)(transaction);\n if (typeof decoded === \"string\") {\n throw decoded;\n }\n const template = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.importWalletTemplate)(_bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.walletTemplateP2pkhNonHd);\n if (typeof template === \"string\") {\n throw new Error(\"Transaction template error\");\n }\n const compiler = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__.walletTemplateToCompilerBch)(template);\n const transactionTemplate = { ...decoded };\n for (const [index, input] of decoded.inputs.entries()) {\n const sourceOutput = sourceOutputs[index];\n transactionTemplate.inputs[index] = {\n ...input,\n unlockingBytecode: {\n compiler,\n data: {\n keys: { privateKeys: { key: signingKey } },\n },\n valueSatoshis: sourceOutput.valueSatoshis,\n script: \"unlock\",\n token: sourceOutput.token,\n },\n };\n }\n const result = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__.generateTransaction)(transactionTemplate);\n if (!result.success) {\n throw result.errors;\n }\n return (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_14__.encodeTransaction)(result.transaction);\n}\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/transaction/Wif.ts?");
|
|
348
348
|
|
|
349
349
|
/***/ }),
|
|
350
350
|
|
|
@@ -374,7 +374,7 @@ eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__
|
|
|
374
374
|
\*****************************************/
|
|
375
375
|
/***/ ((module, __webpack_exports__, __webpack_require__) => {
|
|
376
376
|
|
|
377
|
-
eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"asSendRequestObject\": () => (/* binding */ asSendRequestObject)\n/* harmony export */ });\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/base64.js\");\n/* harmony import */ var _wallet_model_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../wallet/model.js */ \"./src/wallet/model.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_wallet_model_js__WEBPACK_IMPORTED_MODULE_0__]);\n_wallet_model_js__WEBPACK_IMPORTED_MODULE_0__ = (__webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__)[0];\n\n\nfunction asSendRequestObject(requests) {\n let resp = [];\n if (Array.isArray(requests)) {\n requests.forEach((r) => {\n // the SendRequestArray[] case\n if (Array.isArray(r)) {\n if (r[0] === \"OP_RETURN\") {\n // ['OP_RETURN', utf8ToBin('MEMO\\x10')],\n resp.push(_wallet_model_js__WEBPACK_IMPORTED_MODULE_0__.OpReturnData.from(r[1]));\n }\n else if (r[0] === \"OP_RETURNB64\") {\n resp.push(_wallet_model_js__WEBPACK_IMPORTED_MODULE_0__.OpReturnData.fromUint8Array(Uint8Array.from((0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.base64ToBin)(r[1]))));\n }\n else {\n // ['cashaddr', 120] or ['cashaddr', 120n],\n resp.push(new _wallet_model_js__WEBPACK_IMPORTED_MODULE_0__.SendRequest({\n cashaddr: r[0],\n value: typeof r[1] === \"number\"\n ? BigInt(Math.floor[1])\n : r[1],\n }));\n }\n }\n else {\n // SendRequest | TokenSendRequest | OpReturnRequest case\n resp.push(convertToClass(r));\n }\n });\n }\n else {\n // the SendRequest | OpReturnData object case\n resp.push(convertToClass(requests));\n }\n return resp;\n}\nfunction convertToClass(object) {\n if (object.hasOwnProperty(\"
|
|
377
|
+
eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"asSendRequestObject\": () => (/* binding */ asSendRequestObject)\n/* harmony export */ });\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/base64.js\");\n/* harmony import */ var _wallet_model_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../wallet/model.js */ \"./src/wallet/model.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_wallet_model_js__WEBPACK_IMPORTED_MODULE_0__]);\n_wallet_model_js__WEBPACK_IMPORTED_MODULE_0__ = (__webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__)[0];\n\n\nfunction asSendRequestObject(requests) {\n let resp = [];\n if (Array.isArray(requests)) {\n requests.forEach((r) => {\n // the SendRequestArray[] case\n if (Array.isArray(r)) {\n if (r[0] === \"OP_RETURN\") {\n // ['OP_RETURN', utf8ToBin('MEMO\\x10')],\n resp.push(_wallet_model_js__WEBPACK_IMPORTED_MODULE_0__.OpReturnData.from(r[1]));\n }\n else if (r[0] === \"OP_RETURNB64\") {\n resp.push(_wallet_model_js__WEBPACK_IMPORTED_MODULE_0__.OpReturnData.fromUint8Array(Uint8Array.from((0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.base64ToBin)(r[1]))));\n }\n else {\n // ['cashaddr', 120] or ['cashaddr', 120n],\n resp.push(new _wallet_model_js__WEBPACK_IMPORTED_MODULE_0__.SendRequest({\n cashaddr: r[0],\n value: typeof r[1] === \"number\"\n ? BigInt(Math.floor[1])\n : r[1],\n }));\n }\n }\n else {\n // SendRequest | TokenSendRequest | OpReturnRequest case\n resp.push(convertToClass(r));\n }\n });\n }\n else {\n // the SendRequest | OpReturnData object case\n resp.push(convertToClass(requests));\n }\n return resp;\n}\nfunction convertToClass(object) {\n if (object.hasOwnProperty(\"category\")) {\n return new _wallet_model_js__WEBPACK_IMPORTED_MODULE_0__.TokenSendRequest(object);\n }\n else if (object.hasOwnProperty(\"buffer\")) {\n return _wallet_model_js__WEBPACK_IMPORTED_MODULE_0__.OpReturnData.fromUint8Array(object.buffer);\n }\n // endcoding in REST\n else if (object.hasOwnProperty(\"dataString\")) {\n return _wallet_model_js__WEBPACK_IMPORTED_MODULE_0__.OpReturnData.fromString(object.dataString);\n }\n else if (object.hasOwnProperty(\"dataBuffer\")) {\n return _wallet_model_js__WEBPACK_IMPORTED_MODULE_0__.OpReturnData.fromUint8Array(Uint8Array.from((0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.base64ToBin)(object.dataBuffer)));\n }\n else if (object.hasOwnProperty(\"cashaddr\") &&\n object.hasOwnProperty(\"value\") &&\n object.hasOwnProperty(\"category\") === false) {\n return new _wallet_model_js__WEBPACK_IMPORTED_MODULE_0__.SendRequest(object);\n }\n throw new Error(\"Unsupported send object\");\n}\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/util/asSendRequestObject.ts?");
|
|
378
378
|
|
|
379
379
|
/***/ }),
|
|
380
380
|
|
|
@@ -614,7 +614,7 @@ eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__
|
|
|
614
614
|
\**********************************/
|
|
615
615
|
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
|
|
616
616
|
|
|
617
|
-
eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"sumTokenAmounts\": () => (/* binding */ sumTokenAmounts),\n/* harmony export */ \"sumUtxoValue\": () => (/* binding */ sumUtxoValue)\n/* harmony export */ });\nfunction sumUtxoValue(utxos) {\n if (utxos.length > 0) {\n const balanceArray = utxos.map((o) => {\n return o.satoshis;\n });\n const balance = balanceArray.reduce((a, b) => a + b, 0n);\n return balance;\n }\n else {\n return 0n;\n }\n}\nfunction sumTokenAmounts(utxos, tokenId) {\n if (utxos.length > 0) {\n const tokenArray = utxos\n .filter((utxo) => utxo.token?.
|
|
617
|
+
eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"sumTokenAmounts\": () => (/* binding */ sumTokenAmounts),\n/* harmony export */ \"sumUtxoValue\": () => (/* binding */ sumUtxoValue)\n/* harmony export */ });\nfunction sumUtxoValue(utxos) {\n if (utxos.length > 0) {\n const balanceArray = utxos.map((o) => {\n return o.satoshis;\n });\n const balance = balanceArray.reduce((a, b) => a + b, 0n);\n return balance;\n }\n else {\n return 0n;\n }\n}\nfunction sumTokenAmounts(utxos, tokenId) {\n if (utxos.length > 0) {\n const tokenArray = utxos\n .filter((utxo) => utxo.token?.category === tokenId)\n .map((o) => {\n return o.token?.amount || 0n;\n });\n const balance = tokenArray.reduce((a, b) => a + b, 0n);\n return balance;\n }\n else {\n return 0n;\n }\n}\n\n\n//# sourceURL=webpack://mainnet-js/./src/util/sumUtxoValue.ts?");
|
|
618
618
|
|
|
619
619
|
/***/ }),
|
|
620
620
|
|
|
@@ -634,7 +634,7 @@ eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__
|
|
|
634
634
|
\****************************/
|
|
635
635
|
/***/ ((module, __webpack_exports__, __webpack_require__) => {
|
|
636
636
|
|
|
637
|
-
eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"BaseWallet\": () => (/* binding */ BaseWallet),\n/* harmony export */ \"_checkContextSafety\": () => (/* binding */ _checkContextSafety),\n/* harmony export */ \"getNamedWalletId\": () => (/* binding */ getNamedWalletId),\n/* harmony export */ \"getStorageProvider\": () => (/* binding */ getStorageProvider),\n/* harmony export */ \"placeholderCashAddr\": () => (/* binding */ placeholderCashAddr),\n/* harmony export */ \"placeholderTokenAddr\": () => (/* binding */ placeholderTokenAddr)\n/* harmony export */ });\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/hex.js\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../enum.js */ \"./src/enum.ts\");\n/* harmony import */ var _interface_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../interface.js */ \"./src/interface.ts\");\n/* harmony import */ var _network_default_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../network/default.js */ \"./src/network/default.ts\");\n/* harmony import */ var _network_getRelayFeeCache_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../network/getRelayFeeCache.js */ \"./src/network/getRelayFeeCache.ts\");\n/* harmony import */ var _transaction_Wif_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../transaction/Wif.js */ \"./src/transaction/Wif.ts\");\n/* harmony import */ var _util_checkUtxos_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../util/checkUtxos.js */ \"./src/util/checkUtxos.ts\");\n/* harmony import */ var _util_index_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../util/index.js */ \"./src/util/sumUtxoValue.ts\");\n/* harmony import */ var _util_index_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../util/index.js */ \"./src/util/asSendRequestObject.ts\");\n/* harmony import */ var _util_index_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../util/index.js */ \"./src/util/deriveCashaddr.ts\");\n/* harmony import */ var _util_index_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../util/index.js */ \"./src/util/getRuntimePlatform.ts\");\n/* harmony import */ var _util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../util/sumSendRequestAmounts.js */ \"./src/util/sumSendRequestAmounts.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_7__ = __webpack_require__(/*! ./model.js */ \"./src/wallet/model.ts\");\n/* harmony import */ var _Util_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Util.js */ \"./src/wallet/Util.ts\");\n/* harmony import */ var _message_signed_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../message/signed.js */ \"./src/message/signed.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_network_default_js__WEBPACK_IMPORTED_MODULE_0__, _enum_js__WEBPACK_IMPORTED_MODULE_2__, _Util_js__WEBPACK_IMPORTED_MODULE_3__, _model_js__WEBPACK_IMPORTED_MODULE_7__, _transaction_Wif_js__WEBPACK_IMPORTED_MODULE_8__, _util_index_js__WEBPACK_IMPORTED_MODULE_10__, _util_index_js__WEBPACK_IMPORTED_MODULE_11__, _util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_12__, _message_signed_js__WEBPACK_IMPORTED_MODULE_14__]);\n([_network_default_js__WEBPACK_IMPORTED_MODULE_0__, _enum_js__WEBPACK_IMPORTED_MODULE_2__, _Util_js__WEBPACK_IMPORTED_MODULE_3__, _model_js__WEBPACK_IMPORTED_MODULE_7__, _transaction_Wif_js__WEBPACK_IMPORTED_MODULE_8__, _util_index_js__WEBPACK_IMPORTED_MODULE_10__, _util_index_js__WEBPACK_IMPORTED_MODULE_11__, _util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_12__, _message_signed_js__WEBPACK_IMPORTED_MODULE_14__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\n\n\n\n\n\n\n\n\n\n\n\nconst placeholderCashAddr = \"bitcoincash:qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqfnhks603\";\nconst placeholderTokenAddr = \"bitcoincash:zqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqweyg7usz\";\n/**\n * A class to hold features used by all wallets\n * @class BaseWallet\n */\nclass BaseWallet {\n get networkPrefix() {\n return _enum_js__WEBPACK_IMPORTED_MODULE_2__.prefixFromNetworkMap[this.network];\n }\n // interface to util functions. see Util.ts\n get util() {\n if (!this._util) {\n this._util = new _Util_js__WEBPACK_IMPORTED_MODULE_3__.Util(this.network);\n }\n return this._util;\n }\n // interface to util util. see Util.Util\n static get util() {\n return new this().util;\n }\n // Return wallet info\n getInfo() {\n throw Error(\"getInfo not implemented in BaseWallet\");\n }\n slpSemiAware(value = true) {\n this._slpSemiAware = value;\n return this;\n }\n //#region Accessors\n getNetworkProvider(\n // @ts-ignore\n network = _enum_js__WEBPACK_IMPORTED_MODULE_2__.NetworkType.Mainnet) {\n return (0,_network_default_js__WEBPACK_IMPORTED_MODULE_0__.getNetworkProvider)(network);\n }\n /**\n * getDepositAddress - get a wallet deposit address\n *\n * a high-level function,\n *\n * @see {@link https://rest-unstable.mainnet.cash/api-docs/#/wallet/depositAddress|/wallet/deposit_address} for REST endpoint\n *\n * @returns The deposit address as a string\n */\n getDepositAddress() {\n // return this.cashaddr;\n throw Error(\"getDepositAddress not implemented in BaseWallet\");\n }\n /**\n * getChangeAddress - get a wallet change address\n *\n * a high-level function,\n *\n * @see {@link https://rest-unstable.mainnet.cash/api-docs/#/wallet/changeAddress|/wallet/change_address} for REST endpoint\n *\n * @returns The change address as a string\n */\n getChangeAddress() {\n // return this.cashaddr;\n throw Error(\"getChangeAddress not implemented in BaseWallet\");\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 throw Error(\"getTokenDepositAddress not implemented in BaseWallet\");\n }\n /**\n * getTokenDepositAddress - get a cashtoken aware wallet deposit address\n *\n * @returns The cashtoken aware deposit address as a string\n */\n getTokenChangeAddress() {\n // return this.tokenaddr;\n throw Error(\"getTokenDepositAddress not implemented in BaseWallet\");\n }\n //#endregion Accessors\n //#region Constructors and Statics\n /**\n * constructor for a new wallet\n * @param network network for wallet\n *\n * @throws {Error} if called on BaseWallet\n */\n constructor(network = _enum_js__WEBPACK_IMPORTED_MODULE_2__.NetworkType.Mainnet) {\n this._slpSemiAware = false; // a flag which requires an utxo to have more than 546 sats to be spendable and counted in the balance\n this.name = \"\";\n this.network = network;\n this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Watch;\n this.provider = this.getNetworkProvider(this.network);\n this.isTestnet = this.network === _enum_js__WEBPACK_IMPORTED_MODULE_2__.NetworkType.Mainnet ? false : true;\n }\n //#endregion Constructors\n /**\n * named (internal) get a named wallet from the database or create a new one.\n * Note: this function should behave identically if\n *\n * @param {string} name name of the wallet\n * @param {string} dbName database name the wallet is stored in\n * @param {boolean} forceNew attempt to overwrite an existing wallet\n *\n * @throws {Error} if forceNew is true and the wallet already exists\n * @returns a promise to a named wallet\n */\n async named(name, dbName, forceNew = false) {\n if (name.length === 0) {\n throw Error(\"Named wallets must have a non-empty name\");\n }\n _checkContextSafety(this);\n this.name = name;\n dbName = dbName ? dbName : _enum_js__WEBPACK_IMPORTED_MODULE_2__.prefixFromNetworkMap[this.network];\n const db = getStorageProvider(dbName);\n // If there is a database, force saving or error\n if (db) {\n await db.init();\n const savedWalletRecord = await db.getWallet(name);\n if (savedWalletRecord) {\n await db.close();\n if (forceNew) {\n throw Error(`A wallet with the name ${name} already exists in ${dbName}`);\n }\n const recoveredWallet = await this.fromId(savedWalletRecord.wallet);\n recoveredWallet.name = savedWalletRecord.name;\n return recoveredWallet;\n }\n else {\n const wallet = await this.initialize();\n wallet.name = name;\n await db.addWallet(wallet.name, wallet.toDbString());\n await db.close();\n return wallet;\n }\n }\n else {\n throw Error(\"No database was available or configured to store the named wallet.\");\n }\n }\n /**\n * replaceNamed - Replace (recover) named wallet with a new walletId\n *\n * If wallet with a provided name does not exist yet, it will be created with a `walletId` supplied\n * If wallet exists it will be overwritten without exception\n *\n * @param name user friendly wallet alias\n * @param walletId walletId options to steer the creation process\n * @param dbName name under which the wallet will be stored in the database\n *\n * @returns instantiated wallet\n */\n async replaceNamed(name, walletId, dbName) {\n if (name.length === 0) {\n throw Error(\"Named wallets must have a non-empty name\");\n }\n _checkContextSafety(this);\n this.name = name;\n dbName = dbName ? dbName : _enum_js__WEBPACK_IMPORTED_MODULE_2__.prefixFromNetworkMap[this.network];\n let db = getStorageProvider(dbName);\n if (db) {\n await db.init();\n let savedWalletRecord = await db.getWallet(name);\n await this.fromId(walletId);\n if (savedWalletRecord) {\n await db.updateWallet(name, walletId);\n }\n else {\n await db.addWallet(name, walletId);\n }\n await db.close();\n return this;\n }\n else {\n throw Error(\"No database was available or configured to store the named wallet.\");\n }\n }\n /**\n * namedExists - check if a named wallet already exists\n *\n * @param name user friendly wallet alias\n * @param dbName name under which the wallet will be stored in the database\n *\n * @returns boolean\n */\n async namedExists(name, dbName) {\n if (name.length === 0) {\n throw Error(\"Named wallets must have a non-empty name\");\n }\n _checkContextSafety(this);\n dbName = dbName ? dbName : _enum_js__WEBPACK_IMPORTED_MODULE_2__.prefixFromNetworkMap[this.network];\n let db = getStorageProvider(dbName);\n if (db) {\n await db.init();\n let savedWalletRecord = await db.getWallet(name);\n await db.close();\n return savedWalletRecord !== undefined;\n }\n else {\n throw Error(\"No database was available or configured to store the named wallet.\");\n }\n }\n async initialize() {\n return this;\n }\n //#region Serialization\n /**\n * toDbString - store the serialized version of the wallet in the database, not just the name\n *\n * @throws {Error} if called on BaseWallet\n */\n toDbString() {\n return `${this.walletType}:${this.network}:${this.getDepositAddress()}`;\n }\n // Returns the serialized wallet as a string\n // If storing in a database, set asNamed to false to store secrets\n // In all other cases, the a named wallet is deserialized from the database\n // by the name key\n toString() {\n return `${this.walletType}:${this.network}:${this.getDepositAddress()}`;\n }\n //#endregion Serialization\n /**\n * explorerUrl Web url to a transaction on a block explorer\n *\n * @param txId transaction Id\n * @returns Url string\n */\n explorerUrl(txId) {\n const explorerUrlMap = {\n mainnet: \"https://blockchair.com/bitcoin-cash/transaction/\",\n testnet: \"https://www.blockchain.com/bch-testnet/tx/\",\n regtest: \"\",\n };\n return explorerUrlMap[this.network] + txId;\n }\n /**\n * named - create a named wallet\n *\n * @param name user friendly wallet alias\n * @param dbName name under which the wallet will be stored in the database\n * @param force force recreate wallet in the database if a record already exist\n *\n * @returns instantiated wallet\n */\n static async named(name, dbName, force) {\n return new this().named(name, dbName, force);\n }\n /**\n * replaceNamed - replace (recover) named wallet with a new walletId\n *\n * If wallet with a provided name does not exist yet, it will be created with a `walletId` supplied\n * If wallet exists it will be overwritten without exception\n *\n * @param name user friendly wallet alias\n * @param walletId walletId options to steer the creation process\n * @param dbName name under which the wallet will be stored in the database\n *\n * @returns instantiated wallet\n */\n static async replaceNamed(name, walletId, dbName) {\n return new this().replaceNamed(name, walletId, dbName);\n }\n /**\n * namedExists - check if a named wallet already exists\n *\n * @param name user friendly wallet alias\n * @param dbName name under which the wallet will be stored in the database\n *\n * @returns boolean\n */\n static async namedExists(name, dbName) {\n return new this().namedExists(name, dbName);\n }\n fromId(walletId) {\n throw Error(\"fromId not implemented in BaseWallet\");\n }\n //#region Funds\n /**\n * utxos Get unspent outputs for the wallet\n *\n */\n async getUtxos() {\n throw Error(\"getUtxos not implemented in BaseWallet\");\n }\n // gets wallet balance in sats\n async getBalance() {\n return this.getBalanceFromProvider();\n }\n // Gets balance by summing value in all utxos in stats\n async getBalanceFromUtxos() {\n const utxos = (await this.getUtxos()).filter((val) => val.token === undefined);\n return (0,_util_index_js__WEBPACK_IMPORTED_MODULE_5__.sumUtxoValue)(utxos);\n }\n // Gets balance from fulcrum\n async getBalanceFromProvider() {\n // Fulcrum reports balance of all utxos, including tokens, which is undesirable\n // // TODO not sure why getting the balance from a provider doesn't work\n // if (this._slpAware || this._slpSemiAware) {\n // return await this.getBalanceFromUtxos();\n // } else {\n // return await this.provider.getBalance(this.cashaddr);\n // }\n // FIXME\n return this.getBalanceFromUtxos();\n }\n async getAddressUtxos(address) {\n throw Error(\"getAddressUtxos not implemented in BaseWallet\");\n }\n // watching for any transaction hash of this wallet\n async watchAddress(callback) {\n return this.provider.watchAddress(this.getDepositAddress(), callback);\n }\n // watching for any transaction of this wallet\n async watchAddressTransactions(callback) {\n return this.provider.watchAddressTransactions(this.getDepositAddress(), callback);\n }\n // watching for cashtoken transaction of this wallet\n async watchAddressTokenTransactions(callback) {\n return this.provider.watchAddressTokenTransactions(this.getDepositAddress(), callback);\n }\n // sets up a callback to be called upon wallet's balance change\n // can be cancelled by calling the function returned from this one\n async watchBalance(callback) {\n return this.provider.watchAddressStatus(this.getDepositAddress(), async (_status) => {\n const balance = await this.getBalanceFromProvider();\n callback(balance);\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) {\n return new Promise(async (resolve) => {\n let watchCancel;\n watchCancel = await this.watchBalance(async (balance) => {\n if (balance >= value) {\n await watchCancel?.();\n resolve(balance);\n }\n });\n });\n }\n // sets up a callback to be called upon wallet's token balance change\n // can be cancelled by calling the function returned from this one\n async watchTokenBalance(tokenId, callback) {\n let previous = undefined;\n return await this.provider.watchAddressStatus(this.getDepositAddress(), async (_status) => {\n const balance = await this.getTokenBalance(tokenId);\n if (previous != balance) {\n callback(balance);\n }\n previous = balance;\n });\n }\n // waits for address token balance to be greater than or equal to the target amount\n // this call halts the execution\n async waitForTokenBalance(tokenId, amount) {\n return new Promise(async (resolve) => {\n let watchCancel;\n watchCancel = await this.watchTokenBalance(tokenId, async (balance) => {\n if (balance >= amount) {\n await watchCancel?.();\n resolve(balance);\n }\n });\n });\n }\n async _getMaxAmountToSend(params = {\n outputCount: 1,\n options: {},\n }) {\n if (params.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_6__.checkUtxos)(params.options.utxoIds.map((utxoId) => typeof utxoId === \"string\" ? (0,_model_js__WEBPACK_IMPORTED_MODULE_7__.fromUtxoId)(utxoId) : utxoId), this);\n }\n else {\n utxos = (await this.getUtxos()).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_7__.SendRequest({\n cashaddr: placeholderCashAddr,\n value: 100n,\n });\n const sendRequests = Array(params.outputCount)\n .fill(0)\n .map(() => sendRequest);\n const fundingUtxos = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_8__.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_8__.getFeeAmountSimple)({\n utxos: fundingUtxos,\n sendRequests: sendRequests,\n sourceAddress: placeholderCashAddr,\n relayFeePerByteInSatoshi: relayFeePerByteInSatoshi,\n feePaidBy: feePaidBy,\n });\n const spendableAmount = (0,_util_index_js__WEBPACK_IMPORTED_MODULE_5__.sumUtxoValue)(fundingUtxos);\n let result = spendableAmount - fee;\n if (result < 0n) {\n result = 0n;\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 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_7__.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_9__.binToHex)(encodedTransaction);\n resp.sourceOutputs = sourceOutputs;\n }\n return resp;\n }\n /**\n * sendMax Send all available funds to a destination cash address\n *\n * @param {string} cashaddr destination cash address\n * @param {SendRequestOptionsI} options Options of the send requests\n *\n * @returns (depending on the options parameter) the transaction id, new address balance and a link to the transaction on the blockchain explorer\n */\n async sendMax(cashaddr, options) {\n return await this.sendMaxRaw(cashaddr, options);\n }\n /**\n * sendMaxRaw (internal) Send all available funds to a destination cash address\n *\n * @param {string} cashaddr destination cash address\n * @param {SendRequestOptionsI} options Options of the send requests\n *\n * @returns the transaction id sent to the network\n */\n async sendMaxRaw(cashaddr, options, privateKey) {\n const { value: maxSpendableAmount, utxos } = await this._getMaxAmountToSend({\n outputCount: 1,\n options: options,\n privateKey: privateKey,\n });\n if (!options) {\n options = {};\n }\n options.utxoIds = utxos;\n const sendRequest = new _model_js__WEBPACK_IMPORTED_MODULE_7__.SendRequest({\n cashaddr: cashaddr,\n value: maxSpendableAmount,\n });\n const { encodedTransaction, tokenIds, sourceOutputs } = await this.encodeTransaction([sendRequest], true, options, privateKey);\n const resp = new _model_js__WEBPACK_IMPORTED_MODULE_7__.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_9__.binToHex)(encodedTransaction);\n resp.sourceOutputs = sourceOutputs;\n }\n return resp;\n }\n /**\n * encodeTransaction Encode and sign a transaction given a list of sendRequests, options and estimate fees.\n * @param {SendRequest[]} sendRequests SendRequests\n * @param {boolean} discardChange=false\n * @param {SendRequestOptionsI} options Options of the send requests\n */\n async encodeTransaction(requests, discardChange = false, options, privateKey) {\n let sendRequests = (0,_util_index_js__WEBPACK_IMPORTED_MODULE_10__.asSendRequestObject)(requests);\n if (options && options.slpSemiAware) {\n this._slpSemiAware = true;\n }\n let feePaidBy;\n if (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?.changeAddress) {\n changeAddress = options.changeAddress;\n }\n else {\n changeAddress = this.getChangeAddress();\n }\n let checkTokenQuantities = true;\n if (options?.checkTokenQuantities === false) {\n checkTokenQuantities = false;\n }\n // get inputs from options or query all inputs\n let utxos = await this.getUtxos();\n if (options && options.utxoIds) {\n utxos = await (0,_util_checkUtxos_js__WEBPACK_IMPORTED_MODULE_6__.checkUtxos)(options.utxoIds.map((utxoId) => typeof utxoId === \"string\" ? (0,_model_js__WEBPACK_IMPORTED_MODULE_7__.fromUtxoId)(utxoId) : utxoId), utxos);\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_7__.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_7__.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_7__.TokenSendRequest({\n cashaddr: (0,_util_index_js__WEBPACK_IMPORTED_MODULE_11__.toTokenaddr)(this.getChangeAddress()),\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_12__.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_8__.getFeeAmountSimple)({\n utxos: utxos,\n sendRequests: sendRequests,\n sourceAddress: this.getDepositAddress(),\n relayFeePerByteInSatoshi: relayFeePerByteInSatoshi,\n feePaidBy: feePaidBy,\n });\n const fundingUtxos = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_8__.getSuitableUtxos)(utxos, spendAmount + 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_8__.getFeeAmount)({\n utxos: fundingUtxos,\n sendRequests: sendRequests,\n sourceAddress: this.getDepositAddress(),\n relayFeePerByteInSatoshi: relayFeePerByteInSatoshi,\n feePaidBy: feePaidBy,\n walletCache: this.walletCache,\n });\n const { encodedTransaction, sourceOutputs } = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_8__.buildEncodedTransaction)({\n inputs: fundingUtxos,\n outputs: sendRequests,\n signingKey: privateKey ?? _transaction_Wif_js__WEBPACK_IMPORTED_MODULE_8__.placeholderPrivateKeyBin,\n fee,\n discardChange,\n feePaidBy,\n changeAddress,\n buildUnsigned: options?.buildUnsigned === true,\n walletCache: this.walletCache,\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_7__.TokenSendRequest)\n .map((val) => val.tokenId),\n ].filter((value, index, array) => array.indexOf(value) === index);\n return { encodedTransaction, tokenIds, sourceOutputs };\n }\n // Submit a raw transaction\n async submitTransaction(transaction, awaitPropagation = true) {\n if (!this.provider) {\n throw Error(\"Wallet network provider was not initialized\");\n }\n let rawTransaction = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_9__.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 throw Error(\"getRawHistory not implemented in BaseWallet\");\n }\n // gets last transaction of this wallet\n async getLastTransaction(confirmedOnly = false) {\n let history = await this.getRawHistory();\n if (confirmedOnly) {\n history = history.filter((val) => val.height > 0);\n }\n if (!history.length) {\n return null;\n }\n const [lastTx] = history.slice(-1);\n return this.provider.getRawTransactionObject(lastTx.tx_hash);\n }\n // waits for next transaction, program execution is halted\n async waitForTransaction(options = {\n getTransactionInfo: true,\n getBalance: false,\n txHash: undefined,\n }) {\n if (options.getTransactionInfo === undefined) {\n options.getTransactionInfo = true;\n }\n return new Promise(async (resolve) => {\n let txHashSeen = false;\n const makeResponse = async (txHash) => {\n const response = {};\n const promises = [undefined, undefined];\n if (options.getBalance === true) {\n promises[0] = this.getBalance();\n }\n if (options.getTransactionInfo === true) {\n if (!txHash) {\n promises[1] = this.getLastTransaction();\n }\n else {\n promises[1] = this.provider.getRawTransactionObject(txHash);\n }\n }\n const result = await Promise.all(promises);\n response.balance = result[0];\n response.transactionInfo = result[1];\n return response;\n };\n // waiting for a specific transaction to propagate\n if (options.txHash) {\n let cancel;\n const waitForTransactionCallback = async (data) => {\n if (data && data[0] === options.txHash && data[1] !== null) {\n txHashSeen = true;\n await cancel?.();\n resolve(makeResponse(options.txHash));\n }\n };\n cancel = await this.provider.subscribeToTransaction(options.txHash, waitForTransactionCallback);\n return;\n }\n // waiting for any address transaction\n let watchCancel;\n let initialResponseSeen = false;\n watchCancel = await this.provider.watchAddressStatus(this.getDepositAddress(), async (_status) => {\n if (initialResponseSeen) {\n await watchCancel?.();\n resolve(makeResponse());\n return;\n }\n initialResponseSeen = true;\n });\n });\n }\n /**\n * watchBlocks Watch network blocks\n *\n * @param callback callback with a block header object\n * @param skipCurrentHeight if set, the notification about current block will not arrive\n *\n * @returns a function which will cancel watching upon evaluation\n */\n async watchBlocks(callback, skipCurrentHeight = true) {\n return this.provider.watchBlocks(callback, skipCurrentHeight);\n }\n /**\n * waitForBlock Wait for a network block\n *\n * @param height if specified waits for this exact blockchain height, otherwise resolves with the next block\n *\n */\n async waitForBlock(height) {\n return this.provider.waitForBlock(height);\n }\n //#endregion Funds\n //#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 = await this.getUtxos();\n if (options?.utxoIds) {\n utxos = await (0,_util_checkUtxos_js__WEBPACK_IMPORTED_MODULE_6__.checkUtxos)(options.utxoIds.map((utxoId) => typeof utxoId === \"string\" ? (0,_model_js__WEBPACK_IMPORTED_MODULE_7__.fromUtxoId)(utxoId) : utxoId), utxos);\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_7__.TokenSendRequest({\n cashaddr: genesisRequest.cashaddr || this.getTokenDepositAddress(),\n amount: genesisRequest.amount,\n value: genesisRequest.value || 1000n,\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.getUtxos();\n const nftUtxos = utxos.filter((val) => val.token?.tokenId === tokenId &&\n val.token?.capability === _interface_js__WEBPACK_IMPORTED_MODULE_13__.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_7__.TokenSendRequest({\n cashaddr: (0,_util_index_js__WEBPACK_IMPORTED_MODULE_11__.toTokenaddr)(nftUtxos[0].address),\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_7__.TokenSendRequest({\n cashaddr: val.cashaddr || this.getTokenDepositAddress(),\n amount: 0n,\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.getUtxos();\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_7__.TokenSendRequest({\n cashaddr: burnRequest.cashaddr || (0,_util_index_js__WEBPACK_IMPORTED_MODULE_11__.toTokenaddr)(this.getChangeAddress()),\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_7__.TokenSendRequest({\n cashaddr: burnRequest.cashaddr || (0,_util_index_js__WEBPACK_IMPORTED_MODULE_11__.toTokenaddr)(this.getChangeAddress()),\n tokenId: burnRequest.tokenId,\n amount: safeNewAmount,\n value: tokenUtxos.reduce((a, c) => a + c.satoshis, 0n),\n }),\n ];\n }\n }\n const opReturn = _model_js__WEBPACK_IMPORTED_MODULE_7__.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 {Utxo[]} token utxos\n */\n async getTokenUtxos(tokenId) {\n const utxos = await this.getUtxos();\n return utxos.filter((val) => tokenId ? val.token?.tokenId === tokenId : val.token);\n }\n /**\n * getTokenBalance Gets fungible token balance\n * for NFT token balance see @ref getNftTokenBalance\n * @param {string} tokenId tokenId to get balance for\n * @returns {bigint} fungible token balance\n */\n async getTokenBalance(tokenId) {\n const utxos = (await this.getTokenUtxos(tokenId)).filter((val) => val.token?.amount);\n return (0,_util_index_js__WEBPACK_IMPORTED_MODULE_5__.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 //#endregion Cashtokens\n sign(message, privateKey = undefined) {\n if (!privateKey) {\n throw new Error(\"Signing private key not provided\");\n }\n return new _message_signed_js__WEBPACK_IMPORTED_MODULE_14__.SignedMessage().sign(message, privateKey);\n }\n // Convenience wrapper to verify interface\n verify(message, sig, address, publicKey) {\n if (!address && !publicKey) {\n throw new Error(\"Either address or publicKey must be provided for verification\");\n }\n return new _message_signed_js__WEBPACK_IMPORTED_MODULE_14__.SignedMessage().verify(message, sig, address, publicKey);\n }\n}\n/**\n * _checkContextSafety (internal) if running in nodejs, will disable saving\n * mainnet wallets on public servers if ALLOW_MAINNET_USER_WALLETS is set to false\n * @param {BaseWallet} wallet a wallet\n */\nconst _checkContextSafety = function (wallet) {\n if ((0,_util_index_js__WEBPACK_IMPORTED_MODULE_15__.getRuntimePlatform)() === \"node\") {\n if (process.env.ALLOW_MAINNET_USER_WALLETS === `false`) {\n if (wallet.network === _enum_js__WEBPACK_IMPORTED_MODULE_2__.NetworkType.Mainnet) {\n throw Error(`Refusing to save wallet in an open public database, remove ALLOW_MAINNET_USER_WALLETS=\"false\", if this service is secure and private`);\n }\n }\n }\n};\n/**\n * getNamedWalletId - get the full wallet id from the database\n *\n * @param name user friendly wallet alias\n * @param dbName name under which the wallet will be stored in the database\n *\n * @returns boolean\n */\nasync function getNamedWalletId(name, dbName) {\n if (name.length === 0) {\n throw Error(\"Named wallets must have a non-empty name\");\n }\n dbName = dbName ? dbName : dbName;\n let db = getStorageProvider(dbName);\n if (db) {\n await db.init();\n let savedWalletRecord = await db.getWallet(name);\n await db.close();\n if (savedWalletRecord !== undefined) {\n return savedWalletRecord.wallet;\n }\n else {\n throw Error(`No record was found for ${name} in db: ${dbName}`);\n }\n }\n else {\n throw Error(\"No database was available or configured to store the named wallet.\");\n }\n}\nfunction getStorageProvider(dbName) {\n if (!BaseWallet.StorageProvider) {\n return undefined;\n }\n return new BaseWallet.StorageProvider(dbName);\n}\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/wallet/Base.ts?");
|
|
637
|
+
eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"BaseWallet\": () => (/* binding */ BaseWallet),\n/* harmony export */ \"_checkContextSafety\": () => (/* binding */ _checkContextSafety),\n/* harmony export */ \"getNamedWalletId\": () => (/* binding */ getNamedWalletId),\n/* harmony export */ \"getStorageProvider\": () => (/* binding */ getStorageProvider),\n/* harmony export */ \"placeholderCashAddr\": () => (/* binding */ placeholderCashAddr),\n/* harmony export */ \"placeholderTokenAddr\": () => (/* binding */ placeholderTokenAddr)\n/* harmony export */ });\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/hex.js\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../enum.js */ \"./src/enum.ts\");\n/* harmony import */ var _interface_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../interface.js */ \"./src/interface.ts\");\n/* harmony import */ var _network_default_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../network/default.js */ \"./src/network/default.ts\");\n/* harmony import */ var _network_getRelayFeeCache_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../network/getRelayFeeCache.js */ \"./src/network/getRelayFeeCache.ts\");\n/* harmony import */ var _transaction_Wif_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../transaction/Wif.js */ \"./src/transaction/Wif.ts\");\n/* harmony import */ var _util_checkUtxos_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../util/checkUtxos.js */ \"./src/util/checkUtxos.ts\");\n/* harmony import */ var _util_index_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../util/index.js */ \"./src/util/sumUtxoValue.ts\");\n/* harmony import */ var _util_index_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../util/index.js */ \"./src/util/asSendRequestObject.ts\");\n/* harmony import */ var _util_index_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../util/index.js */ \"./src/util/deriveCashaddr.ts\");\n/* harmony import */ var _util_index_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../util/index.js */ \"./src/util/getRuntimePlatform.ts\");\n/* harmony import */ var _util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../util/sumSendRequestAmounts.js */ \"./src/util/sumSendRequestAmounts.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_7__ = __webpack_require__(/*! ./model.js */ \"./src/wallet/model.ts\");\n/* harmony import */ var _Util_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Util.js */ \"./src/wallet/Util.ts\");\n/* harmony import */ var _message_signed_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../message/signed.js */ \"./src/message/signed.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_network_default_js__WEBPACK_IMPORTED_MODULE_0__, _enum_js__WEBPACK_IMPORTED_MODULE_2__, _Util_js__WEBPACK_IMPORTED_MODULE_3__, _model_js__WEBPACK_IMPORTED_MODULE_7__, _transaction_Wif_js__WEBPACK_IMPORTED_MODULE_8__, _util_index_js__WEBPACK_IMPORTED_MODULE_10__, _util_index_js__WEBPACK_IMPORTED_MODULE_11__, _util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_12__, _message_signed_js__WEBPACK_IMPORTED_MODULE_14__]);\n([_network_default_js__WEBPACK_IMPORTED_MODULE_0__, _enum_js__WEBPACK_IMPORTED_MODULE_2__, _Util_js__WEBPACK_IMPORTED_MODULE_3__, _model_js__WEBPACK_IMPORTED_MODULE_7__, _transaction_Wif_js__WEBPACK_IMPORTED_MODULE_8__, _util_index_js__WEBPACK_IMPORTED_MODULE_10__, _util_index_js__WEBPACK_IMPORTED_MODULE_11__, _util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_12__, _message_signed_js__WEBPACK_IMPORTED_MODULE_14__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\n\n\n\n\n\n\n\n\n\n\n\nconst placeholderCashAddr = \"bitcoincash:qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqfnhks603\";\nconst placeholderTokenAddr = \"bitcoincash:zqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqweyg7usz\";\n/**\n * A class to hold features used by all wallets\n * @class BaseWallet\n */\nclass BaseWallet {\n get networkPrefix() {\n return _enum_js__WEBPACK_IMPORTED_MODULE_2__.prefixFromNetworkMap[this.network];\n }\n // interface to util functions. see Util.ts\n get util() {\n if (!this._util) {\n this._util = new _Util_js__WEBPACK_IMPORTED_MODULE_3__.Util(this.network);\n }\n return this._util;\n }\n // interface to util util. see Util.Util\n static get util() {\n return new this().util;\n }\n // Return wallet info\n getInfo() {\n throw Error(\"getInfo not implemented in BaseWallet\");\n }\n slpSemiAware(value = true) {\n this._slpSemiAware = value;\n return this;\n }\n //#region Accessors\n getNetworkProvider(\n // @ts-ignore\n network = _enum_js__WEBPACK_IMPORTED_MODULE_2__.NetworkType.Mainnet) {\n return (0,_network_default_js__WEBPACK_IMPORTED_MODULE_0__.getNetworkProvider)(network);\n }\n /**\n * getDepositAddress - get a wallet deposit address\n *\n * a high-level function,\n *\n * @see {@link https://rest-unstable.mainnet.cash/api-docs/#/wallet/depositAddress|/wallet/deposit_address} for REST endpoint\n *\n * @returns The deposit address as a string\n */\n getDepositAddress() {\n // return this.cashaddr;\n throw Error(\"getDepositAddress not implemented in BaseWallet\");\n }\n /**\n * getChangeAddress - get a wallet change address\n *\n * a high-level function,\n *\n * @see {@link https://rest-unstable.mainnet.cash/api-docs/#/wallet/changeAddress|/wallet/change_address} for REST endpoint\n *\n * @returns The change address as a string\n */\n getChangeAddress() {\n // return this.cashaddr;\n throw Error(\"getChangeAddress not implemented in BaseWallet\");\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 throw Error(\"getTokenDepositAddress not implemented in BaseWallet\");\n }\n /**\n * getTokenDepositAddress - get a cashtoken aware wallet deposit address\n *\n * @returns The cashtoken aware deposit address as a string\n */\n getTokenChangeAddress() {\n // return this.tokenaddr;\n throw Error(\"getTokenDepositAddress not implemented in BaseWallet\");\n }\n //#endregion Accessors\n //#region Constructors and Statics\n /**\n * constructor for a new wallet\n * @param network network for wallet\n *\n * @throws {Error} if called on BaseWallet\n */\n constructor(network = _enum_js__WEBPACK_IMPORTED_MODULE_2__.NetworkType.Mainnet) {\n this._slpSemiAware = false; // a flag which requires an utxo to have more than 546 sats to be spendable and counted in the balance\n this.name = \"\";\n this.network = network;\n this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Watch;\n this.provider = this.getNetworkProvider(this.network);\n this.isTestnet = this.network === _enum_js__WEBPACK_IMPORTED_MODULE_2__.NetworkType.Mainnet ? false : true;\n }\n //#endregion Constructors\n /**\n * named (internal) get a named wallet from the database or create a new one.\n * Note: this function should behave identically if\n *\n * @param {string} name name of the wallet\n * @param {string} dbName database name the wallet is stored in\n * @param {boolean} forceNew attempt to overwrite an existing wallet\n *\n * @throws {Error} if forceNew is true and the wallet already exists\n * @returns a promise to a named wallet\n */\n async named(name, dbName, forceNew = false) {\n if (name.length === 0) {\n throw Error(\"Named wallets must have a non-empty name\");\n }\n _checkContextSafety(this);\n this.name = name;\n dbName = dbName ? dbName : _enum_js__WEBPACK_IMPORTED_MODULE_2__.prefixFromNetworkMap[this.network];\n const db = getStorageProvider(dbName);\n // If there is a database, force saving or error\n if (db) {\n await db.init();\n const savedWalletRecord = await db.getWallet(name);\n if (savedWalletRecord) {\n await db.close();\n if (forceNew) {\n throw Error(`A wallet with the name ${name} already exists in ${dbName}`);\n }\n const recoveredWallet = await this.fromId(savedWalletRecord.wallet);\n recoveredWallet.name = savedWalletRecord.name;\n return recoveredWallet;\n }\n else {\n const wallet = await this.initialize();\n wallet.name = name;\n await db.addWallet(wallet.name, wallet.toDbString());\n await db.close();\n return wallet;\n }\n }\n else {\n throw Error(\"No database was available or configured to store the named wallet.\");\n }\n }\n /**\n * replaceNamed - Replace (recover) named wallet with a new walletId\n *\n * If wallet with a provided name does not exist yet, it will be created with a `walletId` supplied\n * If wallet exists it will be overwritten without exception\n *\n * @param name user friendly wallet alias\n * @param walletId walletId options to steer the creation process\n * @param dbName name under which the wallet will be stored in the database\n *\n * @returns instantiated wallet\n */\n async replaceNamed(name, walletId, dbName) {\n if (name.length === 0) {\n throw Error(\"Named wallets must have a non-empty name\");\n }\n _checkContextSafety(this);\n this.name = name;\n dbName = dbName ? dbName : _enum_js__WEBPACK_IMPORTED_MODULE_2__.prefixFromNetworkMap[this.network];\n let db = getStorageProvider(dbName);\n if (db) {\n await db.init();\n let savedWalletRecord = await db.getWallet(name);\n await this.fromId(walletId);\n if (savedWalletRecord) {\n await db.updateWallet(name, walletId);\n }\n else {\n await db.addWallet(name, walletId);\n }\n await db.close();\n return this;\n }\n else {\n throw Error(\"No database was available or configured to store the named wallet.\");\n }\n }\n /**\n * namedExists - check if a named wallet already exists\n *\n * @param name user friendly wallet alias\n * @param dbName name under which the wallet will be stored in the database\n *\n * @returns boolean\n */\n async namedExists(name, dbName) {\n if (name.length === 0) {\n throw Error(\"Named wallets must have a non-empty name\");\n }\n _checkContextSafety(this);\n dbName = dbName ? dbName : _enum_js__WEBPACK_IMPORTED_MODULE_2__.prefixFromNetworkMap[this.network];\n let db = getStorageProvider(dbName);\n if (db) {\n await db.init();\n let savedWalletRecord = await db.getWallet(name);\n await db.close();\n return savedWalletRecord !== undefined;\n }\n else {\n throw Error(\"No database was available or configured to store the named wallet.\");\n }\n }\n async initialize() {\n return this;\n }\n //#region Serialization\n /**\n * toDbString - store the serialized version of the wallet in the database, not just the name\n *\n * @throws {Error} if called on BaseWallet\n */\n toDbString() {\n return `${this.walletType}:${this.network}:${this.getDepositAddress()}`;\n }\n // Returns the serialized wallet as a string\n // If storing in a database, set asNamed to false to store secrets\n // In all other cases, the a named wallet is deserialized from the database\n // by the name key\n toString() {\n return `${this.walletType}:${this.network}:${this.getDepositAddress()}`;\n }\n //#endregion Serialization\n /**\n * explorerUrl Web url to a transaction on a block explorer\n *\n * @param txId transaction Id\n * @returns Url string\n */\n explorerUrl(txId) {\n const explorerUrlMap = {\n mainnet: \"https://blockchair.com/bitcoin-cash/transaction/\",\n testnet: \"https://www.blockchain.com/bch-testnet/tx/\",\n regtest: \"\",\n };\n return explorerUrlMap[this.network] + txId;\n }\n /**\n * named - create a named wallet\n *\n * @param name user friendly wallet alias\n * @param dbName name under which the wallet will be stored in the database\n * @param force force recreate wallet in the database if a record already exist\n *\n * @returns instantiated wallet\n */\n static async named(name, dbName, force) {\n return new this().named(name, dbName, force);\n }\n /**\n * replaceNamed - replace (recover) named wallet with a new walletId\n *\n * If wallet with a provided name does not exist yet, it will be created with a `walletId` supplied\n * If wallet exists it will be overwritten without exception\n *\n * @param name user friendly wallet alias\n * @param walletId walletId options to steer the creation process\n * @param dbName name under which the wallet will be stored in the database\n *\n * @returns instantiated wallet\n */\n static async replaceNamed(name, walletId, dbName) {\n return new this().replaceNamed(name, walletId, dbName);\n }\n /**\n * namedExists - check if a named wallet already exists\n *\n * @param name user friendly wallet alias\n * @param dbName name under which the wallet will be stored in the database\n *\n * @returns boolean\n */\n static async namedExists(name, dbName) {\n return new this().namedExists(name, dbName);\n }\n fromId(walletId) {\n throw Error(\"fromId not implemented in BaseWallet\");\n }\n //#region Funds\n /**\n * utxos Get unspent outputs for the wallet\n *\n */\n async getUtxos() {\n throw Error(\"getUtxos not implemented in BaseWallet\");\n }\n // gets wallet balance in sats\n async getBalance() {\n return this.getBalanceFromProvider();\n }\n // Gets balance by summing value in all utxos in stats\n async getBalanceFromUtxos() {\n const utxos = (await this.getUtxos()).filter((val) => val.token === undefined);\n return (0,_util_index_js__WEBPACK_IMPORTED_MODULE_5__.sumUtxoValue)(utxos);\n }\n // Gets balance from fulcrum\n async getBalanceFromProvider() {\n // Fulcrum reports balance of all utxos, including tokens, which is undesirable\n // // TODO not sure why getting the balance from a provider doesn't work\n // if (this._slpAware || this._slpSemiAware) {\n // return await this.getBalanceFromUtxos();\n // } else {\n // return await this.provider.getBalance(this.cashaddr);\n // }\n // FIXME\n return this.getBalanceFromUtxos();\n }\n async getAddressUtxos(address) {\n throw Error(\"getAddressUtxos not implemented in BaseWallet\");\n }\n // watching for any transaction hash of this wallet\n async watchAddress(callback) {\n return this.provider.watchAddress(this.getDepositAddress(), callback);\n }\n // watching for any transaction of this wallet\n async watchAddressTransactions(callback) {\n return this.provider.watchAddressTransactions(this.getDepositAddress(), callback);\n }\n // watching for cashtoken transaction of this wallet\n async watchAddressTokenTransactions(callback) {\n return this.provider.watchAddressTokenTransactions(this.getDepositAddress(), callback);\n }\n // sets up a callback to be called upon wallet's balance change\n // can be cancelled by calling the function returned from this one\n async watchBalance(callback) {\n return this.provider.watchAddressStatus(this.getDepositAddress(), async (_status) => {\n const balance = await this.getBalanceFromProvider();\n callback(balance);\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) {\n return new Promise(async (resolve) => {\n let watchCancel;\n watchCancel = await this.watchBalance(async (balance) => {\n if (balance >= value) {\n await watchCancel?.();\n resolve(balance);\n }\n });\n });\n }\n // sets up a callback to be called upon wallet's token balance change\n // can be cancelled by calling the function returned from this one\n async watchTokenBalance(category, callback) {\n let previous = undefined;\n return await this.provider.watchAddressStatus(this.getDepositAddress(), async (_status) => {\n const balance = await this.getTokenBalance(category);\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(category, amount) {\n return new Promise(async (resolve) => {\n let watchCancel;\n watchCancel = await this.watchTokenBalance(category, async (balance) => {\n if (balance >= amount) {\n await watchCancel?.();\n resolve(balance);\n }\n });\n });\n }\n async _getMaxAmountToSend(params = {\n outputCount: 1,\n options: {},\n }) {\n if (params.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_6__.checkUtxos)(params.options.utxoIds.map((utxoId) => typeof utxoId === \"string\" ? (0,_model_js__WEBPACK_IMPORTED_MODULE_7__.fromUtxoId)(utxoId) : utxoId), this);\n }\n else {\n utxos = (await this.getUtxos()).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_7__.SendRequest({\n cashaddr: placeholderCashAddr,\n value: 100n,\n });\n const sendRequests = Array(params.outputCount)\n .fill(0)\n .map(() => sendRequest);\n const fundingUtxos = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_8__.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_8__.getFeeAmountSimple)({\n utxos: fundingUtxos,\n sendRequests: sendRequests,\n sourceAddress: placeholderCashAddr,\n relayFeePerByteInSatoshi: relayFeePerByteInSatoshi,\n feePaidBy: feePaidBy,\n });\n const spendableAmount = (0,_util_index_js__WEBPACK_IMPORTED_MODULE_5__.sumUtxoValue)(fundingUtxos);\n let result = spendableAmount - fee;\n if (result < 0n) {\n result = 0n;\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 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, categories, sourceOutputs } = await this.encodeTransaction(requests, undefined, options);\n const resp = new _model_js__WEBPACK_IMPORTED_MODULE_7__.SendResponse({});\n resp.categories = categories;\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_9__.binToHex)(encodedTransaction);\n resp.sourceOutputs = sourceOutputs;\n }\n return resp;\n }\n /**\n * sendMax Send all available funds to a destination cash address\n *\n * @param {string} cashaddr destination cash address\n * @param {SendRequestOptionsI} options Options of the send requests\n *\n * @returns (depending on the options parameter) the transaction id, new address balance and a link to the transaction on the blockchain explorer\n */\n async sendMax(cashaddr, options) {\n return await this.sendMaxRaw(cashaddr, options);\n }\n /**\n * sendMaxRaw (internal) Send all available funds to a destination cash address\n *\n * @param {string} cashaddr destination cash address\n * @param {SendRequestOptionsI} options Options of the send requests\n *\n * @returns the transaction id sent to the network\n */\n async sendMaxRaw(cashaddr, options, privateKey) {\n const { value: maxSpendableAmount, utxos } = await this._getMaxAmountToSend({\n outputCount: 1,\n options: options,\n privateKey: privateKey,\n });\n if (!options) {\n options = {};\n }\n options.utxoIds = utxos;\n const sendRequest = new _model_js__WEBPACK_IMPORTED_MODULE_7__.SendRequest({\n cashaddr: cashaddr,\n value: maxSpendableAmount,\n });\n const { encodedTransaction, categories, sourceOutputs } = await this.encodeTransaction([sendRequest], true, options, privateKey);\n const resp = new _model_js__WEBPACK_IMPORTED_MODULE_7__.SendResponse({});\n resp.categories = categories;\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_9__.binToHex)(encodedTransaction);\n resp.sourceOutputs = sourceOutputs;\n }\n return resp;\n }\n /**\n * encodeTransaction Encode and sign a transaction given a list of sendRequests, options and estimate fees.\n * @param {SendRequest[]} sendRequests SendRequests\n * @param {boolean} discardChange=false\n * @param {SendRequestOptionsI} options Options of the send requests\n */\n async encodeTransaction(requests, discardChange = false, options, privateKey) {\n let sendRequests = (0,_util_index_js__WEBPACK_IMPORTED_MODULE_10__.asSendRequestObject)(requests);\n if (options && options.slpSemiAware) {\n this._slpSemiAware = true;\n }\n let feePaidBy;\n if (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?.changeAddress) {\n changeAddress = options.changeAddress;\n }\n else {\n changeAddress = this.getChangeAddress();\n }\n let checkTokenQuantities = true;\n if (options?.checkTokenQuantities === false) {\n checkTokenQuantities = false;\n }\n // get inputs from options or query all inputs\n let utxos = await this.getUtxos();\n if (options && options.utxoIds) {\n utxos = await (0,_util_checkUtxos_js__WEBPACK_IMPORTED_MODULE_6__.checkUtxos)(options.utxoIds.map((utxoId) => typeof utxoId === \"string\" ? (0,_model_js__WEBPACK_IMPORTED_MODULE_7__.fromUtxoId)(utxoId) : utxoId), utxos);\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_7__.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_7__.TokenSendRequest);\n const categories = allTokenOutputs\n .map((val) => val.category)\n .filter((val, idx, arr) => arr.indexOf(val) === idx);\n for (let category of categories) {\n const tokenInputs = allTokenInputs.filter((val) => val.token?.category === category);\n const inputAmountSum = tokenInputs.reduce((prev, cur) => prev + cur.token.amount, 0n);\n const tokenOutputs = allTokenOutputs.filter((val) => val.category === category);\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_7__.TokenSendRequest({\n cashaddr: (0,_util_index_js__WEBPACK_IMPORTED_MODULE_11__.toTokenaddr)(this.getChangeAddress()),\n amount: change,\n category: category,\n nft: tokenOutputs[0].nft,\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_12__.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_8__.getFeeAmountSimple)({\n utxos: utxos,\n sendRequests: sendRequests,\n sourceAddress: this.getDepositAddress(),\n relayFeePerByteInSatoshi: relayFeePerByteInSatoshi,\n feePaidBy: feePaidBy,\n });\n const fundingUtxos = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_8__.getSuitableUtxos)(utxos, spendAmount + 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_8__.getFeeAmount)({\n utxos: fundingUtxos,\n sendRequests: sendRequests,\n sourceAddress: this.getDepositAddress(),\n relayFeePerByteInSatoshi: relayFeePerByteInSatoshi,\n feePaidBy: feePaidBy,\n walletCache: this.walletCache,\n });\n const { encodedTransaction, sourceOutputs } = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_8__.buildEncodedTransaction)({\n inputs: fundingUtxos,\n outputs: sendRequests,\n signingKey: privateKey ?? _transaction_Wif_js__WEBPACK_IMPORTED_MODULE_8__.placeholderPrivateKeyBin,\n fee,\n discardChange,\n feePaidBy,\n changeAddress,\n buildUnsigned: options?.buildUnsigned === true,\n walletCache: this.walletCache,\n });\n const categories = [\n ...fundingUtxos\n .filter((val) => val.token?.category)\n .map((val) => val.token.category),\n ...sendRequests\n .filter((val) => val instanceof _model_js__WEBPACK_IMPORTED_MODULE_7__.TokenSendRequest)\n .map((val) => val.category),\n ].filter((value, index, array) => array.indexOf(value) === index);\n return { encodedTransaction, categories, sourceOutputs };\n }\n // Submit a raw transaction\n async submitTransaction(transaction, awaitPropagation = true) {\n if (!this.provider) {\n throw Error(\"Wallet network provider was not initialized\");\n }\n let rawTransaction = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_9__.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 throw Error(\"getRawHistory not implemented in BaseWallet\");\n }\n // gets last transaction of this wallet\n async getLastTransaction(confirmedOnly = false) {\n let history = await this.getRawHistory();\n if (confirmedOnly) {\n history = history.filter((val) => val.height > 0);\n }\n if (!history.length) {\n return null;\n }\n const [lastTx] = history.slice(-1);\n return this.provider.getRawTransactionObject(lastTx.tx_hash);\n }\n // waits for next transaction, program execution is halted\n async waitForTransaction(options = {\n getTransactionInfo: true,\n getBalance: false,\n txHash: undefined,\n }) {\n if (options.getTransactionInfo === undefined) {\n options.getTransactionInfo = true;\n }\n return new Promise(async (resolve) => {\n let txHashSeen = false;\n const makeResponse = async (txHash) => {\n const response = {};\n const promises = [undefined, undefined];\n if (options.getBalance === true) {\n promises[0] = this.getBalance();\n }\n if (options.getTransactionInfo === true) {\n if (!txHash) {\n promises[1] = this.getLastTransaction();\n }\n else {\n promises[1] = this.provider.getRawTransactionObject(txHash);\n }\n }\n const result = await Promise.all(promises);\n response.balance = result[0];\n response.transactionInfo = result[1];\n return response;\n };\n // waiting for a specific transaction to propagate\n if (options.txHash) {\n let cancel;\n const waitForTransactionCallback = async (data) => {\n if (data && data[0] === options.txHash && data[1] !== null) {\n txHashSeen = true;\n await cancel?.();\n resolve(makeResponse(options.txHash));\n }\n };\n cancel = await this.provider.subscribeToTransaction(options.txHash, waitForTransactionCallback);\n return;\n }\n // waiting for any address transaction\n let watchCancel;\n let initialResponseSeen = false;\n watchCancel = await this.provider.watchAddressStatus(this.getDepositAddress(), async (_status) => {\n if (initialResponseSeen) {\n await watchCancel?.();\n resolve(makeResponse());\n return;\n }\n initialResponseSeen = true;\n });\n });\n }\n /**\n * watchBlocks Watch network blocks\n *\n * @param callback callback with a block header object\n * @param skipCurrentHeight if set, the notification about current block will not arrive\n *\n * @returns a function which will cancel watching upon evaluation\n */\n async watchBlocks(callback, skipCurrentHeight = true) {\n return this.provider.watchBlocks(callback, skipCurrentHeight);\n }\n /**\n * waitForBlock Wait for a network block\n *\n * @param height if specified waits for this exact blockchain height, otherwise resolves with the next block\n *\n */\n async waitForBlock(height) {\n return this.provider.waitForBlock(height);\n }\n //#endregion Funds\n //#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 = await this.getUtxos();\n if (options?.utxoIds) {\n utxos = await (0,_util_checkUtxos_js__WEBPACK_IMPORTED_MODULE_6__.checkUtxos)(options.utxoIds.map((utxoId) => typeof utxoId === \"string\" ? (0,_model_js__WEBPACK_IMPORTED_MODULE_7__.fromUtxoId)(utxoId) : utxoId), utxos);\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_7__.TokenSendRequest({\n cashaddr: genesisRequest.cashaddr || this.getTokenDepositAddress(),\n amount: genesisRequest.amount,\n value: genesisRequest.value || 1000n,\n nft: genesisRequest.nft,\n category: 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} category category 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(category, mintRequests, deductTokenAmount = false, options) {\n if (category?.length !== 64) {\n throw Error(`Invalid category supplied: ${category}`);\n }\n if (!Array.isArray(mintRequests)) {\n mintRequests = [mintRequests];\n }\n const utxos = await this.getUtxos();\n const nftUtxos = utxos.filter((val) => val.token?.category === category &&\n val.token?.nft?.capability === _interface_js__WEBPACK_IMPORTED_MODULE_13__.NFTCapability.minting);\n if (!nftUtxos.length) {\n throw new Error(\"You do not have any token UTXOs with minting capability for specified category\");\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_7__.TokenSendRequest({\n cashaddr: (0,_util_index_js__WEBPACK_IMPORTED_MODULE_11__.toTokenaddr)(nftUtxos[0].address),\n category: category,\n nft: nftUtxos[0].token?.nft,\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_7__.TokenSendRequest({\n cashaddr: val.cashaddr || this.getTokenDepositAddress(),\n amount: 0n,\n category: category,\n value: val.value,\n nft: val.nft,\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.category category 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.category?.length !== 64) {\n throw Error(`Invalid category supplied: ${burnRequest.category}`);\n }\n const utxos = await this.getUtxos();\n const tokenUtxos = utxos.filter((val) => val.token?.category === burnRequest.category &&\n val.token?.nft?.capability === burnRequest.nft?.capability &&\n val.token?.nft?.commitment === burnRequest.nft?.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.nft !== undefined;\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_7__.TokenSendRequest({\n cashaddr: burnRequest.cashaddr || (0,_util_index_js__WEBPACK_IMPORTED_MODULE_11__.toTokenaddr)(this.getChangeAddress()),\n category: burnRequest.category,\n nft: burnRequest.nft,\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_7__.TokenSendRequest({\n cashaddr: burnRequest.cashaddr || (0,_util_index_js__WEBPACK_IMPORTED_MODULE_11__.toTokenaddr)(this.getChangeAddress()),\n category: burnRequest.category,\n amount: safeNewAmount,\n value: tokenUtxos.reduce((a, c) => a + c.satoshis, 0n),\n }),\n ];\n }\n }\n const opReturn = _model_js__WEBPACK_IMPORTED_MODULE_7__.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 `category` provided\n * @param {string?} category category to filter utxos by, if not set will return utxos from all tokens\n * @returns {Utxo[]} token utxos\n */\n async getTokenUtxos(category) {\n const utxos = await this.getUtxos();\n return utxos.filter((val) => category ? val.token?.category === category : val.token);\n }\n /**\n * getTokenBalance Gets fungible token balance\n * for NFT token balance see @ref getNftTokenBalance\n * @param {string} category category to get balance for\n * @returns {bigint} fungible token balance\n */\n async getTokenBalance(category) {\n const utxos = (await this.getTokenUtxos(category)).filter((val) => val.token?.amount);\n return (0,_util_index_js__WEBPACK_IMPORTED_MODULE_5__.sumTokenAmounts)(utxos, category);\n }\n /**\n * getNftTokenBalance Gets non-fungible token (NFT) balance for a particular category\n * disregards fungible token balances\n * for fungible token balance see @ref getTokenBalance\n * @param {string} category category to get balance for\n * @returns {number} non-fungible token balance\n */\n async getNftTokenBalance(category) {\n const utxos = (await this.getTokenUtxos(category)).filter((val) => val.token?.nft?.commitment !== undefined);\n return utxos.length;\n }\n /**\n * getAllTokenBalances Gets all fungible token balances in this wallet\n * @returns {Object} a map [category => 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.category]) {\n result[utxo.token.category] = 0n;\n }\n result[utxo.token.category] += 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 [category => balance] for all NFTs in this wallet\n */\n async getAllNftTokenBalances() {\n const result = {};\n const utxos = (await this.getTokenUtxos()).filter((val) => val.token?.nft?.commitment !== undefined);\n for (const utxo of utxos) {\n if (!result[utxo.token.category]) {\n result[utxo.token.category] = 0;\n }\n result[utxo.token.category] += 1;\n }\n return result;\n }\n //#endregion Cashtokens\n sign(message, privateKey = undefined) {\n if (!privateKey) {\n throw new Error(\"Signing private key not provided\");\n }\n return new _message_signed_js__WEBPACK_IMPORTED_MODULE_14__.SignedMessage().sign(message, privateKey);\n }\n // Convenience wrapper to verify interface\n verify(message, sig, address, publicKey) {\n if (!address && !publicKey) {\n throw new Error(\"Either address or publicKey must be provided for verification\");\n }\n return new _message_signed_js__WEBPACK_IMPORTED_MODULE_14__.SignedMessage().verify(message, sig, address, publicKey);\n }\n}\n/**\n * _checkContextSafety (internal) if running in nodejs, will disable saving\n * mainnet wallets on public servers if ALLOW_MAINNET_USER_WALLETS is set to false\n * @param {BaseWallet} wallet a wallet\n */\nconst _checkContextSafety = function (wallet) {\n if ((0,_util_index_js__WEBPACK_IMPORTED_MODULE_15__.getRuntimePlatform)() === \"node\") {\n if (process.env.ALLOW_MAINNET_USER_WALLETS === `false`) {\n if (wallet.network === _enum_js__WEBPACK_IMPORTED_MODULE_2__.NetworkType.Mainnet) {\n throw Error(`Refusing to save wallet in an open public database, remove ALLOW_MAINNET_USER_WALLETS=\"false\", if this service is secure and private`);\n }\n }\n }\n};\n/**\n * getNamedWalletId - get the full wallet id from the database\n *\n * @param name user friendly wallet alias\n * @param dbName name under which the wallet will be stored in the database\n *\n * @returns boolean\n */\nasync function getNamedWalletId(name, dbName) {\n if (name.length === 0) {\n throw Error(\"Named wallets must have a non-empty name\");\n }\n dbName = dbName ? dbName : dbName;\n let db = getStorageProvider(dbName);\n if (db) {\n await db.init();\n let savedWalletRecord = await db.getWallet(name);\n await db.close();\n if (savedWalletRecord !== undefined) {\n return savedWalletRecord.wallet;\n }\n else {\n throw Error(`No record was found for ${name} in db: ${dbName}`);\n }\n }\n else {\n throw Error(\"No database was available or configured to store the named wallet.\");\n }\n}\nfunction getStorageProvider(dbName) {\n if (!BaseWallet.StorageProvider) {\n return undefined;\n }\n return new BaseWallet.StorageProvider(dbName);\n}\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/wallet/Base.ts?");
|
|
638
638
|
|
|
639
639
|
/***/ }),
|
|
640
640
|
|
|
@@ -704,7 +704,7 @@ eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harm
|
|
|
704
704
|
\*****************************/
|
|
705
705
|
/***/ ((module, __webpack_exports__, __webpack_require__) => {
|
|
706
706
|
|
|
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 */ \"OpReturnData\": () => (/* binding */ OpReturnData),\n/* harmony export */ \"SendRequest\": () => (/* binding */ SendRequest),\n/* harmony export */ \"SendResponse\": () => (/* binding */ SendResponse),\n/* harmony export */ \"TokenBurnRequest\": () => (/* binding */ TokenBurnRequest),\n/* harmony export */ \"TokenGenesisRequest\": () => (/* binding */ TokenGenesisRequest),\n/* harmony export */ \"TokenMintRequest\": () => (/* binding */ TokenMintRequest),\n/* harmony export */ \"TokenSendRequest\": () => (/* binding */ TokenSendRequest),\n/* harmony export */ \"XPubKey\": () => (/* binding */ XPubKey),\n/* harmony export */ \"fromUtxoId\": () => (/* binding */ fromUtxoId),\n/* harmony export */ \"toUtxoId\": () => (/* binding */ toUtxoId)\n/* harmony export */ });\n/* harmony import */ var _constant_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../constant.js */ \"./src/constant.ts\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/utf8.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/number.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 _config_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../config.js */ \"./src/config.ts\");\n/* harmony import */ var _util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../util/deriveCashaddr.js */ \"./src/util/deriveCashaddr.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_0__]);\n_util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_0__ = (__webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__)[0];\n\n\n\n\nclass SendRequest {\n constructor({ cashaddr, value }) {\n this.cashaddr = cashaddr;\n this.value = BigInt(value);\n }\n}\nclass TokenGenesisRequest {\n constructor({ amount,
|
|
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 */ \"OpReturnData\": () => (/* binding */ OpReturnData),\n/* harmony export */ \"SendRequest\": () => (/* binding */ SendRequest),\n/* harmony export */ \"SendResponse\": () => (/* binding */ SendResponse),\n/* harmony export */ \"TokenBurnRequest\": () => (/* binding */ TokenBurnRequest),\n/* harmony export */ \"TokenGenesisRequest\": () => (/* binding */ TokenGenesisRequest),\n/* harmony export */ \"TokenMintRequest\": () => (/* binding */ TokenMintRequest),\n/* harmony export */ \"TokenSendRequest\": () => (/* binding */ TokenSendRequest),\n/* harmony export */ \"XPubKey\": () => (/* binding */ XPubKey),\n/* harmony export */ \"fromUtxoId\": () => (/* binding */ fromUtxoId),\n/* harmony export */ \"toUtxoId\": () => (/* binding */ toUtxoId)\n/* harmony export */ });\n/* harmony import */ var _constant_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../constant.js */ \"./src/constant.ts\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/utf8.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/number.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 _config_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../config.js */ \"./src/config.ts\");\n/* harmony import */ var _util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../util/deriveCashaddr.js */ \"./src/util/deriveCashaddr.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_0__]);\n_util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_0__ = (__webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__)[0];\n\n\n\n\nclass SendRequest {\n constructor({ cashaddr, value }) {\n this.cashaddr = cashaddr;\n this.value = BigInt(value);\n }\n}\nclass TokenGenesisRequest {\n constructor({ amount, nft, cashaddr, value, }) {\n this.amount = amount;\n this.nft = nft;\n this.cashaddr = cashaddr;\n this.value = value;\n }\n}\nclass TokenBurnRequest {\n constructor({ category, amount, nft, cashaddr, }) {\n this.category = category;\n this.amount = amount ? BigInt(amount) : 0n;\n this.nft = nft;\n this.cashaddr = cashaddr;\n }\n}\nclass TokenSendRequest {\n constructor({ cashaddr, value, amount, category, nft, }) {\n (0,_util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_0__.checkTokenaddr)(cashaddr, _config_js__WEBPACK_IMPORTED_MODULE_1__.Config.EnforceCashTokenReceiptAddresses);\n this.cashaddr = cashaddr;\n this.value = value;\n this.amount = amount ? BigInt(amount) : 0n;\n this.category = category;\n this.nft = nft;\n }\n}\nclass TokenMintRequest {\n constructor({ nft, cashaddr, value, }) {\n this.nft = nft;\n this.cashaddr = cashaddr;\n this.value = value;\n }\n}\nclass OpReturnData {\n constructor(buffer) {\n this.buffer = Uint8Array.from(buffer);\n }\n /**\n * from - Construct OP_RETURN data from arbitrary data type\n *\n * @param string UTF-8 encoded string message to be converted to OP_RETURN data\n *\n * @returns class instance\n */\n static from(data) {\n return this.fromArray([data]);\n }\n /**\n * fromString - Accept data as a simple UTF-8 string message and append an OP_RETURN and PUSH_DATA1 opcodes to it\n *\n * @param string UTF-8 encoded string message to be converted to OP_RETURN data\n *\n * @returns class instance\n */\n static fromString(string) {\n return this.fromArray([string]);\n }\n /**\n * buffer - Accept OP_RETURN data as a binary buffer.\n * If buffer lacks the OP_RETURN and OP_PUSHDATA opcodes, they will be prepended.\n *\n * @param buffer Data buffer to be assigned to the OP_RETURN outpit\n *\n * @returns class instance\n */\n static fromUint8Array(uint8Array) {\n if (uint8Array[0] !== 0x6a) {\n return this.fromArray([uint8Array]);\n }\n return new this(Uint8Array.from(uint8Array));\n }\n /**\n * fromArray - Accept array of data\n *\n * @param array Array of Uint8Array or UTF-8 encoded string messages to be converted to OP_RETURN data\n *\n * @returns class instance\n */\n static fromArray(array) {\n let data = Uint8Array.from([0x6a]); // OP_RETURN\n for (const element of array) {\n let length;\n let elementData;\n let lengthData;\n if (typeof element === \"string\") {\n elementData = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.utf8ToBin)(element);\n length = elementData.length;\n }\n else if (element instanceof Uint8Array) {\n elementData = element;\n length = elementData.length;\n }\n else {\n throw new Error(\"Wrong data array element\");\n }\n if (length < 76) {\n // OP_PUSHDATA_1\n lengthData = [length];\n }\n else if (length < 223) {\n // default max `-datacarriersize`\n lengthData = [0x4c, length];\n }\n else {\n throw new Error(\"OP_RETURN data can not exceed 220 bytes in size\");\n }\n data = Uint8Array.from([...data, ...lengthData, ...elementData]);\n }\n if (data.length > 220) {\n throw new Error(\"OP_RETURN data can not exceed 220 bytes in size\");\n }\n return new this(data);\n }\n /**\n * parseBinary - parse OP_RETURN data and return pushed chunks of binary data\n *\n * @param opReturn Raw OP_RETURN data\n *\n * @returns array of binary data chunks pushed\n */\n static parseBinary(opReturn) {\n const chunks = [];\n let position = 1;\n // handle direct push, OP_PUSHDATA1, OP_PUSHDATA2;\n // OP_PUSHDATA4 is not supported in OP_RETURNs by consensus\n while (opReturn[position]) {\n let length = 0;\n if (opReturn[position] === 0x4c) {\n length = opReturn[position + 1];\n position += 2;\n }\n else if (opReturn[position] === 0x4d) {\n length = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.binToNumberUint16LE)(opReturn.slice(position + 1, position + 3));\n position += 3;\n }\n else {\n length = opReturn[position];\n position += 1;\n }\n chunks.push(opReturn.slice(position, position + length));\n position += length;\n }\n return chunks;\n }\n /**\n * parse - parse OP_RETURN hex data and return pushed chunks of binary data, converted to utf8 strings\n *\n * @param opReturn Raw OP_RETURN hex data\n *\n * @returns array of binary data chunks pushed, converted to utf8 strings\n */\n static parse(opReturnHex) {\n return this.parseBinary((0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__.hexToBin)(opReturnHex)).map((val) => (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.binToUtf8)(val));\n }\n}\nclass SendResponse {\n constructor({ txId, balance, explorerUrl, }) {\n this.txId = txId;\n this.balance = balance;\n this.explorerUrl = explorerUrl;\n }\n}\nclass XPubKey {\n constructor({ path, xPubKey }) {\n this.path = path;\n this.xPubKey = xPubKey;\n }\n async ready() {\n await this.xPubKey;\n return this.asObject();\n }\n asObject() {\n return {\n path: this.path,\n xPubKey: this.xPubKey,\n };\n }\n}\nconst fromUtxoId = (utxoId) => {\n const [txid, vout, satoshis] = utxoId.split(_constant_js__WEBPACK_IMPORTED_MODULE_5__.DELIMITER);\n return {\n satoshis: satoshis ? BigInt(parseInt(satoshis)) : 0n,\n vout: parseInt(vout),\n txid,\n };\n};\nconst toUtxoId = (utxo) => {\n return [utxo.txid, utxo.vout].join(_constant_js__WEBPACK_IMPORTED_MODULE_5__.DELIMITER).replace(/:+$/, \"\");\n};\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/wallet/model.ts?");
|
|
708
708
|
|
|
709
709
|
/***/ }),
|
|
710
710
|
|