mainnet-js 1.1.4 → 1.1.5
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-1.1.4.js → mainnet-1.1.5.js} +2 -2
- package/dist/module/transaction/Wif.d.ts +6 -4
- package/dist/module/transaction/Wif.d.ts.map +1 -1
- package/dist/module/transaction/Wif.js +54 -22
- package/dist/module/transaction/Wif.js.map +1 -1
- package/dist/module/wallet/Wif.d.ts +2 -1
- package/dist/module/wallet/Wif.d.ts.map +1 -1
- package/dist/module/wallet/Wif.js +8 -6
- package/dist/module/wallet/Wif.js.map +1 -1
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/package.json +1 -1
- package/src/transaction/Wif.ts +76 -21
- package/src/wallet/Cashtokens.test.headless.js +54 -12
- package/src/wallet/Cashtokens.test.ts +52 -12
- package/src/wallet/Wif.ts +18 -7
package/dist/index.html
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
<head>
|
|
4
4
|
<meta charset="utf-8">
|
|
5
5
|
<title>The Empty Mainnet App</title>
|
|
6
|
-
<meta name="viewport" content="width=device-width, initial-scale=1"><script defer src="mainnet-1.1.
|
|
6
|
+
<meta name="viewport" content="width=device-width, initial-scale=1"><script defer src="mainnet-1.1.5.js"></script></head>
|
|
7
7
|
<body><script>document.addEventListener("DOMContentLoaded", async (event) => Object.assign(globalThis, await __mainnetPromise))</script>
|
|
8
8
|
</body>
|
|
9
9
|
</html>
|
|
@@ -1304,7 +1304,7 @@ eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harm
|
|
|
1304
1304
|
\********************************/
|
|
1305
1305
|
/***/ ((module, __webpack_exports__, __webpack_require__) => {
|
|
1306
1306
|
|
|
1307
|
-
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 */ \"getSuitableUtxos\": () => (/* binding */ getSuitableUtxos)\n/* harmony export */ });\n/* unused harmony exports buildP2pkhNonHdTransaction, prepareInputs, prepareOutputs, prepareOpReturnOutput, prepareTokenOutputs */\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/schema/authentication-template.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/compiler/standard/p2pkh.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__ = __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_8__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/address/locking-bytecode.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/transaction/generate-transaction.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__ = __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_11__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/hex.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/message/transaction-encoding.js\");\n/* harmony import */ var _interface_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../interface.js */ \"./src/interface.ts\");\n/* harmony import */ var _allocateFee_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./allocateFee.js */ \"./src/transaction/allocateFee.ts\");\n/* harmony import */ var _constant_js__WEBPACK_IMPORTED_MODULE_7__ = __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_amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../util/amountInSatoshi.js */ \"./src/util/amountInSatoshi.ts\");\n/* harmony import */ var _util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../util/sumSendRequestAmounts.js */ \"./src/util/sumSendRequestAmounts.ts\");\n/* harmony import */ var _util_sumUtxoValue_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../util/sumUtxoValue.js */ \"./src/util/sumUtxoValue.ts\");\n/* harmony import */ var _wallet_enum_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../wallet/enum.js */ \"./src/wallet/enum.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__, _util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_5__, _allocateFee_js__WEBPACK_IMPORTED_MODULE_6__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_8__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_9__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__, _wallet_model_js__WEBPACK_IMPORTED_MODULE_12__, _util_amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_13__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_15__]);\n([_bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__, _util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_5__, _allocateFee_js__WEBPACK_IMPORTED_MODULE_6__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_8__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_9__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__, _wallet_model_js__WEBPACK_IMPORTED_MODULE_12__, _util_amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_13__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_15__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n// Unstable?\n\n\n\n\n\n\n\n\n\n// Build a transaction for a p2pkh transaction for a non HD wallet\nasync function buildP2pkhNonHdTransaction({ inputs, outputs, signingKey, sourceAddress, fee = 0, discardChange = false, slpOutputs = [], feePaidBy = _wallet_enum_js__WEBPACK_IMPORTED_MODULE_0__.FeePaidByEnum.change, changeAddress = \"\", }) {\n if (!signingKey) {\n throw new Error(\"Missing signing key when building transaction\");\n }\n const template = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.importAuthenticationTemplate)(_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.authenticationTemplateP2pkhNonHd);\n if (typeof template === \"string\") {\n throw new Error(\"Transaction template error\");\n }\n const compiler = await (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.authenticationTemplateToCompilerBCH)(template);\n const inputAmount = await (0,_util_sumUtxoValue_js__WEBPACK_IMPORTED_MODULE_4__.sumUtxoValue)(inputs);\n const sendAmount = await (0,_util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_5__.sumSendRequestAmounts)(outputs);\n const changeAmount = BigInt(inputAmount) - BigInt(sendAmount) - BigInt(fee);\n outputs = (0,_allocateFee_js__WEBPACK_IMPORTED_MODULE_6__.allocateFee)(outputs, fee, feePaidBy, changeAmount);\n const lockedOutputs = await prepareOutputs(outputs);\n if (discardChange !== true) {\n if (changeAmount > _constant_js__WEBPACK_IMPORTED_MODULE_7__.DUST_UTXO_THRESHOLD) {\n let changeLockingBytecode;\n if (changeAddress) {\n changeLockingBytecode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_8__.cashAddressToLockingBytecode)(changeAddress);\n }\n else {\n // Get the change locking bytecode\n changeLockingBytecode = compiler.generateBytecode({\n scriptId: \"lock\",\n data: {\n keys: { privateKeys: { key: signingKey } },\n },\n });\n }\n if (typeof changeLockingBytecode === \"string\") {\n throw new 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 sourceAddress,\n });\n const result = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_9__.generateTransaction)({\n inputs: preparedInputs,\n locktime: 0,\n outputs: [...slpOutputs, ...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_10__.verifyTransactionTokens)(result.transaction, sourceOutputs);\n if (tokenValidationResult !== true && fee > 0) {\n throw tokenValidationResult;\n }\n return { transaction: result.transaction, sourceOutputs: sourceOutputs };\n}\nfunction prepareInputs({ inputs, compiler, signingKey, sourceAddress, }) {\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_11__.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_11__.hexToBin)(i.token.commitment),\n }\n : undefined,\n };\n const newInput = signingKey?.length\n ? {\n outpointIndex: utxoIndex,\n outpointTransactionHash: utxoOutpointTransactionHash,\n sequenceNumber: 0,\n unlockingBytecode: {\n compiler,\n data: {\n keys: { privateKeys: { key: signingKey } },\n },\n valueSatoshis: BigInt(utxoTxnValue),\n script: \"unlock\",\n token: libAuthToken,\n },\n }\n : {\n outpointIndex: utxoIndex,\n outpointTransactionHash: utxoOutpointTransactionHash,\n sequenceNumber: 0,\n unlockingBytecode: Uint8Array.from([]),\n };\n preparedInputs.push(newInput);\n const lockingBytecode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_8__.cashAddressToLockingBytecode)(sourceAddress);\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_8__.cashAddressToLockingBytecode)(output.cashaddr);\n if (typeof outputLockingBytecode === \"string\")\n throw new Error(outputLockingBytecode);\n const sendAmount = await (0,_util_amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_13__.amountInSatoshi)(output.value, output.unit);\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_8__.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_11__.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_11__.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 // 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].filter((val) => val.token?.capability === request.capability &&\n val.token?.commitment === request.commitment);\n if (sameCommitmentTokens.length) {\n const input = sameCommitmentTokens[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 if (request.capability === _interface_js__WEBPACK_IMPORTED_MODULE_14__.NFTCapability.minting ||\n request.capability === _interface_js__WEBPACK_IMPORTED_MODULE_14__.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 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_0__.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}\nasync function getFeeAmount({ utxos, sendRequests, privateKey, sourceAddress, relayFeePerByteInSatoshi, slpOutputs, feePaidBy, discardChange, }) {\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: privateKey,\n sourceAddress,\n fee: 0,\n discardChange: discardChange ?? false,\n slpOutputs,\n feePaidBy,\n changeAddress: \"\",\n });\n return 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, sourceAddress, fee = 0, discardChange = false, slpOutputs = [], feePaidBy = _wallet_enum_js__WEBPACK_IMPORTED_MODULE_0__.FeePaidByEnum.change, changeAddress = \"\", }) {\n const { transaction, sourceOutputs } = await buildP2pkhNonHdTransaction({\n inputs,\n outputs,\n signingKey,\n sourceAddress,\n fee,\n discardChange,\n slpOutputs,\n feePaidBy,\n changeAddress,\n });\n return { encodedTransaction: (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_15__.encodeTransaction)(transaction), sourceOutputs };\n}\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/transaction/Wif.ts?");
|
|
1307
|
+
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 */ \"getSuitableUtxos\": () => (/* binding */ getSuitableUtxos),\n/* harmony export */ \"signUnsignedTransaction\": () => (/* binding */ signUnsignedTransaction)\n/* harmony export */ });\n/* unused harmony exports buildP2pkhNonHdTransaction, prepareInputs, prepareOutputs, prepareOpReturnOutput, prepareTokenOutputs */\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/schema/authentication-template.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/compiler/standard/p2pkh.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__ = __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_8__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/address/locking-bytecode.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/transaction/generate-transaction.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__ = __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_11__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/hex.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/message/transaction-encoding.js\");\n/* harmony import */ var _interface_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../interface.js */ \"./src/interface.ts\");\n/* harmony import */ var _allocateFee_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./allocateFee.js */ \"./src/transaction/allocateFee.ts\");\n/* harmony import */ var _constant_js__WEBPACK_IMPORTED_MODULE_7__ = __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_amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../util/amountInSatoshi.js */ \"./src/util/amountInSatoshi.ts\");\n/* harmony import */ var _util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../util/sumSendRequestAmounts.js */ \"./src/util/sumSendRequestAmounts.ts\");\n/* harmony import */ var _util_sumUtxoValue_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../util/sumUtxoValue.js */ \"./src/util/sumUtxoValue.ts\");\n/* harmony import */ var _wallet_enum_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../wallet/enum.js */ \"./src/wallet/enum.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__, _util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_5__, _allocateFee_js__WEBPACK_IMPORTED_MODULE_6__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_8__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_9__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__, _wallet_model_js__WEBPACK_IMPORTED_MODULE_12__, _util_amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_13__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_15__]);\n([_bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__, _util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_5__, _allocateFee_js__WEBPACK_IMPORTED_MODULE_6__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_8__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_9__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__, _wallet_model_js__WEBPACK_IMPORTED_MODULE_12__, _util_amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_13__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_15__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n// Unstable?\n\n\n\n\n\n\n\n\n\n// Build a transaction for a p2pkh transaction for a non HD wallet\nasync function buildP2pkhNonHdTransaction({ inputs, outputs, signingKey, sourceAddress, fee = 0, discardChange = false, slpOutputs = [], feePaidBy = _wallet_enum_js__WEBPACK_IMPORTED_MODULE_0__.FeePaidByEnum.change, changeAddress = \"\", }) {\n if (!signingKey) {\n throw new Error(\"Missing signing key when building transaction\");\n }\n const template = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.importAuthenticationTemplate)(_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.authenticationTemplateP2pkhNonHd);\n if (typeof template === \"string\") {\n throw new Error(\"Transaction template error\");\n }\n const compiler = await (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.authenticationTemplateToCompilerBCH)(template);\n const inputAmount = await (0,_util_sumUtxoValue_js__WEBPACK_IMPORTED_MODULE_4__.sumUtxoValue)(inputs);\n const sendAmount = await (0,_util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_5__.sumSendRequestAmounts)(outputs);\n const changeAmount = BigInt(inputAmount) - BigInt(sendAmount) - BigInt(fee);\n outputs = (0,_allocateFee_js__WEBPACK_IMPORTED_MODULE_6__.allocateFee)(outputs, fee, feePaidBy, changeAmount);\n const lockedOutputs = await prepareOutputs(outputs);\n if (discardChange !== true) {\n if (changeAmount > _constant_js__WEBPACK_IMPORTED_MODULE_7__.DUST_UTXO_THRESHOLD) {\n let changeLockingBytecode;\n if (changeAddress) {\n changeLockingBytecode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_8__.cashAddressToLockingBytecode)(changeAddress);\n }\n else {\n // Get the change locking bytecode\n changeLockingBytecode = compiler.generateBytecode({\n scriptId: \"lock\",\n data: {\n keys: { privateKeys: { key: signingKey } },\n },\n });\n }\n if (typeof changeLockingBytecode === \"string\") {\n throw new 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 sourceAddress,\n });\n const result = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_9__.generateTransaction)({\n inputs: preparedInputs,\n locktime: 0,\n outputs: [...slpOutputs, ...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_10__.verifyTransactionTokens)(result.transaction, sourceOutputs);\n if (tokenValidationResult !== true && fee > 0) {\n throw tokenValidationResult;\n }\n return { transaction: result.transaction, sourceOutputs: sourceOutputs };\n}\nfunction prepareInputs({ inputs, compiler, signingKey, sourceAddress, }) {\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_11__.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_11__.hexToBin)(i.token.commitment),\n }\n : undefined,\n };\n const key = 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_8__.cashAddressToLockingBytecode)(sourceAddress);\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_8__.cashAddressToLockingBytecode)(output.cashaddr);\n if (typeof outputLockingBytecode === \"string\")\n throw new Error(outputLockingBytecode);\n const sendAmount = await (0,_util_amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_13__.amountInSatoshi)(output.value, output.unit);\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_8__.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_11__.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_11__.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 // 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].filter((val) => val.token?.capability === request.capability &&\n val.token?.commitment === request.commitment);\n if (sameCommitmentTokens.length) {\n const input = sameCommitmentTokens[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 if (request.capability === _interface_js__WEBPACK_IMPORTED_MODULE_14__.NFTCapability.minting ||\n request.capability === _interface_js__WEBPACK_IMPORTED_MODULE_14__.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 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_0__.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}\nasync function getFeeAmount({ utxos, sendRequests, privateKey, sourceAddress, relayFeePerByteInSatoshi, slpOutputs, feePaidBy, discardChange, }) {\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: privateKey,\n sourceAddress,\n fee: 0,\n discardChange: discardChange ?? false,\n slpOutputs,\n feePaidBy,\n changeAddress: \"\",\n });\n return 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, sourceAddress, fee = 0, discardChange = false, slpOutputs = [], feePaidBy = _wallet_enum_js__WEBPACK_IMPORTED_MODULE_0__.FeePaidByEnum.change, changeAddress = \"\", buildUnsigned = false, }) {\n const { transaction, sourceOutputs } = await buildP2pkhNonHdTransaction({\n inputs,\n outputs,\n signingKey,\n sourceAddress,\n fee,\n discardChange,\n slpOutputs,\n feePaidBy,\n changeAddress,\n });\n if (buildUnsigned === true) {\n transaction.inputs.forEach((input) => (input.unlockingBytecode = Uint8Array.from([])));\n }\n return { encodedTransaction: (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_15__.encodeTransaction)(transaction), sourceOutputs };\n}\nasync function signUnsignedTransaction(transaction, sourceOutputs, signingKey) {\n if (typeof transaction === \"string\") {\n transaction = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.hexToBin)(transaction);\n }\n const decoded = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_15__.decodeTransaction)(transaction);\n if (typeof decoded === \"string\") {\n throw decoded;\n }\n const template = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.importAuthenticationTemplate)(_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.authenticationTemplateP2pkhNonHd);\n if (typeof template === \"string\") {\n throw new Error(\"Transaction template error\");\n }\n const compiler = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.authenticationTemplateToCompilerBCH)(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_9__.generateTransaction)(transactionTemplate);\n if (!result.success) {\n throw result.errors;\n }\n return (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_15__.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?");
|
|
1308
1308
|
|
|
1309
1309
|
/***/ }),
|
|
1310
1310
|
|
|
@@ -1664,7 +1664,7 @@ eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__
|
|
|
1664
1664
|
\***************************/
|
|
1665
1665
|
/***/ ((module, __webpack_exports__, __webpack_require__) => {
|
|
1666
1666
|
|
|
1667
|
-
eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"RegTestWallet\": () => (/* binding */ RegTestWallet),\n/* harmony export */ \"RegTestWatchWallet\": () => (/* binding */ RegTestWatchWallet),\n/* harmony export */ \"RegTestWifWallet\": () => (/* binding */ RegTestWifWallet),\n/* harmony export */ \"TestNetWallet\": () => (/* binding */ TestNetWallet),\n/* harmony export */ \"TestNetWatchWallet\": () => (/* binding */ TestNetWatchWallet),\n/* harmony export */ \"TestNetWifWallet\": () => (/* binding */ TestNetWifWallet),\n/* harmony export */ \"Wallet\": () => (/* binding */ Wallet),\n/* harmony export */ \"WatchWallet\": () => (/* binding */ WatchWallet),\n/* harmony export */ \"WifWallet\": () => (/* binding */ WifWallet)\n/* harmony export */ });\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/key/hd-key.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_33__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/crypto/default-crypto-instances.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/hex.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/key/key-utils.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/key/wallet-import-format.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_35__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/address/cash-address.js\");\n/* harmony import */ var bip39__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! bip39 */ \"../../node_modules/bip39/src/index.js\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../enum.js */ \"./src/enum.ts\");\n/* harmony import */ var _interface_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../interface.js */ \"./src/interface.ts\");\n/* harmony import */ var _Base_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Base.js */ \"./src/wallet/Base.ts\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./enum.js */ \"./src/wallet/enum.ts\");\n/* harmony import */ var _model_js__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ./model.js */ \"./src/wallet/model.ts\");\n/* harmony import */ var _transaction_Wif_js__WEBPACK_IMPORTED_MODULE_29__ = __webpack_require__(/*! ../transaction/Wif.js */ \"./src/transaction/Wif.ts\");\n/* harmony import */ var _util_asSendRequestObject_js__WEBPACK_IMPORTED_MODULE_30__ = __webpack_require__(/*! ../util/asSendRequestObject.js */ \"./src/util/asSendRequestObject.ts\");\n/* harmony import */ var _util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(/*! ../util/balanceObjectFromSatoshi.js */ \"./src/util/balanceObjectFromSatoshi.ts\");\n/* harmony import */ var _util_checkWifNetwork_js__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ../util/checkWifNetwork.js */ \"./src/util/checkWifNetwork.ts\");\n/* harmony import */ var _util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ../util/deriveCashaddr.js */ \"./src/util/deriveCashaddr.ts\");\n/* harmony import */ var _util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../util/derivePublicKeyHash.js */ \"./src/util/derivePublicKeyHash.ts\");\n/* harmony import */ var _util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../util/checkForEmptySeed.js */ \"./src/util/checkForEmptySeed.ts\");\n/* harmony import */ var _util_sanitizeUnit_js__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(/*! ../util/sanitizeUnit.js */ \"./src/util/sanitizeUnit.ts\");\n/* harmony import */ var _util_sumUtxoValue_js__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(/*! ../util/sumUtxoValue.js */ \"./src/util/sumUtxoValue.ts\");\n/* harmony import */ var _util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_31__ = __webpack_require__(/*! ../util/sumSendRequestAmounts.js */ \"./src/util/sumSendRequestAmounts.ts\");\n/* harmony import */ var _network_getRelayFeeCache_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../network/getRelayFeeCache.js */ \"./src/network/getRelayFeeCache.ts\");\n/* harmony import */ var _Slp_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./Slp.js */ \"./src/wallet/Slp.ts\");\n/* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! axios */ \"../../node_modules/axios/index.js\");\n/* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(axios__WEBPACK_IMPORTED_MODULE_2__);\n/* harmony import */ var _util_bchaddr_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../util/bchaddr.js */ \"../../node_modules/bchaddrjs-slp/src/bchaddr.js\");\n/* harmony import */ var _util_bchaddr_js__WEBPACK_IMPORTED_MODULE_13___default = /*#__PURE__*/__webpack_require__.n(_util_bchaddr_js__WEBPACK_IMPORTED_MODULE_13__);\n/* harmony import */ var _Util_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./Util.js */ \"./src/wallet/Util.ts\");\n/* harmony import */ var _network_index_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../network/index.js */ \"./src/network/default.ts\");\n/* harmony import */ var _util_randomBytes_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../util/randomBytes.js */ \"./src/util/randomBytes.ts\");\n/* harmony import */ var _message_index_js__WEBPACK_IMPORTED_MODULE_34__ = __webpack_require__(/*! ../message/index.js */ \"./src/message/signed.ts\");\n/* harmony import */ var _util_amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(/*! ../util/amountInSatoshi.js */ \"./src/util/amountInSatoshi.ts\");\n/* harmony import */ var _util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ../util/getXPubKey.js */ \"./src/util/getXPubKey.ts\");\n/* harmony import */ var _constant_js__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ../constant.js */ \"./src/constant.ts\");\n/* harmony import */ var _history_electrumTransformer_js__WEBPACK_IMPORTED_MODULE_32__ = __webpack_require__(/*! ../history/electrumTransformer.js */ \"./src/history/electrumTransformer.ts\");\n/* harmony import */ var _Bcmr_js__WEBPACK_IMPORTED_MODULE_28__ = __webpack_require__(/*! ./Bcmr.js */ \"./src/wallet/Bcmr.ts\");\n/* harmony import */ var _qr_Qr_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../qr/Qr.js */ \"./src/qr/Qr.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_Base_js__WEBPACK_IMPORTED_MODULE_3__, _enum_js__WEBPACK_IMPORTED_MODULE_4__, _Slp_js__WEBPACK_IMPORTED_MODULE_6__, _Util_js__WEBPACK_IMPORTED_MODULE_7__, _network_index_js__WEBPACK_IMPORTED_MODULE_9__, _qr_Qr_js__WEBPACK_IMPORTED_MODULE_10__, _util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_12__, _util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_16__, _util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_17__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_18__, _model_js__WEBPACK_IMPORTED_MODULE_20__, _util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_21__, _util_checkWifNetwork_js__WEBPACK_IMPORTED_MODULE_22__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_23__, _util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_25__, _util_amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_27__, _Bcmr_js__WEBPACK_IMPORTED_MODULE_28__, _transaction_Wif_js__WEBPACK_IMPORTED_MODULE_29__, _util_asSendRequestObject_js__WEBPACK_IMPORTED_MODULE_30__, _util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_31__, _history_electrumTransformer_js__WEBPACK_IMPORTED_MODULE_32__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_33__, _message_index_js__WEBPACK_IMPORTED_MODULE_34__]);\n([_Base_js__WEBPACK_IMPORTED_MODULE_3__, _enum_js__WEBPACK_IMPORTED_MODULE_4__, _Slp_js__WEBPACK_IMPORTED_MODULE_6__, _Util_js__WEBPACK_IMPORTED_MODULE_7__, _network_index_js__WEBPACK_IMPORTED_MODULE_9__, _qr_Qr_js__WEBPACK_IMPORTED_MODULE_10__, _util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_12__, _util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_16__, _util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_17__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_18__, _model_js__WEBPACK_IMPORTED_MODULE_20__, _util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_21__, _util_checkWifNetwork_js__WEBPACK_IMPORTED_MODULE_22__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_23__, _util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_25__, _util_amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_27__, _Bcmr_js__WEBPACK_IMPORTED_MODULE_28__, _transaction_Wif_js__WEBPACK_IMPORTED_MODULE_29__, _util_asSendRequestObject_js__WEBPACK_IMPORTED_MODULE_30__, _util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_31__, _history_electrumTransformer_js__WEBPACK_IMPORTED_MODULE_32__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_33__, _message_index_js__WEBPACK_IMPORTED_MODULE_34__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n//#region Imports\n// Stable\n\n// Unstable?\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n//#endregion Imports\n/**\n * Class to manage a bitcoin cash wallet.\n */\nclass Wallet extends _Base_js__WEBPACK_IMPORTED_MODULE_3__.BaseWallet {\n //#endregion\n //#region Constructors and Statics\n constructor(name = \"\", network = _enum_js__WEBPACK_IMPORTED_MODULE_4__.NetworkType.Mainnet, walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Seed) {\n super(name, network, walletType);\n this.derivationPath = \"m/44'/0'/0'/0/0\";\n this.parentDerivationPath = \"m/44'/0'/0'\";\n this._slpAware = false; // a flag which activates utxo checking against an external slp indexer\n this._slpSemiAware = false; // a flag which requires an utxo to have more than 546 sats to be spendable and counted in the balance\n this.fromId = async (walletId) => {\n let [walletType, networkGiven, arg1] = walletId.split(\":\");\n if (this.network != networkGiven) {\n throw Error(`Network prefix ${networkGiven} to a ${this.network} wallet`);\n }\n // \"wif:regtest:cNfsPtqN2bMRS7vH5qd8tR8GMvgXyL5BjnGAKgZ8DYEiCrCCQcP6\"\n if (walletType === \"wif\") {\n return this.fromWIF(arg1);\n }\n return super.fromId(walletId);\n };\n this.networkPrefix = _enum_js__WEBPACK_IMPORTED_MODULE_4__.prefixFromNetworkMap[this.network];\n }\n //#region Accessors\n // interface to slp functions. see Slp.ts\n get slp() {\n if (!this._slp) {\n this._slp = new _Slp_js__WEBPACK_IMPORTED_MODULE_6__.Slp(this);\n this._slpAware = true;\n }\n return this._slp;\n }\n // interface to slp functions. see Slp.ts\n static get slp() {\n return _Slp_js__WEBPACK_IMPORTED_MODULE_6__.Slp;\n }\n // interface to util functions. see Util.ts\n get util() {\n if (!this._util) {\n this._util = new _Util_js__WEBPACK_IMPORTED_MODULE_7__.Util(this);\n }\n return this._util;\n }\n // interface to util util. see Util.Util\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_7__.Util;\n }\n slpAware(value = true) {\n this._slpAware = value;\n return this;\n }\n slpSemiAware(value = true) {\n this._slpSemiAware = value;\n return this;\n }\n getNetworkProvider(network = _interface_js__WEBPACK_IMPORTED_MODULE_8__.Network.MAINNET) {\n return (0,_network_index_js__WEBPACK_IMPORTED_MODULE_9__.getNetworkProvider)(network);\n }\n /**\n * getTokenDepositAddress - get a cashtoken aware wallet deposit address\n *\n * @returns The cashtoken aware deposit address as a string\n */\n getTokenDepositAddress() {\n return this.tokenaddr;\n }\n /**\n * getDepositQr - get an address qrcode, encoded for display on the web\n *\n * @returns The qrcode for the token aware address\n */\n getTokenDepositQr() {\n return (0,_qr_Qr_js__WEBPACK_IMPORTED_MODULE_10__.qrAddress)(this.getTokenDepositAddress());\n }\n /**\n * explorerUrl Web url to a transaction on a block explorer\n *\n * @param txId transaction Id\n * @returns Url string\n */\n explorerUrl(txId) {\n const explorerUrlMap = {\n mainnet: \"https://blockchair.com/bitcoin-cash/transaction/\",\n testnet: \"https://www.blockchain.com/bch-testnet/tx/\",\n regtest: \"\",\n };\n return explorerUrlMap[this.network] + txId;\n }\n // Return wallet info\n getInfo() {\n return {\n cashaddr: this.cashaddr,\n tokenaddr: this.tokenaddr,\n isTestnet: this.isTestnet,\n name: this.name,\n network: this.network,\n seed: this.mnemonic ? this.getSeed().seed : undefined,\n derivationPath: this.mnemonic ? this.getSeed().derivationPath : undefined,\n parentDerivationPath: this.mnemonic\n ? this.getSeed().parentDerivationPath\n : undefined,\n parentXPubKey: this.parentXPubKey ? this.parentXPubKey : undefined,\n publicKey: this.publicKey ? (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.binToHex)(this.publicKey) : undefined,\n publicKeyHash: (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.binToHex)(this.publicKeyHash),\n privateKey: this.privateKey ? (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.binToHex)(this.privateKey) : undefined,\n privateKeyWif: this.privateKeyWif,\n walletId: this.toString(),\n walletDbEntry: this.toDbString(),\n };\n }\n // returns the public key hash for an address\n getPublicKey(hex = false) {\n if (this.publicKey) {\n return hex ? (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.binToHex)(this.publicKey) : this.publicKey;\n }\n else {\n throw Error(\"The public key for this wallet is not known, perhaps the wallet was created to watch the *hash* of a public key? i.e. a cashaddress.\");\n }\n }\n // returns the public key hash for an address\n getPublicKeyCompressed(hex = false) {\n if (this.publicKeyCompressed) {\n return hex\n ? (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.binToHex)(this.publicKeyCompressed)\n : this.publicKeyCompressed;\n }\n else {\n throw Error(\"The compressed public key for this wallet is not known, perhaps the wallet was created to watch the *hash* of a public key? i.e. a cashaddress.\");\n }\n }\n // returns the public key hash for an address\n getPublicKeyHash(hex = false) {\n if (this.publicKeyHash) {\n return hex ? (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.binToHex)(this.publicKeyHash) : this.publicKeyHash;\n }\n else {\n throw Error(\"The public key hash for this wallet is not known. If this wallet was created from the constructor directly, calling the deriveInfo() function may help. \");\n }\n }\n /**\n * fromWIF - create a wallet using the private key supplied in `Wallet Import Format`\n *\n * @param wif WIF encoded private key string\n *\n * @returns instantiated wallet\n */\n static async fromWIF(wif) {\n return new this().fromWIF(wif);\n }\n /**\n * fromCashaddr - create a watch-only wallet in the network derived from the address\n *\n * such kind of wallet does not have a private key and is unable to spend any funds\n * however it still allows to use many utility functions such as getting and watching balance, etc.\n *\n * @param address cashaddress of a wallet\n *\n * @returns instantiated wallet\n */\n static async fromCashaddr(address) {\n const prefix = (0,_util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_12__.derivePrefix)(address);\n const networkType = _enum_js__WEBPACK_IMPORTED_MODULE_4__.networkPrefixMap[prefix];\n return new this(\"\", networkType, _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Watch).watchOnly(address);\n }\n /**\n * fromTokenaddr - create a watch-only wallet in the network derived from the address\n *\n * such kind of wallet does not have a private key and is unable to spend any funds\n * however it still allows to use many utility functions such as getting and watching balance, etc.\n *\n * @param address token aware cashaddress of a wallet\n *\n * @returns instantiated wallet\n */\n static async fromTokenaddr(address) {\n const prefix = (0,_util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_12__.derivePrefix)(address);\n const networkType = _enum_js__WEBPACK_IMPORTED_MODULE_4__.networkPrefixMap[prefix];\n return new this(\"\", networkType, _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Watch).watchOnly(address);\n }\n /**\n * fromSlpaddr - create an SLP aware watch-only wallet in the network derived from the address\n *\n * such kind of wallet does not have a private key and is unable to spend any funds\n * however it still allows to use many utility functions such as getting and watching balance, etc.\n *\n * @param address slpaddress of a wallet\n *\n * @returns instantiated wallet\n */\n static async fromSlpaddr(address) {\n return this.fromCashaddr((0,_util_bchaddr_js__WEBPACK_IMPORTED_MODULE_13__.toCashAddress)(address));\n }\n //#endregion Constructors and Statics\n //#region Protected implementations\n async generate() {\n if (this.walletType === _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Wif) {\n return await this._generateWif();\n }\n else if (this.walletType === _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Watch) {\n return this;\n }\n else if (this.walletType === _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Hd) {\n throw Error(\"Not implemented\");\n }\n else if (this.walletType === _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Seed) {\n return await this._generateMnemonic();\n }\n else {\n console.log(this.walletType);\n throw Error(`Could not determine walletType: ${this.walletType}`);\n }\n }\n async _generateWif() {\n if (!this.privateKey) {\n this.privateKey = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_14__.generatePrivateKey)(() => (0,_util_randomBytes_js__WEBPACK_IMPORTED_MODULE_15__.generateRandomBytes)(32));\n }\n return this.deriveInfo();\n }\n async _generateMnemonic() {\n this.mnemonic = (0,bip39__WEBPACK_IMPORTED_MODULE_0__.generateMnemonic)();\n if (this.mnemonic.length == 0)\n throw Error(\"refusing to create wallet from empty mnemonic\");\n let seed = (0,bip39__WEBPACK_IMPORTED_MODULE_0__.mnemonicToSeedSync)(this.mnemonic);\n (0,_util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_16__.checkForEmptySeed)(seed);\n let network = this.isTestnet ? \"testnet\" : \"mainnet\";\n this.parentXPubKey = await (0,_util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_17__.getXPubKey)(seed, this.parentDerivationPath, network);\n let hdNode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_18__.deriveHdPrivateNodeFromSeed)(seed);\n if (!hdNode.valid) {\n throw Error(\"Invalid private key derived from mnemonic seed\");\n }\n let zerothChild = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_18__.deriveHdPath)(hdNode, this.derivationPath);\n if (typeof zerothChild === \"string\") {\n throw Error(zerothChild);\n }\n this.privateKey = zerothChild.privateKey;\n this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Seed;\n return await this.deriveInfo();\n }\n async getXPubKeys(paths) {\n if (this.mnemonic) {\n if (paths) {\n let xPubKeys = await this.deriveHdPaths(paths);\n return [xPubKeys];\n }\n else {\n return await this.deriveHdPaths(_constant_js__WEBPACK_IMPORTED_MODULE_19__.DERIVATION_PATHS);\n }\n }\n else {\n throw Error(\"xpubkeys can only be derived from seed type wallets.\");\n }\n }\n // Initialize wallet from a mnemonic phrase\n async fromSeed(mnemonic, derivationPath) {\n this.mnemonic = mnemonic.trim().toLowerCase();\n if (this.mnemonic.length == 0)\n throw Error(\"refusing to create wallet from empty mnemonic\");\n let seed = (0,bip39__WEBPACK_IMPORTED_MODULE_0__.mnemonicToSeedSync)(this.mnemonic);\n (0,_util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_16__.checkForEmptySeed)(seed);\n let hdNode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_18__.deriveHdPrivateNodeFromSeed)(seed);\n if (!hdNode.valid) {\n throw Error(\"Invalid private key derived from mnemonic seed\");\n }\n if (derivationPath) {\n this.derivationPath = derivationPath;\n // If the derivation path is for the first account child, set the parent derivation path\n let path = derivationPath.split(\"/\");\n if (path.slice(-2).join(\"/\") == \"0/0\") {\n this.parentDerivationPath = path.slice(0, -2).join(\"/\");\n }\n }\n let zerothChild = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_18__.deriveHdPath)(hdNode, this.derivationPath);\n if (typeof zerothChild === \"string\") {\n throw Error(zerothChild);\n }\n this.privateKey = zerothChild.privateKey;\n let network = this.isTestnet ? \"testnet\" : \"mainnet\";\n this.parentXPubKey = await (0,_util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_17__.getXPubKey)(seed, this.parentDerivationPath, network);\n this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Seed;\n await this.deriveInfo();\n return this;\n }\n // Get common xpub paths from zerothChild privateKey\n async deriveHdPaths(hdPaths) {\n if (!this.mnemonic)\n throw Error(\"refusing to create wallet from empty mnemonic\");\n let seed = (0,bip39__WEBPACK_IMPORTED_MODULE_0__.mnemonicToSeedSync)(this.mnemonic);\n (0,_util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_16__.checkForEmptySeed)(seed);\n let hdNode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_18__.deriveHdPrivateNodeFromSeed)(seed);\n if (!hdNode.valid) {\n throw Error(\"Invalid private key derived from mnemonic seed\");\n }\n let result = [];\n for (const path of hdPaths) {\n if (path === \"m\") {\n throw Error(\"Storing or sharing of parent public key may lead to loss of funds. Storing or sharing *root* parent public keys is strongly discouraged, although all parent keys have risk. See: https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#implications\");\n }\n let childNode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_18__.deriveHdPath)(hdNode, path);\n if (typeof childNode === \"string\") {\n throw Error(childNode);\n }\n let node = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_18__.deriveHdPublicNode)(childNode);\n if (typeof node === \"string\") {\n throw Error(node);\n }\n let xPubKey = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_18__.encodeHdPublicKey)({\n network: this.network,\n node: node,\n });\n let key = new _model_js__WEBPACK_IMPORTED_MODULE_20__.XPubKey({\n path: path,\n xPubKey: xPubKey,\n });\n result.push(await key.ready());\n }\n return await Promise.all(result).then((result) => {\n return result;\n });\n }\n // Initialize a watch only wallet from a cash addr\n async watchOnly(address) {\n this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Watch;\n let addressComponents = address.split(\":\");\n let addressPrefix, addressBase;\n if (addressComponents.length === 1) {\n addressBase = addressComponents.shift();\n addressPrefix = (0,_util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_12__.derivePrefix)(addressBase);\n }\n else {\n addressPrefix = addressComponents.shift();\n addressBase = addressComponents.shift();\n if (addressPrefix in _enum_js__WEBPACK_IMPORTED_MODULE_4__.networkPrefixMap) {\n if (_enum_js__WEBPACK_IMPORTED_MODULE_4__.networkPrefixMap[addressPrefix] != this.network) {\n throw Error(`a ${addressPrefix} address cannot be watched from a ${this.network} Wallet`);\n }\n }\n }\n this.cashaddr = `${addressPrefix}:${addressBase}`;\n this.address = this.cashaddr;\n this.publicKeyHash = (0,_util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_12__.derivePublicKeyHash)(this.cashaddr);\n this.tokenaddr = (0,_util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_21__.deriveTokenaddr)(this.publicKeyHash, this.networkPrefix);\n return this;\n }\n // Initialize wallet from Wallet Import Format\n async fromWIF(secret) {\n (0,_util_checkWifNetwork_js__WEBPACK_IMPORTED_MODULE_22__.checkWifNetwork)(secret, this.network);\n let wifResult = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_23__.decodePrivateKeyWif)(secret);\n if (typeof wifResult === \"string\") {\n throw Error(wifResult);\n }\n let resultData = wifResult;\n this.privateKey = resultData.privateKey;\n this.privateKeyWif = secret;\n this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Wif;\n await this.deriveInfo();\n return this;\n }\n async newRandom(name, dbName) {\n dbName = dbName ? dbName : this.networkPrefix;\n return super.newRandom(name, dbName);\n }\n async named(name, dbName, forceNew = false) {\n dbName = dbName ? dbName : this.networkPrefix;\n return super.named(name, dbName, forceNew);\n }\n async replaceNamed(name, walletId, dbName) {\n dbName = dbName ? dbName : this.networkPrefix;\n return super.replaceNamed(name, walletId, dbName);\n }\n async namedExists(name, dbName) {\n dbName = dbName ? dbName : this.networkPrefix;\n return super.namedExists(name, dbName);\n }\n //#endregion Protected Implementations\n //#region Serialization\n // Returns the serialized wallet as a string\n // If storing in a database, set asNamed to false to store secrets\n // In all other cases, the a named wallet is deserialized from the database\n // by the name key\n toString() {\n const result = super.toString();\n if (result)\n return result;\n if (this.walletType === _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Wif) {\n return `${this.walletType}:${this.network}:${this.privateKeyWif}`;\n }\n throw Error(\"toString unsupported wallet type\");\n }\n //\n toDbString() {\n const result = super.toDbString();\n if (result)\n return result;\n if (this.walletType === _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Wif) {\n return `${this.walletType}:${this.network}:${this.privateKeyWif}`;\n }\n throw Error(\"toDbString unsupported wallet type\");\n }\n //#endregion Serialization\n //#region Funds\n //\n async getAddressUtxos(address) {\n if (!address) {\n address = this.cashaddr;\n }\n if (this._slpAware) {\n const [bchUtxos, slpOutpoints] = await Promise.all([\n this.provider.getUtxos(address),\n this.slp.getSlpOutpoints(),\n ]);\n return bchUtxos.filter((bchutxo) => slpOutpoints.findIndex((slpOutpoint) => `${bchutxo.txid}:${bchutxo.vout}` === slpOutpoint) === -1);\n }\n else if (this._slpSemiAware) {\n const bchUtxos = await this.provider.getUtxos(address);\n return bchUtxos.filter((bchutxo) => bchutxo.satoshis > _constant_js__WEBPACK_IMPORTED_MODULE_19__.DUST_UTXO_THRESHOLD);\n }\n else {\n return await this.provider.getUtxos(address);\n }\n }\n /**\n * utxos Get unspent outputs for the wallet\n *\n */\n async getUtxos() {\n if (!this.cashaddr) {\n throw Error(\"Attempted to get utxos without an address\");\n }\n return await this.getAddressUtxos(this.cashaddr);\n }\n // gets wallet balance in sats, bch and usd\n async getBalance(rawUnit, usdPriceCache = true) {\n if (rawUnit) {\n const unit = (0,_util_sanitizeUnit_js__WEBPACK_IMPORTED_MODULE_24__.sanitizeUnit)(rawUnit);\n return await (0,_util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_25__.balanceFromSatoshi)(await this.getBalanceFromProvider(), unit, usdPriceCache);\n }\n else {\n return await (0,_util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_25__.balanceResponseFromSatoshi)(await this.getBalanceFromProvider(), usdPriceCache);\n }\n }\n // Gets balance by summing value in all utxos in stats\n async getBalanceFromUtxos() {\n const utxos = (await this.getAddressUtxos(this.cashaddr)).filter((val) => val.token === undefined);\n return (0,_util_sumUtxoValue_js__WEBPACK_IMPORTED_MODULE_26__.sumUtxoValue)(utxos);\n }\n // Gets balance from fulcrum\n async getBalanceFromProvider() {\n // Fulcrum reports balance of all utxos, including tokens, which is undesirable\n // // TODO not sure why getting the balance from a provider doesn't work\n // if (this._slpAware || this._slpSemiAware) {\n // return await this.getBalanceFromUtxos();\n // } else {\n // return await this.provider!.getBalance(this.cashaddr!);\n // }\n // FIXME\n return this.getBalanceFromUtxos();\n }\n // watching for any transaction hash of this wallet\n watchAddress(callback) {\n return this.provider.watchAddress(this.getDepositAddress(), callback);\n }\n // watching for any transaction of this wallet\n watchAddressTransactions(callback) {\n return this.provider.watchAddressTransactions(this.getDepositAddress(), callback);\n }\n // watching for cashtoken transaction of this wallet\n watchAddressTokenTransactions(callback) {\n return this.provider.watchAddressTokenTransactions(this.getDepositAddress(), callback);\n }\n // sets up a callback to be called upon wallet's balance change\n // can be cancelled by calling the function returned from this one\n watchBalance(callback) {\n return this.provider.watchAddressStatus(this.getDepositAddress(), async (_status) => {\n const balance = (await this.getBalance());\n callback(balance);\n });\n }\n // sets up a callback to be called upon wallet's BCH or USD balance change\n // if BCH balance does not change, the callback will be triggered every\n // @param `usdPriceRefreshInterval` milliseconds by polling for new BCH USD price\n // Since we want to be most sensitive to usd value change, we do not use the cached exchange rates\n // can be cancelled by calling the function returned from this one\n watchBalanceUsd(callback, usdPriceRefreshInterval = 30000) {\n let usdPrice = -1;\n const _callback = async () => {\n const balance = (await this.getBalance(undefined, false));\n if (usdPrice !== balance.usd) {\n usdPrice = balance.usd;\n callback(balance);\n }\n };\n const watchCancel = this.provider.watchAddressStatus(this.getDepositAddress(), _callback);\n const interval = setInterval(_callback, usdPriceRefreshInterval);\n return async () => {\n await watchCancel();\n clearInterval(interval);\n };\n }\n // waits for address balance to be greater than or equal to the target value\n // this call halts the execution\n async waitForBalance(value, rawUnit = _enum_js__WEBPACK_IMPORTED_MODULE_4__.UnitEnum.BCH) {\n return new Promise(async (resolve) => {\n const watchCancel = this.watchBalance(async (balance) => {\n const satoshiBalance = await (0,_util_amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_27__.amountInSatoshi)(value, rawUnit);\n if (balance.sat >= satoshiBalance) {\n await watchCancel();\n resolve(balance);\n }\n });\n });\n }\n // sets up a callback to be called upon wallet's token balance change\n // can be cancelled by calling the function returned from this one\n watchTokenBalance(tokenId, callback) {\n let previous = undefined;\n return this.provider.watchAddressStatus(this.getDepositAddress(), async (_status) => {\n const balance = await this.getTokenBalance(tokenId);\n if (previous != balance) {\n callback(balance);\n }\n previous = balance;\n });\n }\n // waits for address token balance to be greater than or equal to the target amount\n // this call halts the execution\n async waitForTokenBalance(tokenId, amount) {\n return new Promise(async (resolve) => {\n const watchCancel = this.watchTokenBalance(tokenId, async (balance) => {\n if (balance >= amount) {\n await watchCancel();\n resolve(balance);\n }\n });\n });\n }\n async getTokenInfo(tokenId) {\n return _Bcmr_js__WEBPACK_IMPORTED_MODULE_28__.BCMR.getTokenInfo(tokenId);\n }\n async _getMaxAmountToSend(params = {\n outputCount: 1,\n options: {},\n }) {\n if (!this.privateKey && params.options?.buildUnsigned !== true) {\n throw Error(\"Couldn't get network or private key for wallet.\");\n }\n if (!this.cashaddr) {\n throw Error(\"attempted to send without a cashaddr\");\n }\n if (params.options && params.options.slpAware) {\n this._slpAware = true;\n }\n if (params.options && params.options.slpSemiAware) {\n this._slpSemiAware = true;\n }\n let feePaidBy;\n if (params.options && params.options.feePaidBy) {\n feePaidBy = params.options.feePaidBy;\n }\n else {\n feePaidBy = _enum_js__WEBPACK_IMPORTED_MODULE_5__.FeePaidByEnum.change;\n }\n // get inputs\n let utxos;\n if (params.options && params.options.utxoIds) {\n utxos = params.options.utxoIds.map((utxoId) => typeof utxoId === \"string\" ? (0,_model_js__WEBPACK_IMPORTED_MODULE_20__.fromUtxoId)(utxoId) : utxoId);\n }\n else {\n utxos = (await this.getAddressUtxos(this.cashaddr)).filter((utxo) => !utxo.token);\n }\n // Get current height to assure recently mined coins are not spent.\n const bestHeight = await this.provider.getBlockHeight();\n // simulate outputs using the sender's address\n const sendRequest = new _model_js__WEBPACK_IMPORTED_MODULE_20__.SendRequest({\n cashaddr: this.cashaddr,\n value: 100,\n unit: \"sat\",\n });\n const sendRequests = Array(params.outputCount)\n .fill(0)\n .map(() => sendRequest);\n const fundingUtxos = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_29__.getSuitableUtxos)(utxos, undefined, bestHeight, feePaidBy, sendRequests);\n const relayFeePerByteInSatoshi = await (0,_network_getRelayFeeCache_js__WEBPACK_IMPORTED_MODULE_1__.getRelayFeeCache)(this.provider);\n const fee = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_29__.getFeeAmount)({\n utxos: fundingUtxos,\n sendRequests: sendRequests,\n privateKey: this.privateKey ?? Uint8Array.from([]),\n sourceAddress: this.cashaddr,\n relayFeePerByteInSatoshi: relayFeePerByteInSatoshi,\n slpOutputs: [],\n feePaidBy: feePaidBy,\n });\n const spendableAmount = (0,_util_sumUtxoValue_js__WEBPACK_IMPORTED_MODULE_26__.sumUtxoValue)(fundingUtxos);\n let result = spendableAmount - fee;\n if (result < 0) {\n result = 0;\n }\n return { value: result, utxos: fundingUtxos };\n }\n async getMaxAmountToSend(params = {\n outputCount: 1,\n options: {},\n }) {\n const { value: result } = await this._getMaxAmountToSend(params);\n return await (0,_util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_25__.balanceResponseFromSatoshi)(result);\n }\n /**\n * send Send some amount to an address\n * this function processes the send requests, encodes the transaction, sends it to the network\n * @returns (depending on the options parameter) the transaction id, new address balance and a link to the transaction on the blockchain explorer\n *\n * This is a first class function with REST analog, maintainers should strive to keep backward-compatibility\n *\n */\n async send(requests, options) {\n const { encodedTransaction, tokenIds, sourceOutputs } = await this.encodeTransaction(requests, undefined, options);\n const resp = new _model_js__WEBPACK_IMPORTED_MODULE_20__.SendResponse({});\n resp.tokenIds = tokenIds;\n if (options?.buildUnsigned !== true) {\n const txId = await this.submitTransaction(encodedTransaction, options?.awaitTransactionPropagation === undefined ||\n options?.awaitTransactionPropagation === true);\n resp.txId = txId;\n resp.explorerUrl = this.explorerUrl(resp.txId);\n if (options?.queryBalance === undefined ||\n options?.queryBalance === true) {\n resp.balance = (await this.getBalance());\n }\n }\n else {\n resp.unsignedTransaction = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.binToHex)(encodedTransaction);\n resp.sourceOutputs = sourceOutputs;\n }\n return resp;\n }\n /**\n * sendMax Send all available funds to a destination cash address\n *\n * @param {string} cashaddr destination cash address\n * @param {SendRequestOptionsI} options Options of the send requests\n *\n * @returns (depending on the options parameter) the transaction id, new address balance and a link to the transaction on the blockchain explorer\n */\n async sendMax(cashaddr, options) {\n return await this.sendMaxRaw(cashaddr, options);\n }\n /**\n * sendMaxRaw (internal) Send all available funds to a destination cash address\n *\n * @param {string} cashaddr destination cash address\n * @param {SendRequestOptionsI} options Options of the send requests\n *\n * @returns the transaction id sent to the network\n */\n async sendMaxRaw(cashaddr, options) {\n const { value: maxSpendableAmount, utxos } = await this._getMaxAmountToSend({\n outputCount: 1,\n options: options,\n });\n if (!options) {\n options = {};\n }\n options.utxoIds = utxos;\n const sendRequest = new _model_js__WEBPACK_IMPORTED_MODULE_20__.SendRequest({\n cashaddr: cashaddr,\n value: maxSpendableAmount,\n unit: \"sat\",\n });\n const { encodedTransaction, tokenIds, sourceOutputs } = await this.encodeTransaction([sendRequest], true, options);\n const resp = new _model_js__WEBPACK_IMPORTED_MODULE_20__.SendResponse({});\n resp.tokenIds = tokenIds;\n if (options?.buildUnsigned !== true) {\n const txId = await this.submitTransaction(encodedTransaction, options?.awaitTransactionPropagation === undefined ||\n options?.awaitTransactionPropagation === true);\n resp.txId = txId;\n resp.explorerUrl = this.explorerUrl(resp.txId);\n if (options?.queryBalance === undefined ||\n options?.queryBalance === true) {\n resp.balance = (await this.getBalance());\n }\n }\n else {\n resp.unsignedTransaction = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.binToHex)(encodedTransaction);\n resp.sourceOutputs = sourceOutputs;\n }\n return resp;\n }\n /**\n * encodeTransaction Encode and sign a transaction given a list of sendRequests, options and estimate fees.\n * @param {SendRequest[]} sendRequests SendRequests\n * @param {boolean} discardChange=false\n * @param {SendRequestOptionsI} options Options of the send requests\n */\n async encodeTransaction(requests, discardChange = false, options) {\n let sendRequests = (0,_util_asSendRequestObject_js__WEBPACK_IMPORTED_MODULE_30__.asSendRequestObject)(requests);\n if (!this.privateKey && options?.buildUnsigned !== true) {\n throw new Error(`Wallet ${this.name} is missing either a network or private key`);\n }\n if (!this.cashaddr) {\n throw Error(\"attempted to send without a cashaddr\");\n }\n if (options && options.slpAware) {\n this._slpAware = true;\n }\n if (options && options.slpSemiAware) {\n this._slpSemiAware = true;\n }\n let feePaidBy;\n if (options && options.feePaidBy) {\n feePaidBy = options.feePaidBy;\n }\n else {\n feePaidBy = _enum_js__WEBPACK_IMPORTED_MODULE_5__.FeePaidByEnum.change;\n }\n let changeAddress;\n if (options && options.changeAddress) {\n changeAddress = options.changeAddress;\n }\n else {\n changeAddress = \"\";\n }\n let checkTokenQuantities = true;\n if (options && options.checkTokenQuantities === false) {\n checkTokenQuantities = false;\n }\n // get inputs from options or query all inputs\n let utxos;\n if (options && options.utxoIds) {\n utxos = options.utxoIds.map((utxoId) => typeof utxoId === \"string\" ? (0,_model_js__WEBPACK_IMPORTED_MODULE_20__.fromUtxoId)(utxoId) : utxoId);\n }\n else {\n utxos = await this.getAddressUtxos(this.cashaddr);\n }\n // filter out token utxos if there are no token requests\n if (checkTokenQuantities &&\n !sendRequests.some((val) => val instanceof _model_js__WEBPACK_IMPORTED_MODULE_20__.TokenSendRequest)) {\n utxos = utxos.filter((val) => !val.token);\n }\n // let tokenOp: \"send\" | \"genesis\" | \"mint\" | \"burn\" | undefined = undefined;\n // if (options?.ensureUtxos?.every(val => !val.token) && sendRequests.some(val => (val as TokenSendRequest).tokenId)) {\n // tokenOp = \"genesis\";\n // } else if (options?.ensureUtxos?.length === 1 && options?.ensureUtxos?.[0].token?.capability === NFTCapability.minting && ) {\n // }\n const addTokenChangeOutputs = (inputs, outputs) => {\n // allow for implicit token burn if the total amount sent is less than user had\n // allow for token genesis, creating more tokens than we had before (0)\n if (!checkTokenQuantities) {\n return;\n }\n const allTokenInputs = inputs.filter((val) => val.token);\n const allTokenOutputs = outputs.filter((val) => val instanceof _model_js__WEBPACK_IMPORTED_MODULE_20__.TokenSendRequest);\n const tokenIds = allTokenOutputs\n .map((val) => val.tokenId)\n .filter((val, idx, arr) => arr.indexOf(val) === idx);\n for (let tokenId of tokenIds) {\n const tokenInputs = allTokenInputs.filter((val) => val.token?.tokenId === tokenId);\n const inputAmountSum = tokenInputs.reduce((prev, cur) => prev + cur.token.amount, 0);\n const tokenOutputs = allTokenOutputs.filter((val) => val.tokenId === tokenId);\n const outputAmountSum = tokenOutputs.reduce((prev, cur) => prev + cur.amount, 0);\n const change = inputAmountSum - outputAmountSum;\n if (change < 0) {\n throw new Error(\"Not enough token amount to send\");\n }\n if (change > 0) {\n outputs.push(new _model_js__WEBPACK_IMPORTED_MODULE_20__.TokenSendRequest({\n cashaddr: changeAddress || this.tokenaddr,\n amount: change,\n tokenId: tokenId,\n commitment: tokenOutputs[0].commitment,\n capability: tokenOutputs[0].capability,\n value: tokenOutputs[0].value,\n }));\n }\n }\n };\n addTokenChangeOutputs(utxos, sendRequests);\n const bestHeight = await this.provider.getBlockHeight();\n const spendAmount = await (0,_util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_31__.sumSendRequestAmounts)(sendRequests);\n if (utxos.length === 0) {\n throw Error(\"There were no Unspent Outputs\");\n }\n if (typeof spendAmount !== \"bigint\") {\n throw Error(\"Couldn't get spend amount when building transaction\");\n }\n const relayFeePerByteInSatoshi = await (0,_network_getRelayFeeCache_js__WEBPACK_IMPORTED_MODULE_1__.getRelayFeeCache)(this.provider);\n const feeEstimate = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_29__.getFeeAmount)({\n utxos: utxos,\n sendRequests: sendRequests,\n privateKey: this.privateKey ?? Uint8Array.from([]),\n sourceAddress: this.cashaddr,\n relayFeePerByteInSatoshi: relayFeePerByteInSatoshi,\n slpOutputs: [],\n feePaidBy: feePaidBy,\n });\n const fundingUtxos = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_29__.getSuitableUtxos)(utxos, BigInt(spendAmount) + BigInt(feeEstimate), bestHeight, feePaidBy, sendRequests, options?.ensureUtxos || [], options?.tokenOperation);\n if (fundingUtxos.length === 0) {\n throw Error(\"The available inputs couldn't satisfy the request with fees\");\n }\n const fee = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_29__.getFeeAmount)({\n utxos: fundingUtxos,\n sendRequests: sendRequests,\n privateKey: this.privateKey ?? Uint8Array.from([]),\n sourceAddress: this.cashaddr,\n relayFeePerByteInSatoshi: relayFeePerByteInSatoshi,\n slpOutputs: [],\n feePaidBy: feePaidBy,\n });\n const { encodedTransaction, sourceOutputs } = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_29__.buildEncodedTransaction)({\n inputs: fundingUtxos,\n outputs: sendRequests,\n signingKey: this.privateKey ?? Uint8Array.from([]),\n sourceAddress: this.cashaddr,\n fee,\n discardChange,\n slpOutputs: [],\n feePaidBy,\n changeAddress,\n });\n const tokenIds = [\n ...fundingUtxos\n .filter((val) => val.token?.tokenId)\n .map((val) => val.token.tokenId),\n ...sendRequests\n .filter((val) => val instanceof _model_js__WEBPACK_IMPORTED_MODULE_20__.TokenSendRequest)\n .map((val) => val.tokenId),\n ].filter((value, index, array) => array.indexOf(value) === index);\n return { encodedTransaction, tokenIds, sourceOutputs };\n }\n // Submit a raw transaction\n async submitTransaction(transaction, awaitPropagation = true) {\n if (!this.provider) {\n throw Error(\"Wallet network provider was not initialized\");\n }\n let rawTransaction = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.binToHex)(transaction);\n return await this.provider.sendRawTransaction(rawTransaction, awaitPropagation);\n }\n // gets transaction history of this wallet\n async getRawHistory() {\n return await this.provider.getHistory(this.cashaddr);\n }\n // gets transaction history of this wallet\n async getHistory(unit, start, count, collapseChange) {\n return (0,_history_electrumTransformer_js__WEBPACK_IMPORTED_MODULE_32__.getAddressHistory)(this.cashaddr, this.provider, unit, start, count, collapseChange);\n }\n // gets last transaction of this wallet\n async getLastTransaction(confirmedOnly = false) {\n let history = await this.getRawHistory();\n if (confirmedOnly) {\n history = history.filter((val) => val.height > 0);\n }\n if (!history.length) {\n return null;\n }\n const [lastTx] = history.slice(-1);\n return this.provider.getRawTransactionObject(lastTx.tx_hash);\n }\n // waits for next transaction, program execution is halted\n async waitForTransaction(options = {\n getTransactionInfo: true,\n getBalance: false,\n txHash: undefined,\n }) {\n if (options.getTransactionInfo === undefined) {\n options.getTransactionInfo = true;\n }\n return new Promise(async (resolve) => {\n let txHashSeen = false;\n const makeResponse = async (txHash) => {\n const response = {};\n const promises = [undefined, undefined];\n if (options.getBalance === true) {\n promises[0] = this.getBalance();\n }\n if (options.getTransactionInfo === true) {\n if (!txHash) {\n promises[1] = this.getLastTransaction();\n }\n else {\n promises[1] = this.provider.getRawTransactionObject(txHash);\n }\n }\n const result = await Promise.all(promises);\n response.balance = result[0];\n response.transactionInfo = result[1];\n return response;\n };\n // waiting for a specific transaction to propagate\n if (options.txHash) {\n const waitForTransactionCallback = async (data) => {\n if (data && data[0] === options.txHash) {\n txHashSeen = true;\n this.provider.unsubscribeFromTransaction(options.txHash, waitForTransactionCallback);\n resolve(makeResponse(options.txHash));\n }\n };\n this.provider.subscribeToTransaction(options.txHash, waitForTransactionCallback);\n return;\n }\n // waiting for any address transaction\n const watchCancel = this.provider.watchAddressStatus(this.getDepositAddress(), async (_status) => {\n watchCancel();\n resolve(makeResponse());\n });\n });\n }\n /**\n * watchBlocks Watch network blocks\n *\n * @param callback callback with a block header object\n *\n * @returns a function which will cancel watching upon evaluation\n */\n watchBlocks(callback) {\n return this.provider.watchBlocks(callback);\n }\n /**\n * waitForBlock Wait for a network block\n *\n * @param height if specified waits for this exact blockchain height, otherwise resolves with the next block\n *\n */\n async waitForBlock(height) {\n return this.provider.waitForBlock(height);\n }\n //#endregion Funds\n //#region Private implementation details\n async deriveInfo() {\n const publicKey = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_33__.secp256k1.derivePublicKeyUncompressed(this.privateKey);\n if (typeof publicKey === \"string\") {\n throw new Error(publicKey);\n }\n this.publicKey = publicKey;\n const publicKeyCompressed = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_33__.secp256k1.derivePublicKeyCompressed(this.privateKey);\n if (typeof publicKeyCompressed === \"string\") {\n throw new Error(publicKeyCompressed);\n }\n this.publicKeyCompressed = publicKeyCompressed;\n const networkType = this.network === _enum_js__WEBPACK_IMPORTED_MODULE_4__.NetworkType.Regtest ? _enum_js__WEBPACK_IMPORTED_MODULE_4__.NetworkType.Testnet : this.network;\n this.privateKeyWif = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_23__.encodePrivateKeyWif)(this.privateKey, networkType);\n (0,_util_checkWifNetwork_js__WEBPACK_IMPORTED_MODULE_22__.checkWifNetwork)(this.privateKeyWif, this.network);\n this.cashaddr = (0,_util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_21__.deriveCashaddr)(this.privateKey, this.networkPrefix);\n this.tokenaddr = (0,_util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_21__.deriveTokenaddr)(this.privateKey, this.networkPrefix);\n this.address = this.cashaddr;\n this.publicKeyHash = (0,_util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_12__.derivePublicKeyHash)(this.cashaddr);\n return this;\n }\n //#endregion Private implementation details\n //#region Signing\n // Convenience wrapper to sign interface\n async sign(message) {\n return await Wallet.signedMessage.sign(message, this.privateKey);\n }\n // Convenience wrapper to verify interface\n async verify(message, sig, publicKey) {\n return await Wallet.signedMessage.verify(message, sig, this.cashaddr, publicKey);\n }\n //#endregion Signing\n //#region Cashtokens\n /**\n * Create new cashtoken, both funglible and/or non-fungible (NFT)\n * Refer to spec https://github.com/bitjson/cashtokens\n * @param {number} genesisRequest.amount amount of *fungible* tokens to create\n * @param {NFTCapability?} genesisRequest.capability capability of new NFT\n * @param {string?} genesisRequest.commitment NFT commitment message\n * @param {string?} genesisRequest.cashaddr cash address to send the created token UTXO to; if undefined will default to your address\n * @param {number?} genesisRequest.value satoshi value to send alongside with tokens; if undefined will default to 1000 satoshi\n * @param {SendRequestType | SendRequestType[]} sendRequests single or an array of extra send requests (OP_RETURN, value transfer, etc.) to include in genesis transaction\n * @param {SendRequestOptionsI} options Options of the send requests\n */\n async tokenGenesis(genesisRequest, sendRequests = [], options) {\n if (!Array.isArray(sendRequests)) {\n sendRequests = [sendRequests];\n }\n let utxos;\n if (options && options.utxoIds) {\n utxos = options.utxoIds.map((utxoId) => typeof utxoId === \"string\" ? (0,_model_js__WEBPACK_IMPORTED_MODULE_20__.fromUtxoId)(utxoId) : utxoId);\n }\n else {\n utxos = await this.getAddressUtxos(this.cashaddr);\n }\n const genesisInputs = utxos.filter((val) => val.vout === 0 && !val.token);\n if (genesisInputs.length === 0) {\n throw new Error(\"No suitable inputs with vout=0 available for new token genesis\");\n }\n const genesisSendRequest = new _model_js__WEBPACK_IMPORTED_MODULE_20__.TokenSendRequest({\n cashaddr: genesisRequest.cashaddr || this.tokenaddr,\n amount: genesisRequest.amount,\n value: genesisRequest.value || 1000,\n capability: genesisRequest.capability,\n commitment: genesisRequest.commitment,\n tokenId: genesisInputs[0].txid,\n });\n return this.send([genesisSendRequest, ...sendRequests], {\n ...options,\n utxoIds: utxos,\n ensureUtxos: [genesisInputs[0]],\n checkTokenQuantities: false,\n queryBalance: false,\n tokenOperation: \"genesis\",\n });\n }\n /**\n * Mint new NFT cashtokens using an existing minting token\n * Refer to spec https://github.com/bitjson/cashtokens\n * @param {string} tokenId tokenId of an NFT to mint\n * @param {TokenMintRequest | TokenMintRequest[]} mintRequests mint requests with new token properties and recipients\n * @param {NFTCapability?} mintRequest.capability capability of new NFT\n * @param {string?} mintRequest.commitment NFT commitment message\n * @param {string?} mintRequest.cashaddr cash address to send the created token UTXO to; if undefined will default to your address\n * @param {number?} mintRequest.value satoshi value to send alongside with tokens; if undefined will default to 1000 satoshi\n * @param {boolean?} deductTokenAmount if minting token contains fungible amount, deduct from it by amount of minted tokens\n * @param {SendRequestOptionsI} options Options of the send requests\n */\n async tokenMint(tokenId, mintRequests, deductTokenAmount = false, options) {\n if (tokenId?.length !== 64) {\n throw Error(`Invalid tokenId supplied: ${tokenId}`);\n }\n if (!Array.isArray(mintRequests)) {\n mintRequests = [mintRequests];\n }\n const utxos = await this.getAddressUtxos(this.cashaddr);\n const nftUtxos = utxos.filter((val) => val.token?.tokenId === tokenId &&\n val.token?.capability === _interface_js__WEBPACK_IMPORTED_MODULE_8__.NFTCapability.minting);\n if (!nftUtxos.length) {\n throw new Error(\"You do not have any token UTXOs with minting capability for specified tokenId\");\n }\n const newAmount = deductTokenAmount && nftUtxos[0].token.amount > 0\n ? nftUtxos[0].token.amount - mintRequests.length\n : nftUtxos[0].token.amount;\n const safeNewAmount = Math.max(0, newAmount);\n const mintingInput = new _model_js__WEBPACK_IMPORTED_MODULE_20__.TokenSendRequest({\n cashaddr: this.tokenaddr,\n tokenId: tokenId,\n capability: nftUtxos[0].token.capability,\n commitment: nftUtxos[0].token.commitment,\n amount: safeNewAmount,\n value: nftUtxos[0].satoshis,\n });\n return this.send([\n mintingInput,\n ...mintRequests.map((val) => new _model_js__WEBPACK_IMPORTED_MODULE_20__.TokenSendRequest({\n cashaddr: val.cashaddr || this.tokenaddr,\n amount: 0,\n tokenId: tokenId,\n value: val.value,\n capability: val.capability,\n commitment: val.commitment,\n })),\n ], {\n ...options,\n ensureUtxos: [nftUtxos[0]],\n checkTokenQuantities: false,\n queryBalance: false,\n tokenOperation: \"mint\",\n });\n }\n /**\n * Perform an explicit token burning by spending a token utxo to an OP_RETURN\n *\n * Behaves differently for fungible and non-fungible tokens:\n * * NFTs are always \"destroyed\"\n * * FTs' amount is reduced by the amount specified, if 0 FT amount is left and no NFT present, the token is \"destroyed\"\n *\n * Refer to spec https://github.com/bitjson/cashtokens\n * @param {string} burnRequest.tokenId tokenId of a token to burn\n * @param {NFTCapability} burnRequest.capability capability of the NFT token to select, optional\n * @param {string?} burnRequest.commitment commitment of the NFT token to select, optional\n * @param {number?} burnRequest.amount amount of fungible tokens to burn, optional\n * @param {string?} burnRequest.cashaddr address to return token and satoshi change to\n * @param {string?} message optional message to include in OP_RETURN\n * @param {SendRequestOptionsI} options Options of the send requests\n */\n async tokenBurn(burnRequest, message, options) {\n if (burnRequest.tokenId?.length !== 64) {\n throw Error(`Invalid tokenId supplied: ${burnRequest.tokenId}`);\n }\n const utxos = await this.getAddressUtxos(this.cashaddr);\n const tokenUtxos = utxos.filter((val) => val.token?.tokenId === burnRequest.tokenId &&\n val.token?.capability === burnRequest.capability &&\n val.token?.commitment === burnRequest.commitment);\n if (!tokenUtxos.length) {\n throw new Error(\"You do not have suitable token UTXOs to perform burn\");\n }\n const totalFungibleAmount = tokenUtxos.reduce((prev, cur) => prev + (cur.token?.amount || 0), 0);\n const fungibleBurnAmount = burnRequest.amount && burnRequest.amount > 0 ? burnRequest.amount : 0;\n const hasNFT = burnRequest.capability || burnRequest.commitment;\n let utxoIds = [];\n let changeSendRequests;\n if (hasNFT) {\n // does not have FT tokens, let us destroy the token completely\n if (totalFungibleAmount === 0) {\n changeSendRequests = [];\n utxoIds.push(tokenUtxos[0]);\n }\n else {\n // add utxos to spend from\n let available = 0;\n for (const token of tokenUtxos.filter((val) => val.token?.amount)) {\n utxoIds.push(token);\n available += token.token?.amount;\n if (available >= fungibleBurnAmount) {\n break;\n }\n }\n // if there are FT, reduce their amount\n const newAmount = totalFungibleAmount - fungibleBurnAmount;\n const safeNewAmount = Math.max(0, newAmount);\n changeSendRequests = [\n new _model_js__WEBPACK_IMPORTED_MODULE_20__.TokenSendRequest({\n cashaddr: burnRequest.cashaddr || this.tokenaddr,\n tokenId: burnRequest.tokenId,\n capability: burnRequest.capability,\n commitment: burnRequest.commitment,\n amount: safeNewAmount,\n value: tokenUtxos[0].satoshis,\n }),\n ];\n }\n }\n else {\n // if we are burning last fughible tokens, let us destroy the token completely\n if (totalFungibleAmount === fungibleBurnAmount) {\n changeSendRequests = [];\n utxoIds.push(tokenUtxos[0]);\n }\n else {\n // add utxos to spend from\n let available = 0;\n for (const token of tokenUtxos.filter((val) => val.token?.amount)) {\n utxoIds.push(token);\n available += token.token?.amount;\n if (available >= fungibleBurnAmount) {\n break;\n }\n }\n // reduce the FT amount\n const newAmount = totalFungibleAmount - fungibleBurnAmount;\n const safeNewAmount = Math.max(0, newAmount);\n changeSendRequests = [\n new _model_js__WEBPACK_IMPORTED_MODULE_20__.TokenSendRequest({\n cashaddr: burnRequest.cashaddr || this.tokenaddr,\n tokenId: burnRequest.tokenId,\n amount: safeNewAmount,\n value: tokenUtxos[0].satoshis,\n }),\n ];\n }\n }\n const opReturn = _model_js__WEBPACK_IMPORTED_MODULE_20__.OpReturnData.fromString(message || \"\");\n return this.send([opReturn, ...changeSendRequests], {\n ...options,\n checkTokenQuantities: false,\n queryBalance: false,\n ensureUtxos: utxoIds.length > 0 ? utxoIds : undefined,\n tokenOperation: \"burn\",\n });\n }\n /**\n * getTokenUtxos Get unspent token outputs for the wallet\n * will return utxos only for the specified token if `tokenId` provided\n * @param {string?} tokenId tokenId (category) to filter utxos by, if not set will return utxos from all tokens\n * @returns {UtxoI[]} token utxos\n */\n async getTokenUtxos(tokenId) {\n const utxos = await this.getAddressUtxos(this.address);\n return utxos.filter((val) => tokenId ? val.token?.tokenId === tokenId : val.token);\n }\n /**\n * getTokenBalance Gets fungible token balance\n * for NFT token balance see @ref getNftTokenBalance\n * @param {string} tokenId tokenId to get balance for\n * @returns {number} fungible token balance\n */\n async getTokenBalance(tokenId) {\n const utxos = (await this.getTokenUtxos(tokenId)).filter((val) => val.token?.amount);\n return (0,_util_sumUtxoValue_js__WEBPACK_IMPORTED_MODULE_26__.sumTokenAmounts)(utxos, tokenId);\n }\n /**\n * getNftTokenBalance Gets non-fungible token (NFT) balance for a particula tokenId\n * disregards fungible token balances\n * for fungible token balance see @ref getTokenBalance\n * @param {string} tokenId tokenId to get balance for\n * @returns {number} non-fungible token balance\n */\n async getNftTokenBalance(tokenId) {\n const utxos = (await this.getTokenUtxos(tokenId)).filter((val) => val.token?.commitment !== undefined);\n return utxos.length;\n }\n /**\n * getAllTokenBalances Gets all fungible token balances in this wallet\n * @returns {Object} a map [tokenId => balance] for all tokens in this wallet\n */\n async getAllTokenBalances() {\n const result = {};\n const utxos = (await this.getTokenUtxos()).filter((val) => val.token?.amount);\n for (const utxo of utxos) {\n if (!result[utxo.token.tokenId]) {\n result[utxo.token.tokenId] = 0;\n }\n result[utxo.token.tokenId] += utxo.token.amount;\n }\n return result;\n }\n /**\n * getAllNftTokenBalances Gets all non-fungible token (NFT) balances in this wallet\n * @returns {Object} a map [tokenId => balance] for all NFTs in this wallet\n */\n async getAllNftTokenBalances() {\n const result = {};\n const utxos = (await this.getTokenUtxos()).filter((val) => val.token?.commitment !== undefined);\n for (const utxo of utxos) {\n if (!result[utxo.token.tokenId]) {\n result[utxo.token.tokenId] = 0;\n }\n result[utxo.token.tokenId] += 1;\n }\n return result;\n }\n}\nWallet.signedMessage = new _message_index_js__WEBPACK_IMPORTED_MODULE_34__.SignedMessage();\n/**\n * Class to manage a testnet wallet.\n */\nclass TestNetWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_4__.NetworkType.Testnet);\n }\n // will receive 10000 testnet satoshi, rate limits apply\n async getTestnetSatoshis() {\n try {\n const response = await axios__WEBPACK_IMPORTED_MODULE_2___default().post(`${TestNetWallet.faucetServer}/faucet/get_testnet_bch`, { cashaddr: this.cashaddr });\n const data = response.data;\n return data.txId;\n }\n catch (e) {\n // console.log(e);\n // console.log(e.response ? e.response.data : \"\");\n throw e;\n }\n }\n // be nice and return them back\n async returnTestnetSatoshis() {\n try {\n const response = await axios__WEBPACK_IMPORTED_MODULE_2___default().post(`${TestNetWallet.faucetServer}/faucet/get_addresses`);\n const data = response.data;\n return await this.slpAware().sendMax(data.bchtest);\n }\n catch (e) {\n console.log(e);\n console.log(e.response ? e.response.data : \"\");\n throw e;\n }\n }\n // will receive 10 testnet tokens, rate limits apply\n async getTestnetSlp(tokenId) {\n try {\n const response = await axios__WEBPACK_IMPORTED_MODULE_2___default().post(`${TestNetWallet.faucetServer}/faucet/get_testnet_slp`, { slpaddr: this.slp.slpaddr, tokenId: tokenId });\n const data = response.data;\n return data.txId;\n }\n catch (e) {\n //console.log(e);\n //console.log(e.response ? e.response.data : \"\");\n throw e;\n }\n }\n // be nice and return them back\n async returnTestnetSlp(tokenId) {\n try {\n const response = await axios__WEBPACK_IMPORTED_MODULE_2___default().post(`${TestNetWallet.faucetServer}/faucet/get_addresses`);\n const data = response.data;\n return await this.slp.sendMax(data.slptest, tokenId);\n }\n catch (e) {\n console.log(e);\n console.log(e.response ? e.response.data : \"\");\n throw e;\n }\n }\n // interface to static slp functions. see Slp.ts\n static get slp() {\n return _Slp_js__WEBPACK_IMPORTED_MODULE_6__.TestNetSlp;\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_7__.TestNetUtil;\n }\n}\nTestNetWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_35__.CashAddressNetworkPrefix.testnet;\nTestNetWallet.faucetServer = \"https://rest-unstable.mainnet.cash\";\n/**\n * Class to manage a regtest wallet.\n */\nclass RegTestWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_4__.NetworkType.Regtest);\n }\n // interface to static slp functions. see Slp.ts\n static get slp() {\n return _Slp_js__WEBPACK_IMPORTED_MODULE_6__.RegTestSlp;\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_7__.RegTestUtil;\n }\n}\nRegTestWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_35__.CashAddressNetworkPrefix.regtest;\n/**\n * Class to manage a bitcoin cash wif wallet.\n */\nclass WifWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_4__.NetworkType.Mainnet, _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Wif);\n }\n // interface to static slp functions. see Slp.ts\n static get slp() {\n return _Slp_js__WEBPACK_IMPORTED_MODULE_6__.WifSlp;\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_7__.WifUtil;\n }\n}\nWifWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_35__.CashAddressNetworkPrefix.mainnet;\nWifWallet.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Wif;\n/**\n * Class to manage a testnet wif wallet.\n */\nclass TestNetWifWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_4__.NetworkType.Testnet, _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Wif);\n }\n // interface to static slp functions. see Slp.ts\n static get slp() {\n return _Slp_js__WEBPACK_IMPORTED_MODULE_6__.TestNetWifSlp;\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_7__.TestNetWifUtil;\n }\n}\nTestNetWifWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_35__.CashAddressNetworkPrefix.testnet;\nTestNetWifWallet.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Wif;\n/**\n * Class to manage a regtest wif wallet.\n */\nclass RegTestWifWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_4__.NetworkType.Regtest, _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Wif);\n }\n // interface to static slp functions. see Slp.ts\n static get slp() {\n return _Slp_js__WEBPACK_IMPORTED_MODULE_6__.RegTestWifSlp;\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_7__.RegTestWifUtil;\n }\n}\nRegTestWifWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_35__.CashAddressNetworkPrefix.regtest;\nRegTestWifWallet.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Wif;\n/**\n * Class to manage a bitcoin cash watch wallet.\n */\nclass WatchWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_4__.NetworkType.Mainnet, _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Watch);\n }\n // interface to static slp functions. see Slp.ts\n static get slp() {\n return _Slp_js__WEBPACK_IMPORTED_MODULE_6__.WatchSlp;\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_7__.WatchUtil;\n }\n}\nWatchWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_35__.CashAddressNetworkPrefix.mainnet;\nWatchWallet.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Watch;\n/**\n * Class to manage a testnet watch wallet.\n */\nclass TestNetWatchWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_4__.NetworkType.Testnet, _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Watch);\n }\n // interface to static slp functions. see Slp.ts\n static get slp() {\n return _Slp_js__WEBPACK_IMPORTED_MODULE_6__.TestNetWatchSlp;\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_7__.TestNetWatchUtil;\n }\n}\nTestNetWatchWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_35__.CashAddressNetworkPrefix.testnet;\nTestNetWatchWallet.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Watch;\n/**\n * Class to manage a regtest watch wallet.\n */\nclass RegTestWatchWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_4__.NetworkType.Regtest, _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Watch);\n }\n // interface to static slp functions. see Slp.ts\n static get slp() {\n return _Slp_js__WEBPACK_IMPORTED_MODULE_6__.RegTestWatchSlp;\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_7__.RegTestWatchUtil;\n }\n}\nRegTestWatchWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_35__.CashAddressNetworkPrefix.regtest;\nRegTestWatchWallet.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Watch;\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/wallet/Wif.ts?");
|
|
1667
|
+
eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"RegTestWallet\": () => (/* binding */ RegTestWallet),\n/* harmony export */ \"RegTestWatchWallet\": () => (/* binding */ RegTestWatchWallet),\n/* harmony export */ \"RegTestWifWallet\": () => (/* binding */ RegTestWifWallet),\n/* harmony export */ \"TestNetWallet\": () => (/* binding */ TestNetWallet),\n/* harmony export */ \"TestNetWatchWallet\": () => (/* binding */ TestNetWatchWallet),\n/* harmony export */ \"TestNetWifWallet\": () => (/* binding */ TestNetWifWallet),\n/* harmony export */ \"Wallet\": () => (/* binding */ Wallet),\n/* harmony export */ \"WatchWallet\": () => (/* binding */ WatchWallet),\n/* harmony export */ \"WifWallet\": () => (/* binding */ WifWallet)\n/* harmony export */ });\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/key/hd-key.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_33__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/crypto/default-crypto-instances.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/hex.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/key/key-utils.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/key/wallet-import-format.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_35__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/address/cash-address.js\");\n/* harmony import */ var bip39__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! bip39 */ \"../../node_modules/bip39/src/index.js\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../enum.js */ \"./src/enum.ts\");\n/* harmony import */ var _interface_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../interface.js */ \"./src/interface.ts\");\n/* harmony import */ var _Base_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Base.js */ \"./src/wallet/Base.ts\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./enum.js */ \"./src/wallet/enum.ts\");\n/* harmony import */ var _model_js__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ./model.js */ \"./src/wallet/model.ts\");\n/* harmony import */ var _transaction_Wif_js__WEBPACK_IMPORTED_MODULE_29__ = __webpack_require__(/*! ../transaction/Wif.js */ \"./src/transaction/Wif.ts\");\n/* harmony import */ var _util_asSendRequestObject_js__WEBPACK_IMPORTED_MODULE_30__ = __webpack_require__(/*! ../util/asSendRequestObject.js */ \"./src/util/asSendRequestObject.ts\");\n/* harmony import */ var _util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(/*! ../util/balanceObjectFromSatoshi.js */ \"./src/util/balanceObjectFromSatoshi.ts\");\n/* harmony import */ var _util_checkWifNetwork_js__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ../util/checkWifNetwork.js */ \"./src/util/checkWifNetwork.ts\");\n/* harmony import */ var _util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ../util/deriveCashaddr.js */ \"./src/util/deriveCashaddr.ts\");\n/* harmony import */ var _util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../util/derivePublicKeyHash.js */ \"./src/util/derivePublicKeyHash.ts\");\n/* harmony import */ var _util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../util/checkForEmptySeed.js */ \"./src/util/checkForEmptySeed.ts\");\n/* harmony import */ var _util_sanitizeUnit_js__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(/*! ../util/sanitizeUnit.js */ \"./src/util/sanitizeUnit.ts\");\n/* harmony import */ var _util_sumUtxoValue_js__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(/*! ../util/sumUtxoValue.js */ \"./src/util/sumUtxoValue.ts\");\n/* harmony import */ var _util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_31__ = __webpack_require__(/*! ../util/sumSendRequestAmounts.js */ \"./src/util/sumSendRequestAmounts.ts\");\n/* harmony import */ var _network_getRelayFeeCache_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../network/getRelayFeeCache.js */ \"./src/network/getRelayFeeCache.ts\");\n/* harmony import */ var _Slp_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./Slp.js */ \"./src/wallet/Slp.ts\");\n/* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! axios */ \"../../node_modules/axios/index.js\");\n/* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(axios__WEBPACK_IMPORTED_MODULE_2__);\n/* harmony import */ var _util_bchaddr_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../util/bchaddr.js */ \"../../node_modules/bchaddrjs-slp/src/bchaddr.js\");\n/* harmony import */ var _util_bchaddr_js__WEBPACK_IMPORTED_MODULE_13___default = /*#__PURE__*/__webpack_require__.n(_util_bchaddr_js__WEBPACK_IMPORTED_MODULE_13__);\n/* harmony import */ var _Util_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./Util.js */ \"./src/wallet/Util.ts\");\n/* harmony import */ var _network_index_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../network/index.js */ \"./src/network/default.ts\");\n/* harmony import */ var _util_randomBytes_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../util/randomBytes.js */ \"./src/util/randomBytes.ts\");\n/* harmony import */ var _message_index_js__WEBPACK_IMPORTED_MODULE_34__ = __webpack_require__(/*! ../message/index.js */ \"./src/message/signed.ts\");\n/* harmony import */ var _util_amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(/*! ../util/amountInSatoshi.js */ \"./src/util/amountInSatoshi.ts\");\n/* harmony import */ var _util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ../util/getXPubKey.js */ \"./src/util/getXPubKey.ts\");\n/* harmony import */ var _constant_js__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ../constant.js */ \"./src/constant.ts\");\n/* harmony import */ var _history_electrumTransformer_js__WEBPACK_IMPORTED_MODULE_32__ = __webpack_require__(/*! ../history/electrumTransformer.js */ \"./src/history/electrumTransformer.ts\");\n/* harmony import */ var _Bcmr_js__WEBPACK_IMPORTED_MODULE_28__ = __webpack_require__(/*! ./Bcmr.js */ \"./src/wallet/Bcmr.ts\");\n/* harmony import */ var _qr_Qr_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../qr/Qr.js */ \"./src/qr/Qr.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_Base_js__WEBPACK_IMPORTED_MODULE_3__, _enum_js__WEBPACK_IMPORTED_MODULE_4__, _Slp_js__WEBPACK_IMPORTED_MODULE_6__, _Util_js__WEBPACK_IMPORTED_MODULE_7__, _network_index_js__WEBPACK_IMPORTED_MODULE_9__, _qr_Qr_js__WEBPACK_IMPORTED_MODULE_10__, _util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_12__, _util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_16__, _util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_17__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_18__, _model_js__WEBPACK_IMPORTED_MODULE_20__, _util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_21__, _util_checkWifNetwork_js__WEBPACK_IMPORTED_MODULE_22__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_23__, _util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_25__, _util_amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_27__, _Bcmr_js__WEBPACK_IMPORTED_MODULE_28__, _transaction_Wif_js__WEBPACK_IMPORTED_MODULE_29__, _util_asSendRequestObject_js__WEBPACK_IMPORTED_MODULE_30__, _util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_31__, _history_electrumTransformer_js__WEBPACK_IMPORTED_MODULE_32__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_33__, _message_index_js__WEBPACK_IMPORTED_MODULE_34__]);\n([_Base_js__WEBPACK_IMPORTED_MODULE_3__, _enum_js__WEBPACK_IMPORTED_MODULE_4__, _Slp_js__WEBPACK_IMPORTED_MODULE_6__, _Util_js__WEBPACK_IMPORTED_MODULE_7__, _network_index_js__WEBPACK_IMPORTED_MODULE_9__, _qr_Qr_js__WEBPACK_IMPORTED_MODULE_10__, _util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_12__, _util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_16__, _util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_17__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_18__, _model_js__WEBPACK_IMPORTED_MODULE_20__, _util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_21__, _util_checkWifNetwork_js__WEBPACK_IMPORTED_MODULE_22__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_23__, _util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_25__, _util_amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_27__, _Bcmr_js__WEBPACK_IMPORTED_MODULE_28__, _transaction_Wif_js__WEBPACK_IMPORTED_MODULE_29__, _util_asSendRequestObject_js__WEBPACK_IMPORTED_MODULE_30__, _util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_31__, _history_electrumTransformer_js__WEBPACK_IMPORTED_MODULE_32__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_33__, _message_index_js__WEBPACK_IMPORTED_MODULE_34__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n//#region Imports\n// Stable\n\n// Unstable?\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n//#endregion Imports\n/**\n * Class to manage a bitcoin cash wallet.\n */\nclass Wallet extends _Base_js__WEBPACK_IMPORTED_MODULE_3__.BaseWallet {\n //#endregion\n //#region Constructors and Statics\n constructor(name = \"\", network = _enum_js__WEBPACK_IMPORTED_MODULE_4__.NetworkType.Mainnet, walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Seed) {\n super(name, network, walletType);\n this.derivationPath = \"m/44'/0'/0'/0/0\";\n this.parentDerivationPath = \"m/44'/0'/0'\";\n this._slpAware = false; // a flag which activates utxo checking against an external slp indexer\n this._slpSemiAware = false; // a flag which requires an utxo to have more than 546 sats to be spendable and counted in the balance\n this.fromId = async (walletId) => {\n let [walletType, networkGiven, arg1] = walletId.split(\":\");\n if (this.network != networkGiven) {\n throw Error(`Network prefix ${networkGiven} to a ${this.network} wallet`);\n }\n // \"wif:regtest:cNfsPtqN2bMRS7vH5qd8tR8GMvgXyL5BjnGAKgZ8DYEiCrCCQcP6\"\n if (walletType === \"wif\") {\n return this.fromWIF(arg1);\n }\n return super.fromId(walletId);\n };\n this.networkPrefix = _enum_js__WEBPACK_IMPORTED_MODULE_4__.prefixFromNetworkMap[this.network];\n }\n //#region Accessors\n // interface to slp functions. see Slp.ts\n get slp() {\n if (!this._slp) {\n this._slp = new _Slp_js__WEBPACK_IMPORTED_MODULE_6__.Slp(this);\n this._slpAware = true;\n }\n return this._slp;\n }\n // interface to slp functions. see Slp.ts\n static get slp() {\n return _Slp_js__WEBPACK_IMPORTED_MODULE_6__.Slp;\n }\n // interface to util functions. see Util.ts\n get util() {\n if (!this._util) {\n this._util = new _Util_js__WEBPACK_IMPORTED_MODULE_7__.Util(this);\n }\n return this._util;\n }\n // interface to util util. see Util.Util\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_7__.Util;\n }\n slpAware(value = true) {\n this._slpAware = value;\n return this;\n }\n slpSemiAware(value = true) {\n this._slpSemiAware = value;\n return this;\n }\n getNetworkProvider(network = _interface_js__WEBPACK_IMPORTED_MODULE_8__.Network.MAINNET) {\n return (0,_network_index_js__WEBPACK_IMPORTED_MODULE_9__.getNetworkProvider)(network);\n }\n /**\n * getTokenDepositAddress - get a cashtoken aware wallet deposit address\n *\n * @returns The cashtoken aware deposit address as a string\n */\n getTokenDepositAddress() {\n return this.tokenaddr;\n }\n /**\n * getDepositQr - get an address qrcode, encoded for display on the web\n *\n * @returns The qrcode for the token aware address\n */\n getTokenDepositQr() {\n return (0,_qr_Qr_js__WEBPACK_IMPORTED_MODULE_10__.qrAddress)(this.getTokenDepositAddress());\n }\n /**\n * explorerUrl Web url to a transaction on a block explorer\n *\n * @param txId transaction Id\n * @returns Url string\n */\n explorerUrl(txId) {\n const explorerUrlMap = {\n mainnet: \"https://blockchair.com/bitcoin-cash/transaction/\",\n testnet: \"https://www.blockchain.com/bch-testnet/tx/\",\n regtest: \"\",\n };\n return explorerUrlMap[this.network] + txId;\n }\n // Return wallet info\n getInfo() {\n return {\n cashaddr: this.cashaddr,\n tokenaddr: this.tokenaddr,\n isTestnet: this.isTestnet,\n name: this.name,\n network: this.network,\n seed: this.mnemonic ? this.getSeed().seed : undefined,\n derivationPath: this.mnemonic ? this.getSeed().derivationPath : undefined,\n parentDerivationPath: this.mnemonic\n ? this.getSeed().parentDerivationPath\n : undefined,\n parentXPubKey: this.parentXPubKey ? this.parentXPubKey : undefined,\n publicKey: this.publicKey ? (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.binToHex)(this.publicKey) : undefined,\n publicKeyHash: (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.binToHex)(this.publicKeyHash),\n privateKey: this.privateKey ? (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.binToHex)(this.privateKey) : undefined,\n privateKeyWif: this.privateKeyWif,\n walletId: this.toString(),\n walletDbEntry: this.toDbString(),\n };\n }\n // returns the public key hash for an address\n getPublicKey(hex = false) {\n if (this.publicKey) {\n return hex ? (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.binToHex)(this.publicKey) : this.publicKey;\n }\n else {\n throw Error(\"The public key for this wallet is not known, perhaps the wallet was created to watch the *hash* of a public key? i.e. a cashaddress.\");\n }\n }\n // returns the public key hash for an address\n getPublicKeyCompressed(hex = false) {\n if (this.publicKeyCompressed) {\n return hex\n ? (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.binToHex)(this.publicKeyCompressed)\n : this.publicKeyCompressed;\n }\n else {\n throw Error(\"The compressed public key for this wallet is not known, perhaps the wallet was created to watch the *hash* of a public key? i.e. a cashaddress.\");\n }\n }\n // returns the public key hash for an address\n getPublicKeyHash(hex = false) {\n if (this.publicKeyHash) {\n return hex ? (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.binToHex)(this.publicKeyHash) : this.publicKeyHash;\n }\n else {\n throw Error(\"The public key hash for this wallet is not known. If this wallet was created from the constructor directly, calling the deriveInfo() function may help. \");\n }\n }\n /**\n * fromWIF - create a wallet using the private key supplied in `Wallet Import Format`\n *\n * @param wif WIF encoded private key string\n *\n * @returns instantiated wallet\n */\n static async fromWIF(wif) {\n return new this().fromWIF(wif);\n }\n /**\n * fromCashaddr - create a watch-only wallet in the network derived from the address\n *\n * such kind of wallet does not have a private key and is unable to spend any funds\n * however it still allows to use many utility functions such as getting and watching balance, etc.\n *\n * @param address cashaddress of a wallet\n *\n * @returns instantiated wallet\n */\n static async fromCashaddr(address) {\n const prefix = (0,_util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_12__.derivePrefix)(address);\n const networkType = _enum_js__WEBPACK_IMPORTED_MODULE_4__.networkPrefixMap[prefix];\n return new this(\"\", networkType, _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Watch).watchOnly(address);\n }\n /**\n * fromTokenaddr - create a watch-only wallet in the network derived from the address\n *\n * such kind of wallet does not have a private key and is unable to spend any funds\n * however it still allows to use many utility functions such as getting and watching balance, etc.\n *\n * @param address token aware cashaddress of a wallet\n *\n * @returns instantiated wallet\n */\n static async fromTokenaddr(address) {\n const prefix = (0,_util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_12__.derivePrefix)(address);\n const networkType = _enum_js__WEBPACK_IMPORTED_MODULE_4__.networkPrefixMap[prefix];\n return new this(\"\", networkType, _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Watch).watchOnly(address);\n }\n /**\n * fromSlpaddr - create an SLP aware watch-only wallet in the network derived from the address\n *\n * such kind of wallet does not have a private key and is unable to spend any funds\n * however it still allows to use many utility functions such as getting and watching balance, etc.\n *\n * @param address slpaddress of a wallet\n *\n * @returns instantiated wallet\n */\n static async fromSlpaddr(address) {\n return this.fromCashaddr((0,_util_bchaddr_js__WEBPACK_IMPORTED_MODULE_13__.toCashAddress)(address));\n }\n //#endregion Constructors and Statics\n //#region Protected implementations\n async generate() {\n if (this.walletType === _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Wif) {\n return await this._generateWif();\n }\n else if (this.walletType === _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Watch) {\n return this;\n }\n else if (this.walletType === _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Hd) {\n throw Error(\"Not implemented\");\n }\n else if (this.walletType === _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Seed) {\n return await this._generateMnemonic();\n }\n else {\n console.log(this.walletType);\n throw Error(`Could not determine walletType: ${this.walletType}`);\n }\n }\n async _generateWif() {\n if (!this.privateKey) {\n this.privateKey = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_14__.generatePrivateKey)(() => (0,_util_randomBytes_js__WEBPACK_IMPORTED_MODULE_15__.generateRandomBytes)(32));\n }\n return this.deriveInfo();\n }\n async _generateMnemonic() {\n this.mnemonic = (0,bip39__WEBPACK_IMPORTED_MODULE_0__.generateMnemonic)();\n if (this.mnemonic.length == 0)\n throw Error(\"refusing to create wallet from empty mnemonic\");\n let seed = (0,bip39__WEBPACK_IMPORTED_MODULE_0__.mnemonicToSeedSync)(this.mnemonic);\n (0,_util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_16__.checkForEmptySeed)(seed);\n let network = this.isTestnet ? \"testnet\" : \"mainnet\";\n this.parentXPubKey = await (0,_util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_17__.getXPubKey)(seed, this.parentDerivationPath, network);\n let hdNode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_18__.deriveHdPrivateNodeFromSeed)(seed);\n if (!hdNode.valid) {\n throw Error(\"Invalid private key derived from mnemonic seed\");\n }\n let zerothChild = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_18__.deriveHdPath)(hdNode, this.derivationPath);\n if (typeof zerothChild === \"string\") {\n throw Error(zerothChild);\n }\n this.privateKey = zerothChild.privateKey;\n this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Seed;\n return await this.deriveInfo();\n }\n async getXPubKeys(paths) {\n if (this.mnemonic) {\n if (paths) {\n let xPubKeys = await this.deriveHdPaths(paths);\n return [xPubKeys];\n }\n else {\n return await this.deriveHdPaths(_constant_js__WEBPACK_IMPORTED_MODULE_19__.DERIVATION_PATHS);\n }\n }\n else {\n throw Error(\"xpubkeys can only be derived from seed type wallets.\");\n }\n }\n // Initialize wallet from a mnemonic phrase\n async fromSeed(mnemonic, derivationPath) {\n this.mnemonic = mnemonic.trim().toLowerCase();\n if (this.mnemonic.length == 0)\n throw Error(\"refusing to create wallet from empty mnemonic\");\n let seed = (0,bip39__WEBPACK_IMPORTED_MODULE_0__.mnemonicToSeedSync)(this.mnemonic);\n (0,_util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_16__.checkForEmptySeed)(seed);\n let hdNode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_18__.deriveHdPrivateNodeFromSeed)(seed);\n if (!hdNode.valid) {\n throw Error(\"Invalid private key derived from mnemonic seed\");\n }\n if (derivationPath) {\n this.derivationPath = derivationPath;\n // If the derivation path is for the first account child, set the parent derivation path\n let path = derivationPath.split(\"/\");\n if (path.slice(-2).join(\"/\") == \"0/0\") {\n this.parentDerivationPath = path.slice(0, -2).join(\"/\");\n }\n }\n let zerothChild = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_18__.deriveHdPath)(hdNode, this.derivationPath);\n if (typeof zerothChild === \"string\") {\n throw Error(zerothChild);\n }\n this.privateKey = zerothChild.privateKey;\n let network = this.isTestnet ? \"testnet\" : \"mainnet\";\n this.parentXPubKey = await (0,_util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_17__.getXPubKey)(seed, this.parentDerivationPath, network);\n this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Seed;\n await this.deriveInfo();\n return this;\n }\n // Get common xpub paths from zerothChild privateKey\n async deriveHdPaths(hdPaths) {\n if (!this.mnemonic)\n throw Error(\"refusing to create wallet from empty mnemonic\");\n let seed = (0,bip39__WEBPACK_IMPORTED_MODULE_0__.mnemonicToSeedSync)(this.mnemonic);\n (0,_util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_16__.checkForEmptySeed)(seed);\n let hdNode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_18__.deriveHdPrivateNodeFromSeed)(seed);\n if (!hdNode.valid) {\n throw Error(\"Invalid private key derived from mnemonic seed\");\n }\n let result = [];\n for (const path of hdPaths) {\n if (path === \"m\") {\n throw Error(\"Storing or sharing of parent public key may lead to loss of funds. Storing or sharing *root* parent public keys is strongly discouraged, although all parent keys have risk. See: https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#implications\");\n }\n let childNode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_18__.deriveHdPath)(hdNode, path);\n if (typeof childNode === \"string\") {\n throw Error(childNode);\n }\n let node = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_18__.deriveHdPublicNode)(childNode);\n if (typeof node === \"string\") {\n throw Error(node);\n }\n let xPubKey = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_18__.encodeHdPublicKey)({\n network: this.network,\n node: node,\n });\n let key = new _model_js__WEBPACK_IMPORTED_MODULE_20__.XPubKey({\n path: path,\n xPubKey: xPubKey,\n });\n result.push(await key.ready());\n }\n return await Promise.all(result).then((result) => {\n return result;\n });\n }\n // Initialize a watch only wallet from a cash addr\n async watchOnly(address) {\n this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Watch;\n let addressComponents = address.split(\":\");\n let addressPrefix, addressBase;\n if (addressComponents.length === 1) {\n addressBase = addressComponents.shift();\n addressPrefix = (0,_util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_12__.derivePrefix)(addressBase);\n }\n else {\n addressPrefix = addressComponents.shift();\n addressBase = addressComponents.shift();\n if (addressPrefix in _enum_js__WEBPACK_IMPORTED_MODULE_4__.networkPrefixMap) {\n if (_enum_js__WEBPACK_IMPORTED_MODULE_4__.networkPrefixMap[addressPrefix] != this.network) {\n throw Error(`a ${addressPrefix} address cannot be watched from a ${this.network} Wallet`);\n }\n }\n }\n this.cashaddr = `${addressPrefix}:${addressBase}`;\n this.address = this.cashaddr;\n this.publicKeyHash = (0,_util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_12__.derivePublicKeyHash)(this.cashaddr);\n this.tokenaddr = (0,_util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_21__.deriveTokenaddr)(this.publicKeyHash, this.networkPrefix);\n return this;\n }\n // Initialize wallet from Wallet Import Format\n async fromWIF(secret) {\n (0,_util_checkWifNetwork_js__WEBPACK_IMPORTED_MODULE_22__.checkWifNetwork)(secret, this.network);\n let wifResult = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_23__.decodePrivateKeyWif)(secret);\n if (typeof wifResult === \"string\") {\n throw Error(wifResult);\n }\n let resultData = wifResult;\n this.privateKey = resultData.privateKey;\n this.privateKeyWif = secret;\n this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Wif;\n await this.deriveInfo();\n return this;\n }\n async newRandom(name, dbName) {\n dbName = dbName ? dbName : this.networkPrefix;\n return super.newRandom(name, dbName);\n }\n async named(name, dbName, forceNew = false) {\n dbName = dbName ? dbName : this.networkPrefix;\n return super.named(name, dbName, forceNew);\n }\n async replaceNamed(name, walletId, dbName) {\n dbName = dbName ? dbName : this.networkPrefix;\n return super.replaceNamed(name, walletId, dbName);\n }\n async namedExists(name, dbName) {\n dbName = dbName ? dbName : this.networkPrefix;\n return super.namedExists(name, dbName);\n }\n //#endregion Protected Implementations\n //#region Serialization\n // Returns the serialized wallet as a string\n // If storing in a database, set asNamed to false to store secrets\n // In all other cases, the a named wallet is deserialized from the database\n // by the name key\n toString() {\n const result = super.toString();\n if (result)\n return result;\n if (this.walletType === _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Wif) {\n return `${this.walletType}:${this.network}:${this.privateKeyWif}`;\n }\n throw Error(\"toString unsupported wallet type\");\n }\n //\n toDbString() {\n const result = super.toDbString();\n if (result)\n return result;\n if (this.walletType === _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Wif) {\n return `${this.walletType}:${this.network}:${this.privateKeyWif}`;\n }\n throw Error(\"toDbString unsupported wallet type\");\n }\n //#endregion Serialization\n //#region Funds\n //\n async getAddressUtxos(address) {\n if (!address) {\n address = this.cashaddr;\n }\n if (this._slpAware) {\n const [bchUtxos, slpOutpoints] = await Promise.all([\n this.provider.getUtxos(address),\n this.slp.getSlpOutpoints(),\n ]);\n return bchUtxos.filter((bchutxo) => slpOutpoints.findIndex((slpOutpoint) => `${bchutxo.txid}:${bchutxo.vout}` === slpOutpoint) === -1);\n }\n else if (this._slpSemiAware) {\n const bchUtxos = await this.provider.getUtxos(address);\n return bchUtxos.filter((bchutxo) => bchutxo.satoshis > _constant_js__WEBPACK_IMPORTED_MODULE_19__.DUST_UTXO_THRESHOLD);\n }\n else {\n return await this.provider.getUtxos(address);\n }\n }\n /**\n * utxos Get unspent outputs for the wallet\n *\n */\n async getUtxos() {\n if (!this.cashaddr) {\n throw Error(\"Attempted to get utxos without an address\");\n }\n return await this.getAddressUtxos(this.cashaddr);\n }\n // gets wallet balance in sats, bch and usd\n async getBalance(rawUnit, usdPriceCache = true) {\n if (rawUnit) {\n const unit = (0,_util_sanitizeUnit_js__WEBPACK_IMPORTED_MODULE_24__.sanitizeUnit)(rawUnit);\n return await (0,_util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_25__.balanceFromSatoshi)(await this.getBalanceFromProvider(), unit, usdPriceCache);\n }\n else {\n return await (0,_util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_25__.balanceResponseFromSatoshi)(await this.getBalanceFromProvider(), usdPriceCache);\n }\n }\n // Gets balance by summing value in all utxos in stats\n async getBalanceFromUtxos() {\n const utxos = (await this.getAddressUtxos(this.cashaddr)).filter((val) => val.token === undefined);\n return (0,_util_sumUtxoValue_js__WEBPACK_IMPORTED_MODULE_26__.sumUtxoValue)(utxos);\n }\n // Gets balance from fulcrum\n async getBalanceFromProvider() {\n // Fulcrum reports balance of all utxos, including tokens, which is undesirable\n // // TODO not sure why getting the balance from a provider doesn't work\n // if (this._slpAware || this._slpSemiAware) {\n // return await this.getBalanceFromUtxos();\n // } else {\n // return await this.provider!.getBalance(this.cashaddr!);\n // }\n // FIXME\n return this.getBalanceFromUtxos();\n }\n // watching for any transaction hash of this wallet\n watchAddress(callback) {\n return this.provider.watchAddress(this.getDepositAddress(), callback);\n }\n // watching for any transaction of this wallet\n watchAddressTransactions(callback) {\n return this.provider.watchAddressTransactions(this.getDepositAddress(), callback);\n }\n // watching for cashtoken transaction of this wallet\n watchAddressTokenTransactions(callback) {\n return this.provider.watchAddressTokenTransactions(this.getDepositAddress(), callback);\n }\n // sets up a callback to be called upon wallet's balance change\n // can be cancelled by calling the function returned from this one\n watchBalance(callback) {\n return this.provider.watchAddressStatus(this.getDepositAddress(), async (_status) => {\n const balance = (await this.getBalance());\n callback(balance);\n });\n }\n // sets up a callback to be called upon wallet's BCH or USD balance change\n // if BCH balance does not change, the callback will be triggered every\n // @param `usdPriceRefreshInterval` milliseconds by polling for new BCH USD price\n // Since we want to be most sensitive to usd value change, we do not use the cached exchange rates\n // can be cancelled by calling the function returned from this one\n watchBalanceUsd(callback, usdPriceRefreshInterval = 30000) {\n let usdPrice = -1;\n const _callback = async () => {\n const balance = (await this.getBalance(undefined, false));\n if (usdPrice !== balance.usd) {\n usdPrice = balance.usd;\n callback(balance);\n }\n };\n const watchCancel = this.provider.watchAddressStatus(this.getDepositAddress(), _callback);\n const interval = setInterval(_callback, usdPriceRefreshInterval);\n return async () => {\n await watchCancel();\n clearInterval(interval);\n };\n }\n // waits for address balance to be greater than or equal to the target value\n // this call halts the execution\n async waitForBalance(value, rawUnit = _enum_js__WEBPACK_IMPORTED_MODULE_4__.UnitEnum.BCH) {\n return new Promise(async (resolve) => {\n const watchCancel = this.watchBalance(async (balance) => {\n const satoshiBalance = await (0,_util_amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_27__.amountInSatoshi)(value, rawUnit);\n if (balance.sat >= satoshiBalance) {\n await watchCancel();\n resolve(balance);\n }\n });\n });\n }\n // sets up a callback to be called upon wallet's token balance change\n // can be cancelled by calling the function returned from this one\n watchTokenBalance(tokenId, callback) {\n let previous = undefined;\n return this.provider.watchAddressStatus(this.getDepositAddress(), async (_status) => {\n const balance = await this.getTokenBalance(tokenId);\n if (previous != balance) {\n callback(balance);\n }\n previous = balance;\n });\n }\n // waits for address token balance to be greater than or equal to the target amount\n // this call halts the execution\n async waitForTokenBalance(tokenId, amount) {\n return new Promise(async (resolve) => {\n const watchCancel = this.watchTokenBalance(tokenId, async (balance) => {\n if (balance >= amount) {\n await watchCancel();\n resolve(balance);\n }\n });\n });\n }\n async getTokenInfo(tokenId) {\n return _Bcmr_js__WEBPACK_IMPORTED_MODULE_28__.BCMR.getTokenInfo(tokenId);\n }\n async _getMaxAmountToSend(params = {\n outputCount: 1,\n options: {},\n }) {\n if (!this.privateKey && params.options?.buildUnsigned !== true) {\n throw Error(\"Couldn't get network or private key for wallet.\");\n }\n if (!this.cashaddr) {\n throw Error(\"attempted to send without a cashaddr\");\n }\n if (params.options && params.options.slpAware) {\n this._slpAware = true;\n }\n if (params.options && params.options.slpSemiAware) {\n this._slpSemiAware = true;\n }\n let feePaidBy;\n if (params.options && params.options.feePaidBy) {\n feePaidBy = params.options.feePaidBy;\n }\n else {\n feePaidBy = _enum_js__WEBPACK_IMPORTED_MODULE_5__.FeePaidByEnum.change;\n }\n // get inputs\n let utxos;\n if (params.options && params.options.utxoIds) {\n utxos = params.options.utxoIds.map((utxoId) => typeof utxoId === \"string\" ? (0,_model_js__WEBPACK_IMPORTED_MODULE_20__.fromUtxoId)(utxoId) : utxoId);\n }\n else {\n utxos = (await this.getAddressUtxos(this.cashaddr)).filter((utxo) => !utxo.token);\n }\n // Get current height to assure recently mined coins are not spent.\n const bestHeight = await this.provider.getBlockHeight();\n // simulate outputs using the sender's address\n const sendRequest = new _model_js__WEBPACK_IMPORTED_MODULE_20__.SendRequest({\n cashaddr: this.cashaddr,\n value: 100,\n unit: \"sat\",\n });\n const sendRequests = Array(params.outputCount)\n .fill(0)\n .map(() => sendRequest);\n const fundingUtxos = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_29__.getSuitableUtxos)(utxos, undefined, bestHeight, feePaidBy, sendRequests);\n const relayFeePerByteInSatoshi = await (0,_network_getRelayFeeCache_js__WEBPACK_IMPORTED_MODULE_1__.getRelayFeeCache)(this.provider);\n const fee = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_29__.getFeeAmount)({\n utxos: fundingUtxos,\n sendRequests: sendRequests,\n privateKey: this.privateKey ?? Uint8Array.from([]),\n sourceAddress: this.cashaddr,\n relayFeePerByteInSatoshi: relayFeePerByteInSatoshi,\n slpOutputs: [],\n feePaidBy: feePaidBy,\n });\n const spendableAmount = (0,_util_sumUtxoValue_js__WEBPACK_IMPORTED_MODULE_26__.sumUtxoValue)(fundingUtxos);\n let result = spendableAmount - fee;\n if (result < 0) {\n result = 0;\n }\n return { value: result, utxos: fundingUtxos };\n }\n async getMaxAmountToSend(params = {\n outputCount: 1,\n options: {},\n }) {\n const { value: result } = await this._getMaxAmountToSend(params);\n return await (0,_util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_25__.balanceResponseFromSatoshi)(result);\n }\n /**\n * send Send some amount to an address\n * this function processes the send requests, encodes the transaction, sends it to the network\n * @returns (depending on the options parameter) the transaction id, new address balance and a link to the transaction on the blockchain explorer\n *\n * This is a first class function with REST analog, maintainers should strive to keep backward-compatibility\n *\n */\n async send(requests, options) {\n const { encodedTransaction, tokenIds, sourceOutputs } = await this.encodeTransaction(requests, undefined, options);\n const resp = new _model_js__WEBPACK_IMPORTED_MODULE_20__.SendResponse({});\n resp.tokenIds = tokenIds;\n if (options?.buildUnsigned !== true) {\n const txId = await this.submitTransaction(encodedTransaction, options?.awaitTransactionPropagation === undefined ||\n options?.awaitTransactionPropagation === true);\n resp.txId = txId;\n resp.explorerUrl = this.explorerUrl(resp.txId);\n if (options?.queryBalance === undefined ||\n options?.queryBalance === true) {\n resp.balance = (await this.getBalance());\n }\n }\n else {\n resp.unsignedTransaction = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.binToHex)(encodedTransaction);\n resp.sourceOutputs = sourceOutputs;\n }\n return resp;\n }\n /**\n * sendMax Send all available funds to a destination cash address\n *\n * @param {string} cashaddr destination cash address\n * @param {SendRequestOptionsI} options Options of the send requests\n *\n * @returns (depending on the options parameter) the transaction id, new address balance and a link to the transaction on the blockchain explorer\n */\n async sendMax(cashaddr, options) {\n return await this.sendMaxRaw(cashaddr, options);\n }\n /**\n * sendMaxRaw (internal) Send all available funds to a destination cash address\n *\n * @param {string} cashaddr destination cash address\n * @param {SendRequestOptionsI} options Options of the send requests\n *\n * @returns the transaction id sent to the network\n */\n async sendMaxRaw(cashaddr, options) {\n const { value: maxSpendableAmount, utxos } = await this._getMaxAmountToSend({\n outputCount: 1,\n options: options,\n });\n if (!options) {\n options = {};\n }\n options.utxoIds = utxos;\n const sendRequest = new _model_js__WEBPACK_IMPORTED_MODULE_20__.SendRequest({\n cashaddr: cashaddr,\n value: maxSpendableAmount,\n unit: \"sat\",\n });\n const { encodedTransaction, tokenIds, sourceOutputs } = await this.encodeTransaction([sendRequest], true, options);\n const resp = new _model_js__WEBPACK_IMPORTED_MODULE_20__.SendResponse({});\n resp.tokenIds = tokenIds;\n if (options?.buildUnsigned !== true) {\n const txId = await this.submitTransaction(encodedTransaction, options?.awaitTransactionPropagation === undefined ||\n options?.awaitTransactionPropagation === true);\n resp.txId = txId;\n resp.explorerUrl = this.explorerUrl(resp.txId);\n if (options?.queryBalance === undefined ||\n options?.queryBalance === true) {\n resp.balance = (await this.getBalance());\n }\n }\n else {\n resp.unsignedTransaction = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.binToHex)(encodedTransaction);\n resp.sourceOutputs = sourceOutputs;\n }\n return resp;\n }\n /**\n * encodeTransaction Encode and sign a transaction given a list of sendRequests, options and estimate fees.\n * @param {SendRequest[]} sendRequests SendRequests\n * @param {boolean} discardChange=false\n * @param {SendRequestOptionsI} options Options of the send requests\n */\n async encodeTransaction(requests, discardChange = false, options) {\n let sendRequests = (0,_util_asSendRequestObject_js__WEBPACK_IMPORTED_MODULE_30__.asSendRequestObject)(requests);\n if (!this.privateKey && options?.buildUnsigned !== true) {\n throw new Error(`Wallet ${this.name} is missing either a network or private key`);\n }\n if (!this.cashaddr) {\n throw Error(\"attempted to send without a cashaddr\");\n }\n if (options && options.slpAware) {\n this._slpAware = true;\n }\n if (options && options.slpSemiAware) {\n this._slpSemiAware = true;\n }\n let feePaidBy;\n if (options && options.feePaidBy) {\n feePaidBy = options.feePaidBy;\n }\n else {\n feePaidBy = _enum_js__WEBPACK_IMPORTED_MODULE_5__.FeePaidByEnum.change;\n }\n let changeAddress;\n if (options && options.changeAddress) {\n changeAddress = options.changeAddress;\n }\n else {\n changeAddress = \"\";\n }\n let checkTokenQuantities = true;\n if (options && options.checkTokenQuantities === false) {\n checkTokenQuantities = false;\n }\n // get inputs from options or query all inputs\n let utxos;\n if (options && options.utxoIds) {\n utxos = options.utxoIds.map((utxoId) => typeof utxoId === \"string\" ? (0,_model_js__WEBPACK_IMPORTED_MODULE_20__.fromUtxoId)(utxoId) : utxoId);\n }\n else {\n utxos = await this.getAddressUtxos(this.cashaddr);\n }\n // filter out token utxos if there are no token requests\n if (checkTokenQuantities &&\n !sendRequests.some((val) => val instanceof _model_js__WEBPACK_IMPORTED_MODULE_20__.TokenSendRequest)) {\n utxos = utxos.filter((val) => !val.token);\n }\n const addTokenChangeOutputs = (inputs, outputs) => {\n // allow for implicit token burn if the total amount sent is less than user had\n // allow for token genesis, creating more tokens than we had before (0)\n if (!checkTokenQuantities) {\n return;\n }\n const allTokenInputs = inputs.filter((val) => val.token);\n const allTokenOutputs = outputs.filter((val) => val instanceof _model_js__WEBPACK_IMPORTED_MODULE_20__.TokenSendRequest);\n const tokenIds = allTokenOutputs\n .map((val) => val.tokenId)\n .filter((val, idx, arr) => arr.indexOf(val) === idx);\n for (let tokenId of tokenIds) {\n const tokenInputs = allTokenInputs.filter((val) => val.token?.tokenId === tokenId);\n const inputAmountSum = tokenInputs.reduce((prev, cur) => prev + cur.token.amount, 0);\n const tokenOutputs = allTokenOutputs.filter((val) => val.tokenId === tokenId);\n const outputAmountSum = tokenOutputs.reduce((prev, cur) => prev + cur.amount, 0);\n const change = inputAmountSum - outputAmountSum;\n if (change < 0) {\n throw new Error(\"Not enough token amount to send\");\n }\n if (change > 0) {\n outputs.push(new _model_js__WEBPACK_IMPORTED_MODULE_20__.TokenSendRequest({\n cashaddr: changeAddress || this.tokenaddr,\n amount: change,\n tokenId: tokenId,\n commitment: tokenOutputs[0].commitment,\n capability: tokenOutputs[0].capability,\n value: tokenOutputs[0].value,\n }));\n }\n }\n };\n addTokenChangeOutputs(utxos, sendRequests);\n const bestHeight = await this.provider.getBlockHeight();\n const spendAmount = await (0,_util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_31__.sumSendRequestAmounts)(sendRequests);\n if (utxos.length === 0) {\n throw Error(\"There were no Unspent Outputs\");\n }\n if (typeof spendAmount !== \"bigint\") {\n throw Error(\"Couldn't get spend amount when building transaction\");\n }\n const relayFeePerByteInSatoshi = await (0,_network_getRelayFeeCache_js__WEBPACK_IMPORTED_MODULE_1__.getRelayFeeCache)(this.provider);\n const feeEstimate = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_29__.getFeeAmount)({\n utxos: utxos,\n sendRequests: sendRequests,\n privateKey: this.privateKey ?? Uint8Array.from([]),\n sourceAddress: this.cashaddr,\n relayFeePerByteInSatoshi: relayFeePerByteInSatoshi,\n slpOutputs: [],\n feePaidBy: feePaidBy,\n });\n const fundingUtxos = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_29__.getSuitableUtxos)(utxos, BigInt(spendAmount) + BigInt(feeEstimate), bestHeight, feePaidBy, sendRequests, options?.ensureUtxos || [], options?.tokenOperation);\n if (fundingUtxos.length === 0) {\n throw Error(\"The available inputs couldn't satisfy the request with fees\");\n }\n const fee = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_29__.getFeeAmount)({\n utxos: fundingUtxos,\n sendRequests: sendRequests,\n privateKey: this.privateKey ?? Uint8Array.from([]),\n sourceAddress: this.cashaddr,\n relayFeePerByteInSatoshi: relayFeePerByteInSatoshi,\n slpOutputs: [],\n feePaidBy: feePaidBy,\n });\n const { encodedTransaction, sourceOutputs } = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_29__.buildEncodedTransaction)({\n inputs: fundingUtxos,\n outputs: sendRequests,\n signingKey: this.privateKey ?? Uint8Array.from([]),\n sourceAddress: this.cashaddr,\n fee,\n discardChange,\n slpOutputs: [],\n feePaidBy,\n changeAddress,\n buildUnsigned: options?.buildUnsigned === true,\n });\n const tokenIds = [\n ...fundingUtxos\n .filter((val) => val.token?.tokenId)\n .map((val) => val.token.tokenId),\n ...sendRequests\n .filter((val) => val instanceof _model_js__WEBPACK_IMPORTED_MODULE_20__.TokenSendRequest)\n .map((val) => val.tokenId),\n ].filter((value, index, array) => array.indexOf(value) === index);\n return { encodedTransaction, tokenIds, sourceOutputs };\n }\n async signUnsignedTransaction(transaction, sourceOutputs) {\n if (!this.privateKey) {\n throw Error(\"Can not sign a transaction with watch-only wallet.\");\n }\n return (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_29__.signUnsignedTransaction)(transaction, sourceOutputs, this.privateKey);\n }\n // Submit a raw transaction\n async submitTransaction(transaction, awaitPropagation = true) {\n if (!this.provider) {\n throw Error(\"Wallet network provider was not initialized\");\n }\n let rawTransaction = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.binToHex)(transaction);\n return await this.provider.sendRawTransaction(rawTransaction, awaitPropagation);\n }\n // gets transaction history of this wallet\n async getRawHistory() {\n return await this.provider.getHistory(this.cashaddr);\n }\n // gets transaction history of this wallet\n async getHistory(unit, start, count, collapseChange) {\n return (0,_history_electrumTransformer_js__WEBPACK_IMPORTED_MODULE_32__.getAddressHistory)(this.cashaddr, this.provider, unit, start, count, collapseChange);\n }\n // gets last transaction of this wallet\n async getLastTransaction(confirmedOnly = false) {\n let history = await this.getRawHistory();\n if (confirmedOnly) {\n history = history.filter((val) => val.height > 0);\n }\n if (!history.length) {\n return null;\n }\n const [lastTx] = history.slice(-1);\n return this.provider.getRawTransactionObject(lastTx.tx_hash);\n }\n // waits for next transaction, program execution is halted\n async waitForTransaction(options = {\n getTransactionInfo: true,\n getBalance: false,\n txHash: undefined,\n }) {\n if (options.getTransactionInfo === undefined) {\n options.getTransactionInfo = true;\n }\n return new Promise(async (resolve) => {\n let txHashSeen = false;\n const makeResponse = async (txHash) => {\n const response = {};\n const promises = [undefined, undefined];\n if (options.getBalance === true) {\n promises[0] = this.getBalance();\n }\n if (options.getTransactionInfo === true) {\n if (!txHash) {\n promises[1] = this.getLastTransaction();\n }\n else {\n promises[1] = this.provider.getRawTransactionObject(txHash);\n }\n }\n const result = await Promise.all(promises);\n response.balance = result[0];\n response.transactionInfo = result[1];\n return response;\n };\n // waiting for a specific transaction to propagate\n if (options.txHash) {\n const waitForTransactionCallback = async (data) => {\n if (data && data[0] === options.txHash) {\n txHashSeen = true;\n this.provider.unsubscribeFromTransaction(options.txHash, waitForTransactionCallback);\n resolve(makeResponse(options.txHash));\n }\n };\n this.provider.subscribeToTransaction(options.txHash, waitForTransactionCallback);\n return;\n }\n // waiting for any address transaction\n const watchCancel = this.provider.watchAddressStatus(this.getDepositAddress(), async (_status) => {\n watchCancel();\n resolve(makeResponse());\n });\n });\n }\n /**\n * watchBlocks Watch network blocks\n *\n * @param callback callback with a block header object\n *\n * @returns a function which will cancel watching upon evaluation\n */\n watchBlocks(callback) {\n return this.provider.watchBlocks(callback);\n }\n /**\n * waitForBlock Wait for a network block\n *\n * @param height if specified waits for this exact blockchain height, otherwise resolves with the next block\n *\n */\n async waitForBlock(height) {\n return this.provider.waitForBlock(height);\n }\n //#endregion Funds\n //#region Private implementation details\n async deriveInfo() {\n const publicKey = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_33__.secp256k1.derivePublicKeyUncompressed(this.privateKey);\n if (typeof publicKey === \"string\") {\n throw new Error(publicKey);\n }\n this.publicKey = publicKey;\n const publicKeyCompressed = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_33__.secp256k1.derivePublicKeyCompressed(this.privateKey);\n if (typeof publicKeyCompressed === \"string\") {\n throw new Error(publicKeyCompressed);\n }\n this.publicKeyCompressed = publicKeyCompressed;\n const networkType = this.network === _enum_js__WEBPACK_IMPORTED_MODULE_4__.NetworkType.Regtest ? _enum_js__WEBPACK_IMPORTED_MODULE_4__.NetworkType.Testnet : this.network;\n this.privateKeyWif = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_23__.encodePrivateKeyWif)(this.privateKey, networkType);\n (0,_util_checkWifNetwork_js__WEBPACK_IMPORTED_MODULE_22__.checkWifNetwork)(this.privateKeyWif, this.network);\n this.cashaddr = (0,_util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_21__.deriveCashaddr)(this.privateKey, this.networkPrefix);\n this.tokenaddr = (0,_util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_21__.deriveTokenaddr)(this.privateKey, this.networkPrefix);\n this.address = this.cashaddr;\n this.publicKeyHash = (0,_util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_12__.derivePublicKeyHash)(this.cashaddr);\n return this;\n }\n //#endregion Private implementation details\n //#region Signing\n // Convenience wrapper to sign interface\n async sign(message) {\n return await Wallet.signedMessage.sign(message, this.privateKey);\n }\n // Convenience wrapper to verify interface\n async verify(message, sig, publicKey) {\n return await Wallet.signedMessage.verify(message, sig, this.cashaddr, publicKey);\n }\n //#endregion Signing\n //#region Cashtokens\n /**\n * Create new cashtoken, both funglible and/or non-fungible (NFT)\n * Refer to spec https://github.com/bitjson/cashtokens\n * @param {number} genesisRequest.amount amount of *fungible* tokens to create\n * @param {NFTCapability?} genesisRequest.capability capability of new NFT\n * @param {string?} genesisRequest.commitment NFT commitment message\n * @param {string?} genesisRequest.cashaddr cash address to send the created token UTXO to; if undefined will default to your address\n * @param {number?} genesisRequest.value satoshi value to send alongside with tokens; if undefined will default to 1000 satoshi\n * @param {SendRequestType | SendRequestType[]} sendRequests single or an array of extra send requests (OP_RETURN, value transfer, etc.) to include in genesis transaction\n * @param {SendRequestOptionsI} options Options of the send requests\n */\n async tokenGenesis(genesisRequest, sendRequests = [], options) {\n if (!Array.isArray(sendRequests)) {\n sendRequests = [sendRequests];\n }\n let utxos;\n if (options && options.utxoIds) {\n utxos = options.utxoIds.map((utxoId) => typeof utxoId === \"string\" ? (0,_model_js__WEBPACK_IMPORTED_MODULE_20__.fromUtxoId)(utxoId) : utxoId);\n }\n else {\n utxos = await this.getAddressUtxos(this.cashaddr);\n }\n const genesisInputs = utxos.filter((val) => val.vout === 0 && !val.token);\n if (genesisInputs.length === 0) {\n throw new Error(\"No suitable inputs with vout=0 available for new token genesis\");\n }\n const genesisSendRequest = new _model_js__WEBPACK_IMPORTED_MODULE_20__.TokenSendRequest({\n cashaddr: genesisRequest.cashaddr || this.tokenaddr,\n amount: genesisRequest.amount,\n value: genesisRequest.value || 1000,\n capability: genesisRequest.capability,\n commitment: genesisRequest.commitment,\n tokenId: genesisInputs[0].txid,\n });\n return this.send([genesisSendRequest, ...sendRequests], {\n ...options,\n utxoIds: utxos,\n ensureUtxos: [genesisInputs[0]],\n checkTokenQuantities: false,\n queryBalance: false,\n tokenOperation: \"genesis\",\n });\n }\n /**\n * Mint new NFT cashtokens using an existing minting token\n * Refer to spec https://github.com/bitjson/cashtokens\n * @param {string} tokenId tokenId of an NFT to mint\n * @param {TokenMintRequest | TokenMintRequest[]} mintRequests mint requests with new token properties and recipients\n * @param {NFTCapability?} mintRequest.capability capability of new NFT\n * @param {string?} mintRequest.commitment NFT commitment message\n * @param {string?} mintRequest.cashaddr cash address to send the created token UTXO to; if undefined will default to your address\n * @param {number?} mintRequest.value satoshi value to send alongside with tokens; if undefined will default to 1000 satoshi\n * @param {boolean?} deductTokenAmount if minting token contains fungible amount, deduct from it by amount of minted tokens\n * @param {SendRequestOptionsI} options Options of the send requests\n */\n async tokenMint(tokenId, mintRequests, deductTokenAmount = false, options) {\n if (tokenId?.length !== 64) {\n throw Error(`Invalid tokenId supplied: ${tokenId}`);\n }\n if (!Array.isArray(mintRequests)) {\n mintRequests = [mintRequests];\n }\n const utxos = await this.getAddressUtxos(this.cashaddr);\n const nftUtxos = utxos.filter((val) => val.token?.tokenId === tokenId &&\n val.token?.capability === _interface_js__WEBPACK_IMPORTED_MODULE_8__.NFTCapability.minting);\n if (!nftUtxos.length) {\n throw new Error(\"You do not have any token UTXOs with minting capability for specified tokenId\");\n }\n const newAmount = deductTokenAmount && nftUtxos[0].token.amount > 0\n ? nftUtxos[0].token.amount - mintRequests.length\n : nftUtxos[0].token.amount;\n const safeNewAmount = Math.max(0, newAmount);\n const mintingInput = new _model_js__WEBPACK_IMPORTED_MODULE_20__.TokenSendRequest({\n cashaddr: this.tokenaddr,\n tokenId: tokenId,\n capability: nftUtxos[0].token.capability,\n commitment: nftUtxos[0].token.commitment,\n amount: safeNewAmount,\n value: nftUtxos[0].satoshis,\n });\n return this.send([\n mintingInput,\n ...mintRequests.map((val) => new _model_js__WEBPACK_IMPORTED_MODULE_20__.TokenSendRequest({\n cashaddr: val.cashaddr || this.tokenaddr,\n amount: 0,\n tokenId: tokenId,\n value: val.value,\n capability: val.capability,\n commitment: val.commitment,\n })),\n ], {\n ...options,\n ensureUtxos: [nftUtxos[0]],\n checkTokenQuantities: false,\n queryBalance: false,\n tokenOperation: \"mint\",\n });\n }\n /**\n * Perform an explicit token burning by spending a token utxo to an OP_RETURN\n *\n * Behaves differently for fungible and non-fungible tokens:\n * * NFTs are always \"destroyed\"\n * * FTs' amount is reduced by the amount specified, if 0 FT amount is left and no NFT present, the token is \"destroyed\"\n *\n * Refer to spec https://github.com/bitjson/cashtokens\n * @param {string} burnRequest.tokenId tokenId of a token to burn\n * @param {NFTCapability} burnRequest.capability capability of the NFT token to select, optional\n * @param {string?} burnRequest.commitment commitment of the NFT token to select, optional\n * @param {number?} burnRequest.amount amount of fungible tokens to burn, optional\n * @param {string?} burnRequest.cashaddr address to return token and satoshi change to\n * @param {string?} message optional message to include in OP_RETURN\n * @param {SendRequestOptionsI} options Options of the send requests\n */\n async tokenBurn(burnRequest, message, options) {\n if (burnRequest.tokenId?.length !== 64) {\n throw Error(`Invalid tokenId supplied: ${burnRequest.tokenId}`);\n }\n const utxos = await this.getAddressUtxos(this.cashaddr);\n const tokenUtxos = utxos.filter((val) => val.token?.tokenId === burnRequest.tokenId &&\n val.token?.capability === burnRequest.capability &&\n val.token?.commitment === burnRequest.commitment);\n if (!tokenUtxos.length) {\n throw new Error(\"You do not have suitable token UTXOs to perform burn\");\n }\n const totalFungibleAmount = tokenUtxos.reduce((prev, cur) => prev + (cur.token?.amount || 0), 0);\n const fungibleBurnAmount = burnRequest.amount && burnRequest.amount > 0 ? burnRequest.amount : 0;\n const hasNFT = burnRequest.capability || burnRequest.commitment;\n let utxoIds = [];\n let changeSendRequests;\n if (hasNFT) {\n // does not have FT tokens, let us destroy the token completely\n if (totalFungibleAmount === 0) {\n changeSendRequests = [];\n utxoIds.push(tokenUtxos[0]);\n }\n else {\n // add utxos to spend from\n let available = 0;\n for (const token of tokenUtxos.filter((val) => val.token?.amount)) {\n utxoIds.push(token);\n available += token.token?.amount;\n if (available >= fungibleBurnAmount) {\n break;\n }\n }\n // if there are FT, reduce their amount\n const newAmount = totalFungibleAmount - fungibleBurnAmount;\n const safeNewAmount = Math.max(0, newAmount);\n changeSendRequests = [\n new _model_js__WEBPACK_IMPORTED_MODULE_20__.TokenSendRequest({\n cashaddr: burnRequest.cashaddr || this.tokenaddr,\n tokenId: burnRequest.tokenId,\n capability: burnRequest.capability,\n commitment: burnRequest.commitment,\n amount: safeNewAmount,\n value: tokenUtxos[0].satoshis,\n }),\n ];\n }\n }\n else {\n // if we are burning last fughible tokens, let us destroy the token completely\n if (totalFungibleAmount === fungibleBurnAmount) {\n changeSendRequests = [];\n utxoIds.push(tokenUtxos[0]);\n }\n else {\n // add utxos to spend from\n let available = 0;\n for (const token of tokenUtxos.filter((val) => val.token?.amount)) {\n utxoIds.push(token);\n available += token.token?.amount;\n if (available >= fungibleBurnAmount) {\n break;\n }\n }\n // reduce the FT amount\n const newAmount = totalFungibleAmount - fungibleBurnAmount;\n const safeNewAmount = Math.max(0, newAmount);\n changeSendRequests = [\n new _model_js__WEBPACK_IMPORTED_MODULE_20__.TokenSendRequest({\n cashaddr: burnRequest.cashaddr || this.tokenaddr,\n tokenId: burnRequest.tokenId,\n amount: safeNewAmount,\n value: tokenUtxos[0].satoshis,\n }),\n ];\n }\n }\n const opReturn = _model_js__WEBPACK_IMPORTED_MODULE_20__.OpReturnData.fromString(message || \"\");\n return this.send([opReturn, ...changeSendRequests], {\n ...options,\n checkTokenQuantities: false,\n queryBalance: false,\n ensureUtxos: utxoIds.length > 0 ? utxoIds : undefined,\n tokenOperation: \"burn\",\n });\n }\n /**\n * getTokenUtxos Get unspent token outputs for the wallet\n * will return utxos only for the specified token if `tokenId` provided\n * @param {string?} tokenId tokenId (category) to filter utxos by, if not set will return utxos from all tokens\n * @returns {UtxoI[]} token utxos\n */\n async getTokenUtxos(tokenId) {\n const utxos = await this.getAddressUtxos(this.address);\n return utxos.filter((val) => tokenId ? val.token?.tokenId === tokenId : val.token);\n }\n /**\n * getTokenBalance Gets fungible token balance\n * for NFT token balance see @ref getNftTokenBalance\n * @param {string} tokenId tokenId to get balance for\n * @returns {number} fungible token balance\n */\n async getTokenBalance(tokenId) {\n const utxos = (await this.getTokenUtxos(tokenId)).filter((val) => val.token?.amount);\n return (0,_util_sumUtxoValue_js__WEBPACK_IMPORTED_MODULE_26__.sumTokenAmounts)(utxos, tokenId);\n }\n /**\n * getNftTokenBalance Gets non-fungible token (NFT) balance for a particula tokenId\n * disregards fungible token balances\n * for fungible token balance see @ref getTokenBalance\n * @param {string} tokenId tokenId to get balance for\n * @returns {number} non-fungible token balance\n */\n async getNftTokenBalance(tokenId) {\n const utxos = (await this.getTokenUtxos(tokenId)).filter((val) => val.token?.commitment !== undefined);\n return utxos.length;\n }\n /**\n * getAllTokenBalances Gets all fungible token balances in this wallet\n * @returns {Object} a map [tokenId => balance] for all tokens in this wallet\n */\n async getAllTokenBalances() {\n const result = {};\n const utxos = (await this.getTokenUtxos()).filter((val) => val.token?.amount);\n for (const utxo of utxos) {\n if (!result[utxo.token.tokenId]) {\n result[utxo.token.tokenId] = 0;\n }\n result[utxo.token.tokenId] += utxo.token.amount;\n }\n return result;\n }\n /**\n * getAllNftTokenBalances Gets all non-fungible token (NFT) balances in this wallet\n * @returns {Object} a map [tokenId => balance] for all NFTs in this wallet\n */\n async getAllNftTokenBalances() {\n const result = {};\n const utxos = (await this.getTokenUtxos()).filter((val) => val.token?.commitment !== undefined);\n for (const utxo of utxos) {\n if (!result[utxo.token.tokenId]) {\n result[utxo.token.tokenId] = 0;\n }\n result[utxo.token.tokenId] += 1;\n }\n return result;\n }\n}\nWallet.signedMessage = new _message_index_js__WEBPACK_IMPORTED_MODULE_34__.SignedMessage();\n/**\n * Class to manage a testnet wallet.\n */\nclass TestNetWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_4__.NetworkType.Testnet);\n }\n // will receive 10000 testnet satoshi, rate limits apply\n async getTestnetSatoshis() {\n try {\n const response = await axios__WEBPACK_IMPORTED_MODULE_2___default().post(`${TestNetWallet.faucetServer}/faucet/get_testnet_bch`, { cashaddr: this.cashaddr });\n const data = response.data;\n return data.txId;\n }\n catch (e) {\n // console.log(e);\n // console.log(e.response ? e.response.data : \"\");\n throw e;\n }\n }\n // be nice and return them back\n async returnTestnetSatoshis() {\n try {\n const response = await axios__WEBPACK_IMPORTED_MODULE_2___default().post(`${TestNetWallet.faucetServer}/faucet/get_addresses`);\n const data = response.data;\n return await this.slpAware().sendMax(data.bchtest);\n }\n catch (e) {\n console.log(e);\n console.log(e.response ? e.response.data : \"\");\n throw e;\n }\n }\n // will receive 10 testnet tokens, rate limits apply\n async getTestnetSlp(tokenId) {\n try {\n const response = await axios__WEBPACK_IMPORTED_MODULE_2___default().post(`${TestNetWallet.faucetServer}/faucet/get_testnet_slp`, { slpaddr: this.slp.slpaddr, tokenId: tokenId });\n const data = response.data;\n return data.txId;\n }\n catch (e) {\n //console.log(e);\n //console.log(e.response ? e.response.data : \"\");\n throw e;\n }\n }\n // be nice and return them back\n async returnTestnetSlp(tokenId) {\n try {\n const response = await axios__WEBPACK_IMPORTED_MODULE_2___default().post(`${TestNetWallet.faucetServer}/faucet/get_addresses`);\n const data = response.data;\n return await this.slp.sendMax(data.slptest, tokenId);\n }\n catch (e) {\n console.log(e);\n console.log(e.response ? e.response.data : \"\");\n throw e;\n }\n }\n // interface to static slp functions. see Slp.ts\n static get slp() {\n return _Slp_js__WEBPACK_IMPORTED_MODULE_6__.TestNetSlp;\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_7__.TestNetUtil;\n }\n}\nTestNetWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_35__.CashAddressNetworkPrefix.testnet;\nTestNetWallet.faucetServer = \"https://rest-unstable.mainnet.cash\";\n/**\n * Class to manage a regtest wallet.\n */\nclass RegTestWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_4__.NetworkType.Regtest);\n }\n // interface to static slp functions. see Slp.ts\n static get slp() {\n return _Slp_js__WEBPACK_IMPORTED_MODULE_6__.RegTestSlp;\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_7__.RegTestUtil;\n }\n}\nRegTestWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_35__.CashAddressNetworkPrefix.regtest;\n/**\n * Class to manage a bitcoin cash wif wallet.\n */\nclass WifWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_4__.NetworkType.Mainnet, _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Wif);\n }\n // interface to static slp functions. see Slp.ts\n static get slp() {\n return _Slp_js__WEBPACK_IMPORTED_MODULE_6__.WifSlp;\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_7__.WifUtil;\n }\n}\nWifWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_35__.CashAddressNetworkPrefix.mainnet;\nWifWallet.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Wif;\n/**\n * Class to manage a testnet wif wallet.\n */\nclass TestNetWifWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_4__.NetworkType.Testnet, _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Wif);\n }\n // interface to static slp functions. see Slp.ts\n static get slp() {\n return _Slp_js__WEBPACK_IMPORTED_MODULE_6__.TestNetWifSlp;\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_7__.TestNetWifUtil;\n }\n}\nTestNetWifWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_35__.CashAddressNetworkPrefix.testnet;\nTestNetWifWallet.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Wif;\n/**\n * Class to manage a regtest wif wallet.\n */\nclass RegTestWifWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_4__.NetworkType.Regtest, _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Wif);\n }\n // interface to static slp functions. see Slp.ts\n static get slp() {\n return _Slp_js__WEBPACK_IMPORTED_MODULE_6__.RegTestWifSlp;\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_7__.RegTestWifUtil;\n }\n}\nRegTestWifWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_35__.CashAddressNetworkPrefix.regtest;\nRegTestWifWallet.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Wif;\n/**\n * Class to manage a bitcoin cash watch wallet.\n */\nclass WatchWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_4__.NetworkType.Mainnet, _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Watch);\n }\n // interface to static slp functions. see Slp.ts\n static get slp() {\n return _Slp_js__WEBPACK_IMPORTED_MODULE_6__.WatchSlp;\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_7__.WatchUtil;\n }\n}\nWatchWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_35__.CashAddressNetworkPrefix.mainnet;\nWatchWallet.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Watch;\n/**\n * Class to manage a testnet watch wallet.\n */\nclass TestNetWatchWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_4__.NetworkType.Testnet, _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Watch);\n }\n // interface to static slp functions. see Slp.ts\n static get slp() {\n return _Slp_js__WEBPACK_IMPORTED_MODULE_6__.TestNetWatchSlp;\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_7__.TestNetWatchUtil;\n }\n}\nTestNetWatchWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_35__.CashAddressNetworkPrefix.testnet;\nTestNetWatchWallet.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Watch;\n/**\n * Class to manage a regtest watch wallet.\n */\nclass RegTestWatchWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_4__.NetworkType.Regtest, _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Watch);\n }\n // interface to static slp functions. see Slp.ts\n static get slp() {\n return _Slp_js__WEBPACK_IMPORTED_MODULE_6__.RegTestWatchSlp;\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_7__.RegTestWatchUtil;\n }\n}\nRegTestWatchWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_35__.CashAddressNetworkPrefix.regtest;\nRegTestWatchWallet.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_5__.WalletTypeEnum.Watch;\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/wallet/Wif.ts?");
|
|
1668
1668
|
|
|
1669
1669
|
/***/ }),
|
|
1670
1670
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { Compiler, AnyCompilerConfiguration, AuthenticationProgramStateCommon, CompilationContextBCH, Output } from "@bitauth/libauth";
|
|
1
|
+
import { Compiler, AnyCompilerConfiguration, AuthenticationProgramStateCommon, CompilationContextBCH, Output, Input } from "@bitauth/libauth";
|
|
2
2
|
import { UtxoI } from "../interface.js";
|
|
3
|
-
import { OpReturnData, SendRequest, SendRequestType, TokenSendRequest } from "../wallet/model.js";
|
|
3
|
+
import { OpReturnData, SendRequest, SendRequestType, SourceOutput, TokenSendRequest } from "../wallet/model.js";
|
|
4
4
|
import { FeePaidByEnum } from "../wallet/enum.js";
|
|
5
5
|
export declare function buildP2pkhNonHdTransaction({ inputs, outputs, signingKey, sourceAddress, fee, discardChange, slpOutputs, feePaidBy, changeAddress, }: {
|
|
6
6
|
inputs: UtxoI[];
|
|
@@ -13,7 +13,7 @@ export declare function buildP2pkhNonHdTransaction({ inputs, outputs, signingKey
|
|
|
13
13
|
feePaidBy?: FeePaidByEnum;
|
|
14
14
|
changeAddress?: string;
|
|
15
15
|
}): Promise<{
|
|
16
|
-
transaction: import("@bitauth/libauth").TransactionCommon<
|
|
16
|
+
transaction: import("@bitauth/libauth").TransactionCommon<Input<Uint8Array, Uint8Array>, Output<Uint8Array, Uint8Array>>;
|
|
17
17
|
sourceOutputs: any[];
|
|
18
18
|
}>;
|
|
19
19
|
export declare function prepareInputs({ inputs, compiler, signingKey, sourceAddress, }: {
|
|
@@ -65,7 +65,7 @@ export declare function getFeeAmount({ utxos, sendRequests, privateKey, sourceAd
|
|
|
65
65
|
feePaidBy: FeePaidByEnum;
|
|
66
66
|
discardChange?: boolean;
|
|
67
67
|
}): Promise<number>;
|
|
68
|
-
export declare function buildEncodedTransaction({ inputs, outputs, signingKey, sourceAddress, fee, discardChange, slpOutputs, feePaidBy, changeAddress, }: {
|
|
68
|
+
export declare function buildEncodedTransaction({ inputs, outputs, signingKey, sourceAddress, fee, discardChange, slpOutputs, feePaidBy, changeAddress, buildUnsigned, }: {
|
|
69
69
|
inputs: UtxoI[];
|
|
70
70
|
outputs: Array<SendRequest | TokenSendRequest | OpReturnData>;
|
|
71
71
|
signingKey: Uint8Array;
|
|
@@ -75,8 +75,10 @@ export declare function buildEncodedTransaction({ inputs, outputs, signingKey, s
|
|
|
75
75
|
slpOutputs?: Output[];
|
|
76
76
|
feePaidBy?: FeePaidByEnum;
|
|
77
77
|
changeAddress?: string;
|
|
78
|
+
buildUnsigned?: boolean;
|
|
78
79
|
}): Promise<{
|
|
79
80
|
encodedTransaction: Uint8Array;
|
|
80
81
|
sourceOutputs: any[];
|
|
81
82
|
}>;
|
|
83
|
+
export declare function signUnsignedTransaction(transaction: Uint8Array | string, sourceOutputs: SourceOutput[], signingKey: Uint8Array): Promise<Uint8Array>;
|
|
82
84
|
//# sourceMappingURL=Wif.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Wif.d.ts","sourceRoot":"","sources":["../../../src/transaction/Wif.ts"],"names":[],"mappings":"AACA,OAAO,EAIL,QAAQ,EAIR,wBAAwB,EACxB,gCAAgC,EAChC,qBAAqB,EACrB,MAAM,
|
|
1
|
+
{"version":3,"file":"Wif.d.ts","sourceRoot":"","sources":["../../../src/transaction/Wif.ts"],"names":[],"mappings":"AACA,OAAO,EAIL,QAAQ,EAIR,wBAAwB,EACxB,gCAAgC,EAChC,qBAAqB,EACrB,MAAM,EAKN,KAAK,EAEN,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAyB,KAAK,EAAE,MAAM,iBAAiB,CAAC;AAI/D,OAAO,EACL,YAAY,EACZ,WAAW,EACX,eAAe,EACf,YAAY,EACZ,gBAAgB,EACjB,MAAM,oBAAoB,CAAC;AAI5B,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAGlD,wBAAsB,0BAA0B,CAAC,EAC/C,MAAM,EACN,OAAO,EACP,UAAU,EACV,aAAa,EACb,GAAO,EACP,aAAqB,EACrB,UAAe,EACf,SAAgC,EAChC,aAAkB,GACnB,EAAE;IACD,MAAM,EAAE,KAAK,EAAE,CAAC;IAChB,OAAO,EAAE,KAAK,CAAC,WAAW,GAAG,gBAAgB,GAAG,YAAY,CAAC,CAAC;IAC9D,UAAU,EAAE,UAAU,CAAC;IACvB,aAAa,EAAE,MAAM,CAAC;IACtB,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,UAAU,CAAC,EAAE,MAAM,EAAE,CAAC;IACtB,SAAS,CAAC,EAAE,aAAa,CAAC;IAC1B,aAAa,CAAC,EAAE,MAAM,CAAC;CACxB;;;GAyEA;AAED,wBAAgB,aAAa,CAAC,EAC5B,MAAM,EACN,QAAQ,EACR,UAAU,EACV,aAAa,GACd,EAAE;IACD,MAAM,EAAE,KAAK,EAAE,CAAC;IAChB,QAAQ,EAAE,QAAQ,CAChB,qBAAqB,EACrB,wBAAwB,CAAC,qBAAqB,CAAC,EAC/C,gCAAgC,CACjC,CAAC;IACF,UAAU,EAAE,UAAU,CAAC;IACvB,aAAa,EAAE,MAAM,CAAC;CACvB;;;EAiEA;AAED;;;;;;GAMG;AACH,wBAAsB,cAAc,CAClC,OAAO,EAAE,KAAK,CAAC,WAAW,GAAG,gBAAgB,GAAG,YAAY,CAAC,6CA+B9D;AAED;;;;GAIG;AACH,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,YAAY,GAAG,MAAM,CAKnE;AAED;;;;GAIG;AACH,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,gBAAgB,GAAG,MAAM,CAwBrE;AAED;;;;;;;;GAQG;AACH,wBAAsB,gBAAgB,CACpC,MAAM,EAAE,KAAK,EAAE,EACf,cAAc,EAAE,MAAM,GAAG,SAAS,EAClC,UAAU,EAAE,MAAM,EAClB,SAAS,EAAE,aAAa,EACxB,QAAQ,EAAE,eAAe,EAAE,EAC3B,WAAW,GAAE,KAAK,EAAO,EACzB,cAAc,GAAE,MAAM,GAAG,SAAS,GAAG,MAAM,GAAG,MAAe,GAC5D,OAAO,CAAC,KAAK,EAAE,CAAC,CA2GlB;AAED,wBAAsB,YAAY,CAAC,EACjC,KAAK,EACL,YAAY,EACZ,UAAU,EACV,aAAa,EACb,wBAAwB,EACxB,UAAU,EACV,SAAS,EACT,aAAa,GACd,EAAE;IACD,KAAK,EAAE,KAAK,EAAE,CAAC;IACf,YAAY,EAAE,KAAK,CAAC,WAAW,GAAG,gBAAgB,GAAG,YAAY,CAAC,CAAC;IACnE,UAAU,EAAE,UAAU,CAAC;IACvB,aAAa,EAAE,MAAM,CAAC;IACtB,wBAAwB,EAAE,MAAM,CAAC;IACjC,UAAU,EAAE,MAAM,EAAE,CAAC;IACrB,SAAS,EAAE,aAAa,CAAC;IACzB,aAAa,CAAC,EAAE,OAAO,CAAC;CACzB,mBAuBA;AAGD,wBAAsB,uBAAuB,CAAC,EAC5C,MAAM,EACN,OAAO,EACP,UAAU,EACV,aAAa,EACb,GAAO,EACP,aAAqB,EACrB,UAAe,EACf,SAAgC,EAChC,aAAkB,EAClB,aAAqB,GACtB,EAAE;IACD,MAAM,EAAE,KAAK,EAAE,CAAC;IAChB,OAAO,EAAE,KAAK,CAAC,WAAW,GAAG,gBAAgB,GAAG,YAAY,CAAC,CAAC;IAC9D,UAAU,EAAE,UAAU,CAAC;IACvB,aAAa,EAAE,MAAM,CAAC;IACtB,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,UAAU,CAAC,EAAE,MAAM,EAAE,CAAC;IACtB,SAAS,CAAC,EAAE,aAAa,CAAC;IAC1B,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,aAAa,CAAC,EAAE,OAAO,CAAC;CACzB;;;GAoBA;AAED,wBAAsB,uBAAuB,CAC3C,WAAW,EAAE,UAAU,GAAG,MAAM,EAChC,aAAa,EAAE,YAAY,EAAE,EAC7B,UAAU,EAAE,UAAU,GACrB,OAAO,CAAC,UAAU,CAAC,CA2CrB"}
|