mainnet-js 3.0.0-next.0 → 3.0.0-next.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.html +1 -1
- package/dist/{mainnet-3.0.0-next.0.js → mainnet-3.0.0-next.2.js} +21 -41
- package/dist/module/cache/walletCache.d.ts +10 -4
- package/dist/module/cache/walletCache.d.ts.map +1 -1
- package/dist/module/cache/walletCache.js +12 -13
- package/dist/module/cache/walletCache.js.map +1 -1
- package/dist/module/chain.d.ts +1 -1
- package/dist/module/chain.js +1 -1
- package/dist/module/chain.js.map +1 -1
- package/dist/module/constant.d.ts +1 -1
- package/dist/module/constant.d.ts.map +1 -1
- package/dist/module/constant.js +1 -1
- package/dist/module/constant.js.map +1 -1
- package/dist/module/enum.d.ts +1 -7
- package/dist/module/enum.d.ts.map +1 -1
- package/dist/module/enum.js +0 -6
- package/dist/module/enum.js.map +1 -1
- package/dist/module/history/getHistory.d.ts.map +1 -1
- package/dist/module/history/getHistory.js +17 -47
- package/dist/module/history/getHistory.js.map +1 -1
- package/dist/module/history/interface.d.ts +1 -1
- package/dist/module/history/interface.d.ts.map +1 -1
- package/dist/module/interface.d.ts +6 -5
- package/dist/module/interface.d.ts.map +1 -1
- package/dist/module/interface.js.map +1 -1
- package/dist/module/network/ElectrumNetworkProvider.d.ts.map +1 -1
- package/dist/module/network/ElectrumNetworkProvider.js +2 -4
- package/dist/module/network/ElectrumNetworkProvider.js.map +1 -1
- package/dist/module/network/getRelayFeeCache.js +2 -2
- package/dist/module/network/getRelayFeeCache.js.map +1 -1
- package/dist/module/network/interface.d.ts +2 -2
- package/dist/module/network/interface.d.ts.map +1 -1
- package/dist/module/rate/ExchangeRate.d.ts +2 -1
- package/dist/module/rate/ExchangeRate.d.ts.map +1 -1
- package/dist/module/rate/ExchangeRate.js +4 -1
- package/dist/module/rate/ExchangeRate.js.map +1 -1
- package/dist/module/transaction/Wif.d.ts +9 -9
- package/dist/module/transaction/Wif.d.ts.map +1 -1
- package/dist/module/transaction/Wif.js +35 -35
- package/dist/module/transaction/Wif.js.map +1 -1
- package/dist/module/transaction/allocateFee.d.ts +3 -3
- package/dist/module/transaction/allocateFee.d.ts.map +1 -1
- package/dist/module/transaction/allocateFee.js +5 -6
- package/dist/module/transaction/allocateFee.js.map +1 -1
- package/dist/module/util/amountInSatoshi.d.ts +1 -1
- package/dist/module/util/amountInSatoshi.d.ts.map +1 -1
- package/dist/module/util/amountInSatoshi.js +3 -9
- package/dist/module/util/amountInSatoshi.js.map +1 -1
- package/dist/module/util/asSendRequestObject.d.ts.map +1 -1
- package/dist/module/util/asSendRequestObject.js +10 -7
- package/dist/module/util/asSendRequestObject.js.map +1 -1
- package/dist/module/util/convert.d.ts +3 -0
- package/dist/module/util/convert.d.ts.map +1 -1
- package/dist/module/util/convert.js +12 -0
- package/dist/module/util/convert.js.map +1 -1
- package/dist/module/util/index.d.ts +2 -3
- package/dist/module/util/index.d.ts.map +1 -1
- package/dist/module/util/index.js +2 -3
- package/dist/module/util/index.js.map +1 -1
- package/dist/module/util/satoshiToAmount.d.ts +1 -1
- package/dist/module/util/satoshiToAmount.d.ts.map +1 -1
- package/dist/module/util/satoshiToAmount.js +3 -9
- package/dist/module/util/satoshiToAmount.js.map +1 -1
- package/dist/module/util/sumSendRequestAmounts.d.ts.map +1 -1
- package/dist/module/util/sumSendRequestAmounts.js +3 -4
- package/dist/module/util/sumSendRequestAmounts.js.map +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/Base.d.ts +28 -30
- package/dist/module/wallet/Base.d.ts.map +1 -1
- package/dist/module/wallet/Base.js +82 -119
- package/dist/module/wallet/Base.js.map +1 -1
- package/dist/module/wallet/HDWallet.d.ts +1 -1
- package/dist/module/wallet/Util.js +1 -1
- package/dist/module/wallet/Util.js.map +1 -1
- package/dist/module/wallet/Wif.d.ts +1 -1
- package/dist/module/wallet/interface.d.ts +2 -3
- package/dist/module/wallet/interface.d.ts.map +1 -1
- package/dist/module/wallet/model.d.ts +53 -41
- package/dist/module/wallet/model.d.ts.map +1 -1
- package/dist/module/wallet/model.js +14 -22
- package/dist/module/wallet/model.js.map +1 -1
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/package.json +1 -1
- package/src/cache/walletCache.ts +23 -36
- package/src/chain.ts +1 -1
- package/src/constant.ts +1 -1
- package/src/enum.ts +0 -6
- package/src/history/getHistory.test.ts +20 -34
- package/src/history/getHistory.ts +17 -49
- package/src/history/interface.ts +1 -1
- package/src/interface.ts +6 -5
- package/src/network/Connection.test.ts +3 -3
- package/src/network/ElectrumNetworkProvider.ts +2 -4
- package/src/network/Rpc.test.ts +2 -3
- package/src/network/getRelayFeeCache.ts +2 -2
- package/src/network/interface.ts +2 -2
- package/src/rate/ExchangeRate.test.ts +2 -44
- package/src/rate/ExchangeRate.ts +5 -2
- package/src/transaction/Wif.ts +50 -45
- package/src/transaction/allocateFee.test.ts +110 -131
- package/src/transaction/allocateFee.ts +14 -15
- package/src/util/amountInSatoshi.test.ts +1 -9
- package/src/util/amountInSatoshi.ts +6 -10
- package/src/util/asSendRequestObject.ts +12 -7
- package/src/util/convert.ts +18 -0
- package/src/util/index.ts +2 -7
- package/src/util/satoshiToAmount.test.ts +1 -1
- package/src/util/satoshiToAmount.ts +4 -10
- package/src/util/sumSendRequestAmounts.ts +3 -4
- package/src/util/sumUtxoValue.ts +4 -4
- package/src/wallet/Base.ts +95 -164
- package/src/wallet/Cashtokens.test.headless.js +228 -173
- package/src/wallet/Cashtokens.test.ts +506 -406
- package/src/wallet/HDWallet.test.ts +223 -68
- package/src/wallet/Util.ts +1 -1
- package/src/wallet/Wif.test.ts +108 -133
- package/src/wallet/interface.ts +2 -3
- package/src/wallet/model.test.ts +2 -5
- package/src/wallet/model.ts +64 -71
- package/dist/module/util/balanceObjectFromSatoshi.d.ts +0 -8
- package/dist/module/util/balanceObjectFromSatoshi.d.ts.map +0 -1
- package/dist/module/util/balanceObjectFromSatoshi.js +0 -35
- package/dist/module/util/balanceObjectFromSatoshi.js.map +0 -1
- package/src/util/balanceObjectFromSatoshi.test.ts +0 -58
- package/src/util/balanceObjectFromSatoshi.ts +0 -52
|
@@ -84,7 +84,7 @@ eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harm
|
|
|
84
84
|
\**********************************/
|
|
85
85
|
/***/ ((module, __webpack_exports__, __webpack_require__) => {
|
|
86
86
|
|
|
87
|
-
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 */ \"WalletCache\": () => (/* binding */ WalletCache)\n/* harmony export */ });\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/key/hd-key.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/error.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/crypto/default-crypto-instances.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/crypto/combinations.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/address/cash-address.js\");\n/* harmony import */ var _config_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../config.js */ \"./src/config.ts\");\n/* harmony import */ var _IndexedDbCache_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./IndexedDbCache.js */ \"./src/cache/IndexedDbCache.ts\");\n/* harmony import */ var _MemoryCache_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./MemoryCache.js */ \"./src/cache/MemoryCache.ts\");\n/* harmony import */ var _WebStorageCache_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./WebStorageCache.js */ \"./src/cache/WebStorageCache.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__]);\n([_bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__, _bitauth_libauth__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\nclass WalletCache {\n get storage() {\n if (!_config_js__WEBPACK_IMPORTED_MODULE_0__.Config.UseMemoryCache &&\n !_config_js__WEBPACK_IMPORTED_MODULE_0__.Config.UseLocalStorageCache &&\n !_config_js__WEBPACK_IMPORTED_MODULE_0__.Config.UseIndexedDBCache) {\n this._storage = undefined;\n return this._storage;\n }\n if (_config_js__WEBPACK_IMPORTED_MODULE_0__.Config.UseMemoryCache && !(this._storage instanceof _MemoryCache_js__WEBPACK_IMPORTED_MODULE_1__.MemoryCache)) {\n this._storage = new _MemoryCache_js__WEBPACK_IMPORTED_MODULE_1__.MemoryCache();\n return this._storage;\n }\n if (_config_js__WEBPACK_IMPORTED_MODULE_0__.Config.UseLocalStorageCache &&\n !(this._storage instanceof _WebStorageCache_js__WEBPACK_IMPORTED_MODULE_2__.WebStorageCache)) {\n this._storage = new _WebStorageCache_js__WEBPACK_IMPORTED_MODULE_2__.WebStorageCache();\n return this._storage;\n }\n if (_config_js__WEBPACK_IMPORTED_MODULE_0__.Config.UseIndexedDBCache &&\n !(this._storage instanceof _IndexedDbCache_js__WEBPACK_IMPORTED_MODULE_3__.IndexedDbCache)) {\n this._storage = new _IndexedDbCache_js__WEBPACK_IMPORTED_MODULE_3__.IndexedDbCache();\n return this._storage;\n }\n return this._storage;\n }\n constructor(walletId, hdNode, networkPrefix, writeTimeout = 2000) {\n this.walletId = walletId;\n this.hdNode = hdNode;\n this.networkPrefix = networkPrefix;\n this.writeTimeout = writeTimeout;\n this.walletCache = {};\n this.indexCache = {};\n this.timeouts = [];\n if (!this.hdNode) {\n throw new Error(\"HDNode is undefined\");\n }\n }\n async init() {\n await this.storage?.init();\n const data = await this.storage?.getItem(`walletCache-${this.walletId}`);\n if (data) {\n try {\n const parsed =
|
|
87
|
+
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 */ \"WalletCache\": () => (/* binding */ WalletCache)\n/* harmony export */ });\n/* unused harmony exports stringify, parse */\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/key/hd-key.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/error.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/crypto/default-crypto-instances.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/crypto/combinations.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/address/cash-address.js\");\n/* harmony import */ var _config_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../config.js */ \"./src/config.ts\");\n/* harmony import */ var _IndexedDbCache_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./IndexedDbCache.js */ \"./src/cache/IndexedDbCache.ts\");\n/* harmony import */ var _MemoryCache_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./MemoryCache.js */ \"./src/cache/MemoryCache.ts\");\n/* harmony import */ var _WebStorageCache_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./WebStorageCache.js */ \"./src/cache/WebStorageCache.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__]);\n([_bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__, _bitauth_libauth__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\nconst stringify = (_) => JSON.stringify(_, (_, value) => typeof value === \"bigint\" ? value.toString() + \"n\" : value);\nconst parse = (data) => JSON.parse(data, (_, value) => {\n if (typeof value === \"string\" && /^\\d+n$/.test(value)) {\n return BigInt(value.slice(0, -1));\n }\n return value;\n});\nclass WalletCache {\n get storage() {\n if (!_config_js__WEBPACK_IMPORTED_MODULE_0__.Config.UseMemoryCache &&\n !_config_js__WEBPACK_IMPORTED_MODULE_0__.Config.UseLocalStorageCache &&\n !_config_js__WEBPACK_IMPORTED_MODULE_0__.Config.UseIndexedDBCache) {\n this._storage = undefined;\n return this._storage;\n }\n if (_config_js__WEBPACK_IMPORTED_MODULE_0__.Config.UseMemoryCache && !(this._storage instanceof _MemoryCache_js__WEBPACK_IMPORTED_MODULE_1__.MemoryCache)) {\n this._storage = new _MemoryCache_js__WEBPACK_IMPORTED_MODULE_1__.MemoryCache();\n return this._storage;\n }\n if (_config_js__WEBPACK_IMPORTED_MODULE_0__.Config.UseLocalStorageCache &&\n !(this._storage instanceof _WebStorageCache_js__WEBPACK_IMPORTED_MODULE_2__.WebStorageCache)) {\n this._storage = new _WebStorageCache_js__WEBPACK_IMPORTED_MODULE_2__.WebStorageCache();\n return this._storage;\n }\n if (_config_js__WEBPACK_IMPORTED_MODULE_0__.Config.UseIndexedDBCache &&\n !(this._storage instanceof _IndexedDbCache_js__WEBPACK_IMPORTED_MODULE_3__.IndexedDbCache)) {\n this._storage = new _IndexedDbCache_js__WEBPACK_IMPORTED_MODULE_3__.IndexedDbCache();\n return this._storage;\n }\n return this._storage;\n }\n constructor(walletId, hdNode, networkPrefix, writeTimeout = 2000) {\n this.walletId = walletId;\n this.hdNode = hdNode;\n this.networkPrefix = networkPrefix;\n this.writeTimeout = writeTimeout;\n this.walletCache = {};\n this.indexCache = {};\n this.timeouts = [];\n if (!this.hdNode) {\n throw new Error(\"HDNode is undefined\");\n }\n }\n async init() {\n await this.storage?.init();\n const data = await this.storage?.getItem(`walletCache-${this.walletId}`);\n if (data) {\n try {\n const parsed = parse(data);\n this.walletCache = parsed.walletCache || {};\n this.indexCache = parsed.indexCache || {};\n }\n catch (e) {\n // ignore\n }\n }\n }\n async persist() {\n this.timeouts.map(clearTimeout);\n this.timeouts = [];\n this.storage?.setItem(`walletCache-${this.walletId}`, stringify({\n walletCache: this.walletCache,\n indexCache: this.indexCache,\n }));\n }\n getByIndex(addressIndex, change) {\n const id = `${this.walletId}-${addressIndex}-${change}`;\n if (!this.walletCache[id]) {\n const node = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__.deriveHdPathRelative)(this.hdNode, `${change ? 1 : 0}/${addressIndex}`);\n const privateKey = \"privateKey\" in node ? node.privateKey : undefined;\n const publicKey = \"publicKey\" in node\n ? node.publicKey\n : (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_5__.assertSuccess)(_bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__.secp256k1.derivePublicKeyUncompressed(privateKey));\n const publicKeyCompressed = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_5__.assertSuccess)(_bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__.secp256k1.compressPublicKey(publicKey));\n const publicKeyHash = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__.hash160)(publicKeyCompressed);\n const address = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_8__.encodeCashAddress)({\n throwErrors: true,\n prefix: this.networkPrefix,\n type: _bitauth_libauth__WEBPACK_IMPORTED_MODULE_8__.CashAddressType.p2pkh,\n payload: publicKeyHash,\n }).address;\n const tokenAddress = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_8__.encodeCashAddress)({\n throwErrors: true,\n prefix: this.networkPrefix,\n type: _bitauth_libauth__WEBPACK_IMPORTED_MODULE_8__.CashAddressType.p2pkhWithTokens,\n payload: publicKeyHash,\n }).address;\n this.walletCache[id] = {\n address,\n tokenAddress,\n privateKey: privateKey,\n publicKey,\n publicKeyHash,\n index: addressIndex,\n change,\n status: null,\n utxos: [],\n };\n this.indexCache[address] = {\n index: addressIndex,\n change,\n };\n // batch new data into a single writeout\n this.timeouts.push(setTimeout(() => {\n this.persist().catch(() => { });\n }, this.writeTimeout));\n }\n return this.walletCache[id];\n }\n get(address) {\n const { index, change } = this.indexCache[address] || {};\n if (index === undefined || change === undefined) {\n return undefined;\n }\n return this.getByIndex(index, change);\n }\n setStatusAndUtxos(address, status, utxos) {\n const entry = this.get(address);\n if (!entry) {\n return;\n }\n const { index, change } = this.indexCache[address] || {};\n if (index === undefined || change === undefined) {\n return;\n }\n const key = `${this.walletId}-${index}-${change}`;\n this.walletCache[key].status = status;\n this.walletCache[key].utxos = utxos;\n // batch new data into a single writeout\n this.timeouts.push(setTimeout(() => {\n this.persist().catch(() => { });\n }, this.writeTimeout));\n }\n}\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/cache/walletCache.ts?");
|
|
88
88
|
|
|
89
89
|
/***/ }),
|
|
90
90
|
|
|
@@ -94,7 +94,7 @@ eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__
|
|
|
94
94
|
\**********************/
|
|
95
95
|
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
|
|
96
96
|
|
|
97
|
-
eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"bchParam\": () => (/* binding */ bchParam)\n/* harmony export */ });\nconst bchParam = {\n subUnits:
|
|
97
|
+
eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"bchParam\": () => (/* binding */ bchParam)\n/* harmony export */ });\nconst bchParam = {\n subUnits: 100000000n,\n};\n\n\n//# sourceURL=webpack://mainnet-js/./src/chain.ts?");
|
|
98
98
|
|
|
99
99
|
/***/ }),
|
|
100
100
|
|
|
@@ -114,7 +114,7 @@ eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harm
|
|
|
114
114
|
\*************************/
|
|
115
115
|
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
|
|
116
116
|
|
|
117
|
-
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"DELIMITER\": () => (/* binding */ DELIMITER),\n/* harmony export */ \"DERIVATION_PATHS\": () => (/* binding */ DERIVATION_PATHS),\n/* harmony export */ \"DUST_UTXO_THRESHOLD\": () => (/* binding */ DUST_UTXO_THRESHOLD),\n/* harmony export */ \"EXCHANGE_RATE_TTL\": () => (/* binding */ EXCHANGE_RATE_TTL),\n/* harmony export */ \"MEMPOOL_CHAIN_LIMIT\": () => (/* binding */ MEMPOOL_CHAIN_LIMIT)\n/* harmony export */ });\nconst DELIMITER = \":\";\n// Min amount utxo can be to be accepted by the network\nconst DUST_UTXO_THRESHOLD =
|
|
117
|
+
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"DELIMITER\": () => (/* binding */ DELIMITER),\n/* harmony export */ \"DERIVATION_PATHS\": () => (/* binding */ DERIVATION_PATHS),\n/* harmony export */ \"DUST_UTXO_THRESHOLD\": () => (/* binding */ DUST_UTXO_THRESHOLD),\n/* harmony export */ \"EXCHANGE_RATE_TTL\": () => (/* binding */ EXCHANGE_RATE_TTL),\n/* harmony export */ \"MEMPOOL_CHAIN_LIMIT\": () => (/* binding */ MEMPOOL_CHAIN_LIMIT)\n/* harmony export */ });\nconst DELIMITER = \":\";\n// Min amount utxo can be to be accepted by the network\nconst DUST_UTXO_THRESHOLD = 546n;\n// Current chained tx limit\nconst MEMPOOL_CHAIN_LIMIT = 50;\n// time in milliseconds to cache the usd exchange rate\nconst EXCHANGE_RATE_TTL = 250000;\n// list of common derivation paths\n// a la: https://github.com/Electron-Cash/Electron-Cash/blob/1de24c509992cfebc22217a2a77c862c2b02bc54/electroncash_gui/qt/installwizard.py#L624\nconst DERIVATION_PATHS = [\n \"m/0\",\n \"m/0'\",\n \"m/0'/0\",\n \"m/0'/0'\",\n \"m/0'/0'/0'\",\n \"m/44'/0'/0'\",\n \"m/44'/0'/0'/0\",\n \"m/44'/145'/0'\",\n \"m/44'/145'/0'/0\",\n \"m/44'/245'/0\",\n \"m/44'/245'/0'\",\n \"m/44'/245'/0'/0\",\n];\n\n\n//# sourceURL=webpack://mainnet-js/./src/constant.ts?");
|
|
118
118
|
|
|
119
119
|
/***/ }),
|
|
120
120
|
|
|
@@ -154,7 +154,7 @@ eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harm
|
|
|
154
154
|
\*********************/
|
|
155
155
|
/***/ ((module, __webpack_exports__, __webpack_require__) => {
|
|
156
156
|
|
|
157
|
-
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 */ \"NetworkType\": () => (/* binding */ NetworkType),\n/* harmony export */ \"UnitEnum\": () => (/* binding */ UnitEnum),\n/* harmony export */ \"networkPrefixMap\": () => (/* binding */ networkPrefixMap),\n/* harmony export */ \"prefixFromNetworkMap\": () => (/* binding */ prefixFromNetworkMap)\n/* harmony export */ });\n/* unused harmony export NetworkEnum */\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/address/cash-address.js\");\n\nvar NetworkType;\n(function (NetworkType) {\n NetworkType[\"Mainnet\"] = \"mainnet\";\n NetworkType[\"Testnet\"] = \"testnet\";\n NetworkType[\"Regtest\"] = \"regtest\";\n})(NetworkType || (NetworkType = {}));\nvar NetworkEnum;\n(function (NetworkEnum) {\n NetworkEnum[NetworkEnum[\"Mainnet\"] = \"mainnet\"] = \"Mainnet\";\n NetworkEnum[NetworkEnum[\"Testnet\"] = \"testnet\"] = \"Testnet\";\n NetworkEnum[NetworkEnum[\"Regtest\"] = \"regtest\"] = \"Regtest\";\n
|
|
157
|
+
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 */ \"NetworkType\": () => (/* binding */ NetworkType),\n/* harmony export */ \"UnitEnum\": () => (/* binding */ UnitEnum),\n/* harmony export */ \"networkPrefixMap\": () => (/* binding */ networkPrefixMap),\n/* harmony export */ \"prefixFromNetworkMap\": () => (/* binding */ prefixFromNetworkMap)\n/* harmony export */ });\n/* unused harmony export NetworkEnum */\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/address/cash-address.js\");\n\nvar NetworkType;\n(function (NetworkType) {\n NetworkType[\"Mainnet\"] = \"mainnet\";\n NetworkType[\"Testnet\"] = \"testnet\";\n NetworkType[\"Regtest\"] = \"regtest\";\n})(NetworkType || (NetworkType = {}));\nvar NetworkEnum;\n(function (NetworkEnum) {\n NetworkEnum[NetworkEnum[\"Mainnet\"] = \"mainnet\"] = \"Mainnet\";\n NetworkEnum[NetworkEnum[\"Testnet\"] = \"testnet\"] = \"Testnet\";\n NetworkEnum[NetworkEnum[\"Regtest\"] = \"regtest\"] = \"Regtest\";\n})(NetworkEnum || (NetworkEnum = {}));\nconst networkPrefixMap = {\n bitcoincash: \"mainnet\",\n bchtest: \"testnet\",\n bchreg: \"regtest\",\n};\nconst prefixFromNetworkMap = {\n mainnet: _bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.CashAddressNetworkPrefix.mainnet,\n testnet: _bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.CashAddressNetworkPrefix.testnet,\n regtest: _bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.CashAddressNetworkPrefix.regtest,\n};\nconst literal = (l) => l;\nconst UnitEnum = {\n BCH: literal(\"bch\"),\n USD: literal(\"usd\"),\n SAT: literal(\"sat\"),\n};\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/enum.ts?");
|
|
158
158
|
|
|
159
159
|
/***/ }),
|
|
160
160
|
|
|
@@ -164,7 +164,7 @@ eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__
|
|
|
164
164
|
\***********************************/
|
|
165
165
|
/***/ ((module, __webpack_exports__, __webpack_require__) => {
|
|
166
166
|
|
|
167
|
-
eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"getHistory\": () => (/* binding */ getHistory)\n/* harmony export */ });\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/message/transaction-encoding.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/hex.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/error.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/address/cash-address.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/address/locking-bytecode.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/vm/instruction-sets/instruction-sets.js\");\n/* harmony import */ var _util_convert_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../util/convert.js */ \"./src/util/convert.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_5__, _util_convert_js__WEBPACK_IMPORTED_MODULE_6__]);\n([_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_5__, _util_convert_js__WEBPACK_IMPORTED_MODULE_6__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\n// export type AddressTxI = TxI & {\n// address: string;\n// }\n// export const getAddressHistory = async ({\n// address,\n// provider,\n// unit = \"sat\",\n// fromHeight = 0,\n// toHeight = -1,\n// start = 0,\n// count = -1,\n// }: {\n// address: string;\n// provider: NetworkProvider;\n// unit?: UnitEnum;\n// fromHeight?: number;\n// toHeight?: number;\n// start?: number;\n// count?: number;\n// }): Promise<TransactionHistoryItem[]> => {\n// return getHistory({\n// addresses: [address],\n// provider,\n// unit,\n// fromHeight,\n// toHeight,\n// start,\n// count,\n// });\n// }\nconst getHistory = async ({ addresses, provider, unit = \"sat\", fromHeight = 0, toHeight = -1, start = 0, count = -1, }) => {\n if (!addresses.length) {\n return [];\n }\n if (count === -1) {\n count = 1e10;\n }\n const history = (await Promise.all(addresses.map(async (address) => provider.getHistory(address, fromHeight, toHeight))))\n .flat()\n .filter((value, index, array) => array.findIndex((item) => item.tx_hash === value.tx_hash) === index)\n .sort((a, b) => a.height <= 0 || b.height <= 0 ? a.height - b.height : b.height - a.height)\n .slice(start, start + count);\n // fill transaction timestamps by requesting headers from network and parsing them\n const uniqueHeights = history\n .map((tx) => tx.height)\n .filter((height) => height > 0)\n .filter((value, index, array) => array.indexOf(value) === index);\n const timestampMap = (await Promise.all(uniqueHeights.map(async (height) => [\n height,\n (await provider.getHeader(height, true)).timestamp,\n ]))).reduce((acc, [height, timestamp]) => ({ ...acc, [height]: timestamp }), {});\n // first load all transactions\n const historicTransactions = await Promise.all(history.map(async (tx) => {\n const txHex = (await provider.getRawTransaction(tx.tx_hash));\n const transactionCommon = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.decodeTransaction)((0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.hexToBin)(txHex));\n if (typeof transactionCommon === \"string\") {\n throw transactionCommon;\n }\n const transaction = transactionCommon;\n transaction.blockHeight = tx.height;\n transaction.timestamp = timestampMap[tx.height];\n transaction.hash = tx.tx_hash;\n transaction.size = txHex.length / 2;\n return transaction;\n }));\n // then load their prevout transactions\n const prevoutTransactionHashes = historicTransactions\n .map((tx) => tx.inputs.map((input) => (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.binToHex)(input.outpointTransactionHash)))\n .flat()\n .filter((value, index, array) => array.indexOf(value) === index);\n const prevoutTransactionMap = (await Promise.all(prevoutTransactionHashes.map(async (hash) => {\n if (hash ===\n \"0000000000000000000000000000000000000000000000000000000000000000\") {\n return [hash, undefined];\n }\n const txHex = (await provider.getRawTransaction(hash));\n const transaction = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.decodeTransaction)((0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.hexToBin)(txHex));\n if (typeof transaction === \"string\") {\n throw transaction;\n }\n return [hash, transaction];\n }))).reduce((acc, [hash, transaction]) => ({\n ...acc,\n [hash]: transaction,\n }), {});\n const decoded = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.assertSuccess)((0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.decodeCashAddress)(addresses[0]));\n const prefix = decoded.prefix;\n const addressCache = {};\n // map decoded transaction data to TransactionHistoryItem\n const historyItems = historicTransactions.map((tx) => {\n const result = {};\n let inputTotalValue = 0n;\n let outputTotalValue = 0n;\n const isCoinbase = tx.inputs.length === 1 &&\n tx.inputs[0].outpointTransactionHash.every((b) => b === 0);\n result.inputs = tx.inputs.map((input) => {\n if (isCoinbase) {\n const halvings = Math.floor(tx.blockHeight / 210000);\n const subsidy = Math.floor(5000000000 / 2 ** halvings);\n inputTotalValue += BigInt(subsidy);\n return {\n address: \"coinbase\",\n value: subsidy,\n };\n }\n const prevoutTx = prevoutTransactionMap[(0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.binToHex)(input.outpointTransactionHash)];\n if (!prevoutTx) {\n throw new Error(\"Could not find prevout transaction\");\n }\n const prevoutOutput = prevoutTx.outputs[input.outpointIndex];\n if (!prevoutOutput) {\n throw new Error(\"Could not find prevout output\");\n }\n const cached = addressCache[prevoutOutput.lockingBytecode];\n let address;\n if (!cached) {\n address = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.assertSuccess)((0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__.lockingBytecodeToCashAddress)({\n bytecode: prevoutOutput.lockingBytecode,\n prefix: prefix,\n })).address;\n addressCache[prevoutOutput.lockingBytecode] = address;\n }\n else {\n address = cached;\n }\n inputTotalValue += prevoutOutput.valueSatoshis;\n return {\n address: address,\n value: Number(prevoutOutput.valueSatoshis),\n token: prevoutOutput.token\n ? {\n tokenId: (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.binToHex)(prevoutOutput.token.category),\n amount: prevoutOutput.token.amount,\n capability: prevoutOutput.token.nft?.capability\n ? prevoutOutput.token.nft.capability\n : undefined,\n commitment: prevoutOutput.token.nft?.capability\n ? (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.binToHex)(prevoutOutput.token.nft.commitment)\n : undefined,\n }\n : undefined,\n };\n });\n result.outputs = tx.outputs.map((output) => {\n const cached = addressCache[output.lockingBytecode];\n let address;\n if (!cached) {\n if (output.lockingBytecode[0] === _bitauth_libauth__WEBPACK_IMPORTED_MODULE_5__.Opcodes.OP_RETURN) {\n address = `OP_RETURN: ${(0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.binToHex)(output.lockingBytecode)}`;\n }\n else {\n address = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.assertSuccess)((0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__.lockingBytecodeToCashAddress)({\n bytecode: output.lockingBytecode,\n prefix: prefix,\n })).address;\n addressCache[output.lockingBytecode] = address;\n }\n }\n else {\n address = cached;\n }\n outputTotalValue += output.valueSatoshis;\n return {\n address: address,\n value: Number(output.valueSatoshis),\n token: output.token\n ? {\n tokenId: (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.binToHex)(output.token.category),\n amount: output.token.amount,\n capability: output.token.nft?.capability\n ? output.token.nft.capability\n : undefined,\n commitment: output.token.nft?.capability\n ? (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.binToHex)(output.token.nft.commitment)\n : undefined,\n }\n : undefined,\n };\n });\n result.blockHeight = tx.blockHeight;\n result.timestamp = tx.timestamp;\n result.hash = tx.hash;\n result.size = tx.size;\n result.fee = Number(inputTotalValue - outputTotalValue);\n if (isCoinbase && result.fee) {\n // will indicate the fees collected by the miner\n result.fee = -result.fee;\n }\n return result;\n });\n // compute value changes\n historyItems.forEach((tx) => {\n let satoshiBalance = 0;\n const ftTokenBalances = {};\n const nftTokenBalances = {};\n tx.inputs.forEach((input) => {\n if (addresses.includes(input.address)) {\n satoshiBalance -= input.value;\n if (input.token?.amount) {\n ftTokenBalances[input.token.tokenId] =\n (ftTokenBalances[input.token.tokenId] || BigInt(0)) -\n input.token.amount;\n }\n if (input.token?.capability) {\n nftTokenBalances[input.token.tokenId] =\n (nftTokenBalances[input.token.tokenId] || BigInt(0)) - 1n;\n }\n }\n });\n tx.outputs.forEach((output) => {\n if (addresses.includes(output.address)) {\n satoshiBalance += Number(output.value);\n if (output.token?.amount) {\n ftTokenBalances[output.token.tokenId] =\n (ftTokenBalances[output.token.tokenId] || BigInt(0)) +\n output.token.amount;\n }\n if (output.token?.capability) {\n nftTokenBalances[output.token.tokenId] =\n (nftTokenBalances[output.token.tokenId] || BigInt(0)) + 1n;\n }\n }\n });\n tx.valueChange = satoshiBalance;\n tx.tokenAmountChanges = Object.entries(ftTokenBalances).map(([tokenId, amount]) => ({\n tokenId,\n amount,\n nftAmount: BigInt(0),\n }));\n for (const [tokenId, nftAmount] of Object.entries(nftTokenBalances)) {\n const tokenChange = tx.tokenAmountChanges.find((tokenChange) => tokenChange.tokenId === tokenId);\n if (tokenChange) {\n tokenChange.nftAmount = nftAmount;\n }\n else {\n tx.tokenAmountChanges.push({\n tokenId,\n amount: BigInt(0),\n nftAmount,\n });\n }\n }\n });\n // order transactions in a way such that receives are always ordered before sends, per block\n historyItems.sort((a, b) => (a.blockHeight <= 0 || b.blockHeight <= 0\n ? a.blockHeight - b.blockHeight\n : b.blockHeight - a.blockHeight) || a.valueChange - b.valueChange);\n // backfill the balances\n let prevBalance = (await Promise.all(addresses.map((address) => provider.getBalance(address)))).reduce((a, b) => a + b, 0);\n let prevValueChange = 0;\n historyItems.forEach((tx) => {\n tx.balance = prevBalance - prevValueChange;\n prevBalance = tx.balance;\n prevValueChange = tx.valueChange;\n });\n // convert units if needed\n if (!unit.includes(\"sat\")) {\n for (const tx of historyItems) {\n for (const input of tx.inputs) {\n input.value = await (0,_util_convert_js__WEBPACK_IMPORTED_MODULE_6__.convert)(input.value, \"sat\", unit);\n }\n for (const output of tx.outputs) {\n output.value = await (0,_util_convert_js__WEBPACK_IMPORTED_MODULE_6__.convert)(output.value, \"sat\", unit);\n }\n tx.valueChange = await (0,_util_convert_js__WEBPACK_IMPORTED_MODULE_6__.convert)(tx.valueChange, \"sat\", unit);\n tx.balance = await (0,_util_convert_js__WEBPACK_IMPORTED_MODULE_6__.convert)(tx.balance, \"sat\", unit);\n }\n }\n return historyItems;\n};\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/history/getHistory.ts?");
|
|
167
|
+
eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"getHistory\": () => (/* binding */ getHistory)\n/* harmony export */ });\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/message/transaction-encoding.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/hex.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/error.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/address/cash-address.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/address/locking-bytecode.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/vm/instruction-sets/instruction-sets.js\");\n/* harmony import */ var _util_convert_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../util/convert.js */ \"./src/util/convert.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_5__, _util_convert_js__WEBPACK_IMPORTED_MODULE_6__]);\n([_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_5__, _util_convert_js__WEBPACK_IMPORTED_MODULE_6__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\nconst getHistory = async ({ addresses, provider, unit = \"sat\", fromHeight = 0, toHeight = -1, start = 0, count = -1, }) => {\n if (!addresses.length) {\n return [];\n }\n if (count === -1) {\n count = 1e10;\n }\n const history = (await Promise.all(addresses.map(async (address) => provider.getHistory(address, fromHeight, toHeight))))\n .flat()\n .filter((value, index, array) => array.findIndex((item) => item.tx_hash === value.tx_hash) === index)\n .sort((a, b) => a.height <= 0 || b.height <= 0 ? a.height - b.height : b.height - a.height)\n .slice(start, start + count);\n // fill transaction timestamps by requesting headers from network and parsing them\n const uniqueHeights = history\n .map((tx) => tx.height)\n .filter((height) => height > 0)\n .filter((value, index, array) => array.indexOf(value) === index);\n const timestampMap = (await Promise.all(uniqueHeights.map(async (height) => [\n height,\n (await provider.getHeader(height, true)).timestamp,\n ]))).reduce((acc, [height, timestamp]) => ({ ...acc, [height]: timestamp }), {});\n // first load all transactions\n const historicTransactions = await Promise.all(history.map(async (tx) => {\n const txHex = (await provider.getRawTransaction(tx.tx_hash));\n const transactionCommon = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.decodeTransaction)((0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.hexToBin)(txHex));\n if (typeof transactionCommon === \"string\") {\n throw transactionCommon;\n }\n const transaction = transactionCommon;\n transaction.blockHeight = tx.height;\n transaction.timestamp = timestampMap[tx.height];\n transaction.hash = tx.tx_hash;\n transaction.size = txHex.length / 2;\n return transaction;\n }));\n // then load their prevout transactions\n const prevoutTransactionHashes = historicTransactions\n .map((tx) => tx.inputs.map((input) => (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.binToHex)(input.outpointTransactionHash)))\n .flat()\n .filter((value, index, array) => array.indexOf(value) === index);\n const prevoutTransactionMap = (await Promise.all(prevoutTransactionHashes.map(async (hash) => {\n if (hash ===\n \"0000000000000000000000000000000000000000000000000000000000000000\") {\n return [hash, undefined];\n }\n const txHex = (await provider.getRawTransaction(hash));\n const transaction = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.decodeTransaction)((0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.hexToBin)(txHex));\n if (typeof transaction === \"string\") {\n throw transaction;\n }\n return [hash, transaction];\n }))).reduce((acc, [hash, transaction]) => ({\n ...acc,\n [hash]: transaction,\n }), {});\n const decoded = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.assertSuccess)((0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.decodeCashAddress)(addresses[0]));\n const prefix = decoded.prefix;\n const addressCache = {};\n // map decoded transaction data to TransactionHistoryItem\n const historyItems = historicTransactions.map((tx) => {\n const result = {};\n let inputTotalValue = 0n;\n let outputTotalValue = 0n;\n const isCoinbase = tx.inputs.length === 1 &&\n tx.inputs[0].outpointTransactionHash.every((b) => b === 0);\n result.inputs = tx.inputs.map((input) => {\n if (isCoinbase) {\n const halvings = Math.floor(tx.blockHeight / 210000);\n const subsidy = Math.floor(5000000000 / 2 ** halvings);\n inputTotalValue += BigInt(subsidy);\n return {\n address: \"coinbase\",\n value: subsidy,\n };\n }\n const prevoutTx = prevoutTransactionMap[(0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.binToHex)(input.outpointTransactionHash)];\n if (!prevoutTx) {\n throw new Error(\"Could not find prevout transaction\");\n }\n const prevoutOutput = prevoutTx.outputs[input.outpointIndex];\n if (!prevoutOutput) {\n throw new Error(\"Could not find prevout output\");\n }\n const cached = addressCache[prevoutOutput.lockingBytecode];\n let address;\n if (!cached) {\n address = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.assertSuccess)((0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__.lockingBytecodeToCashAddress)({\n bytecode: prevoutOutput.lockingBytecode,\n prefix: prefix,\n })).address;\n addressCache[prevoutOutput.lockingBytecode] = address;\n }\n else {\n address = cached;\n }\n inputTotalValue += prevoutOutput.valueSatoshis;\n return {\n address: address,\n value: Number(prevoutOutput.valueSatoshis),\n token: prevoutOutput.token\n ? {\n category: (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.binToHex)(prevoutOutput.token.category),\n amount: prevoutOutput.token.amount,\n capability: prevoutOutput.token.nft?.capability\n ? prevoutOutput.token.nft.capability\n : undefined,\n commitment: prevoutOutput.token.nft?.capability\n ? (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.binToHex)(prevoutOutput.token.nft.commitment)\n : undefined,\n }\n : undefined,\n };\n });\n result.outputs = tx.outputs.map((output) => {\n const cached = addressCache[output.lockingBytecode];\n let address;\n if (!cached) {\n if (output.lockingBytecode[0] === _bitauth_libauth__WEBPACK_IMPORTED_MODULE_5__.Opcodes.OP_RETURN) {\n address = `OP_RETURN: ${(0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.binToHex)(output.lockingBytecode)}`;\n }\n else {\n address = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.assertSuccess)((0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__.lockingBytecodeToCashAddress)({\n bytecode: output.lockingBytecode,\n prefix: prefix,\n })).address;\n addressCache[output.lockingBytecode] = address;\n }\n }\n else {\n address = cached;\n }\n outputTotalValue += output.valueSatoshis;\n return {\n address: address,\n value: Number(output.valueSatoshis),\n token: output.token\n ? {\n category: (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.binToHex)(output.token.category),\n amount: output.token.amount,\n capability: output.token.nft?.capability\n ? output.token.nft.capability\n : undefined,\n commitment: output.token.nft?.capability\n ? (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.binToHex)(output.token.nft.commitment)\n : undefined,\n }\n : undefined,\n };\n });\n result.blockHeight = tx.blockHeight;\n result.timestamp = tx.timestamp;\n result.hash = tx.hash;\n result.size = tx.size;\n result.fee = Number(inputTotalValue - outputTotalValue);\n if (isCoinbase && result.fee) {\n // will indicate the fees collected by the miner\n result.fee = -result.fee;\n }\n return result;\n });\n // compute value changes\n historyItems.forEach((tx) => {\n let satoshiBalance = 0;\n const ftTokenBalances = {};\n const nftTokenBalances = {};\n tx.inputs.forEach((input) => {\n if (addresses.includes(input.address)) {\n satoshiBalance -= input.value;\n if (input.token?.amount) {\n ftTokenBalances[input.token.category] =\n (ftTokenBalances[input.token.category] || BigInt(0)) -\n input.token.amount;\n }\n if (input.token?.nft?.capability) {\n nftTokenBalances[input.token.category] =\n (nftTokenBalances[input.token.category] || BigInt(0)) - 1n;\n }\n }\n });\n tx.outputs.forEach((output) => {\n if (addresses.includes(output.address)) {\n satoshiBalance += Number(output.value);\n if (output.token?.amount) {\n ftTokenBalances[output.token.category] =\n (ftTokenBalances[output.token.category] || BigInt(0)) +\n output.token.amount;\n }\n if (output.token?.nft?.capability) {\n nftTokenBalances[output.token.category] =\n (nftTokenBalances[output.token.category] || BigInt(0)) + 1n;\n }\n }\n });\n tx.valueChange = satoshiBalance;\n tx.tokenAmountChanges = Object.entries(ftTokenBalances).map(([category, amount]) => ({\n category,\n amount,\n nftAmount: BigInt(0),\n }));\n for (const [category, nftAmount] of Object.entries(nftTokenBalances)) {\n const tokenChange = tx.tokenAmountChanges.find((tokenChange) => tokenChange.category === category);\n if (tokenChange) {\n tokenChange.nftAmount = nftAmount;\n }\n else {\n tx.tokenAmountChanges.push({\n category: category,\n amount: BigInt(0),\n nftAmount,\n });\n }\n }\n });\n // order transactions in a way such that receives are always ordered before sends, per block\n historyItems.sort((a, b) => (a.blockHeight <= 0 || b.blockHeight <= 0\n ? a.blockHeight - b.blockHeight\n : b.blockHeight - a.blockHeight) || a.valueChange - b.valueChange);\n // backfill the balances\n let prevBalance = (await Promise.all(addresses.map((address) => provider.getBalance(address)))).reduce((a, b) => a + b, 0);\n let prevValueChange = 0;\n historyItems.forEach((tx) => {\n tx.balance = prevBalance - prevValueChange;\n prevBalance = tx.balance;\n prevValueChange = tx.valueChange;\n });\n // convert units if needed\n if (!unit.includes(\"sat\")) {\n for (const tx of historyItems) {\n for (const input of tx.inputs) {\n input.value = await (0,_util_convert_js__WEBPACK_IMPORTED_MODULE_6__.convert)(input.value, \"sat\", unit);\n }\n for (const output of tx.outputs) {\n output.value = await (0,_util_convert_js__WEBPACK_IMPORTED_MODULE_6__.convert)(output.value, \"sat\", unit);\n }\n tx.valueChange = await (0,_util_convert_js__WEBPACK_IMPORTED_MODULE_6__.convert)(tx.valueChange, \"sat\", unit);\n tx.balance = await (0,_util_convert_js__WEBPACK_IMPORTED_MODULE_6__.convert)(tx.balance, \"sat\", unit);\n }\n }\n return historyItems;\n};\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/history/getHistory.ts?");
|
|
168
168
|
|
|
169
169
|
/***/ }),
|
|
170
170
|
|
|
@@ -174,7 +174,7 @@ eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__
|
|
|
174
174
|
\**********************/
|
|
175
175
|
/***/ ((module, __webpack_exports__, __webpack_require__) => {
|
|
176
176
|
|
|
177
|
-
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 */ \"BaseWallet\": () => (/* reexport safe */ _wallet_Base_js__WEBPACK_IMPORTED_MODULE_6__.BaseWallet),\n/* harmony export */ \"CONST\": () => (/* reexport module object */ _constant_js__WEBPACK_IMPORTED_MODULE_19__),\n/* harmony export */ \"Config\": () => (/* reexport safe */ _config_js__WEBPACK_IMPORTED_MODULE_12__.Config),\n/* harmony export */ \"Connection\": () => (/* reexport safe */ _network_index_js__WEBPACK_IMPORTED_MODULE_4__.Connection),\n/* harmony export */ \"DefaultProvider\": () => (/* reexport safe */ _network_configuration_js__WEBPACK_IMPORTED_MODULE_11__.DefaultProvider),\n/* harmony export */ \"ElectrumNetworkProvider\": () => (/* reexport safe */ _network_index_js__WEBPACK_IMPORTED_MODULE_4__.ElectrumNetworkProvider),\n/* harmony export */ \"ExchangeRate\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.ExchangeRate),\n/* harmony export */ \"FeePaidByEnum\": () => (/* reexport safe */ _wallet_enum_js__WEBPACK_IMPORTED_MODULE_14__.FeePaidByEnum),\n/* harmony export */ \"GAP_SIZE\": () => (/* reexport safe */ _wallet_HDWallet_js__WEBPACK_IMPORTED_MODULE_9__.GAP_SIZE),\n/* harmony export */ \"HDWallet\": () => (/* reexport safe */ _wallet_HDWallet_js__WEBPACK_IMPORTED_MODULE_9__.HDWallet),\n/* harmony export */ \"Mainnet\": () => (/* reexport module object */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__),\n/* harmony export */ \"NFTCapability\": () => (/* reexport safe */ _interface_js__WEBPACK_IMPORTED_MODULE_20__.NFTCapability),\n/* harmony export */ \"Network\": () => (/* reexport safe */ _interface_js__WEBPACK_IMPORTED_MODULE_20__.Network),\n/* harmony export */ \"NetworkType\": () => (/* reexport safe */ _enum_js__WEBPACK_IMPORTED_MODULE_13__.NetworkType),\n/* harmony export */ \"OpReturnData\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_15__.OpReturnData),\n/* harmony export */ \"RegTestHDWallet\": () => (/* reexport safe */ _wallet_HDWallet_js__WEBPACK_IMPORTED_MODULE_9__.RegTestHDWallet),\n/* harmony export */ \"RegTestWallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__.RegTestWallet),\n/* harmony export */ \"RegTestWatchWallet\": () => (/* reexport safe */ _wallet_Watch_js__WEBPACK_IMPORTED_MODULE_7__.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_16__.RuntimePlatform),\n/* harmony export */ \"SendRequest\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_15__.SendRequest),\n/* harmony export */ \"SendResponse\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_15__.SendResponse),\n/* harmony export */ \"SignedMessage\": () => (/* reexport safe */ _message_signed_js__WEBPACK_IMPORTED_MODULE_5__.SignedMessage),\n/* harmony export */ \"StorageProvider\": () => (/* reexport safe */ _db_index_js__WEBPACK_IMPORTED_MODULE_2__.StorageProvider),\n/* harmony export */ \"TestNetHDWallet\": () => (/* reexport safe */ _wallet_HDWallet_js__WEBPACK_IMPORTED_MODULE_9__.TestNetHDWallet),\n/* harmony export */ \"TestNetWallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__.TestNetWallet),\n/* harmony export */ \"TestNetWatchWallet\": () => (/* reexport safe */ _wallet_Watch_js__WEBPACK_IMPORTED_MODULE_7__.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_15__.TokenBurnRequest),\n/* harmony export */ \"TokenGenesisRequest\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_15__.TokenGenesisRequest),\n/* harmony export */ \"TokenMintRequest\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_15__.TokenMintRequest),\n/* harmony export */ \"TokenSendRequest\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_15__.TokenSendRequest),\n/* harmony export */ \"UnitEnum\": () => (/* reexport safe */ _enum_js__WEBPACK_IMPORTED_MODULE_13__.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_14__.WalletTypeEnum),\n/* harmony export */ \"WatchWallet\": () => (/* reexport safe */ _wallet_Watch_js__WEBPACK_IMPORTED_MODULE_7__.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_15__.XPubKey),\n/* harmony export */ \"_checkContextSafety\": () => (/* reexport safe */ _wallet_Base_js__WEBPACK_IMPORTED_MODULE_6__._checkContextSafety),\n/* harmony export */ \"amountInSatoshi\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.amountInSatoshi),\n/* harmony export */ \"asSendRequestObject\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.asSendRequestObject),\n/* harmony export */ \"atob\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.atob),\n/* harmony export */ \"balanceFromSatoshi\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.balanceFromSatoshi),\n/* harmony export */ \"balanceResponseFromSatoshi\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.balanceResponseFromSatoshi),\n/* harmony export */ \"binToBase64\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.binToBase64),\n/* harmony export */ \"binToHex\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.binToHex),\n/* harmony export */ \"btoa\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.btoa),\n/* harmony export */ \"checkTokenaddr\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.checkTokenaddr),\n/* harmony export */ \"checkUtxos\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.checkUtxos),\n/* harmony export */ \"convert\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.convert),\n/* harmony export */ \"convertAddress\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.convertAddress),\n/* harmony export */ \"convertObject\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.convertObject),\n/* harmony export */ \"createWallet\": () => (/* reexport safe */ _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_10__.createWallet),\n/* harmony export */ \"createWalletResponse\": () => (/* reexport safe */ _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_10__.createWalletResponse),\n/* harmony export */ \"decodeHeader\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.decodeHeader),\n/* harmony export */ \"delay\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.delay),\n/* harmony export */ \"deriveCashaddr\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.deriveCashaddr),\n/* harmony export */ \"derivePublicKeyHash\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.derivePublicKeyHash),\n/* harmony export */ \"deriveTokenaddr\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.deriveTokenaddr),\n/* harmony export */ \"derivedNetwork\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.derivedNetwork),\n/* harmony export */ \"disconnectProviders\": () => (/* reexport safe */ _network_index_js__WEBPACK_IMPORTED_MODULE_4__.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_15__.fromUtxoId),\n/* harmony export */ \"getAddrsByXpubKey\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.getAddrsByXpubKey),\n/* harmony export */ \"getAddrsByXpubKeyObject\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.getAddrsByXpubKeyObject),\n/* harmony export */ \"getHistory\": () => (/* reexport safe */ _history_getHistory_js__WEBPACK_IMPORTED_MODULE_17__.getHistory),\n/* harmony export */ \"getNamedWalletId\": () => (/* reexport safe */ _wallet_Base_js__WEBPACK_IMPORTED_MODULE_6__.getNamedWalletId),\n/* harmony export */ \"getNetworkProvider\": () => (/* reexport safe */ _network_index_js__WEBPACK_IMPORTED_MODULE_4__.getNetworkProvider),\n/* harmony export */ \"getRuntimePlatform\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.getRuntimePlatform),\n/* harmony export */ \"getStorageProvider\": () => (/* reexport safe */ _wallet_Base_js__WEBPACK_IMPORTED_MODULE_6__.getStorageProvider),\n/* harmony export */ \"getUsdRate\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.getUsdRate),\n/* harmony export */ \"getWeakRandomInt\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.getWeakRandomInt),\n/* harmony export */ \"getXPubKey\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.getXPubKey),\n/* harmony export */ \"getXpubKeyInfo\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.getXpubKeyInfo),\n/* harmony export */ \"getXpubKeyInfoObject\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.getXpubKeyInfoObject),\n/* harmony export */ \"hash160\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.hash160),\n/* harmony export */ \"hexToBin\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.hexToBin),\n/* harmony export */ \"initProvider\": () => (/* reexport safe */ _network_index_js__WEBPACK_IMPORTED_MODULE_4__.initProvider),\n/* harmony export */ \"initProviders\": () => (/* reexport safe */ _network_index_js__WEBPACK_IMPORTED_MODULE_4__.initProviders),\n/* harmony export */ \"isTokenaddr\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.isTokenaddr),\n/* harmony export */ \"isValidAddress\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.isValidAddress),\n/* harmony export */ \"libauth\": () => (/* reexport module object */ _libauth_js__WEBPACK_IMPORTED_MODULE_18__),\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_10__.namedWallet),\n/* harmony export */ \"namedWalletExists\": () => (/* reexport safe */ _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_10__.namedWalletExists),\n/* harmony export */ \"placeholderCashAddr\": () => (/* reexport safe */ _wallet_Base_js__WEBPACK_IMPORTED_MODULE_6__.placeholderCashAddr),\n/* harmony export */ \"placeholderTokenAddr\": () => (/* reexport safe */ _wallet_Base_js__WEBPACK_IMPORTED_MODULE_6__.placeholderTokenAddr),\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_10__.replaceNamedWallet),\n/* harmony export */ \"sanitizeAddress\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.sanitizeAddress),\n/* harmony export */ \"sanitizeUnit\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.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_16__.sha256),\n/* harmony export */ \"sumTokenAmounts\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.sumTokenAmounts),\n/* harmony export */ \"sumUtxoValue\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.sumUtxoValue),\n/* harmony export */ \"toCashaddr\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.toCashaddr),\n/* harmony export */ \"toTokenaddr\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.toTokenaddr),\n/* harmony export */ \"toUtxoId\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_15__.toUtxoId),\n/* harmony export */ \"utf8ToBin\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.utf8ToBin),\n/* harmony export */ \"walletClassMap\": () => (/* reexport safe */ _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_10__.walletClassMap),\n/* harmony export */ \"walletFromId\": () => (/* reexport safe */ _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_10__.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 _network_index_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./network/index.js */ \"./src/network/index.ts\");\n/* harmony import */ var _message_signed_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./message/signed.js */ \"./src/message/signed.ts\");\n/* harmony import */ var _wallet_Base_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./wallet/Base.js */ \"./src/wallet/Base.ts\");\n/* harmony import */ var _wallet_Watch_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./wallet/Watch.js */ \"./src/wallet/Watch.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_HDWallet_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./wallet/HDWallet.js */ \"./src/wallet/HDWallet.ts\");\n/* harmony import */ var _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./wallet/createWallet.js */ \"./src/wallet/createWallet.ts\");\n/* harmony import */ var _network_configuration_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./network/configuration.js */ \"./src/network/configuration.ts\");\n/* harmony import */ var _config_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./config.js */ \"./src/config.ts\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./enum.js */ \"./src/enum.ts\");\n/* harmony import */ var _wallet_enum_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./wallet/enum.js */ \"./src/wallet/enum.ts\");\n/* harmony import */ var _wallet_model_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./wallet/model.js */ \"./src/wallet/model.ts\");\n/* harmony import */ var _util_index_js__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./util/index.js */ \"./src/util/index.ts\");\n/* harmony import */ var _history_getHistory_js__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./history/getHistory.js */ \"./src/history/getHistory.ts\");\n/* harmony import */ var _libauth_js__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./libauth.js */ \"./src/libauth.ts\");\n/* harmony import */ var _constant_js__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./constant.js */ \"./src/constant.ts\");\n/* harmony import */ var _interface_js__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ./interface.js */ \"./src/interface.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_mine_index_js__WEBPACK_IMPORTED_MODULE_3__, _network_index_js__WEBPACK_IMPORTED_MODULE_4__, _message_signed_js__WEBPACK_IMPORTED_MODULE_5__, _wallet_Base_js__WEBPACK_IMPORTED_MODULE_6__, _wallet_Watch_js__WEBPACK_IMPORTED_MODULE_7__, _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__, _wallet_HDWallet_js__WEBPACK_IMPORTED_MODULE_9__, _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_10__, _network_configuration_js__WEBPACK_IMPORTED_MODULE_11__, _enum_js__WEBPACK_IMPORTED_MODULE_13__, _wallet_model_js__WEBPACK_IMPORTED_MODULE_15__, _util_index_js__WEBPACK_IMPORTED_MODULE_16__, _history_getHistory_js__WEBPACK_IMPORTED_MODULE_17__, _libauth_js__WEBPACK_IMPORTED_MODULE_18__]);\n([_mine_index_js__WEBPACK_IMPORTED_MODULE_3__, _network_index_js__WEBPACK_IMPORTED_MODULE_4__, _message_signed_js__WEBPACK_IMPORTED_MODULE_5__, _wallet_Base_js__WEBPACK_IMPORTED_MODULE_6__, _wallet_Watch_js__WEBPACK_IMPORTED_MODULE_7__, _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__, _wallet_HDWallet_js__WEBPACK_IMPORTED_MODULE_9__, _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_10__, _network_configuration_js__WEBPACK_IMPORTED_MODULE_11__, _enum_js__WEBPACK_IMPORTED_MODULE_13__, _wallet_model_js__WEBPACK_IMPORTED_MODULE_15__, _util_index_js__WEBPACK_IMPORTED_MODULE_16__, _history_getHistory_js__WEBPACK_IMPORTED_MODULE_17__, _libauth_js__WEBPACK_IMPORTED_MODULE_18__] = __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\n// libauth\n\n// constants\n\n\n// interfaces\n\n\n\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/index.ts?");
|
|
177
|
+
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 */ \"BaseWallet\": () => (/* reexport safe */ _wallet_Base_js__WEBPACK_IMPORTED_MODULE_6__.BaseWallet),\n/* harmony export */ \"CONST\": () => (/* reexport module object */ _constant_js__WEBPACK_IMPORTED_MODULE_19__),\n/* harmony export */ \"Config\": () => (/* reexport safe */ _config_js__WEBPACK_IMPORTED_MODULE_12__.Config),\n/* harmony export */ \"Connection\": () => (/* reexport safe */ _network_index_js__WEBPACK_IMPORTED_MODULE_4__.Connection),\n/* harmony export */ \"DefaultProvider\": () => (/* reexport safe */ _network_configuration_js__WEBPACK_IMPORTED_MODULE_11__.DefaultProvider),\n/* harmony export */ \"ElectrumNetworkProvider\": () => (/* reexport safe */ _network_index_js__WEBPACK_IMPORTED_MODULE_4__.ElectrumNetworkProvider),\n/* harmony export */ \"ExchageRatePromise\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.ExchageRatePromise),\n/* harmony export */ \"ExchangeRate\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.ExchangeRate),\n/* harmony export */ \"FeePaidByEnum\": () => (/* reexport safe */ _wallet_enum_js__WEBPACK_IMPORTED_MODULE_14__.FeePaidByEnum),\n/* harmony export */ \"GAP_SIZE\": () => (/* reexport safe */ _wallet_HDWallet_js__WEBPACK_IMPORTED_MODULE_9__.GAP_SIZE),\n/* harmony export */ \"HDWallet\": () => (/* reexport safe */ _wallet_HDWallet_js__WEBPACK_IMPORTED_MODULE_9__.HDWallet),\n/* harmony export */ \"Mainnet\": () => (/* reexport module object */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__),\n/* harmony export */ \"NFTCapability\": () => (/* reexport safe */ _interface_js__WEBPACK_IMPORTED_MODULE_20__.NFTCapability),\n/* harmony export */ \"Network\": () => (/* reexport safe */ _interface_js__WEBPACK_IMPORTED_MODULE_20__.Network),\n/* harmony export */ \"NetworkType\": () => (/* reexport safe */ _enum_js__WEBPACK_IMPORTED_MODULE_13__.NetworkType),\n/* harmony export */ \"OpReturnData\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_15__.OpReturnData),\n/* harmony export */ \"RegTestHDWallet\": () => (/* reexport safe */ _wallet_HDWallet_js__WEBPACK_IMPORTED_MODULE_9__.RegTestHDWallet),\n/* harmony export */ \"RegTestWallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__.RegTestWallet),\n/* harmony export */ \"RegTestWatchWallet\": () => (/* reexport safe */ _wallet_Watch_js__WEBPACK_IMPORTED_MODULE_7__.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_16__.RuntimePlatform),\n/* harmony export */ \"SendRequest\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_15__.SendRequest),\n/* harmony export */ \"SendResponse\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_15__.SendResponse),\n/* harmony export */ \"SignedMessage\": () => (/* reexport safe */ _message_signed_js__WEBPACK_IMPORTED_MODULE_5__.SignedMessage),\n/* harmony export */ \"StorageProvider\": () => (/* reexport safe */ _db_index_js__WEBPACK_IMPORTED_MODULE_2__.StorageProvider),\n/* harmony export */ \"TestNetHDWallet\": () => (/* reexport safe */ _wallet_HDWallet_js__WEBPACK_IMPORTED_MODULE_9__.TestNetHDWallet),\n/* harmony export */ \"TestNetWallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__.TestNetWallet),\n/* harmony export */ \"TestNetWatchWallet\": () => (/* reexport safe */ _wallet_Watch_js__WEBPACK_IMPORTED_MODULE_7__.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_15__.TokenBurnRequest),\n/* harmony export */ \"TokenGenesisRequest\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_15__.TokenGenesisRequest),\n/* harmony export */ \"TokenMintRequest\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_15__.TokenMintRequest),\n/* harmony export */ \"TokenSendRequest\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_15__.TokenSendRequest),\n/* harmony export */ \"UnitEnum\": () => (/* reexport safe */ _enum_js__WEBPACK_IMPORTED_MODULE_13__.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_14__.WalletTypeEnum),\n/* harmony export */ \"WatchWallet\": () => (/* reexport safe */ _wallet_Watch_js__WEBPACK_IMPORTED_MODULE_7__.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_15__.XPubKey),\n/* harmony export */ \"_checkContextSafety\": () => (/* reexport safe */ _wallet_Base_js__WEBPACK_IMPORTED_MODULE_6__._checkContextSafety),\n/* harmony export */ \"amountInSatoshi\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.amountInSatoshi),\n/* harmony export */ \"asSendRequestObject\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.asSendRequestObject),\n/* harmony export */ \"atob\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.atob),\n/* harmony export */ \"binToBase64\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.binToBase64),\n/* harmony export */ \"binToHex\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.binToHex),\n/* harmony export */ \"btoa\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.btoa),\n/* harmony export */ \"checkTokenaddr\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.checkTokenaddr),\n/* harmony export */ \"checkUtxos\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.checkUtxos),\n/* harmony export */ \"convert\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.convert),\n/* harmony export */ \"convertAddress\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.convertAddress),\n/* harmony export */ \"convertObject\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.convertObject),\n/* harmony export */ \"createWallet\": () => (/* reexport safe */ _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_10__.createWallet),\n/* harmony export */ \"createWalletResponse\": () => (/* reexport safe */ _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_10__.createWalletResponse),\n/* harmony export */ \"decodeHeader\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.decodeHeader),\n/* harmony export */ \"delay\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.delay),\n/* harmony export */ \"deriveCashaddr\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.deriveCashaddr),\n/* harmony export */ \"derivePublicKeyHash\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.derivePublicKeyHash),\n/* harmony export */ \"deriveTokenaddr\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.deriveTokenaddr),\n/* harmony export */ \"derivedNetwork\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.derivedNetwork),\n/* harmony export */ \"disconnectProviders\": () => (/* reexport safe */ _network_index_js__WEBPACK_IMPORTED_MODULE_4__.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_15__.fromUtxoId),\n/* harmony export */ \"getAddrsByXpubKey\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.getAddrsByXpubKey),\n/* harmony export */ \"getAddrsByXpubKeyObject\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.getAddrsByXpubKeyObject),\n/* harmony export */ \"getHistory\": () => (/* reexport safe */ _history_getHistory_js__WEBPACK_IMPORTED_MODULE_17__.getHistory),\n/* harmony export */ \"getNamedWalletId\": () => (/* reexport safe */ _wallet_Base_js__WEBPACK_IMPORTED_MODULE_6__.getNamedWalletId),\n/* harmony export */ \"getNetworkProvider\": () => (/* reexport safe */ _network_index_js__WEBPACK_IMPORTED_MODULE_4__.getNetworkProvider),\n/* harmony export */ \"getRuntimePlatform\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.getRuntimePlatform),\n/* harmony export */ \"getStorageProvider\": () => (/* reexport safe */ _wallet_Base_js__WEBPACK_IMPORTED_MODULE_6__.getStorageProvider),\n/* harmony export */ \"getUsdRate\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.getUsdRate),\n/* harmony export */ \"getWeakRandomInt\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.getWeakRandomInt),\n/* harmony export */ \"getXPubKey\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.getXPubKey),\n/* harmony export */ \"getXpubKeyInfo\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.getXpubKeyInfo),\n/* harmony export */ \"getXpubKeyInfoObject\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.getXpubKeyInfoObject),\n/* harmony export */ \"hash160\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.hash160),\n/* harmony export */ \"hexToBin\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.hexToBin),\n/* harmony export */ \"initProvider\": () => (/* reexport safe */ _network_index_js__WEBPACK_IMPORTED_MODULE_4__.initProvider),\n/* harmony export */ \"initProviders\": () => (/* reexport safe */ _network_index_js__WEBPACK_IMPORTED_MODULE_4__.initProviders),\n/* harmony export */ \"isTokenaddr\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.isTokenaddr),\n/* harmony export */ \"isValidAddress\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.isValidAddress),\n/* harmony export */ \"libauth\": () => (/* reexport module object */ _libauth_js__WEBPACK_IMPORTED_MODULE_18__),\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_10__.namedWallet),\n/* harmony export */ \"namedWalletExists\": () => (/* reexport safe */ _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_10__.namedWalletExists),\n/* harmony export */ \"placeholderCashAddr\": () => (/* reexport safe */ _wallet_Base_js__WEBPACK_IMPORTED_MODULE_6__.placeholderCashAddr),\n/* harmony export */ \"placeholderTokenAddr\": () => (/* reexport safe */ _wallet_Base_js__WEBPACK_IMPORTED_MODULE_6__.placeholderTokenAddr),\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_10__.replaceNamedWallet),\n/* harmony export */ \"sanitizeAddress\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.sanitizeAddress),\n/* harmony export */ \"sanitizeUnit\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.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_16__.sha256),\n/* harmony export */ \"sumTokenAmounts\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.sumTokenAmounts),\n/* harmony export */ \"sumUtxoValue\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.sumUtxoValue),\n/* harmony export */ \"toBch\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.toBch),\n/* harmony export */ \"toCashaddr\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.toCashaddr),\n/* harmony export */ \"toCurrency\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.toCurrency),\n/* harmony export */ \"toSat\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.toSat),\n/* harmony export */ \"toTokenaddr\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.toTokenaddr),\n/* harmony export */ \"toUtxoId\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_15__.toUtxoId),\n/* harmony export */ \"utf8ToBin\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.utf8ToBin),\n/* harmony export */ \"walletClassMap\": () => (/* reexport safe */ _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_10__.walletClassMap),\n/* harmony export */ \"walletFromId\": () => (/* reexport safe */ _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_10__.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 _network_index_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./network/index.js */ \"./src/network/index.ts\");\n/* harmony import */ var _message_signed_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./message/signed.js */ \"./src/message/signed.ts\");\n/* harmony import */ var _wallet_Base_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./wallet/Base.js */ \"./src/wallet/Base.ts\");\n/* harmony import */ var _wallet_Watch_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./wallet/Watch.js */ \"./src/wallet/Watch.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_HDWallet_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./wallet/HDWallet.js */ \"./src/wallet/HDWallet.ts\");\n/* harmony import */ var _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./wallet/createWallet.js */ \"./src/wallet/createWallet.ts\");\n/* harmony import */ var _network_configuration_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./network/configuration.js */ \"./src/network/configuration.ts\");\n/* harmony import */ var _config_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./config.js */ \"./src/config.ts\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./enum.js */ \"./src/enum.ts\");\n/* harmony import */ var _wallet_enum_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./wallet/enum.js */ \"./src/wallet/enum.ts\");\n/* harmony import */ var _wallet_model_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./wallet/model.js */ \"./src/wallet/model.ts\");\n/* harmony import */ var _util_index_js__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./util/index.js */ \"./src/util/index.ts\");\n/* harmony import */ var _history_getHistory_js__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./history/getHistory.js */ \"./src/history/getHistory.ts\");\n/* harmony import */ var _libauth_js__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./libauth.js */ \"./src/libauth.ts\");\n/* harmony import */ var _constant_js__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./constant.js */ \"./src/constant.ts\");\n/* harmony import */ var _interface_js__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ./interface.js */ \"./src/interface.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_mine_index_js__WEBPACK_IMPORTED_MODULE_3__, _network_index_js__WEBPACK_IMPORTED_MODULE_4__, _message_signed_js__WEBPACK_IMPORTED_MODULE_5__, _wallet_Base_js__WEBPACK_IMPORTED_MODULE_6__, _wallet_Watch_js__WEBPACK_IMPORTED_MODULE_7__, _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__, _wallet_HDWallet_js__WEBPACK_IMPORTED_MODULE_9__, _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_10__, _network_configuration_js__WEBPACK_IMPORTED_MODULE_11__, _enum_js__WEBPACK_IMPORTED_MODULE_13__, _wallet_model_js__WEBPACK_IMPORTED_MODULE_15__, _util_index_js__WEBPACK_IMPORTED_MODULE_16__, _history_getHistory_js__WEBPACK_IMPORTED_MODULE_17__, _libauth_js__WEBPACK_IMPORTED_MODULE_18__]);\n([_mine_index_js__WEBPACK_IMPORTED_MODULE_3__, _network_index_js__WEBPACK_IMPORTED_MODULE_4__, _message_signed_js__WEBPACK_IMPORTED_MODULE_5__, _wallet_Base_js__WEBPACK_IMPORTED_MODULE_6__, _wallet_Watch_js__WEBPACK_IMPORTED_MODULE_7__, _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__, _wallet_HDWallet_js__WEBPACK_IMPORTED_MODULE_9__, _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_10__, _network_configuration_js__WEBPACK_IMPORTED_MODULE_11__, _enum_js__WEBPACK_IMPORTED_MODULE_13__, _wallet_model_js__WEBPACK_IMPORTED_MODULE_15__, _util_index_js__WEBPACK_IMPORTED_MODULE_16__, _history_getHistory_js__WEBPACK_IMPORTED_MODULE_17__, _libauth_js__WEBPACK_IMPORTED_MODULE_18__] = __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\n// libauth\n\n// constants\n\n\n// interfaces\n\n\n\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/index.ts?");
|
|
178
178
|
|
|
179
179
|
/***/ }),
|
|
180
180
|
|
|
@@ -244,7 +244,7 @@ eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__
|
|
|
244
244
|
\************************************************/
|
|
245
245
|
/***/ ((module, __webpack_exports__, __webpack_require__) => {
|
|
246
246
|
|
|
247
|
-
eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"default\": () => (/* binding */ ElectrumNetworkProvider)\n/* harmony export */ });\n/* harmony import */ var _electrum_cash_network__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @electrum-cash/network */ \"../../node_modules/@electrum-cash/network/dist/index.mjs\");\n/* harmony import */ var _interface_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../interface.js */ \"./src/interface.ts\");\n/* harmony import */ var _util_transaction_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../util/transaction.js */ \"./src/util/transaction.ts\");\n/* harmony import */ var _config_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../config.js */ \"./src/config.ts\");\n/* harmony import */ var _util_header_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../util/header.js */ \"./src/util/header.ts\");\n/* harmony import */ var _cache_IndexedDbCache_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../cache/IndexedDbCache.js */ \"./src/cache/IndexedDbCache.ts\");\n/* harmony import */ var _cache_WebStorageCache_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../cache/WebStorageCache.js */ \"./src/cache/WebStorageCache.ts\");\n/* harmony import */ var _cache_MemoryCache_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../cache/MemoryCache.js */ \"./src/cache/MemoryCache.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_util_header_js__WEBPACK_IMPORTED_MODULE_6__, _util_transaction_js__WEBPACK_IMPORTED_MODULE_7__]);\n([_util_header_js__WEBPACK_IMPORTED_MODULE_6__, _util_transaction_js__WEBPACK_IMPORTED_MODULE_7__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\n\n\n\n\n\n\nclass ElectrumNetworkProvider {\n get cache() {\n if (!_config_js__WEBPACK_IMPORTED_MODULE_1__.Config.UseMemoryCache &&\n !_config_js__WEBPACK_IMPORTED_MODULE_1__.Config.UseLocalStorageCache &&\n !_config_js__WEBPACK_IMPORTED_MODULE_1__.Config.UseIndexedDBCache) {\n this._cache = undefined;\n return this._cache;\n }\n if (_config_js__WEBPACK_IMPORTED_MODULE_1__.Config.UseMemoryCache && !(this._cache instanceof _cache_MemoryCache_js__WEBPACK_IMPORTED_MODULE_2__.MemoryCache)) {\n this._cache = new _cache_MemoryCache_js__WEBPACK_IMPORTED_MODULE_2__.MemoryCache();\n return this._cache;\n }\n if (_config_js__WEBPACK_IMPORTED_MODULE_1__.Config.UseLocalStorageCache &&\n !(this._cache instanceof _cache_WebStorageCache_js__WEBPACK_IMPORTED_MODULE_3__.WebStorageCache)) {\n this._cache = new _cache_WebStorageCache_js__WEBPACK_IMPORTED_MODULE_3__.WebStorageCache();\n return this._cache;\n }\n if (_config_js__WEBPACK_IMPORTED_MODULE_1__.Config.UseIndexedDBCache && !(this._cache instanceof _cache_IndexedDbCache_js__WEBPACK_IMPORTED_MODULE_4__.IndexedDbCache)) {\n this._cache = new _cache_IndexedDbCache_js__WEBPACK_IMPORTED_MODULE_4__.IndexedDbCache();\n return this._cache;\n }\n return this._cache;\n }\n constructor(electrum, network = _interface_js__WEBPACK_IMPORTED_MODULE_5__.Network.MAINNET, manualConnectionManagement) {\n this.network = network;\n this.manualConnectionManagement = manualConnectionManagement;\n this.subscriptions = 0;\n this.subscribedToHeaders = false;\n this.subscriptionMap = {};\n if (electrum) {\n this.electrum = electrum;\n }\n else {\n throw new Error(`A electrum-cash client is required.`);\n }\n }\n async getUtxos(cashaddr) {\n const result = await this.performRequest(\"blockchain.address.listunspent\", cashaddr, \"include_tokens\");\n return result.map((utxo) => ({\n address: cashaddr,\n txid: utxo.tx_hash,\n vout: utxo.tx_pos,\n satoshis: utxo.value,\n height: utxo.height,\n token: utxo.token_data\n ? {\n amount: BigInt(utxo.token_data.amount),\n tokenId: utxo.token_data.category,\n capability: utxo.token_data.nft?.capability,\n commitment: utxo.token_data.nft?.commitment,\n }\n : undefined,\n }));\n }\n async getBalance(cashaddr) {\n const result = await this.performRequest(\"blockchain.address.get_balance\", cashaddr);\n return result.confirmed + result.unconfirmed;\n }\n async getHeader(height, verbose = false) {\n const key = `header-${this.network}-${height}-${verbose}`;\n if (this.cache) {\n const cached = await this.cache.getItem(key);\n if (cached) {\n return verbose ? (0,_util_header_js__WEBPACK_IMPORTED_MODULE_6__.decodeHeader)(JSON.parse(cached)) : JSON.parse(cached);\n }\n }\n const result = await this.performRequest(\"blockchain.header.get\", height);\n if (this.cache) {\n await this.cache.setItem(key, JSON.stringify(result));\n }\n return verbose ? (0,_util_header_js__WEBPACK_IMPORTED_MODULE_6__.decodeHeader)(result) : result;\n }\n async getBlockHeight() {\n return (await this.performRequest(\"blockchain.headers.get_tip\"))\n .height;\n }\n async getRawTransaction(txHash, verbose = false, loadInputValues = false) {\n const key = `tx-${this.network}-${txHash}-${verbose}-${loadInputValues}`;\n if (this.cache) {\n const cached = await this.cache.getItem(key);\n if (cached) {\n return verbose ? JSON.parse(cached) : cached;\n }\n }\n try {\n const transaction = (await this.performRequest(\"blockchain.transaction.get\", txHash, verbose));\n if (this.cache) {\n await this.cache.setItem(key, verbose\n ? JSON.stringify(transaction)\n : transaction);\n }\n if (verbose && loadInputValues) {\n // get unique transaction hashes\n const hashes = [...new Set(transaction.vin.map((val) => val.txid))];\n const transactions = await Promise.all(hashes.map((hash) => this.getRawTransactionObject(hash, false)));\n const transactionMap = new Map();\n transactions.forEach((val) => transactionMap.set(val.hash, val));\n transaction.vin.forEach((input) => {\n const output = transactionMap\n .get(input.txid)\n .vout.find((val) => val.n === input.vout);\n input.address = output.scriptPubKey.addresses[0];\n input.value = output.value;\n input.tokenData = output.tokenData;\n });\n }\n return transaction;\n }\n catch (error) {\n if (error.message.indexOf(\"No such mempool or blockchain transaction.\") > -1)\n throw Error(`Could not decode transaction ${txHash}. It might not exist on the current blockchain (${this.network}).`);\n else\n throw error;\n }\n }\n // gets the decoded transaction in human readable form\n async getRawTransactionObject(txHash, loadInputValues = false) {\n return (await this.getRawTransaction(txHash, true, loadInputValues));\n }\n async sendRawTransaction(txHex, awaitPropagation = true) {\n return new Promise(async (resolve, reject) => {\n let txHash = await (0,_util_transaction_js__WEBPACK_IMPORTED_MODULE_7__.getTransactionHash)(txHex);\n if (!awaitPropagation) {\n this.performRequest(\"blockchain.transaction.broadcast\", txHex);\n resolve(txHash);\n }\n else {\n let cancel;\n const waitForTransactionCallback = async (data) => {\n if (data && data[0] === txHash && data[1] !== null) {\n await cancel?.();\n resolve(txHash);\n }\n };\n cancel = await this.subscribeToTransaction(txHash, waitForTransactionCallback);\n this.performRequest(\"blockchain.transaction.broadcast\", txHex).catch(async (error) => {\n await cancel?.();\n reject(error);\n });\n }\n });\n }\n // Get transaction history of a given cashaddr\n async getHistory(cashaddr, fromHeight = 0, toHeight = -1) {\n const result = await this.performRequest(\"blockchain.address.get_history\", cashaddr, fromHeight, toHeight);\n return result;\n }\n // Get the minimum fee a low-priority transaction must pay in order to be accepted to the daemon's memory pool.\n async getRelayFee() {\n const result = (await this.performRequest(\"blockchain.relayfee\"));\n return result;\n }\n async watchAddressStatus(cashaddr, callback) {\n const watchAddressStatusCallback = async (data) => {\n // subscription acknowledgement is the latest known status or null if no status is known\n // status is an array: [ cashaddr, statusHash ]\n if (data instanceof Array) {\n const addr = data[0];\n if (addr !== cashaddr) {\n return;\n }\n const status = data[1];\n callback(status);\n }\n };\n return this.subscribeToAddress(cashaddr, watchAddressStatusCallback);\n }\n async watchAddress(cashaddr, callback) {\n const historyMap = {};\n this.getHistory(cashaddr).then((history) => history.forEach((val) => (historyMap[val.tx_hash] = true)));\n const watchAddressStatusCallback = async () => {\n const newHistory = await this.getHistory(cashaddr);\n // sort history to put unconfirmed transactions in the beginning, then transactions in block height descenting order\n const txHashes = newHistory\n .sort((a, b) => a.height <= 0 || b.height <= 0 ? -1 : b.height - a.height)\n .map((val) => val.tx_hash);\n for (const hash of txHashes) {\n if (!(hash in historyMap)) {\n historyMap[hash] = true;\n callback(hash);\n // exit early to prevent further map lookups\n break;\n }\n }\n };\n return this.watchAddressStatus(cashaddr, watchAddressStatusCallback);\n }\n async watchAddressTransactions(cashaddr, callback) {\n return this.watchAddress(cashaddr, async (txHash) => {\n const tx = await this.getRawTransactionObject(txHash);\n callback(tx);\n });\n }\n async watchAddressTokenTransactions(cashaddr, callback) {\n return this.watchAddress(cashaddr, async (txHash) => {\n const tx = await this.getRawTransactionObject(txHash, true);\n if (tx.vin.some((val) => val.tokenData) ||\n tx.vout.some((val) => val.tokenData)) {\n callback(tx);\n }\n });\n }\n // watch for block headers and block height, if `skipCurrentHeight` is set, the notification about current block will not arrive\n async watchBlocks(callback, skipCurrentHeight = true) {\n let acknowledged = !skipCurrentHeight;\n const waitForBlockCallback = (_header) => {\n if (!acknowledged) {\n acknowledged = true;\n return;\n }\n _header = _header instanceof Array ? _header[0] : _header;\n callback(_header);\n };\n return this.subscribeToHeaders(waitForBlockCallback);\n }\n // Wait for the next block or a block at given blockchain height.\n async waitForBlock(height) {\n return new Promise(async (resolve) => {\n let cancelWatch;\n if (this.electrum.chainHeight && !height) {\n height = this.electrum.chainHeight + 1;\n }\n cancelWatch = await this.watchBlocks(async (header) => {\n if (!height) {\n height = header.height + 1;\n return;\n }\n if (header.height >= height) {\n await cancelWatch?.();\n resolve(header);\n return;\n }\n });\n });\n }\n // subscribe to notifications sent when new block is found, the block header is sent to callback\n async subscribeToHeaders(callback) {\n return this.subscribeRequest(\"blockchain.headers.subscribe\", callback);\n }\n async subscribeToAddress(cashaddr, callback) {\n return this.subscribeRequest(\"blockchain.address.subscribe\", callback, cashaddr);\n }\n async subscribeToTransaction(txHash, callback) {\n return this.subscribeRequest(\"blockchain.transaction.subscribe\", callback, txHash);\n }\n async performRequest(name, ...parameters) {\n await this.ready();\n const requestTimeout = new Promise(function (_resolve, reject) {\n setTimeout(function () {\n reject(\"electrum-cash request timed out, retrying\");\n }, 30000);\n }).catch(function (e) {\n throw e;\n });\n const request = this.electrum.request(name, ...parameters);\n return await Promise.race([request, requestTimeout])\n .then((value) => {\n if (value instanceof Error)\n throw value;\n let result = value;\n return result;\n })\n .catch(async () => {\n return await Promise.race([request, requestTimeout])\n .then((value) => {\n if (value instanceof Error)\n throw value;\n let result = value;\n return result;\n })\n .catch(function (e) {\n throw e;\n });\n });\n }\n async trackSubscription(methodName, ...parameters) {\n const key = `${methodName}-${this.network}-${JSON.stringify(parameters)}`;\n if (this.subscriptionMap[key]) {\n this.subscriptionMap[key]++;\n }\n else {\n this.subscriptionMap[key] = 1;\n }\n await this.electrum.subscribe(methodName, ...parameters);\n }\n async untrackSubscription(methodName, ...parameters) {\n const key = `${methodName}-${this.network}-${JSON.stringify(parameters)}`;\n if (this.subscriptionMap[key]) {\n this.subscriptionMap[key]--;\n if (this.subscriptionMap[key] <= 0) {\n // only really unsubscribe if there are no more subscriptions for this `key`\n delete this.subscriptionMap[key];\n try {\n await this.electrum.unsubscribe(methodName, ...parameters);\n }\n catch { }\n }\n }\n }\n async subscribeRequest(methodName, callback, ...parameters) {\n await this.ready();\n const handler = (data) => {\n if (data.method === methodName) {\n callback(data.params);\n }\n };\n this.electrum.on(\"notification\", handler);\n // safeguard against multiple subscriptions to headers\n if (methodName === \"blockhain.headers.subscribe\") {\n if (!this.subscribedToHeaders) {\n this.subscribedToHeaders = true;\n await this.trackSubscription(methodName, ...parameters);\n }\n }\n else {\n await this.trackSubscription(methodName, ...parameters);\n }\n this.subscriptions++;\n return async () => {\n this.electrum.off(\"notification\", handler);\n this.subscriptions--;\n // there are no blockchain.headers.unsubscribe method, so let's safeguard against it\n if (methodName !== \"blockchain.headers.subscribe\") {\n await this.untrackSubscription(methodName, ...parameters);\n }\n };\n }\n async ready() {\n return this.connect();\n }\n async connect() {\n await this.cache?.init();\n if (this.electrum.status !== _electrum_cash_network__WEBPACK_IMPORTED_MODULE_0__.ConnectionStatus.CONNECTED) {\n await this.electrum.connect();\n }\n }\n disconnect() {\n if (this.subscriptions > 0) {\n // console.warn(\n // `Trying to disconnect a network provider with ${this.subscriptions} active subscriptions. This is in most cases a bad idea.`\n // );\n }\n return this.electrum.disconnect(true, false);\n }\n}\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/network/ElectrumNetworkProvider.ts?");
|
|
247
|
+
eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"default\": () => (/* binding */ ElectrumNetworkProvider)\n/* harmony export */ });\n/* harmony import */ var _electrum_cash_network__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @electrum-cash/network */ \"../../node_modules/@electrum-cash/network/dist/index.mjs\");\n/* harmony import */ var _interface_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../interface.js */ \"./src/interface.ts\");\n/* harmony import */ var _util_transaction_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../util/transaction.js */ \"./src/util/transaction.ts\");\n/* harmony import */ var _config_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../config.js */ \"./src/config.ts\");\n/* harmony import */ var _util_header_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../util/header.js */ \"./src/util/header.ts\");\n/* harmony import */ var _cache_IndexedDbCache_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../cache/IndexedDbCache.js */ \"./src/cache/IndexedDbCache.ts\");\n/* harmony import */ var _cache_WebStorageCache_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../cache/WebStorageCache.js */ \"./src/cache/WebStorageCache.ts\");\n/* harmony import */ var _cache_MemoryCache_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../cache/MemoryCache.js */ \"./src/cache/MemoryCache.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_util_header_js__WEBPACK_IMPORTED_MODULE_6__, _util_transaction_js__WEBPACK_IMPORTED_MODULE_7__]);\n([_util_header_js__WEBPACK_IMPORTED_MODULE_6__, _util_transaction_js__WEBPACK_IMPORTED_MODULE_7__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\n\n\n\n\n\n\nclass ElectrumNetworkProvider {\n get cache() {\n if (!_config_js__WEBPACK_IMPORTED_MODULE_1__.Config.UseMemoryCache &&\n !_config_js__WEBPACK_IMPORTED_MODULE_1__.Config.UseLocalStorageCache &&\n !_config_js__WEBPACK_IMPORTED_MODULE_1__.Config.UseIndexedDBCache) {\n this._cache = undefined;\n return this._cache;\n }\n if (_config_js__WEBPACK_IMPORTED_MODULE_1__.Config.UseMemoryCache && !(this._cache instanceof _cache_MemoryCache_js__WEBPACK_IMPORTED_MODULE_2__.MemoryCache)) {\n this._cache = new _cache_MemoryCache_js__WEBPACK_IMPORTED_MODULE_2__.MemoryCache();\n return this._cache;\n }\n if (_config_js__WEBPACK_IMPORTED_MODULE_1__.Config.UseLocalStorageCache &&\n !(this._cache instanceof _cache_WebStorageCache_js__WEBPACK_IMPORTED_MODULE_3__.WebStorageCache)) {\n this._cache = new _cache_WebStorageCache_js__WEBPACK_IMPORTED_MODULE_3__.WebStorageCache();\n return this._cache;\n }\n if (_config_js__WEBPACK_IMPORTED_MODULE_1__.Config.UseIndexedDBCache && !(this._cache instanceof _cache_IndexedDbCache_js__WEBPACK_IMPORTED_MODULE_4__.IndexedDbCache)) {\n this._cache = new _cache_IndexedDbCache_js__WEBPACK_IMPORTED_MODULE_4__.IndexedDbCache();\n return this._cache;\n }\n return this._cache;\n }\n constructor(electrum, network = _interface_js__WEBPACK_IMPORTED_MODULE_5__.Network.MAINNET, manualConnectionManagement) {\n this.network = network;\n this.manualConnectionManagement = manualConnectionManagement;\n this.subscriptions = 0;\n this.subscribedToHeaders = false;\n this.subscriptionMap = {};\n if (electrum) {\n this.electrum = electrum;\n }\n else {\n throw new Error(`A electrum-cash client is required.`);\n }\n }\n async getUtxos(cashaddr) {\n const result = await this.performRequest(\"blockchain.address.listunspent\", cashaddr, \"include_tokens\");\n return result.map((utxo) => ({\n address: cashaddr,\n txid: utxo.tx_hash,\n vout: utxo.tx_pos,\n satoshis: BigInt(utxo.value),\n height: utxo.height,\n token: utxo.token_data\n ? {\n ...utxo.token_data,\n amount: BigInt(utxo.token_data.amount),\n }\n : undefined,\n }));\n }\n async getBalance(cashaddr) {\n const result = await this.performRequest(\"blockchain.address.get_balance\", cashaddr);\n return result.confirmed + result.unconfirmed;\n }\n async getHeader(height, verbose = false) {\n const key = `header-${this.network}-${height}-${verbose}`;\n if (this.cache) {\n const cached = await this.cache.getItem(key);\n if (cached) {\n return verbose ? (0,_util_header_js__WEBPACK_IMPORTED_MODULE_6__.decodeHeader)(JSON.parse(cached)) : JSON.parse(cached);\n }\n }\n const result = await this.performRequest(\"blockchain.header.get\", height);\n if (this.cache) {\n await this.cache.setItem(key, JSON.stringify(result));\n }\n return verbose ? (0,_util_header_js__WEBPACK_IMPORTED_MODULE_6__.decodeHeader)(result) : result;\n }\n async getBlockHeight() {\n return (await this.performRequest(\"blockchain.headers.get_tip\"))\n .height;\n }\n async getRawTransaction(txHash, verbose = false, loadInputValues = false) {\n const key = `tx-${this.network}-${txHash}-${verbose}-${loadInputValues}`;\n if (this.cache) {\n const cached = await this.cache.getItem(key);\n if (cached) {\n return verbose ? JSON.parse(cached) : cached;\n }\n }\n try {\n const transaction = (await this.performRequest(\"blockchain.transaction.get\", txHash, verbose));\n if (this.cache) {\n await this.cache.setItem(key, verbose\n ? JSON.stringify(transaction)\n : transaction);\n }\n if (verbose && loadInputValues) {\n // get unique transaction hashes\n const hashes = [...new Set(transaction.vin.map((val) => val.txid))];\n const transactions = await Promise.all(hashes.map((hash) => this.getRawTransactionObject(hash, false)));\n const transactionMap = new Map();\n transactions.forEach((val) => transactionMap.set(val.hash, val));\n transaction.vin.forEach((input) => {\n const output = transactionMap\n .get(input.txid)\n .vout.find((val) => val.n === input.vout);\n input.address = output.scriptPubKey.addresses[0];\n input.value = output.value;\n input.tokenData = output.tokenData;\n });\n }\n return transaction;\n }\n catch (error) {\n if (error.message.indexOf(\"No such mempool or blockchain transaction.\") > -1)\n throw Error(`Could not decode transaction ${txHash}. It might not exist on the current blockchain (${this.network}).`);\n else\n throw error;\n }\n }\n // gets the decoded transaction in human readable form\n async getRawTransactionObject(txHash, loadInputValues = false) {\n return (await this.getRawTransaction(txHash, true, loadInputValues));\n }\n async sendRawTransaction(txHex, awaitPropagation = true) {\n return new Promise(async (resolve, reject) => {\n let txHash = await (0,_util_transaction_js__WEBPACK_IMPORTED_MODULE_7__.getTransactionHash)(txHex);\n if (!awaitPropagation) {\n this.performRequest(\"blockchain.transaction.broadcast\", txHex);\n resolve(txHash);\n }\n else {\n let cancel;\n const waitForTransactionCallback = async (data) => {\n if (data && data[0] === txHash && data[1] !== null) {\n await cancel?.();\n resolve(txHash);\n }\n };\n cancel = await this.subscribeToTransaction(txHash, waitForTransactionCallback);\n this.performRequest(\"blockchain.transaction.broadcast\", txHex).catch(async (error) => {\n await cancel?.();\n reject(error);\n });\n }\n });\n }\n // Get transaction history of a given cashaddr\n async getHistory(cashaddr, fromHeight = 0, toHeight = -1) {\n const result = await this.performRequest(\"blockchain.address.get_history\", cashaddr, fromHeight, toHeight);\n return result;\n }\n // Get the minimum fee a low-priority transaction must pay in order to be accepted to the daemon's memory pool.\n async getRelayFee() {\n const result = (await this.performRequest(\"blockchain.relayfee\"));\n return result;\n }\n async watchAddressStatus(cashaddr, callback) {\n const watchAddressStatusCallback = async (data) => {\n // subscription acknowledgement is the latest known status or null if no status is known\n // status is an array: [ cashaddr, statusHash ]\n if (data instanceof Array) {\n const addr = data[0];\n if (addr !== cashaddr) {\n return;\n }\n const status = data[1];\n callback(status);\n }\n };\n return this.subscribeToAddress(cashaddr, watchAddressStatusCallback);\n }\n async watchAddress(cashaddr, callback) {\n const historyMap = {};\n this.getHistory(cashaddr).then((history) => history.forEach((val) => (historyMap[val.tx_hash] = true)));\n const watchAddressStatusCallback = async () => {\n const newHistory = await this.getHistory(cashaddr);\n // sort history to put unconfirmed transactions in the beginning, then transactions in block height descenting order\n const txHashes = newHistory\n .sort((a, b) => a.height <= 0 || b.height <= 0 ? -1 : b.height - a.height)\n .map((val) => val.tx_hash);\n for (const hash of txHashes) {\n if (!(hash in historyMap)) {\n historyMap[hash] = true;\n callback(hash);\n // exit early to prevent further map lookups\n break;\n }\n }\n };\n return this.watchAddressStatus(cashaddr, watchAddressStatusCallback);\n }\n async watchAddressTransactions(cashaddr, callback) {\n return this.watchAddress(cashaddr, async (txHash) => {\n const tx = await this.getRawTransactionObject(txHash);\n callback(tx);\n });\n }\n async watchAddressTokenTransactions(cashaddr, callback) {\n return this.watchAddress(cashaddr, async (txHash) => {\n const tx = await this.getRawTransactionObject(txHash, true);\n if (tx.vin.some((val) => val.tokenData) ||\n tx.vout.some((val) => val.tokenData)) {\n callback(tx);\n }\n });\n }\n // watch for block headers and block height, if `skipCurrentHeight` is set, the notification about current block will not arrive\n async watchBlocks(callback, skipCurrentHeight = true) {\n let acknowledged = !skipCurrentHeight;\n const waitForBlockCallback = (_header) => {\n if (!acknowledged) {\n acknowledged = true;\n return;\n }\n _header = _header instanceof Array ? _header[0] : _header;\n callback(_header);\n };\n return this.subscribeToHeaders(waitForBlockCallback);\n }\n // Wait for the next block or a block at given blockchain height.\n async waitForBlock(height) {\n return new Promise(async (resolve) => {\n let cancelWatch;\n if (this.electrum.chainHeight && !height) {\n height = this.electrum.chainHeight + 1;\n }\n cancelWatch = await this.watchBlocks(async (header) => {\n if (!height) {\n height = header.height + 1;\n return;\n }\n if (header.height >= height) {\n await cancelWatch?.();\n resolve(header);\n return;\n }\n });\n });\n }\n // subscribe to notifications sent when new block is found, the block header is sent to callback\n async subscribeToHeaders(callback) {\n return this.subscribeRequest(\"blockchain.headers.subscribe\", callback);\n }\n async subscribeToAddress(cashaddr, callback) {\n return this.subscribeRequest(\"blockchain.address.subscribe\", callback, cashaddr);\n }\n async subscribeToTransaction(txHash, callback) {\n return this.subscribeRequest(\"blockchain.transaction.subscribe\", callback, txHash);\n }\n async performRequest(name, ...parameters) {\n await this.ready();\n const requestTimeout = new Promise(function (_resolve, reject) {\n setTimeout(function () {\n reject(\"electrum-cash request timed out, retrying\");\n }, 30000);\n }).catch(function (e) {\n throw e;\n });\n const request = this.electrum.request(name, ...parameters);\n return await Promise.race([request, requestTimeout])\n .then((value) => {\n if (value instanceof Error)\n throw value;\n let result = value;\n return result;\n })\n .catch(async () => {\n return await Promise.race([request, requestTimeout])\n .then((value) => {\n if (value instanceof Error)\n throw value;\n let result = value;\n return result;\n })\n .catch(function (e) {\n throw e;\n });\n });\n }\n async trackSubscription(methodName, ...parameters) {\n const key = `${methodName}-${this.network}-${JSON.stringify(parameters)}`;\n if (this.subscriptionMap[key]) {\n this.subscriptionMap[key]++;\n }\n else {\n this.subscriptionMap[key] = 1;\n }\n await this.electrum.subscribe(methodName, ...parameters);\n }\n async untrackSubscription(methodName, ...parameters) {\n const key = `${methodName}-${this.network}-${JSON.stringify(parameters)}`;\n if (this.subscriptionMap[key]) {\n this.subscriptionMap[key]--;\n if (this.subscriptionMap[key] <= 0) {\n // only really unsubscribe if there are no more subscriptions for this `key`\n delete this.subscriptionMap[key];\n try {\n await this.electrum.unsubscribe(methodName, ...parameters);\n }\n catch { }\n }\n }\n }\n async subscribeRequest(methodName, callback, ...parameters) {\n await this.ready();\n const handler = (data) => {\n if (data.method === methodName) {\n callback(data.params);\n }\n };\n this.electrum.on(\"notification\", handler);\n // safeguard against multiple subscriptions to headers\n if (methodName === \"blockhain.headers.subscribe\") {\n if (!this.subscribedToHeaders) {\n this.subscribedToHeaders = true;\n await this.trackSubscription(methodName, ...parameters);\n }\n }\n else {\n await this.trackSubscription(methodName, ...parameters);\n }\n this.subscriptions++;\n return async () => {\n this.electrum.off(\"notification\", handler);\n this.subscriptions--;\n // there are no blockchain.headers.unsubscribe method, so let's safeguard against it\n if (methodName !== \"blockchain.headers.subscribe\") {\n await this.untrackSubscription(methodName, ...parameters);\n }\n };\n }\n async ready() {\n return this.connect();\n }\n async connect() {\n await this.cache?.init();\n if (this.electrum.status !== _electrum_cash_network__WEBPACK_IMPORTED_MODULE_0__.ConnectionStatus.CONNECTED) {\n await this.electrum.connect();\n }\n }\n disconnect() {\n if (this.subscriptions > 0) {\n // console.warn(\n // `Trying to disconnect a network provider with ${this.subscriptions} active subscriptions. This is in most cases a bad idea.`\n // );\n }\n return this.electrum.disconnect(true, false);\n }\n}\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/network/ElectrumNetworkProvider.ts?");
|
|
248
248
|
|
|
249
249
|
/***/ }),
|
|
250
250
|
|
|
@@ -284,7 +284,7 @@ eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__
|
|
|
284
284
|
\*****************************************/
|
|
285
285
|
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
|
|
286
286
|
|
|
287
|
-
eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"getRelayFeeCache\": () => (/* binding */ getRelayFeeCache)\n/* harmony export */ });\n/* harmony import */ var _chain_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../chain.js */ \"./src/chain.ts\");\n/* harmony import */ var _constant_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./constant.js */ \"./src/network/constant.ts\");\n\n\nasync function getRelayFeeCache(provider) {\n let relayFeePerKbInCoins;\n if (_constant_js__WEBPACK_IMPORTED_MODULE_0__.networkTickerMap[provider.network] + \"_RELAY_FEE\" in globalThis) {\n // Stores the fee in BCH_RELAY_FEE, tBCH_RELAY_FEE, etc\n relayFeePerKbInCoins =\n globalThis[_constant_js__WEBPACK_IMPORTED_MODULE_0__.networkTickerMap[provider.network] + \"_RELAY_FEE\"];\n }\n if (typeof relayFeePerKbInCoins !== \"number\") {\n relayFeePerKbInCoins = await provider.getRelayFee();\n globalThis[_constant_js__WEBPACK_IMPORTED_MODULE_0__.networkTickerMap[provider.network] + \"_RELAY_FEE\"] =\n relayFeePerKbInCoins;\n }\n if (typeof relayFeePerKbInCoins === \"number\") {\n return Math.round(relayFeePerKbInCoins * _chain_js__WEBPACK_IMPORTED_MODULE_1__.bchParam.subUnits) / 1000;\n }\n else {\n console.warn(\"Couldn't get min relay fee, using default instead\");\n return Math.round(0.00001 * _chain_js__WEBPACK_IMPORTED_MODULE_1__.bchParam.subUnits) / 1000;\n }\n}\n\n\n//# sourceURL=webpack://mainnet-js/./src/network/getRelayFeeCache.ts?");
|
|
287
|
+
eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"getRelayFeeCache\": () => (/* binding */ getRelayFeeCache)\n/* harmony export */ });\n/* harmony import */ var _chain_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../chain.js */ \"./src/chain.ts\");\n/* harmony import */ var _constant_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./constant.js */ \"./src/network/constant.ts\");\n\n\nasync function getRelayFeeCache(provider) {\n let relayFeePerKbInCoins;\n if (_constant_js__WEBPACK_IMPORTED_MODULE_0__.networkTickerMap[provider.network] + \"_RELAY_FEE\" in globalThis) {\n // Stores the fee in BCH_RELAY_FEE, tBCH_RELAY_FEE, etc\n relayFeePerKbInCoins =\n globalThis[_constant_js__WEBPACK_IMPORTED_MODULE_0__.networkTickerMap[provider.network] + \"_RELAY_FEE\"];\n }\n if (typeof relayFeePerKbInCoins !== \"number\") {\n relayFeePerKbInCoins = await provider.getRelayFee();\n globalThis[_constant_js__WEBPACK_IMPORTED_MODULE_0__.networkTickerMap[provider.network] + \"_RELAY_FEE\"] =\n relayFeePerKbInCoins;\n }\n if (typeof relayFeePerKbInCoins === \"number\") {\n return Math.round(relayFeePerKbInCoins * Number(_chain_js__WEBPACK_IMPORTED_MODULE_1__.bchParam.subUnits)) / 1000;\n }\n else {\n console.warn(\"Couldn't get min relay fee, using default instead\");\n return Math.round(0.00001 * Number(_chain_js__WEBPACK_IMPORTED_MODULE_1__.bchParam.subUnits)) / 1000;\n }\n}\n\n\n//# sourceURL=webpack://mainnet-js/./src/network/getRelayFeeCache.ts?");
|
|
288
288
|
|
|
289
289
|
/***/ }),
|
|
290
290
|
|
|
@@ -314,7 +314,7 @@ eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harm
|
|
|
314
314
|
\**********************************/
|
|
315
315
|
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
|
|
316
316
|
|
|
317
|
-
eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"ExchangeRate\": () => (/* binding */ ExchangeRate)\n/* harmony export */ });\n/* unused harmony exports getTtl, getRateFromExchange */\n/* harmony import */ var _constant_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../constant.js */ \"./src/constant.ts\");\n/* harmony import */ var _util_getRuntimePlatform_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../util/getRuntimePlatform.js */ \"./src/util/getRuntimePlatform.ts\");\n/* harmony import */ var _db_ExchangeRateProvider_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../db/ExchangeRateProvider.js */ \"./src/db/ExchangeRateProvider.ts\");\n/* harmony import */ var _config_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../config.js */ \"./src/config.ts\");\n\n\n\n\nclass ExchangeRate {\n constructor({ symbol, rate, ttl, }) {\n this.symbol = symbol;\n this.rate = rate;\n this.ttl = ttl;\n }\n toString() {\n this.rate.toFixed(2);\n }\n static async get(symbol, useCache = true) {\n const platform = (0,_util_getRuntimePlatform_js__WEBPACK_IMPORTED_MODULE_0__.getRuntimePlatform)();\n if (platform === _util_getRuntimePlatform_js__WEBPACK_IMPORTED_MODULE_0__.RuntimePlatform.browser) {\n try {\n return await this.getRateFromLocalStorage(symbol, useCache);\n }\n catch {\n return await this.getRateFromGlobalScope(symbol, useCache);\n }\n }\n else {\n return await this.getRateFromGlobalScope(symbol, useCache);\n }\n }\n static async getRateFromLocalStorage(symbol, useCache = true) {\n if (!useCache) {\n return await getRateFromExchange(symbol);\n }\n let cache = new _db_ExchangeRateProvider_js__WEBPACK_IMPORTED_MODULE_1__[\"default\"]();\n let cacheRate = await cache.getRate(symbol);\n if (cacheRate) {\n // if the cache is still good, return it\n if (cacheRate.ttl > Date.now()) {\n return cacheRate.rate;\n }\n // else fall through\n }\n let freshRate = await getRateFromExchange(symbol);\n cache.setRate(symbol, freshRate, getTtl());\n return freshRate;\n }\n static async getRateFromGlobalScope(symbol, useCache = true) {\n if (!useCache) {\n return await getRateFromExchange(symbol);\n }\n if (globalThis.RATE) {\n let rateObject = globalThis.RATE;\n if (symbol in rateObject) {\n let cachedRate = rateObject[symbol];\n // If the cache is still good return ie\n if (cachedRate.ttl > Date.now()) {\n return cachedRate.rate;\n }\n }\n }\n let freshRate = await getRateFromExchange(symbol);\n this.cacheRateInGlobalScope(symbol, freshRate);\n return freshRate;\n }\n static cacheRateInGlobalScope(symbol, rate) {\n if (!globalThis.RATE) {\n globalThis.RATE = {};\n }\n else {\n globalThis.RATE[symbol] = {\n symbol: symbol,\n rate: rate,\n ttl: getTtl(),\n };\n }\n }\n}\nfunction getTtl() {\n return Math.trunc(Date.now() + _constant_js__WEBPACK_IMPORTED_MODULE_2__.EXCHANGE_RATE_TTL);\n}\n// Attempt to get the usd rate from some web app\nasync function getRateFromExchange(symbol) {\n if (_config_js__WEBPACK_IMPORTED_MODULE_3__.Config.GetExchangeRateFn) {\n return await _config_js__WEBPACK_IMPORTED_MODULE_3__.Config.GetExchangeRateFn(symbol);\n }\n if (symbol.length > 0) {\n symbol = symbol.toLocaleLowerCase();\n }\n if (symbol === \"usd\") {\n try {\n const response = await fetch(\"https://markets.api.bitcoin.com/live/bitcoin\");\n const data = await response.json();\n return data[\"data\"][\"BCH\"];\n }\n catch { }\n }\n const response = await fetch(\"https://bitpay.com/rates/BCH\");\n const data = (await response.json());\n const rates = data.data.reduce((acc, rate) => ({ ...acc, [rate.code.toLocaleLowerCase()]: rate.rate }), {});\n if (symbol in rates) {\n return rates[symbol];\n }\n throw Error(`Currency '${symbol}' is not supported.`);\n}\n// do not await and do not throw in case we are offline\
|
|
317
|
+
eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"ExchageRatePromise\": () => (/* binding */ ExchageRatePromise),\n/* harmony export */ \"ExchangeRate\": () => (/* binding */ ExchangeRate)\n/* harmony export */ });\n/* unused harmony exports getTtl, getRateFromExchange */\n/* harmony import */ var _constant_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../constant.js */ \"./src/constant.ts\");\n/* harmony import */ var _util_getRuntimePlatform_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../util/getRuntimePlatform.js */ \"./src/util/getRuntimePlatform.ts\");\n/* harmony import */ var _db_ExchangeRateProvider_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../db/ExchangeRateProvider.js */ \"./src/db/ExchangeRateProvider.ts\");\n/* harmony import */ var _config_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../config.js */ \"./src/config.ts\");\n\n\n\n\nclass ExchangeRate {\n constructor({ symbol, rate, ttl, }) {\n this.symbol = symbol;\n this.rate = rate;\n this.ttl = ttl;\n }\n toString() {\n this.rate.toFixed(2);\n }\n static async get(symbol, useCache = true) {\n const platform = (0,_util_getRuntimePlatform_js__WEBPACK_IMPORTED_MODULE_0__.getRuntimePlatform)();\n if (platform === _util_getRuntimePlatform_js__WEBPACK_IMPORTED_MODULE_0__.RuntimePlatform.browser) {\n try {\n return await this.getRateFromLocalStorage(symbol, useCache);\n }\n catch {\n return await this.getRateFromGlobalScope(symbol, useCache);\n }\n }\n else {\n return await this.getRateFromGlobalScope(symbol, useCache);\n }\n }\n static async getRateFromLocalStorage(symbol, useCache = true) {\n if (!useCache) {\n return await getRateFromExchange(symbol);\n }\n let cache = new _db_ExchangeRateProvider_js__WEBPACK_IMPORTED_MODULE_1__[\"default\"]();\n let cacheRate = await cache.getRate(symbol);\n if (cacheRate) {\n // if the cache is still good, return it\n if (cacheRate.ttl > Date.now()) {\n return cacheRate.rate;\n }\n // else fall through\n }\n let freshRate = await getRateFromExchange(symbol);\n cache.setRate(symbol, freshRate, getTtl());\n return freshRate;\n }\n static async getRateFromGlobalScope(symbol, useCache = true) {\n if (!useCache) {\n return await getRateFromExchange(symbol);\n }\n if (globalThis.RATE) {\n let rateObject = globalThis.RATE;\n if (symbol in rateObject) {\n let cachedRate = rateObject[symbol];\n // If the cache is still good return ie\n if (cachedRate.ttl > Date.now()) {\n return cachedRate.rate;\n }\n }\n }\n let freshRate = await getRateFromExchange(symbol);\n this.cacheRateInGlobalScope(symbol, freshRate);\n return freshRate;\n }\n static cacheRateInGlobalScope(symbol, rate) {\n if (!globalThis.RATE) {\n globalThis.RATE = {};\n }\n else {\n globalThis.RATE[symbol] = {\n symbol: symbol,\n rate: rate,\n ttl: getTtl(),\n };\n }\n }\n}\nfunction getTtl() {\n return Math.trunc(Date.now() + _constant_js__WEBPACK_IMPORTED_MODULE_2__.EXCHANGE_RATE_TTL);\n}\n// Attempt to get the usd rate from some web app\nasync function getRateFromExchange(symbol) {\n if (_config_js__WEBPACK_IMPORTED_MODULE_3__.Config.GetExchangeRateFn) {\n return await _config_js__WEBPACK_IMPORTED_MODULE_3__.Config.GetExchangeRateFn(symbol);\n }\n if (symbol.length > 0) {\n symbol = symbol.toLocaleLowerCase();\n }\n if (symbol === \"usd\") {\n try {\n const response = await fetch(\"https://markets.api.bitcoin.com/live/bitcoin\");\n const data = await response.json();\n return data[\"data\"][\"BCH\"];\n }\n catch { }\n }\n const response = await fetch(\"https://bitpay.com/rates/BCH\");\n const data = (await response.json());\n const rates = data.data.reduce((acc, rate) => ({ ...acc, [rate.code.toLocaleLowerCase()]: rate.rate }), {});\n if (symbol in rates) {\n return rates[symbol];\n }\n throw Error(`Currency '${symbol}' is not supported.`);\n}\n// do not await and do not throw in case we are offline\n// this promise can be used to warm up the cache\nconst ExchageRatePromise = ExchangeRate.get(_config_js__WEBPACK_IMPORTED_MODULE_3__.Config.DefaultCurrency)\n .then((result) => result)\n .catch((error) => error);\n\n\n//# sourceURL=webpack://mainnet-js/./src/rate/ExchangeRate.ts?");
|
|
318
318
|
|
|
319
319
|
/***/ }),
|
|
320
320
|
|
|
@@ -344,7 +344,7 @@ eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harm
|
|
|
344
344
|
\********************************/
|
|
345
345
|
/***/ ((module, __webpack_exports__, __webpack_require__) => {
|
|
346
346
|
|
|
347
|
-
eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"buildEncodedTransaction\": () => (/* binding */ buildEncodedTransaction),\n/* harmony export */ \"getFeeAmount\": () => (/* binding */ getFeeAmount),\n/* harmony export */ \"getFeeAmountSimple\": () => (/* binding */ getFeeAmountSimple),\n/* harmony export */ \"getSuitableUtxos\": () => (/* binding */ getSuitableUtxos),\n/* harmony export */ \"placeholderPrivateKeyBin\": () => (/* binding */ placeholderPrivateKeyBin),\n/* harmony export */ \"signUnsignedTransaction\": () => (/* binding */ signUnsignedTransaction)\n/* harmony export */ });\n/* unused harmony exports placeholderPrivateKey, buildP2pkhNonHdTransaction, prepareInputs, prepareOutputs, prepareOpReturnOutput, prepareTokenOutputs */\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/hex.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/schema/wallet-template.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/compiler/standard/p2pkh.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/compiler/compiler-bch/compiler-bch.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/address/locking-bytecode.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/transaction/generate-transaction.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/vm/instruction-sets/bch/2023/bch-2023-tokens.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/message/transaction-encoding.js\");\n/* harmony import */ var _interface_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../interface.js */ \"./src/interface.ts\");\n/* harmony import */ var _allocateFee_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./allocateFee.js */ \"./src/transaction/allocateFee.ts\");\n/* harmony import */ var _constant_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../constant.js */ \"./src/constant.ts\");\n/* harmony import */ var _wallet_model_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../wallet/model.js */ \"./src/wallet/model.ts\");\n/* harmony import */ var _util_amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../util/amountInSatoshi.js */ \"./src/util/amountInSatoshi.ts\");\n/* harmony import */ var _util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../util/sumSendRequestAmounts.js */ \"./src/util/sumSendRequestAmounts.ts\");\n/* harmony import */ var _util_sumUtxoValue_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../util/sumUtxoValue.js */ \"./src/util/sumUtxoValue.ts\");\n/* harmony import */ var _wallet_enum_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../wallet/enum.js */ \"./src/wallet/enum.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__, _util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_6__, _allocateFee_js__WEBPACK_IMPORTED_MODULE_7__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_9__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__, _wallet_model_js__WEBPACK_IMPORTED_MODULE_12__, _util_amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_13__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_15__]);\n([_bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__, _util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_6__, _allocateFee_js__WEBPACK_IMPORTED_MODULE_7__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_9__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__, _wallet_model_js__WEBPACK_IMPORTED_MODULE_12__, _util_amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_13__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_15__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\n\n\n\n\n\n\n\nconst placeholderPrivateKey = \"0000000000000000000000000000000000000000000000000000000000000001\";\nconst placeholderPrivateKeyBin = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.hexToBin)(placeholderPrivateKey);\n// Build a transaction for a p2pkh transaction for a non HD wallet\nasync function buildP2pkhNonHdTransaction({ inputs, outputs, signingKey, fee = 0, discardChange = false, feePaidBy = _wallet_enum_js__WEBPACK_IMPORTED_MODULE_1__.FeePaidByEnum.change, changeAddress = \"\", walletCache, }) {\n if (!signingKey) {\n throw new Error(\"Missing signing key when building transaction\");\n }\n const template = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.importWalletTemplate)(_bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.walletTemplateP2pkhNonHd);\n if (typeof template === \"string\") {\n throw new Error(\"Transaction template error\");\n }\n const compiler = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__.walletTemplateToCompilerBch)(template);\n const inputAmount = (0,_util_sumUtxoValue_js__WEBPACK_IMPORTED_MODULE_5__.sumUtxoValue)(inputs);\n const sendAmount = await (0,_util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_6__.sumSendRequestAmounts)(outputs);\n const changeAmount = BigInt(inputAmount) - BigInt(sendAmount) - BigInt(fee);\n outputs = (0,_allocateFee_js__WEBPACK_IMPORTED_MODULE_7__.allocateFee)(outputs, fee, feePaidBy, changeAmount);\n const lockedOutputs = await prepareOutputs(outputs);\n if (!changeAddress) {\n changeAddress = inputs[0].address;\n }\n if (discardChange !== true) {\n if (changeAmount > _constant_js__WEBPACK_IMPORTED_MODULE_8__.DUST_UTXO_THRESHOLD) {\n const changeLockingBytecode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_9__.cashAddressToLockingBytecode)(changeAddress);\n if (typeof changeLockingBytecode === \"string\") {\n throw Error(changeLockingBytecode);\n }\n lockedOutputs.push({\n lockingBytecode: changeLockingBytecode.bytecode,\n valueSatoshis: BigInt(changeAmount),\n });\n }\n }\n const { preparedInputs, sourceOutputs } = prepareInputs({\n inputs,\n compiler,\n signingKey,\n walletCache,\n });\n const result = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__.generateTransaction)({\n inputs: preparedInputs,\n locktime: 0,\n outputs: lockedOutputs,\n version: 2,\n });\n if (!result.success) {\n throw Error(\"Error building transaction with fee\");\n }\n const tokenValidationResult = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.verifyTransactionTokens)(result.transaction, sourceOutputs, { maximumTokenCommitmentLength: 40 });\n if (tokenValidationResult !== true && fee > 0) {\n throw tokenValidationResult;\n }\n return { transaction: result.transaction, sourceOutputs: sourceOutputs };\n}\nfunction prepareInputs({ inputs, compiler, signingKey, walletCache, }) {\n const preparedInputs = [];\n const sourceOutputs = [];\n for (const i of inputs) {\n const utxoTxnValue = i.satoshis;\n const utxoIndex = i.vout;\n // slice will create a clone of the array\n const utxoOutpointTransactionHash = new Uint8Array(i.txid.match(/.{1,2}/g).map((byte) => parseInt(byte, 16)));\n // reverse the cloned copy\n // utxoOutpointTransactionHash.reverse();\n if (!utxoOutpointTransactionHash || utxoIndex === undefined) {\n throw new Error(\"Missing unspent outpoint when building transaction\");\n }\n const libAuthToken = i.token && {\n amount: BigInt(i.token.amount),\n category: (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.hexToBin)(i.token.tokenId),\n nft: i.token.capability !== undefined || i.token.commitment !== undefined\n ? {\n capability: i.token.capability,\n commitment: i.token.commitment !== undefined &&\n (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.hexToBin)(i.token.commitment),\n }\n : undefined,\n };\n const key = walletCache?.getByAddress(i.address)?.privateKey ??\n (signingKey?.length ? signingKey : Uint8Array.from(Array(32)));\n const newInput = {\n outpointIndex: utxoIndex,\n outpointTransactionHash: utxoOutpointTransactionHash,\n sequenceNumber: 0,\n unlockingBytecode: {\n compiler,\n data: {\n keys: { privateKeys: { key: key } },\n },\n valueSatoshis: BigInt(utxoTxnValue),\n script: \"unlock\",\n token: libAuthToken,\n },\n };\n preparedInputs.push(newInput);\n const lockingBytecode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_9__.cashAddressToLockingBytecode)(i.address);\n if (typeof lockingBytecode === \"string\") {\n throw lockingBytecode;\n }\n sourceOutputs.push({\n outpointIndex: utxoIndex,\n outpointTransactionHash: utxoOutpointTransactionHash,\n sequenceNumber: 0,\n unlockingBytecode: Uint8Array.from([]),\n // additional info for sourceOutputs\n lockingBytecode: lockingBytecode.bytecode,\n valueSatoshis: BigInt(utxoTxnValue),\n token: libAuthToken,\n });\n }\n return { preparedInputs, sourceOutputs };\n}\n/**\n * prepareOutputs - create outputs for a transaction from a list of send requests\n *\n * a wrapper function\n *\n * @returns A promise to a list of unspent outputs\n */\nasync function prepareOutputs(outputs) {\n const lockedOutputs = [];\n for (const output of outputs) {\n if (output instanceof _wallet_model_js__WEBPACK_IMPORTED_MODULE_12__.TokenSendRequest) {\n lockedOutputs.push(prepareTokenOutputs(output));\n continue;\n }\n if (output instanceof _wallet_model_js__WEBPACK_IMPORTED_MODULE_12__.OpReturnData) {\n lockedOutputs.push(prepareOpReturnOutput(output));\n continue;\n }\n const outputLockingBytecode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_9__.cashAddressToLockingBytecode)(output.cashaddr);\n if (typeof outputLockingBytecode === \"string\")\n throw new Error(outputLockingBytecode);\n const sendAmount = await (0,_util_amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_13__.amountInSatoshi)(output.value, output.unit);\n if (sendAmount % 1 !== 0) {\n throw Error(`Cannot send ${sendAmount} satoshis, (fractional sats do not exist, yet), please use an integer number.`);\n }\n const lockedOutput = {\n lockingBytecode: outputLockingBytecode.bytecode,\n valueSatoshis: BigInt(sendAmount),\n };\n lockedOutputs.push(lockedOutput);\n }\n return lockedOutputs;\n}\n/**\n * prepareOpReturnOutput - create an output for OP_RETURN data\n *\n * @returns A promise to a list of unspent outputs\n */\nfunction prepareOpReturnOutput(request) {\n return {\n lockingBytecode: request.buffer,\n valueSatoshis: BigInt(0),\n };\n}\n/**\n * prepareOpReturnOutput - create an output for token data\n *\n * @returns A libauth Output\n */\nfunction prepareTokenOutputs(request) {\n const token = request;\n const outputLockingBytecode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_9__.cashAddressToLockingBytecode)(request.cashaddr);\n if (typeof outputLockingBytecode === \"string\")\n throw new Error(outputLockingBytecode);\n const libAuthToken = {\n amount: BigInt(token.amount),\n category: (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.hexToBin)(token.tokenId),\n nft: token.capability !== undefined || token.commitment !== undefined\n ? {\n capability: token.capability,\n commitment: token.commitment !== undefined && (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.hexToBin)(token.commitment),\n }\n : undefined,\n };\n return {\n lockingBytecode: outputLockingBytecode.bytecode,\n valueSatoshis: BigInt(request.value || 1000),\n token: libAuthToken,\n };\n}\n/**\n * getSuitableUtxos - Filter a list of unspent transaction outputs to the minimum needed to complete a transaction\n *\n * a intermediate function\n *\n * @param unspentOutputs An unfiltered list of available unspent transaction outputs\n *\n * @returns A promise to a list of unspent outputs\n */\nasync function getSuitableUtxos(inputs, amountRequired, bestHeight, feePaidBy, requests, ensureUtxos = [], tokenOperation = \"send\") {\n const suitableUtxos = [...ensureUtxos];\n let amountAvailable = BigInt(0);\n const tokenRequests = requests.filter((val) => val instanceof _wallet_model_js__WEBPACK_IMPORTED_MODULE_12__.TokenSendRequest);\n const availableInputs = inputs.slice();\n const selectedInputs = [];\n // find matching utxos for token transfers\n if (tokenOperation === \"send\") {\n for (const request of tokenRequests) {\n const tokenInputs = availableInputs.filter((val) => val.token?.tokenId === request.tokenId);\n const sameCommitmentTokens = [...suitableUtxos, ...tokenInputs]\n .filter((val) => val.token?.capability === request.capability &&\n val.token?.commitment === request.commitment)\n .filter((val) => selectedInputs.find((selected) => val.txid === selected.txid && val.vout === selected.vout) === undefined);\n if (sameCommitmentTokens.length) {\n const input = sameCommitmentTokens[0];\n const index = availableInputs.indexOf(input);\n if (index !== -1) {\n suitableUtxos.push(input);\n selectedInputs.push(input);\n availableInputs.splice(index, 1);\n amountAvailable += BigInt(input.satoshis);\n }\n continue;\n }\n if (request.capability === _interface_js__WEBPACK_IMPORTED_MODULE_14__.NFTCapability.minting ||\n request.capability === _interface_js__WEBPACK_IMPORTED_MODULE_14__.NFTCapability.mutable) {\n const changeCommitmentTokens = [\n ...suitableUtxos,\n ...tokenInputs,\n ].filter((val) => val.token?.capability === request.capability);\n if (changeCommitmentTokens.length) {\n const input = changeCommitmentTokens[0];\n const index = availableInputs.indexOf(input);\n if (index !== -1) {\n suitableUtxos.push(input);\n availableInputs.splice(index, 1);\n amountAvailable += BigInt(input.satoshis);\n }\n continue;\n }\n }\n // handle splitting the hybrid (FT+NFT) token into its parts\n if (request.capability === undefined &&\n request.commitment === undefined &&\n [...suitableUtxos, ...tokenInputs]\n .map((val) => val.token?.tokenId)\n .includes(request.tokenId)) {\n continue;\n }\n throw Error(`No suitable token utxos available to send token with id \"${request.tokenId}\", capability \"${request.capability}\", commitment \"${request.commitment}\"`);\n }\n }\n // find plain bch outputs\n for (const u of availableInputs) {\n if (u.token) {\n continue;\n }\n if (u.coinbase && u.height && bestHeight) {\n const age = bestHeight - u.height;\n if (age > 100) {\n suitableUtxos.push(u);\n amountAvailable += BigInt(u.satoshis);\n }\n }\n else {\n suitableUtxos.push(u);\n amountAvailable += BigInt(u.satoshis);\n }\n // if amountRequired is not given, assume it is a max spend request, skip this condition\n if (amountRequired && amountAvailable > amountRequired) {\n break;\n }\n }\n const addEnsured = (suitableUtxos) => {\n return [...ensureUtxos, ...suitableUtxos].filter((val, index, array) => array.findIndex((other) => other.txid === val.txid && other.vout === val.vout) === index);\n };\n // if the fee is split with a feePaidBy option, skip checking change.\n if (feePaidBy && feePaidBy != _wallet_enum_js__WEBPACK_IMPORTED_MODULE_1__.FeePaidByEnum.change) {\n return addEnsured(suitableUtxos);\n }\n // If the amount needed is met, or no amount is given, return\n if (typeof amountRequired === \"undefined\") {\n return addEnsured(suitableUtxos);\n }\n else if (amountAvailable < amountRequired) {\n const e = Error(`Amount required was not met, ${amountRequired} satoshis needed, ${amountAvailable} satoshis available`);\n e[\"data\"] = {\n required: amountRequired,\n available: amountAvailable,\n };\n throw e;\n }\n else {\n return addEnsured(suitableUtxos);\n }\n}\n// model-based imprecise and fast fee estimation\nasync function getFeeAmountSimple({ utxos, sendRequests, relayFeePerByteInSatoshi, discardChange, }) {\n const inputSizeP2pkh = 148;\n const outputSizeP2pkh = 34;\n const inputTotalSize = utxos.reduce((prev, curr) => prev +\n (curr.token\n ? inputSizeP2pkh +\n 1 +\n 34 +\n Math.round(1 + (curr.token.commitment?.length ?? 0) / 2) +\n (curr.token.amount ? 9 : 0)\n : inputSizeP2pkh), 0);\n const outputSize = (sendRequest) => {\n if (sendRequest.hasOwnProperty(\"unit\")) {\n return outputSizeP2pkh;\n }\n else if (sendRequest.hasOwnProperty(\"tokenId\")) {\n const tokenRequest = sendRequest;\n return (outputSizeP2pkh +\n 1 +\n 34 +\n Math.round(1 + (tokenRequest.commitment?.length ?? 0) / 2) +\n (tokenRequest.amount ? 9 : 0));\n }\n else if (sendRequest.hasOwnProperty(\"buffer\")) {\n return 9 + sendRequest.buffer.length;\n }\n return 0;\n };\n const outputTotalSize = sendRequests.reduce((prev, curr) => prev + outputSize(curr), 0) +\n (discardChange ? 0 : outputSizeP2pkh);\n return Math.ceil((inputTotalSize + outputTotalSize + 16) * relayFeePerByteInSatoshi);\n}\n// precise fee estimation\nasync function getFeeAmount({ utxos, sendRequests, sourceAddress, relayFeePerByteInSatoshi, feePaidBy, discardChange, walletCache, }) {\n // build transaction\n if (utxos) {\n // Build the transaction to get the approximate size\n const { encodedTransaction: draftTransaction } = await buildEncodedTransaction({\n inputs: utxos,\n outputs: sendRequests,\n signingKey: placeholderPrivateKeyBin,\n fee: 0, //DUST_UTXO_THRESHOLD\n discardChange: discardChange ?? false,\n feePaidBy,\n changeAddress: \"\",\n walletCache,\n });\n return Math.ceil(draftTransaction.length * relayFeePerByteInSatoshi + 1);\n }\n else {\n throw Error(\"The available inputs in the wallet cannot satisfy this send request\");\n }\n}\n// Build encoded transaction\nasync function buildEncodedTransaction({ inputs, outputs, signingKey, fee = 0, discardChange = false, feePaidBy = _wallet_enum_js__WEBPACK_IMPORTED_MODULE_1__.FeePaidByEnum.change, changeAddress = \"\", buildUnsigned = false, walletCache, }) {\n const { transaction, sourceOutputs } = await buildP2pkhNonHdTransaction({\n inputs,\n outputs,\n signingKey,\n fee,\n discardChange,\n feePaidBy,\n changeAddress,\n walletCache,\n });\n if (buildUnsigned === true) {\n transaction.inputs.forEach((input) => (input.unlockingBytecode = Uint8Array.from([])));\n }\n return { encodedTransaction: (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_15__.encodeTransaction)(transaction), sourceOutputs };\n}\nasync function signUnsignedTransaction(transaction, sourceOutputs, signingKey) {\n if (typeof transaction === \"string\") {\n transaction = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.hexToBin)(transaction);\n }\n const decoded = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_15__.decodeTransaction)(transaction);\n if (typeof decoded === \"string\") {\n throw decoded;\n }\n const template = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.importWalletTemplate)(_bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.walletTemplateP2pkhNonHd);\n if (typeof template === \"string\") {\n throw new Error(\"Transaction template error\");\n }\n const compiler = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__.walletTemplateToCompilerBch)(template);\n const transactionTemplate = { ...decoded };\n for (const [index, input] of decoded.inputs.entries()) {\n const sourceOutput = sourceOutputs[index];\n transactionTemplate.inputs[index] = {\n ...input,\n unlockingBytecode: {\n compiler,\n data: {\n keys: { privateKeys: { key: signingKey } },\n },\n valueSatoshis: sourceOutput.valueSatoshis,\n script: \"unlock\",\n token: sourceOutput.token,\n },\n };\n }\n const result = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__.generateTransaction)(transactionTemplate);\n if (!result.success) {\n throw result.errors;\n }\n return (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_15__.encodeTransaction)(result.transaction);\n}\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/transaction/Wif.ts?");
|
|
347
|
+
eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"buildEncodedTransaction\": () => (/* binding */ buildEncodedTransaction),\n/* harmony export */ \"getFeeAmount\": () => (/* binding */ getFeeAmount),\n/* harmony export */ \"getFeeAmountSimple\": () => (/* binding */ getFeeAmountSimple),\n/* harmony export */ \"getSuitableUtxos\": () => (/* binding */ getSuitableUtxos),\n/* harmony export */ \"placeholderPrivateKeyBin\": () => (/* binding */ placeholderPrivateKeyBin),\n/* harmony export */ \"signUnsignedTransaction\": () => (/* binding */ signUnsignedTransaction)\n/* harmony export */ });\n/* unused harmony exports placeholderPrivateKey, buildP2pkhNonHdTransaction, prepareInputs, prepareOutputs, prepareOpReturnOutput, prepareTokenOutputs */\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/hex.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/schema/wallet-template.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/compiler/standard/p2pkh.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/compiler/compiler-bch/compiler-bch.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/address/locking-bytecode.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/transaction/generate-transaction.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/vm/instruction-sets/bch/2023/bch-2023-tokens.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/message/transaction-encoding.js\");\n/* harmony import */ var _interface_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../interface.js */ \"./src/interface.ts\");\n/* harmony import */ var _allocateFee_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./allocateFee.js */ \"./src/transaction/allocateFee.ts\");\n/* harmony import */ var _constant_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../constant.js */ \"./src/constant.ts\");\n/* harmony import */ var _wallet_model_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../wallet/model.js */ \"./src/wallet/model.ts\");\n/* harmony import */ var _util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../util/sumSendRequestAmounts.js */ \"./src/util/sumSendRequestAmounts.ts\");\n/* harmony import */ var _util_sumUtxoValue_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../util/sumUtxoValue.js */ \"./src/util/sumUtxoValue.ts\");\n/* harmony import */ var _wallet_enum_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../wallet/enum.js */ \"./src/wallet/enum.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__, _util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_6__, _allocateFee_js__WEBPACK_IMPORTED_MODULE_7__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_9__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__, _wallet_model_js__WEBPACK_IMPORTED_MODULE_12__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_14__]);\n([_bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__, _util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_6__, _allocateFee_js__WEBPACK_IMPORTED_MODULE_7__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_9__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__, _wallet_model_js__WEBPACK_IMPORTED_MODULE_12__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_14__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\n\n\n\n\n\n\nconst placeholderPrivateKey = \"0000000000000000000000000000000000000000000000000000000000000001\";\nconst placeholderPrivateKeyBin = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.hexToBin)(placeholderPrivateKey);\n// Build a transaction for a p2pkh transaction for a non HD wallet\nasync function buildP2pkhNonHdTransaction({ inputs, outputs, signingKey, fee = 0n, discardChange = false, feePaidBy = _wallet_enum_js__WEBPACK_IMPORTED_MODULE_1__.FeePaidByEnum.change, changeAddress = \"\", walletCache, }) {\n if (!signingKey) {\n throw new Error(\"Missing signing key when building transaction\");\n }\n const template = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.importWalletTemplate)(_bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.walletTemplateP2pkhNonHd);\n if (typeof template === \"string\") {\n throw new Error(\"Transaction template error\");\n }\n const compiler = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__.walletTemplateToCompilerBch)(template);\n const inputAmount = (0,_util_sumUtxoValue_js__WEBPACK_IMPORTED_MODULE_5__.sumUtxoValue)(inputs);\n const sendAmount = await (0,_util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_6__.sumSendRequestAmounts)(outputs);\n const changeAmount = BigInt(inputAmount) - BigInt(sendAmount) - BigInt(fee);\n outputs = (0,_allocateFee_js__WEBPACK_IMPORTED_MODULE_7__.allocateFee)(outputs, fee, feePaidBy, changeAmount);\n const lockedOutputs = await prepareOutputs(outputs);\n if (!changeAddress) {\n changeAddress = inputs[0].address;\n }\n if (discardChange !== true) {\n if (changeAmount > _constant_js__WEBPACK_IMPORTED_MODULE_8__.DUST_UTXO_THRESHOLD) {\n const changeLockingBytecode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_9__.cashAddressToLockingBytecode)(changeAddress);\n if (typeof changeLockingBytecode === \"string\") {\n throw Error(changeLockingBytecode);\n }\n lockedOutputs.push({\n lockingBytecode: changeLockingBytecode.bytecode,\n valueSatoshis: BigInt(changeAmount),\n });\n }\n }\n const { preparedInputs, sourceOutputs } = prepareInputs({\n inputs,\n compiler,\n signingKey,\n walletCache,\n });\n const result = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__.generateTransaction)({\n inputs: preparedInputs,\n locktime: 0,\n outputs: lockedOutputs,\n version: 2,\n });\n if (!result.success) {\n throw Error(\"Error building transaction with fee\");\n }\n const tokenValidationResult = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_11__.verifyTransactionTokens)(result.transaction, sourceOutputs, { maximumTokenCommitmentLength: 40 });\n if (tokenValidationResult !== true && fee > 0) {\n throw tokenValidationResult;\n }\n return { transaction: result.transaction, sourceOutputs: sourceOutputs };\n}\nfunction prepareInputs({ inputs, compiler, signingKey, walletCache, }) {\n const preparedInputs = [];\n const sourceOutputs = [];\n for (const i of inputs) {\n const utxoTxnValue = i.satoshis;\n const utxoIndex = i.vout;\n // slice will create a clone of the array\n const utxoOutpointTransactionHash = new Uint8Array(i.txid.match(/.{1,2}/g).map((byte) => parseInt(byte, 16)));\n // reverse the cloned copy\n // utxoOutpointTransactionHash.reverse();\n if (!utxoOutpointTransactionHash || utxoIndex === undefined) {\n throw new Error(\"Missing unspent outpoint when building transaction\");\n }\n const libAuthToken = i.token && {\n amount: BigInt(i.token.amount),\n category: (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.hexToBin)(i.token.category),\n nft: i.token.nft?.capability !== undefined ||\n i.token.nft?.commitment !== undefined\n ? {\n capability: i.token.nft?.capability,\n commitment: i.token.nft?.commitment !== undefined &&\n (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.hexToBin)(i.token.nft?.commitment),\n }\n : undefined,\n };\n const key = walletCache?.get(i.address)?.privateKey ??\n (signingKey?.length ? signingKey : Uint8Array.from(Array(32)));\n const newInput = {\n outpointIndex: utxoIndex,\n outpointTransactionHash: utxoOutpointTransactionHash,\n sequenceNumber: 0,\n unlockingBytecode: {\n compiler,\n data: {\n keys: { privateKeys: { key: key } },\n },\n valueSatoshis: BigInt(utxoTxnValue),\n script: \"unlock\",\n token: libAuthToken,\n },\n };\n preparedInputs.push(newInput);\n const lockingBytecode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_9__.cashAddressToLockingBytecode)(i.address);\n if (typeof lockingBytecode === \"string\") {\n throw lockingBytecode;\n }\n sourceOutputs.push({\n outpointIndex: utxoIndex,\n outpointTransactionHash: utxoOutpointTransactionHash,\n sequenceNumber: 0,\n unlockingBytecode: Uint8Array.from([]),\n // additional info for sourceOutputs\n lockingBytecode: lockingBytecode.bytecode,\n valueSatoshis: BigInt(utxoTxnValue),\n token: libAuthToken,\n });\n }\n return { preparedInputs, sourceOutputs };\n}\n/**\n * prepareOutputs - create outputs for a transaction from a list of send requests\n *\n * a wrapper function\n *\n * @returns A promise to a list of unspent outputs\n */\nasync function prepareOutputs(outputs) {\n const lockedOutputs = [];\n for (const output of outputs) {\n if (output instanceof _wallet_model_js__WEBPACK_IMPORTED_MODULE_12__.TokenSendRequest) {\n lockedOutputs.push(prepareTokenOutputs(output));\n continue;\n }\n if (output instanceof _wallet_model_js__WEBPACK_IMPORTED_MODULE_12__.OpReturnData) {\n lockedOutputs.push(prepareOpReturnOutput(output));\n continue;\n }\n const outputLockingBytecode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_9__.cashAddressToLockingBytecode)(output.cashaddr);\n if (typeof outputLockingBytecode === \"string\")\n throw new Error(outputLockingBytecode);\n const sendAmount = Number(output.value);\n if (sendAmount % 1 !== 0) {\n throw Error(`Cannot send ${sendAmount} satoshis, (fractional sats do not exist, yet), please use an integer number.`);\n }\n const lockedOutput = {\n lockingBytecode: outputLockingBytecode.bytecode,\n valueSatoshis: BigInt(sendAmount),\n };\n lockedOutputs.push(lockedOutput);\n }\n return lockedOutputs;\n}\n/**\n * prepareOpReturnOutput - create an output for OP_RETURN data\n *\n * @returns A promise to a list of unspent outputs\n */\nfunction prepareOpReturnOutput(request) {\n return {\n lockingBytecode: request.buffer,\n valueSatoshis: BigInt(0),\n };\n}\n/**\n * prepareOpReturnOutput - create an output for token data\n *\n * @returns A libauth Output\n */\nfunction prepareTokenOutputs(request) {\n const token = request;\n const outputLockingBytecode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_9__.cashAddressToLockingBytecode)(request.cashaddr);\n if (typeof outputLockingBytecode === \"string\")\n throw new Error(outputLockingBytecode);\n const libAuthToken = {\n amount: BigInt(token.amount),\n category: (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.hexToBin)(token.category),\n nft: token.nft?.capability !== undefined || token.nft?.commitment !== undefined\n ? {\n capability: token.nft?.capability,\n commitment: token.nft?.commitment !== undefined &&\n (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.hexToBin)(token.nft?.commitment),\n }\n : undefined,\n };\n return {\n lockingBytecode: outputLockingBytecode.bytecode,\n valueSatoshis: BigInt(request.value || 1000),\n token: libAuthToken,\n };\n}\n/**\n * getSuitableUtxos - Filter a list of unspent transaction outputs to the minimum needed to complete a transaction\n *\n * a intermediate function\n *\n * @param unspentOutputs An unfiltered list of available unspent transaction outputs\n *\n * @returns A promise to a list of unspent outputs\n */\nasync function getSuitableUtxos(inputs, amountRequired, bestHeight, feePaidBy, requests, ensureUtxos = [], tokenOperation = \"send\") {\n const suitableUtxos = [...ensureUtxos];\n let amountAvailable = BigInt(0);\n const tokenRequests = requests.filter((val) => val instanceof _wallet_model_js__WEBPACK_IMPORTED_MODULE_12__.TokenSendRequest);\n const availableInputs = inputs.slice();\n const selectedInputs = [];\n // find matching utxos for token transfers\n if (tokenOperation === \"send\") {\n for (const request of tokenRequests) {\n const tokenInputs = availableInputs.filter((val) => val.token?.category === request.category);\n const sameCommitmentTokens = [...suitableUtxos, ...tokenInputs]\n .filter((val) => val.token?.nft?.capability === request.nft?.capability &&\n val.token?.nft?.commitment === request.nft?.commitment)\n .filter((val) => selectedInputs.find((selected) => val.txid === selected.txid && val.vout === selected.vout) === undefined);\n if (sameCommitmentTokens.length) {\n const input = sameCommitmentTokens[0];\n const index = availableInputs.indexOf(input);\n if (index !== -1) {\n suitableUtxos.push(input);\n selectedInputs.push(input);\n availableInputs.splice(index, 1);\n amountAvailable += BigInt(input.satoshis);\n }\n continue;\n }\n if (request.nft?.capability === _interface_js__WEBPACK_IMPORTED_MODULE_13__.NFTCapability.minting ||\n request.nft?.capability === _interface_js__WEBPACK_IMPORTED_MODULE_13__.NFTCapability.mutable) {\n const changeCommitmentTokens = [\n ...suitableUtxos,\n ...tokenInputs,\n ].filter((val) => val.token?.nft?.capability === request.nft?.capability);\n if (changeCommitmentTokens.length) {\n const input = changeCommitmentTokens[0];\n const index = availableInputs.indexOf(input);\n if (index !== -1) {\n suitableUtxos.push(input);\n availableInputs.splice(index, 1);\n amountAvailable += BigInt(input.satoshis);\n }\n continue;\n }\n }\n // handle splitting the hybrid (FT+NFT) token into its parts\n if (request.nft?.capability === undefined &&\n request.nft?.commitment === undefined &&\n [...suitableUtxos, ...tokenInputs]\n .map((val) => val.token?.category)\n .includes(request.category)) {\n continue;\n }\n throw Error(`No suitable token utxos available to send token with id \"${request.category}\", capability \"${request.nft?.capability}\", commitment \"${request.nft?.commitment}\"`);\n }\n }\n // find plain bch outputs\n for (const u of availableInputs) {\n if (u.token) {\n continue;\n }\n if (u.coinbase && u.height && bestHeight) {\n const age = bestHeight - u.height;\n if (age > 100) {\n suitableUtxos.push(u);\n amountAvailable += BigInt(u.satoshis);\n }\n }\n else {\n suitableUtxos.push(u);\n amountAvailable += BigInt(u.satoshis);\n }\n // if amountRequired is not given, assume it is a max spend request, skip this condition\n if (amountRequired && amountAvailable > amountRequired) {\n break;\n }\n }\n const addEnsured = (suitableUtxos) => {\n return [...ensureUtxos, ...suitableUtxos].filter((val, index, array) => array.findIndex((other) => other.txid === val.txid && other.vout === val.vout) === index);\n };\n // if the fee is split with a feePaidBy option, skip checking change.\n if (feePaidBy && feePaidBy != _wallet_enum_js__WEBPACK_IMPORTED_MODULE_1__.FeePaidByEnum.change) {\n return addEnsured(suitableUtxos);\n }\n // If the amount needed is met, or no amount is given, return\n if (typeof amountRequired === \"undefined\") {\n return addEnsured(suitableUtxos);\n }\n else if (amountAvailable < amountRequired) {\n const e = Error(`Amount required was not met, ${amountRequired} satoshis needed, ${amountAvailable} satoshis available`);\n e[\"data\"] = {\n required: amountRequired,\n available: amountAvailable,\n };\n throw e;\n }\n else {\n return addEnsured(suitableUtxos);\n }\n}\n// model-based imprecise and fast fee estimation\nasync function getFeeAmountSimple({ utxos, sendRequests, relayFeePerByteInSatoshi, discardChange, }) {\n const inputSizeP2pkh = 148;\n const outputSizeP2pkh = 34;\n const inputTotalSize = utxos.reduce((prev, curr) => prev +\n (curr.token\n ? inputSizeP2pkh +\n 1 +\n 34 +\n Math.round(1 + (curr.token.nft?.commitment?.length ?? 0) / 2) +\n (curr.token.amount ? 9 : 0)\n : inputSizeP2pkh), 0);\n const outputSize = (sendRequest) => {\n if (sendRequest.hasOwnProperty(\"category\")) {\n const tokenRequest = sendRequest;\n return (outputSizeP2pkh +\n 1 +\n 34 +\n Math.round(1 + (tokenRequest.nft?.commitment?.length ?? 0) / 2) +\n (tokenRequest.amount ? 9 : 0));\n }\n else if (sendRequest.hasOwnProperty(\"buffer\")) {\n return 9 + sendRequest.buffer.length;\n }\n else {\n return outputSizeP2pkh;\n }\n };\n const outputTotalSize = sendRequests.reduce((prev, curr) => prev + outputSize(curr), 0) +\n (discardChange ? 0 : outputSizeP2pkh);\n return BigInt(Math.ceil((inputTotalSize + outputTotalSize + 16) * relayFeePerByteInSatoshi));\n}\n// precise fee estimation\nasync function getFeeAmount({ utxos, sendRequests, sourceAddress, relayFeePerByteInSatoshi, feePaidBy, discardChange, walletCache, }) {\n // build transaction\n if (utxos) {\n // Build the transaction to get the approximate size\n const { encodedTransaction: draftTransaction } = await buildEncodedTransaction({\n inputs: utxos,\n outputs: sendRequests,\n signingKey: placeholderPrivateKeyBin,\n fee: 0n, //DUST_UTXO_THRESHOLD\n discardChange: discardChange ?? false,\n feePaidBy,\n changeAddress: \"\",\n walletCache,\n });\n return BigInt(Math.ceil(draftTransaction.length * relayFeePerByteInSatoshi + 1));\n }\n else {\n throw Error(\"The available inputs in the wallet cannot satisfy this send request\");\n }\n}\n// Build encoded transaction\nasync function buildEncodedTransaction({ inputs, outputs, signingKey, fee = 0n, discardChange = false, feePaidBy = _wallet_enum_js__WEBPACK_IMPORTED_MODULE_1__.FeePaidByEnum.change, changeAddress = \"\", buildUnsigned = false, walletCache, }) {\n const { transaction, sourceOutputs } = await buildP2pkhNonHdTransaction({\n inputs,\n outputs,\n signingKey,\n fee,\n discardChange,\n feePaidBy,\n changeAddress,\n walletCache,\n });\n if (buildUnsigned === true) {\n transaction.inputs.forEach((input) => (input.unlockingBytecode = Uint8Array.from([])));\n }\n return { encodedTransaction: (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_14__.encodeTransaction)(transaction), sourceOutputs };\n}\nasync function signUnsignedTransaction(transaction, sourceOutputs, signingKey) {\n if (typeof transaction === \"string\") {\n transaction = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_0__.hexToBin)(transaction);\n }\n const decoded = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_14__.decodeTransaction)(transaction);\n if (typeof decoded === \"string\") {\n throw decoded;\n }\n const template = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.importWalletTemplate)(_bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.walletTemplateP2pkhNonHd);\n if (typeof template === \"string\") {\n throw new Error(\"Transaction template error\");\n }\n const compiler = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__.walletTemplateToCompilerBch)(template);\n const transactionTemplate = { ...decoded };\n for (const [index, input] of decoded.inputs.entries()) {\n const sourceOutput = sourceOutputs[index];\n transactionTemplate.inputs[index] = {\n ...input,\n unlockingBytecode: {\n compiler,\n data: {\n keys: { privateKeys: { key: signingKey } },\n },\n valueSatoshis: sourceOutput.valueSatoshis,\n script: \"unlock\",\n token: sourceOutput.token,\n },\n };\n }\n const result = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_10__.generateTransaction)(transactionTemplate);\n if (!result.success) {\n throw result.errors;\n }\n return (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_14__.encodeTransaction)(result.transaction);\n}\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/transaction/Wif.ts?");
|
|
348
348
|
|
|
349
349
|
/***/ }),
|
|
350
350
|
|
|
@@ -354,7 +354,7 @@ eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__
|
|
|
354
354
|
\****************************************/
|
|
355
355
|
/***/ ((module, __webpack_exports__, __webpack_require__) => {
|
|
356
356
|
|
|
357
|
-
eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"allocateFee\": () => (/* binding */ allocateFee)\n/* harmony export */ });\n/* unused harmony exports checkFeeForDust, checkSatsAvailable, checkForNonStandardSendRequest, sortSendRequests */\n/* harmony import */ var _wallet_model_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../wallet/model.js */ \"./src/wallet/model.ts\");\n/* harmony import */ var _wallet_enum_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../wallet/enum.js */ \"./src/wallet/enum.ts\");\n/* harmony import */ var _constant_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../constant.js */ \"./src/constant.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_wallet_model_js__WEBPACK_IMPORTED_MODULE_1__]);\n_wallet_model_js__WEBPACK_IMPORTED_MODULE_1__ = (__webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__)[0];\n\n\n\nfunction checkFeeForDust(value) {\n if (value < _constant_js__WEBPACK_IMPORTED_MODULE_0__.DUST_UTXO_THRESHOLD) {\n throw Error(\"Fee strategy would result in dust output\");\n }\n}\nfunction checkSatsAvailable(sendRequestArray, fee) {\n let amountAvailable = sendRequestArray.reduce(function (sum, r) {\n return sum + (r.value - _constant_js__WEBPACK_IMPORTED_MODULE_0__.DUST_UTXO_THRESHOLD);\n },
|
|
357
|
+
eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"allocateFee\": () => (/* binding */ allocateFee)\n/* harmony export */ });\n/* unused harmony exports checkFeeForDust, checkSatsAvailable, checkForNonStandardSendRequest, sortSendRequests */\n/* harmony import */ var _wallet_model_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../wallet/model.js */ \"./src/wallet/model.ts\");\n/* harmony import */ var _wallet_enum_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../wallet/enum.js */ \"./src/wallet/enum.ts\");\n/* harmony import */ var _constant_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../constant.js */ \"./src/constant.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_wallet_model_js__WEBPACK_IMPORTED_MODULE_1__]);\n_wallet_model_js__WEBPACK_IMPORTED_MODULE_1__ = (__webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__)[0];\n\n\n\nfunction checkFeeForDust(value) {\n if (value < _constant_js__WEBPACK_IMPORTED_MODULE_0__.DUST_UTXO_THRESHOLD) {\n throw Error(\"Fee strategy would result in dust output\");\n }\n}\nfunction checkSatsAvailable(sendRequestArray, fee) {\n let amountAvailable = sendRequestArray.reduce(function (sum, r) {\n return sum + (r.value - _constant_js__WEBPACK_IMPORTED_MODULE_0__.DUST_UTXO_THRESHOLD);\n }, 0n);\n if (amountAvailable < fee) {\n throw Error(\"Insufficient funds for transaction given fee\");\n }\n}\nfunction checkForNonStandardSendRequest(output) {\n if (output instanceof _wallet_model_js__WEBPACK_IMPORTED_MODULE_1__.TokenSendRequest) {\n throw Error(\"Cannot specify fee to be paid by TokenSendRequest\");\n }\n if (output instanceof _wallet_model_js__WEBPACK_IMPORTED_MODULE_1__.OpReturnData) {\n throw Error(\"Cannot specify fee to be paid by OpReturnData\");\n }\n return output;\n}\nfunction sortSendRequests(sendRequestArray) {\n return sendRequestArray.sort((a, b) => Number(a.value - b.value));\n}\nfunction distributeFees(requests, fee) {\n checkSatsAvailable(requests, fee);\n for (let r = 0; r < requests.length; r++) {\n if (fee > 0) {\n checkForNonStandardSendRequest(requests[r]);\n let perRequestFee = fee / BigInt(requests.length - r);\n perRequestFee += fee % BigInt(requests.length - r);\n if (requests[r].value - perRequestFee < _constant_js__WEBPACK_IMPORTED_MODULE_0__.DUST_UTXO_THRESHOLD) {\n fee -= requests[r].value;\n requests[r].value = 0n;\n }\n else {\n fee -= perRequestFee;\n requests[r].value -= perRequestFee;\n }\n }\n }\n return requests.filter((r) => r.value >= _constant_js__WEBPACK_IMPORTED_MODULE_0__.DUST_UTXO_THRESHOLD);\n}\nfunction firstPays(requests, fee) {\n let payer = requests.shift();\n payer = checkForNonStandardSendRequest(payer);\n payer.value = payer.value - fee;\n checkFeeForDust(payer.value);\n requests.unshift(payer);\n return requests;\n}\nfunction lastPays(requests, fee) {\n let payer = requests.pop();\n payer = checkForNonStandardSendRequest(payer);\n payer.value = payer.value - fee;\n checkFeeForDust(payer.value);\n requests.push(payer);\n return requests;\n}\nfunction anyPays(requests, fee) {\n for (let r of requests) {\n checkForNonStandardSendRequest(r);\n }\n requests = sortSendRequests(requests);\n requests = distributeFees(requests, fee);\n return requests;\n}\nfunction changeThenFallback(requests, fee, change, fallbackFn) {\n if (BigInt(fee) > change) {\n let outstandingFee = BigInt(fee) - change;\n requests = fallbackFn(requests, outstandingFee);\n }\n return requests;\n}\nfunction allocateFee(requests, fee, feePaidBy, change) {\n if (requests.length > 0) {\n switch (feePaidBy) {\n case _wallet_enum_js__WEBPACK_IMPORTED_MODULE_2__.FeePaidByEnum.change:\n // handled by default\n break;\n case _wallet_enum_js__WEBPACK_IMPORTED_MODULE_2__.FeePaidByEnum.changeThenFirst:\n requests = changeThenFallback(requests, fee, change, firstPays);\n break;\n case _wallet_enum_js__WEBPACK_IMPORTED_MODULE_2__.FeePaidByEnum.changeThenLast:\n requests = changeThenFallback(requests, fee, change, lastPays);\n break;\n case _wallet_enum_js__WEBPACK_IMPORTED_MODULE_2__.FeePaidByEnum.changeThenAny:\n requests = changeThenFallback(requests, fee, change, anyPays);\n break;\n case _wallet_enum_js__WEBPACK_IMPORTED_MODULE_2__.FeePaidByEnum.first:\n requests = firstPays(requests, fee);\n break;\n case _wallet_enum_js__WEBPACK_IMPORTED_MODULE_2__.FeePaidByEnum.last:\n requests = lastPays(requests, fee);\n break;\n case _wallet_enum_js__WEBPACK_IMPORTED_MODULE_2__.FeePaidByEnum.any:\n requests = anyPays(requests, fee);\n break;\n default:\n throw Error(\"FeePaidBy option not recognized\");\n }\n return requests;\n }\n else {\n throw Error(\"Attempted to specify feePaidBy on zero length SendRequest\");\n }\n}\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/transaction/allocateFee.ts?");
|
|
358
358
|
|
|
359
359
|
/***/ }),
|
|
360
360
|
|
|
@@ -364,7 +364,7 @@ eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__
|
|
|
364
364
|
\*************************************/
|
|
365
365
|
/***/ ((module, __webpack_exports__, __webpack_require__) => {
|
|
366
366
|
|
|
367
|
-
eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"amountInSatoshi\": () => (/* binding */ amountInSatoshi)\n/* harmony export */ });\n/* harmony import */ var _chain_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../chain.js */ \"./src/chain.ts\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../enum.js */ \"./src/enum.ts\");\n/* harmony import */ var _rate_ExchangeRate_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../rate/ExchangeRate.js */ \"./src/rate/ExchangeRate.ts\");\n/* harmony import */ var _util_sanitizeUnit_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/sanitizeUnit.js */ \"./src/util/sanitizeUnit.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_enum_js__WEBPACK_IMPORTED_MODULE_2__]);\n_enum_js__WEBPACK_IMPORTED_MODULE_2__ = (__webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__)[0];\n\n\n\n\n/**\n * converts given value and unit into satoshi\n *\n * @param {value} number some value\n * @param {rawUnit} any the unit of value\n *\n * @returns a promise to the value in satoshi\n */\nasync function amountInSatoshi(value, rawUnit) {\n const unit = (0,_util_sanitizeUnit_js__WEBPACK_IMPORTED_MODULE_1__.sanitizeUnit)(rawUnit);\n switch (unit) {\n case _enum_js__WEBPACK_IMPORTED_MODULE_2__.UnitEnum.BCH:\n return Math.round(value * _chain_js__WEBPACK_IMPORTED_MODULE_3__.bchParam.subUnits);\n case _enum_js__WEBPACK_IMPORTED_MODULE_2__.UnitEnum.
|
|
367
|
+
eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"amountInSatoshi\": () => (/* binding */ amountInSatoshi)\n/* harmony export */ });\n/* harmony import */ var _chain_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../chain.js */ \"./src/chain.ts\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../enum.js */ \"./src/enum.ts\");\n/* harmony import */ var _rate_ExchangeRate_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../rate/ExchangeRate.js */ \"./src/rate/ExchangeRate.ts\");\n/* harmony import */ var _util_sanitizeUnit_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/sanitizeUnit.js */ \"./src/util/sanitizeUnit.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_enum_js__WEBPACK_IMPORTED_MODULE_2__]);\n_enum_js__WEBPACK_IMPORTED_MODULE_2__ = (__webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__)[0];\n\n\n\n\n/**\n * converts given value and unit into satoshi\n *\n * @param {value} number some value\n * @param {rawUnit} any the unit of value\n *\n * @returns a promise to the value in satoshi\n */\nasync function amountInSatoshi(value, rawUnit) {\n const unit = (0,_util_sanitizeUnit_js__WEBPACK_IMPORTED_MODULE_1__.sanitizeUnit)(rawUnit);\n switch (unit) {\n case _enum_js__WEBPACK_IMPORTED_MODULE_2__.UnitEnum.BCH:\n return BigInt(Math.round(value * Number(_chain_js__WEBPACK_IMPORTED_MODULE_3__.bchParam.subUnits)));\n case _enum_js__WEBPACK_IMPORTED_MODULE_2__.UnitEnum.SAT:\n return BigInt(value);\n default:\n const Currency_over_BCH = await _rate_ExchangeRate_js__WEBPACK_IMPORTED_MODULE_0__.ExchangeRate.get(rawUnit);\n const SAT_over_BCH = _chain_js__WEBPACK_IMPORTED_MODULE_3__.bchParam.subUnits;\n return BigInt(Math.round(Number(value * (Number(SAT_over_BCH) / Currency_over_BCH))));\n }\n}\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/util/amountInSatoshi.ts?");
|
|
368
368
|
|
|
369
369
|
/***/ }),
|
|
370
370
|
|
|
@@ -374,17 +374,7 @@ eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__
|
|
|
374
374
|
\*****************************************/
|
|
375
375
|
/***/ ((module, __webpack_exports__, __webpack_require__) => {
|
|
376
376
|
|
|
377
|
-
eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"asSendRequestObject\": () => (/* binding */ asSendRequestObject)\n/* harmony export */ });\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/base64.js\");\n/* harmony import */ var _wallet_model_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../wallet/model.js */ \"./src/wallet/model.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_wallet_model_js__WEBPACK_IMPORTED_MODULE_0__]);\n_wallet_model_js__WEBPACK_IMPORTED_MODULE_0__ = (__webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__)[0];\n\n\nfunction asSendRequestObject(requests) {\n let resp = [];\n if (Array.isArray(requests)) {\n requests.forEach((r) => {\n // the SendRequestArray[] case\n if (Array.isArray(r)) {\n if (r[0] === \"OP_RETURN\") {\n // ['OP_RETURN', utf8ToBin('MEMO\\x10')],\n resp.push(_wallet_model_js__WEBPACK_IMPORTED_MODULE_0__.OpReturnData.from(r[1]));\n }\n else if (r[0] === \"OP_RETURNB64\") {\n resp.push(_wallet_model_js__WEBPACK_IMPORTED_MODULE_0__.OpReturnData.fromUint8Array(Uint8Array.from((0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.base64ToBin)(r[1]))));\n }\n else {\n // ['cashaddr', 120
|
|
378
|
-
|
|
379
|
-
/***/ }),
|
|
380
|
-
|
|
381
|
-
/***/ "./src/util/balanceObjectFromSatoshi.ts":
|
|
382
|
-
/*!**********************************************!*\
|
|
383
|
-
!*** ./src/util/balanceObjectFromSatoshi.ts ***!
|
|
384
|
-
\**********************************************/
|
|
385
|
-
/***/ ((module, __webpack_exports__, __webpack_require__) => {
|
|
386
|
-
|
|
387
|
-
eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"balanceFromSatoshi\": () => (/* binding */ balanceFromSatoshi),\n/* harmony export */ \"balanceResponseFromSatoshi\": () => (/* binding */ balanceResponseFromSatoshi)\n/* harmony export */ });\n/* harmony import */ var _chain_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../chain.js */ \"./src/chain.ts\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../enum.js */ \"./src/enum.ts\");\n/* harmony import */ var _floor_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./floor.js */ \"./src/util/floor.ts\");\n/* harmony import */ var _rate_ExchangeRate_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../rate/ExchangeRate.js */ \"./src/rate/ExchangeRate.ts\");\n/* harmony import */ var _sanitizeUnit_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./sanitizeUnit.js */ \"./src/util/sanitizeUnit.ts\");\n/* harmony import */ var _config_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../config.js */ \"./src/config.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_enum_js__WEBPACK_IMPORTED_MODULE_5__]);\n_enum_js__WEBPACK_IMPORTED_MODULE_5__ = (__webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__)[0];\n\n\n\n\n\n\nasync function balanceResponseFromSatoshi(value, priceCache = true) {\n const response = {};\n response.bch = value / _chain_js__WEBPACK_IMPORTED_MODULE_1__.bchParam.subUnits;\n response.sat = value;\n const currencyValue = (value / _chain_js__WEBPACK_IMPORTED_MODULE_1__.bchParam.subUnits) *\n (await _rate_ExchangeRate_js__WEBPACK_IMPORTED_MODULE_0__.ExchangeRate.get(_config_js__WEBPACK_IMPORTED_MODULE_2__.Config.DefaultCurrency, priceCache));\n response[_config_js__WEBPACK_IMPORTED_MODULE_2__.Config.DefaultCurrency] = (0,_floor_js__WEBPACK_IMPORTED_MODULE_3__.floor)(currencyValue, 2);\n return response;\n}\nasync function balanceFromSatoshi(value, rawUnit, priceCache = true) {\n const unit = (0,_sanitizeUnit_js__WEBPACK_IMPORTED_MODULE_4__.sanitizeUnit)(rawUnit);\n switch (unit) {\n case _enum_js__WEBPACK_IMPORTED_MODULE_5__.UnitEnum.BCH:\n return value / _chain_js__WEBPACK_IMPORTED_MODULE_1__.bchParam.subUnits;\n case _enum_js__WEBPACK_IMPORTED_MODULE_5__.UnitEnum.SAT:\n return value;\n case _enum_js__WEBPACK_IMPORTED_MODULE_5__.UnitEnum.SATS:\n return value;\n case _enum_js__WEBPACK_IMPORTED_MODULE_5__.UnitEnum.SATOSHI:\n return value;\n case _enum_js__WEBPACK_IMPORTED_MODULE_5__.UnitEnum.SATOSHIS:\n return value;\n default:\n const currencyValue = (value / _chain_js__WEBPACK_IMPORTED_MODULE_1__.bchParam.subUnits) *\n (await _rate_ExchangeRate_js__WEBPACK_IMPORTED_MODULE_0__.ExchangeRate.get(_config_js__WEBPACK_IMPORTED_MODULE_2__.Config.DefaultCurrency, priceCache));\n return Number(currencyValue.toFixed(2));\n }\n}\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/util/balanceObjectFromSatoshi.ts?");
|
|
377
|
+
eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"asSendRequestObject\": () => (/* binding */ asSendRequestObject)\n/* harmony export */ });\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/base64.js\");\n/* harmony import */ var _wallet_model_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../wallet/model.js */ \"./src/wallet/model.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_wallet_model_js__WEBPACK_IMPORTED_MODULE_0__]);\n_wallet_model_js__WEBPACK_IMPORTED_MODULE_0__ = (__webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__)[0];\n\n\nfunction asSendRequestObject(requests) {\n let resp = [];\n if (Array.isArray(requests)) {\n requests.forEach((r) => {\n // the SendRequestArray[] case\n if (Array.isArray(r)) {\n if (r[0] === \"OP_RETURN\") {\n // ['OP_RETURN', utf8ToBin('MEMO\\x10')],\n resp.push(_wallet_model_js__WEBPACK_IMPORTED_MODULE_0__.OpReturnData.from(r[1]));\n }\n else if (r[0] === \"OP_RETURNB64\") {\n resp.push(_wallet_model_js__WEBPACK_IMPORTED_MODULE_0__.OpReturnData.fromUint8Array(Uint8Array.from((0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.base64ToBin)(r[1]))));\n }\n else {\n // ['cashaddr', 120] or ['cashaddr', 120n],\n resp.push(new _wallet_model_js__WEBPACK_IMPORTED_MODULE_0__.SendRequest({\n cashaddr: r[0],\n value: typeof r[1] === \"number\"\n ? BigInt(Math.floor[1])\n : r[1],\n }));\n }\n }\n else {\n // SendRequest | TokenSendRequest | OpReturnRequest case\n resp.push(convertToClass(r));\n }\n });\n }\n else {\n // the SendRequest | OpReturnData object case\n resp.push(convertToClass(requests));\n }\n return resp;\n}\nfunction convertToClass(object) {\n if (object.hasOwnProperty(\"category\")) {\n return new _wallet_model_js__WEBPACK_IMPORTED_MODULE_0__.TokenSendRequest(object);\n }\n else if (object.hasOwnProperty(\"buffer\")) {\n return _wallet_model_js__WEBPACK_IMPORTED_MODULE_0__.OpReturnData.fromUint8Array(object.buffer);\n }\n // endcoding in REST\n else if (object.hasOwnProperty(\"dataString\")) {\n return _wallet_model_js__WEBPACK_IMPORTED_MODULE_0__.OpReturnData.fromString(object.dataString);\n }\n else if (object.hasOwnProperty(\"dataBuffer\")) {\n return _wallet_model_js__WEBPACK_IMPORTED_MODULE_0__.OpReturnData.fromUint8Array(Uint8Array.from((0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.base64ToBin)(object.dataBuffer)));\n }\n else if (object.hasOwnProperty(\"cashaddr\") &&\n object.hasOwnProperty(\"value\") &&\n object.hasOwnProperty(\"category\") === false) {\n return new _wallet_model_js__WEBPACK_IMPORTED_MODULE_0__.SendRequest(object);\n }\n throw new Error(\"Unsupported send object\");\n}\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/util/asSendRequestObject.ts?");
|
|
388
378
|
|
|
389
379
|
/***/ }),
|
|
390
380
|
|
|
@@ -434,7 +424,7 @@ eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__
|
|
|
434
424
|
\*****************************/
|
|
435
425
|
/***/ ((module, __webpack_exports__, __webpack_require__) => {
|
|
436
426
|
|
|
437
|
-
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 */ \"convert\": () => (/* binding */ convert),\n/* harmony export */ \"convertObject\": () => (/* binding */ convertObject)\n/* harmony export */ });\n/* harmony import */ var _amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./amountInSatoshi.js */ \"./src/util/amountInSatoshi.ts\");\n/* harmony import */ var _satoshiToAmount_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./satoshiToAmount.js */ \"./src/util/satoshiToAmount.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_0__, _satoshiToAmount_js__WEBPACK_IMPORTED_MODULE_1__]);\n([_amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_0__, _satoshiToAmount_js__WEBPACK_IMPORTED_MODULE_1__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\n/**\n * convert transforms unit of measurement for some monetary value\n *\n * @param {value} number amount to convert\n * @param {from} any unit of measurement to convert from\n * @param {to} any unit of measurement to convert to\n *\n * @returns a promise to the value in \"to\" units\n */\nasync function convert(value, from, to) {\n let satoshi = await (0,_amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_0__.amountInSatoshi)(value, from);\n return (0,_satoshiToAmount_js__WEBPACK_IMPORTED_MODULE_1__.satoshiToAmount)(satoshi, to);\n}\nasync function convertObject({ value, from, to, }) {\n return await convert(value, from, to);\n}\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/util/convert.ts?");
|
|
427
|
+
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 */ \"convert\": () => (/* binding */ convert),\n/* harmony export */ \"convertObject\": () => (/* binding */ convertObject),\n/* harmony export */ \"toBch\": () => (/* binding */ toBch),\n/* harmony export */ \"toCurrency\": () => (/* binding */ toCurrency),\n/* harmony export */ \"toSat\": () => (/* binding */ toSat)\n/* harmony export */ });\n/* harmony import */ var _chain_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../chain.js */ \"./src/chain.ts\");\n/* harmony import */ var _amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./amountInSatoshi.js */ \"./src/util/amountInSatoshi.ts\");\n/* harmony import */ var _satoshiToAmount_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./satoshiToAmount.js */ \"./src/util/satoshiToAmount.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_0__, _satoshiToAmount_js__WEBPACK_IMPORTED_MODULE_1__]);\n([_amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_0__, _satoshiToAmount_js__WEBPACK_IMPORTED_MODULE_1__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\n\n/**\n * convert transforms unit of measurement for some monetary value\n *\n * @param {value} number amount to convert\n * @param {from} any unit of measurement to convert from\n * @param {to} any unit of measurement to convert to\n *\n * @returns a promise to the value in \"to\" units\n */\nasync function convert(value, from, to) {\n let satoshi = await (0,_amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_0__.amountInSatoshi)(value, from);\n return (0,_satoshiToAmount_js__WEBPACK_IMPORTED_MODULE_1__.satoshiToAmount)(satoshi, to);\n}\nasync function convertObject({ value, from, to, }) {\n return await convert(value, from, to);\n}\n// sats -> bch\nfunction toBch(sats) {\n return Number(sats) / Number(_chain_js__WEBPACK_IMPORTED_MODULE_2__.bchParam.subUnits);\n}\n// bch -> sats\nfunction toSat(bch) {\n return BigInt(Math.round(Number(bch) * Number(_chain_js__WEBPACK_IMPORTED_MODULE_2__.bchParam.subUnits)));\n}\nasync function toCurrency(sats, currency) {\n return convert(Number(sats), \"sat\", currency);\n}\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/util/convert.ts?");
|
|
438
428
|
|
|
439
429
|
/***/ }),
|
|
440
430
|
|
|
@@ -478,16 +468,6 @@ eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__
|
|
|
478
468
|
|
|
479
469
|
/***/ }),
|
|
480
470
|
|
|
481
|
-
/***/ "./src/util/floor.ts":
|
|
482
|
-
/*!***************************!*\
|
|
483
|
-
!*** ./src/util/floor.ts ***!
|
|
484
|
-
\***************************/
|
|
485
|
-
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
|
|
486
|
-
|
|
487
|
-
eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"floor\": () => (/* binding */ floor)\n/* harmony export */ });\nfunction floor(value, precision) {\n var multiplier = Math.pow(10, precision || 0);\n return Math.floor(value * multiplier) / multiplier;\n}\n\n\n//# sourceURL=webpack://mainnet-js/./src/util/floor.ts?");
|
|
488
|
-
|
|
489
|
-
/***/ }),
|
|
490
|
-
|
|
491
471
|
/***/ "./src/util/getAddrsByXpubKey.ts":
|
|
492
472
|
/*!***************************************!*\
|
|
493
473
|
!*** ./src/util/getAddrsByXpubKey.ts ***!
|
|
@@ -564,7 +544,7 @@ eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__
|
|
|
564
544
|
\***************************/
|
|
565
545
|
/***/ ((module, __webpack_exports__, __webpack_require__) => {
|
|
566
546
|
|
|
567
|
-
eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"ExchangeRate\": () => (/* reexport safe */ _rate_ExchangeRate_js__WEBPACK_IMPORTED_MODULE_16__.ExchangeRate),\n/* harmony export */ \"RuntimePlatform\": () => (/* reexport safe */ _getRuntimePlatform_js__WEBPACK_IMPORTED_MODULE_13__.RuntimePlatform),\n/* harmony export */ \"amountInSatoshi\": () => (/* reexport safe */ _amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_0__.amountInSatoshi),\n/* harmony export */ \"asSendRequestObject\": () => (/* reexport safe */ _asSendRequestObject_js__WEBPACK_IMPORTED_MODULE_1__.asSendRequestObject),\n/* harmony export */ \"atob\": () => (/* reexport safe */ _base64_js__WEBPACK_IMPORTED_MODULE_2__.atob),\n/* harmony export */ \"balanceFromSatoshi\": () => (/* reexport safe */ _balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_22__.balanceFromSatoshi),\n/* harmony export */ \"balanceResponseFromSatoshi\": () => (/* reexport safe */ _balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_22__.balanceResponseFromSatoshi),\n/* harmony export */ \"binToBase64\": () => (/* reexport safe */ _bitauth_libauth__WEBPACK_IMPORTED_MODULE_5__.binToBase64),\n/* harmony export */ \"binToHex\": () => (/* reexport safe */ _bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.binToHex),\n/* harmony export */ \"btoa\": () => (/* reexport safe */ _base64_js__WEBPACK_IMPORTED_MODULE_2__.btoa),\n/* harmony export */ \"checkTokenaddr\": () => (/* reexport safe */ _deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_11__.checkTokenaddr),\n/* harmony export */ \"checkUtxos\": () => (/* reexport safe */ _checkUtxos_js__WEBPACK_IMPORTED_MODULE_24__.checkUtxos),\n/* harmony export */ \"convert\": () => (/* reexport safe */ _convert_js__WEBPACK_IMPORTED_MODULE_7__.convert),\n/* harmony export */ \"convertAddress\": () => (/* reexport safe */ _deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_11__.convertAddress),\n/* harmony export */ \"convertObject\": () => (/* reexport safe */ _convert_js__WEBPACK_IMPORTED_MODULE_7__.convertObject),\n/* harmony export */ \"decodeHeader\": () => (/* reexport safe */ _header_js__WEBPACK_IMPORTED_MODULE_23__.decodeHeader),\n/* harmony export */ \"delay\": () => (/* reexport safe */ _delay_js__WEBPACK_IMPORTED_MODULE_8__.delay),\n/* harmony export */ \"deriveCashaddr\": () => (/* reexport safe */ _deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_11__.deriveCashaddr),\n/* harmony export */ \"derivePublicKeyHash\": () => (/* reexport safe */ _derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_10__.derivePublicKeyHash),\n/* harmony export */ \"deriveTokenaddr\": () => (/* reexport safe */ _deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_11__.deriveTokenaddr),\n/* harmony export */ \"derivedNetwork\": () => (/* reexport safe */ _deriveNetwork_js__WEBPACK_IMPORTED_MODULE_9__.derivedNetwork),\n/* harmony export */ \"getAddrsByXpubKey\": () => (/* reexport safe */ _util_getAddrsByXpubKey_js__WEBPACK_IMPORTED_MODULE_12__.getAddrsByXpubKey),\n/* harmony export */ \"getAddrsByXpubKeyObject\": () => (/* reexport safe */ _util_getAddrsByXpubKey_js__WEBPACK_IMPORTED_MODULE_12__.getAddrsByXpubKeyObject),\n/* harmony export */ \"getRuntimePlatform\": () => (/* reexport safe */ _getRuntimePlatform_js__WEBPACK_IMPORTED_MODULE_13__.getRuntimePlatform),\n/* harmony export */ \"getUsdRate\": () => (/* reexport safe */ _getUsdRate_js__WEBPACK_IMPORTED_MODULE_14__.getUsdRate),\n/* harmony export */ \"getWeakRandomInt\": () => (/* reexport safe */ _randomInt_js__WEBPACK_IMPORTED_MODULE_19__.getWeakRandomInt),\n/* harmony export */ \"getXPubKey\": () => (/* reexport safe */ _util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_20__.getXPubKey),\n/* harmony export */ \"getXpubKeyInfo\": () => (/* reexport safe */ _util_getAddrsByXpubKey_js__WEBPACK_IMPORTED_MODULE_12__.getXpubKeyInfo),\n/* harmony export */ \"getXpubKeyInfoObject\": () => (/* reexport safe */ _util_getAddrsByXpubKey_js__WEBPACK_IMPORTED_MODULE_12__.getXpubKeyInfoObject),\n/* harmony export */ \"hash160\": () => (/* reexport safe */ _hash160_js__WEBPACK_IMPORTED_MODULE_15__.hash160),\n/* harmony export */ \"hexToBin\": () => (/* reexport safe */ _bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.hexToBin),\n/* harmony export */ \"isTokenaddr\": () => (/* reexport safe */ _deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_11__.isTokenaddr),\n/* harmony export */ \"isValidAddress\": () => (/* reexport safe */ _deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_11__.isValidAddress),\n/* harmony export */ \"sanitizeAddress\": () => (/* reexport safe */ _sanitizeAddress_js__WEBPACK_IMPORTED_MODULE_17__.sanitizeAddress),\n/* harmony export */ \"sanitizeUnit\": () => (/* reexport safe */ _sanitizeUnit_js__WEBPACK_IMPORTED_MODULE_18__.sanitizeUnit),\n/* harmony export */ \"sha256\": () => (/* reexport safe */ _bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__.sha256),\n/* harmony export */ \"sumTokenAmounts\": () => (/* reexport safe */ _sumUtxoValue_js__WEBPACK_IMPORTED_MODULE_21__.sumTokenAmounts),\n/* harmony export */ \"sumUtxoValue\": () => (/* reexport safe */ _sumUtxoValue_js__WEBPACK_IMPORTED_MODULE_21__.sumUtxoValue),\n/* harmony export */ \"toCashaddr\": () => (/* reexport safe */ _deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_11__.toCashaddr),\n/* harmony export */ \"toTokenaddr\": () => (/* reexport safe */ _deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_11__.toTokenaddr),\n/* harmony export */ \"utf8ToBin\": () => (/* reexport safe */ _bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__.utf8ToBin)\n/* harmony export */ });\n/* harmony import */ var _amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./amountInSatoshi.js */ \"./src/util/amountInSatoshi.ts\");\n/* harmony import */ var _asSendRequestObject_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./asSendRequestObject.js */ \"./src/util/asSendRequestObject.ts\");\n/* harmony import */ var _base64_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./base64.js */ \"./src/util/base64.ts\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/hex.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/utf8.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/base64.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/crypto/default-crypto-instances.js\");\n/* harmony import */ var _convert_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./convert.js */ \"./src/util/convert.ts\");\n/* harmony import */ var _delay_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./delay.js */ \"./src/util/delay.ts\");\n/* harmony import */ var _deriveNetwork_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./deriveNetwork.js */ \"./src/util/deriveNetwork.ts\");\n/* harmony import */ var _derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./derivePublicKeyHash.js */ \"./src/util/derivePublicKeyHash.ts\");\n/* harmony import */ var _deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./deriveCashaddr.js */ \"./src/util/deriveCashaddr.ts\");\n/* harmony import */ var _util_getAddrsByXpubKey_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../util/getAddrsByXpubKey.js */ \"./src/util/getAddrsByXpubKey.ts\");\n/* harmony import */ var _getRuntimePlatform_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./getRuntimePlatform.js */ \"./src/util/getRuntimePlatform.ts\");\n/* harmony import */ var _getUsdRate_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./getUsdRate.js */ \"./src/util/getUsdRate.ts\");\n/* harmony import */ var _hash160_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./hash160.js */ \"./src/util/hash160.ts\");\n/* harmony import */ var _rate_ExchangeRate_js__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../rate/ExchangeRate.js */ \"./src/rate/ExchangeRate.ts\");\n/* harmony import */ var _sanitizeAddress_js__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./sanitizeAddress.js */ \"./src/util/sanitizeAddress.ts\");\n/* harmony import */ var _sanitizeUnit_js__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./sanitizeUnit.js */ \"./src/util/sanitizeUnit.ts\");\n/* harmony import */ var _randomInt_js__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./randomInt.js */ \"./src/util/randomInt.ts\");\n/* harmony import */ var _util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ../util/getXPubKey.js */ \"./src/util/getXPubKey.ts\");\n/* harmony import */ var _sumUtxoValue_js__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ./sumUtxoValue.js */ \"./src/util/sumUtxoValue.ts\");\n/* harmony import */ var _balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ./balanceObjectFromSatoshi.js */ \"./src/util/balanceObjectFromSatoshi.ts\");\n/* harmony import */ var _header_js__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! ./header.js */ \"./src/util/header.ts\");\n/* harmony import */ var _checkUtxos_js__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(/*! ./checkUtxos.js */ \"./src/util/checkUtxos.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_0__, _asSendRequestObject_js__WEBPACK_IMPORTED_MODULE_1__, _base64_js__WEBPACK_IMPORTED_MODULE_2__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__, _convert_js__WEBPACK_IMPORTED_MODULE_7__, _deriveNetwork_js__WEBPACK_IMPORTED_MODULE_9__, _derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_10__, _deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_11__, _util_getAddrsByXpubKey_js__WEBPACK_IMPORTED_MODULE_12__, _hash160_js__WEBPACK_IMPORTED_MODULE_15__, _sanitizeAddress_js__WEBPACK_IMPORTED_MODULE_17__, _util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_20__, _balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_22__, _header_js__WEBPACK_IMPORTED_MODULE_23__]);\n([_amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_0__, _asSendRequestObject_js__WEBPACK_IMPORTED_MODULE_1__, _base64_js__WEBPACK_IMPORTED_MODULE_2__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__, _convert_js__WEBPACK_IMPORTED_MODULE_7__, _deriveNetwork_js__WEBPACK_IMPORTED_MODULE_9__, _derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_10__, _deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_11__, _util_getAddrsByXpubKey_js__WEBPACK_IMPORTED_MODULE_12__, _hash160_js__WEBPACK_IMPORTED_MODULE_15__, _sanitizeAddress_js__WEBPACK_IMPORTED_MODULE_17__, _util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_20__, _balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_22__, _header_js__WEBPACK_IMPORTED_MODULE_23__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/util/index.ts?");
|
|
547
|
+
eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"ExchageRatePromise\": () => (/* reexport safe */ _rate_ExchangeRate_js__WEBPACK_IMPORTED_MODULE_16__.ExchageRatePromise),\n/* harmony export */ \"ExchangeRate\": () => (/* reexport safe */ _rate_ExchangeRate_js__WEBPACK_IMPORTED_MODULE_16__.ExchangeRate),\n/* harmony export */ \"RuntimePlatform\": () => (/* reexport safe */ _getRuntimePlatform_js__WEBPACK_IMPORTED_MODULE_13__.RuntimePlatform),\n/* harmony export */ \"amountInSatoshi\": () => (/* reexport safe */ _amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_0__.amountInSatoshi),\n/* harmony export */ \"asSendRequestObject\": () => (/* reexport safe */ _asSendRequestObject_js__WEBPACK_IMPORTED_MODULE_1__.asSendRequestObject),\n/* harmony export */ \"atob\": () => (/* reexport safe */ _base64_js__WEBPACK_IMPORTED_MODULE_2__.atob),\n/* harmony export */ \"binToBase64\": () => (/* reexport safe */ _bitauth_libauth__WEBPACK_IMPORTED_MODULE_5__.binToBase64),\n/* harmony export */ \"binToHex\": () => (/* reexport safe */ _bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.binToHex),\n/* harmony export */ \"btoa\": () => (/* reexport safe */ _base64_js__WEBPACK_IMPORTED_MODULE_2__.btoa),\n/* harmony export */ \"checkTokenaddr\": () => (/* reexport safe */ _deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_11__.checkTokenaddr),\n/* harmony export */ \"checkUtxos\": () => (/* reexport safe */ _checkUtxos_js__WEBPACK_IMPORTED_MODULE_23__.checkUtxos),\n/* harmony export */ \"convert\": () => (/* reexport safe */ _convert_js__WEBPACK_IMPORTED_MODULE_7__.convert),\n/* harmony export */ \"convertAddress\": () => (/* reexport safe */ _deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_11__.convertAddress),\n/* harmony export */ \"convertObject\": () => (/* reexport safe */ _convert_js__WEBPACK_IMPORTED_MODULE_7__.convertObject),\n/* harmony export */ \"decodeHeader\": () => (/* reexport safe */ _header_js__WEBPACK_IMPORTED_MODULE_22__.decodeHeader),\n/* harmony export */ \"delay\": () => (/* reexport safe */ _delay_js__WEBPACK_IMPORTED_MODULE_8__.delay),\n/* harmony export */ \"deriveCashaddr\": () => (/* reexport safe */ _deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_11__.deriveCashaddr),\n/* harmony export */ \"derivePublicKeyHash\": () => (/* reexport safe */ _derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_10__.derivePublicKeyHash),\n/* harmony export */ \"deriveTokenaddr\": () => (/* reexport safe */ _deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_11__.deriveTokenaddr),\n/* harmony export */ \"derivedNetwork\": () => (/* reexport safe */ _deriveNetwork_js__WEBPACK_IMPORTED_MODULE_9__.derivedNetwork),\n/* harmony export */ \"getAddrsByXpubKey\": () => (/* reexport safe */ _util_getAddrsByXpubKey_js__WEBPACK_IMPORTED_MODULE_12__.getAddrsByXpubKey),\n/* harmony export */ \"getAddrsByXpubKeyObject\": () => (/* reexport safe */ _util_getAddrsByXpubKey_js__WEBPACK_IMPORTED_MODULE_12__.getAddrsByXpubKeyObject),\n/* harmony export */ \"getRuntimePlatform\": () => (/* reexport safe */ _getRuntimePlatform_js__WEBPACK_IMPORTED_MODULE_13__.getRuntimePlatform),\n/* harmony export */ \"getUsdRate\": () => (/* reexport safe */ _getUsdRate_js__WEBPACK_IMPORTED_MODULE_14__.getUsdRate),\n/* harmony export */ \"getWeakRandomInt\": () => (/* reexport safe */ _randomInt_js__WEBPACK_IMPORTED_MODULE_19__.getWeakRandomInt),\n/* harmony export */ \"getXPubKey\": () => (/* reexport safe */ _util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_20__.getXPubKey),\n/* harmony export */ \"getXpubKeyInfo\": () => (/* reexport safe */ _util_getAddrsByXpubKey_js__WEBPACK_IMPORTED_MODULE_12__.getXpubKeyInfo),\n/* harmony export */ \"getXpubKeyInfoObject\": () => (/* reexport safe */ _util_getAddrsByXpubKey_js__WEBPACK_IMPORTED_MODULE_12__.getXpubKeyInfoObject),\n/* harmony export */ \"hash160\": () => (/* reexport safe */ _hash160_js__WEBPACK_IMPORTED_MODULE_15__.hash160),\n/* harmony export */ \"hexToBin\": () => (/* reexport safe */ _bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.hexToBin),\n/* harmony export */ \"isTokenaddr\": () => (/* reexport safe */ _deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_11__.isTokenaddr),\n/* harmony export */ \"isValidAddress\": () => (/* reexport safe */ _deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_11__.isValidAddress),\n/* harmony export */ \"sanitizeAddress\": () => (/* reexport safe */ _sanitizeAddress_js__WEBPACK_IMPORTED_MODULE_17__.sanitizeAddress),\n/* harmony export */ \"sanitizeUnit\": () => (/* reexport safe */ _sanitizeUnit_js__WEBPACK_IMPORTED_MODULE_18__.sanitizeUnit),\n/* harmony export */ \"sha256\": () => (/* reexport safe */ _bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__.sha256),\n/* harmony export */ \"sumTokenAmounts\": () => (/* reexport safe */ _sumUtxoValue_js__WEBPACK_IMPORTED_MODULE_21__.sumTokenAmounts),\n/* harmony export */ \"sumUtxoValue\": () => (/* reexport safe */ _sumUtxoValue_js__WEBPACK_IMPORTED_MODULE_21__.sumUtxoValue),\n/* harmony export */ \"toBch\": () => (/* reexport safe */ _convert_js__WEBPACK_IMPORTED_MODULE_7__.toBch),\n/* harmony export */ \"toCashaddr\": () => (/* reexport safe */ _deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_11__.toCashaddr),\n/* harmony export */ \"toCurrency\": () => (/* reexport safe */ _convert_js__WEBPACK_IMPORTED_MODULE_7__.toCurrency),\n/* harmony export */ \"toSat\": () => (/* reexport safe */ _convert_js__WEBPACK_IMPORTED_MODULE_7__.toSat),\n/* harmony export */ \"toTokenaddr\": () => (/* reexport safe */ _deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_11__.toTokenaddr),\n/* harmony export */ \"utf8ToBin\": () => (/* reexport safe */ _bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__.utf8ToBin)\n/* harmony export */ });\n/* harmony import */ var _amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./amountInSatoshi.js */ \"./src/util/amountInSatoshi.ts\");\n/* harmony import */ var _asSendRequestObject_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./asSendRequestObject.js */ \"./src/util/asSendRequestObject.ts\");\n/* harmony import */ var _base64_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./base64.js */ \"./src/util/base64.ts\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/hex.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/utf8.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/base64.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/crypto/default-crypto-instances.js\");\n/* harmony import */ var _convert_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./convert.js */ \"./src/util/convert.ts\");\n/* harmony import */ var _delay_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./delay.js */ \"./src/util/delay.ts\");\n/* harmony import */ var _deriveNetwork_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./deriveNetwork.js */ \"./src/util/deriveNetwork.ts\");\n/* harmony import */ var _derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./derivePublicKeyHash.js */ \"./src/util/derivePublicKeyHash.ts\");\n/* harmony import */ var _deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./deriveCashaddr.js */ \"./src/util/deriveCashaddr.ts\");\n/* harmony import */ var _util_getAddrsByXpubKey_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../util/getAddrsByXpubKey.js */ \"./src/util/getAddrsByXpubKey.ts\");\n/* harmony import */ var _getRuntimePlatform_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./getRuntimePlatform.js */ \"./src/util/getRuntimePlatform.ts\");\n/* harmony import */ var _getUsdRate_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./getUsdRate.js */ \"./src/util/getUsdRate.ts\");\n/* harmony import */ var _hash160_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./hash160.js */ \"./src/util/hash160.ts\");\n/* harmony import */ var _rate_ExchangeRate_js__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../rate/ExchangeRate.js */ \"./src/rate/ExchangeRate.ts\");\n/* harmony import */ var _sanitizeAddress_js__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./sanitizeAddress.js */ \"./src/util/sanitizeAddress.ts\");\n/* harmony import */ var _sanitizeUnit_js__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./sanitizeUnit.js */ \"./src/util/sanitizeUnit.ts\");\n/* harmony import */ var _randomInt_js__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./randomInt.js */ \"./src/util/randomInt.ts\");\n/* harmony import */ var _util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ../util/getXPubKey.js */ \"./src/util/getXPubKey.ts\");\n/* harmony import */ var _sumUtxoValue_js__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ./sumUtxoValue.js */ \"./src/util/sumUtxoValue.ts\");\n/* harmony import */ var _header_js__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ./header.js */ \"./src/util/header.ts\");\n/* harmony import */ var _checkUtxos_js__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! ./checkUtxos.js */ \"./src/util/checkUtxos.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_0__, _asSendRequestObject_js__WEBPACK_IMPORTED_MODULE_1__, _base64_js__WEBPACK_IMPORTED_MODULE_2__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__, _convert_js__WEBPACK_IMPORTED_MODULE_7__, _deriveNetwork_js__WEBPACK_IMPORTED_MODULE_9__, _derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_10__, _deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_11__, _util_getAddrsByXpubKey_js__WEBPACK_IMPORTED_MODULE_12__, _hash160_js__WEBPACK_IMPORTED_MODULE_15__, _sanitizeAddress_js__WEBPACK_IMPORTED_MODULE_17__, _util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_20__, _header_js__WEBPACK_IMPORTED_MODULE_22__]);\n([_amountInSatoshi_js__WEBPACK_IMPORTED_MODULE_0__, _asSendRequestObject_js__WEBPACK_IMPORTED_MODULE_1__, _base64_js__WEBPACK_IMPORTED_MODULE_2__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__, _convert_js__WEBPACK_IMPORTED_MODULE_7__, _deriveNetwork_js__WEBPACK_IMPORTED_MODULE_9__, _derivePublicKeyHash_js__WEBPACK_IMPORTED_MODULE_10__, _deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_11__, _util_getAddrsByXpubKey_js__WEBPACK_IMPORTED_MODULE_12__, _hash160_js__WEBPACK_IMPORTED_MODULE_15__, _sanitizeAddress_js__WEBPACK_IMPORTED_MODULE_17__, _util_getXPubKey_js__WEBPACK_IMPORTED_MODULE_20__, _header_js__WEBPACK_IMPORTED_MODULE_22__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/util/index.ts?");
|
|
568
548
|
|
|
569
549
|
/***/ }),
|
|
570
550
|
|
|
@@ -614,7 +594,7 @@ eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harm
|
|
|
614
594
|
\*************************************/
|
|
615
595
|
/***/ ((module, __webpack_exports__, __webpack_require__) => {
|
|
616
596
|
|
|
617
|
-
eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"satoshiToAmount\": () => (/* binding */ satoshiToAmount)\n/* harmony export */ });\n/* harmony import */ var _chain_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../chain.js */ \"./src/chain.ts\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../enum.js */ \"./src/enum.ts\");\n/* harmony import */ var _rate_ExchangeRate_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../rate/ExchangeRate.js */ \"./src/rate/ExchangeRate.ts\");\n/* harmony import */ var _util_sanitizeUnit_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/sanitizeUnit.js */ \"./src/util/sanitizeUnit.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_enum_js__WEBPACK_IMPORTED_MODULE_2__]);\n_enum_js__WEBPACK_IMPORTED_MODULE_2__ = (__webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__)[0];\n\n\n\n\n/**\n * converts given value and unit from satoshi\n *\n * @param {value} number some value in satoshi\n * @param {rawUnit} any the target unit\n *\n * @returns a promise to the value in the unit of account given by rawUnit\n */\nasync function satoshiToAmount(value, rawUnit) {\n const unit = (0,_util_sanitizeUnit_js__WEBPACK_IMPORTED_MODULE_1__.sanitizeUnit)(rawUnit);\n switch (unit) {\n case _enum_js__WEBPACK_IMPORTED_MODULE_2__.UnitEnum.BCH:\n return value / _chain_js__WEBPACK_IMPORTED_MODULE_3__.bchParam.subUnits;\n case _enum_js__WEBPACK_IMPORTED_MODULE_2__.UnitEnum.
|
|
597
|
+
eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"satoshiToAmount\": () => (/* binding */ satoshiToAmount)\n/* harmony export */ });\n/* harmony import */ var _chain_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../chain.js */ \"./src/chain.ts\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../enum.js */ \"./src/enum.ts\");\n/* harmony import */ var _rate_ExchangeRate_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../rate/ExchangeRate.js */ \"./src/rate/ExchangeRate.ts\");\n/* harmony import */ var _util_sanitizeUnit_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/sanitizeUnit.js */ \"./src/util/sanitizeUnit.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_enum_js__WEBPACK_IMPORTED_MODULE_2__]);\n_enum_js__WEBPACK_IMPORTED_MODULE_2__ = (__webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__)[0];\n\n\n\n\n/**\n * converts given value and unit from satoshi\n *\n * @param {value} number some value in satoshi\n * @param {rawUnit} any the target unit\n *\n * @returns a promise to the value in the unit of account given by rawUnit\n */\nasync function satoshiToAmount(value, rawUnit) {\n const unit = (0,_util_sanitizeUnit_js__WEBPACK_IMPORTED_MODULE_1__.sanitizeUnit)(rawUnit);\n switch (unit) {\n case _enum_js__WEBPACK_IMPORTED_MODULE_2__.UnitEnum.BCH:\n return Number(value) / Number(_chain_js__WEBPACK_IMPORTED_MODULE_3__.bchParam.subUnits);\n case _enum_js__WEBPACK_IMPORTED_MODULE_2__.UnitEnum.SAT:\n return Number(value);\n default:\n const Currency_over_BCH = await _rate_ExchangeRate_js__WEBPACK_IMPORTED_MODULE_0__.ExchangeRate.get(rawUnit);\n // truncate currency amounts to fixed precision (2),\n // then return the fixed value string as a float.\n const currencyValue = Number(Number(value) * (Currency_over_BCH / Number(_chain_js__WEBPACK_IMPORTED_MODULE_3__.bchParam.subUnits))).toFixed(2);\n return Number.parseFloat(currencyValue);\n }\n}\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/util/satoshiToAmount.ts?");
|
|
618
598
|
|
|
619
599
|
/***/ }),
|
|
620
600
|
|
|
@@ -624,7 +604,7 @@ eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__
|
|
|
624
604
|
\*******************************************/
|
|
625
605
|
/***/ ((module, __webpack_exports__, __webpack_require__) => {
|
|
626
606
|
|
|
627
|
-
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 */ \"sumSendRequestAmounts\": () => (/* binding */ sumSendRequestAmounts)\n/* harmony export */ });\n/* harmony import */ var _wallet_model_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../wallet/model.js */ \"./src/wallet/model.ts\");\
|
|
607
|
+
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 */ \"sumSendRequestAmounts\": () => (/* binding */ sumSendRequestAmounts)\n/* harmony export */ });\n/* harmony import */ var _wallet_model_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../wallet/model.js */ \"./src/wallet/model.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_wallet_model_js__WEBPACK_IMPORTED_MODULE_0__]);\n_wallet_model_js__WEBPACK_IMPORTED_MODULE_0__ = (__webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__)[0];\n\n// This function sums a list of send request objects\nasync function sumSendRequestAmounts(requests) {\n if (requests) {\n const balanceArray = await Promise.all(requests.map(async (r) => {\n if (r instanceof _wallet_model_js__WEBPACK_IMPORTED_MODULE_0__.SendRequest) {\n return r.value;\n }\n else if (r instanceof _wallet_model_js__WEBPACK_IMPORTED_MODULE_0__.TokenSendRequest) {\n return r.value || 1000n;\n }\n else\n return 0n;\n }));\n const balance = balanceArray.reduce(sumBalance, BigInt(0));\n return balance;\n }\n else {\n return BigInt(0);\n }\n}\nfunction sumBalance(a, b) {\n // a is zero or a number\n if (b instanceof Error) {\n throw b;\n }\n return BigInt(a) + BigInt(b);\n}\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/util/sumSendRequestAmounts.ts?");
|
|
628
608
|
|
|
629
609
|
/***/ }),
|
|
630
610
|
|
|
@@ -634,7 +614,7 @@ eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__
|
|
|
634
614
|
\**********************************/
|
|
635
615
|
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
|
|
636
616
|
|
|
637
|
-
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,
|
|
617
|
+
eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"sumTokenAmounts\": () => (/* binding */ sumTokenAmounts),\n/* harmony export */ \"sumUtxoValue\": () => (/* binding */ sumUtxoValue)\n/* harmony export */ });\nfunction sumUtxoValue(utxos) {\n if (utxos.length > 0) {\n const balanceArray = utxos.map((o) => {\n return o.satoshis;\n });\n const balance = balanceArray.reduce((a, b) => a + b, 0n);\n return balance;\n }\n else {\n return 0n;\n }\n}\nfunction sumTokenAmounts(utxos, tokenId) {\n if (utxos.length > 0) {\n const tokenArray = utxos\n .filter((utxo) => utxo.token?.category === tokenId)\n .map((o) => {\n return o.token?.amount || 0n;\n });\n const balance = tokenArray.reduce((a, b) => a + b, 0n);\n return balance;\n }\n else {\n return 0n;\n }\n}\n\n\n//# sourceURL=webpack://mainnet-js/./src/util/sumUtxoValue.ts?");
|
|
638
618
|
|
|
639
619
|
/***/ }),
|
|
640
620
|
|
|
@@ -654,7 +634,7 @@ eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__
|
|
|
654
634
|
\****************************/
|
|
655
635
|
/***/ ((module, __webpack_exports__, __webpack_require__) => {
|
|
656
636
|
|
|
657
|
-
eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"BaseWallet\": () => (/* binding */ BaseWallet),\n/* harmony export */ \"_checkContextSafety\": () => (/* binding */ _checkContextSafety),\n/* harmony export */ \"getNamedWalletId\": () => (/* binding */ getNamedWalletId),\n/* harmony export */ \"getStorageProvider\": () => (/* binding */ getStorageProvider),\n/* harmony export */ \"placeholderCashAddr\": () => (/* binding */ placeholderCashAddr),\n/* harmony export */ \"placeholderTokenAddr\": () => (/* binding */ placeholderTokenAddr)\n/* harmony export */ });\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/hex.js\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../enum.js */ \"./src/enum.ts\");\n/* harmony import */ var _interface_js__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../interface.js */ \"./src/interface.ts\");\n/* harmony import */ var _network_default_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../network/default.js */ \"./src/network/default.ts\");\n/* harmony import */ var _network_getRelayFeeCache_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../network/getRelayFeeCache.js */ \"./src/network/getRelayFeeCache.ts\");\n/* harmony import */ var _transaction_Wif_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../transaction/Wif.js */ \"./src/transaction/Wif.ts\");\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_checkUtxos_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../util/checkUtxos.js */ \"./src/util/checkUtxos.ts\");\n/* harmony import */ var _util_index_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../util/index.js */ \"./src/util/sumUtxoValue.ts\");\n/* harmony import */ var _util_index_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../util/index.js */ \"./src/util/amountInSatoshi.ts\");\n/* harmony import */ var _util_index_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../util/index.js */ \"./src/util/asSendRequestObject.ts\");\n/* harmony import */ var _util_index_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../util/index.js */ \"./src/util/deriveCashaddr.ts\");\n/* harmony import */ var _util_index_js__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ../util/index.js */ \"./src/util/getRuntimePlatform.ts\");\n/* harmony import */ var _util_sanitizeUnit_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../util/sanitizeUnit.js */ \"./src/util/sanitizeUnit.ts\");\n/* harmony import */ var _util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../util/sumSendRequestAmounts.js */ \"./src/util/sumSendRequestAmounts.ts\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./enum.js */ \"./src/wallet/enum.ts\");\n/* harmony import */ var _model_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./model.js */ \"./src/wallet/model.ts\");\n/* harmony import */ var _Util_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Util.js */ \"./src/wallet/Util.ts\");\n/* harmony import */ var _message_signed_js__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ../message/signed.js */ \"./src/message/signed.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_network_default_js__WEBPACK_IMPORTED_MODULE_0__, _enum_js__WEBPACK_IMPORTED_MODULE_2__, _Util_js__WEBPACK_IMPORTED_MODULE_3__, _util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_6__, _util_index_js__WEBPACK_IMPORTED_MODULE_8__, _model_js__WEBPACK_IMPORTED_MODULE_10__, _transaction_Wif_js__WEBPACK_IMPORTED_MODULE_11__, _util_index_js__WEBPACK_IMPORTED_MODULE_13__, _util_index_js__WEBPACK_IMPORTED_MODULE_14__, _util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_15__, _message_signed_js__WEBPACK_IMPORTED_MODULE_17__]);\n([_network_default_js__WEBPACK_IMPORTED_MODULE_0__, _enum_js__WEBPACK_IMPORTED_MODULE_2__, _Util_js__WEBPACK_IMPORTED_MODULE_3__, _util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_6__, _util_index_js__WEBPACK_IMPORTED_MODULE_8__, _model_js__WEBPACK_IMPORTED_MODULE_10__, _transaction_Wif_js__WEBPACK_IMPORTED_MODULE_11__, _util_index_js__WEBPACK_IMPORTED_MODULE_13__, _util_index_js__WEBPACK_IMPORTED_MODULE_14__, _util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_15__, _message_signed_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\n\n\n\nconst placeholderCashAddr = \"bitcoincash:qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqfnhks603\";\nconst placeholderTokenAddr = \"bitcoincash:zqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqweyg7usz\";\n/**\n * A class to hold features used by all wallets\n * @class BaseWallet\n */\nclass BaseWallet {\n get networkPrefix() {\n return _enum_js__WEBPACK_IMPORTED_MODULE_2__.prefixFromNetworkMap[this.network];\n }\n // interface to util functions. see Util.ts\n get util() {\n if (!this._util) {\n this._util = new _Util_js__WEBPACK_IMPORTED_MODULE_3__.Util(this.network);\n }\n return this._util;\n }\n // interface to util util. see Util.Util\n static get util() {\n return new this().util;\n }\n // Return wallet info\n getInfo() {\n throw Error(\"getInfo not implemented in BaseWallet\");\n }\n slpSemiAware(value = true) {\n this._slpSemiAware = value;\n return this;\n }\n //#region Accessors\n getNetworkProvider(\n // @ts-ignore\n network = _enum_js__WEBPACK_IMPORTED_MODULE_2__.NetworkType.Mainnet) {\n return (0,_network_default_js__WEBPACK_IMPORTED_MODULE_0__.getNetworkProvider)(network);\n }\n /**\n * getDepositAddress - get a wallet deposit address\n *\n * a high-level function,\n *\n * @see {@link https://rest-unstable.mainnet.cash/api-docs/#/wallet/depositAddress|/wallet/deposit_address} for REST endpoint\n *\n * @returns The deposit address as a string\n */\n getDepositAddress() {\n // return this.cashaddr;\n throw Error(\"getDepositAddress not implemented in BaseWallet\");\n }\n /**\n * getChangeAddress - get a wallet change address\n *\n * a high-level function,\n *\n * @see {@link https://rest-unstable.mainnet.cash/api-docs/#/wallet/changeAddress|/wallet/change_address} for REST endpoint\n *\n * @returns The change address as a string\n */\n getChangeAddress() {\n // return this.cashaddr;\n throw Error(\"getChangeAddress not implemented in BaseWallet\");\n }\n /**\n * getTokenDepositAddress - get a cashtoken aware wallet deposit address\n *\n * @returns The cashtoken aware deposit address as a string\n */\n getTokenDepositAddress() {\n // return this.tokenaddr;\n throw Error(\"getTokenDepositAddress not implemented in BaseWallet\");\n }\n /**\n * getTokenDepositAddress - get a cashtoken aware wallet deposit address\n *\n * @returns The cashtoken aware deposit address as a string\n */\n getTokenChangeAddress() {\n // return this.tokenaddr;\n throw Error(\"getTokenDepositAddress not implemented in BaseWallet\");\n }\n //#endregion Accessors\n //#region Constructors and Statics\n /**\n * constructor for a new wallet\n * @param network network for wallet\n *\n * @throws {Error} if called on BaseWallet\n */\n constructor(network = _enum_js__WEBPACK_IMPORTED_MODULE_2__.NetworkType.Mainnet) {\n this._slpSemiAware = false; // a flag which requires an utxo to have more than 546 sats to be spendable and counted in the balance\n this.name = \"\";\n this.network = network;\n this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Watch;\n this.provider = this.getNetworkProvider(this.network);\n this.isTestnet = this.network === _enum_js__WEBPACK_IMPORTED_MODULE_2__.NetworkType.Mainnet ? false : true;\n }\n //#endregion Constructors\n /**\n * named (internal) get a named wallet from the database or create a new one.\n * Note: this function should behave identically if\n *\n * @param {string} name name of the wallet\n * @param {string} dbName database name the wallet is stored in\n * @param {boolean} forceNew attempt to overwrite an existing wallet\n *\n * @throws {Error} if forceNew is true and the wallet already exists\n * @returns a promise to a named wallet\n */\n async named(name, dbName, forceNew = false) {\n if (name.length === 0) {\n throw Error(\"Named wallets must have a non-empty name\");\n }\n _checkContextSafety(this);\n this.name = name;\n dbName = dbName ? dbName : _enum_js__WEBPACK_IMPORTED_MODULE_2__.prefixFromNetworkMap[this.network];\n const db = getStorageProvider(dbName);\n // If there is a database, force saving or error\n if (db) {\n await db.init();\n const savedWalletRecord = await db.getWallet(name);\n if (savedWalletRecord) {\n await db.close();\n if (forceNew) {\n throw Error(`A wallet with the name ${name} already exists in ${dbName}`);\n }\n const recoveredWallet = await this.fromId(savedWalletRecord.wallet);\n recoveredWallet.name = savedWalletRecord.name;\n return recoveredWallet;\n }\n else {\n const wallet = await this.initialize();\n wallet.name = name;\n await db.addWallet(wallet.name, wallet.toDbString());\n await db.close();\n return wallet;\n }\n }\n else {\n throw Error(\"No database was available or configured to store the named wallet.\");\n }\n }\n /**\n * replaceNamed - Replace (recover) named wallet with a new walletId\n *\n * If wallet with a provided name does not exist yet, it will be created with a `walletId` supplied\n * If wallet exists it will be overwritten without exception\n *\n * @param name user friendly wallet alias\n * @param walletId walletId options to steer the creation process\n * @param dbName name under which the wallet will be stored in the database\n *\n * @returns instantiated wallet\n */\n async replaceNamed(name, walletId, dbName) {\n if (name.length === 0) {\n throw Error(\"Named wallets must have a non-empty name\");\n }\n _checkContextSafety(this);\n this.name = name;\n dbName = dbName ? dbName : _enum_js__WEBPACK_IMPORTED_MODULE_2__.prefixFromNetworkMap[this.network];\n let db = getStorageProvider(dbName);\n if (db) {\n await db.init();\n let savedWalletRecord = await db.getWallet(name);\n await this.fromId(walletId);\n if (savedWalletRecord) {\n await db.updateWallet(name, walletId);\n }\n else {\n await db.addWallet(name, walletId);\n }\n await db.close();\n return this;\n }\n else {\n throw Error(\"No database was available or configured to store the named wallet.\");\n }\n }\n /**\n * namedExists - check if a named wallet already exists\n *\n * @param name user friendly wallet alias\n * @param dbName name under which the wallet will be stored in the database\n *\n * @returns boolean\n */\n async namedExists(name, dbName) {\n if (name.length === 0) {\n throw Error(\"Named wallets must have a non-empty name\");\n }\n _checkContextSafety(this);\n dbName = dbName ? dbName : _enum_js__WEBPACK_IMPORTED_MODULE_2__.prefixFromNetworkMap[this.network];\n let db = getStorageProvider(dbName);\n if (db) {\n await db.init();\n let savedWalletRecord = await db.getWallet(name);\n await db.close();\n return savedWalletRecord !== undefined;\n }\n else {\n throw Error(\"No database was available or configured to store the named wallet.\");\n }\n }\n async initialize() {\n return this;\n }\n //#region Serialization\n /**\n * toDbString - store the serialized version of the wallet in the database, not just the name\n *\n * @throws {Error} if called on BaseWallet\n */\n toDbString() {\n return `${this.walletType}:${this.network}:${this.getDepositAddress()}`;\n }\n // Returns the serialized wallet as a string\n // If storing in a database, set asNamed to false to store secrets\n // In all other cases, the a named wallet is deserialized from the database\n // by the name key\n toString() {\n return `${this.walletType}:${this.network}:${this.getDepositAddress()}`;\n }\n //#endregion Serialization\n /**\n * explorerUrl Web url to a transaction on a block explorer\n *\n * @param txId transaction Id\n * @returns Url string\n */\n explorerUrl(txId) {\n const explorerUrlMap = {\n mainnet: \"https://blockchair.com/bitcoin-cash/transaction/\",\n testnet: \"https://www.blockchain.com/bch-testnet/tx/\",\n regtest: \"\",\n };\n return explorerUrlMap[this.network] + txId;\n }\n /**\n * named - create a named wallet\n *\n * @param name user friendly wallet alias\n * @param dbName name under which the wallet will be stored in the database\n * @param force force recreate wallet in the database if a record already exist\n *\n * @returns instantiated wallet\n */\n static async named(name, dbName, force) {\n return new this().named(name, dbName, force);\n }\n /**\n * replaceNamed - replace (recover) named wallet with a new walletId\n *\n * If wallet with a provided name does not exist yet, it will be created with a `walletId` supplied\n * If wallet exists it will be overwritten without exception\n *\n * @param name user friendly wallet alias\n * @param walletId walletId options to steer the creation process\n * @param dbName name under which the wallet will be stored in the database\n *\n * @returns instantiated wallet\n */\n static async replaceNamed(name, walletId, dbName) {\n return new this().replaceNamed(name, walletId, dbName);\n }\n /**\n * namedExists - check if a named wallet already exists\n *\n * @param name user friendly wallet alias\n * @param dbName name under which the wallet will be stored in the database\n *\n * @returns boolean\n */\n static async namedExists(name, dbName) {\n return new this().namedExists(name, dbName);\n }\n fromId(walletId) {\n throw Error(\"fromId not implemented in BaseWallet\");\n }\n //#region Funds\n /**\n * utxos Get unspent outputs for the wallet\n *\n */\n async getUtxos() {\n throw Error(\"getUtxos not implemented in BaseWallet\");\n }\n // gets wallet balance in sats, bch and currency\n async getBalance(rawUnit, priceCache = true) {\n if (rawUnit) {\n const unit = (0,_util_sanitizeUnit_js__WEBPACK_IMPORTED_MODULE_5__.sanitizeUnit)(rawUnit);\n return await (0,_util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_6__.balanceFromSatoshi)(await this.getBalanceFromProvider(), unit, priceCache);\n }\n else {\n return await (0,_util_balanceObjectFromSatoshi_js__WEBPACK_IMPORTED_MODULE_6__.balanceResponseFromSatoshi)(await this.getBalanceFromProvider(), priceCache);\n }\n }\n // Gets balance by summing value in all utxos in stats\n async getBalanceFromUtxos() {\n const utxos = (await this.getUtxos()).filter((val) => val.token === undefined);\n return (0,_util_index_js__WEBPACK_IMPORTED_MODULE_7__.sumUtxoValue)(utxos);\n }\n // Gets balance from fulcrum\n async getBalanceFromProvider() {\n // Fulcrum reports balance of all utxos, including tokens, which is undesirable\n // // TODO not sure why getting the balance from a provider doesn't work\n // if (this._slpAware || this._slpSemiAware) {\n // return await this.getBalanceFromUtxos();\n // } else {\n // return await this.provider.getBalance(this.cashaddr);\n // }\n // FIXME\n return this.getBalanceFromUtxos();\n }\n async getAddressUtxos(address) {\n throw Error(\"getAddressUtxos not implemented in BaseWallet\");\n }\n // watching for any transaction hash of this wallet\n async watchAddress(callback) {\n return this.provider.watchAddress(this.getDepositAddress(), callback);\n }\n // watching for any transaction of this wallet\n async watchAddressTransactions(callback) {\n return this.provider.watchAddressTransactions(this.getDepositAddress(), callback);\n }\n // watching for cashtoken transaction of this wallet\n async watchAddressTokenTransactions(callback) {\n return this.provider.watchAddressTokenTransactions(this.getDepositAddress(), callback);\n }\n // sets up a callback to be called upon wallet's balance change\n // can be cancelled by calling the function returned from this one\n async watchBalance(callback) {\n return this.provider.watchAddressStatus(this.getDepositAddress(), async (_status) => {\n const balance = (await this.getBalance());\n callback(balance);\n });\n }\n // sets up a callback to be called upon wallet's BCH or USD balance change\n // if BCH balance does not change, the callback will be triggered every\n // @param `usdPriceRefreshInterval` milliseconds by polling for new BCH USD price\n // Since we want to be most sensitive to usd value change, we do not use the cached exchange rates\n // can be cancelled by calling the function returned from this one\n async watchBalanceUsd(callback, usdPriceRefreshInterval = 30000) {\n let usdPrice = -1;\n const _callback = async () => {\n const balance = (await this.getBalance(undefined, false));\n if (usdPrice !== balance.usd) {\n usdPrice = balance.usd;\n callback(balance);\n }\n };\n const watchCancel = await this.provider.watchAddressStatus(this.getDepositAddress(), _callback);\n const interval = setInterval(_callback, usdPriceRefreshInterval);\n return async () => {\n await watchCancel?.();\n clearInterval(interval);\n };\n }\n // waits for address balance to be greater than or equal to the target value\n // this call halts the execution\n async waitForBalance(value, rawUnit = _enum_js__WEBPACK_IMPORTED_MODULE_2__.UnitEnum.BCH) {\n return new Promise(async (resolve) => {\n let watchCancel;\n watchCancel = await this.watchBalance(async (balance) => {\n const satoshiBalance = await (0,_util_index_js__WEBPACK_IMPORTED_MODULE_8__.amountInSatoshi)(value, rawUnit);\n if (balance.sat >= satoshiBalance) {\n await watchCancel?.();\n resolve(balance);\n }\n });\n });\n }\n // sets up a callback to be called upon wallet's token balance change\n // can be cancelled by calling the function returned from this one\n async watchTokenBalance(tokenId, callback) {\n let previous = undefined;\n return await this.provider.watchAddressStatus(this.getDepositAddress(), async (_status) => {\n const balance = await this.getTokenBalance(tokenId);\n if (previous != balance) {\n callback(balance);\n }\n previous = balance;\n });\n }\n // waits for address token balance to be greater than or equal to the target amount\n // this call halts the execution\n async waitForTokenBalance(tokenId, amount) {\n return new Promise(async (resolve) => {\n let watchCancel;\n watchCancel = await this.watchTokenBalance(tokenId, async (balance) => {\n if (balance >= amount) {\n await watchCancel?.();\n resolve(balance);\n }\n });\n });\n }\n async _getMaxAmountToSend(params = {\n outputCount: 1,\n options: {},\n }) {\n if (params.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_9__.checkUtxos)(params.options.utxoIds.map((utxoId) => typeof utxoId === \"string\" ? (0,_model_js__WEBPACK_IMPORTED_MODULE_10__.fromUtxoId)(utxoId) : utxoId), this);\n }\n else {\n utxos = (await this.getUtxos()).filter((utxo) => !utxo.token);\n }\n // Get current height to assure recently mined coins are not spent.\n const bestHeight = await this.provider.getBlockHeight();\n // simulate outputs using the sender's address\n const sendRequest = new _model_js__WEBPACK_IMPORTED_MODULE_10__.SendRequest({\n cashaddr: placeholderCashAddr,\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_11__.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_11__.getFeeAmountSimple)({\n utxos: fundingUtxos,\n sendRequests: sendRequests,\n sourceAddress: placeholderCashAddr,\n relayFeePerByteInSatoshi: relayFeePerByteInSatoshi,\n feePaidBy: feePaidBy,\n });\n const spendableAmount = (0,_util_index_js__WEBPACK_IMPORTED_MODULE_7__.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_6__.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_10__.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_12__.binToHex)(encodedTransaction);\n resp.sourceOutputs = sourceOutputs;\n }\n return resp;\n }\n /**\n * sendMax Send all available funds to a destination cash address\n *\n * @param {string} cashaddr destination cash address\n * @param {SendRequestOptionsI} options Options of the send requests\n *\n * @returns (depending on the options parameter) the transaction id, new address balance and a link to the transaction on the blockchain explorer\n */\n async sendMax(cashaddr, options) {\n return await this.sendMaxRaw(cashaddr, options);\n }\n /**\n * sendMaxRaw (internal) Send all available funds to a destination cash address\n *\n * @param {string} cashaddr destination cash address\n * @param {SendRequestOptionsI} options Options of the send requests\n *\n * @returns the transaction id sent to the network\n */\n async sendMaxRaw(cashaddr, options, privateKey) {\n const { value: maxSpendableAmount, utxos } = await this._getMaxAmountToSend({\n outputCount: 1,\n options: options,\n privateKey: privateKey,\n });\n if (!options) {\n options = {};\n }\n options.utxoIds = utxos;\n const sendRequest = new _model_js__WEBPACK_IMPORTED_MODULE_10__.SendRequest({\n cashaddr: cashaddr,\n value: maxSpendableAmount,\n unit: \"sat\",\n });\n const { encodedTransaction, tokenIds, sourceOutputs } = await this.encodeTransaction([sendRequest], true, options, privateKey);\n const resp = new _model_js__WEBPACK_IMPORTED_MODULE_10__.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_12__.binToHex)(encodedTransaction);\n resp.sourceOutputs = sourceOutputs;\n }\n return resp;\n }\n /**\n * encodeTransaction Encode and sign a transaction given a list of sendRequests, options and estimate fees.\n * @param {SendRequest[]} sendRequests SendRequests\n * @param {boolean} discardChange=false\n * @param {SendRequestOptionsI} options Options of the send requests\n */\n async encodeTransaction(requests, discardChange = false, options, privateKey) {\n let sendRequests = (0,_util_index_js__WEBPACK_IMPORTED_MODULE_13__.asSendRequestObject)(requests);\n if (options && options.slpSemiAware) {\n this._slpSemiAware = true;\n }\n let feePaidBy;\n if (options?.feePaidBy) {\n feePaidBy = options.feePaidBy;\n }\n else {\n feePaidBy = _enum_js__WEBPACK_IMPORTED_MODULE_4__.FeePaidByEnum.change;\n }\n let changeAddress;\n if (options?.changeAddress) {\n changeAddress = options.changeAddress;\n }\n else {\n changeAddress = this.getChangeAddress();\n }\n let checkTokenQuantities = true;\n if (options?.checkTokenQuantities === false) {\n checkTokenQuantities = false;\n }\n // get inputs from options or query all inputs\n let utxos = await this.getUtxos();\n if (options && options.utxoIds) {\n utxos = await (0,_util_checkUtxos_js__WEBPACK_IMPORTED_MODULE_9__.checkUtxos)(options.utxoIds.map((utxoId) => typeof utxoId === \"string\" ? (0,_model_js__WEBPACK_IMPORTED_MODULE_10__.fromUtxoId)(utxoId) : utxoId), utxos);\n }\n // filter out token utxos if there are no token requests\n if (checkTokenQuantities &&\n !sendRequests.some((val) => val instanceof _model_js__WEBPACK_IMPORTED_MODULE_10__.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_10__.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_10__.TokenSendRequest({\n cashaddr: (0,_util_index_js__WEBPACK_IMPORTED_MODULE_14__.toTokenaddr)(this.getChangeAddress()),\n amount: change,\n tokenId: tokenId,\n commitment: tokenOutputs[0].commitment,\n capability: tokenOutputs[0].capability,\n value: tokenOutputs[0].value,\n }));\n }\n }\n }\n };\n addTokenChangeOutputs(utxos, sendRequests);\n const bestHeight = await this.provider.getBlockHeight();\n const spendAmount = await (0,_util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_15__.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_11__.getFeeAmountSimple)({\n utxos: utxos,\n sendRequests: sendRequests,\n sourceAddress: this.getDepositAddress(),\n relayFeePerByteInSatoshi: relayFeePerByteInSatoshi,\n feePaidBy: feePaidBy,\n });\n const fundingUtxos = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_11__.getSuitableUtxos)(utxos, BigInt(spendAmount) + BigInt(Math.ceil(feeEstimate)), bestHeight, feePaidBy, sendRequests, options?.ensureUtxos || [], options?.tokenOperation);\n if (fundingUtxos.length === 0) {\n throw Error(\"The available inputs couldn't satisfy the request with fees\");\n }\n const fee = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_11__.getFeeAmount)({\n utxos: fundingUtxos,\n sendRequests: sendRequests,\n sourceAddress: this.getDepositAddress(),\n relayFeePerByteInSatoshi: relayFeePerByteInSatoshi,\n feePaidBy: feePaidBy,\n walletCache: this.walletCache,\n });\n const { encodedTransaction, sourceOutputs } = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_11__.buildEncodedTransaction)({\n inputs: fundingUtxos,\n outputs: sendRequests,\n signingKey: privateKey ?? _transaction_Wif_js__WEBPACK_IMPORTED_MODULE_11__.placeholderPrivateKeyBin,\n fee,\n discardChange,\n feePaidBy,\n changeAddress,\n buildUnsigned: options?.buildUnsigned === true,\n walletCache: this.walletCache,\n });\n const tokenIds = [\n ...fundingUtxos\n .filter((val) => val.token?.tokenId)\n .map((val) => val.token.tokenId),\n ...sendRequests\n .filter((val) => val instanceof _model_js__WEBPACK_IMPORTED_MODULE_10__.TokenSendRequest)\n .map((val) => val.tokenId),\n ].filter((value, index, array) => array.indexOf(value) === index);\n return { encodedTransaction, tokenIds, sourceOutputs };\n }\n // Submit a raw transaction\n async submitTransaction(transaction, awaitPropagation = true) {\n if (!this.provider) {\n throw Error(\"Wallet network provider was not initialized\");\n }\n let rawTransaction = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_12__.binToHex)(transaction);\n return await this.provider.sendRawTransaction(rawTransaction, awaitPropagation);\n }\n // gets transaction history of this wallet\n async getRawHistory(fromHeight = 0, toHeight = -1) {\n throw Error(\"getRawHistory not implemented in BaseWallet\");\n }\n // gets last transaction of this wallet\n async getLastTransaction(confirmedOnly = false) {\n let history = await this.getRawHistory();\n if (confirmedOnly) {\n history = history.filter((val) => val.height > 0);\n }\n if (!history.length) {\n return null;\n }\n const [lastTx] = history.slice(-1);\n return this.provider.getRawTransactionObject(lastTx.tx_hash);\n }\n // waits for next transaction, program execution is halted\n async waitForTransaction(options = {\n getTransactionInfo: true,\n getBalance: false,\n txHash: undefined,\n }) {\n if (options.getTransactionInfo === undefined) {\n options.getTransactionInfo = true;\n }\n return new Promise(async (resolve) => {\n let txHashSeen = false;\n const makeResponse = async (txHash) => {\n const response = {};\n const promises = [undefined, undefined];\n if (options.getBalance === true) {\n promises[0] = this.getBalance();\n }\n if (options.getTransactionInfo === true) {\n if (!txHash) {\n promises[1] = this.getLastTransaction();\n }\n else {\n promises[1] = this.provider.getRawTransactionObject(txHash);\n }\n }\n const result = await Promise.all(promises);\n response.balance = result[0];\n response.transactionInfo = result[1];\n return response;\n };\n // waiting for a specific transaction to propagate\n if (options.txHash) {\n let cancel;\n const waitForTransactionCallback = async (data) => {\n if (data && data[0] === options.txHash && data[1] !== null) {\n txHashSeen = true;\n await cancel?.();\n resolve(makeResponse(options.txHash));\n }\n };\n cancel = await this.provider.subscribeToTransaction(options.txHash, waitForTransactionCallback);\n return;\n }\n // waiting for any address transaction\n let watchCancel;\n let initialResponseSeen = false;\n watchCancel = await this.provider.watchAddressStatus(this.getDepositAddress(), async (_status) => {\n if (initialResponseSeen) {\n await watchCancel?.();\n resolve(makeResponse());\n return;\n }\n initialResponseSeen = true;\n });\n });\n }\n /**\n * watchBlocks Watch network blocks\n *\n * @param callback callback with a block header object\n * @param skipCurrentHeight if set, the notification about current block will not arrive\n *\n * @returns a function which will cancel watching upon evaluation\n */\n async watchBlocks(callback, skipCurrentHeight = true) {\n return this.provider.watchBlocks(callback, skipCurrentHeight);\n }\n /**\n * waitForBlock Wait for a network block\n *\n * @param height if specified waits for this exact blockchain height, otherwise resolves with the next block\n *\n */\n async waitForBlock(height) {\n return this.provider.waitForBlock(height);\n }\n //#endregion Funds\n //#region Cashtokens\n /**\n * Create new cashtoken, both funglible and/or non-fungible (NFT)\n * Refer to spec https://github.com/bitjson/cashtokens\n * @param {number} genesisRequest.amount amount of *fungible* tokens to create\n * @param {NFTCapability?} genesisRequest.capability capability of new NFT\n * @param {string?} genesisRequest.commitment NFT commitment message\n * @param {string?} genesisRequest.cashaddr cash address to send the created token UTXO to; if undefined will default to your address\n * @param {number?} genesisRequest.value satoshi value to send alongside with tokens; if undefined will default to 1000 satoshi\n * @param {SendRequestType | SendRequestType[]} sendRequests single or an array of extra send requests (OP_RETURN, value transfer, etc.) to include in genesis transaction\n * @param {SendRequestOptionsI} options Options of the send requests\n */\n async tokenGenesis(genesisRequest, sendRequests = [], options) {\n if (!Array.isArray(sendRequests)) {\n sendRequests = [sendRequests];\n }\n let utxos = await this.getUtxos();\n if (options?.utxoIds) {\n utxos = await (0,_util_checkUtxos_js__WEBPACK_IMPORTED_MODULE_9__.checkUtxos)(options.utxoIds.map((utxoId) => typeof utxoId === \"string\" ? (0,_model_js__WEBPACK_IMPORTED_MODULE_10__.fromUtxoId)(utxoId) : utxoId), utxos);\n }\n const genesisInputs = utxos.filter((val) => val.vout === 0 && !val.token);\n if (genesisInputs.length === 0) {\n throw new Error(\"No suitable inputs with vout=0 available for new token genesis\");\n }\n const genesisSendRequest = new _model_js__WEBPACK_IMPORTED_MODULE_10__.TokenSendRequest({\n cashaddr: genesisRequest.cashaddr || this.getTokenDepositAddress(),\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.getUtxos();\n const nftUtxos = utxos.filter((val) => val.token?.tokenId === tokenId &&\n val.token?.capability === _interface_js__WEBPACK_IMPORTED_MODULE_16__.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_10__.TokenSendRequest({\n cashaddr: (0,_util_index_js__WEBPACK_IMPORTED_MODULE_14__.toTokenaddr)(nftUtxos[0].address),\n tokenId: tokenId,\n capability: nftUtxos[0].token.capability,\n commitment: nftUtxos[0].token.commitment,\n amount: safeNewAmount,\n value: nftUtxos[0].satoshis,\n });\n return this.send([\n mintingInput,\n ...mintRequests.map((val) => new _model_js__WEBPACK_IMPORTED_MODULE_10__.TokenSendRequest({\n cashaddr: val.cashaddr || this.getTokenDepositAddress(),\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.getUtxos();\n const tokenUtxos = utxos.filter((val) => val.token?.tokenId === burnRequest.tokenId &&\n val.token?.capability === burnRequest.capability &&\n val.token?.commitment === burnRequest.commitment);\n if (!tokenUtxos.length) {\n throw new Error(\"You do not have suitable token UTXOs to perform burn\");\n }\n const totalFungibleAmount = tokenUtxos.reduce((prev, cur) => prev + (cur.token?.amount || 0n), 0n);\n let fungibleBurnAmount = burnRequest.amount && burnRequest.amount > 0 ? burnRequest.amount : 0n;\n fungibleBurnAmount = BigInt(fungibleBurnAmount);\n const hasNFT = burnRequest.capability || burnRequest.commitment;\n let utxoIds = [];\n let changeSendRequests;\n if (hasNFT) {\n // does not have FT tokens, let us destroy the token completely\n if (totalFungibleAmount === 0n) {\n changeSendRequests = [];\n utxoIds.push(tokenUtxos[0]);\n }\n else {\n // add utxos to spend from\n let available = 0n;\n for (const token of tokenUtxos.filter((val) => val.token?.amount)) {\n utxoIds.push(token);\n available += token.token.amount;\n if (available >= fungibleBurnAmount) {\n break;\n }\n }\n // if there are FT, reduce their amount\n const newAmount = totalFungibleAmount - fungibleBurnAmount;\n const safeNewAmount = newAmount < 0n ? 0n : newAmount;\n changeSendRequests = [\n new _model_js__WEBPACK_IMPORTED_MODULE_10__.TokenSendRequest({\n cashaddr: burnRequest.cashaddr || (0,_util_index_js__WEBPACK_IMPORTED_MODULE_14__.toTokenaddr)(this.getChangeAddress()),\n tokenId: burnRequest.tokenId,\n capability: burnRequest.capability,\n commitment: burnRequest.commitment,\n amount: safeNewAmount,\n value: tokenUtxos[0].satoshis,\n }),\n ];\n }\n }\n else {\n // if we are burning last fungible tokens, let us destroy the token completely\n if (totalFungibleAmount === fungibleBurnAmount) {\n changeSendRequests = [];\n utxoIds.push(...tokenUtxos);\n }\n else {\n // add utxos to spend from\n let available = 0n;\n for (const token of tokenUtxos.filter((val) => val.token?.amount)) {\n utxoIds.push(token);\n available += token.token.amount;\n if (available >= fungibleBurnAmount) {\n break;\n }\n }\n // reduce the FT amount\n const newAmount = available - fungibleBurnAmount;\n const safeNewAmount = newAmount < 0n ? 0n : newAmount;\n changeSendRequests = [\n new _model_js__WEBPACK_IMPORTED_MODULE_10__.TokenSendRequest({\n cashaddr: burnRequest.cashaddr || (0,_util_index_js__WEBPACK_IMPORTED_MODULE_14__.toTokenaddr)(this.getChangeAddress()),\n tokenId: burnRequest.tokenId,\n amount: safeNewAmount,\n value: tokenUtxos.reduce((a, c) => a + c.satoshis, 0),\n }),\n ];\n }\n }\n const opReturn = _model_js__WEBPACK_IMPORTED_MODULE_10__.OpReturnData.fromString(message || \"\");\n return this.send([opReturn, ...changeSendRequests], {\n ...options,\n checkTokenQuantities: false,\n queryBalance: false,\n ensureUtxos: utxoIds.length > 0 ? utxoIds : undefined,\n tokenOperation: \"burn\",\n });\n }\n /**\n * getTokenUtxos Get unspent token outputs for the wallet\n * will return utxos only for the specified token if `tokenId` provided\n * @param {string?} tokenId tokenId (category) to filter utxos by, if not set will return utxos from all tokens\n * @returns {Utxo[]} token utxos\n */\n async getTokenUtxos(tokenId) {\n const utxos = await this.getUtxos();\n return utxos.filter((val) => tokenId ? val.token?.tokenId === tokenId : val.token);\n }\n /**\n * getTokenBalance Gets fungible token balance\n * for NFT token balance see @ref getNftTokenBalance\n * @param {string} tokenId tokenId to get balance for\n * @returns {bigint} fungible token balance\n */\n async getTokenBalance(tokenId) {\n const utxos = (await this.getTokenUtxos(tokenId)).filter((val) => val.token?.amount);\n return (0,_util_index_js__WEBPACK_IMPORTED_MODULE_7__.sumTokenAmounts)(utxos, tokenId);\n }\n /**\n * getNftTokenBalance Gets non-fungible token (NFT) balance for a particular tokenId\n * disregards fungible token balances\n * for fungible token balance see @ref getTokenBalance\n * @param {string} tokenId tokenId to get balance for\n * @returns {number} non-fungible token balance\n */\n async getNftTokenBalance(tokenId) {\n const utxos = (await this.getTokenUtxos(tokenId)).filter((val) => val.token?.commitment !== undefined);\n return utxos.length;\n }\n /**\n * getAllTokenBalances Gets all fungible token balances in this wallet\n * @returns {Object} a map [tokenId => balance] for all tokens in this wallet\n */\n async getAllTokenBalances() {\n const result = {};\n const utxos = (await this.getTokenUtxos()).filter((val) => val.token?.amount);\n for (const utxo of utxos) {\n if (!result[utxo.token.tokenId]) {\n result[utxo.token.tokenId] = 0n;\n }\n result[utxo.token.tokenId] += utxo.token.amount;\n }\n return result;\n }\n /**\n * getAllNftTokenBalances Gets all non-fungible token (NFT) balances in this wallet\n * @returns {Object} a map [tokenId => balance] for all NFTs in this wallet\n */\n async getAllNftTokenBalances() {\n const result = {};\n const utxos = (await this.getTokenUtxos()).filter((val) => val.token?.commitment !== undefined);\n for (const utxo of utxos) {\n if (!result[utxo.token.tokenId]) {\n result[utxo.token.tokenId] = 0;\n }\n result[utxo.token.tokenId] += 1;\n }\n return result;\n }\n //#endregion Cashtokens\n sign(message, privateKey = undefined) {\n if (!privateKey) {\n throw new Error(\"Signing private key not provided\");\n }\n return new _message_signed_js__WEBPACK_IMPORTED_MODULE_17__.SignedMessage().sign(message, privateKey);\n }\n // Convenience wrapper to verify interface\n verify(message, sig, address, publicKey) {\n if (!address && !publicKey) {\n throw new Error(\"Either address or publicKey must be provided for verification\");\n }\n return new _message_signed_js__WEBPACK_IMPORTED_MODULE_17__.SignedMessage().verify(message, sig, address, publicKey);\n }\n}\n/**\n * _checkContextSafety (internal) if running in nodejs, will disable saving\n * mainnet wallets on public servers if ALLOW_MAINNET_USER_WALLETS is set to false\n * @param {BaseWallet} wallet a wallet\n */\nconst _checkContextSafety = function (wallet) {\n if ((0,_util_index_js__WEBPACK_IMPORTED_MODULE_18__.getRuntimePlatform)() === \"node\") {\n if (process.env.ALLOW_MAINNET_USER_WALLETS === `false`) {\n if (wallet.network === _enum_js__WEBPACK_IMPORTED_MODULE_2__.NetworkType.Mainnet) {\n throw Error(`Refusing to save wallet in an open public database, remove ALLOW_MAINNET_USER_WALLETS=\"false\", if this service is secure and private`);\n }\n }\n }\n};\n/**\n * getNamedWalletId - get the full wallet id from the database\n *\n * @param name user friendly wallet alias\n * @param dbName name under which the wallet will be stored in the database\n *\n * @returns boolean\n */\nasync function getNamedWalletId(name, dbName) {\n if (name.length === 0) {\n throw Error(\"Named wallets must have a non-empty name\");\n }\n dbName = dbName ? dbName : dbName;\n let db = getStorageProvider(dbName);\n if (db) {\n await db.init();\n let savedWalletRecord = await db.getWallet(name);\n await db.close();\n if (savedWalletRecord !== undefined) {\n return savedWalletRecord.wallet;\n }\n else {\n throw Error(`No record was found for ${name} in db: ${dbName}`);\n }\n }\n else {\n throw Error(\"No database was available or configured to store the named wallet.\");\n }\n}\nfunction getStorageProvider(dbName) {\n if (!BaseWallet.StorageProvider) {\n return undefined;\n }\n return new BaseWallet.StorageProvider(dbName);\n}\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/wallet/Base.ts?");
|
|
637
|
+
eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"BaseWallet\": () => (/* binding */ BaseWallet),\n/* harmony export */ \"_checkContextSafety\": () => (/* binding */ _checkContextSafety),\n/* harmony export */ \"getNamedWalletId\": () => (/* binding */ getNamedWalletId),\n/* harmony export */ \"getStorageProvider\": () => (/* binding */ getStorageProvider),\n/* harmony export */ \"placeholderCashAddr\": () => (/* binding */ placeholderCashAddr),\n/* harmony export */ \"placeholderTokenAddr\": () => (/* binding */ placeholderTokenAddr)\n/* harmony export */ });\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/hex.js\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../enum.js */ \"./src/enum.ts\");\n/* harmony import */ var _interface_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../interface.js */ \"./src/interface.ts\");\n/* harmony import */ var _network_default_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../network/default.js */ \"./src/network/default.ts\");\n/* harmony import */ var _network_getRelayFeeCache_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../network/getRelayFeeCache.js */ \"./src/network/getRelayFeeCache.ts\");\n/* harmony import */ var _transaction_Wif_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../transaction/Wif.js */ \"./src/transaction/Wif.ts\");\n/* harmony import */ var _util_checkUtxos_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../util/checkUtxos.js */ \"./src/util/checkUtxos.ts\");\n/* harmony import */ var _util_index_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../util/index.js */ \"./src/util/sumUtxoValue.ts\");\n/* harmony import */ var _util_index_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../util/index.js */ \"./src/util/asSendRequestObject.ts\");\n/* harmony import */ var _util_index_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../util/index.js */ \"./src/util/deriveCashaddr.ts\");\n/* harmony import */ var _util_index_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../util/index.js */ \"./src/util/getRuntimePlatform.ts\");\n/* harmony import */ var _util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../util/sumSendRequestAmounts.js */ \"./src/util/sumSendRequestAmounts.ts\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./enum.js */ \"./src/wallet/enum.ts\");\n/* harmony import */ var _model_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./model.js */ \"./src/wallet/model.ts\");\n/* harmony import */ var _Util_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Util.js */ \"./src/wallet/Util.ts\");\n/* harmony import */ var _message_signed_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../message/signed.js */ \"./src/message/signed.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_network_default_js__WEBPACK_IMPORTED_MODULE_0__, _enum_js__WEBPACK_IMPORTED_MODULE_2__, _Util_js__WEBPACK_IMPORTED_MODULE_3__, _model_js__WEBPACK_IMPORTED_MODULE_7__, _transaction_Wif_js__WEBPACK_IMPORTED_MODULE_8__, _util_index_js__WEBPACK_IMPORTED_MODULE_10__, _util_index_js__WEBPACK_IMPORTED_MODULE_11__, _util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_12__, _message_signed_js__WEBPACK_IMPORTED_MODULE_14__]);\n([_network_default_js__WEBPACK_IMPORTED_MODULE_0__, _enum_js__WEBPACK_IMPORTED_MODULE_2__, _Util_js__WEBPACK_IMPORTED_MODULE_3__, _model_js__WEBPACK_IMPORTED_MODULE_7__, _transaction_Wif_js__WEBPACK_IMPORTED_MODULE_8__, _util_index_js__WEBPACK_IMPORTED_MODULE_10__, _util_index_js__WEBPACK_IMPORTED_MODULE_11__, _util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_12__, _message_signed_js__WEBPACK_IMPORTED_MODULE_14__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\n\n\n\n\n\n\n\n\n\n\n\nconst placeholderCashAddr = \"bitcoincash:qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqfnhks603\";\nconst placeholderTokenAddr = \"bitcoincash:zqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqweyg7usz\";\n/**\n * A class to hold features used by all wallets\n * @class BaseWallet\n */\nclass BaseWallet {\n get networkPrefix() {\n return _enum_js__WEBPACK_IMPORTED_MODULE_2__.prefixFromNetworkMap[this.network];\n }\n // interface to util functions. see Util.ts\n get util() {\n if (!this._util) {\n this._util = new _Util_js__WEBPACK_IMPORTED_MODULE_3__.Util(this.network);\n }\n return this._util;\n }\n // interface to util util. see Util.Util\n static get util() {\n return new this().util;\n }\n // Return wallet info\n getInfo() {\n throw Error(\"getInfo not implemented in BaseWallet\");\n }\n slpSemiAware(value = true) {\n this._slpSemiAware = value;\n return this;\n }\n //#region Accessors\n getNetworkProvider(\n // @ts-ignore\n network = _enum_js__WEBPACK_IMPORTED_MODULE_2__.NetworkType.Mainnet) {\n return (0,_network_default_js__WEBPACK_IMPORTED_MODULE_0__.getNetworkProvider)(network);\n }\n /**\n * getDepositAddress - get a wallet deposit address\n *\n * a high-level function,\n *\n * @see {@link https://rest-unstable.mainnet.cash/api-docs/#/wallet/depositAddress|/wallet/deposit_address} for REST endpoint\n *\n * @returns The deposit address as a string\n */\n getDepositAddress() {\n // return this.cashaddr;\n throw Error(\"getDepositAddress not implemented in BaseWallet\");\n }\n /**\n * getChangeAddress - get a wallet change address\n *\n * a high-level function,\n *\n * @see {@link https://rest-unstable.mainnet.cash/api-docs/#/wallet/changeAddress|/wallet/change_address} for REST endpoint\n *\n * @returns The change address as a string\n */\n getChangeAddress() {\n // return this.cashaddr;\n throw Error(\"getChangeAddress not implemented in BaseWallet\");\n }\n /**\n * getTokenDepositAddress - get a cashtoken aware wallet deposit address\n *\n * @returns The cashtoken aware deposit address as a string\n */\n getTokenDepositAddress() {\n // return this.tokenaddr;\n throw Error(\"getTokenDepositAddress not implemented in BaseWallet\");\n }\n /**\n * getTokenDepositAddress - get a cashtoken aware wallet deposit address\n *\n * @returns The cashtoken aware deposit address as a string\n */\n getTokenChangeAddress() {\n // return this.tokenaddr;\n throw Error(\"getTokenDepositAddress not implemented in BaseWallet\");\n }\n //#endregion Accessors\n //#region Constructors and Statics\n /**\n * constructor for a new wallet\n * @param network network for wallet\n *\n * @throws {Error} if called on BaseWallet\n */\n constructor(network = _enum_js__WEBPACK_IMPORTED_MODULE_2__.NetworkType.Mainnet) {\n this._slpSemiAware = false; // a flag which requires an utxo to have more than 546 sats to be spendable and counted in the balance\n this.name = \"\";\n this.network = network;\n this.walletType = _enum_js__WEBPACK_IMPORTED_MODULE_4__.WalletTypeEnum.Watch;\n this.provider = this.getNetworkProvider(this.network);\n this.isTestnet = this.network === _enum_js__WEBPACK_IMPORTED_MODULE_2__.NetworkType.Mainnet ? false : true;\n }\n //#endregion Constructors\n /**\n * named (internal) get a named wallet from the database or create a new one.\n * Note: this function should behave identically if\n *\n * @param {string} name name of the wallet\n * @param {string} dbName database name the wallet is stored in\n * @param {boolean} forceNew attempt to overwrite an existing wallet\n *\n * @throws {Error} if forceNew is true and the wallet already exists\n * @returns a promise to a named wallet\n */\n async named(name, dbName, forceNew = false) {\n if (name.length === 0) {\n throw Error(\"Named wallets must have a non-empty name\");\n }\n _checkContextSafety(this);\n this.name = name;\n dbName = dbName ? dbName : _enum_js__WEBPACK_IMPORTED_MODULE_2__.prefixFromNetworkMap[this.network];\n const db = getStorageProvider(dbName);\n // If there is a database, force saving or error\n if (db) {\n await db.init();\n const savedWalletRecord = await db.getWallet(name);\n if (savedWalletRecord) {\n await db.close();\n if (forceNew) {\n throw Error(`A wallet with the name ${name} already exists in ${dbName}`);\n }\n const recoveredWallet = await this.fromId(savedWalletRecord.wallet);\n recoveredWallet.name = savedWalletRecord.name;\n return recoveredWallet;\n }\n else {\n const wallet = await this.initialize();\n wallet.name = name;\n await db.addWallet(wallet.name, wallet.toDbString());\n await db.close();\n return wallet;\n }\n }\n else {\n throw Error(\"No database was available or configured to store the named wallet.\");\n }\n }\n /**\n * replaceNamed - Replace (recover) named wallet with a new walletId\n *\n * If wallet with a provided name does not exist yet, it will be created with a `walletId` supplied\n * If wallet exists it will be overwritten without exception\n *\n * @param name user friendly wallet alias\n * @param walletId walletId options to steer the creation process\n * @param dbName name under which the wallet will be stored in the database\n *\n * @returns instantiated wallet\n */\n async replaceNamed(name, walletId, dbName) {\n if (name.length === 0) {\n throw Error(\"Named wallets must have a non-empty name\");\n }\n _checkContextSafety(this);\n this.name = name;\n dbName = dbName ? dbName : _enum_js__WEBPACK_IMPORTED_MODULE_2__.prefixFromNetworkMap[this.network];\n let db = getStorageProvider(dbName);\n if (db) {\n await db.init();\n let savedWalletRecord = await db.getWallet(name);\n await this.fromId(walletId);\n if (savedWalletRecord) {\n await db.updateWallet(name, walletId);\n }\n else {\n await db.addWallet(name, walletId);\n }\n await db.close();\n return this;\n }\n else {\n throw Error(\"No database was available or configured to store the named wallet.\");\n }\n }\n /**\n * namedExists - check if a named wallet already exists\n *\n * @param name user friendly wallet alias\n * @param dbName name under which the wallet will be stored in the database\n *\n * @returns boolean\n */\n async namedExists(name, dbName) {\n if (name.length === 0) {\n throw Error(\"Named wallets must have a non-empty name\");\n }\n _checkContextSafety(this);\n dbName = dbName ? dbName : _enum_js__WEBPACK_IMPORTED_MODULE_2__.prefixFromNetworkMap[this.network];\n let db = getStorageProvider(dbName);\n if (db) {\n await db.init();\n let savedWalletRecord = await db.getWallet(name);\n await db.close();\n return savedWalletRecord !== undefined;\n }\n else {\n throw Error(\"No database was available or configured to store the named wallet.\");\n }\n }\n async initialize() {\n return this;\n }\n //#region Serialization\n /**\n * toDbString - store the serialized version of the wallet in the database, not just the name\n *\n * @throws {Error} if called on BaseWallet\n */\n toDbString() {\n return `${this.walletType}:${this.network}:${this.getDepositAddress()}`;\n }\n // Returns the serialized wallet as a string\n // If storing in a database, set asNamed to false to store secrets\n // In all other cases, the a named wallet is deserialized from the database\n // by the name key\n toString() {\n return `${this.walletType}:${this.network}:${this.getDepositAddress()}`;\n }\n //#endregion Serialization\n /**\n * explorerUrl Web url to a transaction on a block explorer\n *\n * @param txId transaction Id\n * @returns Url string\n */\n explorerUrl(txId) {\n const explorerUrlMap = {\n mainnet: \"https://blockchair.com/bitcoin-cash/transaction/\",\n testnet: \"https://www.blockchain.com/bch-testnet/tx/\",\n regtest: \"\",\n };\n return explorerUrlMap[this.network] + txId;\n }\n /**\n * named - create a named wallet\n *\n * @param name user friendly wallet alias\n * @param dbName name under which the wallet will be stored in the database\n * @param force force recreate wallet in the database if a record already exist\n *\n * @returns instantiated wallet\n */\n static async named(name, dbName, force) {\n return new this().named(name, dbName, force);\n }\n /**\n * replaceNamed - replace (recover) named wallet with a new walletId\n *\n * If wallet with a provided name does not exist yet, it will be created with a `walletId` supplied\n * If wallet exists it will be overwritten without exception\n *\n * @param name user friendly wallet alias\n * @param walletId walletId options to steer the creation process\n * @param dbName name under which the wallet will be stored in the database\n *\n * @returns instantiated wallet\n */\n static async replaceNamed(name, walletId, dbName) {\n return new this().replaceNamed(name, walletId, dbName);\n }\n /**\n * namedExists - check if a named wallet already exists\n *\n * @param name user friendly wallet alias\n * @param dbName name under which the wallet will be stored in the database\n *\n * @returns boolean\n */\n static async namedExists(name, dbName) {\n return new this().namedExists(name, dbName);\n }\n fromId(walletId) {\n throw Error(\"fromId not implemented in BaseWallet\");\n }\n //#region Funds\n /**\n * utxos Get unspent outputs for the wallet\n *\n */\n async getUtxos() {\n throw Error(\"getUtxos not implemented in BaseWallet\");\n }\n // gets wallet balance in sats\n async getBalance() {\n return this.getBalanceFromProvider();\n }\n // Gets balance by summing value in all utxos in stats\n async getBalanceFromUtxos() {\n const utxos = (await this.getUtxos()).filter((val) => val.token === undefined);\n return (0,_util_index_js__WEBPACK_IMPORTED_MODULE_5__.sumUtxoValue)(utxos);\n }\n // Gets balance from fulcrum\n async getBalanceFromProvider() {\n // Fulcrum reports balance of all utxos, including tokens, which is undesirable\n // // TODO not sure why getting the balance from a provider doesn't work\n // if (this._slpAware || this._slpSemiAware) {\n // return await this.getBalanceFromUtxos();\n // } else {\n // return await this.provider.getBalance(this.cashaddr);\n // }\n // FIXME\n return this.getBalanceFromUtxos();\n }\n async getAddressUtxos(address) {\n throw Error(\"getAddressUtxos not implemented in BaseWallet\");\n }\n // watching for any transaction hash of this wallet\n async watchAddress(callback) {\n return this.provider.watchAddress(this.getDepositAddress(), callback);\n }\n // watching for any transaction of this wallet\n async watchAddressTransactions(callback) {\n return this.provider.watchAddressTransactions(this.getDepositAddress(), callback);\n }\n // watching for cashtoken transaction of this wallet\n async watchAddressTokenTransactions(callback) {\n return this.provider.watchAddressTokenTransactions(this.getDepositAddress(), callback);\n }\n // sets up a callback to be called upon wallet's balance change\n // can be cancelled by calling the function returned from this one\n async watchBalance(callback) {\n return this.provider.watchAddressStatus(this.getDepositAddress(), async (_status) => {\n const balance = await this.getBalanceFromProvider();\n callback(balance);\n });\n }\n // waits for address balance to be greater than or equal to the target value\n // this call halts the execution\n async waitForBalance(value) {\n return new Promise(async (resolve) => {\n let watchCancel;\n watchCancel = await this.watchBalance(async (balance) => {\n if (balance >= value) {\n await watchCancel?.();\n resolve(balance);\n }\n });\n });\n }\n // sets up a callback to be called upon wallet's token balance change\n // can be cancelled by calling the function returned from this one\n async watchTokenBalance(category, callback) {\n let previous = undefined;\n return await this.provider.watchAddressStatus(this.getDepositAddress(), async (_status) => {\n const balance = await this.getTokenBalance(category);\n if (previous != balance) {\n callback(balance);\n }\n previous = balance;\n });\n }\n // waits for address token balance to be greater than or equal to the target amount\n // this call halts the execution\n async waitForTokenBalance(category, amount) {\n return new Promise(async (resolve) => {\n let watchCancel;\n watchCancel = await this.watchTokenBalance(category, async (balance) => {\n if (balance >= amount) {\n await watchCancel?.();\n resolve(balance);\n }\n });\n });\n }\n async _getMaxAmountToSend(params = {\n outputCount: 1,\n options: {},\n }) {\n if (params.options && params.options.slpSemiAware) {\n this._slpSemiAware = true;\n }\n let feePaidBy;\n if (params.options && params.options.feePaidBy) {\n feePaidBy = params.options.feePaidBy;\n }\n else {\n feePaidBy = _enum_js__WEBPACK_IMPORTED_MODULE_4__.FeePaidByEnum.change;\n }\n // get inputs\n let utxos;\n if (params.options && params.options.utxoIds) {\n utxos = await (0,_util_checkUtxos_js__WEBPACK_IMPORTED_MODULE_6__.checkUtxos)(params.options.utxoIds.map((utxoId) => typeof utxoId === \"string\" ? (0,_model_js__WEBPACK_IMPORTED_MODULE_7__.fromUtxoId)(utxoId) : utxoId), this);\n }\n else {\n utxos = (await this.getUtxos()).filter((utxo) => !utxo.token);\n }\n // Get current height to assure recently mined coins are not spent.\n const bestHeight = await this.provider.getBlockHeight();\n // simulate outputs using the sender's address\n const sendRequest = new _model_js__WEBPACK_IMPORTED_MODULE_7__.SendRequest({\n cashaddr: placeholderCashAddr,\n value: 100n,\n });\n const sendRequests = Array(params.outputCount)\n .fill(0)\n .map(() => sendRequest);\n const fundingUtxos = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_8__.getSuitableUtxos)(utxos, undefined, bestHeight, feePaidBy, sendRequests);\n const relayFeePerByteInSatoshi = await (0,_network_getRelayFeeCache_js__WEBPACK_IMPORTED_MODULE_1__.getRelayFeeCache)(this.provider);\n const fee = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_8__.getFeeAmountSimple)({\n utxos: fundingUtxos,\n sendRequests: sendRequests,\n sourceAddress: placeholderCashAddr,\n relayFeePerByteInSatoshi: relayFeePerByteInSatoshi,\n feePaidBy: feePaidBy,\n });\n const spendableAmount = (0,_util_index_js__WEBPACK_IMPORTED_MODULE_5__.sumUtxoValue)(fundingUtxos);\n let result = spendableAmount - fee;\n if (result < 0n) {\n result = 0n;\n }\n return { value: result, utxos: fundingUtxos };\n }\n async getMaxAmountToSend(params = {\n outputCount: 1,\n options: {},\n }) {\n const { value: result } = await this._getMaxAmountToSend(params);\n return result;\n }\n /**\n * send Send some amount to an address\n * this function processes the send requests, encodes the transaction, sends it to the network\n * @returns (depending on the options parameter) the transaction id, new address balance and a link to the transaction on the blockchain explorer\n *\n * This is a first class function with REST analog, maintainers should strive to keep backward-compatibility\n *\n */\n async send(requests, options) {\n const { encodedTransaction, categories, sourceOutputs } = await this.encodeTransaction(requests, undefined, options);\n const resp = new _model_js__WEBPACK_IMPORTED_MODULE_7__.SendResponse({});\n resp.categories = categories;\n if (options?.buildUnsigned !== true) {\n const txId = await this.submitTransaction(encodedTransaction, options?.awaitTransactionPropagation === undefined ||\n options?.awaitTransactionPropagation === true);\n resp.txId = txId;\n resp.explorerUrl = this.explorerUrl(resp.txId);\n if (options?.queryBalance === undefined ||\n options?.queryBalance === true) {\n resp.balance = await this.getBalance();\n }\n }\n else {\n resp.unsignedTransaction = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_9__.binToHex)(encodedTransaction);\n resp.sourceOutputs = sourceOutputs;\n }\n return resp;\n }\n /**\n * sendMax Send all available funds to a destination cash address\n *\n * @param {string} cashaddr destination cash address\n * @param {SendRequestOptionsI} options Options of the send requests\n *\n * @returns (depending on the options parameter) the transaction id, new address balance and a link to the transaction on the blockchain explorer\n */\n async sendMax(cashaddr, options) {\n return await this.sendMaxRaw(cashaddr, options);\n }\n /**\n * sendMaxRaw (internal) Send all available funds to a destination cash address\n *\n * @param {string} cashaddr destination cash address\n * @param {SendRequestOptionsI} options Options of the send requests\n *\n * @returns the transaction id sent to the network\n */\n async sendMaxRaw(cashaddr, options, privateKey) {\n const { value: maxSpendableAmount, utxos } = await this._getMaxAmountToSend({\n outputCount: 1,\n options: options,\n privateKey: privateKey,\n });\n if (!options) {\n options = {};\n }\n options.utxoIds = utxos;\n const sendRequest = new _model_js__WEBPACK_IMPORTED_MODULE_7__.SendRequest({\n cashaddr: cashaddr,\n value: maxSpendableAmount,\n });\n const { encodedTransaction, categories, sourceOutputs } = await this.encodeTransaction([sendRequest], true, options, privateKey);\n const resp = new _model_js__WEBPACK_IMPORTED_MODULE_7__.SendResponse({});\n resp.categories = categories;\n if (options?.buildUnsigned !== true) {\n const txId = await this.submitTransaction(encodedTransaction, options?.awaitTransactionPropagation === undefined ||\n options?.awaitTransactionPropagation === true);\n resp.txId = txId;\n resp.explorerUrl = this.explorerUrl(resp.txId);\n if (options?.queryBalance === undefined ||\n options?.queryBalance === true) {\n resp.balance = await this.getBalance();\n }\n }\n else {\n resp.unsignedTransaction = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_9__.binToHex)(encodedTransaction);\n resp.sourceOutputs = sourceOutputs;\n }\n return resp;\n }\n /**\n * encodeTransaction Encode and sign a transaction given a list of sendRequests, options and estimate fees.\n * @param {SendRequest[]} sendRequests SendRequests\n * @param {boolean} discardChange=false\n * @param {SendRequestOptionsI} options Options of the send requests\n */\n async encodeTransaction(requests, discardChange = false, options, privateKey) {\n let sendRequests = (0,_util_index_js__WEBPACK_IMPORTED_MODULE_10__.asSendRequestObject)(requests);\n if (options && options.slpSemiAware) {\n this._slpSemiAware = true;\n }\n let feePaidBy;\n if (options?.feePaidBy) {\n feePaidBy = options.feePaidBy;\n }\n else {\n feePaidBy = _enum_js__WEBPACK_IMPORTED_MODULE_4__.FeePaidByEnum.change;\n }\n let changeAddress;\n if (options?.changeAddress) {\n changeAddress = options.changeAddress;\n }\n else {\n changeAddress = this.getChangeAddress();\n }\n let checkTokenQuantities = true;\n if (options?.checkTokenQuantities === false) {\n checkTokenQuantities = false;\n }\n // get inputs from options or query all inputs\n let utxos = await this.getUtxos();\n if (options && options.utxoIds) {\n utxos = await (0,_util_checkUtxos_js__WEBPACK_IMPORTED_MODULE_6__.checkUtxos)(options.utxoIds.map((utxoId) => typeof utxoId === \"string\" ? (0,_model_js__WEBPACK_IMPORTED_MODULE_7__.fromUtxoId)(utxoId) : utxoId), utxos);\n }\n // filter out token utxos if there are no token requests\n if (checkTokenQuantities &&\n !sendRequests.some((val) => val instanceof _model_js__WEBPACK_IMPORTED_MODULE_7__.TokenSendRequest)) {\n utxos = utxos.filter((val) => !val.token);\n }\n const addTokenChangeOutputs = (inputs, outputs) => {\n // Allow for implicit token burn if the total amount sent is less than user had\n // allow for token genesis, creating more tokens than we had before (0)\n if (!checkTokenQuantities) {\n return;\n }\n const allTokenInputs = inputs.filter((val) => val.token);\n const allTokenOutputs = outputs.filter((val) => val instanceof _model_js__WEBPACK_IMPORTED_MODULE_7__.TokenSendRequest);\n const categories = allTokenOutputs\n .map((val) => val.category)\n .filter((val, idx, arr) => arr.indexOf(val) === idx);\n for (let category of categories) {\n const tokenInputs = allTokenInputs.filter((val) => val.token?.category === category);\n const inputAmountSum = tokenInputs.reduce((prev, cur) => prev + cur.token.amount, 0n);\n const tokenOutputs = allTokenOutputs.filter((val) => val.category === category);\n const outputAmountSum = tokenOutputs.reduce((prev, cur) => prev + cur.amount, 0n);\n const diff = inputAmountSum - outputAmountSum;\n if (diff < 0) {\n throw new Error(\"Not enough token amount to send\");\n }\n if (diff >= 0) {\n let available = 0n;\n let change = 0n;\n const ensureUtxos = [];\n for (const token of tokenInputs.filter((val) => val.token?.amount)) {\n ensureUtxos.push(token);\n available += token.token.amount;\n if (available >= outputAmountSum) {\n change = available - outputAmountSum;\n //break;\n }\n }\n if (ensureUtxos.length) {\n if (!options) {\n options = {};\n }\n options.ensureUtxos = [\n ...(options.ensureUtxos ?? []),\n ...ensureUtxos,\n ].filter((val, index, array) => array.findIndex((other) => other.txid === val.txid && other.vout === val.vout) === index);\n }\n if (change > 0) {\n outputs.push(new _model_js__WEBPACK_IMPORTED_MODULE_7__.TokenSendRequest({\n cashaddr: (0,_util_index_js__WEBPACK_IMPORTED_MODULE_11__.toTokenaddr)(this.getChangeAddress()),\n amount: change,\n category: category,\n nft: tokenOutputs[0].nft,\n value: tokenOutputs[0].value,\n }));\n }\n }\n }\n };\n addTokenChangeOutputs(utxos, sendRequests);\n const bestHeight = await this.provider.getBlockHeight();\n const spendAmount = await (0,_util_sumSendRequestAmounts_js__WEBPACK_IMPORTED_MODULE_12__.sumSendRequestAmounts)(sendRequests);\n if (utxos.length === 0) {\n throw Error(\"There were no Unspent Outputs\");\n }\n if (typeof spendAmount !== \"bigint\") {\n throw Error(\"Couldn't get spend amount when building transaction\");\n }\n const relayFeePerByteInSatoshi = await (0,_network_getRelayFeeCache_js__WEBPACK_IMPORTED_MODULE_1__.getRelayFeeCache)(this.provider);\n const feeEstimate = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_8__.getFeeAmountSimple)({\n utxos: utxos,\n sendRequests: sendRequests,\n sourceAddress: this.getDepositAddress(),\n relayFeePerByteInSatoshi: relayFeePerByteInSatoshi,\n feePaidBy: feePaidBy,\n });\n const fundingUtxos = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_8__.getSuitableUtxos)(utxos, spendAmount + feeEstimate, bestHeight, feePaidBy, sendRequests, options?.ensureUtxos || [], options?.tokenOperation);\n if (fundingUtxos.length === 0) {\n throw Error(\"The available inputs couldn't satisfy the request with fees\");\n }\n const fee = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_8__.getFeeAmount)({\n utxos: fundingUtxos,\n sendRequests: sendRequests,\n sourceAddress: this.getDepositAddress(),\n relayFeePerByteInSatoshi: relayFeePerByteInSatoshi,\n feePaidBy: feePaidBy,\n walletCache: this.walletCache,\n });\n const { encodedTransaction, sourceOutputs } = await (0,_transaction_Wif_js__WEBPACK_IMPORTED_MODULE_8__.buildEncodedTransaction)({\n inputs: fundingUtxos,\n outputs: sendRequests,\n signingKey: privateKey ?? _transaction_Wif_js__WEBPACK_IMPORTED_MODULE_8__.placeholderPrivateKeyBin,\n fee,\n discardChange,\n feePaidBy,\n changeAddress,\n buildUnsigned: options?.buildUnsigned === true,\n walletCache: this.walletCache,\n });\n const categories = [\n ...fundingUtxos\n .filter((val) => val.token?.category)\n .map((val) => val.token.category),\n ...sendRequests\n .filter((val) => val instanceof _model_js__WEBPACK_IMPORTED_MODULE_7__.TokenSendRequest)\n .map((val) => val.category),\n ].filter((value, index, array) => array.indexOf(value) === index);\n return { encodedTransaction, categories, sourceOutputs };\n }\n // Submit a raw transaction\n async submitTransaction(transaction, awaitPropagation = true) {\n if (!this.provider) {\n throw Error(\"Wallet network provider was not initialized\");\n }\n let rawTransaction = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_9__.binToHex)(transaction);\n return await this.provider.sendRawTransaction(rawTransaction, awaitPropagation);\n }\n // gets transaction history of this wallet\n async getRawHistory(fromHeight = 0, toHeight = -1) {\n throw Error(\"getRawHistory not implemented in BaseWallet\");\n }\n // gets last transaction of this wallet\n async getLastTransaction(confirmedOnly = false) {\n let history = await this.getRawHistory();\n if (confirmedOnly) {\n history = history.filter((val) => val.height > 0);\n }\n if (!history.length) {\n return null;\n }\n const [lastTx] = history.slice(-1);\n return this.provider.getRawTransactionObject(lastTx.tx_hash);\n }\n // waits for next transaction, program execution is halted\n async waitForTransaction(options = {\n getTransactionInfo: true,\n getBalance: false,\n txHash: undefined,\n }) {\n if (options.getTransactionInfo === undefined) {\n options.getTransactionInfo = true;\n }\n return new Promise(async (resolve) => {\n let txHashSeen = false;\n const makeResponse = async (txHash) => {\n const response = {};\n const promises = [undefined, undefined];\n if (options.getBalance === true) {\n promises[0] = this.getBalance();\n }\n if (options.getTransactionInfo === true) {\n if (!txHash) {\n promises[1] = this.getLastTransaction();\n }\n else {\n promises[1] = this.provider.getRawTransactionObject(txHash);\n }\n }\n const result = await Promise.all(promises);\n response.balance = result[0];\n response.transactionInfo = result[1];\n return response;\n };\n // waiting for a specific transaction to propagate\n if (options.txHash) {\n let cancel;\n const waitForTransactionCallback = async (data) => {\n if (data && data[0] === options.txHash && data[1] !== null) {\n txHashSeen = true;\n await cancel?.();\n resolve(makeResponse(options.txHash));\n }\n };\n cancel = await this.provider.subscribeToTransaction(options.txHash, waitForTransactionCallback);\n return;\n }\n // waiting for any address transaction\n let watchCancel;\n let initialResponseSeen = false;\n watchCancel = await this.provider.watchAddressStatus(this.getDepositAddress(), async (_status) => {\n if (initialResponseSeen) {\n await watchCancel?.();\n resolve(makeResponse());\n return;\n }\n initialResponseSeen = true;\n });\n });\n }\n /**\n * watchBlocks Watch network blocks\n *\n * @param callback callback with a block header object\n * @param skipCurrentHeight if set, the notification about current block will not arrive\n *\n * @returns a function which will cancel watching upon evaluation\n */\n async watchBlocks(callback, skipCurrentHeight = true) {\n return this.provider.watchBlocks(callback, skipCurrentHeight);\n }\n /**\n * waitForBlock Wait for a network block\n *\n * @param height if specified waits for this exact blockchain height, otherwise resolves with the next block\n *\n */\n async waitForBlock(height) {\n return this.provider.waitForBlock(height);\n }\n //#endregion Funds\n //#region Cashtokens\n /**\n * Create new cashtoken, both funglible and/or non-fungible (NFT)\n * Refer to spec https://github.com/bitjson/cashtokens\n * @param {number} genesisRequest.amount amount of *fungible* tokens to create\n * @param {NFTCapability?} genesisRequest.capability capability of new NFT\n * @param {string?} genesisRequest.commitment NFT commitment message\n * @param {string?} genesisRequest.cashaddr cash address to send the created token UTXO to; if undefined will default to your address\n * @param {number?} genesisRequest.value satoshi value to send alongside with tokens; if undefined will default to 1000 satoshi\n * @param {SendRequestType | SendRequestType[]} sendRequests single or an array of extra send requests (OP_RETURN, value transfer, etc.) to include in genesis transaction\n * @param {SendRequestOptionsI} options Options of the send requests\n */\n async tokenGenesis(genesisRequest, sendRequests = [], options) {\n if (!Array.isArray(sendRequests)) {\n sendRequests = [sendRequests];\n }\n let utxos = await this.getUtxos();\n if (options?.utxoIds) {\n utxos = await (0,_util_checkUtxos_js__WEBPACK_IMPORTED_MODULE_6__.checkUtxos)(options.utxoIds.map((utxoId) => typeof utxoId === \"string\" ? (0,_model_js__WEBPACK_IMPORTED_MODULE_7__.fromUtxoId)(utxoId) : utxoId), utxos);\n }\n const genesisInputs = utxos.filter((val) => val.vout === 0 && !val.token);\n if (genesisInputs.length === 0) {\n throw new Error(\"No suitable inputs with vout=0 available for new token genesis\");\n }\n const genesisSendRequest = new _model_js__WEBPACK_IMPORTED_MODULE_7__.TokenSendRequest({\n cashaddr: genesisRequest.cashaddr || this.getTokenDepositAddress(),\n amount: genesisRequest.amount,\n value: genesisRequest.value || 1000n,\n nft: genesisRequest.nft,\n category: genesisInputs[0].txid,\n });\n return this.send([genesisSendRequest, ...sendRequests], {\n ...options,\n utxoIds: utxos,\n ensureUtxos: [genesisInputs[0]],\n checkTokenQuantities: false,\n queryBalance: false,\n tokenOperation: \"genesis\",\n });\n }\n /**\n * Mint new NFT cashtokens using an existing minting token\n * Refer to spec https://github.com/bitjson/cashtokens\n * @param {string} category category of an NFT to mint\n * @param {TokenMintRequest | TokenMintRequest[]} mintRequests mint requests with new token properties and recipients\n * @param {NFTCapability?} mintRequest.capability capability of new NFT\n * @param {string?} mintRequest.commitment NFT commitment message\n * @param {string?} mintRequest.cashaddr cash address to send the created token UTXO to; if undefined will default to your address\n * @param {number?} mintRequest.value satoshi value to send alongside with tokens; if undefined will default to 1000 satoshi\n * @param {boolean?} deductTokenAmount if minting token contains fungible amount, deduct from it by amount of minted tokens\n * @param {SendRequestOptionsI} options Options of the send requests\n */\n async tokenMint(category, mintRequests, deductTokenAmount = false, options) {\n if (category?.length !== 64) {\n throw Error(`Invalid category supplied: ${category}`);\n }\n if (!Array.isArray(mintRequests)) {\n mintRequests = [mintRequests];\n }\n const utxos = await this.getUtxos();\n const nftUtxos = utxos.filter((val) => val.token?.category === category &&\n val.token?.nft?.capability === _interface_js__WEBPACK_IMPORTED_MODULE_13__.NFTCapability.minting);\n if (!nftUtxos.length) {\n throw new Error(\"You do not have any token UTXOs with minting capability for specified category\");\n }\n const newAmount = deductTokenAmount && nftUtxos[0].token.amount > 0\n ? nftUtxos[0].token.amount - BigInt(mintRequests.length)\n : nftUtxos[0].token.amount;\n const safeNewAmount = newAmount < 0n ? 0n : newAmount;\n const mintingInput = new _model_js__WEBPACK_IMPORTED_MODULE_7__.TokenSendRequest({\n cashaddr: (0,_util_index_js__WEBPACK_IMPORTED_MODULE_11__.toTokenaddr)(nftUtxos[0].address),\n category: category,\n nft: nftUtxos[0].token?.nft,\n amount: safeNewAmount,\n value: nftUtxos[0].satoshis,\n });\n return this.send([\n mintingInput,\n ...mintRequests.map((val) => new _model_js__WEBPACK_IMPORTED_MODULE_7__.TokenSendRequest({\n cashaddr: val.cashaddr || this.getTokenDepositAddress(),\n amount: 0n,\n category: category,\n value: val.value,\n nft: val.nft,\n })),\n ], {\n ...options,\n ensureUtxos: [nftUtxos[0]],\n checkTokenQuantities: false,\n queryBalance: false,\n tokenOperation: \"mint\",\n });\n }\n /**\n * Perform an explicit token burning by spending a token utxo to an OP_RETURN\n *\n * Behaves differently for fungible and non-fungible tokens:\n * * NFTs are always \"destroyed\"\n * * FTs' amount is reduced by the amount specified, if 0 FT amount is left and no NFT present, the token is \"destroyed\"\n *\n * Refer to spec https://github.com/bitjson/cashtokens\n * @param {string} burnRequest.category category of a token to burn\n * @param {NFTCapability} burnRequest.capability capability of the NFT token to select, optional\n * @param {string?} burnRequest.commitment commitment of the NFT token to select, optional\n * @param {number?} burnRequest.amount amount of fungible tokens to burn, optional\n * @param {string?} burnRequest.cashaddr address to return token and satoshi change to\n * @param {string?} message optional message to include in OP_RETURN\n * @param {SendRequestOptionsI} options Options of the send requests\n */\n async tokenBurn(burnRequest, message, options) {\n if (burnRequest.category?.length !== 64) {\n throw Error(`Invalid category supplied: ${burnRequest.category}`);\n }\n const utxos = await this.getUtxos();\n const tokenUtxos = utxos.filter((val) => val.token?.category === burnRequest.category &&\n val.token?.nft?.capability === burnRequest.nft?.capability &&\n val.token?.nft?.commitment === burnRequest.nft?.commitment);\n if (!tokenUtxos.length) {\n throw new Error(\"You do not have suitable token UTXOs to perform burn\");\n }\n const totalFungibleAmount = tokenUtxos.reduce((prev, cur) => prev + (cur.token?.amount || 0n), 0n);\n let fungibleBurnAmount = burnRequest.amount && burnRequest.amount > 0 ? burnRequest.amount : 0n;\n fungibleBurnAmount = BigInt(fungibleBurnAmount);\n const hasNFT = burnRequest.nft !== undefined;\n let utxoIds = [];\n let changeSendRequests;\n if (hasNFT) {\n // does not have FT tokens, let us destroy the token completely\n if (totalFungibleAmount === 0n) {\n changeSendRequests = [];\n utxoIds.push(tokenUtxos[0]);\n }\n else {\n // add utxos to spend from\n let available = 0n;\n for (const token of tokenUtxos.filter((val) => val.token?.amount)) {\n utxoIds.push(token);\n available += token.token.amount;\n if (available >= fungibleBurnAmount) {\n break;\n }\n }\n // if there are FT, reduce their amount\n const newAmount = totalFungibleAmount - fungibleBurnAmount;\n const safeNewAmount = newAmount < 0n ? 0n : newAmount;\n changeSendRequests = [\n new _model_js__WEBPACK_IMPORTED_MODULE_7__.TokenSendRequest({\n cashaddr: burnRequest.cashaddr || (0,_util_index_js__WEBPACK_IMPORTED_MODULE_11__.toTokenaddr)(this.getChangeAddress()),\n category: burnRequest.category,\n nft: burnRequest.nft,\n amount: safeNewAmount,\n value: tokenUtxos[0].satoshis,\n }),\n ];\n }\n }\n else {\n // if we are burning last fungible tokens, let us destroy the token completely\n if (totalFungibleAmount === fungibleBurnAmount) {\n changeSendRequests = [];\n utxoIds.push(...tokenUtxos);\n }\n else {\n // add utxos to spend from\n let available = 0n;\n for (const token of tokenUtxos.filter((val) => val.token?.amount)) {\n utxoIds.push(token);\n available += token.token.amount;\n if (available >= fungibleBurnAmount) {\n break;\n }\n }\n // reduce the FT amount\n const newAmount = available - fungibleBurnAmount;\n const safeNewAmount = newAmount < 0n ? 0n : newAmount;\n changeSendRequests = [\n new _model_js__WEBPACK_IMPORTED_MODULE_7__.TokenSendRequest({\n cashaddr: burnRequest.cashaddr || (0,_util_index_js__WEBPACK_IMPORTED_MODULE_11__.toTokenaddr)(this.getChangeAddress()),\n category: burnRequest.category,\n amount: safeNewAmount,\n value: tokenUtxos.reduce((a, c) => a + c.satoshis, 0n),\n }),\n ];\n }\n }\n const opReturn = _model_js__WEBPACK_IMPORTED_MODULE_7__.OpReturnData.fromString(message || \"\");\n return this.send([opReturn, ...changeSendRequests], {\n ...options,\n checkTokenQuantities: false,\n queryBalance: false,\n ensureUtxos: utxoIds.length > 0 ? utxoIds : undefined,\n tokenOperation: \"burn\",\n });\n }\n /**\n * getTokenUtxos Get unspent token outputs for the wallet\n * will return utxos only for the specified token if `category` provided\n * @param {string?} category category to filter utxos by, if not set will return utxos from all tokens\n * @returns {Utxo[]} token utxos\n */\n async getTokenUtxos(category) {\n const utxos = await this.getUtxos();\n return utxos.filter((val) => category ? val.token?.category === category : val.token);\n }\n /**\n * getTokenBalance Gets fungible token balance\n * for NFT token balance see @ref getNftTokenBalance\n * @param {string} category category to get balance for\n * @returns {bigint} fungible token balance\n */\n async getTokenBalance(category) {\n const utxos = (await this.getTokenUtxos(category)).filter((val) => val.token?.amount);\n return (0,_util_index_js__WEBPACK_IMPORTED_MODULE_5__.sumTokenAmounts)(utxos, category);\n }\n /**\n * getNftTokenBalance Gets non-fungible token (NFT) balance for a particular category\n * disregards fungible token balances\n * for fungible token balance see @ref getTokenBalance\n * @param {string} category category to get balance for\n * @returns {number} non-fungible token balance\n */\n async getNftTokenBalance(category) {\n const utxos = (await this.getTokenUtxos(category)).filter((val) => val.token?.nft?.commitment !== undefined);\n return utxos.length;\n }\n /**\n * getAllTokenBalances Gets all fungible token balances in this wallet\n * @returns {Object} a map [category => balance] for all tokens in this wallet\n */\n async getAllTokenBalances() {\n const result = {};\n const utxos = (await this.getTokenUtxos()).filter((val) => val.token?.amount);\n for (const utxo of utxos) {\n if (!result[utxo.token.category]) {\n result[utxo.token.category] = 0n;\n }\n result[utxo.token.category] += utxo.token.amount;\n }\n return result;\n }\n /**\n * getAllNftTokenBalances Gets all non-fungible token (NFT) balances in this wallet\n * @returns {Object} a map [category => balance] for all NFTs in this wallet\n */\n async getAllNftTokenBalances() {\n const result = {};\n const utxos = (await this.getTokenUtxos()).filter((val) => val.token?.nft?.commitment !== undefined);\n for (const utxo of utxos) {\n if (!result[utxo.token.category]) {\n result[utxo.token.category] = 0;\n }\n result[utxo.token.category] += 1;\n }\n return result;\n }\n //#endregion Cashtokens\n sign(message, privateKey = undefined) {\n if (!privateKey) {\n throw new Error(\"Signing private key not provided\");\n }\n return new _message_signed_js__WEBPACK_IMPORTED_MODULE_14__.SignedMessage().sign(message, privateKey);\n }\n // Convenience wrapper to verify interface\n verify(message, sig, address, publicKey) {\n if (!address && !publicKey) {\n throw new Error(\"Either address or publicKey must be provided for verification\");\n }\n return new _message_signed_js__WEBPACK_IMPORTED_MODULE_14__.SignedMessage().verify(message, sig, address, publicKey);\n }\n}\n/**\n * _checkContextSafety (internal) if running in nodejs, will disable saving\n * mainnet wallets on public servers if ALLOW_MAINNET_USER_WALLETS is set to false\n * @param {BaseWallet} wallet a wallet\n */\nconst _checkContextSafety = function (wallet) {\n if ((0,_util_index_js__WEBPACK_IMPORTED_MODULE_15__.getRuntimePlatform)() === \"node\") {\n if (process.env.ALLOW_MAINNET_USER_WALLETS === `false`) {\n if (wallet.network === _enum_js__WEBPACK_IMPORTED_MODULE_2__.NetworkType.Mainnet) {\n throw Error(`Refusing to save wallet in an open public database, remove ALLOW_MAINNET_USER_WALLETS=\"false\", if this service is secure and private`);\n }\n }\n }\n};\n/**\n * getNamedWalletId - get the full wallet id from the database\n *\n * @param name user friendly wallet alias\n * @param dbName name under which the wallet will be stored in the database\n *\n * @returns boolean\n */\nasync function getNamedWalletId(name, dbName) {\n if (name.length === 0) {\n throw Error(\"Named wallets must have a non-empty name\");\n }\n dbName = dbName ? dbName : dbName;\n let db = getStorageProvider(dbName);\n if (db) {\n await db.init();\n let savedWalletRecord = await db.getWallet(name);\n await db.close();\n if (savedWalletRecord !== undefined) {\n return savedWalletRecord.wallet;\n }\n else {\n throw Error(`No record was found for ${name} in db: ${dbName}`);\n }\n }\n else {\n throw Error(\"No database was available or configured to store the named wallet.\");\n }\n}\nfunction getStorageProvider(dbName) {\n if (!BaseWallet.StorageProvider) {\n return undefined;\n }\n return new BaseWallet.StorageProvider(dbName);\n}\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/wallet/Base.ts?");
|
|
658
638
|
|
|
659
639
|
/***/ }),
|
|
660
640
|
|
|
@@ -674,7 +654,7 @@ eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__
|
|
|
674
654
|
\****************************/
|
|
675
655
|
/***/ ((module, __webpack_exports__, __webpack_require__) => {
|
|
676
656
|
|
|
677
|
-
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 */ \"Util\": () => (/* binding */ Util)\n/* harmony export */ });\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/hex.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/message/transaction-encoding.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/address/locking-bytecode.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/compiler/p2pkh-utils.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/error.js\");\n/* harmony import */ var _chain_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../chain.js */ \"./src/chain.ts\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../enum.js */ \"./src/enum.ts\");\n/* harmony import */ var _network_default_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../network/default.js */ \"./src/network/default.ts\");\n/* harmony import */ var _util_transaction_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../util/transaction.js */ \"./src/util/transaction.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_network_default_js__WEBPACK_IMPORTED_MODULE_0__, _enum_js__WEBPACK_IMPORTED_MODULE_1__, _util_transaction_js__WEBPACK_IMPORTED_MODULE_2__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_5__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__]);\n([_network_default_js__WEBPACK_IMPORTED_MODULE_0__, _enum_js__WEBPACK_IMPORTED_MODULE_1__, _util_transaction_js__WEBPACK_IMPORTED_MODULE_2__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__, _bitauth_libauth__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\n/**\n * Class with various wallet utilities.\n */\nclass Util {\n /**\n * Initializes a wallet Util class.\n *\n * @param network The network type to use. Defaults to mainnet.\n */\n constructor(network = _enum_js__WEBPACK_IMPORTED_MODULE_1__.NetworkType.Mainnet) {\n this.network = network;\n this.provider = (0,_network_default_js__WEBPACK_IMPORTED_MODULE_0__.getNetworkProvider)(network);\n }\n async getTransactionHash(rawTransactionHex) {\n return (0,_util_transaction_js__WEBPACK_IMPORTED_MODULE_2__.getTransactionHash)(rawTransactionHex);\n }\n static async getTransactionHash(rawTransactionHex) {\n return (0,_util_transaction_js__WEBPACK_IMPORTED_MODULE_2__.getTransactionHash)(rawTransactionHex);\n }\n async decodeTransaction(transactionHashOrHex, loadInputValues = false) {\n let transactionHex;\n let transactionBin;\n let txHash;\n // raw transaction\n if (transactionHashOrHex.length > 64) {\n txHash = await this.getTransactionHash(transactionHashOrHex);\n transactionBin = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.hexToBin)(transactionHashOrHex);\n transactionHex = transactionHashOrHex;\n }\n else {\n // tx hash, look up the raw transaction\n txHash = transactionHashOrHex;\n transactionHex = await this.provider.getRawTransaction(txHash);\n transactionBin = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.hexToBin)(transactionHex);\n }\n const result = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__.decodeTransaction)(transactionBin);\n if (typeof result === \"string\") {\n throw Error(result);\n }\n const transaction = this.mapToElectrumRawTransaction(result, txHash, transactionHex);\n if (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.decodeTransaction(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 mapToElectrumRawTransaction(transaction, txHash, txHex) {\n let result = {};\n result.vin = transaction.inputs.map((input) => {\n return {\n scriptSig: {\n hex: (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.binToHex)(input.unlockingBytecode),\n },\n sequence: input.sequenceNumber,\n txid: (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.binToHex)(input.outpointTransactionHash),\n vout: input.outpointIndex,\n };\n });\n result.vout = transaction.outputs.map((output, index) => {\n return {\n n: index,\n scriptPubKey: {\n addresses: [\n (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_5__.isPayToPublicKey)(output.lockingBytecode)\n ? (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__.publicKeyToP2pkhCashAddress)({\n publicKey: (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_5__.lockingBytecodeToAddressContents)(output.lockingBytecode).payload,\n prefix: _enum_js__WEBPACK_IMPORTED_MODULE_1__.prefixFromNetworkMap[this.network],\n })\n : (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__.assertSuccess)((0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_5__.lockingBytecodeToCashAddress)({\n bytecode: output.lockingBytecode,\n prefix: _enum_js__WEBPACK_IMPORTED_MODULE_1__.prefixFromNetworkMap[this.network],\n })).address,\n ],\n hex: (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.binToHex)(output.lockingBytecode),\n },\n value: Number(output.valueSatoshis) / _chain_js__WEBPACK_IMPORTED_MODULE_8__.bchParam.subUnits,\n };\n });\n result.locktime = transaction.locktime;\n result.version = transaction.version;\n result.hash = txHash;\n result.hex = txHex;\n result.txid = txHash;\n result.size = txHex.length / 2;\n return result;\n }\n static async decodeTransaction(transactionHashOrHex, loadInputValues = false, network) {\n return new this(network).decodeTransaction(transactionHashOrHex, loadInputValues);\n }\n}\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/wallet/Util.ts?");
|
|
657
|
+
eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"Util\": () => (/* binding */ Util)\n/* harmony export */ });\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/hex.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/message/transaction-encoding.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/address/locking-bytecode.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/compiler/p2pkh-utils.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/error.js\");\n/* harmony import */ var _chain_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../chain.js */ \"./src/chain.ts\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../enum.js */ \"./src/enum.ts\");\n/* harmony import */ var _network_default_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../network/default.js */ \"./src/network/default.ts\");\n/* harmony import */ var _util_transaction_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../util/transaction.js */ \"./src/util/transaction.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_network_default_js__WEBPACK_IMPORTED_MODULE_0__, _enum_js__WEBPACK_IMPORTED_MODULE_1__, _util_transaction_js__WEBPACK_IMPORTED_MODULE_2__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_5__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__]);\n([_network_default_js__WEBPACK_IMPORTED_MODULE_0__, _enum_js__WEBPACK_IMPORTED_MODULE_1__, _util_transaction_js__WEBPACK_IMPORTED_MODULE_2__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__, _bitauth_libauth__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\n/**\n * Class with various wallet utilities.\n */\nclass Util {\n /**\n * Initializes a wallet Util class.\n *\n * @param network The network type to use. Defaults to mainnet.\n */\n constructor(network = _enum_js__WEBPACK_IMPORTED_MODULE_1__.NetworkType.Mainnet) {\n this.network = network;\n this.provider = (0,_network_default_js__WEBPACK_IMPORTED_MODULE_0__.getNetworkProvider)(network);\n }\n async getTransactionHash(rawTransactionHex) {\n return (0,_util_transaction_js__WEBPACK_IMPORTED_MODULE_2__.getTransactionHash)(rawTransactionHex);\n }\n static async getTransactionHash(rawTransactionHex) {\n return (0,_util_transaction_js__WEBPACK_IMPORTED_MODULE_2__.getTransactionHash)(rawTransactionHex);\n }\n async decodeTransaction(transactionHashOrHex, loadInputValues = false) {\n let transactionHex;\n let transactionBin;\n let txHash;\n // raw transaction\n if (transactionHashOrHex.length > 64) {\n txHash = await this.getTransactionHash(transactionHashOrHex);\n transactionBin = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.hexToBin)(transactionHashOrHex);\n transactionHex = transactionHashOrHex;\n }\n else {\n // tx hash, look up the raw transaction\n txHash = transactionHashOrHex;\n transactionHex = await this.provider.getRawTransaction(txHash);\n transactionBin = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.hexToBin)(transactionHex);\n }\n const result = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__.decodeTransaction)(transactionBin);\n if (typeof result === \"string\") {\n throw Error(result);\n }\n const transaction = this.mapToElectrumRawTransaction(result, txHash, transactionHex);\n if (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.decodeTransaction(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 mapToElectrumRawTransaction(transaction, txHash, txHex) {\n let result = {};\n result.vin = transaction.inputs.map((input) => {\n return {\n scriptSig: {\n hex: (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.binToHex)(input.unlockingBytecode),\n },\n sequence: input.sequenceNumber,\n txid: (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.binToHex)(input.outpointTransactionHash),\n vout: input.outpointIndex,\n };\n });\n result.vout = transaction.outputs.map((output, index) => {\n return {\n n: index,\n scriptPubKey: {\n addresses: [\n (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_5__.isPayToPublicKey)(output.lockingBytecode)\n ? (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_6__.publicKeyToP2pkhCashAddress)({\n publicKey: (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_5__.lockingBytecodeToAddressContents)(output.lockingBytecode).payload,\n prefix: _enum_js__WEBPACK_IMPORTED_MODULE_1__.prefixFromNetworkMap[this.network],\n })\n : (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__.assertSuccess)((0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_5__.lockingBytecodeToCashAddress)({\n bytecode: output.lockingBytecode,\n prefix: _enum_js__WEBPACK_IMPORTED_MODULE_1__.prefixFromNetworkMap[this.network],\n })).address,\n ],\n hex: (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.binToHex)(output.lockingBytecode),\n },\n value: Number(output.valueSatoshis) / Number(_chain_js__WEBPACK_IMPORTED_MODULE_8__.bchParam.subUnits),\n };\n });\n result.locktime = transaction.locktime;\n result.version = transaction.version;\n result.hash = txHash;\n result.hex = txHex;\n result.txid = txHash;\n result.size = txHex.length / 2;\n return result;\n }\n static async decodeTransaction(transactionHashOrHex, loadInputValues = false, network) {\n return new this(network).decodeTransaction(transactionHashOrHex, loadInputValues);\n }\n}\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/wallet/Util.ts?");
|
|
678
658
|
|
|
679
659
|
/***/ }),
|
|
680
660
|
|
|
@@ -724,7 +704,7 @@ eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harm
|
|
|
724
704
|
\*****************************/
|
|
725
705
|
/***/ ((module, __webpack_exports__, __webpack_require__) => {
|
|
726
706
|
|
|
727
|
-
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
|
|
707
|
+
eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"OpReturnData\": () => (/* binding */ OpReturnData),\n/* harmony export */ \"SendRequest\": () => (/* binding */ SendRequest),\n/* harmony export */ \"SendResponse\": () => (/* binding */ SendResponse),\n/* harmony export */ \"TokenBurnRequest\": () => (/* binding */ TokenBurnRequest),\n/* harmony export */ \"TokenGenesisRequest\": () => (/* binding */ TokenGenesisRequest),\n/* harmony export */ \"TokenMintRequest\": () => (/* binding */ TokenMintRequest),\n/* harmony export */ \"TokenSendRequest\": () => (/* binding */ TokenSendRequest),\n/* harmony export */ \"XPubKey\": () => (/* binding */ XPubKey),\n/* harmony export */ \"fromUtxoId\": () => (/* binding */ fromUtxoId),\n/* harmony export */ \"toUtxoId\": () => (/* binding */ toUtxoId)\n/* harmony export */ });\n/* harmony import */ var _constant_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../constant.js */ \"./src/constant.ts\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/utf8.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/number.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/hex.js\");\n/* harmony import */ var _config_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../config.js */ \"./src/config.ts\");\n/* harmony import */ var _util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../util/deriveCashaddr.js */ \"./src/util/deriveCashaddr.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_0__]);\n_util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_0__ = (__webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__)[0];\n\n\n\n\nclass SendRequest {\n constructor({ cashaddr, value }) {\n this.cashaddr = cashaddr;\n this.value = BigInt(value);\n }\n}\nclass TokenGenesisRequest {\n constructor({ amount, nft, cashaddr, value, }) {\n this.amount = amount;\n this.nft = nft;\n this.cashaddr = cashaddr;\n this.value = value;\n }\n}\nclass TokenBurnRequest {\n constructor({ category, amount, nft, cashaddr, }) {\n this.category = category;\n this.amount = amount ? BigInt(amount) : 0n;\n this.nft = nft;\n this.cashaddr = cashaddr;\n }\n}\nclass TokenSendRequest {\n constructor({ cashaddr, value, amount, category, nft, }) {\n (0,_util_deriveCashaddr_js__WEBPACK_IMPORTED_MODULE_0__.checkTokenaddr)(cashaddr, _config_js__WEBPACK_IMPORTED_MODULE_1__.Config.EnforceCashTokenReceiptAddresses);\n this.cashaddr = cashaddr;\n this.value = value;\n this.amount = amount ? BigInt(amount) : 0n;\n this.category = category;\n this.nft = nft;\n }\n}\nclass TokenMintRequest {\n constructor({ nft, cashaddr, value, }) {\n this.nft = nft;\n this.cashaddr = cashaddr;\n this.value = value;\n }\n}\nclass OpReturnData {\n constructor(buffer) {\n this.buffer = Uint8Array.from(buffer);\n }\n /**\n * from - Construct OP_RETURN data from arbitrary data type\n *\n * @param string UTF-8 encoded string message to be converted to OP_RETURN data\n *\n * @returns class instance\n */\n static from(data) {\n return this.fromArray([data]);\n }\n /**\n * fromString - Accept data as a simple UTF-8 string message and append an OP_RETURN and PUSH_DATA1 opcodes to it\n *\n * @param string UTF-8 encoded string message to be converted to OP_RETURN data\n *\n * @returns class instance\n */\n static fromString(string) {\n return this.fromArray([string]);\n }\n /**\n * buffer - Accept OP_RETURN data as a binary buffer.\n * If buffer lacks the OP_RETURN and OP_PUSHDATA opcodes, they will be prepended.\n *\n * @param buffer Data buffer to be assigned to the OP_RETURN outpit\n *\n * @returns class instance\n */\n static fromUint8Array(uint8Array) {\n if (uint8Array[0] !== 0x6a) {\n return this.fromArray([uint8Array]);\n }\n return new this(Uint8Array.from(uint8Array));\n }\n /**\n * fromArray - Accept array of data\n *\n * @param array Array of Uint8Array or UTF-8 encoded string messages to be converted to OP_RETURN data\n *\n * @returns class instance\n */\n static fromArray(array) {\n let data = Uint8Array.from([0x6a]); // OP_RETURN\n for (const element of array) {\n let length;\n let elementData;\n let lengthData;\n if (typeof element === \"string\") {\n elementData = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.utf8ToBin)(element);\n length = elementData.length;\n }\n else if (element instanceof Uint8Array) {\n elementData = element;\n length = elementData.length;\n }\n else {\n throw new Error(\"Wrong data array element\");\n }\n if (length < 76) {\n // OP_PUSHDATA_1\n lengthData = [length];\n }\n else if (length < 223) {\n // default max `-datacarriersize`\n lengthData = [0x4c, length];\n }\n else {\n throw new Error(\"OP_RETURN data can not exceed 220 bytes in size\");\n }\n data = Uint8Array.from([...data, ...lengthData, ...elementData]);\n }\n if (data.length > 220) {\n throw new Error(\"OP_RETURN data can not exceed 220 bytes in size\");\n }\n return new this(data);\n }\n /**\n * parseBinary - parse OP_RETURN data and return pushed chunks of binary data\n *\n * @param opReturn Raw OP_RETURN data\n *\n * @returns array of binary data chunks pushed\n */\n static parseBinary(opReturn) {\n const chunks = [];\n let position = 1;\n // handle direct push, OP_PUSHDATA1, OP_PUSHDATA2;\n // OP_PUSHDATA4 is not supported in OP_RETURNs by consensus\n while (opReturn[position]) {\n let length = 0;\n if (opReturn[position] === 0x4c) {\n length = opReturn[position + 1];\n position += 2;\n }\n else if (opReturn[position] === 0x4d) {\n length = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.binToNumberUint16LE)(opReturn.slice(position + 1, position + 3));\n position += 3;\n }\n else {\n length = opReturn[position];\n position += 1;\n }\n chunks.push(opReturn.slice(position, position + length));\n position += length;\n }\n return chunks;\n }\n /**\n * parse - parse OP_RETURN hex data and return pushed chunks of binary data, converted to utf8 strings\n *\n * @param opReturn Raw OP_RETURN hex data\n *\n * @returns array of binary data chunks pushed, converted to utf8 strings\n */\n static parse(opReturnHex) {\n return this.parseBinary((0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_4__.hexToBin)(opReturnHex)).map((val) => (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.binToUtf8)(val));\n }\n}\nclass SendResponse {\n constructor({ txId, balance, explorerUrl, }) {\n this.txId = txId;\n this.balance = balance;\n this.explorerUrl = explorerUrl;\n }\n}\nclass XPubKey {\n constructor({ path, xPubKey }) {\n this.path = path;\n this.xPubKey = xPubKey;\n }\n async ready() {\n await this.xPubKey;\n return this.asObject();\n }\n asObject() {\n return {\n path: this.path,\n xPubKey: this.xPubKey,\n };\n }\n}\nconst fromUtxoId = (utxoId) => {\n const [txid, vout, satoshis] = utxoId.split(_constant_js__WEBPACK_IMPORTED_MODULE_5__.DELIMITER);\n return {\n satoshis: satoshis ? BigInt(parseInt(satoshis)) : 0n,\n vout: parseInt(vout),\n txid,\n };\n};\nconst toUtxoId = (utxo) => {\n return [utxo.txid, utxo.vout].join(_constant_js__WEBPACK_IMPORTED_MODULE_5__.DELIMITER).replace(/:+$/, \"\");\n};\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/wallet/model.ts?");
|
|
728
708
|
|
|
729
709
|
/***/ }),
|
|
730
710
|
|