@unisat/wallet-state 1.0.0 → 1.0.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.
Files changed (40) hide show
  1. package/lib/index.d.mts +934 -0
  2. package/lib/index.d.ts +934 -0
  3. package/lib/index.js +2225 -0
  4. package/lib/index.js.map +1 -0
  5. package/lib/index.mjs +2124 -0
  6. package/lib/index.mjs.map +1 -0
  7. package/package.json +19 -5
  8. package/src/actions/global.ts +5 -0
  9. package/src/context/I18nContext.tsx +191 -0
  10. package/src/context/PriceContext.tsx +81 -0
  11. package/src/context/WalletContext.tsx +703 -0
  12. package/src/context/index.ts +3 -0
  13. package/src/hooks/accounts.ts +23 -21
  14. package/src/hooks/approval.ts +72 -0
  15. package/src/hooks/base.ts +6 -0
  16. package/src/hooks/discovery.ts +29 -0
  17. package/src/hooks/global.ts +129 -5
  18. package/src/hooks/i18n.ts +53 -0
  19. package/src/hooks/index.ts +9 -15
  20. package/src/hooks/keyrings.ts +14 -5
  21. package/src/hooks/settings.ts +318 -5
  22. package/src/hooks/transactions.ts +44 -38
  23. package/src/hooks/ui.ts +133 -5
  24. package/src/index.ts +42 -5
  25. package/src/{slices → reducers}/accounts.ts +12 -12
  26. package/src/reducers/discovery.ts +73 -0
  27. package/src/reducers/global.ts +51 -0
  28. package/src/{slices → reducers}/keyrings.ts +7 -6
  29. package/src/{slices → reducers}/settings.ts +5 -5
  30. package/src/{slices → reducers}/transactions.ts +4 -5
  31. package/src/{slices → reducers}/ui.ts +4 -5
  32. package/src/updater/accounts.ts +107 -0
  33. package/src/updater/index.ts +1 -0
  34. package/src/utils/bitcoin-utils.ts +81 -0
  35. package/src/utils/eventBus.ts +49 -0
  36. package/src/utils/i18n.ts +41 -0
  37. package/src/slices/global.ts +0 -52
  38. package/src/slices/index.ts +0 -10
  39. package/src/store/index.ts +0 -43
  40. package/src/types/index.ts +0 -37
package/lib/index.mjs ADDED
@@ -0,0 +1,2124 @@
1
+ import { save, load } from 'redux-localstorage-simple';
2
+ import { createAction, createSlice, configureStore } from '@reduxjs/toolkit';
3
+ import { setupListeners } from '@reduxjs/toolkit/query/react';
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 '@unisat/keyring-service/types';
15
+ import { useDispatch, useSelector } from 'react-redux';
16
+ import { useNavigate } 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
+ 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
+ var initialState7 = {
511
+ assetTabKey: 0 /* ORDINALS */,
512
+ ordinalsAssetTabKey: 0 /* ALL */,
513
+ catAssetTabKey: 0 /* CAT20 */,
514
+ alkanesAssetTabKey: 0 /* TOKEN */,
515
+ uiTxCreateScreen: {
516
+ toInfo: {
517
+ address: "",
518
+ domain: ""
519
+ },
520
+ inputAmount: "",
521
+ enableRBF: false,
522
+ feeRate: 1
523
+ },
524
+ babylonSendScreen: {
525
+ inputAmount: "",
526
+ memo: ""
527
+ },
528
+ navigationSource: 1 /* NORMAL */,
529
+ isBalanceHidden: false
530
+ };
531
+ var slice7 = createSlice({
532
+ name: "ui",
533
+ initialState: initialState7,
534
+ reducers: {
535
+ reset(state) {
536
+ return initialState7;
537
+ },
538
+ updateAssetTabScreen(state, action) {
539
+ const { payload } = action;
540
+ if (payload.assetTabKey !== void 0) {
541
+ state.assetTabKey = payload.assetTabKey;
542
+ }
543
+ if (payload.ordinalsAssetTabKey !== void 0) {
544
+ state.ordinalsAssetTabKey = payload.ordinalsAssetTabKey;
545
+ }
546
+ if (payload.catAssetTabKey !== void 0) {
547
+ state.catAssetTabKey = payload.catAssetTabKey;
548
+ }
549
+ if (payload.alkanesAssetTabKey !== void 0) {
550
+ state.alkanesAssetTabKey = payload.alkanesAssetTabKey;
551
+ }
552
+ return state;
553
+ },
554
+ updateTxCreateScreen(state, action) {
555
+ if (action.payload.toInfo !== void 0) {
556
+ state.uiTxCreateScreen.toInfo = action.payload.toInfo;
557
+ }
558
+ if (action.payload.inputAmount !== void 0) {
559
+ state.uiTxCreateScreen.inputAmount = action.payload.inputAmount;
560
+ }
561
+ if (action.payload.enableRBF !== void 0) {
562
+ state.uiTxCreateScreen.enableRBF = action.payload.enableRBF;
563
+ }
564
+ if (action.payload.feeRate !== void 0) {
565
+ state.uiTxCreateScreen.feeRate = action.payload.feeRate;
566
+ }
567
+ },
568
+ resetTxCreateScreen(state) {
569
+ state.uiTxCreateScreen = initialState7.uiTxCreateScreen;
570
+ },
571
+ updateBabylonSendScreen(state, action) {
572
+ if (action.payload.inputAmount !== void 0) {
573
+ state.babylonSendScreen.inputAmount = action.payload.inputAmount;
574
+ }
575
+ if (action.payload.memo !== void 0) {
576
+ state.babylonSendScreen.memo = action.payload.memo;
577
+ }
578
+ },
579
+ resetBabylonSendScreen(state) {
580
+ state.babylonSendScreen = initialState7.babylonSendScreen;
581
+ },
582
+ setNavigationSource(state, action) {
583
+ state.navigationSource = action.payload;
584
+ },
585
+ setBalanceHidden(state, action) {
586
+ state.isBalanceHidden = action.payload;
587
+ }
588
+ },
589
+ extraReducers: (builder) => {
590
+ builder.addCase(updateVersion, (state) => {
591
+ if (!state.assetTabKey) {
592
+ state.assetTabKey = 0 /* ORDINALS */;
593
+ }
594
+ if (!state.ordinalsAssetTabKey) {
595
+ state.ordinalsAssetTabKey = 0 /* ALL */;
596
+ }
597
+ if (!state.catAssetTabKey) {
598
+ state.catAssetTabKey = 0 /* CAT20 */;
599
+ }
600
+ if (!state.alkanesAssetTabKey) {
601
+ state.alkanesAssetTabKey = 0 /* TOKEN */;
602
+ }
603
+ if (!state.uiTxCreateScreen) {
604
+ state.uiTxCreateScreen = initialState7.uiTxCreateScreen;
605
+ }
606
+ if (!state.babylonSendScreen) {
607
+ state.babylonSendScreen = initialState7.babylonSendScreen;
608
+ }
609
+ if (state.isBalanceHidden === void 0) {
610
+ state.isBalanceHidden = false;
611
+ }
612
+ });
613
+ }
614
+ });
615
+ var uiActions = slice7.actions;
616
+ var ui_default = slice7.reducer;
617
+ var WalletContext = createContext(null);
618
+ var WalletProvider = ({
619
+ children,
620
+ wallet
621
+ }) => /* @__PURE__ */ jsx(WalletContext.Provider, { value: { wallet }, children });
622
+ var useWallet = () => {
623
+ const { wallet } = useContext(WalletContext);
624
+ return wallet;
625
+ };
626
+ var I18nContext = createContext({
627
+ t: (key) => key,
628
+ locale: FALLBACK_LOCALE,
629
+ supportedLocales: [],
630
+ localeNames: {},
631
+ // eslint-disable-next-line @typescript-eslint/no-empty-function
632
+ changeLocale: async () => {
633
+ }
634
+ });
635
+ var I18nProvider = ({ children }) => {
636
+ const [locale, setLocale] = useState(FALLBACK_LOCALE);
637
+ const [isInitialized, setIsInitialized] = useState(false);
638
+ const [error, setError] = useState(null);
639
+ const wallet = useWallet();
640
+ useEffect(() => {
641
+ const initialize = async () => {
642
+ try {
643
+ let localeToUse = FALLBACK_LOCALE;
644
+ const userSelectedLanguage = localStorage.getItem("userSelectedLanguage") === "true";
645
+ if (userSelectedLanguage) {
646
+ const savedLocale = localStorage.getItem("i18nextLng");
647
+ if (savedLocale && getSupportedLocales().includes(savedLocale)) {
648
+ localeToUse = savedLocale;
649
+ log.debug(`Using user selected language: ${savedLocale}`);
650
+ }
651
+ } else {
652
+ try {
653
+ const isFirstOpen = await wallet.getIsFirstOpen();
654
+ if (isFirstOpen) {
655
+ const browserLang = navigator.language;
656
+ log.debug(`New user - Browser language: ${browserLang}`);
657
+ const mappedLocale = BROWSER_TO_APP_LOCALE_MAP[browserLang];
658
+ if (mappedLocale && getSupportedLocales().includes(mappedLocale)) {
659
+ localeToUse = mappedLocale;
660
+ log.debug(`Using mapped browser language: ${mappedLocale}`);
661
+ } else if (getSupportedLocales().includes(browserLang)) {
662
+ localeToUse = browserLang;
663
+ log.debug(`Using browser language: ${browserLang}`);
664
+ } else {
665
+ const mainLang = browserLang.split("-")[0];
666
+ if (getSupportedLocales().includes(mainLang)) {
667
+ localeToUse = mainLang;
668
+ log.debug(`Using browser main language: ${mainLang}`);
669
+ } else {
670
+ log.debug(`Browser language not supported, using default: ${FALLBACK_LOCALE}`);
671
+ localeToUse = FALLBACK_LOCALE;
672
+ }
673
+ }
674
+ } else {
675
+ log.debug("Existing user - Using default English");
676
+ localeToUse = FALLBACK_LOCALE;
677
+ }
678
+ } catch (error2) {
679
+ log.error("Failed to get user status, using default language:", error2);
680
+ localeToUse = FALLBACK_LOCALE;
681
+ }
682
+ }
683
+ localStorage.setItem("i18nextLng", localeToUse);
684
+ await initI18n(localeToUse);
685
+ chrome.storage.local.set({ i18nextLng: localeToUse });
686
+ await initI18n(localeToUse);
687
+ setIsInitialized(true);
688
+ } catch (error2) {
689
+ log.error("Failed to initialize i18n:", error2);
690
+ setLocale(FALLBACK_LOCALE);
691
+ setIsInitialized(true);
692
+ setError(error2 instanceof Error ? error2 : new Error("Unknown error"));
693
+ }
694
+ };
695
+ initialize();
696
+ }, [wallet]);
697
+ const changeLocale = async (newLocale) => {
698
+ try {
699
+ await changeLanguage(newLocale);
700
+ setLocale(newLocale);
701
+ localStorage.setItem("userSelectedLanguage", "true");
702
+ localStorage.setItem("i18nextLng", newLocale);
703
+ chrome.storage.local.set({ i18nextLng: newLocale });
704
+ } catch (error2) {
705
+ setError(error2 instanceof Error ? error2 : new Error("Unknown error"));
706
+ }
707
+ };
708
+ const t2 = (key, substitutions) => {
709
+ try {
710
+ return t(key, substitutions);
711
+ } catch (error2) {
712
+ log.error(`Translation error for key "${key}":`, error2);
713
+ return key;
714
+ }
715
+ };
716
+ if (!isInitialized) {
717
+ return /* @__PURE__ */ jsx(
718
+ "div",
719
+ {
720
+ style: {
721
+ display: "flex",
722
+ flexDirection: "column",
723
+ width: "100vw",
724
+ height: "100vh",
725
+ overflowY: "auto",
726
+ overflowX: "hidden"
727
+ },
728
+ children: /* @__PURE__ */ jsx(
729
+ "div",
730
+ {
731
+ style: {
732
+ display: "flex",
733
+ flex: 1,
734
+ flexDirection: "column",
735
+ justifyItems: "center",
736
+ alignItems: "center"
737
+ },
738
+ children: /* @__PURE__ */ jsx("div", {})
739
+ }
740
+ )
741
+ }
742
+ );
743
+ }
744
+ if (error && process.env.NODE_ENV === "development") {
745
+ return /* @__PURE__ */ jsxs("div", { style: { color: "red", padding: "20px" }, children: [
746
+ /* @__PURE__ */ jsx("h2", { children: "Error initializing i18n" }),
747
+ /* @__PURE__ */ jsx("p", { children: error.message }),
748
+ /* @__PURE__ */ jsx("pre", { children: error.stack })
749
+ ] });
750
+ }
751
+ return /* @__PURE__ */ jsx(
752
+ I18nContext.Provider,
753
+ {
754
+ value: {
755
+ t: t2,
756
+ locale,
757
+ supportedLocales: getSupportedLocales(),
758
+ localeNames: LOCALE_NAMES,
759
+ changeLocale
760
+ },
761
+ children
762
+ }
763
+ );
764
+ };
765
+ function getAddressType(address, networkType) {
766
+ if (address.startsWith("bc1q") || address.startsWith("tb1q")) {
767
+ return AddressType.P2WPKH;
768
+ } else if (address.startsWith("bc1p") || address.startsWith("tb1p")) {
769
+ return AddressType.P2TR;
770
+ } else if (address.startsWith("1") || address.startsWith("m") || address.startsWith("n")) {
771
+ return AddressType.P2PKH;
772
+ } else if (address.startsWith("3") || address.startsWith("2")) {
773
+ return AddressType.P2SH_P2WPKH;
774
+ } else {
775
+ return AddressType.UNKNOWN;
776
+ }
777
+ }
778
+ var fetchLocale = async (locale) => {
779
+ const res = await fetch(`./_locales/${locale}/messages.json`);
780
+ const data = await res.json();
781
+ return Object.keys(data).reduce((res2, key) => {
782
+ return {
783
+ ...res2,
784
+ [key.replace(/__/g, " ")]: data[key].message
785
+ };
786
+ }, {});
787
+ };
788
+ i18n.use(initReactI18next).init({
789
+ fallbackLng: "en",
790
+ defaultNS: "translations",
791
+ interpolation: {
792
+ escapeValue: false
793
+ // react already safes from xss
794
+ }
795
+ });
796
+ var I18N_NS = "translations";
797
+ var addResourceBundle = async (locale) => {
798
+ if (i18n.hasResourceBundle(locale, I18N_NS))
799
+ return;
800
+ const bundle = await fetchLocale(locale);
801
+ i18n.addResourceBundle(locale, "translations", bundle);
802
+ };
803
+ addResourceBundle("en");
804
+ i18n.on("languageChanged", function(lng) {
805
+ addResourceBundle(lng);
806
+ });
807
+ var i18n_default = i18n;
808
+ var useAppDispatch = () => useDispatch();
809
+ var useAppSelector = useSelector;
810
+
811
+ // src/hooks/keyrings.ts
812
+ function useKeyringsState() {
813
+ return useAppSelector((state) => state.keyrings);
814
+ }
815
+ function useKeyrings() {
816
+ const keyringsState = useKeyringsState();
817
+ return keyringsState.keyrings;
818
+ }
819
+ function useCurrentKeyring() {
820
+ const keyringsState = useKeyringsState();
821
+ return keyringsState.current;
822
+ }
823
+
824
+ // src/hooks/accounts.ts
825
+ function useAccountsState() {
826
+ return useAppSelector((state) => state.accounts);
827
+ }
828
+ function useCurrentAccount() {
829
+ const accountsState = useAccountsState();
830
+ return accountsState.current;
831
+ }
832
+ function useCurrentAddress() {
833
+ const accountsState = useAccountsState();
834
+ return accountsState.current.address;
835
+ }
836
+ function useAccountBalance() {
837
+ const accountsState = useAccountsState();
838
+ const currentAccount = useCurrentAccount();
839
+ return accountsState.balanceV2Map[currentAccount.address] || {
840
+ availableBalance: 0,
841
+ unavailableBalance: 0,
842
+ totalBalance: 0
843
+ };
844
+ }
845
+ function useAccountAddress() {
846
+ const currentAccount = useCurrentAccount();
847
+ return currentAccount.address;
848
+ }
849
+ function useFetchBalanceCallback() {
850
+ const dispatch = useAppDispatch();
851
+ const wallet = useWallet();
852
+ const currentAccount = useCurrentAccount();
853
+ const balance = useAccountBalance();
854
+ return useCallback(async () => {
855
+ if (!currentAccount.address)
856
+ return;
857
+ const summary = await wallet.getAddressSummary(currentAccount.address);
858
+ summary.address = currentAccount.address;
859
+ dispatch(accountActions["setAddressSummary"](summary));
860
+ const balanceV2 = await wallet.getAddressBalanceV2(currentAccount.address);
861
+ dispatch(
862
+ accountActions["setBalanceV2"]({
863
+ address: currentAccount.address,
864
+ balance: balanceV2
865
+ })
866
+ );
867
+ }, [dispatch, wallet, currentAccount, balance]);
868
+ }
869
+ function useReloadAccounts() {
870
+ const dispatch = useAppDispatch();
871
+ const wallet = useWallet();
872
+ return useCallback(async () => {
873
+ const keyrings = await wallet.getKeyrings();
874
+ dispatch(keyringsActions["setKeyrings"](keyrings));
875
+ const currentKeyring = await wallet.getCurrentKeyring();
876
+ dispatch(keyringsActions["setCurrent"](currentKeyring));
877
+ const _accounts = await wallet.getAccounts();
878
+ dispatch(accountActions["setAccounts"](_accounts));
879
+ const account = await wallet.getCurrentAccount();
880
+ dispatch(accountActions["setCurrent"](account));
881
+ dispatch(accountActions["expireBalance"](null));
882
+ dispatch(accountActions["expireInscriptions"](null));
883
+ wallet.getWalletConfig().then((data) => {
884
+ dispatch(settingsActions["updateSettings"]({ walletConfig: data }));
885
+ });
886
+ }, [dispatch, wallet]);
887
+ }
888
+
889
+ // src/hooks/settings.ts
890
+ function useSettingsState() {
891
+ return useAppSelector((state) => state.settings);
892
+ }
893
+ function useLocale() {
894
+ const settings = useSettingsState();
895
+ return settings.locale;
896
+ }
897
+ function useChangeLocaleCallback() {
898
+ const dispatch = useAppDispatch();
899
+ const wallet = useWallet();
900
+ return useCallback(
901
+ async (locale) => {
902
+ await wallet.setLocale(locale);
903
+ await addResourceBundle(locale);
904
+ i18n_default.changeLanguage(locale);
905
+ dispatch(
906
+ settingsActions.updateSettings({
907
+ locale
908
+ })
909
+ );
910
+ window.location.reload();
911
+ },
912
+ [dispatch, wallet]
913
+ );
914
+ }
915
+ function useNetworkType() {
916
+ const accountsState = useSettingsState();
917
+ const chain = CHAINS_MAP[accountsState.chainType];
918
+ if (chain) {
919
+ return chain.networkType;
920
+ } else {
921
+ return NetworkType.TESTNET;
922
+ }
923
+ }
924
+ function useChangeNetworkTypeCallback() {
925
+ const dispatch = useAppDispatch();
926
+ const wallet = useWallet();
927
+ return useCallback(
928
+ async (type) => {
929
+ if (type === NetworkType.MAINNET) {
930
+ await wallet.setChainType(ChainType.BITCOIN_MAINNET);
931
+ dispatch(
932
+ settingsActions.updateSettings({
933
+ chainType: ChainType.BITCOIN_MAINNET
934
+ })
935
+ );
936
+ } else if (type === NetworkType.TESTNET) {
937
+ await wallet.setChainType(ChainType.BITCOIN_TESTNET);
938
+ dispatch(
939
+ settingsActions.updateSettings({
940
+ chainType: ChainType.BITCOIN_TESTNET
941
+ })
942
+ );
943
+ }
944
+ },
945
+ [dispatch]
946
+ );
947
+ }
948
+ function useChainType() {
949
+ const accountsState = useSettingsState();
950
+ return accountsState.chainType;
951
+ }
952
+ function useChain() {
953
+ const accountsState = useSettingsState();
954
+ return CHAINS_MAP[accountsState.chainType];
955
+ }
956
+ function useChangeChainTypeCallback() {
957
+ const dispatch = useAppDispatch();
958
+ const wallet = useWallet();
959
+ return useCallback(
960
+ async (type) => {
961
+ dispatch(
962
+ settingsActions.updateSettings({
963
+ chainType: type
964
+ })
965
+ );
966
+ await wallet.setChainType(type);
967
+ },
968
+ [dispatch]
969
+ );
970
+ }
971
+ function useBTCUnit() {
972
+ const chainType = useChainType();
973
+ return CHAINS_MAP[chainType].unit;
974
+ }
975
+ function useTxExplorerUrl(txid) {
976
+ const chain = useChain();
977
+ if (chain.enum === ChainType.BITCOIN_MAINNET) {
978
+ return `${chain.unisatExplorerUrl}/tx/${txid}`;
979
+ } else if (chain.defaultExplorer === "mempool-space") {
980
+ return `${chain.mempoolSpaceUrl}/tx/${txid}`;
981
+ } else {
982
+ return `${chain.unisatExplorerUrl}/tx/${txid}`;
983
+ }
984
+ }
985
+ function useGetTxExplorerUrlCallback() {
986
+ const chain = useChain();
987
+ return useCallback(
988
+ (txid) => {
989
+ if (chain.enum === ChainType.BITCOIN_MAINNET) {
990
+ return `${chain.unisatExplorerUrl}/tx/${txid}`;
991
+ } else if (chain.defaultExplorer === "mempool-space") {
992
+ return `${chain.mempoolSpaceUrl}/tx/${txid}`;
993
+ } else {
994
+ return `${chain.unisatExplorerUrl}/tx/${txid}`;
995
+ }
996
+ },
997
+ [chain]
998
+ );
999
+ }
1000
+ function useAddressExplorerUrl(address) {
1001
+ const chain = useChain();
1002
+ if (chain.enum === ChainType.BITCOIN_MAINNET) {
1003
+ return `${chain.unisatExplorerUrl}/address/${address}`;
1004
+ } else if (chain.defaultExplorer === "mempool-space") {
1005
+ return `${chain.mempoolSpaceUrl}/address/${address}`;
1006
+ } else {
1007
+ return `${chain.unisatExplorerUrl}/address/${address}`;
1008
+ }
1009
+ }
1010
+ function useCAT20TokenInfoExplorerUrl(version, tokenId) {
1011
+ const chain = useChain();
1012
+ if (version === CAT_VERSION.V1) {
1013
+ return `${chain.unisatExplorerUrl}/cat20/${tokenId}`;
1014
+ } else {
1015
+ return `${chain.unisatExplorerUrl}/cat20-v2/${tokenId}`;
1016
+ }
1017
+ }
1018
+ function useUnisatWebsite() {
1019
+ const chainType = useChainType();
1020
+ return CHAINS_MAP[chainType].unisatUrl;
1021
+ }
1022
+ function useOrdinalsWebsite() {
1023
+ const chainType = useChainType();
1024
+ return CHAINS_MAP[chainType].ordinalsUrl;
1025
+ }
1026
+ function useWalletConfig() {
1027
+ const accountsState = useSettingsState();
1028
+ return accountsState.walletConfig;
1029
+ }
1030
+ function useVersionInfo() {
1031
+ const accountsState = useSettingsState();
1032
+ const walletConfig = accountsState.walletConfig;
1033
+ const newVersion = walletConfig.version;
1034
+ const skippedVersion = accountsState.skippedVersion;
1035
+ const currentVesion = VERSION;
1036
+ let skipped = false;
1037
+ let latestVersion = "";
1038
+ if (!newVersion) {
1039
+ skipped = true;
1040
+ }
1041
+ if (newVersion == skippedVersion) {
1042
+ skipped = true;
1043
+ }
1044
+ if (newVersion) {
1045
+ if (compareVersions(currentVesion, newVersion) >= 0) {
1046
+ skipped = true;
1047
+ } else {
1048
+ latestVersion = newVersion;
1049
+ }
1050
+ }
1051
+ if (currentVesion === "0.0.0") {
1052
+ skipped = true;
1053
+ }
1054
+ return {
1055
+ currentVesion,
1056
+ newVersion,
1057
+ latestVersion,
1058
+ skipped
1059
+ };
1060
+ }
1061
+ function useSkipVersionCallback() {
1062
+ const wallet = useWallet();
1063
+ const dispatch = useAppDispatch();
1064
+ return useCallback((version) => {
1065
+ wallet.setSkippedVersion(version).then((v) => {
1066
+ dispatch(settingsActions.updateSettings({ skippedVersion: version }));
1067
+ });
1068
+ }, []);
1069
+ }
1070
+ function useAutoLockTimeId() {
1071
+ const state = useSettingsState();
1072
+ return state.autoLockTimeId;
1073
+ }
1074
+ function getAddressTips(address, chanEnum) {
1075
+ let ret = {
1076
+ homeTip: "",
1077
+ sendTip: ""
1078
+ };
1079
+ try {
1080
+ const chain = CHAINS_MAP[chanEnum];
1081
+ const addressType = getAddressType(address, chain.networkType);
1082
+ if (chain.isFractal && addressType === AddressType.P2PKH) {
1083
+ ret = {
1084
+ homeTip: t("legacy_address_warning_3"),
1085
+ sendTip: t("legacy_address_warning_4")
1086
+ };
1087
+ }
1088
+ } catch (e) {
1089
+ console.log(e);
1090
+ }
1091
+ return ret;
1092
+ }
1093
+ function useAddressTips() {
1094
+ const chain = useChain();
1095
+ const account = useCurrentAccount();
1096
+ return getAddressTips(account.address, chain.enum);
1097
+ }
1098
+ function useCAT721NFTContentBaseUrl(version) {
1099
+ const chainType = useChainType();
1100
+ if (chainType === ChainType.FRACTAL_BITCOIN_MAINNET) {
1101
+ if (version === CAT_VERSION.V1) {
1102
+ return "https://tracker-fractal-mainnet.catprotocol.org";
1103
+ } else {
1104
+ return "https://tracker2-fractal-mainnet.catprotocol.org";
1105
+ }
1106
+ } else if (chainType === ChainType.FRACTAL_BITCOIN_TESTNET) {
1107
+ return "https://tracker-fractal-testnet.catprotocol.org";
1108
+ } else {
1109
+ return "";
1110
+ }
1111
+ }
1112
+ function useBRC20MarketPlaceWebsite(ticker) {
1113
+ const chainType = useChainType();
1114
+ if (chainType === ChainType.BITCOIN_MAINNET) {
1115
+ if (ticker.length == 6) {
1116
+ return `${CHAINS_MAP[chainType].unisatUrl}/market/brc20_prog?tick=${ticker}`;
1117
+ }
1118
+ }
1119
+ return `${CHAINS_MAP[chainType].unisatUrl}/market/brc20?tick=${ticker}`;
1120
+ }
1121
+ function useRunesMarketPlaceWebsite(ticker) {
1122
+ const chainType = useChainType();
1123
+ return `${CHAINS_MAP[chainType].unisatUrl}/runes/market?tick=${ticker}`;
1124
+ }
1125
+ function useCAT20MarketPlaceWebsite(tokenId) {
1126
+ const chainType = useChainType();
1127
+ return `${CHAINS_MAP[chainType].unisatUrl}/dex/cat20/${tokenId}`;
1128
+ }
1129
+ function useBabylonConfig() {
1130
+ const chainType = useChainType();
1131
+ return BABYLON_CONFIG_MAP[chainType] || BABYLON_CONFIG_MAP[ChainType.BITCOIN_MAINNET];
1132
+ }
1133
+ function useIsMainnetChain() {
1134
+ const chainType = useChainType();
1135
+ return chainType === ChainType.BITCOIN_MAINNET || chainType === ChainType.FRACTAL_BITCOIN_MAINNET;
1136
+ }
1137
+ function useDeveloperMode() {
1138
+ const settings = useSettingsState();
1139
+ return settings.developerMode;
1140
+ }
1141
+ function useSetDeveloperModeCallback() {
1142
+ const dispatch = useAppDispatch();
1143
+ const wallet = useWallet();
1144
+ return useCallback(
1145
+ async (developerMode) => {
1146
+ await wallet.setDeveloperMode(developerMode);
1147
+ dispatch(
1148
+ settingsActions.updateSettings({
1149
+ developerMode
1150
+ })
1151
+ );
1152
+ },
1153
+ [dispatch, wallet]
1154
+ );
1155
+ }
1156
+ var PriceContext = createContext({});
1157
+ function usePrice() {
1158
+ const context = useContext(PriceContext);
1159
+ if (!context) {
1160
+ throw Error("Feature flag hooks can only be used by children of BridgeProvider.");
1161
+ } else {
1162
+ return context;
1163
+ }
1164
+ }
1165
+ var isRequestingCoinPrice = false;
1166
+ var refreshCoinPriceTime = 0;
1167
+ function PriceProvider({ children }) {
1168
+ const wallet = useWallet();
1169
+ const chainType = useChainType();
1170
+ const chain = useChain();
1171
+ const [isLoadingCoinPrice, setIsLoadingCoinPrice] = useState(false);
1172
+ const [coinPrice, setCoinPrice] = useState({
1173
+ btc: 0,
1174
+ fb: 0
1175
+ });
1176
+ const refreshCoinPrice = useCallback(() => {
1177
+ if (chain.showPrice === false) {
1178
+ return;
1179
+ }
1180
+ if (isRequestingCoinPrice) {
1181
+ return;
1182
+ }
1183
+ if (Date.now() - refreshCoinPriceTime < 30 * 1e3) {
1184
+ return;
1185
+ }
1186
+ isRequestingCoinPrice = true;
1187
+ setIsLoadingCoinPrice(true);
1188
+ wallet.getCoinPrice().then((res) => {
1189
+ refreshCoinPriceTime = Date.now();
1190
+ setCoinPrice(res);
1191
+ }).catch((e) => {
1192
+ setCoinPrice({
1193
+ btc: 0,
1194
+ fb: 0
1195
+ });
1196
+ }).finally(() => {
1197
+ setIsLoadingCoinPrice(false);
1198
+ isRequestingCoinPrice = false;
1199
+ });
1200
+ }, [chainType, chain]);
1201
+ useEffect(() => {
1202
+ refreshCoinPrice();
1203
+ }, [refreshCoinPrice]);
1204
+ const value = {
1205
+ isLoadingCoinPrice,
1206
+ coinPrice,
1207
+ refreshCoinPrice
1208
+ };
1209
+ return /* @__PURE__ */ jsx(PriceContext.Provider, { value, children });
1210
+ }
1211
+ var UI_TYPE = {
1212
+ Tab: "index",
1213
+ Pop: "popup",
1214
+ Notification: "notification",
1215
+ SidePanel: "sidepanel"
1216
+ };
1217
+ var getUiType = () => {
1218
+ const { pathname } = window.location;
1219
+ return Object.entries(UI_TYPE).reduce((m, [key, value]) => {
1220
+ m[`is${key}`] = pathname === `/${value}.html`;
1221
+ return m;
1222
+ }, {});
1223
+ };
1224
+ var useApproval = () => {
1225
+ const wallet = useWallet();
1226
+ const navigate = useNavigate();
1227
+ const getApproval = wallet.getApproval;
1228
+ const resolveApproval = async (data, stay = false, forceReject = false) => {
1229
+ const approval = await getApproval();
1230
+ if (approval) {
1231
+ wallet.resolveApproval(data, forceReject);
1232
+ }
1233
+ if (stay) {
1234
+ return;
1235
+ }
1236
+ setTimeout(() => {
1237
+ navigate("/");
1238
+ });
1239
+ };
1240
+ const rejectApproval = async (err, stay = false, isInternal = false) => {
1241
+ const approval = await getApproval();
1242
+ if (approval) {
1243
+ await wallet.rejectApproval(err, stay, isInternal);
1244
+ }
1245
+ if (!stay) {
1246
+ navigate("/");
1247
+ }
1248
+ };
1249
+ useEffect(() => {
1250
+ if (!getUiType().isNotification) {
1251
+ return () => {
1252
+ };
1253
+ }
1254
+ window.addEventListener("beforeunload", rejectApproval);
1255
+ return () => window.removeEventListener("beforeunload", rejectApproval);
1256
+ }, []);
1257
+ return [getApproval, resolveApproval, rejectApproval];
1258
+ };
1259
+
1260
+ // src/hooks/discovery.ts
1261
+ function useDiscoveryState() {
1262
+ return useAppSelector((state) => state.discovery);
1263
+ }
1264
+ function useAppList() {
1265
+ const state = useDiscoveryState();
1266
+ return state.appList;
1267
+ }
1268
+ function useBannerList() {
1269
+ const state = useDiscoveryState();
1270
+ return state.bannerList;
1271
+ }
1272
+ function useLastFetchInfo() {
1273
+ const state = useDiscoveryState();
1274
+ return {
1275
+ lastFetchTime: state.lastFetchTime,
1276
+ lasfFetchChainType: state.lastFetchChainType
1277
+ };
1278
+ }
1279
+ function useHasNewBanner() {
1280
+ const state = useDiscoveryState();
1281
+ return state.hasNewBanner;
1282
+ }
1283
+ function useGlobalState() {
1284
+ return useAppSelector((state) => state.global);
1285
+ }
1286
+ function useTab() {
1287
+ const globalState = useGlobalState();
1288
+ return globalState.tab;
1289
+ }
1290
+ function useSetTabCallback() {
1291
+ const dispatch = useAppDispatch();
1292
+ return useCallback(
1293
+ (tab) => {
1294
+ dispatch(
1295
+ globalActions["update"]({
1296
+ tab
1297
+ })
1298
+ );
1299
+ },
1300
+ [dispatch]
1301
+ );
1302
+ }
1303
+ function useBooted() {
1304
+ const globalState = useGlobalState();
1305
+ return globalState.isBooted;
1306
+ }
1307
+ function useIsUnlocked() {
1308
+ const globalState = useGlobalState();
1309
+ return globalState.isUnlocked;
1310
+ }
1311
+ function useIsReady() {
1312
+ const globalState = useGlobalState();
1313
+ return globalState.isReady;
1314
+ }
1315
+ function useUnlockCallback() {
1316
+ const dispatch = useAppDispatch();
1317
+ const wallet = useWallet();
1318
+ const [, resolveApproval] = useApproval();
1319
+ return useCallback(
1320
+ async (password) => {
1321
+ await wallet.unlock(password);
1322
+ dispatch(globalActions.update({ isUnlocked: true }));
1323
+ resolveApproval();
1324
+ },
1325
+ [dispatch, wallet]
1326
+ );
1327
+ }
1328
+ function useCreateAccountCallback() {
1329
+ const dispatch = useAppDispatch();
1330
+ const wallet = useWallet();
1331
+ return useCallback(
1332
+ async (mnemonics, hdPath, passphrase, addressType, accountCount) => {
1333
+ await wallet.createKeyringWithMnemonics(
1334
+ mnemonics,
1335
+ hdPath,
1336
+ passphrase,
1337
+ addressType,
1338
+ accountCount
1339
+ );
1340
+ dispatch(globalActions.update({ isUnlocked: true }));
1341
+ },
1342
+ [dispatch, wallet]
1343
+ );
1344
+ }
1345
+ function useImportAccountsFromKeystoneCallback() {
1346
+ const dispatch = useAppDispatch();
1347
+ const wallet = useWallet();
1348
+ return useCallback(
1349
+ async (urType, urCbor, addressType, accountCount, hdPath, filterPubkey, connectionType = "USB") => {
1350
+ await wallet.createKeyringWithKeystone(
1351
+ urType,
1352
+ urCbor,
1353
+ addressType,
1354
+ hdPath,
1355
+ accountCount,
1356
+ filterPubkey,
1357
+ connectionType
1358
+ );
1359
+ dispatch(globalActions.update({ isUnlocked: true }));
1360
+ },
1361
+ [dispatch, wallet]
1362
+ );
1363
+ }
1364
+ function useCreateColdWalletCallback() {
1365
+ const dispatch = useAppDispatch();
1366
+ const wallet = useWallet();
1367
+ return useCallback(
1368
+ async (xpub, addressType, alianName, hdPath, accountCount) => {
1369
+ await wallet.createKeyringWithColdWallet(xpub, addressType, alianName, hdPath, accountCount);
1370
+ dispatch(globalActions.update({ isUnlocked: true }));
1371
+ },
1372
+ [dispatch, wallet]
1373
+ );
1374
+ }
1375
+ var defaultI18nContext = {
1376
+ t: (key) => key,
1377
+ locale: FALLBACK_LOCALE,
1378
+ supportedLocales: [FALLBACK_LOCALE],
1379
+ localeNames: LOCALE_NAMES,
1380
+ changeLocale: async () => {
1381
+ }
1382
+ };
1383
+ var useI18n = () => {
1384
+ try {
1385
+ const context = useContext(I18nContext);
1386
+ if (!context) {
1387
+ console.warn("useI18n must be used within an I18nProvider, using default context instead");
1388
+ return defaultI18nContext;
1389
+ }
1390
+ return context;
1391
+ } catch (error) {
1392
+ console.error("Error in useI18n:", error);
1393
+ return defaultI18nContext;
1394
+ }
1395
+ };
1396
+ var getCurrentLocale = async () => {
1397
+ return await getCurrentLocaleAsync();
1398
+ };
1399
+ var getSpecialLocale = async () => {
1400
+ const currentLocale = await getCurrentLocale();
1401
+ const specialLocales = ["es", "ru", "fr", "ja"];
1402
+ const isSpecialLocale = specialLocales.includes(currentLocale);
1403
+ return { currentLocale, isSpecialLocale };
1404
+ };
1405
+ function useTools() {
1406
+ return {
1407
+ showLoading: (show) => {
1408
+ }
1409
+ };
1410
+ }
1411
+ function useTransactionsState() {
1412
+ return useAppSelector((state) => state.transactions);
1413
+ }
1414
+ function useBitcoinTx() {
1415
+ const transactionsState = useTransactionsState();
1416
+ return transactionsState.bitcoinTx;
1417
+ }
1418
+ function usePrepareSendBTCCallback() {
1419
+ const dispatch = useAppDispatch();
1420
+ const wallet = useWallet();
1421
+ const fromAddress = useAccountAddress();
1422
+ const utxos = useUtxos();
1423
+ const fetchUtxos = useFetchUtxosCallback();
1424
+ useCurrentAccount();
1425
+ useBTCUnit();
1426
+ const { t: t2 } = useI18n();
1427
+ return useCallback(
1428
+ async ({
1429
+ toAddressInfo,
1430
+ toAmount,
1431
+ feeRate,
1432
+ enableRBF,
1433
+ memo,
1434
+ memos,
1435
+ disableAutoAdjust
1436
+ }) => {
1437
+ let _utxos = utxos;
1438
+ if (_utxos.length === 0) {
1439
+ _utxos = await fetchUtxos();
1440
+ }
1441
+ const safeBalance = _utxos.filter((v) => v.inscriptions.length == 0).reduce((pre, cur) => pre + cur.satoshis, 0);
1442
+ if (safeBalance < toAmount) {
1443
+ throw new Error(t2("insufficient_balance"));
1444
+ }
1445
+ if (!feeRate) {
1446
+ const summary = await wallet.getFeeSummary();
1447
+ feeRate = summary.list[1].feeRate;
1448
+ }
1449
+ let res;
1450
+ if (safeBalance === toAmount && !disableAutoAdjust) {
1451
+ res = await wallet.sendAllBTC({
1452
+ to: toAddressInfo.address,
1453
+ btcUtxos: _utxos,
1454
+ enableRBF,
1455
+ feeRate
1456
+ });
1457
+ } else {
1458
+ res = await wallet.sendBTC({
1459
+ to: toAddressInfo.address,
1460
+ amount: toAmount,
1461
+ btcUtxos: _utxos,
1462
+ enableRBF,
1463
+ feeRate,
1464
+ memo,
1465
+ memos
1466
+ });
1467
+ }
1468
+ dispatch(
1469
+ transactionsActions.updateBitcoinTx({
1470
+ rawtx: res.rawtx,
1471
+ psbtHex: res.psbtHex,
1472
+ fromAddress,
1473
+ feeRate,
1474
+ enableRBF
1475
+ })
1476
+ );
1477
+ const rawTxInfo = {
1478
+ psbtHex: res.psbtHex,
1479
+ rawtx: res.rawtx,
1480
+ toAddressInfo,
1481
+ fee: res.fee
1482
+ };
1483
+ return rawTxInfo;
1484
+ },
1485
+ [dispatch, wallet, fromAddress, utxos, fetchUtxos]
1486
+ );
1487
+ }
1488
+ function usePrepareSendBypassHeadOffsetsCallback() {
1489
+ const dispatch = useAppDispatch();
1490
+ const wallet = useWallet();
1491
+ const fromAddress = useAccountAddress();
1492
+ useCurrentAccount();
1493
+ useBTCUnit();
1494
+ return useCallback(
1495
+ async ({
1496
+ toAddressInfo,
1497
+ toAmount,
1498
+ feeRate
1499
+ }) => {
1500
+ const res = await wallet.sendCoinBypassHeadOffsets(
1501
+ [
1502
+ {
1503
+ address: toAddressInfo.address,
1504
+ satoshis: toAmount
1505
+ }
1506
+ ],
1507
+ feeRate
1508
+ );
1509
+ dispatch(
1510
+ transactionsActions.updateBitcoinTx({
1511
+ rawtx: res.rawtx,
1512
+ psbtHex: res.psbtHex,
1513
+ fromAddress,
1514
+ feeRate
1515
+ })
1516
+ );
1517
+ const rawTxInfo = {
1518
+ psbtHex: res.psbtHex,
1519
+ rawtx: res.rawtx,
1520
+ toAddressInfo,
1521
+ fee: res.fee
1522
+ };
1523
+ return rawTxInfo;
1524
+ },
1525
+ [dispatch, wallet, fromAddress]
1526
+ );
1527
+ }
1528
+ function usePushBitcoinTxCallback() {
1529
+ const dispatch = useAppDispatch();
1530
+ const wallet = useWallet();
1531
+ const tools = useTools();
1532
+ return useCallback(
1533
+ async (rawtx) => {
1534
+ const ret = {
1535
+ success: false,
1536
+ txid: "",
1537
+ error: ""
1538
+ };
1539
+ try {
1540
+ tools.showLoading(true);
1541
+ const txid = await wallet.pushTx(rawtx);
1542
+ await timeUtils.sleep(3);
1543
+ tools.showLoading(false);
1544
+ dispatch(transactionsActions.updateBitcoinTx({ txid }));
1545
+ dispatch(accountActions.expireBalance());
1546
+ setTimeout(() => {
1547
+ dispatch(accountActions.expireBalance());
1548
+ }, 2e3);
1549
+ setTimeout(() => {
1550
+ dispatch(accountActions.expireBalance());
1551
+ }, 5e3);
1552
+ ret.success = true;
1553
+ ret.txid = txid;
1554
+ } catch (e) {
1555
+ ret.error = e.message;
1556
+ }
1557
+ return ret;
1558
+ },
1559
+ [dispatch, wallet]
1560
+ );
1561
+ }
1562
+ function useOrdinalsTx() {
1563
+ const transactionsState = useTransactionsState();
1564
+ return transactionsState.ordinalsTx;
1565
+ }
1566
+ function usePrepareSendOrdinalsInscriptionCallback() {
1567
+ const dispatch = useAppDispatch();
1568
+ const wallet = useWallet();
1569
+ const fromAddress = useAccountAddress();
1570
+ const utxos = useUtxos();
1571
+ const fetchUtxos = useFetchUtxosCallback();
1572
+ useCurrentAccount();
1573
+ return useCallback(
1574
+ async ({
1575
+ toAddressInfo,
1576
+ inscriptionId,
1577
+ feeRate,
1578
+ outputValue,
1579
+ enableRBF
1580
+ }) => {
1581
+ if (!feeRate) {
1582
+ const summary = await wallet.getFeeSummary();
1583
+ feeRate = summary.list[1].feeRate;
1584
+ }
1585
+ let btcUtxos = utxos;
1586
+ if (btcUtxos.length === 0) {
1587
+ btcUtxos = await fetchUtxos();
1588
+ }
1589
+ const res = await wallet.sendOrdinalsInscription({
1590
+ to: toAddressInfo.address,
1591
+ inscriptionId,
1592
+ feeRate,
1593
+ outputValue,
1594
+ enableRBF,
1595
+ btcUtxos
1596
+ });
1597
+ dispatch(
1598
+ transactionsActions.updateOrdinalsTx({
1599
+ rawtx: res.rawtx,
1600
+ psbtHex: res.psbtHex,
1601
+ fromAddress,
1602
+ // inscription,
1603
+ feeRate,
1604
+ outputValue,
1605
+ enableRBF
1606
+ })
1607
+ );
1608
+ const rawTxInfo = {
1609
+ psbtHex: res.psbtHex,
1610
+ rawtx: res.rawtx,
1611
+ toAddressInfo
1612
+ };
1613
+ return rawTxInfo;
1614
+ },
1615
+ [dispatch, wallet, fromAddress, utxos]
1616
+ );
1617
+ }
1618
+ function usePrepareSendOrdinalsInscriptionsCallback() {
1619
+ const dispatch = useAppDispatch();
1620
+ const wallet = useWallet();
1621
+ const fromAddress = useAccountAddress();
1622
+ const fetchUtxos = useFetchUtxosCallback();
1623
+ const utxos = useUtxos();
1624
+ useCurrentAccount();
1625
+ return useCallback(
1626
+ async ({
1627
+ toAddressInfo,
1628
+ inscriptionIds,
1629
+ feeRate,
1630
+ enableRBF
1631
+ }) => {
1632
+ if (!feeRate) {
1633
+ const summary = await wallet.getFeeSummary();
1634
+ feeRate = summary.list[1].feeRate;
1635
+ }
1636
+ let btcUtxos = utxos;
1637
+ if (btcUtxos.length === 0) {
1638
+ btcUtxos = await fetchUtxos();
1639
+ }
1640
+ const res = await wallet.sendOrdinalsInscriptions({
1641
+ to: toAddressInfo.address,
1642
+ inscriptionIds,
1643
+ feeRate,
1644
+ enableRBF,
1645
+ btcUtxos
1646
+ });
1647
+ dispatch(
1648
+ transactionsActions.updateOrdinalsTx({
1649
+ rawtx: res.rawtx,
1650
+ psbtHex: res.psbtHex,
1651
+ fromAddress,
1652
+ feeRate,
1653
+ enableRBF
1654
+ })
1655
+ );
1656
+ const rawTxInfo = {
1657
+ psbtHex: res.psbtHex,
1658
+ rawtx: res.rawtx,
1659
+ toAddressInfo
1660
+ };
1661
+ return rawTxInfo;
1662
+ },
1663
+ [dispatch, wallet, fromAddress, utxos]
1664
+ );
1665
+ }
1666
+ function useCreateSplitTxCallback() {
1667
+ const dispatch = useAppDispatch();
1668
+ const wallet = useWallet();
1669
+ const fromAddress = useAccountAddress();
1670
+ const utxos = useUtxos();
1671
+ const fetchUtxos = useFetchUtxosCallback();
1672
+ useCurrentAccount();
1673
+ return useCallback(
1674
+ async ({
1675
+ inscriptionId,
1676
+ feeRate,
1677
+ outputValue,
1678
+ enableRBF
1679
+ }) => {
1680
+ let btcUtxos = utxos;
1681
+ if (btcUtxos.length === 0) {
1682
+ btcUtxos = await fetchUtxos();
1683
+ }
1684
+ const res = await wallet.splitOrdinalsInscription({
1685
+ inscriptionId,
1686
+ feeRate,
1687
+ outputValue,
1688
+ enableRBF,
1689
+ btcUtxos
1690
+ });
1691
+ dispatch(
1692
+ transactionsActions.updateOrdinalsTx({
1693
+ rawtx: res.rawtx,
1694
+ psbtHex: res.psbtHex,
1695
+ fromAddress,
1696
+ // inscription,
1697
+ enableRBF,
1698
+ feeRate,
1699
+ outputValue
1700
+ })
1701
+ );
1702
+ const rawTxInfo = {
1703
+ psbtHex: res.psbtHex,
1704
+ rawtx: res.rawtx,
1705
+ toAddressInfo: {
1706
+ address: fromAddress
1707
+ }
1708
+ };
1709
+ return { rawTxInfo, splitedCount: res.splitedCount };
1710
+ },
1711
+ [dispatch, wallet, fromAddress, utxos]
1712
+ );
1713
+ }
1714
+ function usePushOrdinalsTxCallback() {
1715
+ const dispatch = useAppDispatch();
1716
+ const wallet = useWallet();
1717
+ const tools = useTools();
1718
+ return useCallback(
1719
+ async (rawtx) => {
1720
+ const ret = {
1721
+ success: false,
1722
+ txid: "",
1723
+ error: ""
1724
+ };
1725
+ try {
1726
+ tools.showLoading(true);
1727
+ const txid = await wallet.pushTx(rawtx);
1728
+ await timeUtils.sleep(3);
1729
+ tools.showLoading(false);
1730
+ dispatch(transactionsActions.updateOrdinalsTx({ txid }));
1731
+ dispatch(accountActions.expireBalance());
1732
+ setTimeout(() => {
1733
+ dispatch(accountActions.expireBalance());
1734
+ }, 2e3);
1735
+ setTimeout(() => {
1736
+ dispatch(accountActions.expireBalance());
1737
+ }, 5e3);
1738
+ ret.success = true;
1739
+ ret.txid = txid;
1740
+ } catch (e) {
1741
+ console.log(e);
1742
+ ret.error = e.message;
1743
+ }
1744
+ return ret;
1745
+ },
1746
+ [dispatch, wallet]
1747
+ );
1748
+ }
1749
+ function useUtxos() {
1750
+ const transactionsState = useTransactionsState();
1751
+ return transactionsState.utxos;
1752
+ }
1753
+ function useFetchUtxosCallback() {
1754
+ const dispatch = useAppDispatch();
1755
+ const wallet = useWallet();
1756
+ const account = useCurrentAccount();
1757
+ return useCallback(async () => {
1758
+ const data = await wallet.getBTCUtxos();
1759
+ dispatch(transactionsActions.setUtxos(data));
1760
+ return data;
1761
+ }, [wallet, account]);
1762
+ }
1763
+ function useSpendUnavailableUtxos() {
1764
+ const transactionsState = useTransactionsState();
1765
+ return transactionsState.spendUnavailableUtxos;
1766
+ }
1767
+ function useSetSpendUnavailableUtxosCallback() {
1768
+ const dispatch = useAppDispatch();
1769
+ return useCallback(
1770
+ (utxos) => {
1771
+ dispatch(transactionsActions.setSpendUnavailableUtxos(utxos));
1772
+ },
1773
+ [dispatch]
1774
+ );
1775
+ }
1776
+ function useSafeBalance() {
1777
+ const utxos = useUtxos();
1778
+ return useMemo(() => {
1779
+ const satoshis = utxos.filter((v) => v.inscriptions.length === 0).reduce((pre, cur) => pre + cur.satoshis, 0);
1780
+ return numUtils.satoshisToAmount(satoshis);
1781
+ }, [utxos]);
1782
+ }
1783
+ function useAssetUtxosRunes() {
1784
+ const transactionsState = useTransactionsState();
1785
+ return transactionsState.assetUtxos_runes;
1786
+ }
1787
+ function useFetchAssetUtxosRunesCallback() {
1788
+ const dispatch = useAppDispatch();
1789
+ const wallet = useWallet();
1790
+ const account = useCurrentAccount();
1791
+ return useCallback(
1792
+ async (rune) => {
1793
+ const data = await wallet.getAssetUtxosRunes(rune);
1794
+ dispatch(transactionsActions.setAssetUtxosRunes(data));
1795
+ return data;
1796
+ },
1797
+ [wallet, account]
1798
+ );
1799
+ }
1800
+ function usePrepareSendRunesCallback() {
1801
+ const dispatch = useAppDispatch();
1802
+ const wallet = useWallet();
1803
+ const fromAddress = useAccountAddress();
1804
+ const utxos = useUtxos();
1805
+ const fetchUtxos = useFetchUtxosCallback();
1806
+ const assetUtxosRunes = useAssetUtxosRunes();
1807
+ const fetchAssetUtxosRunes = useFetchAssetUtxosRunesCallback();
1808
+ const account = useCurrentAccount();
1809
+ return useCallback(
1810
+ async ({
1811
+ toAddressInfo,
1812
+ runeid,
1813
+ runeAmount,
1814
+ outputValue,
1815
+ feeRate,
1816
+ enableRBF
1817
+ }) => {
1818
+ if (!feeRate) {
1819
+ const summary = await wallet.getFeeSummary();
1820
+ feeRate = summary.list[1].feeRate;
1821
+ }
1822
+ let btcUtxos = utxos;
1823
+ if (btcUtxos.length === 0) {
1824
+ btcUtxos = await fetchUtxos();
1825
+ }
1826
+ let assetUtxos = assetUtxosRunes;
1827
+ if (assetUtxos.length == 0) {
1828
+ assetUtxos = await fetchAssetUtxosRunes(runeid);
1829
+ }
1830
+ const res = await wallet.sendRunes({
1831
+ to: toAddressInfo.address,
1832
+ runeid,
1833
+ runeAmount,
1834
+ outputValue,
1835
+ feeRate,
1836
+ enableRBF,
1837
+ btcUtxos,
1838
+ assetUtxos
1839
+ });
1840
+ dispatch(
1841
+ transactionsActions.updateRunesTx({
1842
+ rawtx: res.rawtx,
1843
+ psbtHex: res.psbtHex,
1844
+ fromAddress,
1845
+ feeRate,
1846
+ enableRBF,
1847
+ runeid,
1848
+ runeAmount,
1849
+ outputValue
1850
+ })
1851
+ );
1852
+ const rawTxInfo = {
1853
+ psbtHex: res.psbtHex,
1854
+ rawtx: res.rawtx,
1855
+ toAddressInfo
1856
+ };
1857
+ return rawTxInfo;
1858
+ },
1859
+ [dispatch, wallet, fromAddress, utxos, assetUtxosRunes, fetchAssetUtxosRunes, account]
1860
+ );
1861
+ }
1862
+ function useRunesTx() {
1863
+ const transactionsState = useTransactionsState();
1864
+ return transactionsState.runesTx;
1865
+ }
1866
+ function usePrepareSendAlkanesCallback() {
1867
+ const wallet = useWallet();
1868
+ const account = useCurrentAccount();
1869
+ const callback = useCallback(
1870
+ async (toAddressInfo, alkaneid, amount, feeRate, enableRBF = false) => {
1871
+ return await wallet.sendAlkanes({
1872
+ to: toAddressInfo.address,
1873
+ alkaneid,
1874
+ amount,
1875
+ feeRate,
1876
+ enableRBF
1877
+ });
1878
+ },
1879
+ [wallet, account]
1880
+ );
1881
+ return callback;
1882
+ }
1883
+ function useUIState() {
1884
+ return useAppSelector((state) => state.ui);
1885
+ }
1886
+ function useAssetTabKey() {
1887
+ const uiState = useUIState();
1888
+ return uiState.assetTabKey;
1889
+ }
1890
+ function useOrdinalsAssetTabKey() {
1891
+ const uiState = useUIState();
1892
+ return uiState.ordinalsAssetTabKey;
1893
+ }
1894
+ function useCATAssetTabKey() {
1895
+ const uiState = useUIState();
1896
+ return uiState.catAssetTabKey;
1897
+ }
1898
+ function useAlkanesAssetTabKey() {
1899
+ const uiState = useUIState();
1900
+ return uiState.alkanesAssetTabKey;
1901
+ }
1902
+ function useUiTxCreateScreen() {
1903
+ const uiState = useUIState();
1904
+ return uiState.uiTxCreateScreen;
1905
+ }
1906
+ function useUpdateUiTxCreateScreen() {
1907
+ const dispatch = useAppDispatch();
1908
+ return ({
1909
+ toInfo,
1910
+ inputAmount,
1911
+ enableRBF,
1912
+ feeRate
1913
+ }) => {
1914
+ dispatch(uiActions.updateTxCreateScreen({ toInfo, inputAmount, enableRBF, feeRate }));
1915
+ };
1916
+ }
1917
+ function useResetUiTxCreateScreen() {
1918
+ const dispatch = useAppDispatch();
1919
+ return () => {
1920
+ dispatch(uiActions.resetTxCreateScreen());
1921
+ };
1922
+ }
1923
+ function useSupportedAssets() {
1924
+ const chainType = useChainType();
1925
+ const currentAddress = useCurrentAddress();
1926
+ useNetworkType();
1927
+ useCurrentAccount();
1928
+ const assetTabKeys = [];
1929
+ const assets = {
1930
+ ordinals: false,
1931
+ runes: false,
1932
+ CAT20: false,
1933
+ alkanes: false
1934
+ };
1935
+ assets.ordinals = true;
1936
+ assetTabKeys.push(0 /* ORDINALS */);
1937
+ assets.runes = true;
1938
+ assetTabKeys.push(2 /* RUNES */);
1939
+ if (chainType === ChainType.FRACTAL_BITCOIN_MAINNET || chainType === ChainType.FRACTAL_BITCOIN_TESTNET) {
1940
+ const addressType = getAddressType(currentAddress);
1941
+ if (addressType == AddressType.P2TR || addressType == AddressType.P2WPKH) {
1942
+ assets.CAT20 = true;
1943
+ assetTabKeys.push(3 /* CAT */);
1944
+ }
1945
+ }
1946
+ if (chainType === ChainType.BITCOIN_SIGNET || chainType === ChainType.BITCOIN_MAINNET) {
1947
+ assets.alkanes = true;
1948
+ assetTabKeys.push(4 /* ALKANES */);
1949
+ }
1950
+ return {
1951
+ tabKeys: assetTabKeys,
1952
+ assets,
1953
+ key: assetTabKeys.join(",")
1954
+ };
1955
+ }
1956
+ var useIsInExpandView = () => {
1957
+ if (typeof window === "undefined") {
1958
+ return false;
1959
+ }
1960
+ return useMemo(() => {
1961
+ if (window.innerWidth > 156 * 3) {
1962
+ return true;
1963
+ } else {
1964
+ return false;
1965
+ }
1966
+ }, [window.innerWidth]);
1967
+ };
1968
+ var useUtxoTools = (chain) => {
1969
+ const openUtxoTools = () => {
1970
+ window.open(`${chain.unisatUrl}/utxo?tab=all`);
1971
+ };
1972
+ return {
1973
+ openUtxoTools
1974
+ };
1975
+ };
1976
+
1977
+ // src/utils/eventBus.ts
1978
+ var EventBus = class {
1979
+ constructor() {
1980
+ this.events = {};
1981
+ this.emit = (type, params) => {
1982
+ const listeners = this.events[type];
1983
+ if (listeners) {
1984
+ listeners.forEach((fn) => {
1985
+ fn(params);
1986
+ });
1987
+ }
1988
+ };
1989
+ this.once = (type, fn) => {
1990
+ const listeners = this.events[type];
1991
+ const func = (...params) => {
1992
+ fn(...params);
1993
+ this.events[type] = this.events[type].filter((item) => item !== func);
1994
+ };
1995
+ if (listeners) {
1996
+ this.events[type].push(func);
1997
+ } else {
1998
+ this.events[type] = [func];
1999
+ }
2000
+ };
2001
+ this.addEventListener = (type, fn) => {
2002
+ const listeners = this.events[type];
2003
+ if (listeners) {
2004
+ this.events[type].push(fn);
2005
+ } else {
2006
+ this.events[type] = [fn];
2007
+ }
2008
+ };
2009
+ this.removeEventListener = (type, fn) => {
2010
+ const listeners = this.events[type];
2011
+ if (listeners) {
2012
+ this.events[type] = this.events[type].filter((item) => item !== fn);
2013
+ }
2014
+ };
2015
+ this.removeAllEventListeners = (type) => {
2016
+ this.events[type] = [];
2017
+ };
2018
+ }
2019
+ };
2020
+ var eventBus_default = new EventBus();
2021
+
2022
+ // src/updater/accounts.ts
2023
+ function AccountUpdater() {
2024
+ const dispatch = useAppDispatch();
2025
+ const wallet = useWallet();
2026
+ const currentAccount = useCurrentAccount();
2027
+ const isUnlocked = useIsUnlocked();
2028
+ const selfRef = useRef({
2029
+ preAccountKey: "",
2030
+ loadingBalance: false,
2031
+ loadingHistory: false
2032
+ });
2033
+ const self = selfRef.current;
2034
+ const reloadAccounts = useReloadAccounts();
2035
+ const onCurrentChange = useCallback(async () => {
2036
+ if (isUnlocked && currentAccount && currentAccount.key != self.preAccountKey) {
2037
+ self.preAccountKey = currentAccount.key;
2038
+ reloadAccounts();
2039
+ }
2040
+ }, [dispatch, currentAccount, wallet, isUnlocked]);
2041
+ useEffect(() => {
2042
+ onCurrentChange();
2043
+ }, [currentAccount && currentAccount.key, isUnlocked]);
2044
+ const fetchBalance = useFetchBalanceCallback();
2045
+ useEffect(() => {
2046
+ if (self.loadingBalance) {
2047
+ return;
2048
+ }
2049
+ if (!isUnlocked) {
2050
+ return;
2051
+ }
2052
+ self.loadingBalance = true;
2053
+ fetchBalance().finally(() => {
2054
+ self.loadingBalance = false;
2055
+ });
2056
+ }, [fetchBalance, wallet, isUnlocked, self]);
2057
+ useEffect(() => {
2058
+ const accountChangeHandler = (account) => {
2059
+ if (account && account.address) {
2060
+ dispatch(accountActions.setCurrent(account));
2061
+ }
2062
+ };
2063
+ eventBus_default.addEventListener("accountsChanged", accountChangeHandler);
2064
+ return () => {
2065
+ eventBus_default.removeEventListener("accountsChanged", accountChangeHandler);
2066
+ };
2067
+ }, [dispatch]);
2068
+ useEffect(() => {
2069
+ const chaintChangeHandler = (params) => {
2070
+ dispatch(
2071
+ settingsActions.updateSettings({
2072
+ chainType: params.type
2073
+ })
2074
+ );
2075
+ reloadAccounts();
2076
+ };
2077
+ eventBus_default.addEventListener("chainChanged", chaintChangeHandler);
2078
+ return () => {
2079
+ eventBus_default.removeEventListener("chainChanged", chaintChangeHandler);
2080
+ };
2081
+ }, [dispatch]);
2082
+ useEffect(() => {
2083
+ const lockHandler = () => {
2084
+ dispatch(globalActions.update({ isUnlocked: false }));
2085
+ };
2086
+ eventBus_default.addEventListener("lock", lockHandler);
2087
+ return () => {
2088
+ eventBus_default.removeEventListener("lock", lockHandler);
2089
+ };
2090
+ }, [dispatch]);
2091
+ useEffect(() => {
2092
+ const unlockHandler = () => {
2093
+ dispatch(globalActions.update({ isUnlocked: true }));
2094
+ };
2095
+ eventBus_default.addEventListener("unlock", unlockHandler);
2096
+ return () => {
2097
+ eventBus_default.removeEventListener("unlock", unlockHandler);
2098
+ };
2099
+ }, [dispatch]);
2100
+ return null;
2101
+ }
2102
+
2103
+ // src/index.ts
2104
+ var PERSISTED_KEYS = ["ui", "discovery"];
2105
+ var store = configureStore({
2106
+ reducer: {
2107
+ accounts: accounts_default,
2108
+ transactions: transactions_default,
2109
+ settings: settings_default,
2110
+ global: global_default,
2111
+ keyrings: keyrings_default,
2112
+ ui: ui_default,
2113
+ discovery: discovery_default
2114
+ },
2115
+ middleware: (getDefaultMiddleware) => getDefaultMiddleware({ thunk: true }).concat(save({ states: PERSISTED_KEYS, debounce: 1e3 })),
2116
+ preloadedState: load({ states: PERSISTED_KEYS, disableWarnings: true })
2117
+ });
2118
+ store.dispatch(updateVersion());
2119
+ setupListeners(store.dispatch);
2120
+ var src_default = store;
2121
+
2122
+ export { AccountUpdater, I18nProvider, PriceProvider, WalletProvider, src_default as default, getAddressTips, getCurrentLocale, getSpecialLocale, getUiType, useAddressExplorerUrl, useAddressTips, useAlkanesAssetTabKey, useAppDispatch, useAppList, useAppSelector, useApproval, useAssetTabKey, useAssetUtxosRunes, useAutoLockTimeId, useBRC20MarketPlaceWebsite, useBTCUnit, useBabylonConfig, useBannerList, useBitcoinTx, useBooted, useCAT20MarketPlaceWebsite, useCAT20TokenInfoExplorerUrl, useCAT721NFTContentBaseUrl, useCATAssetTabKey, useChain, useChainType, useChangeChainTypeCallback, useChangeLocaleCallback, useChangeNetworkTypeCallback, useCreateAccountCallback, useCreateColdWalletCallback, useCreateSplitTxCallback, useCurrentKeyring, useDeveloperMode, useDiscoveryState, useFetchAssetUtxosRunesCallback, useFetchUtxosCallback, useGetTxExplorerUrlCallback, useGlobalState, useHasNewBanner, useI18n, useImportAccountsFromKeystoneCallback, useIsInExpandView, useIsMainnetChain, useIsReady, useIsUnlocked, useKeyrings, useKeyringsState, useLastFetchInfo, useLocale, useNetworkType, useOrdinalsAssetTabKey, useOrdinalsTx, useOrdinalsWebsite, usePrepareSendAlkanesCallback, usePrepareSendBTCCallback, usePrepareSendBypassHeadOffsetsCallback, usePrepareSendOrdinalsInscriptionCallback, usePrepareSendOrdinalsInscriptionsCallback, usePrepareSendRunesCallback, usePrice, usePushBitcoinTxCallback, usePushOrdinalsTxCallback, useResetUiTxCreateScreen, useRunesMarketPlaceWebsite, useRunesTx, useSafeBalance, useSetDeveloperModeCallback, useSetSpendUnavailableUtxosCallback, useSetTabCallback, useSettingsState, useSkipVersionCallback, useSpendUnavailableUtxos, useSupportedAssets, useTab, useTransactionsState, useTxExplorerUrl, useUIState, useUiTxCreateScreen, useUnisatWebsite, useUnlockCallback, useUpdateUiTxCreateScreen, useUtxoTools, useUtxos, useVersionInfo, useWallet, useWalletConfig };
2123
+ //# sourceMappingURL=out.js.map
2124
+ //# sourceMappingURL=index.mjs.map