mainnet-js 2.2.8 → 2.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.html +1 -1
- package/dist/{mainnet-2.2.8.js → mainnet-2.3.0.js} +7 -7
- package/dist/module/config.d.ts +2 -0
- package/dist/module/config.d.ts.map +1 -1
- package/dist/module/config.js +4 -0
- package/dist/module/config.js.map +1 -1
- package/dist/module/index.d.ts +1 -0
- package/dist/module/index.d.ts.map +1 -1
- package/dist/module/index.js +1 -0
- package/dist/module/index.js.map +1 -1
- package/dist/module/interface.d.ts +1 -1
- package/dist/module/network/ElectrumNetworkProvider.js +1 -1
- package/dist/module/transaction/Wif.d.ts +1 -1
- package/dist/module/util/sumUtxoValue.d.ts +1 -1
- package/dist/module/util/sumUtxoValue.js +3 -3
- package/dist/module/util/sumUtxoValue.js.map +1 -1
- package/dist/module/wallet/Bcmr.d.ts.map +1 -1
- package/dist/module/wallet/Bcmr.js +3 -2
- package/dist/module/wallet/Bcmr.js.map +1 -1
- package/dist/module/wallet/Wif.d.ts +6 -6
- package/dist/module/wallet/Wif.d.ts.map +1 -1
- package/dist/module/wallet/Wif.js +19 -18
- package/dist/module/wallet/Wif.js.map +1 -1
- package/dist/module/wallet/model.d.ts +6 -6
- package/dist/module/wallet/model.d.ts.map +1 -1
- package/dist/module/wallet/model.js +3 -3
- package/dist/module/wallet/model.js.map +1 -1
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/package.json +1 -1
- package/polyfill/json.js +7 -0
- package/src/config.ts +5 -0
- package/src/index.ts +1 -0
- package/src/interface.ts +1 -1
- package/src/network/ElectrumNetworkProvider.ts +1 -1
- package/src/transaction/Wif.ts +1 -1
- package/src/util/sumUtxoValue.ts +5 -5
- package/src/wallet/Bcmr.test.ts +1 -1
- package/src/wallet/Bcmr.ts +3 -2
- package/src/wallet/Cashtokens.test.headless.js +44 -39
- package/src/wallet/Cashtokens.test.ts +117 -122
- package/src/wallet/Wif.test.ts +6 -9
- package/src/wallet/Wif.ts +28 -27
- package/src/wallet/model.ts +9 -9
|
@@ -544,7 +544,7 @@ eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harm
|
|
|
544
544
|
\***********************/
|
|
545
545
|
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
|
|
546
546
|
|
|
547
|
-
eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"Config\": () => (/* binding */ Config)\n/* harmony export */ });\nclass Config {\n}\n// enforces all token-related methods to specify tokenaddr as recepient and change cashaddr\nConfig.EnforceCashTokenReceiptAddresses = false;\nConfig.DefaultParentDerivationPath = \"m/44'/0'/0'\";\n\n\n//# sourceURL=webpack://mainnet-js/./src/config.ts?");
|
|
547
|
+
eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"Config\": () => (/* binding */ Config)\n/* harmony export */ });\nclass Config {\n static setIpfsGateway(ipfsGateway) {\n this.DefaultIpfsGateway = ipfsGateway;\n }\n}\n// enforces all token-related methods to specify tokenaddr as recepient and change cashaddr\nConfig.EnforceCashTokenReceiptAddresses = false;\nConfig.DefaultParentDerivationPath = \"m/44'/0'/0'\";\nConfig.DefaultIpfsGateway = \"https://dweb.link/ipfs/\";\n\n\n//# sourceURL=webpack://mainnet-js/./src/config.ts?");
|
|
548
548
|
|
|
549
549
|
/***/ }),
|
|
550
550
|
|
|
@@ -614,7 +614,7 @@ eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__
|
|
|
614
614
|
\**********************/
|
|
615
615
|
/***/ ((module, __webpack_exports__, __webpack_require__) => {
|
|
616
616
|
|
|
617
|
-
eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"BCMR\": () => (/* reexport safe */ _wallet_Bcmr_js__WEBPACK_IMPORTED_MODULE_4__.BCMR),\n/* harmony export */ \"BalanceResponse\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.BalanceResponse),\n/* harmony export */ \"BaseWallet\": () => (/* reexport safe */ _wallet_Base_js__WEBPACK_IMPORTED_MODULE_7__.BaseWallet),\n/* harmony export */ \"CONST\": () => (/* reexport module object */ _constant_js__WEBPACK_IMPORTED_MODULE_18__),\n/* harmony export */ \"Config\": () => (/* reexport safe */ _config_js__WEBPACK_IMPORTED_MODULE_11__.Config),\n/* harmony export */ \"Connection\": () => (/* reexport safe */ _network_index_js__WEBPACK_IMPORTED_MODULE_5__.Connection),\n/* harmony export */ \"DefaultProvider\": () => (/* reexport safe */ _network_configuration_js__WEBPACK_IMPORTED_MODULE_10__.DefaultProvider),\n/* harmony export */ \"ElectrumNetworkProvider\": () => (/* reexport safe */ _network_index_js__WEBPACK_IMPORTED_MODULE_5__.ElectrumNetworkProvider),\n/* harmony export */ \"ExchangeRate\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.ExchangeRate),\n/* harmony export */ \"FeePaidByEnum\": () => (/* reexport safe */ _wallet_enum_js__WEBPACK_IMPORTED_MODULE_13__.FeePaidByEnum),\n/* harmony export */ \"Mainnet\": () => (/* reexport module object */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__),\n/* harmony export */ \"NFTCapability\": () => (/* reexport safe */ _interface_js__WEBPACK_IMPORTED_MODULE_19__.NFTCapability),\n/* harmony export */ \"Network\": () => (/* reexport safe */ _interface_js__WEBPACK_IMPORTED_MODULE_19__.Network),\n/* harmony export */ \"NetworkType\": () => (/* reexport safe */ _enum_js__WEBPACK_IMPORTED_MODULE_12__.NetworkType),\n/* harmony export */ \"OpReturnData\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_14__.OpReturnData),\n/* harmony export */ \"RegTestWallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__.RegTestWallet),\n/* harmony export */ \"RegTestWatchWallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__.RegTestWatchWallet),\n/* harmony export */ \"RegTestWifWallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__.RegTestWifWallet),\n/* harmony export */ \"RuntimePlatform\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.RuntimePlatform),\n/* harmony export */ \"SendRequest\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_14__.SendRequest),\n/* harmony export */ \"SendResponse\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_14__.SendResponse),\n/* harmony export */ \"SignedMessage\": () => (/* reexport safe */ _message_signed_js__WEBPACK_IMPORTED_MODULE_6__.SignedMessage),\n/* harmony export */ \"StorageProvider\": () => (/* reexport safe */ _db_index_js__WEBPACK_IMPORTED_MODULE_2__.StorageProvider),\n/* harmony export */ \"TestNetWallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__.TestNetWallet),\n/* harmony export */ \"TestNetWatchWallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__.TestNetWatchWallet),\n/* harmony export */ \"TestNetWifWallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__.TestNetWifWallet),\n/* harmony export */ \"TokenBurnRequest\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_14__.TokenBurnRequest),\n/* harmony export */ \"TokenGenesisRequest\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_14__.TokenGenesisRequest),\n/* harmony export */ \"TokenMintRequest\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_14__.TokenMintRequest),\n/* harmony export */ \"TokenSendRequest\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_14__.TokenSendRequest),\n/* harmony export */ \"UnitEnum\": () => (/* reexport safe */ _enum_js__WEBPACK_IMPORTED_MODULE_12__.UnitEnum),\n/* harmony export */ \"Wallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__.Wallet),\n/* harmony export */ \"WalletTypeEnum\": () => (/* reexport safe */ _wallet_enum_js__WEBPACK_IMPORTED_MODULE_13__.WalletTypeEnum),\n/* harmony export */ \"WatchWallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__.WatchWallet),\n/* harmony export */ \"WifWallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__.WifWallet),\n/* harmony export */ \"XPubKey\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_14__.XPubKey),\n/* harmony export */ \"amountInSatoshi\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.amountInSatoshi),\n/* harmony export */ \"asSendRequestObject\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.asSendRequestObject),\n/* harmony export */ \"atob\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.atob),\n/* harmony export */ \"balanceFromSatoshi\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.balanceFromSatoshi),\n/* harmony export */ \"balanceResponseFromSatoshi\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.balanceResponseFromSatoshi),\n/* harmony export */ \"binToBase64\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.binToBase64),\n/* harmony export */ \"binToHex\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.binToHex),\n/* harmony export */ \"btoa\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.btoa),\n/* harmony export */ \"checkTokenaddr\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.checkTokenaddr),\n/* harmony export */ \"convert\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.convert),\n/* harmony export */ \"convertObject\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.convertObject),\n/* harmony export */ \"createWallet\": () => (/* reexport safe */ _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_9__.createWallet),\n/* harmony export */ \"createWalletResponse\": () => (/* reexport safe */ _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_9__.createWalletResponse),\n/* harmony export */ \"delay\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.delay),\n/* harmony export */ \"deriveCashaddr\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.deriveCashaddr),\n/* harmony export */ \"derivePublicKeyHash\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.derivePublicKeyHash),\n/* harmony export */ \"deriveTokenaddr\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.deriveTokenaddr),\n/* harmony export */ \"derivedNetwork\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.derivedNetwork),\n/* harmony export */ \"disconnectProviders\": () => (/* reexport safe */ _network_index_js__WEBPACK_IMPORTED_MODULE_5__.disconnectProviders),\n/* harmony export */ \"expect\": () => (/* reexport safe */ _test_expect_js__WEBPACK_IMPORTED_MODULE_1__.expect),\n/* harmony export */ \"fromUtxoId\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_14__.fromUtxoId),\n/* harmony export */ \"getAddrsByXpubKey\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.getAddrsByXpubKey),\n/* harmony export */ \"getAddrsByXpubKeyObject\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.getAddrsByXpubKeyObject),\n/* harmony export */ \"getNetworkProvider\": () => (/* reexport safe */ _network_index_js__WEBPACK_IMPORTED_MODULE_5__.getNetworkProvider),\n/* harmony export */ \"getRandomInt\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.getRandomInt),\n/* harmony export */ \"getRuntimePlatform\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.getRuntimePlatform),\n/* harmony export */ \"getUsdRate\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.getUsdRate),\n/* harmony export */ \"getXPubKey\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.getXPubKey),\n/* harmony export */ \"getXpubKeyInfo\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.getXpubKeyInfo),\n/* harmony export */ \"getXpubKeyInfoObject\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.getXpubKeyInfoObject),\n/* harmony export */ \"hash160\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.hash160),\n/* harmony export */ \"hexToBin\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.hexToBin),\n/* harmony export */ \"initProviders\": () => (/* reexport safe */ _network_index_js__WEBPACK_IMPORTED_MODULE_5__.initProviders),\n/* harmony export */ \"isTokenaddr\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.isTokenaddr),\n/* harmony export */ \"isValidAddress\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.isValidAddress),\n/* harmony export */ \"libauth\": () => (/* reexport module object */ _libauth_js__WEBPACK_IMPORTED_MODULE_16__),\n/* harmony export */ \"mine\": () => (/* reexport safe */ _mine_index_js__WEBPACK_IMPORTED_MODULE_3__.mine),\n/* harmony export */ \"namedWallet\": () => (/* reexport safe */ _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_9__.namedWallet),\n/* harmony export */ \"namedWalletExists\": () => (/* reexport safe */ _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_9__.namedWalletExists),\n/* harmony export */ \"qrAddress\": () => (/* reexport safe */ _qr_Qr_js__WEBPACK_IMPORTED_MODULE_17__.qrAddress),\n/* harmony export */ \"randomValues\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.randomValues),\n/* harmony export */ \"removeFetchMock\": () => (/* reexport safe */ _test_fetch_js__WEBPACK_IMPORTED_MODULE_0__.removeFetchMock),\n/* harmony export */ \"replaceNamedWallet\": () => (/* reexport safe */ _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_9__.replaceNamedWallet),\n/* harmony export */ \"sanitizeAddress\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.sanitizeAddress),\n/* harmony export */ \"sanitizeUnit\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.sanitizeUnit),\n/* harmony export */ \"setupFetchMock\": () => (/* reexport safe */ _test_fetch_js__WEBPACK_IMPORTED_MODULE_0__.setupFetchMock),\n/* harmony export */ \"sha256\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.sha256),\n/* harmony export */ \"sumTokenAmounts\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.sumTokenAmounts),\n/* harmony export */ \"sumUtxoValue\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.sumUtxoValue),\n/* harmony export */ \"toCashaddr\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.toCashaddr),\n/* harmony export */ \"toTokenaddr\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.toTokenaddr),\n/* harmony export */ \"toUtxoId\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_14__.toUtxoId),\n/* harmony export */ \"utf8ToBin\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.utf8ToBin),\n/* harmony export */ \"walletClassMap\": () => (/* reexport safe */ _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_9__.walletClassMap),\n/* harmony export */ \"walletFromId\": () => (/* reexport safe */ _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_9__.walletFromId)\n/* harmony export */ });\n/* harmony import */ var _test_fetch_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./test/fetch.js */ \"./src/test/fetch.ts\");\n/* harmony import */ var _test_expect_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./test/expect.js */ \"./src/test/expect.ts\");\n/* harmony import */ var _db_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./db/index.js */ \"./src/db/index.ts\");\n/* harmony import */ var _mine_index_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./mine/index.js */ \"./src/mine/index.ts\");\n/* harmony import */ var _wallet_Bcmr_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./wallet/Bcmr.js */ \"./src/wallet/Bcmr.ts\");\n/* harmony import */ var _network_index_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./network/index.js */ \"./src/network/index.ts\");\n/* harmony import */ var _message_signed_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./message/signed.js */ \"./src/message/signed.ts\");\n/* harmony import */ var _wallet_Base_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./wallet/Base.js */ \"./src/wallet/Base.ts\");\n/* harmony import */ var _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./wallet/Wif.js */ \"./src/wallet/Wif.ts\");\n/* harmony import */ var _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./wallet/createWallet.js */ \"./src/wallet/createWallet.ts\");\n/* harmony import */ var _network_configuration_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./network/configuration.js */ \"./src/network/configuration.ts\");\n/* harmony import */ var _config_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./config.js */ \"./src/config.ts\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./enum.js */ \"./src/enum.ts\");\n/* harmony import */ var _wallet_enum_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./wallet/enum.js */ \"./src/wallet/enum.ts\");\n/* harmony import */ var _wallet_model_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./wallet/model.js */ \"./src/wallet/model.ts\");\n/* harmony import */ var _util_index_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./util/index.js */ \"./src/util/index.ts\");\n/* harmony import */ var _libauth_js__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./libauth.js */ \"./src/libauth.ts\");\n/* harmony import */ var _qr_Qr_js__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./qr/Qr.js */ \"./src/qr/Qr.ts\");\n/* harmony import */ var _constant_js__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./constant.js */ \"./src/constant.ts\");\n/* harmony import */ var _interface_js__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./interface.js */ \"./src/interface.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_wallet_Bcmr_js__WEBPACK_IMPORTED_MODULE_4__, _network_index_js__WEBPACK_IMPORTED_MODULE_5__, _message_signed_js__WEBPACK_IMPORTED_MODULE_6__, _wallet_Base_js__WEBPACK_IMPORTED_MODULE_7__, _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__, _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_9__, _network_configuration_js__WEBPACK_IMPORTED_MODULE_10__, _enum_js__WEBPACK_IMPORTED_MODULE_12__, _wallet_model_js__WEBPACK_IMPORTED_MODULE_14__, _util_index_js__WEBPACK_IMPORTED_MODULE_15__, _libauth_js__WEBPACK_IMPORTED_MODULE_16__, _qr_Qr_js__WEBPACK_IMPORTED_MODULE_17__]);\n([_wallet_Bcmr_js__WEBPACK_IMPORTED_MODULE_4__, _network_index_js__WEBPACK_IMPORTED_MODULE_5__, _message_signed_js__WEBPACK_IMPORTED_MODULE_6__, _wallet_Base_js__WEBPACK_IMPORTED_MODULE_7__, _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__, _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_9__, _network_configuration_js__WEBPACK_IMPORTED_MODULE_10__, _enum_js__WEBPACK_IMPORTED_MODULE_12__, _wallet_model_js__WEBPACK_IMPORTED_MODULE_14__, _util_index_js__WEBPACK_IMPORTED_MODULE_15__, _libauth_js__WEBPACK_IMPORTED_MODULE_16__, _qr_Qr_js__WEBPACK_IMPORTED_MODULE_17__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\n\n\n\n\n\n\n\n\n// provider\n\n// config\n\n// Enum\n\n\n// models\n\n// utils\n\n\n\n// libauth\n\n// qr\n\n// constants\n\n\n// interfaces\n\n\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/index.ts?");
|
|
617
|
+
eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"BCMR\": () => (/* reexport safe */ _wallet_Bcmr_js__WEBPACK_IMPORTED_MODULE_4__.BCMR),\n/* harmony export */ \"BalanceResponse\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.BalanceResponse),\n/* harmony export */ \"BaseWallet\": () => (/* reexport safe */ _wallet_Base_js__WEBPACK_IMPORTED_MODULE_7__.BaseWallet),\n/* harmony export */ \"CONST\": () => (/* reexport module object */ _constant_js__WEBPACK_IMPORTED_MODULE_18__),\n/* harmony export */ \"Config\": () => (/* reexport safe */ _config_js__WEBPACK_IMPORTED_MODULE_11__.Config),\n/* harmony export */ \"Connection\": () => (/* reexport safe */ _network_index_js__WEBPACK_IMPORTED_MODULE_5__.Connection),\n/* harmony export */ \"DefaultProvider\": () => (/* reexport safe */ _network_configuration_js__WEBPACK_IMPORTED_MODULE_10__.DefaultProvider),\n/* harmony export */ \"ElectrumNetworkProvider\": () => (/* reexport safe */ _network_index_js__WEBPACK_IMPORTED_MODULE_5__.ElectrumNetworkProvider),\n/* harmony export */ \"ExchangeRate\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.ExchangeRate),\n/* harmony export */ \"FeePaidByEnum\": () => (/* reexport safe */ _wallet_enum_js__WEBPACK_IMPORTED_MODULE_13__.FeePaidByEnum),\n/* harmony export */ \"Mainnet\": () => (/* reexport module object */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__),\n/* harmony export */ \"NFTCapability\": () => (/* reexport safe */ _interface_js__WEBPACK_IMPORTED_MODULE_19__.NFTCapability),\n/* harmony export */ \"Network\": () => (/* reexport safe */ _interface_js__WEBPACK_IMPORTED_MODULE_19__.Network),\n/* harmony export */ \"NetworkType\": () => (/* reexport safe */ _enum_js__WEBPACK_IMPORTED_MODULE_12__.NetworkType),\n/* harmony export */ \"OpReturnData\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_14__.OpReturnData),\n/* harmony export */ \"RegTestWallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__.RegTestWallet),\n/* harmony export */ \"RegTestWatchWallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__.RegTestWatchWallet),\n/* harmony export */ \"RegTestWifWallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__.RegTestWifWallet),\n/* harmony export */ \"RuntimePlatform\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.RuntimePlatform),\n/* harmony export */ \"SendRequest\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_14__.SendRequest),\n/* harmony export */ \"SendResponse\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_14__.SendResponse),\n/* harmony export */ \"SignedMessage\": () => (/* reexport safe */ _message_signed_js__WEBPACK_IMPORTED_MODULE_6__.SignedMessage),\n/* harmony export */ \"StorageProvider\": () => (/* reexport safe */ _db_index_js__WEBPACK_IMPORTED_MODULE_2__.StorageProvider),\n/* harmony export */ \"TestNetWallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__.TestNetWallet),\n/* harmony export */ \"TestNetWatchWallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__.TestNetWatchWallet),\n/* harmony export */ \"TestNetWifWallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__.TestNetWifWallet),\n/* harmony export */ \"TokenBurnRequest\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_14__.TokenBurnRequest),\n/* harmony export */ \"TokenGenesisRequest\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_14__.TokenGenesisRequest),\n/* harmony export */ \"TokenMintRequest\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_14__.TokenMintRequest),\n/* harmony export */ \"TokenSendRequest\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_14__.TokenSendRequest),\n/* harmony export */ \"UnitEnum\": () => (/* reexport safe */ _enum_js__WEBPACK_IMPORTED_MODULE_12__.UnitEnum),\n/* harmony export */ \"Wallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__.Wallet),\n/* harmony export */ \"WalletTypeEnum\": () => (/* reexport safe */ _wallet_enum_js__WEBPACK_IMPORTED_MODULE_13__.WalletTypeEnum),\n/* harmony export */ \"WatchWallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__.WatchWallet),\n/* harmony export */ \"WifWallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__.WifWallet),\n/* harmony export */ \"XPubKey\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_14__.XPubKey),\n/* harmony export */ \"amountInSatoshi\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.amountInSatoshi),\n/* harmony export */ \"asSendRequestObject\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.asSendRequestObject),\n/* harmony export */ \"atob\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.atob),\n/* harmony export */ \"balanceFromSatoshi\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.balanceFromSatoshi),\n/* harmony export */ \"balanceResponseFromSatoshi\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.balanceResponseFromSatoshi),\n/* harmony export */ \"binToBase64\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.binToBase64),\n/* harmony export */ \"binToHex\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.binToHex),\n/* harmony export */ \"btoa\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.btoa),\n/* harmony export */ \"checkTokenaddr\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.checkTokenaddr),\n/* harmony export */ \"convert\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.convert),\n/* harmony export */ \"convertObject\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.convertObject),\n/* harmony export */ \"createWallet\": () => (/* reexport safe */ _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_9__.createWallet),\n/* harmony export */ \"createWalletResponse\": () => (/* reexport safe */ _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_9__.createWalletResponse),\n/* harmony export */ \"delay\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.delay),\n/* harmony export */ \"deriveCashaddr\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.deriveCashaddr),\n/* harmony export */ \"derivePublicKeyHash\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.derivePublicKeyHash),\n/* harmony export */ \"deriveTokenaddr\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.deriveTokenaddr),\n/* harmony export */ \"derivedNetwork\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.derivedNetwork),\n/* harmony export */ \"disconnectProviders\": () => (/* reexport safe */ _network_index_js__WEBPACK_IMPORTED_MODULE_5__.disconnectProviders),\n/* harmony export */ \"expect\": () => (/* reexport safe */ _test_expect_js__WEBPACK_IMPORTED_MODULE_1__.expect),\n/* harmony export */ \"fromUtxoId\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_14__.fromUtxoId),\n/* harmony export */ \"getAddrsByXpubKey\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.getAddrsByXpubKey),\n/* harmony export */ \"getAddrsByXpubKeyObject\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.getAddrsByXpubKeyObject),\n/* harmony export */ \"getNetworkProvider\": () => (/* reexport safe */ _network_index_js__WEBPACK_IMPORTED_MODULE_5__.getNetworkProvider),\n/* harmony export */ \"getRandomInt\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.getRandomInt),\n/* harmony export */ \"getRuntimePlatform\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.getRuntimePlatform),\n/* harmony export */ \"getUsdRate\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.getUsdRate),\n/* harmony export */ \"getXPubKey\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.getXPubKey),\n/* harmony export */ \"getXpubKeyInfo\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.getXpubKeyInfo),\n/* harmony export */ \"getXpubKeyInfoObject\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.getXpubKeyInfoObject),\n/* harmony export */ \"hash160\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.hash160),\n/* harmony export */ \"hexToBin\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.hexToBin),\n/* harmony export */ \"initProviders\": () => (/* reexport safe */ _network_index_js__WEBPACK_IMPORTED_MODULE_5__.initProviders),\n/* harmony export */ \"isTokenaddr\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.isTokenaddr),\n/* harmony export */ \"isValidAddress\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.isValidAddress),\n/* harmony export */ \"libauth\": () => (/* reexport module object */ _libauth_js__WEBPACK_IMPORTED_MODULE_16__),\n/* harmony export */ \"mine\": () => (/* reexport safe */ _mine_index_js__WEBPACK_IMPORTED_MODULE_3__.mine),\n/* harmony export */ \"namedWallet\": () => (/* reexport safe */ _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_9__.namedWallet),\n/* harmony export */ \"namedWalletExists\": () => (/* reexport safe */ _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_9__.namedWalletExists),\n/* harmony export */ \"qrAddress\": () => (/* reexport safe */ _qr_Qr_js__WEBPACK_IMPORTED_MODULE_17__.qrAddress),\n/* harmony export */ \"randomValues\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.randomValues),\n/* harmony export */ \"removeFetchMock\": () => (/* reexport safe */ _test_fetch_js__WEBPACK_IMPORTED_MODULE_0__.removeFetchMock),\n/* harmony export */ \"replaceNamedWallet\": () => (/* reexport safe */ _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_9__.replaceNamedWallet),\n/* harmony export */ \"sanitizeAddress\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.sanitizeAddress),\n/* harmony export */ \"sanitizeUnit\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.sanitizeUnit),\n/* harmony export */ \"setupFetchMock\": () => (/* reexport safe */ _test_fetch_js__WEBPACK_IMPORTED_MODULE_0__.setupFetchMock),\n/* harmony export */ \"sha256\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.sha256),\n/* harmony export */ \"sumTokenAmounts\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.sumTokenAmounts),\n/* harmony export */ \"sumUtxoValue\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.sumUtxoValue),\n/* harmony export */ \"toCashaddr\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.toCashaddr),\n/* harmony export */ \"toTokenaddr\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.toTokenaddr),\n/* harmony export */ \"toUtxoId\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_14__.toUtxoId),\n/* harmony export */ \"utf8ToBin\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.utf8ToBin),\n/* harmony export */ \"walletClassMap\": () => (/* reexport safe */ _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_9__.walletClassMap),\n/* harmony export */ \"walletFromId\": () => (/* reexport safe */ _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_9__.walletFromId)\n/* harmony export */ });\n/* harmony import */ var _test_fetch_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./test/fetch.js */ \"./src/test/fetch.ts\");\n/* harmony import */ var _test_expect_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./test/expect.js */ \"./src/test/expect.ts\");\n/* harmony import */ var _db_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./db/index.js */ \"./src/db/index.ts\");\n/* harmony import */ var _mine_index_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./mine/index.js */ \"./src/mine/index.ts\");\n/* harmony import */ var _wallet_Bcmr_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./wallet/Bcmr.js */ \"./src/wallet/Bcmr.ts\");\n/* harmony import */ var _network_index_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./network/index.js */ \"./src/network/index.ts\");\n/* harmony import */ var _message_signed_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./message/signed.js */ \"./src/message/signed.ts\");\n/* harmony import */ var _wallet_Base_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./wallet/Base.js */ \"./src/wallet/Base.ts\");\n/* harmony import */ var _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./wallet/Wif.js */ \"./src/wallet/Wif.ts\");\n/* harmony import */ var _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./wallet/createWallet.js */ \"./src/wallet/createWallet.ts\");\n/* harmony import */ var _network_configuration_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./network/configuration.js */ \"./src/network/configuration.ts\");\n/* harmony import */ var _config_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./config.js */ \"./src/config.ts\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./enum.js */ \"./src/enum.ts\");\n/* harmony import */ var _wallet_enum_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./wallet/enum.js */ \"./src/wallet/enum.ts\");\n/* harmony import */ var _wallet_model_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./wallet/model.js */ \"./src/wallet/model.ts\");\n/* harmony import */ var _util_index_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./util/index.js */ \"./src/util/index.ts\");\n/* harmony import */ var _libauth_js__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./libauth.js */ \"./src/libauth.ts\");\n/* harmony import */ var _qr_Qr_js__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./qr/Qr.js */ \"./src/qr/Qr.ts\");\n/* harmony import */ var _constant_js__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./constant.js */ \"./src/constant.ts\");\n/* harmony import */ var _interface_js__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./interface.js */ \"./src/interface.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_wallet_Bcmr_js__WEBPACK_IMPORTED_MODULE_4__, _network_index_js__WEBPACK_IMPORTED_MODULE_5__, _message_signed_js__WEBPACK_IMPORTED_MODULE_6__, _wallet_Base_js__WEBPACK_IMPORTED_MODULE_7__, _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__, _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_9__, _network_configuration_js__WEBPACK_IMPORTED_MODULE_10__, _enum_js__WEBPACK_IMPORTED_MODULE_12__, _wallet_model_js__WEBPACK_IMPORTED_MODULE_14__, _util_index_js__WEBPACK_IMPORTED_MODULE_15__, _libauth_js__WEBPACK_IMPORTED_MODULE_16__, _qr_Qr_js__WEBPACK_IMPORTED_MODULE_17__]);\n([_wallet_Bcmr_js__WEBPACK_IMPORTED_MODULE_4__, _network_index_js__WEBPACK_IMPORTED_MODULE_5__, _message_signed_js__WEBPACK_IMPORTED_MODULE_6__, _wallet_Base_js__WEBPACK_IMPORTED_MODULE_7__, _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__, _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_9__, _network_configuration_js__WEBPACK_IMPORTED_MODULE_10__, _enum_js__WEBPACK_IMPORTED_MODULE_12__, _wallet_model_js__WEBPACK_IMPORTED_MODULE_14__, _util_index_js__WEBPACK_IMPORTED_MODULE_15__, _libauth_js__WEBPACK_IMPORTED_MODULE_16__, _qr_Qr_js__WEBPACK_IMPORTED_MODULE_17__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\n\n\n\n\n\n\n\n\n\n// provider\n\n// config\n\n// Enum\n\n\n// models\n\n// utils\n\n\n\n// libauth\n\n// qr\n\n// constants\n\n\n// interfaces\n\n\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/index.ts?");
|
|
618
618
|
|
|
619
619
|
/***/ }),
|
|
620
620
|
|
|
@@ -684,7 +684,7 @@ eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__
|
|
|
684
684
|
\************************************************/
|
|
685
685
|
/***/ ((module, __webpack_exports__, __webpack_require__) => {
|
|
686
686
|
|
|
687
|
-
eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"default\": () => (/* binding */ ElectrumNetworkProvider)\n/* harmony export */ });\n/* harmony import */ var electrum_cash__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! electrum-cash */ \"../../node_modules/electrum-cash/dist/index.mjs.js\");\n/* harmony import */ var _interface_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../interface.js */ \"./src/interface.ts\");\n/* harmony import */ var _util_delay_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../util/delay.js */ \"./src/util/delay.ts\");\n/* harmony import */ var _util_transaction_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../util/transaction.js */ \"./src/util/transaction.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_util_transaction_js__WEBPACK_IMPORTED_MODULE_2__]);\n_util_transaction_js__WEBPACK_IMPORTED_MODULE_2__ = (__webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__)[0];\n\n\n\n\nclass ElectrumNetworkProvider {\n constructor(electrum, network = _interface_js__WEBPACK_IMPORTED_MODULE_1__.Network.MAINNET, manualConnectionManagement) {\n this.network = network;\n this.manualConnectionManagement = manualConnectionManagement;\n this.subscriptions = 0;\n this.blockHeight = 0;\n if (electrum) {\n this.electrum = electrum;\n this.connectPromise = this.getConnectPromise();\n if (this.electrum instanceof electrum_cash__WEBPACK_IMPORTED_MODULE_0__.ElectrumCluster) {\n this.version = this.electrum.version;\n }\n else {\n this.version = this.electrum.connection.version;\n }\n }\n else {\n throw new Error(`A electrum-cash cluster or client is required.`);\n }\n }\n async getConnectPromise(_timeout = 3000) {\n // connects to the electrum cash and waits until the connection is ready to accept requests\n let timeoutHandle;\n await Promise.race([\n new Promise(async (resolve) => {\n this.connectPromise = undefined;\n if (this.electrum instanceof electrum_cash__WEBPACK_IMPORTED_MODULE_0__.ElectrumCluster) {\n try {\n await this.connectCluster();\n }\n catch (e) {\n console.warn(`Unable to connect to one or more electrum-cash hosts: ${JSON.stringify(e)}`);\n }\n resolve(await this.readyCluster());\n }\n else {\n resolve(await this.connectClient());\n }\n }),\n // new Promise(\n // (_resolve, reject) =>\n // (timeoutHandle = setTimeout(() => {\n // reject(\n // new Error(`Timeout connecting to electrum network: ${this.network}`)\n // );\n // }, _timeout))\n // ),\n ]);\n clearTimeout(timeoutHandle);\n }\n async getUtxos(cashaddr) {\n const result = (await this.performRequest(\"blockchain.address.listunspent\", cashaddr, \"include_tokens\"));\n return result.map((utxo) => ({\n txid: utxo.tx_hash,\n vout: utxo.tx_pos,\n satoshis: utxo.value,\n height: utxo.height,\n token: utxo.token_data\n ? {\n amount: Number(utxo.token_data.amount),\n tokenId: utxo.token_data.category,\n capability: utxo.token_data.nft?.capability,\n commitment: utxo.token_data.nft?.commitment,\n }\n : undefined,\n }));\n }\n async getBalance(cashaddr) {\n const result = (await this.performRequest(\"blockchain.address.get_balance\", cashaddr));\n return result.confirmed + result.unconfirmed;\n }\n async getBlockHeight() {\n return (await this.performRequest(\"blockchain.headers.get_tip\"))\n .height;\n }\n async getRawTransaction(txHash, verbose = false, loadInputValues = false) {\n const key = `${this.network}-${txHash}-${verbose}-${loadInputValues}`;\n if (ElectrumNetworkProvider.rawTransactionCache[key]) {\n return ElectrumNetworkProvider.rawTransactionCache[key];\n }\n try {\n const transaction = (await this.performRequest(\"blockchain.transaction.get\", txHash, verbose));\n ElectrumNetworkProvider.rawTransactionCache[key] = transaction;\n if (verbose && loadInputValues) {\n // get unique transaction hashes\n const hashes = [...new Set(transaction.vin.map((val) => val.txid))];\n const transactions = await Promise.all(hashes.map((hash) => this.getRawTransactionObject(hash, false)));\n const transactionMap = new Map();\n transactions.forEach((val) => transactionMap.set(val.hash, val));\n transaction.vin.forEach((input) => {\n const output = transactionMap\n .get(input.txid)\n .vout.find((val) => val.n === input.vout);\n input.address = output.scriptPubKey.addresses[0];\n input.value = output.value;\n input.tokenData = output.tokenData;\n });\n }\n return transaction;\n }\n catch (error) {\n if (error.message.indexOf(\"No such mempool or blockchain transaction.\") > -1)\n throw Error(`Could not decode transaction ${txHash}. It might not exist on the current blockchain (${this.network}).`);\n else\n throw error;\n }\n }\n // gets the decoded transaction in human readable form\n async getRawTransactionObject(txHash, loadInputValues = false) {\n return (await this.getRawTransaction(txHash, true, loadInputValues));\n }\n async sendRawTransaction(txHex, awaitPropagation = true) {\n return new Promise(async (resolve, reject) => {\n let txHash = await (0,_util_transaction_js__WEBPACK_IMPORTED_MODULE_2__.getTransactionHash)(txHex);\n if (!awaitPropagation) {\n this.performRequest(\"blockchain.transaction.broadcast\", txHex);\n resolve(txHash);\n }\n else {\n const waitForTransactionCallback = async (data) => {\n if (data && data[0] === txHash) {\n this.unsubscribeFromTransaction(txHash, waitForTransactionCallback);\n resolve(txHash);\n }\n };\n this.subscribeToTransaction(txHash, waitForTransactionCallback);\n this.performRequest(\"blockchain.transaction.broadcast\", txHex).catch((error) => {\n this.unsubscribeFromTransaction(txHash, waitForTransactionCallback);\n reject(error);\n });\n }\n });\n }\n // Get transaction history of a given cashaddr\n async getHistory(cashaddr) {\n const result = (await this.performRequest(\"blockchain.address.get_history\", cashaddr));\n return result;\n }\n // Get the minimum fee a low-priority transaction must pay in order to be accepted to the daemon's memory pool.\n async getRelayFee() {\n const result = (await this.performRequest(\"blockchain.relayfee\"));\n return result;\n }\n watchAddressStatus(cashaddr, callback) {\n const watchAddressStatusCallback = async (data) => {\n // subscription acknowledgement is the latest known status or null if no status is known\n // status is an array: [ cashaddr, statusHash ]\n if (data instanceof Array) {\n const addr = data[0];\n if (addr !== cashaddr) {\n return;\n }\n const status = data[1];\n callback(status);\n }\n };\n this.subscribeToAddress(cashaddr, watchAddressStatusCallback);\n return async () => {\n await this.unsubscribeFromAddress(cashaddr, watchAddressStatusCallback);\n };\n }\n watchAddress(cashaddr, callback) {\n const historyMap = {};\n this.getHistory(cashaddr).then((history) => history.forEach((val) => (historyMap[val.tx_hash] = true)));\n const watchAddressStatusCallback = async () => {\n const newHistory = await this.getHistory(cashaddr);\n // sort history to put unconfirmed transactions in the beginning, then transactions in block height descenting order\n const txHashes = newHistory\n .sort((a, b) => a.height <= 0 || b.height <= 0 ? -1 : b.height - a.height)\n .map((val) => val.tx_hash);\n for (const hash of txHashes) {\n if (!(hash in historyMap)) {\n historyMap[hash] = true;\n callback(hash);\n // exit early to prevent further map lookups\n break;\n }\n }\n };\n return this.watchAddressStatus(cashaddr, watchAddressStatusCallback);\n }\n watchAddressTransactions(cashaddr, callback) {\n return this.watchAddress(cashaddr, async (txHash) => {\n const tx = await this.getRawTransactionObject(txHash);\n callback(tx);\n });\n }\n watchAddressTokenTransactions(cashaddr, callback) {\n return this.watchAddress(cashaddr, async (txHash) => {\n const tx = await this.getRawTransactionObject(txHash, true);\n if (tx.vin.some((val) => val.tokenData) ||\n tx.vout.some((val) => val.tokenData)) {\n callback(tx);\n }\n });\n }\n // Wait for the next block or a block at given blockchain height.\n watchBlocks(callback) {\n let acknowledged = false;\n const waitForBlockCallback = (_header) => {\n if (!acknowledged) {\n acknowledged = true;\n return;\n }\n _header = _header instanceof Array ? _header[0] : _header;\n callback(_header);\n };\n this.subscribeToHeaders(waitForBlockCallback);\n return async () => {\n this.unsubscribeFromHeaders(waitForBlockCallback);\n };\n }\n // Wait for the next block or a block at given blockchain height.\n async waitForBlock(height) {\n return new Promise(async (resolve) => {\n const cancelWatch = this.watchBlocks(async (header) => {\n if (height === undefined || header.height >= height) {\n await cancelWatch();\n resolve(header);\n }\n });\n });\n }\n // subscribe to notifications sent when new block is found, the block header is sent to callback\n async subscribeToHeaders(callback) {\n await this.subscribeRequest(\"blockchain.headers.subscribe\", callback);\n }\n // unsubscribe to notifications sent when new block is found\n async unsubscribeFromHeaders(callback) {\n await this.unsubscribeRequest(\"blockchain.headers.subscribe\", callback);\n }\n async subscribeToAddress(cashaddr, callback) {\n await this.subscribeRequest(\"blockchain.address.subscribe\", callback, cashaddr);\n }\n async unsubscribeFromAddress(cashaddr, callback) {\n await this.unsubscribeRequest(\"blockchain.address.subscribe\", callback, cashaddr);\n }\n async subscribeToAddressTransactions(cashaddr, callback) {\n await this.subscribeRequest(\"blockchain.address.transactions.subscribe\", callback, cashaddr);\n }\n async unsubscribeFromAddressTransactions(cashaddr, callback) {\n await this.unsubscribeRequest(\"blockchain.address.transactions.subscribe\", callback, cashaddr);\n }\n async subscribeToTransaction(txHash, callback) {\n await this.subscribeRequest(\"blockchain.transaction.subscribe\", callback, txHash);\n }\n async unsubscribeFromTransaction(txHash, callback) {\n await this.unsubscribeRequest(\"blockchain.transaction.subscribe\", callback, txHash);\n }\n async performRequest(name, ...parameters) {\n await this.ready();\n const requestTimeout = new Promise(function (_resolve, reject) {\n setTimeout(function () {\n reject(\"electrum-cash request timed out, retrying\");\n }, 30000);\n }).catch(function (e) {\n throw e;\n });\n const request = this.electrum.request(name, ...parameters);\n return await Promise.race([request, requestTimeout])\n .then((value) => {\n if (value instanceof Error)\n throw value;\n let result = value;\n return result;\n })\n .catch(async () => {\n // console.warn(\n // \"initial electrum-cash request attempt timed out, retrying...\"\n // );\n return await Promise.race([request, requestTimeout])\n .then((value) => {\n if (value instanceof Error)\n throw value;\n let result = value;\n return result;\n })\n .catch(function (e) {\n throw e;\n });\n });\n }\n async subscribeRequest(methodName, callback, ...parameters) {\n await this.ready();\n const result = await this.electrum.subscribe(callback, methodName, ...parameters);\n this.subscriptions++;\n return result;\n }\n async unsubscribeRequest(methodName, callback, ...parameters) {\n await this.ready();\n const result = this.electrum.unsubscribe(callback, methodName, ...parameters);\n this.subscriptions--;\n return result;\n }\n async ready() {\n return (await this.connect());\n }\n async connect() {\n return await this.connectPromise;\n }\n disconnect() {\n if (this.subscriptions > 0) {\n // console.warn(\n // `Trying to disconnect a network provider with ${this.subscriptions} active subscriptions. This is in most cases a bad idea.`\n // );\n }\n return this.isElectrumClient()\n ? this.disconnectClient()\n : this.disconnectCluster();\n }\n isElectrumClient() {\n return this.electrum.hasOwnProperty(\"connection\");\n }\n async readyClient(timeout) {\n timeout = typeof timeout !== \"undefined\" ? timeout : 3000;\n let connectPromise = async () => {\n while (this.electrum.connection.status !==\n electrum_cash__WEBPACK_IMPORTED_MODULE_0__.ConnectionStatus.CONNECTED) {\n await (0,_util_delay_js__WEBPACK_IMPORTED_MODULE_3__.delay)(100);\n }\n return true;\n };\n return connectPromise;\n }\n async readyCluster(timeout) {\n timeout;\n return this.electrum.ready();\n }\n async connectCluster() {\n return this.electrum.startup();\n }\n async connectClient() {\n let connectionPromise = async () => {\n try {\n return await this.electrum.connect();\n }\n catch (e) {\n console.warn(`Warning: Failed to connect to client on ${this.network} at ${this.electrum.connection.host}.`, e);\n return;\n }\n };\n return [await connectionPromise()];\n }\n async disconnectCluster() {\n return this.electrum.shutdown();\n }\n async disconnectClient() {\n return [await this.electrum.disconnect(true)];\n }\n}\nElectrumNetworkProvider.rawTransactionCache = {};\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/network/ElectrumNetworkProvider.ts?");
|
|
687
|
+
eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"default\": () => (/* binding */ ElectrumNetworkProvider)\n/* harmony export */ });\n/* harmony import */ var electrum_cash__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! electrum-cash */ \"../../node_modules/electrum-cash/dist/index.mjs.js\");\n/* harmony import */ var _interface_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../interface.js */ \"./src/interface.ts\");\n/* harmony import */ var _util_delay_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../util/delay.js */ \"./src/util/delay.ts\");\n/* harmony import */ var _util_transaction_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../util/transaction.js */ \"./src/util/transaction.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_util_transaction_js__WEBPACK_IMPORTED_MODULE_2__]);\n_util_transaction_js__WEBPACK_IMPORTED_MODULE_2__ = (__webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__)[0];\n\n\n\n\nclass ElectrumNetworkProvider {\n constructor(electrum, network = _interface_js__WEBPACK_IMPORTED_MODULE_1__.Network.MAINNET, manualConnectionManagement) {\n this.network = network;\n this.manualConnectionManagement = manualConnectionManagement;\n this.subscriptions = 0;\n this.blockHeight = 0;\n if (electrum) {\n this.electrum = electrum;\n this.connectPromise = this.getConnectPromise();\n if (this.electrum instanceof electrum_cash__WEBPACK_IMPORTED_MODULE_0__.ElectrumCluster) {\n this.version = this.electrum.version;\n }\n else {\n this.version = this.electrum.connection.version;\n }\n }\n else {\n throw new Error(`A electrum-cash cluster or client is required.`);\n }\n }\n async getConnectPromise(_timeout = 3000) {\n // connects to the electrum cash and waits until the connection is ready to accept requests\n let timeoutHandle;\n await Promise.race([\n new Promise(async (resolve) => {\n this.connectPromise = undefined;\n if (this.electrum instanceof electrum_cash__WEBPACK_IMPORTED_MODULE_0__.ElectrumCluster) {\n try {\n await this.connectCluster();\n }\n catch (e) {\n console.warn(`Unable to connect to one or more electrum-cash hosts: ${JSON.stringify(e)}`);\n }\n resolve(await this.readyCluster());\n }\n else {\n resolve(await this.connectClient());\n }\n }),\n // new Promise(\n // (_resolve, reject) =>\n // (timeoutHandle = setTimeout(() => {\n // reject(\n // new Error(`Timeout connecting to electrum network: ${this.network}`)\n // );\n // }, _timeout))\n // ),\n ]);\n clearTimeout(timeoutHandle);\n }\n async getUtxos(cashaddr) {\n const result = (await this.performRequest(\"blockchain.address.listunspent\", cashaddr, \"include_tokens\"));\n return result.map((utxo) => ({\n txid: utxo.tx_hash,\n vout: utxo.tx_pos,\n satoshis: utxo.value,\n height: utxo.height,\n token: utxo.token_data\n ? {\n amount: BigInt(utxo.token_data.amount),\n tokenId: utxo.token_data.category,\n capability: utxo.token_data.nft?.capability,\n commitment: utxo.token_data.nft?.commitment,\n }\n : undefined,\n }));\n }\n async getBalance(cashaddr) {\n const result = (await this.performRequest(\"blockchain.address.get_balance\", cashaddr));\n return result.confirmed + result.unconfirmed;\n }\n async getBlockHeight() {\n return (await this.performRequest(\"blockchain.headers.get_tip\"))\n .height;\n }\n async getRawTransaction(txHash, verbose = false, loadInputValues = false) {\n const key = `${this.network}-${txHash}-${verbose}-${loadInputValues}`;\n if (ElectrumNetworkProvider.rawTransactionCache[key]) {\n return ElectrumNetworkProvider.rawTransactionCache[key];\n }\n try {\n const transaction = (await this.performRequest(\"blockchain.transaction.get\", txHash, verbose));\n ElectrumNetworkProvider.rawTransactionCache[key] = transaction;\n if (verbose && loadInputValues) {\n // get unique transaction hashes\n const hashes = [...new Set(transaction.vin.map((val) => val.txid))];\n const transactions = await Promise.all(hashes.map((hash) => this.getRawTransactionObject(hash, false)));\n const transactionMap = new Map();\n transactions.forEach((val) => transactionMap.set(val.hash, val));\n transaction.vin.forEach((input) => {\n const output = transactionMap\n .get(input.txid)\n .vout.find((val) => val.n === input.vout);\n input.address = output.scriptPubKey.addresses[0];\n input.value = output.value;\n input.tokenData = output.tokenData;\n });\n }\n return transaction;\n }\n catch (error) {\n if (error.message.indexOf(\"No such mempool or blockchain transaction.\") > -1)\n throw Error(`Could not decode transaction ${txHash}. It might not exist on the current blockchain (${this.network}).`);\n else\n throw error;\n }\n }\n // gets the decoded transaction in human readable form\n async getRawTransactionObject(txHash, loadInputValues = false) {\n return (await this.getRawTransaction(txHash, true, loadInputValues));\n }\n async sendRawTransaction(txHex, awaitPropagation = true) {\n return new Promise(async (resolve, reject) => {\n let txHash = await (0,_util_transaction_js__WEBPACK_IMPORTED_MODULE_2__.getTransactionHash)(txHex);\n if (!awaitPropagation) {\n this.performRequest(\"blockchain.transaction.broadcast\", txHex);\n resolve(txHash);\n }\n else {\n const waitForTransactionCallback = async (data) => {\n if (data && data[0] === txHash) {\n this.unsubscribeFromTransaction(txHash, waitForTransactionCallback);\n resolve(txHash);\n }\n };\n this.subscribeToTransaction(txHash, waitForTransactionCallback);\n this.performRequest(\"blockchain.transaction.broadcast\", txHex).catch((error) => {\n this.unsubscribeFromTransaction(txHash, waitForTransactionCallback);\n reject(error);\n });\n }\n });\n }\n // Get transaction history of a given cashaddr\n async getHistory(cashaddr) {\n const result = (await this.performRequest(\"blockchain.address.get_history\", cashaddr));\n return result;\n }\n // Get the minimum fee a low-priority transaction must pay in order to be accepted to the daemon's memory pool.\n async getRelayFee() {\n const result = (await this.performRequest(\"blockchain.relayfee\"));\n return result;\n }\n watchAddressStatus(cashaddr, callback) {\n const watchAddressStatusCallback = async (data) => {\n // subscription acknowledgement is the latest known status or null if no status is known\n // status is an array: [ cashaddr, statusHash ]\n if (data instanceof Array) {\n const addr = data[0];\n if (addr !== cashaddr) {\n return;\n }\n const status = data[1];\n callback(status);\n }\n };\n this.subscribeToAddress(cashaddr, watchAddressStatusCallback);\n return async () => {\n await this.unsubscribeFromAddress(cashaddr, watchAddressStatusCallback);\n };\n }\n watchAddress(cashaddr, callback) {\n const historyMap = {};\n this.getHistory(cashaddr).then((history) => history.forEach((val) => (historyMap[val.tx_hash] = true)));\n const watchAddressStatusCallback = async () => {\n const newHistory = await this.getHistory(cashaddr);\n // sort history to put unconfirmed transactions in the beginning, then transactions in block height descenting order\n const txHashes = newHistory\n .sort((a, b) => a.height <= 0 || b.height <= 0 ? -1 : b.height - a.height)\n .map((val) => val.tx_hash);\n for (const hash of txHashes) {\n if (!(hash in historyMap)) {\n historyMap[hash] = true;\n callback(hash);\n // exit early to prevent further map lookups\n break;\n }\n }\n };\n return this.watchAddressStatus(cashaddr, watchAddressStatusCallback);\n }\n watchAddressTransactions(cashaddr, callback) {\n return this.watchAddress(cashaddr, async (txHash) => {\n const tx = await this.getRawTransactionObject(txHash);\n callback(tx);\n });\n }\n watchAddressTokenTransactions(cashaddr, callback) {\n return this.watchAddress(cashaddr, async (txHash) => {\n const tx = await this.getRawTransactionObject(txHash, true);\n if (tx.vin.some((val) => val.tokenData) ||\n tx.vout.some((val) => val.tokenData)) {\n callback(tx);\n }\n });\n }\n // Wait for the next block or a block at given blockchain height.\n watchBlocks(callback) {\n let acknowledged = false;\n const waitForBlockCallback = (_header) => {\n if (!acknowledged) {\n acknowledged = true;\n return;\n }\n _header = _header instanceof Array ? _header[0] : _header;\n callback(_header);\n };\n this.subscribeToHeaders(waitForBlockCallback);\n return async () => {\n this.unsubscribeFromHeaders(waitForBlockCallback);\n };\n }\n // Wait for the next block or a block at given blockchain height.\n async waitForBlock(height) {\n return new Promise(async (resolve) => {\n const cancelWatch = this.watchBlocks(async (header) => {\n if (height === undefined || header.height >= height) {\n await cancelWatch();\n resolve(header);\n }\n });\n });\n }\n // subscribe to notifications sent when new block is found, the block header is sent to callback\n async subscribeToHeaders(callback) {\n await this.subscribeRequest(\"blockchain.headers.subscribe\", callback);\n }\n // unsubscribe to notifications sent when new block is found\n async unsubscribeFromHeaders(callback) {\n await this.unsubscribeRequest(\"blockchain.headers.subscribe\", callback);\n }\n async subscribeToAddress(cashaddr, callback) {\n await this.subscribeRequest(\"blockchain.address.subscribe\", callback, cashaddr);\n }\n async unsubscribeFromAddress(cashaddr, callback) {\n await this.unsubscribeRequest(\"blockchain.address.subscribe\", callback, cashaddr);\n }\n async subscribeToAddressTransactions(cashaddr, callback) {\n await this.subscribeRequest(\"blockchain.address.transactions.subscribe\", callback, cashaddr);\n }\n async unsubscribeFromAddressTransactions(cashaddr, callback) {\n await this.unsubscribeRequest(\"blockchain.address.transactions.subscribe\", callback, cashaddr);\n }\n async subscribeToTransaction(txHash, callback) {\n await this.subscribeRequest(\"blockchain.transaction.subscribe\", callback, txHash);\n }\n async unsubscribeFromTransaction(txHash, callback) {\n await this.unsubscribeRequest(\"blockchain.transaction.subscribe\", callback, txHash);\n }\n async performRequest(name, ...parameters) {\n await this.ready();\n const requestTimeout = new Promise(function (_resolve, reject) {\n setTimeout(function () {\n reject(\"electrum-cash request timed out, retrying\");\n }, 30000);\n }).catch(function (e) {\n throw e;\n });\n const request = this.electrum.request(name, ...parameters);\n return await Promise.race([request, requestTimeout])\n .then((value) => {\n if (value instanceof Error)\n throw value;\n let result = value;\n return result;\n })\n .catch(async () => {\n // console.warn(\n // \"initial electrum-cash request attempt timed out, retrying...\"\n // );\n return await Promise.race([request, requestTimeout])\n .then((value) => {\n if (value instanceof Error)\n throw value;\n let result = value;\n return result;\n })\n .catch(function (e) {\n throw e;\n });\n });\n }\n async subscribeRequest(methodName, callback, ...parameters) {\n await this.ready();\n const result = await this.electrum.subscribe(callback, methodName, ...parameters);\n this.subscriptions++;\n return result;\n }\n async unsubscribeRequest(methodName, callback, ...parameters) {\n await this.ready();\n const result = this.electrum.unsubscribe(callback, methodName, ...parameters);\n this.subscriptions--;\n return result;\n }\n async ready() {\n return (await this.connect());\n }\n async connect() {\n return await this.connectPromise;\n }\n disconnect() {\n if (this.subscriptions > 0) {\n // console.warn(\n // `Trying to disconnect a network provider with ${this.subscriptions} active subscriptions. This is in most cases a bad idea.`\n // );\n }\n return this.isElectrumClient()\n ? this.disconnectClient()\n : this.disconnectCluster();\n }\n isElectrumClient() {\n return this.electrum.hasOwnProperty(\"connection\");\n }\n async readyClient(timeout) {\n timeout = typeof timeout !== \"undefined\" ? timeout : 3000;\n let connectPromise = async () => {\n while (this.electrum.connection.status !==\n electrum_cash__WEBPACK_IMPORTED_MODULE_0__.ConnectionStatus.CONNECTED) {\n await (0,_util_delay_js__WEBPACK_IMPORTED_MODULE_3__.delay)(100);\n }\n return true;\n };\n return connectPromise;\n }\n async readyCluster(timeout) {\n timeout;\n return this.electrum.ready();\n }\n async connectCluster() {\n return this.electrum.startup();\n }\n async connectClient() {\n let connectionPromise = async () => {\n try {\n return await this.electrum.connect();\n }\n catch (e) {\n console.warn(`Warning: Failed to connect to client on ${this.network} at ${this.electrum.connection.host}.`, e);\n return;\n }\n };\n return [await connectionPromise()];\n }\n async disconnectCluster() {\n return this.electrum.shutdown();\n }\n async disconnectClient() {\n return [await this.electrum.disconnect(true)];\n }\n}\nElectrumNetworkProvider.rawTransactionCache = {};\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/network/ElectrumNetworkProvider.ts?");
|
|
688
688
|
|
|
689
689
|
/***/ }),
|
|
690
690
|
|
|
@@ -1084,7 +1084,7 @@ eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__
|
|
|
1084
1084
|
\**********************************/
|
|
1085
1085
|
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
|
|
1086
1086
|
|
|
1087
|
-
eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"sumTokenAmounts\": () => (/* binding */ sumTokenAmounts),\n/* harmony export */ \"sumUtxoValue\": () => (/* binding */ sumUtxoValue)\n/* harmony export */ });\nfunction sumUtxoValue(utxos) {\n if (utxos.length > 0) {\n const balanceArray = utxos.map((o) => {\n return o.satoshis;\n });\n const balance = balanceArray.reduce((a, b) => a + b, 0);\n return balance;\n }\n else {\n return 0;\n }\n}\nfunction sumTokenAmounts(utxos, tokenId) {\n if (utxos.length > 0) {\n const tokenArray = utxos\n .filter((utxo) => utxo.token?.tokenId === tokenId)\n .map((o) => {\n return o.token?.amount ||
|
|
1087
|
+
eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"sumTokenAmounts\": () => (/* binding */ sumTokenAmounts),\n/* harmony export */ \"sumUtxoValue\": () => (/* binding */ sumUtxoValue)\n/* harmony export */ });\nfunction sumUtxoValue(utxos) {\n if (utxos.length > 0) {\n const balanceArray = utxos.map((o) => {\n return o.satoshis;\n });\n const balance = balanceArray.reduce((a, b) => a + b, 0);\n return balance;\n }\n else {\n return 0;\n }\n}\nfunction sumTokenAmounts(utxos, tokenId) {\n if (utxos.length > 0) {\n const tokenArray = utxos\n .filter((utxo) => utxo.token?.tokenId === tokenId)\n .map((o) => {\n return o.token?.amount || 0n;\n });\n const balance = tokenArray.reduce((a, b) => a + b, 0n);\n return balance;\n }\n else {\n return 0n;\n }\n}\n\n\n//# sourceURL=webpack://mainnet-js/./src/util/sumUtxoValue.ts?");
|
|
1088
1088
|
|
|
1089
1089
|
/***/ }),
|
|
1090
1090
|
|
|
@@ -1114,7 +1114,7 @@ eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__
|
|
|
1114
1114
|
\****************************/
|
|
1115
1115
|
/***/ ((module, __webpack_exports__, __webpack_require__) => {
|
|
1116
1116
|
|
|
1117
|
-
eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"BCMR\": () => (/* binding */ BCMR)\n/* harmony export */ });\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/hex.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/crypto/default-crypto-instances.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/utf8.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/message/transaction-encoding.js\");\n/* harmony import */ var _interface_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../interface.js */ \"./src/interface.ts\");\n/* harmony import */ var _network_Connection_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../network/Connection.js */ \"./src/network/Connection.ts\");\n/* harmony import */ var _model_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./model.js */ \"./src/wallet/model.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__, _model_js__WEBPACK_IMPORTED_MODULE_3__, _network_Connection_js__WEBPACK_IMPORTED_MODULE_5__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__]);\n([_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__, _model_js__WEBPACK_IMPORTED_MODULE_3__, _network_Connection_js__WEBPACK_IMPORTED_MODULE_5__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\n\n\n// Implementation of CHIP-BCMR v2.0.0-draft, refer to https://github.com/bitjson/chip-bcmr\nclass BCMR {\n static getRegistries() {\n return this.metadataRegistries;\n }\n static resetRegistries() {\n this.metadataRegistries = [];\n }\n /**\n * fetchMetadataRegistry Fetch the BCMR registry JSON file from a remote URI, optionally verifying its content hash\n *\n * @param {string} uri URI of the registry to fetch from\n * @param {string?} contentHash SHA256 hash of the resource the `uri` parameter points at.\n * If specified, calculates the hash of the data fetched from `uri` and matches it with provided one.\n * Yields an error upon mismatch.\n *\n * @returns {Registry} resolved registry\n */\n static async fetchMetadataRegistry(uri, contentHash) {\n if (uri.indexOf(\"https://\") < 0) {\n uri = `https://${uri}`;\n }\n // content hashes HTTPS Publication Outputs per spec\n if (contentHash) {\n // request as text and verify hash\n const response = await fetch(uri);\n const data = await response.text();\n const hash = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.binToHex)(_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.sha256.hash((0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.utf8ToBin)(data)));\n if (contentHash != hash) {\n throw new Error(`Content hash mismatch for URI: ${uri}\\nreceived: ${hash}\\nrequired: ${contentHash}`);\n }\n return JSON.parse(data);\n }\n // request as JSON\n const response = await fetch(uri);\n const data = await response.json();\n return data;\n }\n /**\n * addMetadataRegistry Add the metadata registry to the list of tracked registries\n *\n * @param {Registry} registry Registry object per schema specification, see https://raw.githubusercontent.com/bitjson/chip-bcmr/master/bcmr-v1.schema.json\n *\n */\n static addMetadataRegistry(registry) {\n if (this.metadataRegistries.some((val) => JSON.stringify(val) === JSON.stringify(registry))) {\n return;\n }\n this.metadataRegistries.push(registry);\n }\n /**\n * addMetadataRegistryFromUri Add the metadata registry by fetching a JSON file from a remote URI, optionally verifying its content hash\n *\n * @param {string} uri URI of the registry to fetch from\n * @param {string?} contentHash SHA256 hash of the resource the `uri` parameter points at.\n * If specified, calculates the hash of the data fetched from `uri` and matches it with provided one.\n * Yields an error upon mismatch.\n *\n */\n static async addMetadataRegistryFromUri(uri, contentHash) {\n const registry = await this.fetchMetadataRegistry(uri, contentHash);\n this.addMetadataRegistry(registry);\n }\n // helper function to enforce the constraints on the 0th output, decode the BCMR's OP_RETURN data\n // returns resolved AuthChainElement\n static makeAuthChainElement(rawTx, hash) {\n let opReturns;\n let spends0thOutput = false;\n if (rawTx.hasOwnProperty(\"vout\")) {\n const electrumTransaction = rawTx;\n opReturns = electrumTransaction.vout\n .filter((val) => val.scriptPubKey.type === \"nulldata\")\n .map((val) => val.scriptPubKey.hex);\n spends0thOutput = electrumTransaction.vin.some((val) => val.vout === 0);\n }\n else {\n const libauthTransaction = rawTx;\n opReturns = libauthTransaction.outputs\n .map((val) => (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.binToHex)(val.lockingBytecode))\n .filter((val) => val.indexOf(\"6a\") === 0);\n spends0thOutput = libauthTransaction.inputs.some((val) => val.outpointIndex === 0);\n }\n if (!spends0thOutput) {\n throw new Error(\"Invalid authchain transaction (does not spend 0th output of previous transaction)\");\n }\n const bcmrOpReturns = opReturns.filter((val) => val.indexOf(\"6a0442434d52\") === 0 ||\n val.indexOf(\"6a4c0442434d52\") === 0 ||\n val.indexOf(\"6a4d040042434d52\") === 0 ||\n val.indexOf(\"6a4e0400000042434d52\") === 0);\n if (bcmrOpReturns.length === 0) {\n return {\n txHash: hash,\n contentHash: \"\",\n uris: [],\n httpsUrl: \"\",\n };\n }\n const opReturnHex = opReturns[0];\n const chunks = _model_js__WEBPACK_IMPORTED_MODULE_3__.OpReturnData.parseBinary((0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.hexToBin)(opReturnHex));\n if (chunks.length < 2) {\n throw new Error(`Malformed BCMR output: ${opReturnHex}`);\n }\n const result = {\n txHash: hash,\n contentHash: \"\",\n uris: [],\n httpsUrl: \"\",\n };\n if (chunks.length === 2) {\n // IPFS Publication Output\n result.contentHash = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.binToHex)(chunks[1]);\n const ipfsCid = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.binToUtf8)(chunks[1]);\n result.uris = [`ipfs://${ipfsCid}`];\n result.httpsUrl = `https://dweb.link/ipfs/${ipfsCid}`;\n }\n else {\n // URI Publication Output\n // content hash is in OP_SHA256 byte order per spec\n result.contentHash = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.binToHex)(chunks[1].slice());\n const uris = chunks.slice(2);\n for (const uri of uris) {\n const uriString = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.binToUtf8)(uri);\n result.uris.push(uriString);\n if (result.httpsUrl) {\n continue;\n }\n if (uriString.indexOf(\"ipfs://\") === 0) {\n const ipfsCid = uriString.replace(\"ipfs://\", \"\");\n result.httpsUrl = `https://dweb.link/ipfs/${ipfsCid}`;\n }\n else if (uriString.indexOf(\"https://\") === 0) {\n result.httpsUrl = uriString;\n }\n else if (uriString.indexOf(\"https://\") === -1) {\n result.httpsUrl = uriString;\n // case for domain name specifier, like example.com\n if (uriString.indexOf(\"/\") === -1) {\n const parts = uriString.toLowerCase().split(\".\");\n if (!(parts?.[0]?.indexOf(\"baf\") === 0 && parts?.[1] === \"ipfs\")) {\n result.httpsUrl = `${result.httpsUrl}/.well-known/bitcoin-cash-metadata-registry.json`;\n }\n }\n result.httpsUrl = `https://${result.httpsUrl}`;\n }\n else {\n throw new Error(`Unsupported uri type: ${uriString}`);\n }\n }\n }\n return result;\n }\n /**\n * buildAuthChain Build an authchain - Zeroth-Descendant Transaction Chain, refer to https://github.com/bitjson/chip-bcmr#zeroth-descendant-transaction-chains\n * The authchain in this implementation is specific to resolve to a valid metadata registry\n *\n * @param {string} options.transactionHash (required) transaction hash from which to build the auth chain\n * @param {Network?} options.network (default=mainnet) network to query the data from\n * @param {boolean?} options.resolveBase (default=false) boolean flag to indicate that autchain building should resolve and verify elements back to base or be stopped at this exact chain element\n * @param {boolean?} options.followToHead (default=true) boolean flag to indicate that autchain building should progress to head or be stopped at this exact chain element\n * @param {ElectrumRawTransaction?} options.rawTx cached raw transaction obtained previously, spares a Fulcrum call\n * @param {TxI[]?} options.historyCache cached address history to be reused if authchain building proceeds with the same address, spares a flurry of Fulcrum calls\n *\n * @returns {AuthChain} returns the resolved authchain\n */\n static async buildAuthChain(options) {\n if (options.network === undefined) {\n options.network = _interface_js__WEBPACK_IMPORTED_MODULE_4__.Network.MAINNET;\n }\n if (options.followToHead === undefined) {\n options.followToHead = true;\n }\n if (options.resolveBase === undefined) {\n options.resolveBase = false;\n }\n const provider = (await (0,_network_Connection_js__WEBPACK_IMPORTED_MODULE_5__.initProvider)(options.network));\n if (options.rawTx === undefined) {\n options.rawTx = await provider.getRawTransactionObject(options.transactionHash);\n }\n // figure out the autchain by moving towards authhead\n const getAuthChainChild = async () => {\n const history = options.historyCache ||\n (await provider.getHistory(options.rawTx.vout[0].scriptPubKey.addresses[0]));\n const thisTx = history.find((val) => val.tx_hash === options.transactionHash);\n let filteredHistory = history.filter((val) => val.height > 0\n ? val.height >= thisTx.height || val.height <= 0\n : val.height <= 0 && val.tx_hash !== thisTx.tx_hash);\n for (const historyTx of filteredHistory) {\n const historyRawTx = await provider.getRawTransactionObject(historyTx.tx_hash);\n const authChainVin = historyRawTx.vin.find((val) => val.txid === options.transactionHash && val.vout === 0);\n // if we've found continuation of authchain, we shall recurse into it\n if (authChainVin) {\n // reuse queried address history if the next element in chain is the same address\n const historyCache = options.rawTx.vout[0].scriptPubKey.addresses[0] ===\n historyRawTx.vout[0].scriptPubKey.addresses[0]\n ? filteredHistory\n : undefined;\n // combine the authchain element with the rest obtained\n return { rawTx: historyRawTx, historyCache };\n }\n }\n return undefined;\n };\n // make authchain element and combine with the rest obtained\n let element;\n try {\n element = BCMR.makeAuthChainElement(options.rawTx, options.rawTx.hash);\n }\n catch (error) {\n // special case for cashtoken authchain lookup by categoryId - allow to fail first lookup and inspect the genesis transaction\n // follow authchain to head and look for BCMR outputs\n const child = await getAuthChainChild();\n if (child) {\n return await BCMR.buildAuthChain({\n ...options,\n transactionHash: child.rawTx.hash,\n rawTx: child.rawTx,\n historyCache: child.historyCache,\n });\n }\n else {\n throw error;\n }\n }\n let chainBase = [];\n if (options.resolveBase) {\n // check for accelerated path if \"authchain\" extension is in registry\n const registry = await this.fetchMetadataRegistry(element.httpsUrl, element.contentHash);\n if (registry.extensions &&\n registry.extensions[\"authchain\"] &&\n Object.keys(registry.extensions[\"authchain\"]).length) {\n const chainTxArray = Object.values(registry.extensions[\"authchain\"]);\n chainBase = chainTxArray\n .map((tx) => {\n const transactionBin = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.hexToBin)(tx);\n const decoded = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__.decodeTransaction)(transactionBin);\n if (typeof decoded === \"string\") {\n throw new Error(`Error decoding transaction ${JSON.stringify(tx)}, ${decoded}`);\n }\n const hash = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.binToHex)(_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.sha256.hash(_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.sha256.hash(transactionBin)).reverse());\n return { decoded, hash };\n })\n .map(({ decoded, hash }) => BCMR.makeAuthChainElement(decoded, hash));\n }\n else {\n // simply go back in history towards authhead\n let stop = false;\n let tx = { ...options.rawTx };\n let maxElements = 10;\n while (stop == false || maxElements === 0) {\n const vin = tx.vin.find((val) => val.vout === 0);\n tx = await provider.getRawTransactionObject(vin.txid);\n try {\n const pastElement = BCMR.makeAuthChainElement(tx, tx.hash);\n chainBase.unshift(pastElement);\n maxElements--;\n }\n catch {\n stop = true;\n }\n }\n }\n }\n // if we follow to head, we need to locate the next transaction spending our 0th output\n // and repeat the building process recursively\n if (options.followToHead) {\n const child = await getAuthChainChild();\n if (child) {\n const chainHead = await BCMR.buildAuthChain({\n transactionHash: child.rawTx.hash,\n network: options.network,\n rawTx: child.rawTx,\n historyCache: child.historyCache,\n followToHead: options.followToHead,\n resolveBase: false,\n });\n // combine the authchain element with the rest obtained\n return [...chainBase, element, ...chainHead].filter((val) => val.httpsUrl.length);\n }\n }\n // return the last chain element (or the only found in an edge case)\n return [...chainBase, element].filter((val) => val.httpsUrl.length);\n }\n /**\n * fetchAuthChainFromChaingraph Fetch the authchain information from a trusted external indexer\n * The authchain in this implementation is specific to resolve to a valid metadata registry\n *\n * @param {string} options.chaingraphUrl (required) URL of a chaingraph indexer instance to fetch info from\n * @param {string} options.transactionHash (required) transaction hash from which to build the auth chain\n * @param {string?} options.network (default=undefined) network to query the data from, specific to the queried instance,\n * can be 'mainnet', 'chipnet', or anything else.\n * if left undefined all chaingraph transactions will be looked at, disregarding the chain\n *\n * @returns {AuthChain} returns the resolved authchain\n */\n static async fetchAuthChainFromChaingraph(options) {\n if (!options.chaingraphUrl) {\n throw new Error(\"Provide `chaingraphUrl` param.\");\n }\n const response = await fetch(options.chaingraphUrl, {\n method: \"POST\",\n headers: {\n Accept: \"*/*\",\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n operationName: null,\n variables: {},\n query: `\n{\n transaction(\n where: {\n hash:{_eq:\"\\\\\\\\x${options.transactionHash}\"}\n }\n ) {\n hash\n authchains {\n authchain_length\n migrations(\n where: {\n transaction: {\n outputs: { locking_bytecode_pattern: { _like: \"6a04%\" } }\n }\n }\n ) {\n transaction {\n hash\n inputs(where:{ outpoint_index: { _eq:\"0\" } }){\n outpoint_index\n }\n outputs(where: { locking_bytecode_pattern: { _like: \"6a04%\" } }) {\n output_index\n locking_bytecode\n }\n }\n }\n }\n }\n}`,\n }),\n });\n const responseData = await response.json();\n const result = [];\n const migrations = responseData.data.transaction[0]?.authchains[0].migrations;\n if (!migrations) {\n return result;\n }\n for (const migration of migrations) {\n const transaction = migration.transaction[0];\n if (!transaction) {\n continue;\n }\n transaction.inputs.forEach((input) => (input.outpointIndex = Number(input.outpoint_index)));\n transaction.outputs.forEach((output) => {\n output.outputIndex = Number(output.output_index);\n output.lockingBytecode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.hexToBin)(output.locking_bytecode.replace(\"\\\\x\", \"\"));\n });\n const txHash = transaction.hash.replace(\"\\\\x\", \"\");\n result.push(BCMR.makeAuthChainElement(transaction, txHash));\n }\n return result.filter((element) => element.contentHash.length && element.httpsUrl.length);\n }\n /**\n * addMetadataRegistryAuthChain Add BCMR metadata registry by resolving an authchain\n *\n * @param {string} options.transactionHash (required) transaction hash from which to build the auth chain\n * @param {Network?} options.network (default=mainnet) network to query the data from\n * @param {boolean?} options.followToHead (default=true) boolean flag to indicate that autchain building should progress to head (most recent registry version) or be stopped at this exact chain element\n * @param {ElectrumRawTransaction?} options.rawTx cached raw transaction obtained previously, spares a Fulcrum call\n *\n * @returns {AuthChain} returns the resolved authchain\n */\n static async addMetadataRegistryAuthChain(options) {\n const authChain = await this.buildAuthChain({\n ...options,\n resolveBase: false,\n });\n if (!authChain.length) {\n throw new Error(`There were no BCMR entries in the resolved authchain ${JSON.stringify(authChain, null, 2)}`);\n }\n const registry = await this.fetchMetadataRegistry(authChain.reverse()[0].httpsUrl);\n this.addMetadataRegistry(registry);\n return authChain;\n }\n /**\n * getTokenInfo Return the token info (or the identity snapshot as per spec)\n *\n * @param {string} tokenId token id to look up\n *\n * @returns {IdentitySnapshot?} return the info for the token found, otherwise undefined\n */\n static getTokenInfo(tokenId) {\n for (const registry of this.metadataRegistries.slice().reverse()) {\n const history = registry.identities?.[tokenId];\n if (!history) {\n continue;\n }\n const latestIdentityIndex = Object.keys(history)[0];\n if (latestIdentityIndex === undefined) {\n continue;\n }\n return history[latestIdentityIndex];\n }\n return undefined;\n }\n}\n// List of tracked registries\nBCMR.metadataRegistries = [];\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/wallet/Bcmr.ts?");
|
|
1117
|
+
eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"BCMR\": () => (/* binding */ BCMR)\n/* harmony export */ });\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/hex.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/crypto/default-crypto-instances.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/utf8.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/message/transaction-encoding.js\");\n/* harmony import */ var _interface_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../interface.js */ \"./src/interface.ts\");\n/* harmony import */ var _network_Connection_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../network/Connection.js */ \"./src/network/Connection.ts\");\n/* harmony import */ var _model_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./model.js */ \"./src/wallet/model.ts\");\n/* harmony import */ var _config_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../config.js */ \"./src/config.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__, _model_js__WEBPACK_IMPORTED_MODULE_3__, _network_Connection_js__WEBPACK_IMPORTED_MODULE_6__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__]);\n([_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__, _model_js__WEBPACK_IMPORTED_MODULE_3__, _network_Connection_js__WEBPACK_IMPORTED_MODULE_6__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\n\n\n\n// Implementation of CHIP-BCMR v2.0.0-draft, refer to https://github.com/bitjson/chip-bcmr\nclass BCMR {\n static getRegistries() {\n return this.metadataRegistries;\n }\n static resetRegistries() {\n this.metadataRegistries = [];\n }\n /**\n * fetchMetadataRegistry Fetch the BCMR registry JSON file from a remote URI, optionally verifying its content hash\n *\n * @param {string} uri URI of the registry to fetch from\n * @param {string?} contentHash SHA256 hash of the resource the `uri` parameter points at.\n * If specified, calculates the hash of the data fetched from `uri` and matches it with provided one.\n * Yields an error upon mismatch.\n *\n * @returns {Registry} resolved registry\n */\n static async fetchMetadataRegistry(uri, contentHash) {\n if (uri.indexOf(\"https://\") < 0) {\n uri = `https://${uri}`;\n }\n // content hashes HTTPS Publication Outputs per spec\n if (contentHash) {\n // request as text and verify hash\n const response = await fetch(uri);\n const data = await response.text();\n const hash = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.binToHex)(_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.sha256.hash((0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.utf8ToBin)(data)));\n if (contentHash != hash) {\n throw new Error(`Content hash mismatch for URI: ${uri}\\nreceived: ${hash}\\nrequired: ${contentHash}`);\n }\n return JSON.parse(data);\n }\n // request as JSON\n const response = await fetch(uri);\n const data = await response.json();\n return data;\n }\n /**\n * addMetadataRegistry Add the metadata registry to the list of tracked registries\n *\n * @param {Registry} registry Registry object per schema specification, see https://raw.githubusercontent.com/bitjson/chip-bcmr/master/bcmr-v1.schema.json\n *\n */\n static addMetadataRegistry(registry) {\n if (this.metadataRegistries.some((val) => JSON.stringify(val) === JSON.stringify(registry))) {\n return;\n }\n this.metadataRegistries.push(registry);\n }\n /**\n * addMetadataRegistryFromUri Add the metadata registry by fetching a JSON file from a remote URI, optionally verifying its content hash\n *\n * @param {string} uri URI of the registry to fetch from\n * @param {string?} contentHash SHA256 hash of the resource the `uri` parameter points at.\n * If specified, calculates the hash of the data fetched from `uri` and matches it with provided one.\n * Yields an error upon mismatch.\n *\n */\n static async addMetadataRegistryFromUri(uri, contentHash) {\n const registry = await this.fetchMetadataRegistry(uri, contentHash);\n this.addMetadataRegistry(registry);\n }\n // helper function to enforce the constraints on the 0th output, decode the BCMR's OP_RETURN data\n // returns resolved AuthChainElement\n static makeAuthChainElement(rawTx, hash) {\n let opReturns;\n let spends0thOutput = false;\n if (rawTx.hasOwnProperty(\"vout\")) {\n const electrumTransaction = rawTx;\n opReturns = electrumTransaction.vout\n .filter((val) => val.scriptPubKey.type === \"nulldata\")\n .map((val) => val.scriptPubKey.hex);\n spends0thOutput = electrumTransaction.vin.some((val) => val.vout === 0);\n }\n else {\n const libauthTransaction = rawTx;\n opReturns = libauthTransaction.outputs\n .map((val) => (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.binToHex)(val.lockingBytecode))\n .filter((val) => val.indexOf(\"6a\") === 0);\n spends0thOutput = libauthTransaction.inputs.some((val) => val.outpointIndex === 0);\n }\n if (!spends0thOutput) {\n throw new Error(\"Invalid authchain transaction (does not spend 0th output of previous transaction)\");\n }\n const bcmrOpReturns = opReturns.filter((val) => val.indexOf(\"6a0442434d52\") === 0 ||\n val.indexOf(\"6a4c0442434d52\") === 0 ||\n val.indexOf(\"6a4d040042434d52\") === 0 ||\n val.indexOf(\"6a4e0400000042434d52\") === 0);\n if (bcmrOpReturns.length === 0) {\n return {\n txHash: hash,\n contentHash: \"\",\n uris: [],\n httpsUrl: \"\",\n };\n }\n const opReturnHex = opReturns[0];\n const chunks = _model_js__WEBPACK_IMPORTED_MODULE_3__.OpReturnData.parseBinary((0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.hexToBin)(opReturnHex));\n if (chunks.length < 2) {\n throw new Error(`Malformed BCMR output: ${opReturnHex}`);\n }\n const result = {\n txHash: hash,\n contentHash: \"\",\n uris: [],\n httpsUrl: \"\",\n };\n if (chunks.length === 2) {\n // IPFS Publication Output\n result.contentHash = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.binToHex)(chunks[1]);\n const ipfsCid = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.binToUtf8)(chunks[1]);\n result.uris = [`ipfs://${ipfsCid}`];\n result.httpsUrl = `${_config_js__WEBPACK_IMPORTED_MODULE_4__.Config.DefaultIpfsGateway}${ipfsCid}`;\n }\n else {\n // URI Publication Output\n // content hash is in OP_SHA256 byte order per spec\n result.contentHash = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.binToHex)(chunks[1].slice());\n const uris = chunks.slice(2);\n for (const uri of uris) {\n const uriString = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.binToUtf8)(uri);\n result.uris.push(uriString);\n if (result.httpsUrl) {\n continue;\n }\n if (uriString.indexOf(\"ipfs://\") === 0) {\n const ipfsCid = uriString.replace(\"ipfs://\", \"\");\n result.httpsUrl = `${_config_js__WEBPACK_IMPORTED_MODULE_4__.Config.DefaultIpfsGateway}${ipfsCid}`;\n }\n else if (uriString.indexOf(\"https://\") === 0) {\n result.httpsUrl = uriString;\n }\n else if (uriString.indexOf(\"https://\") === -1) {\n result.httpsUrl = uriString;\n // case for domain name specifier, like example.com\n if (uriString.indexOf(\"/\") === -1) {\n const parts = uriString.toLowerCase().split(\".\");\n if (!(parts?.[0]?.indexOf(\"baf\") === 0 && parts?.[1] === \"ipfs\")) {\n result.httpsUrl = `${result.httpsUrl}/.well-known/bitcoin-cash-metadata-registry.json`;\n }\n }\n result.httpsUrl = `https://${result.httpsUrl}`;\n }\n else {\n throw new Error(`Unsupported uri type: ${uriString}`);\n }\n }\n }\n return result;\n }\n /**\n * buildAuthChain Build an authchain - Zeroth-Descendant Transaction Chain, refer to https://github.com/bitjson/chip-bcmr#zeroth-descendant-transaction-chains\n * The authchain in this implementation is specific to resolve to a valid metadata registry\n *\n * @param {string} options.transactionHash (required) transaction hash from which to build the auth chain\n * @param {Network?} options.network (default=mainnet) network to query the data from\n * @param {boolean?} options.resolveBase (default=false) boolean flag to indicate that autchain building should resolve and verify elements back to base or be stopped at this exact chain element\n * @param {boolean?} options.followToHead (default=true) boolean flag to indicate that autchain building should progress to head or be stopped at this exact chain element\n * @param {ElectrumRawTransaction?} options.rawTx cached raw transaction obtained previously, spares a Fulcrum call\n * @param {TxI[]?} options.historyCache cached address history to be reused if authchain building proceeds with the same address, spares a flurry of Fulcrum calls\n *\n * @returns {AuthChain} returns the resolved authchain\n */\n static async buildAuthChain(options) {\n if (options.network === undefined) {\n options.network = _interface_js__WEBPACK_IMPORTED_MODULE_5__.Network.MAINNET;\n }\n if (options.followToHead === undefined) {\n options.followToHead = true;\n }\n if (options.resolveBase === undefined) {\n options.resolveBase = false;\n }\n const provider = (await (0,_network_Connection_js__WEBPACK_IMPORTED_MODULE_6__.initProvider)(options.network));\n if (options.rawTx === undefined) {\n options.rawTx = await provider.getRawTransactionObject(options.transactionHash);\n }\n // figure out the autchain by moving towards authhead\n const getAuthChainChild = async () => {\n const history = options.historyCache ||\n (await provider.getHistory(options.rawTx.vout[0].scriptPubKey.addresses[0]));\n const thisTx = history.find((val) => val.tx_hash === options.transactionHash);\n let filteredHistory = history.filter((val) => val.height > 0\n ? val.height >= thisTx.height || val.height <= 0\n : val.height <= 0 && val.tx_hash !== thisTx.tx_hash);\n for (const historyTx of filteredHistory) {\n const historyRawTx = await provider.getRawTransactionObject(historyTx.tx_hash);\n const authChainVin = historyRawTx.vin.find((val) => val.txid === options.transactionHash && val.vout === 0);\n // if we've found continuation of authchain, we shall recurse into it\n if (authChainVin) {\n // reuse queried address history if the next element in chain is the same address\n const historyCache = options.rawTx.vout[0].scriptPubKey.addresses[0] ===\n historyRawTx.vout[0].scriptPubKey.addresses[0]\n ? filteredHistory\n : undefined;\n // combine the authchain element with the rest obtained\n return { rawTx: historyRawTx, historyCache };\n }\n }\n return undefined;\n };\n // make authchain element and combine with the rest obtained\n let element;\n try {\n element = BCMR.makeAuthChainElement(options.rawTx, options.rawTx.hash);\n }\n catch (error) {\n // special case for cashtoken authchain lookup by categoryId - allow to fail first lookup and inspect the genesis transaction\n // follow authchain to head and look for BCMR outputs\n const child = await getAuthChainChild();\n if (child) {\n return await BCMR.buildAuthChain({\n ...options,\n transactionHash: child.rawTx.hash,\n rawTx: child.rawTx,\n historyCache: child.historyCache,\n });\n }\n else {\n throw error;\n }\n }\n let chainBase = [];\n if (options.resolveBase) {\n // check for accelerated path if \"authchain\" extension is in registry\n const registry = await this.fetchMetadataRegistry(element.httpsUrl, element.contentHash);\n if (registry.extensions &&\n registry.extensions[\"authchain\"] &&\n Object.keys(registry.extensions[\"authchain\"]).length) {\n const chainTxArray = Object.values(registry.extensions[\"authchain\"]);\n chainBase = chainTxArray\n .map((tx) => {\n const transactionBin = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.hexToBin)(tx);\n const decoded = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__.decodeTransaction)(transactionBin);\n if (typeof decoded === \"string\") {\n throw new Error(`Error decoding transaction ${JSON.stringify(tx)}, ${decoded}`);\n }\n const hash = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.binToHex)(_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.sha256.hash(_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.sha256.hash(transactionBin)).reverse());\n return { decoded, hash };\n })\n .map(({ decoded, hash }) => BCMR.makeAuthChainElement(decoded, hash));\n }\n else {\n // simply go back in history towards authhead\n let stop = false;\n let tx = { ...options.rawTx };\n let maxElements = 10;\n while (stop == false || maxElements === 0) {\n const vin = tx.vin.find((val) => val.vout === 0);\n tx = await provider.getRawTransactionObject(vin.txid);\n try {\n const pastElement = BCMR.makeAuthChainElement(tx, tx.hash);\n chainBase.unshift(pastElement);\n maxElements--;\n }\n catch {\n stop = true;\n }\n }\n }\n }\n // if we follow to head, we need to locate the next transaction spending our 0th output\n // and repeat the building process recursively\n if (options.followToHead) {\n const child = await getAuthChainChild();\n if (child) {\n const chainHead = await BCMR.buildAuthChain({\n transactionHash: child.rawTx.hash,\n network: options.network,\n rawTx: child.rawTx,\n historyCache: child.historyCache,\n followToHead: options.followToHead,\n resolveBase: false,\n });\n // combine the authchain element with the rest obtained\n return [...chainBase, element, ...chainHead].filter((val) => val.httpsUrl.length);\n }\n }\n // return the last chain element (or the only found in an edge case)\n return [...chainBase, element].filter((val) => val.httpsUrl.length);\n }\n /**\n * fetchAuthChainFromChaingraph Fetch the authchain information from a trusted external indexer\n * The authchain in this implementation is specific to resolve to a valid metadata registry\n *\n * @param {string} options.chaingraphUrl (required) URL of a chaingraph indexer instance to fetch info from\n * @param {string} options.transactionHash (required) transaction hash from which to build the auth chain\n * @param {string?} options.network (default=undefined) network to query the data from, specific to the queried instance,\n * can be 'mainnet', 'chipnet', or anything else.\n * if left undefined all chaingraph transactions will be looked at, disregarding the chain\n *\n * @returns {AuthChain} returns the resolved authchain\n */\n static async fetchAuthChainFromChaingraph(options) {\n if (!options.chaingraphUrl) {\n throw new Error(\"Provide `chaingraphUrl` param.\");\n }\n const response = await fetch(options.chaingraphUrl, {\n method: \"POST\",\n headers: {\n Accept: \"*/*\",\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n operationName: null,\n variables: {},\n query: `\n{\n transaction(\n where: {\n hash:{_eq:\"\\\\\\\\x${options.transactionHash}\"}\n }\n ) {\n hash\n authchains {\n authchain_length\n migrations(\n where: {\n transaction: {\n outputs: { locking_bytecode_pattern: { _like: \"6a04%\" } }\n }\n }\n ) {\n transaction {\n hash\n inputs(where:{ outpoint_index: { _eq:\"0\" } }){\n outpoint_index\n }\n outputs(where: { locking_bytecode_pattern: { _like: \"6a04%\" } }) {\n output_index\n locking_bytecode\n }\n }\n }\n }\n }\n}`,\n }),\n });\n const responseData = await response.json();\n const result = [];\n const migrations = responseData.data.transaction[0]?.authchains[0].migrations;\n if (!migrations) {\n return result;\n }\n for (const migration of migrations) {\n const transaction = migration.transaction[0];\n if (!transaction) {\n continue;\n }\n transaction.inputs.forEach((input) => (input.outpointIndex = Number(input.outpoint_index)));\n transaction.outputs.forEach((output) => {\n output.outputIndex = Number(output.output_index);\n output.lockingBytecode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.hexToBin)(output.locking_bytecode.replace(\"\\\\x\", \"\"));\n });\n const txHash = transaction.hash.replace(\"\\\\x\", \"\");\n result.push(BCMR.makeAuthChainElement(transaction, txHash));\n }\n return result.filter((element) => element.contentHash.length && element.httpsUrl.length);\n }\n /**\n * addMetadataRegistryAuthChain Add BCMR metadata registry by resolving an authchain\n *\n * @param {string} options.transactionHash (required) transaction hash from which to build the auth chain\n * @param {Network?} options.network (default=mainnet) network to query the data from\n * @param {boolean?} options.followToHead (default=true) boolean flag to indicate that autchain building should progress to head (most recent registry version) or be stopped at this exact chain element\n * @param {ElectrumRawTransaction?} options.rawTx cached raw transaction obtained previously, spares a Fulcrum call\n *\n * @returns {AuthChain} returns the resolved authchain\n */\n static async addMetadataRegistryAuthChain(options) {\n const authChain = await this.buildAuthChain({\n ...options,\n resolveBase: false,\n });\n if (!authChain.length) {\n throw new Error(`There were no BCMR entries in the resolved authchain ${JSON.stringify(authChain, null, 2)}`);\n }\n const registry = await this.fetchMetadataRegistry(authChain.reverse()[0].httpsUrl);\n this.addMetadataRegistry(registry);\n return authChain;\n }\n /**\n * getTokenInfo Return the token info (or the identity snapshot as per spec)\n *\n * @param {string} tokenId token id to look up\n *\n * @returns {IdentitySnapshot?} return the info for the token found, otherwise undefined\n */\n static getTokenInfo(tokenId) {\n for (const registry of this.metadataRegistries.slice().reverse()) {\n const history = registry.identities?.[tokenId];\n if (!history) {\n continue;\n }\n const latestIdentityIndex = Object.keys(history)[0];\n if (latestIdentityIndex === undefined) {\n continue;\n }\n return history[latestIdentityIndex];\n }\n return undefined;\n }\n}\n// List of tracked registries\nBCMR.metadataRegistries = [];\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/wallet/Bcmr.ts?");
|
|
1118
1118
|
|
|
1119
1119
|
/***/ }),
|
|
1120
1120
|
|
|
@@ -1134,7 +1134,7 @@ eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__
|
|
|
1134
1134
|
\***************************/
|
|
1135
1135
|
/***/ ((module, __webpack_exports__, __webpack_require__) => {
|
|
1136
1136
|
|
|
1137
|
-
eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"RegTestWallet\": () => (/* binding */ RegTestWallet),\n/* harmony export */ \"RegTestWatchWallet\": () => (/* binding */ RegTestWatchWallet),\n/* harmony export */ \"RegTestWifWallet\": () => (/* binding */ RegTestWifWallet),\n/* harmony export */ \"TestNetWallet\": () => (/* binding */ TestNetWallet),\n/* harmony export */ \"TestNetWatchWallet\": () => (/* binding */ TestNetWatchWallet),\n/* harmony export */ \"TestNetWifWallet\": () => (/* binding */ TestNetWifWallet),\n/* harmony export */ \"Wallet\": () => (/* binding */ Wallet),\n/* harmony export */ \"WatchWallet\": () => (/* binding */ WatchWallet),\n/* harmony export */ \"WifWallet\": () => (/* binding */ WifWallet)\n/* harmony export */ });\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/key/hd-key.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/address/cash-address.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_33__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/crypto/default-crypto-instances.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/hex.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/key/key-utils.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/key/wallet-import-format.js\");\n/* harmony import */ var bip39__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! bip39 */ \"../../node_modules/bip39/src/index.js\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../enum.js */ \"./src/enum.ts\");\n/* harmony import */ var _interface_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../interface.js */ \"./src/interface.ts\");\n/* harmony import */ var _Base_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Base.js */ \"./src/wallet/Base.ts\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./enum.js */ \"./src/wallet/enum.ts\");\n/* harmony import */ var _model_js__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./model.js */ \"./src/wallet/model.ts\");\n/* harmony import */ var _transaction_Wif_js__WEBPACK_IMPORTED_MODULE_29__ = __webpack_require__(/*! ../transaction/Wif.js */ \"./src/transaction/Wif.ts\");\n/* harmony import */ var _util_asSendRequestObject_js__WEBPACK_IMPORTED_MODULE_30__ = __webpack_require__(/*! ../util/asSendRequestObject.js */ \"./src/util/asSendRequestObject.ts\");\n/* harmony import */ var _util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(/*! ../util/balanceObjectFromSatoshi.js */ \"./src/util/balanceObjectFromSatoshi.ts\");\n/* harmony import */ var _util_checkWifNetwork_js__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ../util/checkWifNetwork.js */ \"./src/util/checkWifNetwork.ts\");\n/* harmony import */ var _util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ../util/deriveCashaddr.js */ \"./src/util/deriveCashaddr.ts\");\n/* harmony import */ var _util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../util/derivePublicKeyHash.js */ \"./src/util/derivePublicKeyHash.ts\");\n/* harmony import */ var _util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../util/checkForEmptySeed.js */ \"./src/util/checkForEmptySeed.ts\");\n/* harmony import */ var _util_sanitizeUnit_js__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! ../util/sanitizeUnit.js */ \"./src/util/sanitizeUnit.ts\");\n/* harmony import */ var _util_sumUtxoValue_js__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(/*! ../util/sumUtxoValue.js */ \"./src/util/sumUtxoValue.ts\");\n/* harmony import */ var _util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_31__ = __webpack_require__(/*! ../util/sumSendRequestAmounts.js */ \"./src/util/sumSendRequestAmounts.ts\");\n/* harmony import */ var _network_getRelayFeeCache_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../network/getRelayFeeCache.js */ \"./src/network/getRelayFeeCache.ts\");\n/* harmony import */ var _Util_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./Util.js */ \"./src/wallet/Util.ts\");\n/* harmony import */ var _network_index_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../network/index.js */ \"./src/network/default.ts\");\n/* harmony import */ var _util_randomBytes_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../util/randomBytes.js */ \"./src/util/randomBytes.ts\");\n/* harmony import */ var _message_index_js__WEBPACK_IMPORTED_MODULE_34__ = __webpack_require__(/*! ../message/index.js */ \"./src/message/signed.ts\");\n/* harmony import */ var _util_amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(/*! ../util/amountInSatoshi.js */ \"./src/util/amountInSatoshi.ts\");\n/* harmony import */ var _util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../util/getXPubKey.js */ \"./src/util/getXPubKey.ts\");\n/* harmony import */ var _constant_js__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ../constant.js */ \"./src/constant.ts\");\n/* harmony import */ var _history_electrumTransformer_js__WEBPACK_IMPORTED_MODULE_32__ = __webpack_require__(/*! ../history/electrumTransformer.js */ \"./src/history/electrumTransformer.ts\");\n/* harmony import */ var _Bcmr_js__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(/*! ./Bcmr.js */ \"./src/wallet/Bcmr.ts\");\n/* harmony import */ var _qr_Qr_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../qr/Qr.js */ \"./src/qr/Qr.ts\");\n/* harmony import */ var _config_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../config.js */ \"./src/config.ts\");\n/* harmony import */ var _util_checkUtxos_js__WEBPACK_IMPORTED_MODULE_28__ = __webpack_require__(/*! ../util/checkUtxos.js */ \"./src/util/checkUtxos.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_Base_js__WEBPACK_IMPORTED_MODULE_2__, _enum_js__WEBPACK_IMPORTED_MODULE_3__, _Util_js__WEBPACK_IMPORTED_MODULE_6__, _network_index_js__WEBPACK_IMPORTED_MODULE_8__, _qr_Qr_js__WEBPACK_IMPORTED_MODULE_9__, _util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_11__, _util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_14__, _util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_15__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_16__, _model_js__WEBPACK_IMPORTED_MODULE_18__, _util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_20__, _util_checkWifNetwork_js__WEBPACK_IMPORTED_MODULE_21__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_22__, _util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_24__, _util_amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_26__, _Bcmr_js__WEBPACK_IMPORTED_MODULE_27__, _transaction_Wif_js__WEBPACK_IMPORTED_MODULE_29__, _util_asSendRequestObject_js__WEBPACK_IMPORTED_MODULE_30__, _util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_31__, _history_electrumTransformer_js__WEBPACK_IMPORTED_MODULE_32__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_33__, _message_index_js__WEBPACK_IMPORTED_MODULE_34__]);\n([_Base_js__WEBPACK_IMPORTED_MODULE_2__, _enum_js__WEBPACK_IMPORTED_MODULE_3__, _Util_js__WEBPACK_IMPORTED_MODULE_6__, _network_index_js__WEBPACK_IMPORTED_MODULE_8__, _qr_Qr_js__WEBPACK_IMPORTED_MODULE_9__, _util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_11__, _util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_14__, _util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_15__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_16__, _model_js__WEBPACK_IMPORTED_MODULE_18__, _util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_20__, _util_checkWifNetwork_js__WEBPACK_IMPORTED_MODULE_21__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_22__, _util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_24__, _util_amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_26__, _Bcmr_js__WEBPACK_IMPORTED_MODULE_27__, _transaction_Wif_js__WEBPACK_IMPORTED_MODULE_29__, _util_asSendRequestObject_js__WEBPACK_IMPORTED_MODULE_30__, _util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_31__, _history_electrumTransformer_js__WEBPACK_IMPORTED_MODULE_32__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_33__, _message_index_js__WEBPACK_IMPORTED_MODULE_34__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n//#region Imports\n// Stable\n\n// Unstable?\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n//#endregion Imports\n/**\n * Class to manage a bitcoin cash wallet.\n */\nclass Wallet extends _Base_js__WEBPACK_IMPORTED_MODULE_2__.BaseWallet {\n //#endregion\n //#region Constructors and Statics\n constructor(name = \"\", network = _enum_js__WEBPACK_IMPORTED_MODULE_3__.NetworkType.Mainnet, walletType = _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Seed) {\n super(name, network, walletType);\n this.derivationPath = _config_js__WEBPACK_IMPORTED_MODULE_5__.Config.DefaultParentDerivationPath + \"/0/0\";\n this.parentDerivationPath = _config_js__WEBPACK_IMPORTED_MODULE_5__.Config.DefaultParentDerivationPath;\n this._slpSemiAware = false; // a flag which requires an utxo to have more than 546 sats to be spendable and counted in the balance\n this.fromId = async (walletId) => {\n let [walletType, networkGiven, arg1] = walletId.split(\":\");\n if (this.network != networkGiven) {\n throw Error(`Network prefix ${networkGiven} to a ${this.network} wallet`);\n }\n // \"wif:regtest:cNfsPtqN2bMRS7vH5qd8tR8GMvgXyL5BjnGAKgZ8DYEiCrCCQcP6\"\n if (walletType === \"wif\") {\n return this.fromWIF(arg1);\n }\n return super.fromId(walletId);\n };\n this.networkPrefix = _enum_js__WEBPACK_IMPORTED_MODULE_3__.prefixFromNetworkMap[this.network];\n }\n //#region Accessors\n // interface to util functions. see Util.ts\n get util() {\n if (!this._util) {\n this._util = new _Util_js__WEBPACK_IMPORTED_MODULE_6__.Util(this);\n }\n return this._util;\n }\n // interface to util util. see Util.Util\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_6__.Util;\n }\n slpSemiAware(value = true) {\n this._slpSemiAware = value;\n return this;\n }\n getNetworkProvider(network = _interface_js__WEBPACK_IMPORTED_MODULE_7__.Network.MAINNET) {\n return (0,_network_index_js__WEBPACK_IMPORTED_MODULE_8__.getNetworkProvider)(network);\n }\n /**\n * getTokenDepositAddress - get a cashtoken aware wallet deposit address\n *\n * @returns The cashtoken aware deposit address as a string\n */\n getTokenDepositAddress() {\n return this.tokenaddr;\n }\n /**\n * getDepositQr - get an address qrcode, encoded for display on the web\n *\n * @returns The qrcode for the token aware address\n */\n getTokenDepositQr() {\n return (0,_qr_Qr_js__WEBPACK_IMPORTED_MODULE_9__.qrAddress)(this.getTokenDepositAddress());\n }\n /**\n * explorerUrl Web url to a transaction on a block explorer\n *\n * @param txId transaction Id\n * @returns Url string\n */\n explorerUrl(txId) {\n const explorerUrlMap = {\n mainnet: \"https://blockchair.com/bitcoin-cash/transaction/\",\n testnet: \"https://www.blockchain.com/bch-testnet/tx/\",\n regtest: \"\",\n };\n return explorerUrlMap[this.network] + txId;\n }\n // Return wallet info\n getInfo() {\n return {\n cashaddr: this.cashaddr,\n tokenaddr: this.tokenaddr,\n isTestnet: this.isTestnet,\n name: this.name,\n network: this.network,\n seed: this.mnemonic ? this.getSeed().seed : undefined,\n derivationPath: this.mnemonic ? this.getSeed().derivationPath : undefined,\n parentDerivationPath: this.mnemonic\n ? this.getSeed().parentDerivationPath\n : undefined,\n parentXPubKey: this.parentXPubKey ? this.parentXPubKey : undefined,\n publicKey: this.publicKey ? (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__.binToHex)(this.publicKey) : undefined,\n publicKeyHash: (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__.binToHex)(this.publicKeyHash),\n privateKey: this.privateKey ? (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__.binToHex)(this.privateKey) : undefined,\n privateKeyWif: this.privateKeyWif,\n walletId: this.toString(),\n walletDbEntry: this.toDbString(),\n };\n }\n // returns the public key hash for an address\n getPublicKey(hex = false) {\n if (this.publicKey) {\n return hex ? (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__.binToHex)(this.publicKey) : this.publicKey;\n }\n else {\n throw Error(\"The public key for this wallet is not known, perhaps the wallet was created to watch the *hash* of a public key? i.e. a cashaddress.\");\n }\n }\n // returns the public key hash for an address\n getPublicKeyCompressed(hex = false) {\n if (this.publicKeyCompressed) {\n return hex\n ? (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__.binToHex)(this.publicKeyCompressed)\n : this.publicKeyCompressed;\n }\n else {\n throw Error(\"The compressed public key for this wallet is not known, perhaps the wallet was created to watch the *hash* of a public key? i.e. a cashaddress.\");\n }\n }\n // returns the public key hash for an address\n getPublicKeyHash(hex = false) {\n if (this.publicKeyHash) {\n return hex ? (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__.binToHex)(this.publicKeyHash) : this.publicKeyHash;\n }\n else {\n throw Error(\"The public key hash for this wallet is not known. If this wallet was created from the constructor directly, calling the deriveInfo() function may help. \");\n }\n }\n /**\n * fromWIF - create a wallet using the private key supplied in `Wallet Import Format`\n *\n * @param wif WIF encoded private key string\n *\n * @returns instantiated wallet\n */\n static async fromWIF(wif) {\n return new this().fromWIF(wif);\n }\n /**\n * fromCashaddr - create a watch-only wallet in the network derived from the address\n *\n * such kind of wallet does not have a private key and is unable to spend any funds\n * however it still allows to use many utility functions such as getting and watching balance, etc.\n *\n * @param address cashaddress of a wallet\n *\n * @returns instantiated wallet\n */\n static async fromCashaddr(address) {\n const prefix = (0,_util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_11__.derivePrefix)(address);\n const networkType = _enum_js__WEBPACK_IMPORTED_MODULE_3__.networkPrefixMap[prefix];\n return new this(\"\", networkType, _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Watch).watchOnly(address);\n }\n /**\n * fromTokenaddr - create a watch-only wallet in the network derived from the address\n *\n * such kind of wallet does not have a private key and is unable to spend any funds\n * however it still allows to use many utility functions such as getting and watching balance, etc.\n *\n * @param address token aware cashaddress of a wallet\n *\n * @returns instantiated wallet\n */\n static async fromTokenaddr(address) {\n const prefix = (0,_util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_11__.derivePrefix)(address);\n const networkType = _enum_js__WEBPACK_IMPORTED_MODULE_3__.networkPrefixMap[prefix];\n return new this(\"\", networkType, _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Watch).watchOnly(address);\n }\n //#endregion Constructors and Statics\n //#region Protected implementations\n async generate() {\n if (this.walletType === _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Wif) {\n return await this._generateWif();\n }\n else if (this.walletType === _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Watch) {\n return this;\n }\n else if (this.walletType === _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Hd) {\n throw Error(\"Not implemented\");\n }\n else if (this.walletType === _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Seed) {\n return await this._generateMnemonic();\n }\n else {\n console.log(this.walletType);\n throw Error(`Could not determine walletType: ${this.walletType}`);\n }\n }\n async _generateWif() {\n if (!this.privateKey) {\n this.privateKey = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_12__.generatePrivateKey)(() => (0,_util_randomBytes_js__WEBPACK_IMPORTED_MODULE_13__.generateRandomBytes)(32));\n }\n return this.deriveInfo();\n }\n async _generateMnemonic() {\n this.mnemonic = (0,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_14__.checkForEmptySeed)(seed);\n let network = this.isTestnet ? \"testnet\" : \"mainnet\";\n this.parentXPubKey = await (0,_util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_15__.getXPubKey)(seed, this.parentDerivationPath, network);\n let hdNode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_16__.deriveHdPrivateNodeFromSeed)(seed);\n if (!hdNode.valid) {\n throw Error(\"Invalid private key derived from mnemonic seed\");\n }\n let zerothChild = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_16__.deriveHdPath)(hdNode, this.derivationPath);\n if (typeof zerothChild === \"string\") {\n throw Error(zerothChild);\n }\n this.privateKey = zerothChild.privateKey;\n this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Seed;\n return await this.deriveInfo();\n }\n async getXPubKeys(paths) {\n if (this.mnemonic) {\n if (paths) {\n let xPubKeys = await this.deriveHdPaths(paths);\n return [xPubKeys];\n }\n else {\n return await this.deriveHdPaths(_constant_js__WEBPACK_IMPORTED_MODULE_17__.DERIVATION_PATHS);\n }\n }\n else {\n throw Error(\"xpubkeys can only be derived from seed type wallets.\");\n }\n }\n // Initialize wallet from a mnemonic phrase\n async fromSeed(mnemonic, derivationPath) {\n this.mnemonic = mnemonic.trim().toLowerCase();\n if (this.mnemonic.length == 0)\n throw Error(\"refusing to create wallet from empty mnemonic\");\n let seed = (0,bip39__WEBPACK_IMPORTED_MODULE_0__.mnemonicToSeedSync)(this.mnemonic);\n (0,_util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_14__.checkForEmptySeed)(seed);\n let hdNode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_16__.deriveHdPrivateNodeFromSeed)(seed);\n if (!hdNode.valid) {\n throw Error(\"Invalid private key derived from mnemonic seed\");\n }\n if (derivationPath) {\n this.derivationPath = derivationPath;\n // If the derivation path is for the first account child, set the parent derivation path\n let path = derivationPath.split(\"/\");\n if (path.slice(-2).join(\"/\") == \"0/0\") {\n this.parentDerivationPath = path.slice(0, -2).join(\"/\");\n }\n }\n let zerothChild = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_16__.deriveHdPath)(hdNode, this.derivationPath);\n if (typeof zerothChild === \"string\") {\n throw Error(zerothChild);\n }\n this.privateKey = zerothChild.privateKey;\n let network = this.isTestnet ? \"testnet\" : \"mainnet\";\n this.parentXPubKey = await (0,_util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_15__.getXPubKey)(seed, this.parentDerivationPath, network);\n this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Seed;\n await this.deriveInfo();\n return this;\n }\n // Get common xpub paths from zerothChild privateKey\n async deriveHdPaths(hdPaths) {\n if (!this.mnemonic)\n throw Error(\"refusing to create wallet from empty mnemonic\");\n let seed = (0,bip39__WEBPACK_IMPORTED_MODULE_0__.mnemonicToSeedSync)(this.mnemonic);\n (0,_util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_14__.checkForEmptySeed)(seed);\n let hdNode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_16__.deriveHdPrivateNodeFromSeed)(seed);\n if (!hdNode.valid) {\n throw Error(\"Invalid private key derived from mnemonic seed\");\n }\n let result = [];\n for (const path of hdPaths) {\n if (path === \"m\") {\n throw Error(\"Storing or sharing of parent public key may lead to loss of funds. Storing or sharing *root* parent public keys is strongly discouraged, although all parent keys have risk. See: https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#implications\");\n }\n let childNode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_16__.deriveHdPath)(hdNode, path);\n if (typeof childNode === \"string\") {\n throw Error(childNode);\n }\n let node = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_16__.deriveHdPublicNode)(childNode);\n if (typeof node === \"string\") {\n throw Error(node);\n }\n let xPubKey = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_16__.encodeHdPublicKey)({\n network: this.network,\n node: node,\n });\n let key = new _model_js__WEBPACK_IMPORTED_MODULE_18__.XPubKey({\n path: path,\n xPubKey: xPubKey,\n });\n result.push(await key.ready());\n }\n return await Promise.all(result).then((result) => {\n return result;\n });\n }\n // Initialize a watch only wallet from a cash addr\n async watchOnly(address) {\n this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Watch;\n let addressComponents = address.split(\":\");\n let addressPrefix, addressBase;\n if (addressComponents.length === 1) {\n addressBase = addressComponents.shift();\n addressPrefix = (0,_util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_11__.derivePrefix)(addressBase);\n }\n else {\n addressPrefix = addressComponents.shift();\n addressBase = addressComponents.shift();\n if (addressPrefix in _enum_js__WEBPACK_IMPORTED_MODULE_3__.networkPrefixMap) {\n if (_enum_js__WEBPACK_IMPORTED_MODULE_3__.networkPrefixMap[addressPrefix] != this.network) {\n throw Error(`a ${addressPrefix} address cannot be watched from a ${this.network} Wallet`);\n }\n }\n }\n const prefixedAddress = `${addressPrefix}:${addressBase}`;\n // check if a token aware address was provided\n let addressData = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_19__.decodeCashAddress)(prefixedAddress);\n if (typeof addressData === \"string\")\n throw addressData;\n this.publicKeyHash = addressData.payload;\n let nonTokenAwareType = addressData.type;\n if (nonTokenAwareType == _bitauth_libauth__WEBPACK_IMPORTED_MODULE_19__.CashAddressType.p2pkhWithTokens)\n nonTokenAwareType = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_19__.CashAddressType.p2pkh;\n if (nonTokenAwareType == _bitauth_libauth__WEBPACK_IMPORTED_MODULE_19__.CashAddressType.p2shWithTokens)\n nonTokenAwareType = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_19__.CashAddressType.p2sh;\n if (nonTokenAwareType == _bitauth_libauth__WEBPACK_IMPORTED_MODULE_19__.CashAddressType.p2pkh)\n this.publicKeyHash = addressData.payload;\n this.cashaddr = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_19__.encodeCashAddress)(addressData.prefix, nonTokenAwareType, addressData.payload);\n this.address = this.cashaddr;\n this.tokenaddr = (0,_util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_20__.deriveTokenaddr)(addressData.payload, this.networkPrefix);\n return this;\n }\n // Initialize wallet from Wallet Import Format\n async fromWIF(secret) {\n (0,_util_checkWifNetwork_js__WEBPACK_IMPORTED_MODULE_21__.checkWifNetwork)(secret, this.network);\n let wifResult = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_22__.decodePrivateKeyWif)(secret);\n if (typeof wifResult === \"string\") {\n throw Error(wifResult);\n }\n let resultData = wifResult;\n this.privateKey = resultData.privateKey;\n this.privateKeyWif = secret;\n this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Wif;\n await this.deriveInfo();\n return this;\n }\n async newRandom(name, dbName) {\n dbName = dbName ? dbName : this.networkPrefix;\n return super.newRandom(name, dbName);\n }\n async named(name, dbName, forceNew = false) {\n dbName = dbName ? dbName : this.networkPrefix;\n return super.named(name, dbName, forceNew);\n }\n async replaceNamed(name, walletId, dbName) {\n dbName = dbName ? dbName : this.networkPrefix;\n return super.replaceNamed(name, walletId, dbName);\n }\n async namedExists(name, dbName) {\n dbName = dbName ? dbName : this.networkPrefix;\n return super.namedExists(name, dbName);\n }\n //#endregion Protected Implementations\n //#region Serialization\n // Returns the serialized wallet as a string\n // If storing in a database, set asNamed to false to store secrets\n // In all other cases, the a named wallet is deserialized from the database\n // by the name key\n toString() {\n const result = super.toString();\n if (result)\n return result;\n if (this.walletType === _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Wif) {\n return `${this.walletType}:${this.network}:${this.privateKeyWif}`;\n }\n throw Error(\"toString unsupported wallet type\");\n }\n //\n toDbString() {\n const result = super.toDbString();\n if (result)\n return result;\n if (this.walletType === _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Wif) {\n return `${this.walletType}:${this.network}:${this.privateKeyWif}`;\n }\n throw Error(\"toDbString unsupported wallet type\");\n }\n //#endregion Serialization\n //#region Funds\n //\n async getAddressUtxos(address) {\n if (!address) {\n address = this.cashaddr;\n }\n if (this._slpSemiAware) {\n const bchUtxos = await this.provider.getUtxos(address);\n return bchUtxos.filter((bchutxo) => bchutxo.satoshis > _constant_js__WEBPACK_IMPORTED_MODULE_17__.DUST_UTXO_THRESHOLD);\n }\n else {\n return await this.provider.getUtxos(address);\n }\n }\n /**\n * utxos Get unspent outputs for the wallet\n *\n */\n async getUtxos() {\n if (!this.cashaddr) {\n throw Error(\"Attempted to get utxos without an address\");\n }\n return await this.getAddressUtxos(this.cashaddr);\n }\n // gets wallet balance in sats, bch and usd\n async getBalance(rawUnit, usdPriceCache = true) {\n if (rawUnit) {\n const unit = (0,_util_sanitizeUnit_js__WEBPACK_IMPORTED_MODULE_23__.sanitizeUnit)(rawUnit);\n return await (0,_util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_24__.balanceFromSatoshi)(await this.getBalanceFromProvider(), unit, usdPriceCache);\n }\n else {\n return await (0,_util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_24__.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_25__.sumUtxoValue)(utxos);\n }\n // Gets balance from fulcrum\n async getBalanceFromProvider() {\n // Fulcrum reports balance of all utxos, including tokens, which is undesirable\n // // TODO not sure why getting the balance from a provider doesn't work\n // if (this._slpAware || this._slpSemiAware) {\n // return await this.getBalanceFromUtxos();\n // } else {\n // return await this.provider!.getBalance(this.cashaddr!);\n // }\n // FIXME\n return this.getBalanceFromUtxos();\n }\n // watching for any transaction hash of this wallet\n watchAddress(callback) {\n return this.provider.watchAddress(this.getDepositAddress(), callback);\n }\n // watching for any transaction of this wallet\n watchAddressTransactions(callback) {\n return this.provider.watchAddressTransactions(this.getDepositAddress(), callback);\n }\n // watching for cashtoken transaction of this wallet\n watchAddressTokenTransactions(callback) {\n return this.provider.watchAddressTokenTransactions(this.getDepositAddress(), callback);\n }\n // sets up a callback to be called upon wallet's balance change\n // can be cancelled by calling the function returned from this one\n watchBalance(callback) {\n return this.provider.watchAddressStatus(this.getDepositAddress(), async (_status) => {\n const balance = (await this.getBalance());\n callback(balance);\n });\n }\n // sets up a callback to be called upon wallet's BCH or USD balance change\n // if BCH balance does not change, the callback will be triggered every\n // @param `usdPriceRefreshInterval` milliseconds by polling for new BCH USD price\n // Since we want to be most sensitive to usd value change, we do not use the cached exchange rates\n // can be cancelled by calling the function returned from this one\n watchBalanceUsd(callback, usdPriceRefreshInterval = 30000) {\n let usdPrice = -1;\n const _callback = async () => {\n const balance = (await this.getBalance(undefined, false));\n if (usdPrice !== balance.usd) {\n usdPrice = balance.usd;\n callback(balance);\n }\n };\n const watchCancel = this.provider.watchAddressStatus(this.getDepositAddress(), _callback);\n const interval = setInterval(_callback, usdPriceRefreshInterval);\n return async () => {\n await watchCancel();\n clearInterval(interval);\n };\n }\n // waits for address balance to be greater than or equal to the target value\n // this call halts the execution\n async waitForBalance(value, rawUnit = _enum_js__WEBPACK_IMPORTED_MODULE_3__.UnitEnum.BCH) {\n return new Promise(async (resolve) => {\n const watchCancel = this.watchBalance(async (balance) => {\n const satoshiBalance = await (0,_util_amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_26__.amountInSatoshi)(value, rawUnit);\n if (balance.sat >= satoshiBalance) {\n await watchCancel();\n resolve(balance);\n }\n });\n });\n }\n // sets up a callback to be called upon wallet's token balance change\n // can be cancelled by calling the function returned from this one\n watchTokenBalance(tokenId, callback) {\n let previous = undefined;\n return this.provider.watchAddressStatus(this.getDepositAddress(), async (_status) => {\n const balance = await this.getTokenBalance(tokenId);\n if (previous != balance) {\n callback(balance);\n }\n previous = balance;\n });\n }\n // waits for address token balance to be greater than or equal to the target amount\n // this call halts the execution\n async waitForTokenBalance(tokenId, amount) {\n return new Promise(async (resolve) => {\n const watchCancel = this.watchTokenBalance(tokenId, async (balance) => {\n if (balance >= amount) {\n await watchCancel();\n resolve(balance);\n }\n });\n });\n }\n async getTokenInfo(tokenId) {\n return _Bcmr_js__WEBPACK_IMPORTED_MODULE_27__.BCMR.getTokenInfo(tokenId);\n }\n async _getMaxAmountToSend(params = {\n outputCount: 1,\n options: {},\n }) {\n if (!this.privateKey && params.options?.buildUnsigned !== true) {\n throw Error(\"Couldn't get network or private key for wallet.\");\n }\n if (!this.cashaddr) {\n throw Error(\"attempted to send without a cashaddr\");\n }\n if (params.options && params.options.slpSemiAware) {\n this._slpSemiAware = true;\n }\n let feePaidBy;\n if (params.options && params.options.feePaidBy) {\n feePaidBy = params.options.feePaidBy;\n }\n else {\n feePaidBy = _enum_js__WEBPACK_IMPORTED_MODULE_4__.FeePaidByEnum.change;\n }\n // get inputs\n let utxos;\n if (params.options && params.options.utxoIds) {\n utxos = await (0,_util_checkUtxos_js__WEBPACK_IMPORTED_MODULE_28__.checkUtxos)(params.options.utxoIds.map((utxoId) => typeof utxoId === \"string\" ? (0,_model_js__WEBPACK_IMPORTED_MODULE_18__.fromUtxoId)(utxoId) : utxoId), this);\n }\n else {\n utxos = (await this.getAddressUtxos(this.cashaddr)).filter((utxo) => !utxo.token);\n }\n // Get current height to assure recently mined coins are not spent.\n const bestHeight = await this.provider.getBlockHeight();\n // simulate outputs using the sender's address\n const sendRequest = new _model_js__WEBPACK_IMPORTED_MODULE_18__.SendRequest({\n cashaddr: this.cashaddr,\n value: 100,\n unit: \"sat\",\n });\n const sendRequests = Array(params.outputCount)\n .fill(0)\n .map(() => sendRequest);\n const fundingUtxos = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_29__.getSuitableUtxos)(utxos, undefined, bestHeight, feePaidBy, sendRequests);\n const relayFeePerByteInSatoshi = await (0,_network_getRelayFeeCache_js__WEBPACK_IMPORTED_MODULE_1__.getRelayFeeCache)(this.provider);\n const fee = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_29__.getFeeAmountSimple)({\n utxos: fundingUtxos,\n sendRequests: sendRequests,\n privateKey: this.privateKey ?? Uint8Array.from([]),\n sourceAddress: this.cashaddr,\n relayFeePerByteInSatoshi: relayFeePerByteInSatoshi,\n feePaidBy: feePaidBy,\n });\n const spendableAmount = (0,_util_sumUtxoValue_js__WEBPACK_IMPORTED_MODULE_25__.sumUtxoValue)(fundingUtxos);\n let result = spendableAmount - fee;\n if (result < 0) {\n result = 0;\n }\n return { value: result, utxos: fundingUtxos };\n }\n async getMaxAmountToSend(params = {\n outputCount: 1,\n options: {},\n }) {\n const { value: result } = await this._getMaxAmountToSend(params);\n return await (0,_util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_24__.balanceResponseFromSatoshi)(result);\n }\n /**\n * send Send some amount to an address\n * this function processes the send requests, encodes the transaction, sends it to the network\n * @returns (depending on the options parameter) the transaction id, new address balance and a link to the transaction on the blockchain explorer\n *\n * This is a first class function with REST analog, maintainers should strive to keep backward-compatibility\n *\n */\n async send(requests, options) {\n const { encodedTransaction, tokenIds, sourceOutputs } = await this.encodeTransaction(requests, undefined, options);\n const resp = new _model_js__WEBPACK_IMPORTED_MODULE_18__.SendResponse({});\n resp.tokenIds = tokenIds;\n if (options?.buildUnsigned !== true) {\n const txId = await this.submitTransaction(encodedTransaction, options?.awaitTransactionPropagation === undefined ||\n options?.awaitTransactionPropagation === true);\n resp.txId = txId;\n resp.explorerUrl = this.explorerUrl(resp.txId);\n if (options?.queryBalance === undefined ||\n options?.queryBalance === true) {\n resp.balance = (await this.getBalance());\n }\n }\n else {\n resp.unsignedTransaction = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__.binToHex)(encodedTransaction);\n resp.sourceOutputs = sourceOutputs;\n }\n return resp;\n }\n /**\n * sendMax Send all available funds to a destination cash address\n *\n * @param {string} cashaddr destination cash address\n * @param {SendRequestOptionsI} options Options of the send requests\n *\n * @returns (depending on the options parameter) the transaction id, new address balance and a link to the transaction on the blockchain explorer\n */\n async sendMax(cashaddr, options) {\n return await this.sendMaxRaw(cashaddr, options);\n }\n /**\n * sendMaxRaw (internal) Send all available funds to a destination cash address\n *\n * @param {string} cashaddr destination cash address\n * @param {SendRequestOptionsI} options Options of the send requests\n *\n * @returns the transaction id sent to the network\n */\n async sendMaxRaw(cashaddr, options) {\n const { value: maxSpendableAmount, utxos } = await this._getMaxAmountToSend({\n outputCount: 1,\n options: options,\n });\n if (!options) {\n options = {};\n }\n options.utxoIds = utxos;\n const sendRequest = new _model_js__WEBPACK_IMPORTED_MODULE_18__.SendRequest({\n cashaddr: cashaddr,\n value: maxSpendableAmount,\n unit: \"sat\",\n });\n const { encodedTransaction, tokenIds, sourceOutputs } = await this.encodeTransaction([sendRequest], true, options);\n const resp = new _model_js__WEBPACK_IMPORTED_MODULE_18__.SendResponse({});\n resp.tokenIds = tokenIds;\n if (options?.buildUnsigned !== true) {\n const txId = await this.submitTransaction(encodedTransaction, options?.awaitTransactionPropagation === undefined ||\n options?.awaitTransactionPropagation === true);\n resp.txId = txId;\n resp.explorerUrl = this.explorerUrl(resp.txId);\n if (options?.queryBalance === undefined ||\n options?.queryBalance === true) {\n resp.balance = (await this.getBalance());\n }\n }\n else {\n resp.unsignedTransaction = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__.binToHex)(encodedTransaction);\n resp.sourceOutputs = sourceOutputs;\n }\n return resp;\n }\n /**\n * encodeTransaction Encode and sign a transaction given a list of sendRequests, options and estimate fees.\n * @param {SendRequest[]} sendRequests SendRequests\n * @param {boolean} discardChange=false\n * @param {SendRequestOptionsI} options Options of the send requests\n */\n async encodeTransaction(requests, discardChange = false, options) {\n let sendRequests = (0,_util_asSendRequestObject_js__WEBPACK_IMPORTED_MODULE_30__.asSendRequestObject)(requests);\n if (!this.privateKey && options?.buildUnsigned !== true) {\n throw new Error(`Wallet ${this.name} is missing either a network or private key`);\n }\n if (!this.cashaddr) {\n throw Error(\"attempted to send without a cashaddr\");\n }\n if (options && options.slpSemiAware) {\n this._slpSemiAware = true;\n }\n let feePaidBy;\n if (options && options.feePaidBy) {\n feePaidBy = options.feePaidBy;\n }\n else {\n feePaidBy = _enum_js__WEBPACK_IMPORTED_MODULE_4__.FeePaidByEnum.change;\n }\n let changeAddress;\n if (options && options.changeAddress) {\n changeAddress = options.changeAddress;\n }\n else {\n changeAddress = this.cashaddr;\n }\n let checkTokenQuantities = true;\n if (options && options.checkTokenQuantities === false) {\n checkTokenQuantities = false;\n }\n // get inputs from options or query all inputs\n let utxos;\n if (options && options.utxoIds) {\n utxos = await (0,_util_checkUtxos_js__WEBPACK_IMPORTED_MODULE_28__.checkUtxos)(options.utxoIds.map((utxoId) => typeof utxoId === \"string\" ? (0,_model_js__WEBPACK_IMPORTED_MODULE_18__.fromUtxoId)(utxoId) : utxoId), this);\n }\n else {\n utxos = await this.getAddressUtxos(this.cashaddr);\n }\n // filter out token utxos if there are no token requests\n if (checkTokenQuantities &&\n !sendRequests.some((val) => val instanceof _model_js__WEBPACK_IMPORTED_MODULE_18__.TokenSendRequest)) {\n utxos = utxos.filter((val) => !val.token);\n }\n const addTokenChangeOutputs = (inputs, outputs) => {\n // Do NOT allow for implicit token burn if the total amount sent is less than user had\n // allow for token genesis, creating more tokens than we had before (0)\n if (!checkTokenQuantities) {\n return;\n }\n const allTokenInputs = inputs.filter((val) => val.token);\n const allTokenOutputs = outputs.filter((val) => val instanceof _model_js__WEBPACK_IMPORTED_MODULE_18__.TokenSendRequest);\n const tokenIds = allTokenOutputs\n .map((val) => val.tokenId)\n .filter((val, idx, arr) => arr.indexOf(val) === idx);\n for (let tokenId of tokenIds) {\n const tokenInputs = allTokenInputs.filter((val) => val.token?.tokenId === tokenId);\n const inputAmountSum = tokenInputs.reduce((prev, cur) => prev + cur.token.amount, 0);\n const tokenOutputs = allTokenOutputs.filter((val) => val.tokenId === tokenId);\n const outputAmountSum = tokenOutputs.reduce((prev, cur) => prev + cur.amount, 0);\n const diff = inputAmountSum - outputAmountSum;\n if (diff < 0) {\n throw new Error(\"Not enough token amount to send\");\n }\n if (diff >= 0) {\n let available = 0;\n let change = 0;\n const ensureUtxos = [];\n for (const token of tokenInputs.filter((val) => val.token?.amount)) {\n ensureUtxos.push(token);\n available += token.token?.amount;\n if (available >= outputAmountSum) {\n change = available - outputAmountSum;\n //break;\n }\n }\n if (ensureUtxos.length) {\n if (!options) {\n options = {};\n }\n options.ensureUtxos = [\n ...(options.ensureUtxos ?? []),\n ...ensureUtxos,\n ].filter((val, index, array) => array.findIndex((other) => other.txid === val.txid && other.vout === val.vout) === index);\n }\n if (change > 0) {\n outputs.push(new _model_js__WEBPACK_IMPORTED_MODULE_18__.TokenSendRequest({\n cashaddr: (0,_util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_20__.toTokenaddr)(changeAddress) || this.tokenaddr,\n amount: change,\n tokenId: tokenId,\n commitment: tokenOutputs[0].commitment,\n capability: tokenOutputs[0].capability,\n value: tokenOutputs[0].value,\n }));\n }\n }\n }\n };\n addTokenChangeOutputs(utxos, sendRequests);\n const bestHeight = await this.provider.getBlockHeight();\n const spendAmount = await (0,_util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_31__.sumSendRequestAmounts)(sendRequests);\n if (utxos.length === 0) {\n throw Error(\"There were no Unspent Outputs\");\n }\n if (typeof spendAmount !== \"bigint\") {\n throw Error(\"Couldn't get spend amount when building transaction\");\n }\n const relayFeePerByteInSatoshi = await (0,_network_getRelayFeeCache_js__WEBPACK_IMPORTED_MODULE_1__.getRelayFeeCache)(this.provider);\n const feeEstimate = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_29__.getFeeAmountSimple)({\n utxos: utxos,\n sendRequests: sendRequests,\n privateKey: this.privateKey ?? Uint8Array.from([]),\n sourceAddress: this.cashaddr,\n relayFeePerByteInSatoshi: relayFeePerByteInSatoshi,\n feePaidBy: feePaidBy,\n });\n const fundingUtxos = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_29__.getSuitableUtxos)(utxos, BigInt(spendAmount) + BigInt(feeEstimate), bestHeight, feePaidBy, sendRequests, options?.ensureUtxos || [], options?.tokenOperation);\n if (fundingUtxos.length === 0) {\n throw Error(\"The available inputs couldn't satisfy the request with fees\");\n }\n const fee = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_29__.getFeeAmount)({\n utxos: fundingUtxos,\n sendRequests: sendRequests,\n privateKey: this.privateKey ?? Uint8Array.from([]),\n sourceAddress: this.cashaddr,\n relayFeePerByteInSatoshi: relayFeePerByteInSatoshi,\n feePaidBy: feePaidBy,\n });\n const { encodedTransaction, sourceOutputs } = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_29__.buildEncodedTransaction)({\n inputs: fundingUtxos,\n outputs: sendRequests,\n signingKey: this.privateKey ?? Uint8Array.from([]),\n sourceAddress: this.cashaddr,\n fee,\n discardChange,\n feePaidBy,\n changeAddress,\n buildUnsigned: options?.buildUnsigned === true,\n });\n const tokenIds = [\n ...fundingUtxos\n .filter((val) => val.token?.tokenId)\n .map((val) => val.token.tokenId),\n ...sendRequests\n .filter((val) => val instanceof _model_js__WEBPACK_IMPORTED_MODULE_18__.TokenSendRequest)\n .map((val) => val.tokenId),\n ].filter((value, index, array) => array.indexOf(value) === index);\n return { encodedTransaction, tokenIds, sourceOutputs };\n }\n async signUnsignedTransaction(transaction, sourceOutputs) {\n if (!this.privateKey) {\n throw Error(\"Can not sign a transaction with watch-only wallet.\");\n }\n return (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_29__.signUnsignedTransaction)(transaction, sourceOutputs, this.privateKey);\n }\n // Submit a raw transaction\n async submitTransaction(transaction, awaitPropagation = true) {\n if (!this.provider) {\n throw Error(\"Wallet network provider was not initialized\");\n }\n let rawTransaction = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__.binToHex)(transaction);\n return await this.provider.sendRawTransaction(rawTransaction, awaitPropagation);\n }\n // gets transaction history of this wallet\n async getRawHistory() {\n return await this.provider.getHistory(this.cashaddr);\n }\n // gets transaction history of this wallet\n async getHistory(unit, start, count, collapseChange) {\n return (0,_history_electrumTransformer_js__WEBPACK_IMPORTED_MODULE_32__.getAddressHistory)(this.cashaddr, this.provider, unit, start, count, collapseChange);\n }\n // gets last transaction of this wallet\n async getLastTransaction(confirmedOnly = false) {\n let history = await this.getRawHistory();\n if (confirmedOnly) {\n history = history.filter((val) => val.height > 0);\n }\n if (!history.length) {\n return null;\n }\n const [lastTx] = history.slice(-1);\n return this.provider.getRawTransactionObject(lastTx.tx_hash);\n }\n // waits for next transaction, program execution is halted\n async waitForTransaction(options = {\n getTransactionInfo: true,\n getBalance: false,\n txHash: undefined,\n }) {\n if (options.getTransactionInfo === undefined) {\n options.getTransactionInfo = true;\n }\n return new Promise(async (resolve) => {\n let txHashSeen = false;\n const makeResponse = async (txHash) => {\n const response = {};\n const promises = [undefined, undefined];\n if (options.getBalance === true) {\n promises[0] = this.getBalance();\n }\n if (options.getTransactionInfo === true) {\n if (!txHash) {\n promises[1] = this.getLastTransaction();\n }\n else {\n promises[1] = this.provider.getRawTransactionObject(txHash);\n }\n }\n const result = await Promise.all(promises);\n response.balance = result[0];\n response.transactionInfo = result[1];\n return response;\n };\n // waiting for a specific transaction to propagate\n if (options.txHash) {\n const waitForTransactionCallback = async (data) => {\n if (data && data[0] === options.txHash) {\n txHashSeen = true;\n this.provider.unsubscribeFromTransaction(options.txHash, waitForTransactionCallback);\n resolve(makeResponse(options.txHash));\n }\n };\n this.provider.subscribeToTransaction(options.txHash, waitForTransactionCallback);\n return;\n }\n // waiting for any address transaction\n const watchCancel = this.provider.watchAddressStatus(this.getDepositAddress(), async (_status) => {\n watchCancel();\n resolve(makeResponse());\n });\n });\n }\n /**\n * watchBlocks Watch network blocks\n *\n * @param callback callback with a block header object\n *\n * @returns a function which will cancel watching upon evaluation\n */\n watchBlocks(callback) {\n return this.provider.watchBlocks(callback);\n }\n /**\n * waitForBlock Wait for a network block\n *\n * @param height if specified waits for this exact blockchain height, otherwise resolves with the next block\n *\n */\n async waitForBlock(height) {\n return this.provider.waitForBlock(height);\n }\n //#endregion Funds\n //#region Private implementation details\n async deriveInfo() {\n const publicKey = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_33__.secp256k1.derivePublicKeyUncompressed(this.privateKey);\n if (typeof publicKey === \"string\") {\n throw new Error(publicKey);\n }\n this.publicKey = publicKey;\n const publicKeyCompressed = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_33__.secp256k1.derivePublicKeyCompressed(this.privateKey);\n if (typeof publicKeyCompressed === \"string\") {\n throw new Error(publicKeyCompressed);\n }\n this.publicKeyCompressed = publicKeyCompressed;\n const networkType = this.network === _enum_js__WEBPACK_IMPORTED_MODULE_3__.NetworkType.Regtest ? _enum_js__WEBPACK_IMPORTED_MODULE_3__.NetworkType.Testnet : this.network;\n this.privateKeyWif = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_22__.encodePrivateKeyWif)(this.privateKey, networkType);\n (0,_util_checkWifNetwork_js__WEBPACK_IMPORTED_MODULE_21__.checkWifNetwork)(this.privateKeyWif, this.network);\n this.cashaddr = (0,_util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_20__.deriveCashaddr)(this.privateKey, this.networkPrefix);\n this.tokenaddr = (0,_util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_20__.deriveTokenaddr)(this.privateKey, this.networkPrefix);\n this.address = this.cashaddr;\n this.publicKeyHash = (0,_util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_11__.derivePublicKeyHash)(this.cashaddr);\n return this;\n }\n //#endregion Private implementation details\n //#region Signing\n // Convenience wrapper to sign interface\n async sign(message) {\n return await Wallet.signedMessage.sign(message, this.privateKey);\n }\n // Convenience wrapper to verify interface\n async verify(message, sig, publicKey) {\n return await Wallet.signedMessage.verify(message, sig, this.cashaddr, publicKey);\n }\n //#endregion Signing\n //#region Cashtokens\n /**\n * Create new cashtoken, both funglible and/or non-fungible (NFT)\n * Refer to spec https://github.com/bitjson/cashtokens\n * @param {number} genesisRequest.amount amount of *fungible* tokens to create\n * @param {NFTCapability?} genesisRequest.capability capability of new NFT\n * @param {string?} genesisRequest.commitment NFT commitment message\n * @param {string?} genesisRequest.cashaddr cash address to send the created token UTXO to; if undefined will default to your address\n * @param {number?} genesisRequest.value satoshi value to send alongside with tokens; if undefined will default to 1000 satoshi\n * @param {SendRequestType | SendRequestType[]} sendRequests single or an array of extra send requests (OP_RETURN, value transfer, etc.) to include in genesis transaction\n * @param {SendRequestOptionsI} options Options of the send requests\n */\n async tokenGenesis(genesisRequest, sendRequests = [], options) {\n if (!Array.isArray(sendRequests)) {\n sendRequests = [sendRequests];\n }\n let utxos;\n if (options && options.utxoIds) {\n utxos = await (0,_util_checkUtxos_js__WEBPACK_IMPORTED_MODULE_28__.checkUtxos)(options.utxoIds.map((utxoId) => typeof utxoId === \"string\" ? (0,_model_js__WEBPACK_IMPORTED_MODULE_18__.fromUtxoId)(utxoId) : utxoId), this);\n }\n else {\n utxos = await this.getAddressUtxos(this.cashaddr);\n }\n const genesisInputs = utxos.filter((val) => val.vout === 0 && !val.token);\n if (genesisInputs.length === 0) {\n throw new Error(\"No suitable inputs with vout=0 available for new token genesis\");\n }\n const genesisSendRequest = new _model_js__WEBPACK_IMPORTED_MODULE_18__.TokenSendRequest({\n cashaddr: genesisRequest.cashaddr || this.tokenaddr,\n amount: genesisRequest.amount,\n value: genesisRequest.value || 1000,\n capability: genesisRequest.capability,\n commitment: genesisRequest.commitment,\n tokenId: genesisInputs[0].txid,\n });\n return this.send([genesisSendRequest, ...sendRequests], {\n ...options,\n utxoIds: utxos,\n ensureUtxos: [genesisInputs[0]],\n checkTokenQuantities: false,\n queryBalance: false,\n tokenOperation: \"genesis\",\n });\n }\n /**\n * Mint new NFT cashtokens using an existing minting token\n * Refer to spec https://github.com/bitjson/cashtokens\n * @param {string} tokenId tokenId of an NFT to mint\n * @param {TokenMintRequest | TokenMintRequest[]} mintRequests mint requests with new token properties and recipients\n * @param {NFTCapability?} mintRequest.capability capability of new NFT\n * @param {string?} mintRequest.commitment NFT commitment message\n * @param {string?} mintRequest.cashaddr cash address to send the created token UTXO to; if undefined will default to your address\n * @param {number?} mintRequest.value satoshi value to send alongside with tokens; if undefined will default to 1000 satoshi\n * @param {boolean?} deductTokenAmount if minting token contains fungible amount, deduct from it by amount of minted tokens\n * @param {SendRequestOptionsI} options Options of the send requests\n */\n async tokenMint(tokenId, mintRequests, deductTokenAmount = false, options) {\n if (tokenId?.length !== 64) {\n throw Error(`Invalid tokenId supplied: ${tokenId}`);\n }\n if (!Array.isArray(mintRequests)) {\n mintRequests = [mintRequests];\n }\n const utxos = await this.getAddressUtxos(this.cashaddr);\n const nftUtxos = utxos.filter((val) => val.token?.tokenId === tokenId &&\n val.token?.capability === _interface_js__WEBPACK_IMPORTED_MODULE_7__.NFTCapability.minting);\n if (!nftUtxos.length) {\n throw new Error(\"You do not have any token UTXOs with minting capability for specified tokenId\");\n }\n const newAmount = deductTokenAmount && nftUtxos[0].token.amount > 0\n ? nftUtxos[0].token.amount - mintRequests.length\n : nftUtxos[0].token.amount;\n const safeNewAmount = Math.max(0, newAmount);\n const mintingInput = new _model_js__WEBPACK_IMPORTED_MODULE_18__.TokenSendRequest({\n cashaddr: this.tokenaddr,\n tokenId: tokenId,\n capability: nftUtxos[0].token.capability,\n commitment: nftUtxos[0].token.commitment,\n amount: safeNewAmount,\n value: nftUtxos[0].satoshis,\n });\n return this.send([\n mintingInput,\n ...mintRequests.map((val) => new _model_js__WEBPACK_IMPORTED_MODULE_18__.TokenSendRequest({\n cashaddr: val.cashaddr || this.tokenaddr,\n amount: 0,\n tokenId: tokenId,\n value: val.value,\n capability: val.capability,\n commitment: val.commitment,\n })),\n ], {\n ...options,\n ensureUtxos: [nftUtxos[0]],\n checkTokenQuantities: false,\n queryBalance: false,\n tokenOperation: \"mint\",\n });\n }\n /**\n * Perform an explicit token burning by spending a token utxo to an OP_RETURN\n *\n * Behaves differently for fungible and non-fungible tokens:\n * * NFTs are always \"destroyed\"\n * * FTs' amount is reduced by the amount specified, if 0 FT amount is left and no NFT present, the token is \"destroyed\"\n *\n * Refer to spec https://github.com/bitjson/cashtokens\n * @param {string} burnRequest.tokenId tokenId of a token to burn\n * @param {NFTCapability} burnRequest.capability capability of the NFT token to select, optional\n * @param {string?} burnRequest.commitment commitment of the NFT token to select, optional\n * @param {number?} burnRequest.amount amount of fungible tokens to burn, optional\n * @param {string?} burnRequest.cashaddr address to return token and satoshi change to\n * @param {string?} message optional message to include in OP_RETURN\n * @param {SendRequestOptionsI} options Options of the send requests\n */\n async tokenBurn(burnRequest, message, options) {\n if (burnRequest.tokenId?.length !== 64) {\n throw Error(`Invalid tokenId supplied: ${burnRequest.tokenId}`);\n }\n const utxos = await this.getAddressUtxos(this.cashaddr);\n const tokenUtxos = utxos.filter((val) => val.token?.tokenId === burnRequest.tokenId &&\n val.token?.capability === burnRequest.capability &&\n val.token?.commitment === burnRequest.commitment);\n if (!tokenUtxos.length) {\n throw new Error(\"You do not have suitable token UTXOs to perform burn\");\n }\n const totalFungibleAmount = tokenUtxos.reduce((prev, cur) => prev + (cur.token?.amount || 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_18__.TokenSendRequest({\n cashaddr: burnRequest.cashaddr || this.tokenaddr,\n tokenId: burnRequest.tokenId,\n capability: burnRequest.capability,\n commitment: burnRequest.commitment,\n amount: safeNewAmount,\n value: tokenUtxos[0].satoshis,\n }),\n ];\n }\n }\n else {\n // if we are burning last 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_18__.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_18__.OpReturnData.fromString(message || \"\");\n return this.send([opReturn, ...changeSendRequests], {\n ...options,\n checkTokenQuantities: false,\n queryBalance: false,\n ensureUtxos: utxoIds.length > 0 ? utxoIds : undefined,\n tokenOperation: \"burn\",\n });\n }\n /**\n * getTokenUtxos Get unspent token outputs for the wallet\n * will return utxos only for the specified token if `tokenId` provided\n * @param {string?} tokenId tokenId (category) to filter utxos by, if not set will return utxos from all tokens\n * @returns {UtxoI[]} token utxos\n */\n async getTokenUtxos(tokenId) {\n const utxos = await this.getAddressUtxos(this.address);\n return utxos.filter((val) => tokenId ? val.token?.tokenId === tokenId : val.token);\n }\n /**\n * getTokenBalance Gets fungible token balance\n * for NFT token balance see @ref getNftTokenBalance\n * @param {string} tokenId tokenId to get balance for\n * @returns {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_25__.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.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_19__.CashAddressNetworkPrefix.mainnet;\nWallet.signedMessage = new _message_index_js__WEBPACK_IMPORTED_MODULE_34__.SignedMessage();\n/**\n * Class to manage a testnet wallet.\n */\nclass TestNetWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_3__.NetworkType.Testnet);\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_6__.TestNetUtil;\n }\n}\nTestNetWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_19__.CashAddressNetworkPrefix.testnet;\nTestNetWallet.faucetServer = \"https://rest-unstable.mainnet.cash\";\n/**\n * Class to manage a regtest wallet.\n */\nclass RegTestWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_3__.NetworkType.Regtest);\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_6__.RegTestUtil;\n }\n}\nRegTestWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_19__.CashAddressNetworkPrefix.regtest;\n/**\n * Class to manage a bitcoin cash wif wallet.\n */\nclass WifWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_3__.NetworkType.Mainnet, _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Wif);\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_6__.WifUtil;\n }\n}\nWifWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_19__.CashAddressNetworkPrefix.mainnet;\nWifWallet.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Wif;\n/**\n * Class to manage a testnet wif wallet.\n */\nclass TestNetWifWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_3__.NetworkType.Testnet, _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Wif);\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_6__.TestNetWifUtil;\n }\n}\nTestNetWifWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_19__.CashAddressNetworkPrefix.testnet;\nTestNetWifWallet.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Wif;\n/**\n * Class to manage a regtest wif wallet.\n */\nclass RegTestWifWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_3__.NetworkType.Regtest, _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Wif);\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_6__.RegTestWifUtil;\n }\n}\nRegTestWifWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_19__.CashAddressNetworkPrefix.regtest;\nRegTestWifWallet.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Wif;\n/**\n * Class to manage a bitcoin cash watch wallet.\n */\nclass WatchWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_3__.NetworkType.Mainnet, _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Watch);\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_6__.WatchUtil;\n }\n}\nWatchWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_19__.CashAddressNetworkPrefix.mainnet;\nWatchWallet.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Watch;\n/**\n * Class to manage a testnet watch wallet.\n */\nclass TestNetWatchWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_3__.NetworkType.Testnet, _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Watch);\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_6__.TestNetWatchUtil;\n }\n}\nTestNetWatchWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_19__.CashAddressNetworkPrefix.testnet;\nTestNetWatchWallet.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Watch;\n/**\n * Class to manage a regtest watch wallet.\n */\nclass RegTestWatchWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_3__.NetworkType.Regtest, _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Watch);\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_6__.RegTestWatchUtil;\n }\n}\nRegTestWatchWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_19__.CashAddressNetworkPrefix.regtest;\nRegTestWatchWallet.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Watch;\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/wallet/Wif.ts?");
|
|
1137
|
+
eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"RegTestWallet\": () => (/* binding */ RegTestWallet),\n/* harmony export */ \"RegTestWatchWallet\": () => (/* binding */ RegTestWatchWallet),\n/* harmony export */ \"RegTestWifWallet\": () => (/* binding */ RegTestWifWallet),\n/* harmony export */ \"TestNetWallet\": () => (/* binding */ TestNetWallet),\n/* harmony export */ \"TestNetWatchWallet\": () => (/* binding */ TestNetWatchWallet),\n/* harmony export */ \"TestNetWifWallet\": () => (/* binding */ TestNetWifWallet),\n/* harmony export */ \"Wallet\": () => (/* binding */ Wallet),\n/* harmony export */ \"WatchWallet\": () => (/* binding */ WatchWallet),\n/* harmony export */ \"WifWallet\": () => (/* binding */ WifWallet)\n/* harmony export */ });\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/key/hd-key.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/address/cash-address.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_33__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/crypto/default-crypto-instances.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/hex.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/key/key-utils.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/key/wallet-import-format.js\");\n/* harmony import */ var bip39__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! bip39 */ \"../../node_modules/bip39/src/index.js\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../enum.js */ \"./src/enum.ts\");\n/* harmony import */ var _interface_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../interface.js */ \"./src/interface.ts\");\n/* harmony import */ var _Base_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Base.js */ \"./src/wallet/Base.ts\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./enum.js */ \"./src/wallet/enum.ts\");\n/* harmony import */ var _model_js__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./model.js */ \"./src/wallet/model.ts\");\n/* harmony import */ var _transaction_Wif_js__WEBPACK_IMPORTED_MODULE_29__ = __webpack_require__(/*! ../transaction/Wif.js */ \"./src/transaction/Wif.ts\");\n/* harmony import */ var _util_asSendRequestObject_js__WEBPACK_IMPORTED_MODULE_30__ = __webpack_require__(/*! ../util/asSendRequestObject.js */ \"./src/util/asSendRequestObject.ts\");\n/* harmony import */ var _util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(/*! ../util/balanceObjectFromSatoshi.js */ \"./src/util/balanceObjectFromSatoshi.ts\");\n/* harmony import */ var _util_checkWifNetwork_js__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ../util/checkWifNetwork.js */ \"./src/util/checkWifNetwork.ts\");\n/* harmony import */ var _util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ../util/deriveCashaddr.js */ \"./src/util/deriveCashaddr.ts\");\n/* harmony import */ var _util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../util/derivePublicKeyHash.js */ \"./src/util/derivePublicKeyHash.ts\");\n/* harmony import */ var _util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../util/checkForEmptySeed.js */ \"./src/util/checkForEmptySeed.ts\");\n/* harmony import */ var _util_sanitizeUnit_js__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! ../util/sanitizeUnit.js */ \"./src/util/sanitizeUnit.ts\");\n/* harmony import */ var _util_sumUtxoValue_js__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(/*! ../util/sumUtxoValue.js */ \"./src/util/sumUtxoValue.ts\");\n/* harmony import */ var _util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_31__ = __webpack_require__(/*! ../util/sumSendRequestAmounts.js */ \"./src/util/sumSendRequestAmounts.ts\");\n/* harmony import */ var _network_getRelayFeeCache_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../network/getRelayFeeCache.js */ \"./src/network/getRelayFeeCache.ts\");\n/* harmony import */ var _Util_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./Util.js */ \"./src/wallet/Util.ts\");\n/* harmony import */ var _network_index_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../network/index.js */ \"./src/network/default.ts\");\n/* harmony import */ var _util_randomBytes_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../util/randomBytes.js */ \"./src/util/randomBytes.ts\");\n/* harmony import */ var _message_index_js__WEBPACK_IMPORTED_MODULE_34__ = __webpack_require__(/*! ../message/index.js */ \"./src/message/signed.ts\");\n/* harmony import */ var _util_amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(/*! ../util/amountInSatoshi.js */ \"./src/util/amountInSatoshi.ts\");\n/* harmony import */ var _util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../util/getXPubKey.js */ \"./src/util/getXPubKey.ts\");\n/* harmony import */ var _constant_js__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ../constant.js */ \"./src/constant.ts\");\n/* harmony import */ var _history_electrumTransformer_js__WEBPACK_IMPORTED_MODULE_32__ = __webpack_require__(/*! ../history/electrumTransformer.js */ \"./src/history/electrumTransformer.ts\");\n/* harmony import */ var _Bcmr_js__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(/*! ./Bcmr.js */ \"./src/wallet/Bcmr.ts\");\n/* harmony import */ var _qr_Qr_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../qr/Qr.js */ \"./src/qr/Qr.ts\");\n/* harmony import */ var _config_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../config.js */ \"./src/config.ts\");\n/* harmony import */ var _util_checkUtxos_js__WEBPACK_IMPORTED_MODULE_28__ = __webpack_require__(/*! ../util/checkUtxos.js */ \"./src/util/checkUtxos.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_Base_js__WEBPACK_IMPORTED_MODULE_2__, _enum_js__WEBPACK_IMPORTED_MODULE_3__, _Util_js__WEBPACK_IMPORTED_MODULE_6__, _network_index_js__WEBPACK_IMPORTED_MODULE_8__, _qr_Qr_js__WEBPACK_IMPORTED_MODULE_9__, _util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_11__, _util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_14__, _util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_15__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_16__, _model_js__WEBPACK_IMPORTED_MODULE_18__, _util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_20__, _util_checkWifNetwork_js__WEBPACK_IMPORTED_MODULE_21__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_22__, _util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_24__, _util_amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_26__, _Bcmr_js__WEBPACK_IMPORTED_MODULE_27__, _transaction_Wif_js__WEBPACK_IMPORTED_MODULE_29__, _util_asSendRequestObject_js__WEBPACK_IMPORTED_MODULE_30__, _util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_31__, _history_electrumTransformer_js__WEBPACK_IMPORTED_MODULE_32__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_33__, _message_index_js__WEBPACK_IMPORTED_MODULE_34__]);\n([_Base_js__WEBPACK_IMPORTED_MODULE_2__, _enum_js__WEBPACK_IMPORTED_MODULE_3__, _Util_js__WEBPACK_IMPORTED_MODULE_6__, _network_index_js__WEBPACK_IMPORTED_MODULE_8__, _qr_Qr_js__WEBPACK_IMPORTED_MODULE_9__, _util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_11__, _util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_14__, _util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_15__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_16__, _model_js__WEBPACK_IMPORTED_MODULE_18__, _util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_20__, _util_checkWifNetwork_js__WEBPACK_IMPORTED_MODULE_21__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_22__, _util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_24__, _util_amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_26__, _Bcmr_js__WEBPACK_IMPORTED_MODULE_27__, _transaction_Wif_js__WEBPACK_IMPORTED_MODULE_29__, _util_asSendRequestObject_js__WEBPACK_IMPORTED_MODULE_30__, _util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_31__, _history_electrumTransformer_js__WEBPACK_IMPORTED_MODULE_32__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_33__, _message_index_js__WEBPACK_IMPORTED_MODULE_34__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n//#region Imports\n// Stable\n\n// Unstable?\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n//#endregion Imports\n/**\n * Class to manage a bitcoin cash wallet.\n */\nclass Wallet extends _Base_js__WEBPACK_IMPORTED_MODULE_2__.BaseWallet {\n //#endregion\n //#region Constructors and Statics\n constructor(name = \"\", network = _enum_js__WEBPACK_IMPORTED_MODULE_3__.NetworkType.Mainnet, walletType = _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Seed) {\n super(name, network, walletType);\n this.derivationPath = _config_js__WEBPACK_IMPORTED_MODULE_5__.Config.DefaultParentDerivationPath + \"/0/0\";\n this.parentDerivationPath = _config_js__WEBPACK_IMPORTED_MODULE_5__.Config.DefaultParentDerivationPath;\n this._slpSemiAware = false; // a flag which requires an utxo to have more than 546 sats to be spendable and counted in the balance\n this.fromId = async (walletId) => {\n let [walletType, networkGiven, arg1] = walletId.split(\":\");\n if (this.network != networkGiven) {\n throw Error(`Network prefix ${networkGiven} to a ${this.network} wallet`);\n }\n // \"wif:regtest:cNfsPtqN2bMRS7vH5qd8tR8GMvgXyL5BjnGAKgZ8DYEiCrCCQcP6\"\n if (walletType === \"wif\") {\n return this.fromWIF(arg1);\n }\n return super.fromId(walletId);\n };\n this.networkPrefix = _enum_js__WEBPACK_IMPORTED_MODULE_3__.prefixFromNetworkMap[this.network];\n }\n //#region Accessors\n // interface to util functions. see Util.ts\n get util() {\n if (!this._util) {\n this._util = new _Util_js__WEBPACK_IMPORTED_MODULE_6__.Util(this);\n }\n return this._util;\n }\n // interface to util util. see Util.Util\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_6__.Util;\n }\n slpSemiAware(value = true) {\n this._slpSemiAware = value;\n return this;\n }\n getNetworkProvider(network = _interface_js__WEBPACK_IMPORTED_MODULE_7__.Network.MAINNET) {\n return (0,_network_index_js__WEBPACK_IMPORTED_MODULE_8__.getNetworkProvider)(network);\n }\n /**\n * getTokenDepositAddress - get a cashtoken aware wallet deposit address\n *\n * @returns The cashtoken aware deposit address as a string\n */\n getTokenDepositAddress() {\n return this.tokenaddr;\n }\n /**\n * getDepositQr - get an address qrcode, encoded for display on the web\n *\n * @returns The qrcode for the token aware address\n */\n getTokenDepositQr() {\n return (0,_qr_Qr_js__WEBPACK_IMPORTED_MODULE_9__.qrAddress)(this.getTokenDepositAddress());\n }\n /**\n * explorerUrl Web url to a transaction on a block explorer\n *\n * @param txId transaction Id\n * @returns Url string\n */\n explorerUrl(txId) {\n const explorerUrlMap = {\n mainnet: \"https://blockchair.com/bitcoin-cash/transaction/\",\n testnet: \"https://www.blockchain.com/bch-testnet/tx/\",\n regtest: \"\",\n };\n return explorerUrlMap[this.network] + txId;\n }\n // Return wallet info\n getInfo() {\n return {\n cashaddr: this.cashaddr,\n tokenaddr: this.tokenaddr,\n isTestnet: this.isTestnet,\n name: this.name,\n network: this.network,\n seed: this.mnemonic ? this.getSeed().seed : undefined,\n derivationPath: this.mnemonic ? this.getSeed().derivationPath : undefined,\n parentDerivationPath: this.mnemonic\n ? this.getSeed().parentDerivationPath\n : undefined,\n parentXPubKey: this.parentXPubKey ? this.parentXPubKey : undefined,\n publicKey: this.publicKey ? (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__.binToHex)(this.publicKey) : undefined,\n publicKeyHash: (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__.binToHex)(this.publicKeyHash),\n privateKey: this.privateKey ? (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__.binToHex)(this.privateKey) : undefined,\n privateKeyWif: this.privateKeyWif,\n walletId: this.toString(),\n walletDbEntry: this.toDbString(),\n };\n }\n // returns the public key hash for an address\n getPublicKey(hex = false) {\n if (this.publicKey) {\n return hex ? (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__.binToHex)(this.publicKey) : this.publicKey;\n }\n else {\n throw Error(\"The public key for this wallet is not known, perhaps the wallet was created to watch the *hash* of a public key? i.e. a cashaddress.\");\n }\n }\n // returns the public key hash for an address\n getPublicKeyCompressed(hex = false) {\n if (this.publicKeyCompressed) {\n return hex\n ? (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__.binToHex)(this.publicKeyCompressed)\n : this.publicKeyCompressed;\n }\n else {\n throw Error(\"The compressed public key for this wallet is not known, perhaps the wallet was created to watch the *hash* of a public key? i.e. a cashaddress.\");\n }\n }\n // returns the public key hash for an address\n getPublicKeyHash(hex = false) {\n if (this.publicKeyHash) {\n return hex ? (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__.binToHex)(this.publicKeyHash) : this.publicKeyHash;\n }\n else {\n throw Error(\"The public key hash for this wallet is not known. If this wallet was created from the constructor directly, calling the deriveInfo() function may help. \");\n }\n }\n /**\n * fromWIF - create a wallet using the private key supplied in `Wallet Import Format`\n *\n * @param wif WIF encoded private key string\n *\n * @returns instantiated wallet\n */\n static async fromWIF(wif) {\n return new this().fromWIF(wif);\n }\n /**\n * fromCashaddr - create a watch-only wallet in the network derived from the address\n *\n * such kind of wallet does not have a private key and is unable to spend any funds\n * however it still allows to use many utility functions such as getting and watching balance, etc.\n *\n * @param address cashaddress of a wallet\n *\n * @returns instantiated wallet\n */\n static async fromCashaddr(address) {\n const prefix = (0,_util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_11__.derivePrefix)(address);\n const networkType = _enum_js__WEBPACK_IMPORTED_MODULE_3__.networkPrefixMap[prefix];\n return new this(\"\", networkType, _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Watch).watchOnly(address);\n }\n /**\n * fromTokenaddr - create a watch-only wallet in the network derived from the address\n *\n * such kind of wallet does not have a private key and is unable to spend any funds\n * however it still allows to use many utility functions such as getting and watching balance, etc.\n *\n * @param address token aware cashaddress of a wallet\n *\n * @returns instantiated wallet\n */\n static async fromTokenaddr(address) {\n const prefix = (0,_util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_11__.derivePrefix)(address);\n const networkType = _enum_js__WEBPACK_IMPORTED_MODULE_3__.networkPrefixMap[prefix];\n return new this(\"\", networkType, _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Watch).watchOnly(address);\n }\n //#endregion Constructors and Statics\n //#region Protected implementations\n async generate() {\n if (this.walletType === _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Wif) {\n return await this._generateWif();\n }\n else if (this.walletType === _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Watch) {\n return this;\n }\n else if (this.walletType === _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Hd) {\n throw Error(\"Not implemented\");\n }\n else if (this.walletType === _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Seed) {\n return await this._generateMnemonic();\n }\n else {\n console.log(this.walletType);\n throw Error(`Could not determine walletType: ${this.walletType}`);\n }\n }\n async _generateWif() {\n if (!this.privateKey) {\n this.privateKey = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_12__.generatePrivateKey)(() => (0,_util_randomBytes_js__WEBPACK_IMPORTED_MODULE_13__.generateRandomBytes)(32));\n }\n return this.deriveInfo();\n }\n async _generateMnemonic() {\n this.mnemonic = (0,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_14__.checkForEmptySeed)(seed);\n let network = this.isTestnet ? \"testnet\" : \"mainnet\";\n this.parentXPubKey = await (0,_util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_15__.getXPubKey)(seed, this.parentDerivationPath, network);\n let hdNode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_16__.deriveHdPrivateNodeFromSeed)(seed);\n if (!hdNode.valid) {\n throw Error(\"Invalid private key derived from mnemonic seed\");\n }\n let zerothChild = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_16__.deriveHdPath)(hdNode, this.derivationPath);\n if (typeof zerothChild === \"string\") {\n throw Error(zerothChild);\n }\n this.privateKey = zerothChild.privateKey;\n this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Seed;\n return await this.deriveInfo();\n }\n async getXPubKeys(paths) {\n if (this.mnemonic) {\n if (paths) {\n let xPubKeys = await this.deriveHdPaths(paths);\n return [xPubKeys];\n }\n else {\n return await this.deriveHdPaths(_constant_js__WEBPACK_IMPORTED_MODULE_17__.DERIVATION_PATHS);\n }\n }\n else {\n throw Error(\"xpubkeys can only be derived from seed type wallets.\");\n }\n }\n // Initialize wallet from a mnemonic phrase\n async fromSeed(mnemonic, derivationPath) {\n this.mnemonic = mnemonic.trim().toLowerCase();\n if (this.mnemonic.length == 0)\n throw Error(\"refusing to create wallet from empty mnemonic\");\n let seed = (0,bip39__WEBPACK_IMPORTED_MODULE_0__.mnemonicToSeedSync)(this.mnemonic);\n (0,_util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_14__.checkForEmptySeed)(seed);\n let hdNode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_16__.deriveHdPrivateNodeFromSeed)(seed);\n if (!hdNode.valid) {\n throw Error(\"Invalid private key derived from mnemonic seed\");\n }\n if (derivationPath) {\n this.derivationPath = derivationPath;\n // If the derivation path is for the first account child, set the parent derivation path\n let path = derivationPath.split(\"/\");\n if (path.slice(-2).join(\"/\") == \"0/0\") {\n this.parentDerivationPath = path.slice(0, -2).join(\"/\");\n }\n }\n let zerothChild = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_16__.deriveHdPath)(hdNode, this.derivationPath);\n if (typeof zerothChild === \"string\") {\n throw Error(zerothChild);\n }\n this.privateKey = zerothChild.privateKey;\n let network = this.isTestnet ? \"testnet\" : \"mainnet\";\n this.parentXPubKey = await (0,_util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_15__.getXPubKey)(seed, this.parentDerivationPath, network);\n this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Seed;\n await this.deriveInfo();\n return this;\n }\n // Get common xpub paths from zerothChild privateKey\n async deriveHdPaths(hdPaths) {\n if (!this.mnemonic)\n throw Error(\"refusing to create wallet from empty mnemonic\");\n let seed = (0,bip39__WEBPACK_IMPORTED_MODULE_0__.mnemonicToSeedSync)(this.mnemonic);\n (0,_util_checkForEmptySeed_js__WEBPACK_IMPORTED_MODULE_14__.checkForEmptySeed)(seed);\n let hdNode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_16__.deriveHdPrivateNodeFromSeed)(seed);\n if (!hdNode.valid) {\n throw Error(\"Invalid private key derived from mnemonic seed\");\n }\n let result = [];\n for (const path of hdPaths) {\n if (path === \"m\") {\n throw Error(\"Storing or sharing of parent public key may lead to loss of funds. Storing or sharing *root* parent public keys is strongly discouraged, although all parent keys have risk. See: https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#implications\");\n }\n let childNode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_16__.deriveHdPath)(hdNode, path);\n if (typeof childNode === \"string\") {\n throw Error(childNode);\n }\n let node = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_16__.deriveHdPublicNode)(childNode);\n if (typeof node === \"string\") {\n throw Error(node);\n }\n let xPubKey = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_16__.encodeHdPublicKey)({\n network: this.network,\n node: node,\n });\n let key = new _model_js__WEBPACK_IMPORTED_MODULE_18__.XPubKey({\n path: path,\n xPubKey: xPubKey,\n });\n result.push(await key.ready());\n }\n return await Promise.all(result).then((result) => {\n return result;\n });\n }\n // Initialize a watch only wallet from a cash addr\n async watchOnly(address) {\n this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Watch;\n let addressComponents = address.split(\":\");\n let addressPrefix, addressBase;\n if (addressComponents.length === 1) {\n addressBase = addressComponents.shift();\n addressPrefix = (0,_util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_11__.derivePrefix)(addressBase);\n }\n else {\n addressPrefix = addressComponents.shift();\n addressBase = addressComponents.shift();\n if (addressPrefix in _enum_js__WEBPACK_IMPORTED_MODULE_3__.networkPrefixMap) {\n if (_enum_js__WEBPACK_IMPORTED_MODULE_3__.networkPrefixMap[addressPrefix] != this.network) {\n throw Error(`a ${addressPrefix} address cannot be watched from a ${this.network} Wallet`);\n }\n }\n }\n const prefixedAddress = `${addressPrefix}:${addressBase}`;\n // check if a token aware address was provided\n let addressData = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_19__.decodeCashAddress)(prefixedAddress);\n if (typeof addressData === \"string\")\n throw addressData;\n this.publicKeyHash = addressData.payload;\n let nonTokenAwareType = addressData.type;\n if (nonTokenAwareType == _bitauth_libauth__WEBPACK_IMPORTED_MODULE_19__.CashAddressType.p2pkhWithTokens)\n nonTokenAwareType = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_19__.CashAddressType.p2pkh;\n if (nonTokenAwareType == _bitauth_libauth__WEBPACK_IMPORTED_MODULE_19__.CashAddressType.p2shWithTokens)\n nonTokenAwareType = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_19__.CashAddressType.p2sh;\n if (nonTokenAwareType == _bitauth_libauth__WEBPACK_IMPORTED_MODULE_19__.CashAddressType.p2pkh)\n this.publicKeyHash = addressData.payload;\n this.cashaddr = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_19__.encodeCashAddress)(addressData.prefix, nonTokenAwareType, addressData.payload);\n this.address = this.cashaddr;\n this.tokenaddr = (0,_util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_20__.deriveTokenaddr)(addressData.payload, this.networkPrefix);\n return this;\n }\n // Initialize wallet from Wallet Import Format\n async fromWIF(secret) {\n (0,_util_checkWifNetwork_js__WEBPACK_IMPORTED_MODULE_21__.checkWifNetwork)(secret, this.network);\n let wifResult = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_22__.decodePrivateKeyWif)(secret);\n if (typeof wifResult === \"string\") {\n throw Error(wifResult);\n }\n let resultData = wifResult;\n this.privateKey = resultData.privateKey;\n this.privateKeyWif = secret;\n this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Wif;\n await this.deriveInfo();\n return this;\n }\n async newRandom(name, dbName) {\n dbName = dbName ? dbName : this.networkPrefix;\n return super.newRandom(name, dbName);\n }\n async named(name, dbName, forceNew = false) {\n dbName = dbName ? dbName : this.networkPrefix;\n return super.named(name, dbName, forceNew);\n }\n async replaceNamed(name, walletId, dbName) {\n dbName = dbName ? dbName : this.networkPrefix;\n return super.replaceNamed(name, walletId, dbName);\n }\n async namedExists(name, dbName) {\n dbName = dbName ? dbName : this.networkPrefix;\n return super.namedExists(name, dbName);\n }\n //#endregion Protected Implementations\n //#region Serialization\n // Returns the serialized wallet as a string\n // If storing in a database, set asNamed to false to store secrets\n // In all other cases, the a named wallet is deserialized from the database\n // by the name key\n toString() {\n const result = super.toString();\n if (result)\n return result;\n if (this.walletType === _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Wif) {\n return `${this.walletType}:${this.network}:${this.privateKeyWif}`;\n }\n throw Error(\"toString unsupported wallet type\");\n }\n //\n toDbString() {\n const result = super.toDbString();\n if (result)\n return result;\n if (this.walletType === _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Wif) {\n return `${this.walletType}:${this.network}:${this.privateKeyWif}`;\n }\n throw Error(\"toDbString unsupported wallet type\");\n }\n //#endregion Serialization\n //#region Funds\n //\n async getAddressUtxos(address) {\n if (!address) {\n address = this.cashaddr;\n }\n if (this._slpSemiAware) {\n const bchUtxos = await this.provider.getUtxos(address);\n return bchUtxos.filter((bchutxo) => bchutxo.satoshis > _constant_js__WEBPACK_IMPORTED_MODULE_17__.DUST_UTXO_THRESHOLD);\n }\n else {\n return await this.provider.getUtxos(address);\n }\n }\n /**\n * utxos Get unspent outputs for the wallet\n *\n */\n async getUtxos() {\n if (!this.cashaddr) {\n throw Error(\"Attempted to get utxos without an address\");\n }\n return await this.getAddressUtxos(this.cashaddr);\n }\n // gets wallet balance in sats, bch and usd\n async getBalance(rawUnit, usdPriceCache = true) {\n if (rawUnit) {\n const unit = (0,_util_sanitizeUnit_js__WEBPACK_IMPORTED_MODULE_23__.sanitizeUnit)(rawUnit);\n return await (0,_util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_24__.balanceFromSatoshi)(await this.getBalanceFromProvider(), unit, usdPriceCache);\n }\n else {\n return await (0,_util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_24__.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_25__.sumUtxoValue)(utxos);\n }\n // Gets balance from fulcrum\n async getBalanceFromProvider() {\n // Fulcrum reports balance of all utxos, including tokens, which is undesirable\n // // TODO not sure why getting the balance from a provider doesn't work\n // if (this._slpAware || this._slpSemiAware) {\n // return await this.getBalanceFromUtxos();\n // } else {\n // return await this.provider!.getBalance(this.cashaddr!);\n // }\n // FIXME\n return this.getBalanceFromUtxos();\n }\n // watching for any transaction hash of this wallet\n watchAddress(callback) {\n return this.provider.watchAddress(this.getDepositAddress(), callback);\n }\n // watching for any transaction of this wallet\n watchAddressTransactions(callback) {\n return this.provider.watchAddressTransactions(this.getDepositAddress(), callback);\n }\n // watching for cashtoken transaction of this wallet\n watchAddressTokenTransactions(callback) {\n return this.provider.watchAddressTokenTransactions(this.getDepositAddress(), callback);\n }\n // sets up a callback to be called upon wallet's balance change\n // can be cancelled by calling the function returned from this one\n watchBalance(callback) {\n return this.provider.watchAddressStatus(this.getDepositAddress(), async (_status) => {\n const balance = (await this.getBalance());\n callback(balance);\n });\n }\n // sets up a callback to be called upon wallet's BCH or USD balance change\n // if BCH balance does not change, the callback will be triggered every\n // @param `usdPriceRefreshInterval` milliseconds by polling for new BCH USD price\n // Since we want to be most sensitive to usd value change, we do not use the cached exchange rates\n // can be cancelled by calling the function returned from this one\n watchBalanceUsd(callback, usdPriceRefreshInterval = 30000) {\n let usdPrice = -1;\n const _callback = async () => {\n const balance = (await this.getBalance(undefined, false));\n if (usdPrice !== balance.usd) {\n usdPrice = balance.usd;\n callback(balance);\n }\n };\n const watchCancel = this.provider.watchAddressStatus(this.getDepositAddress(), _callback);\n const interval = setInterval(_callback, usdPriceRefreshInterval);\n return async () => {\n await watchCancel();\n clearInterval(interval);\n };\n }\n // waits for address balance to be greater than or equal to the target value\n // this call halts the execution\n async waitForBalance(value, rawUnit = _enum_js__WEBPACK_IMPORTED_MODULE_3__.UnitEnum.BCH) {\n return new Promise(async (resolve) => {\n const watchCancel = this.watchBalance(async (balance) => {\n const satoshiBalance = await (0,_util_amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_26__.amountInSatoshi)(value, rawUnit);\n if (balance.sat >= satoshiBalance) {\n await watchCancel();\n resolve(balance);\n }\n });\n });\n }\n // sets up a callback to be called upon wallet's token balance change\n // can be cancelled by calling the function returned from this one\n watchTokenBalance(tokenId, callback) {\n let previous = undefined;\n return this.provider.watchAddressStatus(this.getDepositAddress(), async (_status) => {\n const balance = await this.getTokenBalance(tokenId);\n if (previous != balance) {\n callback(balance);\n }\n previous = balance;\n });\n }\n // waits for address token balance to be greater than or equal to the target amount\n // this call halts the execution\n async waitForTokenBalance(tokenId, amount) {\n return new Promise(async (resolve) => {\n const watchCancel = this.watchTokenBalance(tokenId, async (balance) => {\n if (balance >= amount) {\n await watchCancel();\n resolve(balance);\n }\n });\n });\n }\n async getTokenInfo(tokenId) {\n return _Bcmr_js__WEBPACK_IMPORTED_MODULE_27__.BCMR.getTokenInfo(tokenId);\n }\n async _getMaxAmountToSend(params = {\n outputCount: 1,\n options: {},\n }) {\n if (!this.privateKey && params.options?.buildUnsigned !== true) {\n throw Error(\"Couldn't get network or private key for wallet.\");\n }\n if (!this.cashaddr) {\n throw Error(\"attempted to send without a cashaddr\");\n }\n if (params.options && params.options.slpSemiAware) {\n this._slpSemiAware = true;\n }\n let feePaidBy;\n if (params.options && params.options.feePaidBy) {\n feePaidBy = params.options.feePaidBy;\n }\n else {\n feePaidBy = _enum_js__WEBPACK_IMPORTED_MODULE_4__.FeePaidByEnum.change;\n }\n // get inputs\n let utxos;\n if (params.options && params.options.utxoIds) {\n utxos = await (0,_util_checkUtxos_js__WEBPACK_IMPORTED_MODULE_28__.checkUtxos)(params.options.utxoIds.map((utxoId) => typeof utxoId === \"string\" ? (0,_model_js__WEBPACK_IMPORTED_MODULE_18__.fromUtxoId)(utxoId) : utxoId), this);\n }\n else {\n utxos = (await this.getAddressUtxos(this.cashaddr)).filter((utxo) => !utxo.token);\n }\n // Get current height to assure recently mined coins are not spent.\n const bestHeight = await this.provider.getBlockHeight();\n // simulate outputs using the sender's address\n const sendRequest = new _model_js__WEBPACK_IMPORTED_MODULE_18__.SendRequest({\n cashaddr: this.cashaddr,\n value: 100,\n unit: \"sat\",\n });\n const sendRequests = Array(params.outputCount)\n .fill(0)\n .map(() => sendRequest);\n const fundingUtxos = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_29__.getSuitableUtxos)(utxos, undefined, bestHeight, feePaidBy, sendRequests);\n const relayFeePerByteInSatoshi = await (0,_network_getRelayFeeCache_js__WEBPACK_IMPORTED_MODULE_1__.getRelayFeeCache)(this.provider);\n const fee = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_29__.getFeeAmountSimple)({\n utxos: fundingUtxos,\n sendRequests: sendRequests,\n privateKey: this.privateKey ?? Uint8Array.from([]),\n sourceAddress: this.cashaddr,\n relayFeePerByteInSatoshi: relayFeePerByteInSatoshi,\n feePaidBy: feePaidBy,\n });\n const spendableAmount = (0,_util_sumUtxoValue_js__WEBPACK_IMPORTED_MODULE_25__.sumUtxoValue)(fundingUtxos);\n let result = spendableAmount - fee;\n if (result < 0) {\n result = 0;\n }\n return { value: result, utxos: fundingUtxos };\n }\n async getMaxAmountToSend(params = {\n outputCount: 1,\n options: {},\n }) {\n const { value: result } = await this._getMaxAmountToSend(params);\n return await (0,_util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_24__.balanceResponseFromSatoshi)(result);\n }\n /**\n * send Send some amount to an address\n * this function processes the send requests, encodes the transaction, sends it to the network\n * @returns (depending on the options parameter) the transaction id, new address balance and a link to the transaction on the blockchain explorer\n *\n * This is a first class function with REST analog, maintainers should strive to keep backward-compatibility\n *\n */\n async send(requests, options) {\n const { encodedTransaction, tokenIds, sourceOutputs } = await this.encodeTransaction(requests, undefined, options);\n const resp = new _model_js__WEBPACK_IMPORTED_MODULE_18__.SendResponse({});\n resp.tokenIds = tokenIds;\n if (options?.buildUnsigned !== true) {\n const txId = await this.submitTransaction(encodedTransaction, options?.awaitTransactionPropagation === undefined ||\n options?.awaitTransactionPropagation === true);\n resp.txId = txId;\n resp.explorerUrl = this.explorerUrl(resp.txId);\n if (options?.queryBalance === undefined ||\n options?.queryBalance === true) {\n resp.balance = (await this.getBalance());\n }\n }\n else {\n resp.unsignedTransaction = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__.binToHex)(encodedTransaction);\n resp.sourceOutputs = sourceOutputs;\n }\n return resp;\n }\n /**\n * sendMax Send all available funds to a destination cash address\n *\n * @param {string} cashaddr destination cash address\n * @param {SendRequestOptionsI} options Options of the send requests\n *\n * @returns (depending on the options parameter) the transaction id, new address balance and a link to the transaction on the blockchain explorer\n */\n async sendMax(cashaddr, options) {\n return await this.sendMaxRaw(cashaddr, options);\n }\n /**\n * sendMaxRaw (internal) Send all available funds to a destination cash address\n *\n * @param {string} cashaddr destination cash address\n * @param {SendRequestOptionsI} options Options of the send requests\n *\n * @returns the transaction id sent to the network\n */\n async sendMaxRaw(cashaddr, options) {\n const { value: maxSpendableAmount, utxos } = await this._getMaxAmountToSend({\n outputCount: 1,\n options: options,\n });\n if (!options) {\n options = {};\n }\n options.utxoIds = utxos;\n const sendRequest = new _model_js__WEBPACK_IMPORTED_MODULE_18__.SendRequest({\n cashaddr: cashaddr,\n value: maxSpendableAmount,\n unit: \"sat\",\n });\n const { encodedTransaction, tokenIds, sourceOutputs } = await this.encodeTransaction([sendRequest], true, options);\n const resp = new _model_js__WEBPACK_IMPORTED_MODULE_18__.SendResponse({});\n resp.tokenIds = tokenIds;\n if (options?.buildUnsigned !== true) {\n const txId = await this.submitTransaction(encodedTransaction, options?.awaitTransactionPropagation === undefined ||\n options?.awaitTransactionPropagation === true);\n resp.txId = txId;\n resp.explorerUrl = this.explorerUrl(resp.txId);\n if (options?.queryBalance === undefined ||\n options?.queryBalance === true) {\n resp.balance = (await this.getBalance());\n }\n }\n else {\n resp.unsignedTransaction = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__.binToHex)(encodedTransaction);\n resp.sourceOutputs = sourceOutputs;\n }\n return resp;\n }\n /**\n * encodeTransaction Encode and sign a transaction given a list of sendRequests, options and estimate fees.\n * @param {SendRequest[]} sendRequests SendRequests\n * @param {boolean} discardChange=false\n * @param {SendRequestOptionsI} options Options of the send requests\n */\n async encodeTransaction(requests, discardChange = false, options) {\n let sendRequests = (0,_util_asSendRequestObject_js__WEBPACK_IMPORTED_MODULE_30__.asSendRequestObject)(requests);\n if (!this.privateKey && options?.buildUnsigned !== true) {\n throw new Error(`Wallet ${this.name} is missing either a network or private key`);\n }\n if (!this.cashaddr) {\n throw Error(\"attempted to send without a cashaddr\");\n }\n if (options && options.slpSemiAware) {\n this._slpSemiAware = true;\n }\n let feePaidBy;\n if (options && options.feePaidBy) {\n feePaidBy = options.feePaidBy;\n }\n else {\n feePaidBy = _enum_js__WEBPACK_IMPORTED_MODULE_4__.FeePaidByEnum.change;\n }\n let changeAddress;\n if (options && options.changeAddress) {\n changeAddress = options.changeAddress;\n }\n else {\n changeAddress = this.cashaddr;\n }\n let checkTokenQuantities = true;\n if (options && options.checkTokenQuantities === false) {\n checkTokenQuantities = false;\n }\n // get inputs from options or query all inputs\n let utxos;\n if (options && options.utxoIds) {\n utxos = await (0,_util_checkUtxos_js__WEBPACK_IMPORTED_MODULE_28__.checkUtxos)(options.utxoIds.map((utxoId) => typeof utxoId === \"string\" ? (0,_model_js__WEBPACK_IMPORTED_MODULE_18__.fromUtxoId)(utxoId) : utxoId), this);\n }\n else {\n utxos = await this.getAddressUtxos(this.cashaddr);\n }\n // filter out token utxos if there are no token requests\n if (checkTokenQuantities &&\n !sendRequests.some((val) => val instanceof _model_js__WEBPACK_IMPORTED_MODULE_18__.TokenSendRequest)) {\n utxos = utxos.filter((val) => !val.token);\n }\n const addTokenChangeOutputs = (inputs, outputs) => {\n // Allow for implicit token burn if the total amount sent is less than user had\n // allow for token genesis, creating more tokens than we had before (0)\n if (!checkTokenQuantities) {\n return;\n }\n const allTokenInputs = inputs.filter((val) => val.token);\n const allTokenOutputs = outputs.filter((val) => val instanceof _model_js__WEBPACK_IMPORTED_MODULE_18__.TokenSendRequest);\n const tokenIds = allTokenOutputs\n .map((val) => val.tokenId)\n .filter((val, idx, arr) => arr.indexOf(val) === idx);\n for (let tokenId of tokenIds) {\n const tokenInputs = allTokenInputs.filter((val) => val.token?.tokenId === tokenId);\n const inputAmountSum = tokenInputs.reduce((prev, cur) => prev + cur.token.amount, 0n);\n const tokenOutputs = allTokenOutputs.filter((val) => val.tokenId === tokenId);\n const outputAmountSum = tokenOutputs.reduce((prev, cur) => prev + cur.amount, 0n);\n const diff = inputAmountSum - outputAmountSum;\n if (diff < 0) {\n throw new Error(\"Not enough token amount to send\");\n }\n if (diff >= 0) {\n let available = 0n;\n let change = 0n;\n const ensureUtxos = [];\n for (const token of tokenInputs.filter((val) => val.token?.amount)) {\n ensureUtxos.push(token);\n available += token.token?.amount;\n if (available >= outputAmountSum) {\n change = available - outputAmountSum;\n //break;\n }\n }\n if (ensureUtxos.length) {\n if (!options) {\n options = {};\n }\n options.ensureUtxos = [\n ...(options.ensureUtxos ?? []),\n ...ensureUtxos,\n ].filter((val, index, array) => array.findIndex((other) => other.txid === val.txid && other.vout === val.vout) === index);\n }\n if (change > 0) {\n outputs.push(new _model_js__WEBPACK_IMPORTED_MODULE_18__.TokenSendRequest({\n cashaddr: (0,_util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_20__.toTokenaddr)(changeAddress) || this.tokenaddr,\n amount: change,\n tokenId: tokenId,\n commitment: tokenOutputs[0].commitment,\n capability: tokenOutputs[0].capability,\n value: tokenOutputs[0].value,\n }));\n }\n }\n }\n };\n addTokenChangeOutputs(utxos, sendRequests);\n const bestHeight = await this.provider.getBlockHeight();\n const spendAmount = await (0,_util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_31__.sumSendRequestAmounts)(sendRequests);\n if (utxos.length === 0) {\n throw Error(\"There were no Unspent Outputs\");\n }\n if (typeof spendAmount !== \"bigint\") {\n throw Error(\"Couldn't get spend amount when building transaction\");\n }\n const relayFeePerByteInSatoshi = await (0,_network_getRelayFeeCache_js__WEBPACK_IMPORTED_MODULE_1__.getRelayFeeCache)(this.provider);\n const feeEstimate = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_29__.getFeeAmountSimple)({\n utxos: utxos,\n sendRequests: sendRequests,\n privateKey: this.privateKey ?? Uint8Array.from([]),\n sourceAddress: this.cashaddr,\n relayFeePerByteInSatoshi: relayFeePerByteInSatoshi,\n feePaidBy: feePaidBy,\n });\n const fundingUtxos = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_29__.getSuitableUtxos)(utxos, BigInt(spendAmount) + BigInt(feeEstimate), bestHeight, feePaidBy, sendRequests, options?.ensureUtxos || [], options?.tokenOperation);\n if (fundingUtxos.length === 0) {\n throw Error(\"The available inputs couldn't satisfy the request with fees\");\n }\n const fee = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_29__.getFeeAmount)({\n utxos: fundingUtxos,\n sendRequests: sendRequests,\n privateKey: this.privateKey ?? Uint8Array.from([]),\n sourceAddress: this.cashaddr,\n relayFeePerByteInSatoshi: relayFeePerByteInSatoshi,\n feePaidBy: feePaidBy,\n });\n const { encodedTransaction, sourceOutputs } = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_29__.buildEncodedTransaction)({\n inputs: fundingUtxos,\n outputs: sendRequests,\n signingKey: this.privateKey ?? Uint8Array.from([]),\n sourceAddress: this.cashaddr,\n fee,\n discardChange,\n feePaidBy,\n changeAddress,\n buildUnsigned: options?.buildUnsigned === true,\n });\n const tokenIds = [\n ...fundingUtxos\n .filter((val) => val.token?.tokenId)\n .map((val) => val.token.tokenId),\n ...sendRequests\n .filter((val) => val instanceof _model_js__WEBPACK_IMPORTED_MODULE_18__.TokenSendRequest)\n .map((val) => val.tokenId),\n ].filter((value, index, array) => array.indexOf(value) === index);\n return { encodedTransaction, tokenIds, sourceOutputs };\n }\n async signUnsignedTransaction(transaction, sourceOutputs) {\n if (!this.privateKey) {\n throw Error(\"Can not sign a transaction with watch-only wallet.\");\n }\n return (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_29__.signUnsignedTransaction)(transaction, sourceOutputs, this.privateKey);\n }\n // Submit a raw transaction\n async submitTransaction(transaction, awaitPropagation = true) {\n if (!this.provider) {\n throw Error(\"Wallet network provider was not initialized\");\n }\n let rawTransaction = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__.binToHex)(transaction);\n return await this.provider.sendRawTransaction(rawTransaction, awaitPropagation);\n }\n // gets transaction history of this wallet\n async getRawHistory() {\n return await this.provider.getHistory(this.cashaddr);\n }\n // gets transaction history of this wallet\n async getHistory(unit, start, count, collapseChange) {\n return (0,_history_electrumTransformer_js__WEBPACK_IMPORTED_MODULE_32__.getAddressHistory)(this.cashaddr, this.provider, unit, start, count, collapseChange);\n }\n // gets last transaction of this wallet\n async getLastTransaction(confirmedOnly = false) {\n let history = await this.getRawHistory();\n if (confirmedOnly) {\n history = history.filter((val) => val.height > 0);\n }\n if (!history.length) {\n return null;\n }\n const [lastTx] = history.slice(-1);\n return this.provider.getRawTransactionObject(lastTx.tx_hash);\n }\n // waits for next transaction, program execution is halted\n async waitForTransaction(options = {\n getTransactionInfo: true,\n getBalance: false,\n txHash: undefined,\n }) {\n if (options.getTransactionInfo === undefined) {\n options.getTransactionInfo = true;\n }\n return new Promise(async (resolve) => {\n let txHashSeen = false;\n const makeResponse = async (txHash) => {\n const response = {};\n const promises = [undefined, undefined];\n if (options.getBalance === true) {\n promises[0] = this.getBalance();\n }\n if (options.getTransactionInfo === true) {\n if (!txHash) {\n promises[1] = this.getLastTransaction();\n }\n else {\n promises[1] = this.provider.getRawTransactionObject(txHash);\n }\n }\n const result = await Promise.all(promises);\n response.balance = result[0];\n response.transactionInfo = result[1];\n return response;\n };\n // waiting for a specific transaction to propagate\n if (options.txHash) {\n const waitForTransactionCallback = async (data) => {\n if (data && data[0] === options.txHash) {\n txHashSeen = true;\n this.provider.unsubscribeFromTransaction(options.txHash, waitForTransactionCallback);\n resolve(makeResponse(options.txHash));\n }\n };\n this.provider.subscribeToTransaction(options.txHash, waitForTransactionCallback);\n return;\n }\n // waiting for any address transaction\n const watchCancel = this.provider.watchAddressStatus(this.getDepositAddress(), async (_status) => {\n watchCancel();\n resolve(makeResponse());\n });\n });\n }\n /**\n * watchBlocks Watch network blocks\n *\n * @param callback callback with a block header object\n *\n * @returns a function which will cancel watching upon evaluation\n */\n watchBlocks(callback) {\n return this.provider.watchBlocks(callback);\n }\n /**\n * waitForBlock Wait for a network block\n *\n * @param height if specified waits for this exact blockchain height, otherwise resolves with the next block\n *\n */\n async waitForBlock(height) {\n return this.provider.waitForBlock(height);\n }\n //#endregion Funds\n //#region Private implementation details\n async deriveInfo() {\n const publicKey = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_33__.secp256k1.derivePublicKeyUncompressed(this.privateKey);\n if (typeof publicKey === \"string\") {\n throw new Error(publicKey);\n }\n this.publicKey = publicKey;\n const publicKeyCompressed = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_33__.secp256k1.derivePublicKeyCompressed(this.privateKey);\n if (typeof publicKeyCompressed === \"string\") {\n throw new Error(publicKeyCompressed);\n }\n this.publicKeyCompressed = publicKeyCompressed;\n const networkType = this.network === _enum_js__WEBPACK_IMPORTED_MODULE_3__.NetworkType.Regtest ? _enum_js__WEBPACK_IMPORTED_MODULE_3__.NetworkType.Testnet : this.network;\n this.privateKeyWif = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_22__.encodePrivateKeyWif)(this.privateKey, networkType);\n (0,_util_checkWifNetwork_js__WEBPACK_IMPORTED_MODULE_21__.checkWifNetwork)(this.privateKeyWif, this.network);\n this.cashaddr = (0,_util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_20__.deriveCashaddr)(this.privateKey, this.networkPrefix);\n this.tokenaddr = (0,_util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_20__.deriveTokenaddr)(this.privateKey, this.networkPrefix);\n this.address = this.cashaddr;\n this.publicKeyHash = (0,_util_derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_11__.derivePublicKeyHash)(this.cashaddr);\n return this;\n }\n //#endregion Private implementation details\n //#region Signing\n // Convenience wrapper to sign interface\n async sign(message) {\n return await Wallet.signedMessage.sign(message, this.privateKey);\n }\n // Convenience wrapper to verify interface\n async verify(message, sig, publicKey) {\n return await Wallet.signedMessage.verify(message, sig, this.cashaddr, publicKey);\n }\n //#endregion Signing\n //#region Cashtokens\n /**\n * Create new cashtoken, both funglible and/or non-fungible (NFT)\n * Refer to spec https://github.com/bitjson/cashtokens\n * @param {number} genesisRequest.amount amount of *fungible* tokens to create\n * @param {NFTCapability?} genesisRequest.capability capability of new NFT\n * @param {string?} genesisRequest.commitment NFT commitment message\n * @param {string?} genesisRequest.cashaddr cash address to send the created token UTXO to; if undefined will default to your address\n * @param {number?} genesisRequest.value satoshi value to send alongside with tokens; if undefined will default to 1000 satoshi\n * @param {SendRequestType | SendRequestType[]} sendRequests single or an array of extra send requests (OP_RETURN, value transfer, etc.) to include in genesis transaction\n * @param {SendRequestOptionsI} options Options of the send requests\n */\n async tokenGenesis(genesisRequest, sendRequests = [], options) {\n if (!Array.isArray(sendRequests)) {\n sendRequests = [sendRequests];\n }\n let utxos;\n if (options && options.utxoIds) {\n utxos = await (0,_util_checkUtxos_js__WEBPACK_IMPORTED_MODULE_28__.checkUtxos)(options.utxoIds.map((utxoId) => typeof utxoId === \"string\" ? (0,_model_js__WEBPACK_IMPORTED_MODULE_18__.fromUtxoId)(utxoId) : utxoId), this);\n }\n else {\n utxos = await this.getAddressUtxos(this.cashaddr);\n }\n const genesisInputs = utxos.filter((val) => val.vout === 0 && !val.token);\n if (genesisInputs.length === 0) {\n throw new Error(\"No suitable inputs with vout=0 available for new token genesis\");\n }\n const genesisSendRequest = new _model_js__WEBPACK_IMPORTED_MODULE_18__.TokenSendRequest({\n cashaddr: genesisRequest.cashaddr || this.tokenaddr,\n amount: genesisRequest.amount,\n value: genesisRequest.value || 1000,\n capability: genesisRequest.capability,\n commitment: genesisRequest.commitment,\n tokenId: genesisInputs[0].txid,\n });\n return this.send([genesisSendRequest, ...sendRequests], {\n ...options,\n utxoIds: utxos,\n ensureUtxos: [genesisInputs[0]],\n checkTokenQuantities: false,\n queryBalance: false,\n tokenOperation: \"genesis\",\n });\n }\n /**\n * Mint new NFT cashtokens using an existing minting token\n * Refer to spec https://github.com/bitjson/cashtokens\n * @param {string} tokenId tokenId of an NFT to mint\n * @param {TokenMintRequest | TokenMintRequest[]} mintRequests mint requests with new token properties and recipients\n * @param {NFTCapability?} mintRequest.capability capability of new NFT\n * @param {string?} mintRequest.commitment NFT commitment message\n * @param {string?} mintRequest.cashaddr cash address to send the created token UTXO to; if undefined will default to your address\n * @param {number?} mintRequest.value satoshi value to send alongside with tokens; if undefined will default to 1000 satoshi\n * @param {boolean?} deductTokenAmount if minting token contains fungible amount, deduct from it by amount of minted tokens\n * @param {SendRequestOptionsI} options Options of the send requests\n */\n async tokenMint(tokenId, mintRequests, deductTokenAmount = false, options) {\n if (tokenId?.length !== 64) {\n throw Error(`Invalid tokenId supplied: ${tokenId}`);\n }\n if (!Array.isArray(mintRequests)) {\n mintRequests = [mintRequests];\n }\n const utxos = await this.getAddressUtxos(this.cashaddr);\n const nftUtxos = utxos.filter((val) => val.token?.tokenId === tokenId &&\n val.token?.capability === _interface_js__WEBPACK_IMPORTED_MODULE_7__.NFTCapability.minting);\n if (!nftUtxos.length) {\n throw new Error(\"You do not have any token UTXOs with minting capability for specified tokenId\");\n }\n const newAmount = deductTokenAmount && nftUtxos[0].token.amount > 0\n ? nftUtxos[0].token.amount - BigInt(mintRequests.length)\n : nftUtxos[0].token.amount;\n const safeNewAmount = newAmount < 0n ? 0n : newAmount;\n const mintingInput = new _model_js__WEBPACK_IMPORTED_MODULE_18__.TokenSendRequest({\n cashaddr: this.tokenaddr,\n tokenId: tokenId,\n capability: nftUtxos[0].token.capability,\n commitment: nftUtxos[0].token.commitment,\n amount: safeNewAmount,\n value: nftUtxos[0].satoshis,\n });\n return this.send([\n mintingInput,\n ...mintRequests.map((val) => new _model_js__WEBPACK_IMPORTED_MODULE_18__.TokenSendRequest({\n cashaddr: val.cashaddr || this.tokenaddr,\n amount: 0,\n tokenId: tokenId,\n value: val.value,\n capability: val.capability,\n commitment: val.commitment,\n })),\n ], {\n ...options,\n ensureUtxos: [nftUtxos[0]],\n checkTokenQuantities: false,\n queryBalance: false,\n tokenOperation: \"mint\",\n });\n }\n /**\n * Perform an explicit token burning by spending a token utxo to an OP_RETURN\n *\n * Behaves differently for fungible and non-fungible tokens:\n * * NFTs are always \"destroyed\"\n * * FTs' amount is reduced by the amount specified, if 0 FT amount is left and no NFT present, the token is \"destroyed\"\n *\n * Refer to spec https://github.com/bitjson/cashtokens\n * @param {string} burnRequest.tokenId tokenId of a token to burn\n * @param {NFTCapability} burnRequest.capability capability of the NFT token to select, optional\n * @param {string?} burnRequest.commitment commitment of the NFT token to select, optional\n * @param {number?} burnRequest.amount amount of fungible tokens to burn, optional\n * @param {string?} burnRequest.cashaddr address to return token and satoshi change to\n * @param {string?} message optional message to include in OP_RETURN\n * @param {SendRequestOptionsI} options Options of the send requests\n */\n async tokenBurn(burnRequest, message, options) {\n if (burnRequest.tokenId?.length !== 64) {\n throw Error(`Invalid tokenId supplied: ${burnRequest.tokenId}`);\n }\n const utxos = await this.getAddressUtxos(this.cashaddr);\n const tokenUtxos = utxos.filter((val) => val.token?.tokenId === burnRequest.tokenId &&\n val.token?.capability === burnRequest.capability &&\n val.token?.commitment === burnRequest.commitment);\n if (!tokenUtxos.length) {\n throw new Error(\"You do not have suitable token UTXOs to perform burn\");\n }\n const totalFungibleAmount = tokenUtxos.reduce((prev, cur) => prev + (cur.token?.amount || 0n), 0n);\n let fungibleBurnAmount = burnRequest.amount && burnRequest.amount > 0 ? burnRequest.amount : 0n;\n fungibleBurnAmount = BigInt(fungibleBurnAmount);\n const hasNFT = burnRequest.capability || burnRequest.commitment;\n let utxoIds = [];\n let changeSendRequests;\n if (hasNFT) {\n // does not have FT tokens, let us destroy the token completely\n if (totalFungibleAmount === 0n) {\n changeSendRequests = [];\n utxoIds.push(tokenUtxos[0]);\n }\n else {\n // add utxos to spend from\n let available = 0n;\n for (const token of tokenUtxos.filter((val) => val.token?.amount)) {\n utxoIds.push(token);\n available += token.token?.amount;\n if (available >= fungibleBurnAmount) {\n break;\n }\n }\n // if there are FT, reduce their amount\n const newAmount = totalFungibleAmount - fungibleBurnAmount;\n const safeNewAmount = newAmount < 0n ? 0n : newAmount;\n changeSendRequests = [\n new _model_js__WEBPACK_IMPORTED_MODULE_18__.TokenSendRequest({\n cashaddr: burnRequest.cashaddr || this.tokenaddr,\n tokenId: burnRequest.tokenId,\n capability: burnRequest.capability,\n commitment: burnRequest.commitment,\n amount: safeNewAmount,\n value: tokenUtxos[0].satoshis,\n }),\n ];\n }\n }\n else {\n // if we are burning last fungible tokens, let us destroy the token completely\n if (totalFungibleAmount === fungibleBurnAmount) {\n changeSendRequests = [];\n utxoIds.push(tokenUtxos[0]);\n }\n else {\n // add utxos to spend from\n let available = 0n;\n for (const token of tokenUtxos.filter((val) => val.token?.amount)) {\n utxoIds.push(token);\n available += token.token?.amount;\n if (available >= fungibleBurnAmount) {\n break;\n }\n }\n // reduce the FT amount\n const newAmount = totalFungibleAmount - fungibleBurnAmount;\n const safeNewAmount = newAmount < 0n ? 0n : newAmount;\n changeSendRequests = [\n new _model_js__WEBPACK_IMPORTED_MODULE_18__.TokenSendRequest({\n cashaddr: burnRequest.cashaddr || this.tokenaddr,\n tokenId: burnRequest.tokenId,\n amount: safeNewAmount,\n value: tokenUtxos[0].satoshis,\n }),\n ];\n }\n }\n const opReturn = _model_js__WEBPACK_IMPORTED_MODULE_18__.OpReturnData.fromString(message || \"\");\n return this.send([opReturn, ...changeSendRequests], {\n ...options,\n checkTokenQuantities: false,\n queryBalance: false,\n ensureUtxos: utxoIds.length > 0 ? utxoIds : undefined,\n tokenOperation: \"burn\",\n });\n }\n /**\n * getTokenUtxos Get unspent token outputs for the wallet\n * will return utxos only for the specified token if `tokenId` provided\n * @param {string?} tokenId tokenId (category) to filter utxos by, if not set will return utxos from all tokens\n * @returns {UtxoI[]} token utxos\n */\n async getTokenUtxos(tokenId) {\n const utxos = await this.getAddressUtxos(this.address);\n return utxos.filter((val) => tokenId ? val.token?.tokenId === tokenId : val.token);\n }\n /**\n * getTokenBalance Gets fungible token balance\n * for NFT token balance see @ref getNftTokenBalance\n * @param {string} tokenId tokenId to get balance for\n * @returns {bigint} fungible token balance\n */\n async getTokenBalance(tokenId) {\n const utxos = (await this.getTokenUtxos(tokenId)).filter((val) => val.token?.amount);\n return (0,_util_sumUtxoValue_js__WEBPACK_IMPORTED_MODULE_25__.sumTokenAmounts)(utxos, tokenId);\n }\n /**\n * getNftTokenBalance Gets non-fungible token (NFT) balance for a particular tokenId\n * disregards fungible token balances\n * for fungible token balance see @ref getTokenBalance\n * @param {string} tokenId tokenId to get balance for\n * @returns {number} non-fungible token balance\n */\n async getNftTokenBalance(tokenId) {\n const utxos = (await this.getTokenUtxos(tokenId)).filter((val) => val.token?.commitment !== undefined);\n return utxos.length;\n }\n /**\n * getAllTokenBalances Gets all fungible token balances in this wallet\n * @returns {Object} a map [tokenId => balance] for all tokens in this wallet\n */\n async getAllTokenBalances() {\n const result = {};\n const utxos = (await this.getTokenUtxos()).filter((val) => val.token?.amount);\n for (const utxo of utxos) {\n if (!result[utxo.token.tokenId]) {\n result[utxo.token.tokenId] = 0n;\n }\n result[utxo.token.tokenId] += utxo.token.amount;\n }\n return result;\n }\n /**\n * getAllNftTokenBalances Gets all non-fungible token (NFT) balances in this wallet\n * @returns {Object} a map [tokenId => balance] for all NFTs in this wallet\n */\n async getAllNftTokenBalances() {\n const result = {};\n const utxos = (await this.getTokenUtxos()).filter((val) => val.token?.commitment !== undefined);\n for (const utxo of utxos) {\n if (!result[utxo.token.tokenId]) {\n result[utxo.token.tokenId] = 0;\n }\n result[utxo.token.tokenId] += 1;\n }\n return result;\n }\n}\nWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_19__.CashAddressNetworkPrefix.mainnet;\nWallet.signedMessage = new _message_index_js__WEBPACK_IMPORTED_MODULE_34__.SignedMessage();\n/**\n * Class to manage a testnet wallet.\n */\nclass TestNetWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_3__.NetworkType.Testnet);\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_6__.TestNetUtil;\n }\n}\nTestNetWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_19__.CashAddressNetworkPrefix.testnet;\nTestNetWallet.faucetServer = \"https://rest-unstable.mainnet.cash\";\n/**\n * Class to manage a regtest wallet.\n */\nclass RegTestWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_3__.NetworkType.Regtest);\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_6__.RegTestUtil;\n }\n}\nRegTestWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_19__.CashAddressNetworkPrefix.regtest;\n/**\n * Class to manage a bitcoin cash wif wallet.\n */\nclass WifWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_3__.NetworkType.Mainnet, _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Wif);\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_6__.WifUtil;\n }\n}\nWifWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_19__.CashAddressNetworkPrefix.mainnet;\nWifWallet.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Wif;\n/**\n * Class to manage a testnet wif wallet.\n */\nclass TestNetWifWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_3__.NetworkType.Testnet, _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Wif);\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_6__.TestNetWifUtil;\n }\n}\nTestNetWifWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_19__.CashAddressNetworkPrefix.testnet;\nTestNetWifWallet.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Wif;\n/**\n * Class to manage a regtest wif wallet.\n */\nclass RegTestWifWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_3__.NetworkType.Regtest, _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Wif);\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_6__.RegTestWifUtil;\n }\n}\nRegTestWifWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_19__.CashAddressNetworkPrefix.regtest;\nRegTestWifWallet.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Wif;\n/**\n * Class to manage a bitcoin cash watch wallet.\n */\nclass WatchWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_3__.NetworkType.Mainnet, _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Watch);\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_6__.WatchUtil;\n }\n}\nWatchWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_19__.CashAddressNetworkPrefix.mainnet;\nWatchWallet.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Watch;\n/**\n * Class to manage a testnet watch wallet.\n */\nclass TestNetWatchWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_3__.NetworkType.Testnet, _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Watch);\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_6__.TestNetWatchUtil;\n }\n}\nTestNetWatchWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_19__.CashAddressNetworkPrefix.testnet;\nTestNetWatchWallet.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Watch;\n/**\n * Class to manage a regtest watch wallet.\n */\nclass RegTestWatchWallet extends Wallet {\n constructor(name = \"\") {\n super(name, _enum_js__WEBPACK_IMPORTED_MODULE_3__.NetworkType.Regtest, _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Watch);\n }\n // interface to static util functions. see Util.ts\n static get util() {\n return _Util_js__WEBPACK_IMPORTED_MODULE_6__.RegTestWatchUtil;\n }\n}\nRegTestWatchWallet.networkPrefix = _bitauth_libauth__WEBPACK_IMPORTED_MODULE_19__.CashAddressNetworkPrefix.regtest;\nRegTestWatchWallet.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Watch;\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/wallet/Wif.ts?");
|
|
1138
1138
|
|
|
1139
1139
|
/***/ }),
|
|
1140
1140
|
|
|
@@ -1164,7 +1164,7 @@ eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harm
|
|
|
1164
1164
|
\*****************************/
|
|
1165
1165
|
/***/ ((module, __webpack_exports__, __webpack_require__) => {
|
|
1166
1166
|
|
|
1167
|
-
eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"OpReturnData\": () => (/* binding */ OpReturnData),\n/* harmony export */ \"SendRequest\": () => (/* binding */ SendRequest),\n/* harmony export */ \"SendResponse\": () => (/* binding */ SendResponse),\n/* harmony export */ \"TokenBurnRequest\": () => (/* binding */ TokenBurnRequest),\n/* harmony export */ \"TokenGenesisRequest\": () => (/* binding */ TokenGenesisRequest),\n/* harmony export */ \"TokenMintRequest\": () => (/* binding */ TokenMintRequest),\n/* harmony export */ \"TokenSendRequest\": () => (/* binding */ TokenSendRequest),\n/* harmony export */ \"XPubKey\": () => (/* binding */ XPubKey),\n/* harmony export */ \"fromUtxoId\": () => (/* binding */ fromUtxoId),\n/* harmony export */ \"toUtxoId\": () => (/* binding */ toUtxoId)\n/* harmony export */ });\n/* harmony import */ var _util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../util/balanceObjectFromSatoshi.js */ \"./src/util/balanceObjectFromSatoshi.ts\");\n/* harmony import */ var _util_sanitizeUnit_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../util/sanitizeUnit.js */ \"./src/util/sanitizeUnit.ts\");\n/* harmony import */ var _constant_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../constant.js */ \"./src/constant.ts\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/utf8.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/number.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/hex.js\");\n/* harmony import */ var _config_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../config.js */ \"./src/config.ts\");\n/* harmony import */ var _util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/deriveCashaddr.js */ \"./src/util/deriveCashaddr.ts\");\n/* provided dependency */ var Buffer = __webpack_require__(/*! buffer */ \"../../node_modules/buffer/index.js\")[\"Buffer\"];\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_1__, _util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_6__]);\n([_util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_1__, _util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_6__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\n\n\n\n\nclass SendRequest {\n constructor({ cashaddr, value, unit, }) {\n this.cashaddr = cashaddr;\n this.value = value;\n this.unit = (0,_util_sanitizeUnit_js__WEBPACK_IMPORTED_MODULE_0__.sanitizeUnit)(unit);\n }\n}\nclass TokenGenesisRequest {\n constructor({ amount, capability, commitment, cashaddr, value, }) {\n this.amount = amount;\n this.capability = capability;\n this.commitment = commitment;\n this.cashaddr = cashaddr;\n this.value = value;\n }\n}\nclass TokenBurnRequest {\n constructor({ tokenId, capability, commitment, amount, cashaddr, }) {\n this.tokenId = tokenId;\n this.capability = capability;\n this.commitment = commitment;\n this.amount = amount;\n this.cashaddr = cashaddr;\n }\n}\nclass TokenSendRequest {\n constructor({ cashaddr, value, amount, tokenId, capability, commitment, }) {\n (0,_util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_1__.checkTokenaddr)(cashaddr, _config_js__WEBPACK_IMPORTED_MODULE_2__.Config.EnforceCashTokenReceiptAddresses);\n this.cashaddr = cashaddr;\n this.value = value;\n this.amount = amount || 0;\n this.tokenId = tokenId;\n this.capability = capability;\n this.commitment = commitment;\n }\n}\nclass TokenMintRequest {\n constructor({ capability, commitment, cashaddr, value, }) {\n this.capability = capability;\n this.commitment = commitment;\n this.cashaddr = cashaddr;\n this.value = value;\n }\n}\nclass OpReturnData {\n constructor(buffer) {\n this.buffer = Buffer.from(buffer);\n }\n /**\n * from - Construct OP_RETURN data from arbitrary data type\n *\n * @param string UTF-8 encoded string message to be converted to OP_RETURN data\n *\n * @returns class instance\n */\n static from(data) {\n return this.fromArray([data]);\n }\n /**\n * fromString - Accept data as a simple UTF-8 string message and append an OP_RETURN and PUSH_DATA1 opcodes to it\n *\n * @param string UTF-8 encoded string message to be converted to OP_RETURN data\n *\n * @returns class instance\n */\n static fromString(string) {\n return this.fromArray([string]);\n }\n /**\n * buffer - Accept OP_RETURN data as a binary buffer.\n * If buffer lacks the OP_RETURN and OP_PUSHDATA opcodes, they will be prepended.\n *\n * @param buffer Data buffer to be assigned to the OP_RETURN outpit\n *\n * @returns class instance\n */\n static fromBuffer(buffer) {\n if (buffer[0] !== 0x6a) {\n return this.fromArray([buffer]);\n }\n return new this(buffer);\n }\n /**\n * buffer - Accept OP_RETURN data as a binary buffer.\n * If buffer lacks the OP_RETURN and OP_PUSHDATA opcodes, they will be prepended.\n *\n * @param buffer Data buffer to be assigned to the OP_RETURN outpit\n *\n * @returns class instance\n */\n static fromUint8Array(uint8Array) {\n if (uint8Array[0] !== 0x6a) {\n return this.fromArray([uint8Array]);\n }\n return new this(Buffer.from(uint8Array));\n }\n /**\n * fromArray - Accept array of data\n *\n * @param array Array of Buffer or UTF-8 encoded string messages to be converted to OP_RETURN data\n *\n * @returns class instance\n */\n static fromArray(array) {\n let data = Buffer.from([0x6a]); // OP_RETURN\n for (const element of array) {\n let length;\n let elementData;\n let lengthData;\n if (typeof element === \"string\") {\n elementData = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.utf8ToBin)(element);\n length = elementData.length;\n }\n else if (element instanceof Buffer) {\n elementData = element;\n length = elementData.length;\n }\n else if (element instanceof Uint8Array) {\n elementData = Buffer.from(element);\n length = elementData.length;\n }\n else {\n throw new Error(\"Wrong data array element\");\n }\n if (length < 76) {\n // OP_PUSHDATA_1\n lengthData = [length];\n }\n else if (length < 223) {\n // default max `-datacarriersize`\n lengthData = [0x4c, length];\n }\n else {\n throw new Error(\"OP_RETURN data can not exceed 220 bytes in size\");\n }\n data = Buffer.from([...data, ...lengthData, ...elementData]);\n }\n if (data.length > 220) {\n throw new Error(\"OP_RETURN data can not exceed 220 bytes in size\");\n }\n return new this(data);\n }\n /**\n * parseBinary - parse OP_RETURN data and return pushed chunks of binary data\n *\n * @param opReturn Raw OP_RETURN data\n *\n * @returns array of binary data chunks pushed\n */\n static parseBinary(opReturn) {\n const chunks = [];\n let position = 1;\n // handle direct push, OP_PUSHDATA1, OP_PUSHDATA2;\n // OP_PUSHDATA4 is not supported in OP_RETURNs by consensus\n while (opReturn[position]) {\n let length = 0;\n if (opReturn[position] === 0x4c) {\n length = opReturn[position + 1];\n position += 2;\n }\n else if (opReturn[position] === 0x4d) {\n length = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__.binToNumberUint16LE)(opReturn.slice(position + 1, position + 3));\n position += 3;\n }\n else {\n length = opReturn[position];\n position += 1;\n }\n chunks.push(opReturn.slice(position, position + length));\n position += length;\n }\n return chunks;\n }\n /**\n * parse - parse OP_RETURN hex data and return pushed chunks of binary data, converted to utf8 strings\n *\n * @param opReturn Raw OP_RETURN hex data\n *\n * @returns array of binary data chunks pushed, converted to utf8 strings\n */\n static parse(opReturnHex) {\n return this.parseBinary((0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_5__.hexToBin)(opReturnHex)).map((val) => (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.binToUtf8)(val));\n }\n}\nclass SendResponse {\n constructor({ txId, balance, explorerUrl, }) {\n this.txId = txId;\n this.balance = new _util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_6__.BalanceResponse(balance);\n this.explorerUrl = explorerUrl;\n }\n}\nclass XPubKey {\n constructor({ path, xPubKey }) {\n this.path = path;\n this.xPubKey = xPubKey;\n }\n async ready() {\n await this.xPubKey;\n return this.asObject();\n }\n asObject() {\n return {\n path: this.path,\n xPubKey: this.xPubKey,\n };\n }\n}\nconst fromUtxoId = (utxoId) => {\n const [txid, vout, satoshis, tokenId, amount, capability, commitment] = utxoId.split(_constant_js__WEBPACK_IMPORTED_MODULE_7__.DELIMITER);\n return {\n satoshis: satoshis ? parseInt(satoshis) : 0,\n vout: parseInt(vout),\n txid,\n token: tokenId\n ? {\n tokenId,\n amount: parseInt(amount),\n capability: capability || undefined,\n commitment: commitment || undefined,\n }\n : undefined,\n };\n};\nconst toUtxoId = (utxo) => {\n return [\n utxo.txid,\n utxo.vout,\n utxo.satoshis,\n utxo.token?.tokenId,\n utxo.token?.amount,\n utxo.token?.capability,\n utxo.token?.commitment,\n ]\n .join(_constant_js__WEBPACK_IMPORTED_MODULE_7__.DELIMITER)\n .replace(/:+$/, \"\");\n};\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/wallet/model.ts?");
|
|
1167
|
+
eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"OpReturnData\": () => (/* binding */ OpReturnData),\n/* harmony export */ \"SendRequest\": () => (/* binding */ SendRequest),\n/* harmony export */ \"SendResponse\": () => (/* binding */ SendResponse),\n/* harmony export */ \"TokenBurnRequest\": () => (/* binding */ TokenBurnRequest),\n/* harmony export */ \"TokenGenesisRequest\": () => (/* binding */ TokenGenesisRequest),\n/* harmony export */ \"TokenMintRequest\": () => (/* binding */ TokenMintRequest),\n/* harmony export */ \"TokenSendRequest\": () => (/* binding */ TokenSendRequest),\n/* harmony export */ \"XPubKey\": () => (/* binding */ XPubKey),\n/* harmony export */ \"fromUtxoId\": () => (/* binding */ fromUtxoId),\n/* harmony export */ \"toUtxoId\": () => (/* binding */ toUtxoId)\n/* harmony export */ });\n/* harmony import */ var _util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../util/balanceObjectFromSatoshi.js */ \"./src/util/balanceObjectFromSatoshi.ts\");\n/* harmony import */ var _util_sanitizeUnit_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../util/sanitizeUnit.js */ \"./src/util/sanitizeUnit.ts\");\n/* harmony import */ var _constant_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../constant.js */ \"./src/constant.ts\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/utf8.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/number.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/hex.js\");\n/* harmony import */ var _config_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../config.js */ \"./src/config.ts\");\n/* harmony import */ var _util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/deriveCashaddr.js */ \"./src/util/deriveCashaddr.ts\");\n/* provided dependency */ var Buffer = __webpack_require__(/*! buffer */ \"../../node_modules/buffer/index.js\")[\"Buffer\"];\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_1__, _util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_6__]);\n([_util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_1__, _util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_6__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\n\n\n\n\nclass SendRequest {\n constructor({ cashaddr, value, unit, }) {\n this.cashaddr = cashaddr;\n this.value = value;\n this.unit = (0,_util_sanitizeUnit_js__WEBPACK_IMPORTED_MODULE_0__.sanitizeUnit)(unit);\n }\n}\nclass TokenGenesisRequest {\n constructor({ amount, capability, commitment, cashaddr, value, }) {\n this.amount = amount;\n this.capability = capability;\n this.commitment = commitment;\n this.cashaddr = cashaddr;\n this.value = value;\n }\n}\nclass TokenBurnRequest {\n constructor({ tokenId, capability, commitment, amount, cashaddr, }) {\n this.tokenId = tokenId;\n this.capability = capability;\n this.commitment = commitment;\n this.amount = amount ? BigInt(amount) : 0n;\n this.cashaddr = cashaddr;\n }\n}\nclass TokenSendRequest {\n constructor({ cashaddr, value, amount, tokenId, capability, commitment, }) {\n (0,_util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_1__.checkTokenaddr)(cashaddr, _config_js__WEBPACK_IMPORTED_MODULE_2__.Config.EnforceCashTokenReceiptAddresses);\n this.cashaddr = cashaddr;\n this.value = value;\n this.amount = amount ? BigInt(amount) : 0n;\n this.tokenId = tokenId;\n this.capability = capability;\n this.commitment = commitment;\n }\n}\nclass TokenMintRequest {\n constructor({ capability, commitment, cashaddr, value, }) {\n this.capability = capability;\n this.commitment = commitment;\n this.cashaddr = cashaddr;\n this.value = value;\n }\n}\nclass OpReturnData {\n constructor(buffer) {\n this.buffer = Buffer.from(buffer);\n }\n /**\n * from - Construct OP_RETURN data from arbitrary data type\n *\n * @param string UTF-8 encoded string message to be converted to OP_RETURN data\n *\n * @returns class instance\n */\n static from(data) {\n return this.fromArray([data]);\n }\n /**\n * fromString - Accept data as a simple UTF-8 string message and append an OP_RETURN and PUSH_DATA1 opcodes to it\n *\n * @param string UTF-8 encoded string message to be converted to OP_RETURN data\n *\n * @returns class instance\n */\n static fromString(string) {\n return this.fromArray([string]);\n }\n /**\n * buffer - Accept OP_RETURN data as a binary buffer.\n * If buffer lacks the OP_RETURN and OP_PUSHDATA opcodes, they will be prepended.\n *\n * @param buffer Data buffer to be assigned to the OP_RETURN outpit\n *\n * @returns class instance\n */\n static fromBuffer(buffer) {\n if (buffer[0] !== 0x6a) {\n return this.fromArray([buffer]);\n }\n return new this(buffer);\n }\n /**\n * buffer - Accept OP_RETURN data as a binary buffer.\n * If buffer lacks the OP_RETURN and OP_PUSHDATA opcodes, they will be prepended.\n *\n * @param buffer Data buffer to be assigned to the OP_RETURN outpit\n *\n * @returns class instance\n */\n static fromUint8Array(uint8Array) {\n if (uint8Array[0] !== 0x6a) {\n return this.fromArray([uint8Array]);\n }\n return new this(Buffer.from(uint8Array));\n }\n /**\n * fromArray - Accept array of data\n *\n * @param array Array of Buffer or UTF-8 encoded string messages to be converted to OP_RETURN data\n *\n * @returns class instance\n */\n static fromArray(array) {\n let data = Buffer.from([0x6a]); // OP_RETURN\n for (const element of array) {\n let length;\n let elementData;\n let lengthData;\n if (typeof element === \"string\") {\n elementData = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.utf8ToBin)(element);\n length = elementData.length;\n }\n else if (element instanceof Buffer) {\n elementData = element;\n length = elementData.length;\n }\n else if (element instanceof Uint8Array) {\n elementData = Buffer.from(element);\n length = elementData.length;\n }\n else {\n throw new Error(\"Wrong data array element\");\n }\n if (length < 76) {\n // OP_PUSHDATA_1\n lengthData = [length];\n }\n else if (length < 223) {\n // default max `-datacarriersize`\n lengthData = [0x4c, length];\n }\n else {\n throw new Error(\"OP_RETURN data can not exceed 220 bytes in size\");\n }\n data = Buffer.from([...data, ...lengthData, ...elementData]);\n }\n if (data.length > 220) {\n throw new Error(\"OP_RETURN data can not exceed 220 bytes in size\");\n }\n return new this(data);\n }\n /**\n * parseBinary - parse OP_RETURN data and return pushed chunks of binary data\n *\n * @param opReturn Raw OP_RETURN data\n *\n * @returns array of binary data chunks pushed\n */\n static parseBinary(opReturn) {\n const chunks = [];\n let position = 1;\n // handle direct push, OP_PUSHDATA1, OP_PUSHDATA2;\n // OP_PUSHDATA4 is not supported in OP_RETURNs by consensus\n while (opReturn[position]) {\n let length = 0;\n if (opReturn[position] === 0x4c) {\n length = opReturn[position + 1];\n position += 2;\n }\n else if (opReturn[position] === 0x4d) {\n length = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__.binToNumberUint16LE)(opReturn.slice(position + 1, position + 3));\n position += 3;\n }\n else {\n length = opReturn[position];\n position += 1;\n }\n chunks.push(opReturn.slice(position, position + length));\n position += length;\n }\n return chunks;\n }\n /**\n * parse - parse OP_RETURN hex data and return pushed chunks of binary data, converted to utf8 strings\n *\n * @param opReturn Raw OP_RETURN hex data\n *\n * @returns array of binary data chunks pushed, converted to utf8 strings\n */\n static parse(opReturnHex) {\n return this.parseBinary((0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_5__.hexToBin)(opReturnHex)).map((val) => (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.binToUtf8)(val));\n }\n}\nclass SendResponse {\n constructor({ txId, balance, explorerUrl, }) {\n this.txId = txId;\n this.balance = new _util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_6__.BalanceResponse(balance);\n this.explorerUrl = explorerUrl;\n }\n}\nclass XPubKey {\n constructor({ path, xPubKey }) {\n this.path = path;\n this.xPubKey = xPubKey;\n }\n async ready() {\n await this.xPubKey;\n return this.asObject();\n }\n asObject() {\n return {\n path: this.path,\n xPubKey: this.xPubKey,\n };\n }\n}\nconst fromUtxoId = (utxoId) => {\n const [txid, vout, satoshis, tokenId, amount, capability, commitment] = utxoId.split(_constant_js__WEBPACK_IMPORTED_MODULE_7__.DELIMITER);\n return {\n satoshis: satoshis ? parseInt(satoshis) : 0,\n vout: parseInt(vout),\n txid,\n token: tokenId\n ? {\n tokenId,\n amount: BigInt(amount),\n capability: capability || undefined,\n commitment: commitment || undefined,\n }\n : undefined,\n };\n};\nconst toUtxoId = (utxo) => {\n return [\n utxo.txid,\n utxo.vout,\n utxo.satoshis,\n utxo.token?.tokenId,\n utxo.token?.amount,\n utxo.token?.capability,\n utxo.token?.commitment,\n ]\n .join(_constant_js__WEBPACK_IMPORTED_MODULE_7__.DELIMITER)\n .replace(/:+$/, \"\");\n};\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/wallet/model.ts?");
|
|
1168
1168
|
|
|
1169
1169
|
/***/ }),
|
|
1170
1170
|
|