@unisat/wallet-state 1.0.1 → 1.0.4

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/lib/index.mjs ADDED
@@ -0,0 +1,2273 @@
1
+ import { save, load } from 'redux-localstorage-simple';
2
+ import { createAction, createSlice, configureStore } from '@reduxjs/toolkit';
3
+ import { setupListeners } from '@reduxjs/toolkit/dist/query/react/index.js';
4
+ import { ChainType, AddressType, NetworkType } from '@unisat/wallet-types';
5
+ import { DEFAULT_LOCKTIME_ID, CHAINS_MAP, CAT_VERSION, VERSION } from '@unisat/wallet-shared';
6
+ import log from 'loglevel';
7
+ import { createContext, useContext, useState, useEffect, useCallback, useMemo, useRef } from 'react';
8
+ import { FALLBACK_LOCALE, getSupportedLocales, LOCALE_NAMES, t, getCurrentLocaleAsync, BROWSER_TO_APP_LOCALE_MAP, initI18n, changeLanguage } from '@unisat/i18n';
9
+ import { jsx, jsxs } from 'react/jsx-runtime';
10
+ import compareVersions from 'compare-versions';
11
+ import i18n from 'i18next';
12
+ import { initReactI18next } from 'react-i18next';
13
+ import { BABYLON_CONFIG_MAP } from '@unisat/babylon-service/types';
14
+ import { KeyringType } from '@unisat/keyring-service/types';
15
+ import { useDispatch, useSelector } from 'react-redux';
16
+ import { useNavigate, useLocation } from 'react-router-dom';
17
+ import { timeUtils, numUtils } from '@unisat/base-utils';
18
+
19
+ // src/index.ts
20
+ var updateVersion = createAction("global/updateVersion");
21
+
22
+ // src/reducers/accounts.ts
23
+ var initialAccount = {
24
+ type: "",
25
+ address: "",
26
+ brandName: "",
27
+ alianName: "",
28
+ displayBrandName: "",
29
+ index: 0,
30
+ balance: 0,
31
+ pubkey: "",
32
+ key: "",
33
+ flag: 0
34
+ };
35
+ var initialState = {
36
+ accounts: [],
37
+ current: initialAccount,
38
+ loading: false,
39
+ balanceMap: {},
40
+ balanceV2Map: {},
41
+ historyMap: {},
42
+ inscriptionsMap: {},
43
+ appSummary: {
44
+ apps: []
45
+ },
46
+ inscriptionSummary: {
47
+ mintedList: []
48
+ },
49
+ addressSummary: {
50
+ totalSatoshis: 0,
51
+ btcSatoshis: 0,
52
+ assetSatoshis: 0,
53
+ inscriptionCount: 0,
54
+ brc20Count: 0,
55
+ brc20Count5Byte: 0,
56
+ brc20Count6Byte: 0,
57
+ loading: true,
58
+ address: "",
59
+ runesCount: 0
60
+ }
61
+ };
62
+ var slice = createSlice({
63
+ name: "accounts",
64
+ initialState,
65
+ reducers: {
66
+ pendingLogin(state) {
67
+ state.loading = true;
68
+ },
69
+ setCurrent(state, action) {
70
+ const { payload } = action;
71
+ state.current = payload || initialAccount;
72
+ },
73
+ setAccounts(state, action) {
74
+ const { payload } = action;
75
+ state.accounts = payload;
76
+ },
77
+ setBalance(state, action) {
78
+ const {
79
+ payload: {
80
+ address,
81
+ amount,
82
+ btc_amount,
83
+ inscription_amount,
84
+ confirm_btc_amount,
85
+ pending_btc_amount
86
+ }
87
+ } = action;
88
+ state.balanceMap[address] = state.balanceMap[address] || {
89
+ amount: "0",
90
+ btc_amount: "0",
91
+ inscription_amount: "0",
92
+ confirm_btc_amount: "0",
93
+ pending_btc_amount: "0",
94
+ expired: true
95
+ };
96
+ state.balanceMap[address].amount = amount;
97
+ state.balanceMap[address].btc_amount = btc_amount;
98
+ state.balanceMap[address].inscription_amount = inscription_amount;
99
+ state.balanceMap[address].confirm_btc_amount = confirm_btc_amount;
100
+ state.balanceMap[address].pending_btc_amount = pending_btc_amount;
101
+ state.balanceMap[address].expired = false;
102
+ },
103
+ setBalanceV2(state, action) {
104
+ const {
105
+ payload: {
106
+ balance: { availableBalance, unavailableBalance, totalBalance },
107
+ address
108
+ }
109
+ } = action;
110
+ state.balanceV2Map[address] = state.balanceV2Map[address] || {
111
+ availableBalance: 0,
112
+ unavailableBalance: 0,
113
+ totalBalance: 0
114
+ };
115
+ state.balanceV2Map[address].availableBalance = availableBalance;
116
+ state.balanceV2Map[address].unavailableBalance = unavailableBalance;
117
+ state.balanceV2Map[address].totalBalance = totalBalance;
118
+ },
119
+ setAddressSummary(state, action) {
120
+ state.addressSummary = action.payload;
121
+ },
122
+ expireBalance(state) {
123
+ const balance = state.balanceMap[state.current.address];
124
+ if (balance) {
125
+ balance.expired = true;
126
+ }
127
+ },
128
+ setHistory(state, action) {
129
+ const {
130
+ payload: { address, list }
131
+ } = action;
132
+ state.historyMap[address] = state.historyMap[address] || {
133
+ list: [],
134
+ expired: true
135
+ };
136
+ state.historyMap[address].list = list;
137
+ state.historyMap[address].expired = false;
138
+ },
139
+ expireHistory(state) {
140
+ const history = state.historyMap[state.current.address];
141
+ if (history) {
142
+ history.expired = true;
143
+ }
144
+ },
145
+ setInscriptions(state, action) {
146
+ const {
147
+ payload: { address, list }
148
+ } = action;
149
+ state.inscriptionsMap[address] = state.inscriptionsMap[address] || {
150
+ list: [],
151
+ expired: true
152
+ };
153
+ state.inscriptionsMap[address].list = list;
154
+ state.inscriptionsMap[address].expired = false;
155
+ },
156
+ expireInscriptions(state) {
157
+ const inscriptions = state.inscriptionsMap[state.current.address];
158
+ if (inscriptions) {
159
+ inscriptions.expired = true;
160
+ }
161
+ },
162
+ setCurrentAccountName(state, action) {
163
+ const { payload } = action;
164
+ state.current.alianName = payload;
165
+ const account = state.accounts.find((v) => v.address === state.current.address);
166
+ if (account) {
167
+ account.alianName = payload;
168
+ }
169
+ },
170
+ setCurrentAddressFlag(state, action) {
171
+ const { payload } = action;
172
+ state.current.flag = payload;
173
+ const account = state.accounts.find((v) => v.address === state.current.address);
174
+ if (account) {
175
+ account.flag = payload;
176
+ }
177
+ },
178
+ setInscriptionSummary(state, action) {
179
+ const { payload } = action;
180
+ state.inscriptionSummary = payload;
181
+ },
182
+ setAppSummary(state, action) {
183
+ const { payload } = action;
184
+ state.appSummary = payload;
185
+ },
186
+ rejectLogin(state) {
187
+ state.loading = false;
188
+ },
189
+ reset(state) {
190
+ return initialState;
191
+ },
192
+ updateAccountName(state, action) {
193
+ const account = action.payload;
194
+ if (state.current.key === account.key) {
195
+ state.current.alianName = account.alianName;
196
+ }
197
+ state.accounts.forEach((v) => {
198
+ if (v.key === account.key) {
199
+ v.alianName = account.alianName;
200
+ }
201
+ });
202
+ }
203
+ },
204
+ extraReducers: (builder) => {
205
+ builder.addCase(updateVersion, (state) => {
206
+ if (!state.addressSummary) {
207
+ state.addressSummary = {
208
+ totalSatoshis: 0,
209
+ btcSatoshis: 0,
210
+ assetSatoshis: 0,
211
+ inscriptionCount: 0,
212
+ brc20Count: 0,
213
+ brc20Count5Byte: 0,
214
+ brc20Count6Byte: 0,
215
+ loading: true,
216
+ address: "",
217
+ runesCount: 0
218
+ };
219
+ }
220
+ if (!state.balanceV2Map) {
221
+ state.balanceV2Map = {};
222
+ }
223
+ });
224
+ }
225
+ });
226
+ var accountActions = slice.actions;
227
+ var accounts_default = slice.reducer;
228
+ var initialState2 = {
229
+ bannerList: [],
230
+ appList: [],
231
+ lastFetchTime: 0,
232
+ lastFetchChainType: ChainType.BITCOIN_MAINNET,
233
+ cachedBannerIds: [],
234
+ hasNewBanner: true
235
+ };
236
+ var slice2 = createSlice({
237
+ name: "discovery",
238
+ initialState: initialState2,
239
+ reducers: {
240
+ reset(state) {
241
+ return initialState2;
242
+ },
243
+ setBannerList(state, action) {
244
+ const { payload } = action;
245
+ const newBannerIds = payload.bannerList.map((banner) => banner.id);
246
+ const hasNewBanner = newBannerIds.some((id) => !state.cachedBannerIds.includes(id));
247
+ state.bannerList = payload.bannerList;
248
+ state.lastFetchChainType = payload.chainType;
249
+ state.lastFetchTime = payload.fetchTime;
250
+ state.hasNewBanner = hasNewBanner;
251
+ state.cachedBannerIds = newBannerIds;
252
+ },
253
+ setAppList(state, action) {
254
+ const { payload } = action;
255
+ state.appList = payload.appList;
256
+ state.lastFetchChainType = payload.chainType;
257
+ state.lastFetchTime = payload.fetchTime;
258
+ },
259
+ clearNewBannerFlag(state) {
260
+ state.hasNewBanner = false;
261
+ }
262
+ }
263
+ });
264
+ var discoveryActions = slice2.actions;
265
+ var discovery_default = slice2.reducer;
266
+ var initialState3 = {
267
+ tab: "home",
268
+ isUnlocked: false,
269
+ isReady: false,
270
+ isBooted: false
271
+ };
272
+ var reducers = {
273
+ reset: (state) => initialState3,
274
+ update: (state, action) => {
275
+ const { payload } = action;
276
+ state = Object.assign({}, state, payload);
277
+ return state;
278
+ }
279
+ };
280
+ var slice3 = createSlice({
281
+ name: "global",
282
+ initialState: initialState3,
283
+ reducers,
284
+ extraReducers: (builder) => {
285
+ builder.addCase(updateVersion, (state) => {
286
+ });
287
+ }
288
+ });
289
+ var globalActions = slice3.actions;
290
+ var global_default = slice3.reducer;
291
+ var initialKeyring = {
292
+ key: "",
293
+ index: 0,
294
+ type: "",
295
+ addressType: AddressType.P2TR,
296
+ accounts: [],
297
+ alianName: "",
298
+ hdPath: ""
299
+ };
300
+ var initialState4 = {
301
+ keyrings: [],
302
+ current: initialKeyring
303
+ };
304
+ var slice4 = createSlice({
305
+ name: "keyrings",
306
+ initialState: initialState4,
307
+ reducers: {
308
+ setCurrent(state, action) {
309
+ const { payload } = action;
310
+ state.current = payload || initialKeyring;
311
+ },
312
+ setKeyrings(state, action) {
313
+ const { payload } = action;
314
+ state.keyrings = payload;
315
+ },
316
+ reset(state) {
317
+ return initialState4;
318
+ },
319
+ updateKeyringName(state, action) {
320
+ const keyring = action.payload;
321
+ if (state.current.key === keyring.key) {
322
+ state.current.alianName = keyring.alianName;
323
+ }
324
+ state.keyrings.forEach((v) => {
325
+ if (v.key === keyring.key) {
326
+ v.alianName = keyring.alianName;
327
+ }
328
+ });
329
+ },
330
+ updateAccountName(state, action) {
331
+ const account = action.payload;
332
+ state.current.accounts.forEach((v) => {
333
+ if (v.key === account.key) {
334
+ v.alianName = account.alianName;
335
+ }
336
+ });
337
+ state.keyrings.forEach((v) => {
338
+ v.accounts.forEach((w) => {
339
+ if (w.key === account.key) {
340
+ w.alianName = account.alianName;
341
+ }
342
+ });
343
+ });
344
+ }
345
+ },
346
+ extraReducers: (builder) => {
347
+ builder.addCase(updateVersion, (state) => {
348
+ });
349
+ }
350
+ });
351
+ var keyringsActions = slice4.actions;
352
+ var keyrings_default = slice4.reducer;
353
+ var initialState5 = {
354
+ locale: "English",
355
+ networkType: NetworkType.MAINNET,
356
+ chainType: ChainType.BITCOIN_MAINNET,
357
+ walletConfig: {
358
+ version: "",
359
+ moonPayEnabled: true,
360
+ statusMessage: "",
361
+ endpoint: "",
362
+ chainTip: "",
363
+ disableUtxoTools: true
364
+ },
365
+ skippedVersion: "",
366
+ autoLockTimeId: DEFAULT_LOCKTIME_ID,
367
+ developerMode: false
368
+ };
369
+ var slice5 = createSlice({
370
+ name: "settings",
371
+ initialState: initialState5,
372
+ reducers: {
373
+ reset(state) {
374
+ return initialState5;
375
+ },
376
+ updateSettings(state, action) {
377
+ const { payload } = action;
378
+ state = Object.assign({}, state, payload);
379
+ return state;
380
+ }
381
+ },
382
+ extraReducers: (builder) => {
383
+ builder.addCase(updateVersion, (state) => {
384
+ if (!state.networkType) {
385
+ state.networkType = NetworkType.MAINNET;
386
+ }
387
+ });
388
+ }
389
+ });
390
+ var settingsActions = slice5.actions;
391
+ var settings_default = slice5.reducer;
392
+ var initialState6 = {
393
+ bitcoinTx: {
394
+ fromAddress: "",
395
+ toAddress: "",
396
+ toSatoshis: 0,
397
+ rawtx: "",
398
+ txid: "",
399
+ fee: 0,
400
+ estimateFee: 0,
401
+ changeSatoshis: 0,
402
+ sending: false,
403
+ autoAdjust: false,
404
+ psbtHex: "",
405
+ feeRate: 5,
406
+ toDomain: "",
407
+ enableRBF: false
408
+ },
409
+ ordinalsTx: {
410
+ fromAddress: "",
411
+ toAddress: "",
412
+ inscription: {
413
+ inscriptionId: "",
414
+ inscriptionNumber: 0,
415
+ address: "",
416
+ outputValue: 0,
417
+ preview: "",
418
+ content: "",
419
+ contentType: "",
420
+ contentLength: 0,
421
+ timestamp: 0,
422
+ genesisTransaction: "",
423
+ location: "",
424
+ output: "",
425
+ offset: 0,
426
+ contentBody: "",
427
+ utxoHeight: 0,
428
+ utxoConfirmation: 0
429
+ },
430
+ rawtx: "",
431
+ txid: "",
432
+ fee: 0,
433
+ estimateFee: 0,
434
+ changeSatoshis: 0,
435
+ sending: false,
436
+ psbtHex: "",
437
+ feeRate: 5,
438
+ toDomain: "",
439
+ outputValue: 1e4,
440
+ enableRBF: false
441
+ },
442
+ runesTx: {
443
+ fromAddress: "",
444
+ toAddress: "",
445
+ rawtx: "",
446
+ txid: "",
447
+ fee: 0,
448
+ estimateFee: 0,
449
+ changeSatoshis: 0,
450
+ sending: false,
451
+ psbtHex: "",
452
+ feeRate: 5,
453
+ toDomain: "",
454
+ outputValue: 1e4,
455
+ enableRBF: false
456
+ },
457
+ utxos: [],
458
+ spendUnavailableUtxos: [],
459
+ assetUtxos_inscriptions: [],
460
+ assetUtxos_runes: []
461
+ };
462
+ var slice6 = createSlice({
463
+ name: "transactions",
464
+ initialState: initialState6,
465
+ reducers: {
466
+ updateBitcoinTx(state, action) {
467
+ const { payload } = action;
468
+ state.bitcoinTx = Object.assign({}, state.bitcoinTx, payload);
469
+ },
470
+ updateOrdinalsTx(state, action) {
471
+ const { payload } = action;
472
+ state.ordinalsTx = Object.assign({}, state.ordinalsTx, payload);
473
+ },
474
+ updateRunesTx(state, action) {
475
+ const { payload } = action;
476
+ state.runesTx = Object.assign({}, state.runesTx, payload);
477
+ },
478
+ setUtxos(state, action) {
479
+ state.utxos = action.payload;
480
+ },
481
+ setSpendUnavailableUtxos(state, action) {
482
+ state.spendUnavailableUtxos = action.payload;
483
+ },
484
+ setAssetUtxosInscriptions(state, action) {
485
+ state.assetUtxos_inscriptions = action.payload;
486
+ },
487
+ setAssetUtxosRunes(state, action) {
488
+ state.assetUtxos_runes = action.payload;
489
+ },
490
+ reset(state) {
491
+ return initialState6;
492
+ }
493
+ },
494
+ extraReducers: (builder) => {
495
+ builder.addCase(updateVersion, (state) => {
496
+ if (!state.assetUtxos_inscriptions) {
497
+ state.assetUtxos_inscriptions = [];
498
+ }
499
+ if (!state.spendUnavailableUtxos) {
500
+ state.spendUnavailableUtxos = [];
501
+ }
502
+ if (!state.assetUtxos_runes) {
503
+ state.assetUtxos_runes = [];
504
+ }
505
+ });
506
+ }
507
+ });
508
+ var transactionsActions = slice6.actions;
509
+ var transactions_default = slice6.reducer;
510
+
511
+ // src/types/ui.ts
512
+ var AssetTabKey = /* @__PURE__ */ ((AssetTabKey2) => {
513
+ AssetTabKey2[AssetTabKey2["ORDINALS"] = 0] = "ORDINALS";
514
+ AssetTabKey2[AssetTabKey2["ATOMICALS"] = 1] = "ATOMICALS";
515
+ AssetTabKey2[AssetTabKey2["RUNES"] = 2] = "RUNES";
516
+ AssetTabKey2[AssetTabKey2["CAT"] = 3] = "CAT";
517
+ AssetTabKey2[AssetTabKey2["ALKANES"] = 4] = "ALKANES";
518
+ return AssetTabKey2;
519
+ })(AssetTabKey || {});
520
+ var OrdinalsAssetTabKey = /* @__PURE__ */ ((OrdinalsAssetTabKey2) => {
521
+ OrdinalsAssetTabKey2[OrdinalsAssetTabKey2["ALL"] = 0] = "ALL";
522
+ OrdinalsAssetTabKey2[OrdinalsAssetTabKey2["BRC20"] = 1] = "BRC20";
523
+ OrdinalsAssetTabKey2[OrdinalsAssetTabKey2["BRC20_6BYTE"] = 2] = "BRC20_6BYTE";
524
+ return OrdinalsAssetTabKey2;
525
+ })(OrdinalsAssetTabKey || {});
526
+ var CATAssetTabKey = /* @__PURE__ */ ((CATAssetTabKey2) => {
527
+ CATAssetTabKey2[CATAssetTabKey2["CAT20"] = 0] = "CAT20";
528
+ CATAssetTabKey2[CATAssetTabKey2["CAT721"] = 1] = "CAT721";
529
+ CATAssetTabKey2[CATAssetTabKey2["CAT20_V2"] = 2] = "CAT20_V2";
530
+ CATAssetTabKey2[CATAssetTabKey2["CAT721_V2"] = 3] = "CAT721_V2";
531
+ return CATAssetTabKey2;
532
+ })(CATAssetTabKey || {});
533
+ var AlkanesAssetTabKey = /* @__PURE__ */ ((AlkanesAssetTabKey2) => {
534
+ AlkanesAssetTabKey2[AlkanesAssetTabKey2["TOKEN"] = 0] = "TOKEN";
535
+ AlkanesAssetTabKey2[AlkanesAssetTabKey2["COLLECTION"] = 1] = "COLLECTION";
536
+ return AlkanesAssetTabKey2;
537
+ })(AlkanesAssetTabKey || {});
538
+ var NavigationSource = /* @__PURE__ */ ((NavigationSource2) => {
539
+ NavigationSource2[NavigationSource2["BACK"] = 0] = "BACK";
540
+ NavigationSource2[NavigationSource2["NORMAL"] = 1] = "NORMAL";
541
+ return NavigationSource2;
542
+ })(NavigationSource || {});
543
+
544
+ // src/reducers/ui.ts
545
+ var initialState7 = {
546
+ assetTabKey: 0 /* ORDINALS */,
547
+ ordinalsAssetTabKey: 0 /* ALL */,
548
+ catAssetTabKey: 0 /* CAT20 */,
549
+ alkanesAssetTabKey: 0 /* TOKEN */,
550
+ uiTxCreateScreen: {
551
+ toInfo: {
552
+ address: "",
553
+ domain: ""
554
+ },
555
+ inputAmount: "",
556
+ enableRBF: false,
557
+ feeRate: 1
558
+ },
559
+ babylonSendScreen: {
560
+ inputAmount: "",
561
+ memo: ""
562
+ },
563
+ navigationSource: 1 /* NORMAL */,
564
+ isBalanceHidden: false
565
+ };
566
+ var slice7 = createSlice({
567
+ name: "ui",
568
+ initialState: initialState7,
569
+ reducers: {
570
+ reset(state) {
571
+ return initialState7;
572
+ },
573
+ updateAssetTabScreen(state, action) {
574
+ const { payload } = action;
575
+ if (payload.assetTabKey !== void 0) {
576
+ state.assetTabKey = payload.assetTabKey;
577
+ }
578
+ if (payload.ordinalsAssetTabKey !== void 0) {
579
+ state.ordinalsAssetTabKey = payload.ordinalsAssetTabKey;
580
+ }
581
+ if (payload.catAssetTabKey !== void 0) {
582
+ state.catAssetTabKey = payload.catAssetTabKey;
583
+ }
584
+ if (payload.alkanesAssetTabKey !== void 0) {
585
+ state.alkanesAssetTabKey = payload.alkanesAssetTabKey;
586
+ }
587
+ return state;
588
+ },
589
+ updateTxCreateScreen(state, action) {
590
+ if (action.payload.toInfo !== void 0) {
591
+ state.uiTxCreateScreen.toInfo = action.payload.toInfo;
592
+ }
593
+ if (action.payload.inputAmount !== void 0) {
594
+ state.uiTxCreateScreen.inputAmount = action.payload.inputAmount;
595
+ }
596
+ if (action.payload.enableRBF !== void 0) {
597
+ state.uiTxCreateScreen.enableRBF = action.payload.enableRBF;
598
+ }
599
+ if (action.payload.feeRate !== void 0) {
600
+ state.uiTxCreateScreen.feeRate = action.payload.feeRate;
601
+ }
602
+ },
603
+ resetTxCreateScreen(state) {
604
+ state.uiTxCreateScreen = initialState7.uiTxCreateScreen;
605
+ },
606
+ updateBabylonSendScreen(state, action) {
607
+ if (action.payload.inputAmount !== void 0) {
608
+ state.babylonSendScreen.inputAmount = action.payload.inputAmount;
609
+ }
610
+ if (action.payload.memo !== void 0) {
611
+ state.babylonSendScreen.memo = action.payload.memo;
612
+ }
613
+ },
614
+ resetBabylonSendScreen(state) {
615
+ state.babylonSendScreen = initialState7.babylonSendScreen;
616
+ },
617
+ setNavigationSource(state, action) {
618
+ state.navigationSource = action.payload;
619
+ },
620
+ setBalanceHidden(state, action) {
621
+ state.isBalanceHidden = action.payload;
622
+ }
623
+ },
624
+ extraReducers: (builder) => {
625
+ builder.addCase(updateVersion, (state) => {
626
+ if (!state.assetTabKey) {
627
+ state.assetTabKey = 0 /* ORDINALS */;
628
+ }
629
+ if (!state.ordinalsAssetTabKey) {
630
+ state.ordinalsAssetTabKey = 0 /* ALL */;
631
+ }
632
+ if (!state.catAssetTabKey) {
633
+ state.catAssetTabKey = 0 /* CAT20 */;
634
+ }
635
+ if (!state.alkanesAssetTabKey) {
636
+ state.alkanesAssetTabKey = 0 /* TOKEN */;
637
+ }
638
+ if (!state.uiTxCreateScreen) {
639
+ state.uiTxCreateScreen = initialState7.uiTxCreateScreen;
640
+ }
641
+ if (!state.babylonSendScreen) {
642
+ state.babylonSendScreen = initialState7.babylonSendScreen;
643
+ }
644
+ if (state.isBalanceHidden === void 0) {
645
+ state.isBalanceHidden = false;
646
+ }
647
+ });
648
+ }
649
+ });
650
+ var uiActions = slice7.actions;
651
+ var ui_default = slice7.reducer;
652
+ var WalletContext = createContext(null);
653
+ var WalletProvider = ({
654
+ children,
655
+ wallet
656
+ }) => /* @__PURE__ */ jsx(WalletContext.Provider, { value: { wallet }, children });
657
+ var useWallet = () => {
658
+ const { wallet } = useContext(WalletContext);
659
+ return wallet;
660
+ };
661
+ var I18nContext = createContext({
662
+ t: (key) => key,
663
+ locale: FALLBACK_LOCALE,
664
+ supportedLocales: [],
665
+ localeNames: {},
666
+ // eslint-disable-next-line @typescript-eslint/no-empty-function
667
+ changeLocale: async () => {
668
+ }
669
+ });
670
+ var I18nProvider = ({ children }) => {
671
+ const [locale, setLocale] = useState(FALLBACK_LOCALE);
672
+ const [isInitialized, setIsInitialized] = useState(false);
673
+ const [error, setError] = useState(null);
674
+ const wallet = useWallet();
675
+ useEffect(() => {
676
+ const initialize = async () => {
677
+ try {
678
+ let localeToUse = FALLBACK_LOCALE;
679
+ const userSelectedLanguage = localStorage.getItem("userSelectedLanguage") === "true";
680
+ if (userSelectedLanguage) {
681
+ const savedLocale = localStorage.getItem("i18nextLng");
682
+ if (savedLocale && getSupportedLocales().includes(savedLocale)) {
683
+ localeToUse = savedLocale;
684
+ log.debug(`Using user selected language: ${savedLocale}`);
685
+ }
686
+ } else {
687
+ try {
688
+ const isFirstOpen = await wallet.getIsFirstOpen();
689
+ if (isFirstOpen) {
690
+ const browserLang = navigator.language;
691
+ log.debug(`New user - Browser language: ${browserLang}`);
692
+ const mappedLocale = BROWSER_TO_APP_LOCALE_MAP[browserLang];
693
+ if (mappedLocale && getSupportedLocales().includes(mappedLocale)) {
694
+ localeToUse = mappedLocale;
695
+ log.debug(`Using mapped browser language: ${mappedLocale}`);
696
+ } else if (getSupportedLocales().includes(browserLang)) {
697
+ localeToUse = browserLang;
698
+ log.debug(`Using browser language: ${browserLang}`);
699
+ } else {
700
+ const mainLang = browserLang.split("-")[0];
701
+ if (getSupportedLocales().includes(mainLang)) {
702
+ localeToUse = mainLang;
703
+ log.debug(`Using browser main language: ${mainLang}`);
704
+ } else {
705
+ log.debug(`Browser language not supported, using default: ${FALLBACK_LOCALE}`);
706
+ localeToUse = FALLBACK_LOCALE;
707
+ }
708
+ }
709
+ } else {
710
+ log.debug("Existing user - Using default English");
711
+ localeToUse = FALLBACK_LOCALE;
712
+ }
713
+ } catch (error2) {
714
+ log.error("Failed to get user status, using default language:", error2);
715
+ localeToUse = FALLBACK_LOCALE;
716
+ }
717
+ }
718
+ localStorage.setItem("i18nextLng", localeToUse);
719
+ await initI18n(localeToUse);
720
+ chrome.storage.local.set({ i18nextLng: localeToUse });
721
+ await initI18n(localeToUse);
722
+ setIsInitialized(true);
723
+ } catch (error2) {
724
+ log.error("Failed to initialize i18n:", error2);
725
+ setLocale(FALLBACK_LOCALE);
726
+ setIsInitialized(true);
727
+ setError(error2 instanceof Error ? error2 : new Error("Unknown error"));
728
+ }
729
+ };
730
+ initialize();
731
+ }, [wallet]);
732
+ const changeLocale = async (newLocale) => {
733
+ try {
734
+ await changeLanguage(newLocale);
735
+ setLocale(newLocale);
736
+ localStorage.setItem("userSelectedLanguage", "true");
737
+ localStorage.setItem("i18nextLng", newLocale);
738
+ chrome.storage.local.set({ i18nextLng: newLocale });
739
+ } catch (error2) {
740
+ setError(error2 instanceof Error ? error2 : new Error("Unknown error"));
741
+ }
742
+ };
743
+ const t2 = (key, substitutions) => {
744
+ try {
745
+ return t(key, substitutions);
746
+ } catch (error2) {
747
+ log.error(`Translation error for key "${key}":`, error2);
748
+ return key;
749
+ }
750
+ };
751
+ if (!isInitialized) {
752
+ return /* @__PURE__ */ jsx(
753
+ "div",
754
+ {
755
+ style: {
756
+ display: "flex",
757
+ flexDirection: "column",
758
+ width: "100vw",
759
+ height: "100vh",
760
+ overflowY: "auto",
761
+ overflowX: "hidden"
762
+ },
763
+ children: /* @__PURE__ */ jsx(
764
+ "div",
765
+ {
766
+ style: {
767
+ display: "flex",
768
+ flex: 1,
769
+ flexDirection: "column",
770
+ justifyItems: "center",
771
+ alignItems: "center"
772
+ },
773
+ children: /* @__PURE__ */ jsx("div", {})
774
+ }
775
+ )
776
+ }
777
+ );
778
+ }
779
+ if (error && process.env.NODE_ENV === "development") {
780
+ return /* @__PURE__ */ jsxs("div", { style: { color: "red", padding: "20px" }, children: [
781
+ /* @__PURE__ */ jsx("h2", { children: "Error initializing i18n" }),
782
+ /* @__PURE__ */ jsx("p", { children: error.message }),
783
+ /* @__PURE__ */ jsx("pre", { children: error.stack })
784
+ ] });
785
+ }
786
+ return /* @__PURE__ */ jsx(
787
+ I18nContext.Provider,
788
+ {
789
+ value: {
790
+ t: t2,
791
+ locale,
792
+ supportedLocales: getSupportedLocales(),
793
+ localeNames: LOCALE_NAMES,
794
+ changeLocale
795
+ },
796
+ children
797
+ }
798
+ );
799
+ };
800
+ function getAddressType(address, networkType) {
801
+ if (address.startsWith("bc1q") || address.startsWith("tb1q")) {
802
+ return AddressType.P2WPKH;
803
+ } else if (address.startsWith("bc1p") || address.startsWith("tb1p")) {
804
+ return AddressType.P2TR;
805
+ } else if (address.startsWith("1") || address.startsWith("m") || address.startsWith("n")) {
806
+ return AddressType.P2PKH;
807
+ } else if (address.startsWith("3") || address.startsWith("2")) {
808
+ return AddressType.P2SH_P2WPKH;
809
+ } else {
810
+ return AddressType.UNKNOWN;
811
+ }
812
+ }
813
+ var fetchLocale = async (locale) => {
814
+ const res = await fetch(`./_locales/${locale}/messages.json`);
815
+ const data = await res.json();
816
+ return Object.keys(data).reduce((res2, key) => {
817
+ return {
818
+ ...res2,
819
+ [key.replace(/__/g, " ")]: data[key].message
820
+ };
821
+ }, {});
822
+ };
823
+ i18n.use(initReactI18next).init({
824
+ fallbackLng: "en",
825
+ defaultNS: "translations",
826
+ interpolation: {
827
+ escapeValue: false
828
+ // react already safes from xss
829
+ }
830
+ });
831
+ var I18N_NS = "translations";
832
+ var addResourceBundle = async (locale) => {
833
+ if (i18n.hasResourceBundle(locale, I18N_NS))
834
+ return;
835
+ const bundle = await fetchLocale(locale);
836
+ i18n.addResourceBundle(locale, "translations", bundle);
837
+ };
838
+ addResourceBundle("en");
839
+ i18n.on("languageChanged", function(lng) {
840
+ addResourceBundle(lng);
841
+ });
842
+ var i18n_default = i18n;
843
+ var useAppDispatch = () => useDispatch();
844
+ var useAppSelector = useSelector;
845
+
846
+ // src/hooks/keyrings.ts
847
+ function useKeyringsState() {
848
+ return useAppSelector((state) => state.keyrings);
849
+ }
850
+ function useKeyrings() {
851
+ const keyringsState = useKeyringsState();
852
+ return keyringsState.keyrings;
853
+ }
854
+ function useCurrentKeyring() {
855
+ const keyringsState = useKeyringsState();
856
+ return keyringsState.current;
857
+ }
858
+
859
+ // src/hooks/accounts.ts
860
+ function useAccountsState() {
861
+ return useAppSelector((state) => state.accounts);
862
+ }
863
+ function useCurrentAccount() {
864
+ const accountsState = useAccountsState();
865
+ return accountsState.current;
866
+ }
867
+ function useCurrentAddress() {
868
+ const accountsState = useAccountsState();
869
+ return accountsState.current.address;
870
+ }
871
+ function useAccounts() {
872
+ const accountsState = useAccountsState();
873
+ return accountsState.accounts;
874
+ }
875
+ function useAccountBalance() {
876
+ const accountsState = useAccountsState();
877
+ const currentAccount = useCurrentAccount();
878
+ return accountsState.balanceV2Map[currentAccount.address] || {
879
+ availableBalance: 0,
880
+ unavailableBalance: 0,
881
+ totalBalance: 0
882
+ };
883
+ }
884
+ function useAddressSummary() {
885
+ const accountsState = useAccountsState();
886
+ return accountsState.addressSummary;
887
+ }
888
+ function useAccountInscriptions() {
889
+ const accountsState = useAccountsState();
890
+ const currentAccount = useCurrentAccount();
891
+ return accountsState.inscriptionsMap[currentAccount.address] || { list: [], expired: true };
892
+ }
893
+ function useInscriptionSummary() {
894
+ const accountsState = useAccountsState();
895
+ return accountsState.inscriptionSummary;
896
+ }
897
+ function useAppSummary() {
898
+ const accountsState = useAccountsState();
899
+ return accountsState.appSummary;
900
+ }
901
+ function useUnreadAppSummary() {
902
+ const accountsState = useAccountsState();
903
+ const summary = accountsState.appSummary;
904
+ return summary.apps.find((w) => w.time && summary.readTabTime && w.time > summary.readTabTime);
905
+ }
906
+ function useReadTab() {
907
+ const wallet = useWallet();
908
+ const dispatch = useAppDispatch();
909
+ const appSummary = useAppSummary();
910
+ return useCallback(
911
+ async (name) => {
912
+ await wallet.readTab(name);
913
+ if (name == "app") {
914
+ const appSummary2 = await wallet.getAppSummary();
915
+ dispatch(accountActions["setAppSummary"](appSummary2));
916
+ }
917
+ },
918
+ [dispatch, wallet, appSummary]
919
+ );
920
+ }
921
+ function useReadApp() {
922
+ const wallet = useWallet();
923
+ const dispatch = useAppDispatch();
924
+ const appSummary = useAppSummary();
925
+ return useCallback(
926
+ async (id) => {
927
+ await wallet.readApp(id);
928
+ const appSummary2 = await wallet.getAppSummary();
929
+ dispatch(accountActions["setAppSummary"](appSummary2));
930
+ },
931
+ [dispatch, wallet, appSummary]
932
+ );
933
+ }
934
+ function useHistory() {
935
+ const accountsState = useAccountsState();
936
+ const address = useAccountAddress();
937
+ return accountsState.historyMap[address] || { list: [], expired: true };
938
+ }
939
+ function useAccountAddress() {
940
+ const currentAccount = useCurrentAccount();
941
+ return currentAccount.address;
942
+ }
943
+ function useSetCurrentAccountCallback() {
944
+ const dispatch = useAppDispatch();
945
+ return useCallback(
946
+ (account) => {
947
+ dispatch(accountActions["setCurrent"](account));
948
+ },
949
+ [dispatch]
950
+ );
951
+ }
952
+ function useImportAccountCallback() {
953
+ const wallet = useWallet();
954
+ const dispatch = useAppDispatch();
955
+ const currentKeyring = useCurrentKeyring();
956
+ return useCallback(
957
+ async (privateKey, addressType) => {
958
+ let success = false;
959
+ let error;
960
+ try {
961
+ const alianName = await wallet.getNextAlianName(currentKeyring);
962
+ await wallet.createKeyringWithPrivateKey(privateKey, addressType, alianName);
963
+ const currentAccount = await wallet.getCurrentAccount();
964
+ dispatch(accountActions["setCurrent"](currentAccount));
965
+ success = true;
966
+ } catch (e) {
967
+ console.log(e);
968
+ error = e.message;
969
+ }
970
+ return { success, error };
971
+ },
972
+ [dispatch, wallet, currentKeyring]
973
+ );
974
+ }
975
+ function useChangeAddressFlagCallback() {
976
+ const dispatch = useAppDispatch();
977
+ const wallet = useWallet();
978
+ const currentAccount = useCurrentAccount();
979
+ return useCallback(
980
+ async (isAdd, flag) => {
981
+ const account = isAdd ? await wallet.addAddressFlag(currentAccount, flag) : await wallet.removeAddressFlag(currentAccount, flag);
982
+ dispatch(accountActions["setCurrentAddressFlag"](account.flag));
983
+ },
984
+ [dispatch, wallet, currentAccount]
985
+ );
986
+ }
987
+ function useFetchBalanceCallback() {
988
+ const dispatch = useAppDispatch();
989
+ const wallet = useWallet();
990
+ const currentAccount = useCurrentAccount();
991
+ const balance = useAccountBalance();
992
+ return useCallback(async () => {
993
+ if (!currentAccount.address)
994
+ return;
995
+ const summary = await wallet.getAddressSummary(currentAccount.address);
996
+ summary.address = currentAccount.address;
997
+ dispatch(accountActions["setAddressSummary"](summary));
998
+ const balanceV2 = await wallet.getAddressBalanceV2(currentAccount.address);
999
+ dispatch(
1000
+ accountActions["setBalanceV2"]({
1001
+ address: currentAccount.address,
1002
+ balance: balanceV2
1003
+ })
1004
+ );
1005
+ }, [dispatch, wallet, currentAccount, balance]);
1006
+ }
1007
+ function useReloadAccounts() {
1008
+ const dispatch = useAppDispatch();
1009
+ const wallet = useWallet();
1010
+ return useCallback(async () => {
1011
+ const keyrings = await wallet.getKeyrings();
1012
+ dispatch(keyringsActions["setKeyrings"](keyrings));
1013
+ const currentKeyring = await wallet.getCurrentKeyring();
1014
+ dispatch(keyringsActions["setCurrent"](currentKeyring));
1015
+ const _accounts = await wallet.getAccounts();
1016
+ dispatch(accountActions["setAccounts"](_accounts));
1017
+ const account = await wallet.getCurrentAccount();
1018
+ dispatch(accountActions["setCurrent"](account));
1019
+ dispatch(accountActions["expireBalance"](null));
1020
+ dispatch(accountActions["expireInscriptions"](null));
1021
+ wallet.getWalletConfig().then((data) => {
1022
+ dispatch(settingsActions["updateSettings"]({ walletConfig: data }));
1023
+ });
1024
+ }, [dispatch, wallet]);
1025
+ }
1026
+ function useIsKeystoneWallet() {
1027
+ const currentKeyring = useCurrentKeyring();
1028
+ return currentKeyring.type === KeyringType.KeystoneKeyring;
1029
+ }
1030
+
1031
+ // src/hooks/settings.ts
1032
+ function useSettingsState() {
1033
+ return useAppSelector((state) => state.settings);
1034
+ }
1035
+ function useLocale() {
1036
+ const settings = useSettingsState();
1037
+ return settings.locale;
1038
+ }
1039
+ function useChangeLocaleCallback() {
1040
+ const dispatch = useAppDispatch();
1041
+ const wallet = useWallet();
1042
+ return useCallback(
1043
+ async (locale) => {
1044
+ await wallet.setLocale(locale);
1045
+ await addResourceBundle(locale);
1046
+ i18n_default.changeLanguage(locale);
1047
+ dispatch(
1048
+ settingsActions.updateSettings({
1049
+ locale
1050
+ })
1051
+ );
1052
+ window.location.reload();
1053
+ },
1054
+ [dispatch, wallet]
1055
+ );
1056
+ }
1057
+ function useNetworkType() {
1058
+ const accountsState = useSettingsState();
1059
+ const chain = CHAINS_MAP[accountsState.chainType];
1060
+ if (chain) {
1061
+ return chain.networkType;
1062
+ } else {
1063
+ return NetworkType.TESTNET;
1064
+ }
1065
+ }
1066
+ function useChangeNetworkTypeCallback() {
1067
+ const dispatch = useAppDispatch();
1068
+ const wallet = useWallet();
1069
+ return useCallback(
1070
+ async (type) => {
1071
+ if (type === NetworkType.MAINNET) {
1072
+ await wallet.setChainType(ChainType.BITCOIN_MAINNET);
1073
+ dispatch(
1074
+ settingsActions.updateSettings({
1075
+ chainType: ChainType.BITCOIN_MAINNET
1076
+ })
1077
+ );
1078
+ } else if (type === NetworkType.TESTNET) {
1079
+ await wallet.setChainType(ChainType.BITCOIN_TESTNET);
1080
+ dispatch(
1081
+ settingsActions.updateSettings({
1082
+ chainType: ChainType.BITCOIN_TESTNET
1083
+ })
1084
+ );
1085
+ }
1086
+ },
1087
+ [dispatch]
1088
+ );
1089
+ }
1090
+ function useChainType() {
1091
+ const accountsState = useSettingsState();
1092
+ return accountsState.chainType;
1093
+ }
1094
+ function useChain() {
1095
+ const accountsState = useSettingsState();
1096
+ return CHAINS_MAP[accountsState.chainType];
1097
+ }
1098
+ function useChangeChainTypeCallback() {
1099
+ const dispatch = useAppDispatch();
1100
+ const wallet = useWallet();
1101
+ return useCallback(
1102
+ async (type) => {
1103
+ dispatch(
1104
+ settingsActions.updateSettings({
1105
+ chainType: type
1106
+ })
1107
+ );
1108
+ await wallet.setChainType(type);
1109
+ },
1110
+ [dispatch]
1111
+ );
1112
+ }
1113
+ function useBTCUnit() {
1114
+ const chainType = useChainType();
1115
+ return CHAINS_MAP[chainType].unit;
1116
+ }
1117
+ function useTxExplorerUrl(txid) {
1118
+ const chain = useChain();
1119
+ if (chain.enum === ChainType.BITCOIN_MAINNET) {
1120
+ return `${chain.unisatExplorerUrl}/tx/${txid}`;
1121
+ } else if (chain.defaultExplorer === "mempool-space") {
1122
+ return `${chain.mempoolSpaceUrl}/tx/${txid}`;
1123
+ } else {
1124
+ return `${chain.unisatExplorerUrl}/tx/${txid}`;
1125
+ }
1126
+ }
1127
+ function useGetTxExplorerUrlCallback() {
1128
+ const chain = useChain();
1129
+ return useCallback(
1130
+ (txid) => {
1131
+ if (chain.enum === ChainType.BITCOIN_MAINNET) {
1132
+ return `${chain.unisatExplorerUrl}/tx/${txid}`;
1133
+ } else if (chain.defaultExplorer === "mempool-space") {
1134
+ return `${chain.mempoolSpaceUrl}/tx/${txid}`;
1135
+ } else {
1136
+ return `${chain.unisatExplorerUrl}/tx/${txid}`;
1137
+ }
1138
+ },
1139
+ [chain]
1140
+ );
1141
+ }
1142
+ function useAddressExplorerUrl(address) {
1143
+ const chain = useChain();
1144
+ if (chain.enum === ChainType.BITCOIN_MAINNET) {
1145
+ return `${chain.unisatExplorerUrl}/address/${address}`;
1146
+ } else if (chain.defaultExplorer === "mempool-space") {
1147
+ return `${chain.mempoolSpaceUrl}/address/${address}`;
1148
+ } else {
1149
+ return `${chain.unisatExplorerUrl}/address/${address}`;
1150
+ }
1151
+ }
1152
+ function useCAT20TokenInfoExplorerUrl(version, tokenId) {
1153
+ const chain = useChain();
1154
+ if (version === CAT_VERSION.V1) {
1155
+ return `${chain.unisatExplorerUrl}/cat20/${tokenId}`;
1156
+ } else {
1157
+ return `${chain.unisatExplorerUrl}/cat20-v2/${tokenId}`;
1158
+ }
1159
+ }
1160
+ function useUnisatWebsite() {
1161
+ const chainType = useChainType();
1162
+ return CHAINS_MAP[chainType].unisatUrl;
1163
+ }
1164
+ function useOrdinalsWebsite() {
1165
+ const chainType = useChainType();
1166
+ return CHAINS_MAP[chainType].ordinalsUrl;
1167
+ }
1168
+ function useWalletConfig() {
1169
+ const accountsState = useSettingsState();
1170
+ return accountsState.walletConfig;
1171
+ }
1172
+ function useVersionInfo() {
1173
+ const accountsState = useSettingsState();
1174
+ const walletConfig = accountsState.walletConfig;
1175
+ const newVersion = walletConfig.version;
1176
+ const skippedVersion = accountsState.skippedVersion;
1177
+ const currentVesion = VERSION;
1178
+ let skipped = false;
1179
+ let latestVersion = "";
1180
+ if (!newVersion) {
1181
+ skipped = true;
1182
+ }
1183
+ if (newVersion == skippedVersion) {
1184
+ skipped = true;
1185
+ }
1186
+ if (newVersion) {
1187
+ if (compareVersions(currentVesion, newVersion) >= 0) {
1188
+ skipped = true;
1189
+ } else {
1190
+ latestVersion = newVersion;
1191
+ }
1192
+ }
1193
+ if (currentVesion === "0.0.0") {
1194
+ skipped = true;
1195
+ }
1196
+ return {
1197
+ currentVesion,
1198
+ newVersion,
1199
+ latestVersion,
1200
+ skipped
1201
+ };
1202
+ }
1203
+ function useSkipVersionCallback() {
1204
+ const wallet = useWallet();
1205
+ const dispatch = useAppDispatch();
1206
+ return useCallback((version) => {
1207
+ wallet.setSkippedVersion(version).then((v) => {
1208
+ dispatch(settingsActions.updateSettings({ skippedVersion: version }));
1209
+ });
1210
+ }, []);
1211
+ }
1212
+ function useAutoLockTimeId() {
1213
+ const state = useSettingsState();
1214
+ return state.autoLockTimeId;
1215
+ }
1216
+ function getAddressTips(address, chanEnum) {
1217
+ let ret = {
1218
+ homeTip: "",
1219
+ sendTip: ""
1220
+ };
1221
+ try {
1222
+ const chain = CHAINS_MAP[chanEnum];
1223
+ const addressType = getAddressType(address, chain.networkType);
1224
+ if (chain.isFractal && addressType === AddressType.P2PKH) {
1225
+ ret = {
1226
+ homeTip: t("legacy_address_warning_3"),
1227
+ sendTip: t("legacy_address_warning_4")
1228
+ };
1229
+ }
1230
+ } catch (e) {
1231
+ console.log(e);
1232
+ }
1233
+ return ret;
1234
+ }
1235
+ function useAddressTips() {
1236
+ const chain = useChain();
1237
+ const account = useCurrentAccount();
1238
+ return getAddressTips(account.address, chain.enum);
1239
+ }
1240
+ function useCAT721NFTContentBaseUrl(version) {
1241
+ const chainType = useChainType();
1242
+ if (chainType === ChainType.FRACTAL_BITCOIN_MAINNET) {
1243
+ if (version === CAT_VERSION.V1) {
1244
+ return "https://tracker-fractal-mainnet.catprotocol.org";
1245
+ } else {
1246
+ return "https://tracker2-fractal-mainnet.catprotocol.org";
1247
+ }
1248
+ } else if (chainType === ChainType.FRACTAL_BITCOIN_TESTNET) {
1249
+ return "https://tracker-fractal-testnet.catprotocol.org";
1250
+ } else {
1251
+ return "";
1252
+ }
1253
+ }
1254
+ function useBRC20MarketPlaceWebsite(ticker) {
1255
+ const chainType = useChainType();
1256
+ if (chainType === ChainType.BITCOIN_MAINNET) {
1257
+ if (ticker.length == 6) {
1258
+ return `${CHAINS_MAP[chainType].unisatUrl}/market/brc20_prog?tick=${ticker}`;
1259
+ }
1260
+ }
1261
+ return `${CHAINS_MAP[chainType].unisatUrl}/market/brc20?tick=${ticker}`;
1262
+ }
1263
+ function useRunesMarketPlaceWebsite(ticker) {
1264
+ const chainType = useChainType();
1265
+ return `${CHAINS_MAP[chainType].unisatUrl}/runes/market?tick=${ticker}`;
1266
+ }
1267
+ function useCAT20MarketPlaceWebsite(tokenId) {
1268
+ const chainType = useChainType();
1269
+ return `${CHAINS_MAP[chainType].unisatUrl}/dex/cat20/${tokenId}`;
1270
+ }
1271
+ function useBabylonConfig() {
1272
+ const chainType = useChainType();
1273
+ return BABYLON_CONFIG_MAP[chainType] || BABYLON_CONFIG_MAP[ChainType.BITCOIN_MAINNET];
1274
+ }
1275
+ function useIsMainnetChain() {
1276
+ const chainType = useChainType();
1277
+ return chainType === ChainType.BITCOIN_MAINNET || chainType === ChainType.FRACTAL_BITCOIN_MAINNET;
1278
+ }
1279
+ function useDeveloperMode() {
1280
+ const settings = useSettingsState();
1281
+ return settings.developerMode;
1282
+ }
1283
+ function useSetDeveloperModeCallback() {
1284
+ const dispatch = useAppDispatch();
1285
+ const wallet = useWallet();
1286
+ return useCallback(
1287
+ async (developerMode) => {
1288
+ await wallet.setDeveloperMode(developerMode);
1289
+ dispatch(
1290
+ settingsActions.updateSettings({
1291
+ developerMode
1292
+ })
1293
+ );
1294
+ },
1295
+ [dispatch, wallet]
1296
+ );
1297
+ }
1298
+ var PriceContext = createContext({});
1299
+ function usePrice() {
1300
+ const context = useContext(PriceContext);
1301
+ if (!context) {
1302
+ throw Error("Feature flag hooks can only be used by children of BridgeProvider.");
1303
+ } else {
1304
+ return context;
1305
+ }
1306
+ }
1307
+ var isRequestingCoinPrice = false;
1308
+ var refreshCoinPriceTime = 0;
1309
+ function PriceProvider({ children }) {
1310
+ const wallet = useWallet();
1311
+ const chainType = useChainType();
1312
+ const chain = useChain();
1313
+ const [isLoadingCoinPrice, setIsLoadingCoinPrice] = useState(false);
1314
+ const [coinPrice, setCoinPrice] = useState({
1315
+ btc: 0,
1316
+ fb: 0
1317
+ });
1318
+ const refreshCoinPrice = useCallback(() => {
1319
+ if (chain.showPrice === false) {
1320
+ return;
1321
+ }
1322
+ if (isRequestingCoinPrice) {
1323
+ return;
1324
+ }
1325
+ if (Date.now() - refreshCoinPriceTime < 30 * 1e3) {
1326
+ return;
1327
+ }
1328
+ isRequestingCoinPrice = true;
1329
+ setIsLoadingCoinPrice(true);
1330
+ wallet.getCoinPrice().then((res) => {
1331
+ refreshCoinPriceTime = Date.now();
1332
+ setCoinPrice(res);
1333
+ }).catch((e) => {
1334
+ setCoinPrice({
1335
+ btc: 0,
1336
+ fb: 0
1337
+ });
1338
+ }).finally(() => {
1339
+ setIsLoadingCoinPrice(false);
1340
+ isRequestingCoinPrice = false;
1341
+ });
1342
+ }, [chainType, chain]);
1343
+ useEffect(() => {
1344
+ refreshCoinPrice();
1345
+ }, [refreshCoinPrice]);
1346
+ const value = {
1347
+ isLoadingCoinPrice,
1348
+ coinPrice,
1349
+ refreshCoinPrice
1350
+ };
1351
+ return /* @__PURE__ */ jsx(PriceContext.Provider, { value, children });
1352
+ }
1353
+ var UI_TYPE = {
1354
+ Tab: "index",
1355
+ Pop: "popup",
1356
+ Notification: "notification",
1357
+ SidePanel: "sidepanel"
1358
+ };
1359
+ var getUiType = () => {
1360
+ const { pathname } = window.location;
1361
+ return Object.entries(UI_TYPE).reduce((m, [key, value]) => {
1362
+ m[`is${key}`] = pathname === `/${value}.html`;
1363
+ return m;
1364
+ }, {});
1365
+ };
1366
+ var useApproval = () => {
1367
+ const wallet = useWallet();
1368
+ const navigate = useNavigate();
1369
+ const getApproval = wallet.getApproval;
1370
+ const resolveApproval = async (data, stay = false, forceReject = false) => {
1371
+ const approval = await getApproval();
1372
+ if (approval) {
1373
+ wallet.resolveApproval(data, forceReject);
1374
+ }
1375
+ if (stay) {
1376
+ return;
1377
+ }
1378
+ setTimeout(() => {
1379
+ navigate("/");
1380
+ });
1381
+ };
1382
+ const rejectApproval = async (err, stay = false, isInternal = false) => {
1383
+ const approval = await getApproval();
1384
+ if (approval) {
1385
+ await wallet.rejectApproval(err, stay, isInternal);
1386
+ }
1387
+ if (!stay) {
1388
+ navigate("/");
1389
+ }
1390
+ };
1391
+ useEffect(() => {
1392
+ if (!getUiType().isNotification) {
1393
+ return () => {
1394
+ };
1395
+ }
1396
+ window.addEventListener("beforeunload", rejectApproval);
1397
+ return () => window.removeEventListener("beforeunload", rejectApproval);
1398
+ }, []);
1399
+ return [getApproval, resolveApproval, rejectApproval];
1400
+ };
1401
+
1402
+ // src/hooks/discovery.ts
1403
+ function useDiscoveryState() {
1404
+ return useAppSelector((state) => state.discovery);
1405
+ }
1406
+ function useAppList() {
1407
+ const state = useDiscoveryState();
1408
+ return state.appList;
1409
+ }
1410
+ function useBannerList() {
1411
+ const state = useDiscoveryState();
1412
+ return state.bannerList;
1413
+ }
1414
+ function useLastFetchInfo() {
1415
+ const state = useDiscoveryState();
1416
+ return {
1417
+ lastFetchTime: state.lastFetchTime,
1418
+ lasfFetchChainType: state.lastFetchChainType
1419
+ };
1420
+ }
1421
+ function useHasNewBanner() {
1422
+ const state = useDiscoveryState();
1423
+ return state.hasNewBanner;
1424
+ }
1425
+ function useGlobalState() {
1426
+ return useAppSelector((state) => state.global);
1427
+ }
1428
+ function useTab() {
1429
+ const globalState = useGlobalState();
1430
+ return globalState.tab;
1431
+ }
1432
+ function useSetTabCallback() {
1433
+ const dispatch = useAppDispatch();
1434
+ return useCallback(
1435
+ (tab) => {
1436
+ dispatch(
1437
+ globalActions["update"]({
1438
+ tab
1439
+ })
1440
+ );
1441
+ },
1442
+ [dispatch]
1443
+ );
1444
+ }
1445
+ function useBooted() {
1446
+ const globalState = useGlobalState();
1447
+ return globalState.isBooted;
1448
+ }
1449
+ function useIsUnlocked() {
1450
+ const globalState = useGlobalState();
1451
+ return globalState.isUnlocked;
1452
+ }
1453
+ function useIsReady() {
1454
+ const globalState = useGlobalState();
1455
+ return globalState.isReady;
1456
+ }
1457
+ function useUnlockCallback() {
1458
+ const dispatch = useAppDispatch();
1459
+ const wallet = useWallet();
1460
+ const [, resolveApproval] = useApproval();
1461
+ return useCallback(
1462
+ async (password) => {
1463
+ await wallet.unlock(password);
1464
+ dispatch(globalActions.update({ isUnlocked: true }));
1465
+ resolveApproval();
1466
+ },
1467
+ [dispatch, wallet]
1468
+ );
1469
+ }
1470
+ function useCreateAccountCallback() {
1471
+ const dispatch = useAppDispatch();
1472
+ const wallet = useWallet();
1473
+ return useCallback(
1474
+ async (mnemonics, hdPath, passphrase, addressType, accountCount) => {
1475
+ await wallet.createKeyringWithMnemonics(
1476
+ mnemonics,
1477
+ hdPath,
1478
+ passphrase,
1479
+ addressType,
1480
+ accountCount
1481
+ );
1482
+ dispatch(globalActions.update({ isUnlocked: true }));
1483
+ },
1484
+ [dispatch, wallet]
1485
+ );
1486
+ }
1487
+ function useImportAccountsFromKeystoneCallback() {
1488
+ const dispatch = useAppDispatch();
1489
+ const wallet = useWallet();
1490
+ return useCallback(
1491
+ async (urType, urCbor, addressType, accountCount, hdPath, filterPubkey, connectionType = "USB") => {
1492
+ await wallet.createKeyringWithKeystone(
1493
+ urType,
1494
+ urCbor,
1495
+ addressType,
1496
+ hdPath,
1497
+ accountCount,
1498
+ filterPubkey,
1499
+ connectionType
1500
+ );
1501
+ dispatch(globalActions.update({ isUnlocked: true }));
1502
+ },
1503
+ [dispatch, wallet]
1504
+ );
1505
+ }
1506
+ function useCreateColdWalletCallback() {
1507
+ const dispatch = useAppDispatch();
1508
+ const wallet = useWallet();
1509
+ return useCallback(
1510
+ async (xpub, addressType, alianName, hdPath, accountCount) => {
1511
+ await wallet.createKeyringWithColdWallet(xpub, addressType, alianName, hdPath, accountCount);
1512
+ dispatch(globalActions.update({ isUnlocked: true }));
1513
+ },
1514
+ [dispatch, wallet]
1515
+ );
1516
+ }
1517
+ var defaultI18nContext = {
1518
+ t: (key) => key,
1519
+ locale: FALLBACK_LOCALE,
1520
+ supportedLocales: [FALLBACK_LOCALE],
1521
+ localeNames: LOCALE_NAMES,
1522
+ changeLocale: async () => {
1523
+ }
1524
+ };
1525
+ var useI18n = () => {
1526
+ try {
1527
+ const context = useContext(I18nContext);
1528
+ if (!context) {
1529
+ console.warn("useI18n must be used within an I18nProvider, using default context instead");
1530
+ return defaultI18nContext;
1531
+ }
1532
+ return context;
1533
+ } catch (error) {
1534
+ console.error("Error in useI18n:", error);
1535
+ return defaultI18nContext;
1536
+ }
1537
+ };
1538
+ var getCurrentLocale = async () => {
1539
+ return await getCurrentLocaleAsync();
1540
+ };
1541
+ var getSpecialLocale = async () => {
1542
+ const currentLocale = await getCurrentLocale();
1543
+ const specialLocales = ["es", "ru", "fr", "ja"];
1544
+ const isSpecialLocale = specialLocales.includes(currentLocale);
1545
+ return { currentLocale, isSpecialLocale };
1546
+ };
1547
+ function useTools() {
1548
+ return {
1549
+ showLoading: (show) => {
1550
+ }
1551
+ };
1552
+ }
1553
+ function useTransactionsState() {
1554
+ return useAppSelector((state) => state.transactions);
1555
+ }
1556
+ function useBitcoinTx() {
1557
+ const transactionsState = useTransactionsState();
1558
+ return transactionsState.bitcoinTx;
1559
+ }
1560
+ function usePrepareSendBTCCallback() {
1561
+ const dispatch = useAppDispatch();
1562
+ const wallet = useWallet();
1563
+ const fromAddress = useAccountAddress();
1564
+ const utxos = useUtxos();
1565
+ const fetchUtxos = useFetchUtxosCallback();
1566
+ useCurrentAccount();
1567
+ useBTCUnit();
1568
+ const { t: t2 } = useI18n();
1569
+ return useCallback(
1570
+ async ({
1571
+ toAddressInfo,
1572
+ toAmount,
1573
+ feeRate,
1574
+ enableRBF,
1575
+ memo,
1576
+ memos,
1577
+ disableAutoAdjust
1578
+ }) => {
1579
+ let _utxos = utxos;
1580
+ if (_utxos.length === 0) {
1581
+ _utxos = await fetchUtxos();
1582
+ }
1583
+ const safeBalance = _utxos.filter((v) => v.inscriptions.length == 0).reduce((pre, cur) => pre + cur.satoshis, 0);
1584
+ if (safeBalance < toAmount) {
1585
+ throw new Error(t2("insufficient_balance"));
1586
+ }
1587
+ if (!feeRate) {
1588
+ const summary = await wallet.getFeeSummary();
1589
+ feeRate = summary.list[1].feeRate;
1590
+ }
1591
+ let res;
1592
+ if (safeBalance === toAmount && !disableAutoAdjust) {
1593
+ res = await wallet.sendAllBTC({
1594
+ to: toAddressInfo.address,
1595
+ btcUtxos: _utxos,
1596
+ enableRBF,
1597
+ feeRate
1598
+ });
1599
+ } else {
1600
+ res = await wallet.sendBTC({
1601
+ to: toAddressInfo.address,
1602
+ amount: toAmount,
1603
+ btcUtxos: _utxos,
1604
+ enableRBF,
1605
+ feeRate,
1606
+ memo,
1607
+ memos
1608
+ });
1609
+ }
1610
+ dispatch(
1611
+ transactionsActions.updateBitcoinTx({
1612
+ rawtx: res.rawtx,
1613
+ psbtHex: res.psbtHex,
1614
+ fromAddress,
1615
+ feeRate,
1616
+ enableRBF
1617
+ })
1618
+ );
1619
+ const rawTxInfo = {
1620
+ psbtHex: res.psbtHex,
1621
+ rawtx: res.rawtx,
1622
+ toAddressInfo,
1623
+ fee: res.fee
1624
+ };
1625
+ return rawTxInfo;
1626
+ },
1627
+ [dispatch, wallet, fromAddress, utxos, fetchUtxos]
1628
+ );
1629
+ }
1630
+ function usePrepareSendBypassHeadOffsetsCallback() {
1631
+ const dispatch = useAppDispatch();
1632
+ const wallet = useWallet();
1633
+ const fromAddress = useAccountAddress();
1634
+ useCurrentAccount();
1635
+ useBTCUnit();
1636
+ return useCallback(
1637
+ async ({
1638
+ toAddressInfo,
1639
+ toAmount,
1640
+ feeRate
1641
+ }) => {
1642
+ const res = await wallet.sendCoinBypassHeadOffsets(
1643
+ [
1644
+ {
1645
+ address: toAddressInfo.address,
1646
+ satoshis: toAmount
1647
+ }
1648
+ ],
1649
+ feeRate
1650
+ );
1651
+ dispatch(
1652
+ transactionsActions.updateBitcoinTx({
1653
+ rawtx: res.rawtx,
1654
+ psbtHex: res.psbtHex,
1655
+ fromAddress,
1656
+ feeRate
1657
+ })
1658
+ );
1659
+ const rawTxInfo = {
1660
+ psbtHex: res.psbtHex,
1661
+ rawtx: res.rawtx,
1662
+ toAddressInfo,
1663
+ fee: res.fee
1664
+ };
1665
+ return rawTxInfo;
1666
+ },
1667
+ [dispatch, wallet, fromAddress]
1668
+ );
1669
+ }
1670
+ function usePushBitcoinTxCallback() {
1671
+ const dispatch = useAppDispatch();
1672
+ const wallet = useWallet();
1673
+ const tools = useTools();
1674
+ return useCallback(
1675
+ async (rawtx) => {
1676
+ const ret = {
1677
+ success: false,
1678
+ txid: "",
1679
+ error: ""
1680
+ };
1681
+ try {
1682
+ tools.showLoading(true);
1683
+ const txid = await wallet.pushTx(rawtx);
1684
+ await timeUtils.sleep(3);
1685
+ tools.showLoading(false);
1686
+ dispatch(transactionsActions.updateBitcoinTx({ txid }));
1687
+ dispatch(accountActions.expireBalance());
1688
+ setTimeout(() => {
1689
+ dispatch(accountActions.expireBalance());
1690
+ }, 2e3);
1691
+ setTimeout(() => {
1692
+ dispatch(accountActions.expireBalance());
1693
+ }, 5e3);
1694
+ ret.success = true;
1695
+ ret.txid = txid;
1696
+ } catch (e) {
1697
+ ret.error = e.message;
1698
+ }
1699
+ return ret;
1700
+ },
1701
+ [dispatch, wallet]
1702
+ );
1703
+ }
1704
+ function useOrdinalsTx() {
1705
+ const transactionsState = useTransactionsState();
1706
+ return transactionsState.ordinalsTx;
1707
+ }
1708
+ function usePrepareSendOrdinalsInscriptionCallback() {
1709
+ const dispatch = useAppDispatch();
1710
+ const wallet = useWallet();
1711
+ const fromAddress = useAccountAddress();
1712
+ const utxos = useUtxos();
1713
+ const fetchUtxos = useFetchUtxosCallback();
1714
+ useCurrentAccount();
1715
+ return useCallback(
1716
+ async ({
1717
+ toAddressInfo,
1718
+ inscriptionId,
1719
+ feeRate,
1720
+ outputValue,
1721
+ enableRBF
1722
+ }) => {
1723
+ if (!feeRate) {
1724
+ const summary = await wallet.getFeeSummary();
1725
+ feeRate = summary.list[1].feeRate;
1726
+ }
1727
+ let btcUtxos = utxos;
1728
+ if (btcUtxos.length === 0) {
1729
+ btcUtxos = await fetchUtxos();
1730
+ }
1731
+ const res = await wallet.sendOrdinalsInscription({
1732
+ to: toAddressInfo.address,
1733
+ inscriptionId,
1734
+ feeRate,
1735
+ outputValue,
1736
+ enableRBF,
1737
+ btcUtxos
1738
+ });
1739
+ dispatch(
1740
+ transactionsActions.updateOrdinalsTx({
1741
+ rawtx: res.rawtx,
1742
+ psbtHex: res.psbtHex,
1743
+ fromAddress,
1744
+ // inscription,
1745
+ feeRate,
1746
+ outputValue,
1747
+ enableRBF
1748
+ })
1749
+ );
1750
+ const rawTxInfo = {
1751
+ psbtHex: res.psbtHex,
1752
+ rawtx: res.rawtx,
1753
+ toAddressInfo
1754
+ };
1755
+ return rawTxInfo;
1756
+ },
1757
+ [dispatch, wallet, fromAddress, utxos]
1758
+ );
1759
+ }
1760
+ function usePrepareSendOrdinalsInscriptionsCallback() {
1761
+ const dispatch = useAppDispatch();
1762
+ const wallet = useWallet();
1763
+ const fromAddress = useAccountAddress();
1764
+ const fetchUtxos = useFetchUtxosCallback();
1765
+ const utxos = useUtxos();
1766
+ useCurrentAccount();
1767
+ return useCallback(
1768
+ async ({
1769
+ toAddressInfo,
1770
+ inscriptionIds,
1771
+ feeRate,
1772
+ enableRBF
1773
+ }) => {
1774
+ if (!feeRate) {
1775
+ const summary = await wallet.getFeeSummary();
1776
+ feeRate = summary.list[1].feeRate;
1777
+ }
1778
+ let btcUtxos = utxos;
1779
+ if (btcUtxos.length === 0) {
1780
+ btcUtxos = await fetchUtxos();
1781
+ }
1782
+ const res = await wallet.sendOrdinalsInscriptions({
1783
+ to: toAddressInfo.address,
1784
+ inscriptionIds,
1785
+ feeRate,
1786
+ enableRBF,
1787
+ btcUtxos
1788
+ });
1789
+ dispatch(
1790
+ transactionsActions.updateOrdinalsTx({
1791
+ rawtx: res.rawtx,
1792
+ psbtHex: res.psbtHex,
1793
+ fromAddress,
1794
+ feeRate,
1795
+ enableRBF
1796
+ })
1797
+ );
1798
+ const rawTxInfo = {
1799
+ psbtHex: res.psbtHex,
1800
+ rawtx: res.rawtx,
1801
+ toAddressInfo
1802
+ };
1803
+ return rawTxInfo;
1804
+ },
1805
+ [dispatch, wallet, fromAddress, utxos]
1806
+ );
1807
+ }
1808
+ function useCreateSplitTxCallback() {
1809
+ const dispatch = useAppDispatch();
1810
+ const wallet = useWallet();
1811
+ const fromAddress = useAccountAddress();
1812
+ const utxos = useUtxos();
1813
+ const fetchUtxos = useFetchUtxosCallback();
1814
+ useCurrentAccount();
1815
+ return useCallback(
1816
+ async ({
1817
+ inscriptionId,
1818
+ feeRate,
1819
+ outputValue,
1820
+ enableRBF
1821
+ }) => {
1822
+ let btcUtxos = utxos;
1823
+ if (btcUtxos.length === 0) {
1824
+ btcUtxos = await fetchUtxos();
1825
+ }
1826
+ const res = await wallet.splitOrdinalsInscription({
1827
+ inscriptionId,
1828
+ feeRate,
1829
+ outputValue,
1830
+ enableRBF,
1831
+ btcUtxos
1832
+ });
1833
+ dispatch(
1834
+ transactionsActions.updateOrdinalsTx({
1835
+ rawtx: res.rawtx,
1836
+ psbtHex: res.psbtHex,
1837
+ fromAddress,
1838
+ // inscription,
1839
+ enableRBF,
1840
+ feeRate,
1841
+ outputValue
1842
+ })
1843
+ );
1844
+ const rawTxInfo = {
1845
+ psbtHex: res.psbtHex,
1846
+ rawtx: res.rawtx,
1847
+ toAddressInfo: {
1848
+ address: fromAddress
1849
+ }
1850
+ };
1851
+ return { rawTxInfo, splitedCount: res.splitedCount };
1852
+ },
1853
+ [dispatch, wallet, fromAddress, utxos]
1854
+ );
1855
+ }
1856
+ function usePushOrdinalsTxCallback() {
1857
+ const dispatch = useAppDispatch();
1858
+ const wallet = useWallet();
1859
+ const tools = useTools();
1860
+ return useCallback(
1861
+ async (rawtx) => {
1862
+ const ret = {
1863
+ success: false,
1864
+ txid: "",
1865
+ error: ""
1866
+ };
1867
+ try {
1868
+ tools.showLoading(true);
1869
+ const txid = await wallet.pushTx(rawtx);
1870
+ await timeUtils.sleep(3);
1871
+ tools.showLoading(false);
1872
+ dispatch(transactionsActions.updateOrdinalsTx({ txid }));
1873
+ dispatch(accountActions.expireBalance());
1874
+ setTimeout(() => {
1875
+ dispatch(accountActions.expireBalance());
1876
+ }, 2e3);
1877
+ setTimeout(() => {
1878
+ dispatch(accountActions.expireBalance());
1879
+ }, 5e3);
1880
+ ret.success = true;
1881
+ ret.txid = txid;
1882
+ } catch (e) {
1883
+ console.log(e);
1884
+ ret.error = e.message;
1885
+ }
1886
+ return ret;
1887
+ },
1888
+ [dispatch, wallet]
1889
+ );
1890
+ }
1891
+ function useUtxos() {
1892
+ const transactionsState = useTransactionsState();
1893
+ return transactionsState.utxos;
1894
+ }
1895
+ function useFetchUtxosCallback() {
1896
+ const dispatch = useAppDispatch();
1897
+ const wallet = useWallet();
1898
+ const account = useCurrentAccount();
1899
+ return useCallback(async () => {
1900
+ const data = await wallet.getBTCUtxos();
1901
+ dispatch(transactionsActions.setUtxos(data));
1902
+ return data;
1903
+ }, [wallet, account]);
1904
+ }
1905
+ function useSpendUnavailableUtxos() {
1906
+ const transactionsState = useTransactionsState();
1907
+ return transactionsState.spendUnavailableUtxos;
1908
+ }
1909
+ function useSetSpendUnavailableUtxosCallback() {
1910
+ const dispatch = useAppDispatch();
1911
+ return useCallback(
1912
+ (utxos) => {
1913
+ dispatch(transactionsActions.setSpendUnavailableUtxos(utxos));
1914
+ },
1915
+ [dispatch]
1916
+ );
1917
+ }
1918
+ function useSafeBalance() {
1919
+ const utxos = useUtxos();
1920
+ return useMemo(() => {
1921
+ const satoshis = utxos.filter((v) => v.inscriptions.length === 0).reduce((pre, cur) => pre + cur.satoshis, 0);
1922
+ return numUtils.satoshisToAmount(satoshis);
1923
+ }, [utxos]);
1924
+ }
1925
+ function useAssetUtxosRunes() {
1926
+ const transactionsState = useTransactionsState();
1927
+ return transactionsState.assetUtxos_runes;
1928
+ }
1929
+ function useFetchAssetUtxosRunesCallback() {
1930
+ const dispatch = useAppDispatch();
1931
+ const wallet = useWallet();
1932
+ const account = useCurrentAccount();
1933
+ return useCallback(
1934
+ async (rune) => {
1935
+ const data = await wallet.getAssetUtxosRunes(rune);
1936
+ dispatch(transactionsActions.setAssetUtxosRunes(data));
1937
+ return data;
1938
+ },
1939
+ [wallet, account]
1940
+ );
1941
+ }
1942
+ function usePrepareSendRunesCallback() {
1943
+ const dispatch = useAppDispatch();
1944
+ const wallet = useWallet();
1945
+ const fromAddress = useAccountAddress();
1946
+ const utxos = useUtxos();
1947
+ const fetchUtxos = useFetchUtxosCallback();
1948
+ const assetUtxosRunes = useAssetUtxosRunes();
1949
+ const fetchAssetUtxosRunes = useFetchAssetUtxosRunesCallback();
1950
+ const account = useCurrentAccount();
1951
+ return useCallback(
1952
+ async ({
1953
+ toAddressInfo,
1954
+ runeid,
1955
+ runeAmount,
1956
+ outputValue,
1957
+ feeRate,
1958
+ enableRBF
1959
+ }) => {
1960
+ if (!feeRate) {
1961
+ const summary = await wallet.getFeeSummary();
1962
+ feeRate = summary.list[1].feeRate;
1963
+ }
1964
+ let btcUtxos = utxos;
1965
+ if (btcUtxos.length === 0) {
1966
+ btcUtxos = await fetchUtxos();
1967
+ }
1968
+ let assetUtxos = assetUtxosRunes;
1969
+ if (assetUtxos.length == 0) {
1970
+ assetUtxos = await fetchAssetUtxosRunes(runeid);
1971
+ }
1972
+ const res = await wallet.sendRunes({
1973
+ to: toAddressInfo.address,
1974
+ runeid,
1975
+ runeAmount,
1976
+ outputValue,
1977
+ feeRate,
1978
+ enableRBF,
1979
+ btcUtxos,
1980
+ assetUtxos
1981
+ });
1982
+ dispatch(
1983
+ transactionsActions.updateRunesTx({
1984
+ rawtx: res.rawtx,
1985
+ psbtHex: res.psbtHex,
1986
+ fromAddress,
1987
+ feeRate,
1988
+ enableRBF,
1989
+ runeid,
1990
+ runeAmount,
1991
+ outputValue
1992
+ })
1993
+ );
1994
+ const rawTxInfo = {
1995
+ psbtHex: res.psbtHex,
1996
+ rawtx: res.rawtx,
1997
+ toAddressInfo
1998
+ };
1999
+ return rawTxInfo;
2000
+ },
2001
+ [dispatch, wallet, fromAddress, utxos, assetUtxosRunes, fetchAssetUtxosRunes, account]
2002
+ );
2003
+ }
2004
+ function useRunesTx() {
2005
+ const transactionsState = useTransactionsState();
2006
+ return transactionsState.runesTx;
2007
+ }
2008
+ function usePrepareSendAlkanesCallback() {
2009
+ const wallet = useWallet();
2010
+ const account = useCurrentAccount();
2011
+ const callback = useCallback(
2012
+ async (toAddressInfo, alkaneid, amount, feeRate, enableRBF = false) => {
2013
+ return await wallet.sendAlkanes({
2014
+ to: toAddressInfo.address,
2015
+ alkaneid,
2016
+ amount,
2017
+ feeRate,
2018
+ enableRBF
2019
+ });
2020
+ },
2021
+ [wallet, account]
2022
+ );
2023
+ return callback;
2024
+ }
2025
+ function useUIState() {
2026
+ return useAppSelector((state) => state.ui);
2027
+ }
2028
+ function useAssetTabKey() {
2029
+ const uiState = useUIState();
2030
+ return uiState.assetTabKey;
2031
+ }
2032
+ function useOrdinalsAssetTabKey() {
2033
+ const uiState = useUIState();
2034
+ return uiState.ordinalsAssetTabKey;
2035
+ }
2036
+ function useCATAssetTabKey() {
2037
+ const uiState = useUIState();
2038
+ return uiState.catAssetTabKey;
2039
+ }
2040
+ function useAlkanesAssetTabKey() {
2041
+ const uiState = useUIState();
2042
+ return uiState.alkanesAssetTabKey;
2043
+ }
2044
+ function useUiTxCreateScreen() {
2045
+ const uiState = useUIState();
2046
+ return uiState.uiTxCreateScreen;
2047
+ }
2048
+ function useUpdateUiTxCreateScreen() {
2049
+ const dispatch = useAppDispatch();
2050
+ return ({
2051
+ toInfo,
2052
+ inputAmount,
2053
+ enableRBF,
2054
+ feeRate
2055
+ }) => {
2056
+ dispatch(uiActions.updateTxCreateScreen({ toInfo, inputAmount, enableRBF, feeRate }));
2057
+ };
2058
+ }
2059
+ function useResetUiTxCreateScreen() {
2060
+ const dispatch = useAppDispatch();
2061
+ return () => {
2062
+ dispatch(uiActions.resetTxCreateScreen());
2063
+ };
2064
+ }
2065
+ function useSupportedAssets() {
2066
+ const chainType = useChainType();
2067
+ const currentAddress = useCurrentAddress();
2068
+ useNetworkType();
2069
+ useCurrentAccount();
2070
+ const assetTabKeys = [];
2071
+ const assets = {
2072
+ ordinals: false,
2073
+ runes: false,
2074
+ CAT20: false,
2075
+ alkanes: false
2076
+ };
2077
+ assets.ordinals = true;
2078
+ assetTabKeys.push(0 /* ORDINALS */);
2079
+ assets.runes = true;
2080
+ assetTabKeys.push(2 /* RUNES */);
2081
+ if (chainType === ChainType.FRACTAL_BITCOIN_MAINNET || chainType === ChainType.FRACTAL_BITCOIN_TESTNET) {
2082
+ const addressType = getAddressType(currentAddress);
2083
+ if (addressType == AddressType.P2TR || addressType == AddressType.P2WPKH) {
2084
+ assets.CAT20 = true;
2085
+ assetTabKeys.push(3 /* CAT */);
2086
+ }
2087
+ }
2088
+ if (chainType === ChainType.BITCOIN_SIGNET || chainType === ChainType.BITCOIN_MAINNET) {
2089
+ assets.alkanes = true;
2090
+ assetTabKeys.push(4 /* ALKANES */);
2091
+ }
2092
+ return {
2093
+ tabKeys: assetTabKeys,
2094
+ assets,
2095
+ key: assetTabKeys.join(",")
2096
+ };
2097
+ }
2098
+ var useIsInExpandView = () => {
2099
+ if (typeof window === "undefined") {
2100
+ return false;
2101
+ }
2102
+ return useMemo(() => {
2103
+ if (window.innerWidth > 156 * 3) {
2104
+ return true;
2105
+ } else {
2106
+ return false;
2107
+ }
2108
+ }, [window.innerWidth]);
2109
+ };
2110
+ var useUtxoTools = (chain) => {
2111
+ const openUtxoTools = () => {
2112
+ window.open(`${chain.unisatUrl}/utxo?tab=all`);
2113
+ };
2114
+ return {
2115
+ openUtxoTools
2116
+ };
2117
+ };
2118
+ function useLocationState() {
2119
+ const { state } = useLocation();
2120
+ return state;
2121
+ }
2122
+
2123
+ // src/utils/eventBus.ts
2124
+ var EventBus = class {
2125
+ constructor() {
2126
+ this.events = {};
2127
+ this.emit = (type, params) => {
2128
+ const listeners = this.events[type];
2129
+ if (listeners) {
2130
+ listeners.forEach((fn) => {
2131
+ fn(params);
2132
+ });
2133
+ }
2134
+ };
2135
+ this.once = (type, fn) => {
2136
+ const listeners = this.events[type];
2137
+ const func = (...params) => {
2138
+ fn(...params);
2139
+ this.events[type] = this.events[type].filter((item) => item !== func);
2140
+ };
2141
+ if (listeners) {
2142
+ this.events[type].push(func);
2143
+ } else {
2144
+ this.events[type] = [func];
2145
+ }
2146
+ };
2147
+ this.addEventListener = (type, fn) => {
2148
+ const listeners = this.events[type];
2149
+ if (listeners) {
2150
+ this.events[type].push(fn);
2151
+ } else {
2152
+ this.events[type] = [fn];
2153
+ }
2154
+ };
2155
+ this.removeEventListener = (type, fn) => {
2156
+ const listeners = this.events[type];
2157
+ if (listeners) {
2158
+ this.events[type] = this.events[type].filter((item) => item !== fn);
2159
+ }
2160
+ };
2161
+ this.removeAllEventListeners = (type) => {
2162
+ this.events[type] = [];
2163
+ };
2164
+ }
2165
+ };
2166
+ var eventBus_default = new EventBus();
2167
+
2168
+ // src/updater/accounts.ts
2169
+ function AccountUpdater() {
2170
+ const dispatch = useAppDispatch();
2171
+ const wallet = useWallet();
2172
+ const currentAccount = useCurrentAccount();
2173
+ const isUnlocked = useIsUnlocked();
2174
+ const selfRef = useRef({
2175
+ preAccountKey: "",
2176
+ loadingBalance: false,
2177
+ loadingHistory: false
2178
+ });
2179
+ const self = selfRef.current;
2180
+ const reloadAccounts = useReloadAccounts();
2181
+ const onCurrentChange = useCallback(async () => {
2182
+ if (isUnlocked && currentAccount && currentAccount.key != self.preAccountKey) {
2183
+ self.preAccountKey = currentAccount.key;
2184
+ reloadAccounts();
2185
+ }
2186
+ }, [dispatch, currentAccount, wallet, isUnlocked]);
2187
+ useEffect(() => {
2188
+ onCurrentChange();
2189
+ }, [currentAccount && currentAccount.key, isUnlocked]);
2190
+ const fetchBalance = useFetchBalanceCallback();
2191
+ useEffect(() => {
2192
+ if (self.loadingBalance) {
2193
+ return;
2194
+ }
2195
+ if (!isUnlocked) {
2196
+ return;
2197
+ }
2198
+ self.loadingBalance = true;
2199
+ fetchBalance().finally(() => {
2200
+ self.loadingBalance = false;
2201
+ });
2202
+ }, [fetchBalance, wallet, isUnlocked, self]);
2203
+ useEffect(() => {
2204
+ const accountChangeHandler = (account) => {
2205
+ if (account && account.address) {
2206
+ dispatch(accountActions.setCurrent(account));
2207
+ }
2208
+ };
2209
+ eventBus_default.addEventListener("accountsChanged", accountChangeHandler);
2210
+ return () => {
2211
+ eventBus_default.removeEventListener("accountsChanged", accountChangeHandler);
2212
+ };
2213
+ }, [dispatch]);
2214
+ useEffect(() => {
2215
+ const chaintChangeHandler = (params) => {
2216
+ dispatch(
2217
+ settingsActions.updateSettings({
2218
+ chainType: params.type
2219
+ })
2220
+ );
2221
+ reloadAccounts();
2222
+ };
2223
+ eventBus_default.addEventListener("chainChanged", chaintChangeHandler);
2224
+ return () => {
2225
+ eventBus_default.removeEventListener("chainChanged", chaintChangeHandler);
2226
+ };
2227
+ }, [dispatch]);
2228
+ useEffect(() => {
2229
+ const lockHandler = () => {
2230
+ dispatch(globalActions.update({ isUnlocked: false }));
2231
+ };
2232
+ eventBus_default.addEventListener("lock", lockHandler);
2233
+ return () => {
2234
+ eventBus_default.removeEventListener("lock", lockHandler);
2235
+ };
2236
+ }, [dispatch]);
2237
+ useEffect(() => {
2238
+ const unlockHandler = () => {
2239
+ dispatch(globalActions.update({ isUnlocked: true }));
2240
+ };
2241
+ eventBus_default.addEventListener("unlock", unlockHandler);
2242
+ return () => {
2243
+ eventBus_default.removeEventListener("unlock", unlockHandler);
2244
+ };
2245
+ }, [dispatch]);
2246
+ return null;
2247
+ }
2248
+
2249
+ // src/index.ts
2250
+ var PERSISTED_KEYS = ["ui", "discovery"];
2251
+ var store = configureStore({
2252
+ reducer: {
2253
+ accounts: accounts_default,
2254
+ transactions: transactions_default,
2255
+ settings: settings_default,
2256
+ global: global_default,
2257
+ keyrings: keyrings_default,
2258
+ ui: ui_default,
2259
+ discovery: discovery_default
2260
+ },
2261
+ middleware: (getDefaultMiddleware) => (
2262
+ // @ts-ignore
2263
+ getDefaultMiddleware({ thunk: true }).concat(save({ states: PERSISTED_KEYS, debounce: 1e3 }))
2264
+ ),
2265
+ preloadedState: load({ states: PERSISTED_KEYS, disableWarnings: true })
2266
+ });
2267
+ store.dispatch(updateVersion());
2268
+ setupListeners(store.dispatch);
2269
+ var src_default = store;
2270
+
2271
+ export { AccountUpdater, AlkanesAssetTabKey, AssetTabKey, CATAssetTabKey, I18nProvider, NavigationSource, OrdinalsAssetTabKey, PriceProvider, WalletProvider, accountActions, src_default as default, discoveryActions, getAddressTips, getCurrentLocale, getSpecialLocale, getUiType, globalActions, keyringsActions, settingsActions, transactionsActions, uiActions, useAccountAddress, useAccountBalance, useAccountInscriptions, useAccounts, useAccountsState, useAddressExplorerUrl, useAddressSummary, useAddressTips, useAlkanesAssetTabKey, useAppDispatch, useAppList, useAppSelector, useAppSummary, useApproval, useAssetTabKey, useAssetUtxosRunes, useAutoLockTimeId, useBRC20MarketPlaceWebsite, useBTCUnit, useBabylonConfig, useBannerList, useBitcoinTx, useBooted, useCAT20MarketPlaceWebsite, useCAT20TokenInfoExplorerUrl, useCAT721NFTContentBaseUrl, useCATAssetTabKey, useChain, useChainType, useChangeAddressFlagCallback, useChangeChainTypeCallback, useChangeLocaleCallback, useChangeNetworkTypeCallback, useCreateAccountCallback, useCreateColdWalletCallback, useCreateSplitTxCallback, useCurrentAccount, useCurrentAddress, useCurrentKeyring, useDeveloperMode, useDiscoveryState, useFetchAssetUtxosRunesCallback, useFetchBalanceCallback, useFetchUtxosCallback, useGetTxExplorerUrlCallback, useGlobalState, useHasNewBanner, useHistory, useI18n, useImportAccountCallback, useImportAccountsFromKeystoneCallback, useInscriptionSummary, useIsInExpandView, useIsKeystoneWallet, useIsMainnetChain, useIsReady, useIsUnlocked, useKeyrings, useKeyringsState, useLastFetchInfo, useLocale, useLocationState, useNetworkType, useOrdinalsAssetTabKey, useOrdinalsTx, useOrdinalsWebsite, usePrepareSendAlkanesCallback, usePrepareSendBTCCallback, usePrepareSendBypassHeadOffsetsCallback, usePrepareSendOrdinalsInscriptionCallback, usePrepareSendOrdinalsInscriptionsCallback, usePrepareSendRunesCallback, usePrice, usePushBitcoinTxCallback, usePushOrdinalsTxCallback, useReadApp, useReadTab, useReloadAccounts, useResetUiTxCreateScreen, useRunesMarketPlaceWebsite, useRunesTx, useSafeBalance, useSetCurrentAccountCallback, useSetDeveloperModeCallback, useSetSpendUnavailableUtxosCallback, useSetTabCallback, useSettingsState, useSkipVersionCallback, useSpendUnavailableUtxos, useSupportedAssets, useTab, useTransactionsState, useTxExplorerUrl, useUIState, useUiTxCreateScreen, useUnisatWebsite, useUnlockCallback, useUnreadAppSummary, useUpdateUiTxCreateScreen, useUtxoTools, useUtxos, useVersionInfo, useWallet, useWalletConfig };
2272
+ //# sourceMappingURL=out.js.map
2273
+ //# sourceMappingURL=index.mjs.map