@maximedogawa/chia-wallet-connect-react 0.0.1

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 (146) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +622 -0
  3. package/dist/api.d.ts +62 -0
  4. package/dist/api.d.ts.map +1 -0
  5. package/dist/api.js +170 -0
  6. package/dist/api.js.map +1 -0
  7. package/dist/components/shared/CopyButton.d.ts +11 -0
  8. package/dist/components/shared/CopyButton.d.ts.map +1 -0
  9. package/dist/components/shared/CopyButton.js +122 -0
  10. package/dist/components/shared/CopyButton.js.map +1 -0
  11. package/dist/components/shared/Modal.d.ts +11 -0
  12. package/dist/components/shared/Modal.d.ts.map +1 -0
  13. package/dist/components/shared/Modal.js +18 -0
  14. package/dist/components/shared/Modal.js.map +1 -0
  15. package/dist/components/shared/SafeImage.d.ts +15 -0
  16. package/dist/components/shared/SafeImage.d.ts.map +1 -0
  17. package/dist/components/shared/SafeImage.js +15 -0
  18. package/dist/components/shared/SafeImage.js.map +1 -0
  19. package/dist/components/shared/icons/ChevronUpDownIcon.d.ts +6 -0
  20. package/dist/components/shared/icons/ChevronUpDownIcon.d.ts.map +1 -0
  21. package/dist/components/shared/icons/ChevronUpDownIcon.js +8 -0
  22. package/dist/components/shared/icons/ChevronUpDownIcon.js.map +1 -0
  23. package/dist/components/shared/icons/CrossIcon.d.ts +8 -0
  24. package/dist/components/shared/icons/CrossIcon.d.ts.map +1 -0
  25. package/dist/components/shared/icons/CrossIcon.js +8 -0
  26. package/dist/components/shared/icons/CrossIcon.js.map +1 -0
  27. package/dist/components/shared/icons/PlusIcon.d.ts +6 -0
  28. package/dist/components/shared/icons/PlusIcon.d.ts.map +1 -0
  29. package/dist/components/shared/icons/PlusIcon.js +8 -0
  30. package/dist/components/shared/icons/PlusIcon.js.map +1 -0
  31. package/dist/components/shared/icons/WalletConnectIcon.d.ts +7 -0
  32. package/dist/components/shared/icons/WalletConnectIcon.d.ts.map +1 -0
  33. package/dist/components/shared/icons/WalletConnectIcon.js +17 -0
  34. package/dist/components/shared/icons/WalletConnectIcon.js.map +1 -0
  35. package/dist/components/shared/navbar/Navbar.d.ts +7 -0
  36. package/dist/components/shared/navbar/Navbar.d.ts.map +1 -0
  37. package/dist/components/shared/navbar/Navbar.js +13 -0
  38. package/dist/components/shared/navbar/Navbar.js.map +1 -0
  39. package/dist/components/shared/navbar/walletIntegration/AddAssetButton.d.ts +10 -0
  40. package/dist/components/shared/navbar/walletIntegration/AddAssetButton.d.ts.map +1 -0
  41. package/dist/components/shared/navbar/walletIntegration/AddAssetButton.js +36 -0
  42. package/dist/components/shared/navbar/walletIntegration/AddAssetButton.js.map +1 -0
  43. package/dist/components/shared/navbar/walletIntegration/ConnectButton.d.ts +25 -0
  44. package/dist/components/shared/navbar/walletIntegration/ConnectButton.d.ts.map +1 -0
  45. package/dist/components/shared/navbar/walletIntegration/ConnectButton.js +79 -0
  46. package/dist/components/shared/navbar/walletIntegration/ConnectButton.js.map +1 -0
  47. package/dist/components/shared/navbar/walletIntegration/ConnectWalletModal.d.ts +10 -0
  48. package/dist/components/shared/navbar/walletIntegration/ConnectWalletModal.d.ts.map +1 -0
  49. package/dist/components/shared/navbar/walletIntegration/ConnectWalletModal.js +129 -0
  50. package/dist/components/shared/navbar/walletIntegration/ConnectWalletModal.js.map +1 -0
  51. package/dist/components/shared/navbar/walletIntegration/CustomWalletConnectModal.d.ts +11 -0
  52. package/dist/components/shared/navbar/walletIntegration/CustomWalletConnectModal.d.ts.map +1 -0
  53. package/dist/components/shared/navbar/walletIntegration/CustomWalletConnectModal.js +38 -0
  54. package/dist/components/shared/navbar/walletIntegration/CustomWalletConnectModal.js.map +1 -0
  55. package/dist/components/shared/navbar/walletIntegration/FingerprintListbox.d.ts +8 -0
  56. package/dist/components/shared/navbar/walletIntegration/FingerprintListbox.d.ts.map +1 -0
  57. package/dist/components/shared/navbar/walletIntegration/FingerprintListbox.js +25 -0
  58. package/dist/components/shared/navbar/walletIntegration/FingerprintListbox.js.map +1 -0
  59. package/dist/components/shared/navbar/walletIntegration/WalletConnectQR.d.ts +8 -0
  60. package/dist/components/shared/navbar/walletIntegration/WalletConnectQR.d.ts.map +1 -0
  61. package/dist/components/shared/navbar/walletIntegration/WalletConnectQR.js +35 -0
  62. package/dist/components/shared/navbar/walletIntegration/WalletConnectQR.js.map +1 -0
  63. package/dist/components/shared/navbar/walletIntegration/WalletConnectSession.d.ts +8 -0
  64. package/dist/components/shared/navbar/walletIntegration/WalletConnectSession.d.ts.map +1 -0
  65. package/dist/components/shared/navbar/walletIntegration/WalletConnectSession.js +64 -0
  66. package/dist/components/shared/navbar/walletIntegration/WalletConnectSession.js.map +1 -0
  67. package/dist/constants/sage-methods.d.ts +41 -0
  68. package/dist/constants/sage-methods.d.ts.map +1 -0
  69. package/dist/constants/sage-methods.js +71 -0
  70. package/dist/constants/sage-methods.js.map +1 -0
  71. package/dist/constants/wallet-connect.d.ts +49 -0
  72. package/dist/constants/wallet-connect.d.ts.map +1 -0
  73. package/dist/constants/wallet-connect.js +127 -0
  74. package/dist/constants/wallet-connect.js.map +1 -0
  75. package/dist/hooks/useWalletConnectRestore.d.ts +35 -0
  76. package/dist/hooks/useWalletConnectRestore.d.ts.map +1 -0
  77. package/dist/hooks/useWalletConnectRestore.js +122 -0
  78. package/dist/hooks/useWalletConnectRestore.js.map +1 -0
  79. package/dist/hooks/useWalletConnectionState.d.ts +27 -0
  80. package/dist/hooks/useWalletConnectionState.d.ts.map +1 -0
  81. package/dist/hooks/useWalletConnectionState.js +49 -0
  82. package/dist/hooks/useWalletConnectionState.js.map +1 -0
  83. package/dist/hooks.d.ts +7 -0
  84. package/dist/hooks.d.ts.map +1 -0
  85. package/dist/hooks.js +7 -0
  86. package/dist/hooks.js.map +1 -0
  87. package/dist/index.d.ts +25 -0
  88. package/dist/index.d.ts.map +1 -0
  89. package/dist/index.js +65 -0
  90. package/dist/index.js.map +1 -0
  91. package/dist/package.json +16 -0
  92. package/dist/state/completeWithWalletSlice.d.ts +18 -0
  93. package/dist/state/completeWithWalletSlice.d.ts.map +1 -0
  94. package/dist/state/completeWithWalletSlice.js +31 -0
  95. package/dist/state/completeWithWalletSlice.js.map +1 -0
  96. package/dist/state/globalOnLoadDataSlice.d.ts +17 -0
  97. package/dist/state/globalOnLoadDataSlice.d.ts.map +1 -0
  98. package/dist/state/globalOnLoadDataSlice.js +44 -0
  99. package/dist/state/globalOnLoadDataSlice.js.map +1 -0
  100. package/dist/state/settingsModalSlice.d.ts +7 -0
  101. package/dist/state/settingsModalSlice.d.ts.map +1 -0
  102. package/dist/state/settingsModalSlice.js +21 -0
  103. package/dist/state/settingsModalSlice.js.map +1 -0
  104. package/dist/state/store.d.ts +21 -0
  105. package/dist/state/store.d.ts.map +1 -0
  106. package/dist/state/store.js +110 -0
  107. package/dist/state/store.js.map +1 -0
  108. package/dist/state/walletConnectSlice.d.ts +16 -0
  109. package/dist/state/walletConnectSlice.d.ts.map +1 -0
  110. package/dist/state/walletConnectSlice.js +71 -0
  111. package/dist/state/walletConnectSlice.js.map +1 -0
  112. package/dist/state/walletSlice.d.ts +12 -0
  113. package/dist/state/walletSlice.d.ts.map +1 -0
  114. package/dist/state/walletSlice.js +44 -0
  115. package/dist/state/walletSlice.js.map +1 -0
  116. package/dist/styles/globals.css +54 -0
  117. package/dist/utils/analyticsUtils.d.ts +5 -0
  118. package/dist/utils/analyticsUtils.d.ts.map +1 -0
  119. package/dist/utils/analyticsUtils.js +32 -0
  120. package/dist/utils/analyticsUtils.js.map +1 -0
  121. package/dist/utils/deviceDetection.d.ts +14 -0
  122. package/dist/utils/deviceDetection.d.ts.map +1 -0
  123. package/dist/utils/deviceDetection.js +81 -0
  124. package/dist/utils/deviceDetection.js.map +1 -0
  125. package/dist/utils/logger.d.ts +13 -0
  126. package/dist/utils/logger.d.ts.map +1 -0
  127. package/dist/utils/logger.js +68 -0
  128. package/dist/utils/logger.js.map +1 -0
  129. package/dist/utils/walletIntegration/restoreConnectionState.d.ts +7 -0
  130. package/dist/utils/walletIntegration/restoreConnectionState.d.ts.map +1 -0
  131. package/dist/utils/walletIntegration/restoreConnectionState.js +145 -0
  132. package/dist/utils/walletIntegration/restoreConnectionState.js.map +1 -0
  133. package/dist/utils/walletIntegration/walletIntegrationInterface.d.ts +35 -0
  134. package/dist/utils/walletIntegration/walletIntegrationInterface.d.ts.map +1 -0
  135. package/dist/utils/walletIntegration/walletIntegrationInterface.js +3 -0
  136. package/dist/utils/walletIntegration/walletIntegrationInterface.js.map +1 -0
  137. package/dist/utils/walletIntegration/walletManager.d.ts +18 -0
  138. package/dist/utils/walletIntegration/walletManager.d.ts.map +1 -0
  139. package/dist/utils/walletIntegration/walletManager.js +118 -0
  140. package/dist/utils/walletIntegration/walletManager.js.map +1 -0
  141. package/dist/utils/walletIntegration/wallets/walletConnect.d.ts +65 -0
  142. package/dist/utils/walletIntegration/wallets/walletConnect.d.ts.map +1 -0
  143. package/dist/utils/walletIntegration/wallets/walletConnect.js +891 -0
  144. package/dist/utils/walletIntegration/wallets/walletConnect.js.map +1 -0
  145. package/package.json +107 -0
  146. package/tailwind.config.js +27 -0
@@ -0,0 +1,891 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const sign_client_1 = __importDefault(require("@walletconnect/sign-client"));
7
+ const modal_1 = require("@walletconnect/modal");
8
+ const react_hot_toast_1 = require("react-hot-toast");
9
+ const pino_1 = __importDefault(require("pino"));
10
+ const store_js_1 = __importDefault(require("../../../state/store.js"));
11
+ const walletSlice_js_1 = require("../../../state/walletSlice.js");
12
+ const walletConnectSlice_js_1 = require("../../../state/walletConnectSlice.js");
13
+ const completeWithWalletSlice_js_1 = require("../../../state/completeWithWalletSlice.js");
14
+ const wallet_connect_js_1 = require("../../../constants/wallet-connect.js");
15
+ const sage_methods_js_1 = require("../../../constants/sage-methods.js");
16
+ const logger_js_1 = require("../../../utils/logger.js");
17
+ const deviceDetection_js_1 = require("../../../utils/deviceDetection.js");
18
+ const logger = (0, logger_js_1.createLogger)('WalletConnect');
19
+ // Singleton SignClient instance to prevent multiple initializations
20
+ let globalSignClient = null;
21
+ let globalSignClientPromise = null;
22
+ // Type guard for WalletConnect errors
23
+ function isWalletConnectError(error) {
24
+ return (typeof error === 'object' &&
25
+ error !== null &&
26
+ 'message' in error &&
27
+ typeof error.message === 'string');
28
+ }
29
+ class WalletConnectIntegration {
30
+ name = "WalletConnect";
31
+ image;
32
+ chainId = wallet_connect_js_1.CHIA_CHAIN_ID;
33
+ topic;
34
+ client;
35
+ selectedFingerprint;
36
+ session;
37
+ metadata;
38
+ modal; // Native WalletConnect modal (desktop only)
39
+ modalThemeObserver; // Observer for theme changes
40
+ constructor(image, metadata) {
41
+ // Allow image to be passed as prop, otherwise use default from constants
42
+ this.image = image || wallet_connect_js_1.DEFAULT_WALLET_IMAGE;
43
+ // Allow metadata to be passed as prop for custom configuration
44
+ this.metadata = metadata;
45
+ // Give methods access to current Redux state
46
+ const state = store_js_1.default.getState();
47
+ const selectedSession = state.walletConnect.selectedSession;
48
+ if (selectedSession) {
49
+ this.topic = selectedSession.topic;
50
+ this.session = selectedSession;
51
+ const fingerprint = state.walletConnect.selectedFingerprint[selectedSession.topic];
52
+ this.selectedFingerprint = fingerprint;
53
+ }
54
+ }
55
+ async updateSessions() {
56
+ try {
57
+ const sessions = await this.getAllSessions();
58
+ if (sessions) {
59
+ store_js_1.default.dispatch((0, walletConnectSlice_js_1.setSessions)(sessions));
60
+ }
61
+ else {
62
+ store_js_1.default.dispatch((0, walletConnectSlice_js_1.setSessions)([]));
63
+ store_js_1.default.dispatch((0, walletSlice_js_1.setAddress)(null));
64
+ if (store_js_1.default.getState().wallet.connectedWallet === "WalletConnect")
65
+ store_js_1.default.dispatch((0, walletSlice_js_1.setConnectedWallet)(null));
66
+ logger.error('No WC sessions found');
67
+ }
68
+ }
69
+ catch (error) {
70
+ if (isWalletConnectError(error)) {
71
+ logger.error(`WalletConnect - ${error.message}`);
72
+ }
73
+ throw error;
74
+ }
75
+ }
76
+ async deleteTopicFromLocalStorage(topic) {
77
+ for (let i = 0; i < localStorage.length; i++) {
78
+ const key = localStorage.key(i);
79
+ if (key?.startsWith('wc') && key.endsWith('//session')) {
80
+ const responseList = await JSON.parse(localStorage.getItem(key));
81
+ localStorage.setItem(key, JSON.stringify(responseList.filter((item) => item.topic !== topic)));
82
+ }
83
+ }
84
+ }
85
+ // If the session being disconnected is the only session connected, then disconnect the wallet in the wallet slice
86
+ async updateConnectedWalletOnDisconnect(topic) {
87
+ const state = store_js_1.default.getState();
88
+ if (!state.walletConnect.sessions.length && "WalletConnect" === store_js_1.default.getState().wallet.connectedWallet) {
89
+ store_js_1.default.dispatch((0, walletSlice_js_1.setConnectedWallet)(null));
90
+ }
91
+ if (!topic)
92
+ return;
93
+ // If user disconnects the currently selected session, select the next available one
94
+ const sessions = state.walletConnect.sessions;
95
+ const selectedSession = state.walletConnect.selectedSession;
96
+ if (sessions.length && selectedSession && topic === selectedSession.topic) {
97
+ const newSessionTopic = sessions[sessions.length - 1].topic;
98
+ store_js_1.default.dispatch((0, walletConnectSlice_js_1.selectSession)(newSessionTopic));
99
+ }
100
+ }
101
+ async connect() {
102
+ // For WalletConnect, check if there are existing sessions
103
+ // If there are sessions but no selected session, select the first one
104
+ const state = store_js_1.default.getState();
105
+ const sessions = state.walletConnect.sessions;
106
+ const selectedSession = state.walletConnect.selectedSession;
107
+ if (sessions.length > 0 && !selectedSession) {
108
+ // Select the first available session
109
+ const firstSession = sessions[0];
110
+ store_js_1.default.dispatch((0, walletConnectSlice_js_1.selectSession)(firstSession.topic));
111
+ // Ensure fingerprint is set for this session
112
+ if (!state.walletConnect.selectedFingerprint[firstSession.topic]) {
113
+ const defaultFingerprint = Number(firstSession.namespaces.chia.accounts[0].split(":")[2]);
114
+ store_js_1.default.dispatch((0, walletConnectSlice_js_1.setSelectedFingerprint)({ topic: firstSession.topic, selectedFingerprint: defaultFingerprint }));
115
+ logger.debug('connect: Set default fingerprint for session', { topic: firstSession.topic, fingerprint: defaultFingerprint });
116
+ }
117
+ logger.debug('connect: Selected first available session', { topic: firstSession.topic });
118
+ return true;
119
+ }
120
+ // If there's already a selected session, ensure it has a fingerprint
121
+ if (selectedSession) {
122
+ if (!state.walletConnect.selectedFingerprint[selectedSession.topic]) {
123
+ const defaultFingerprint = Number(selectedSession.namespaces.chia.accounts[0].split(":")[2]);
124
+ store_js_1.default.dispatch((0, walletConnectSlice_js_1.setSelectedFingerprint)({ topic: selectedSession.topic, selectedFingerprint: defaultFingerprint }));
125
+ logger.debug('connect: Set default fingerprint for existing session', { topic: selectedSession.topic, fingerprint: defaultFingerprint });
126
+ }
127
+ logger.debug('connect: Session already selected', { topic: selectedSession.topic });
128
+ return true;
129
+ }
130
+ // No sessions available - user needs to call connectSession() first
131
+ logger.debug('connect: No sessions available, connectSession() must be called first');
132
+ return false;
133
+ }
134
+ async connectSession() {
135
+ // Initiate connection and pass pairing uri to the modal (QR code)
136
+ try {
137
+ const signClient = await this.signClient();
138
+ if (signClient) {
139
+ // Ensure modal is initialized before connecting (for desktop)
140
+ // Modal initialization happens in signClient(), but we need to ensure it's ready
141
+ if (!this.modal && !(0, deviceDetection_js_1.isIOS)() && typeof window !== 'undefined') {
142
+ const modalConfig = (0, wallet_connect_js_1.getModalConfig)();
143
+ if (modalConfig) {
144
+ try {
145
+ this.modal = new modal_1.WalletConnectModal(modalConfig);
146
+ logger.debug('Native WalletConnect modal initialized for desktop', { theme: modalConfig.themeMode });
147
+ this.setupThemeObserver();
148
+ }
149
+ catch (modalError) {
150
+ logger.error('Failed to initialize WalletConnect modal:', modalError);
151
+ }
152
+ }
153
+ }
154
+ // Use REQUIRED_NAMESPACES from constants (includes all Sage methods)
155
+ // Note: requiredNamespaces is deprecated, using optionalNamespaces instead
156
+ // Fetch uri to display QR code to establish new wallet connection
157
+ const { uri, approval } = await signClient.connect({
158
+ optionalNamespaces: wallet_connect_js_1.REQUIRED_NAMESPACES,
159
+ });
160
+ // Use native WalletConnect modal on desktop, custom modal on iOS
161
+ if (uri) {
162
+ if (this.modal && !(0, deviceDetection_js_1.isIOS)()) {
163
+ // Use native WalletConnect modal for desktop
164
+ this.modal.openModal({ uri });
165
+ logger.debug('Opened native WalletConnect modal');
166
+ }
167
+ else {
168
+ // Use custom modal for iOS or fallback
169
+ store_js_1.default.dispatch((0, walletConnectSlice_js_1.setPairingUri)(uri));
170
+ }
171
+ }
172
+ // If new connection established successfully
173
+ const session = await approval();
174
+ logger.info('Connected Chia wallet via WalletConnect', { session, signClient });
175
+ // Close native modal if it was opened
176
+ if (this.modal && !(0, deviceDetection_js_1.isIOS)()) {
177
+ this.modal.closeModal();
178
+ }
179
+ store_js_1.default.dispatch((0, walletConnectSlice_js_1.setPairingUri)(null));
180
+ this.detectEvents();
181
+ await this.updateSessions();
182
+ store_js_1.default.dispatch((0, walletConnectSlice_js_1.connectSession)(session));
183
+ // Update instance properties to match the new session
184
+ this.topic = session.topic;
185
+ this.session = session;
186
+ this.selectedFingerprint = Number(session.namespaces.chia.accounts[0].split(":")[2]);
187
+ // Verify connection using CHIA_GET_ADDRESS method (Sage method)
188
+ let address = null;
189
+ try {
190
+ logger.debug('Verifying connection using CHIA_GET_ADDRESS method...');
191
+ address = await this.verifyConnectionWithSageMethod();
192
+ if (address) {
193
+ logger.debug('Connection verified successfully!');
194
+ logger.debug('Address retrieved:', address);
195
+ }
196
+ else {
197
+ logger.debug('CHIA_GET_ADDRESS returned null, trying fallback method...');
198
+ // Fallback to regular getAddress if Sage method doesn't work
199
+ address = await this.getAddress();
200
+ logger.debug('Fallback address fetch result:', address);
201
+ }
202
+ }
203
+ catch (addressError) {
204
+ logger.debug('CHIA_GET_ADDRESS verification failed, trying fallback:', addressError);
205
+ // Try fallback method
206
+ try {
207
+ address = await this.getAddress();
208
+ logger.debug('Fallback address fetch successful:', address);
209
+ }
210
+ catch (fallbackError) {
211
+ logger.error('Failed to fetch address after connection:', fallbackError);
212
+ // Continue even if address fetch fails - connection is still successful
213
+ }
214
+ }
215
+ // Update main wallet slice to notify that it is now the active wallet
216
+ // Use WalletConnect icon (this.image) instead of Sage Wallet icon
217
+ const setConnectedWalletInfo = {
218
+ wallet: "WalletConnect",
219
+ address: address,
220
+ image: this.image, // Use WalletConnect icon, not Sage Wallet icon
221
+ name: "WalletConnect"
222
+ };
223
+ store_js_1.default.dispatch((0, walletSlice_js_1.setConnectedWallet)(setConnectedWalletInfo));
224
+ return session;
225
+ }
226
+ }
227
+ catch (error) {
228
+ logger.error('Error connecting WalletConnect session:', error);
229
+ // Close native modal if it was opened
230
+ if (this.modal && !(0, deviceDetection_js_1.isIOS)()) {
231
+ this.modal.closeModal();
232
+ }
233
+ // Clear pairing URI on error
234
+ store_js_1.default.dispatch((0, walletConnectSlice_js_1.setPairingUri)(null));
235
+ // Re-throw error so calling code can handle it
236
+ throw error;
237
+ }
238
+ }
239
+ disconnect() {
240
+ return true;
241
+ }
242
+ async disconnectSession(topic) {
243
+ // Sign client
244
+ const signClient = await this.signClient();
245
+ // Fetch previous connection
246
+ try {
247
+ if (!signClient) {
248
+ react_hot_toast_1.toast.error('Not connected via WalletConnect or could not sign client', { id: 'failed-to-sign-client' });
249
+ return;
250
+ }
251
+ // Send request to get Wallets via WalletConnect
252
+ await signClient.disconnect({
253
+ topic,
254
+ reason: {
255
+ code: 6000,
256
+ message: "User disconnected."
257
+ },
258
+ });
259
+ await this.deleteTopicFromLocalStorage(topic);
260
+ await this.updateSessions();
261
+ await this.updateConnectedWalletOnDisconnect();
262
+ // Remove any saved fingerprint preference if any
263
+ store_js_1.default.dispatch((0, walletConnectSlice_js_1.deleteTopicFromFingerprintMemory)(topic));
264
+ }
265
+ catch (error) {
266
+ this.updateSessions();
267
+ if (isWalletConnectError(error)) {
268
+ logger.error('Error disconnecting session:', error.message);
269
+ }
270
+ else {
271
+ logger.error('Error disconnecting session:', error);
272
+ }
273
+ }
274
+ }
275
+ async generateOffer(requestAssets, offerAssets, fee) {
276
+ // Show modal to user taking them through each step of the process
277
+ store_js_1.default.dispatch((0, completeWithWalletSlice_js_1.setRequestStep)("getWallets"));
278
+ store_js_1.default.dispatch((0, completeWithWalletSlice_js_1.setOfferRejected)(false));
279
+ // showCompleteWithWalletModal(this)
280
+ let firstRun = true;
281
+ let tempAssetsToAddArray = [];
282
+ let walletsResponse;
283
+ while (firstRun || tempAssetsToAddArray.length > 0) {
284
+ firstRun = false;
285
+ tempAssetsToAddArray = [];
286
+ // Send request to fetch users wallets
287
+ walletsResponse = await this.getWallets();
288
+ if (!walletsResponse?.isSage) {
289
+ const wallets = walletsResponse?.wallets;
290
+ if (!wallets) {
291
+ store_js_1.default.dispatch((0, completeWithWalletSlice_js_1.setRequestStep)(null));
292
+ return;
293
+ }
294
+ // Match assetIds to users wallet to find the wallet ID (required to send a create offer)
295
+ // For offering assets
296
+ offerAssets.forEach(offerItem => {
297
+ // If item is Chia, set walletId to 1 as this is the default
298
+ if (offerItem.assetId === "")
299
+ return offerItem.walletId = 1;
300
+ const matchingChiaWallet = wallets.data.find(item => item.meta.assetId === offerItem.assetId);
301
+ if (matchingChiaWallet) {
302
+ offerItem.walletId = matchingChiaWallet.id;
303
+ }
304
+ else {
305
+ tempAssetsToAddArray.push({ ...offerItem });
306
+ }
307
+ });
308
+ // For requesting assets
309
+ requestAssets.forEach(requestItem => {
310
+ // If item is Chia, set walletId to 1 as this is the default
311
+ if (requestItem.assetId === "")
312
+ return requestItem.walletId = 1;
313
+ const matchingChiaWallet = wallets.data.find(item => item.meta.assetId == requestItem.assetId);
314
+ if (matchingChiaWallet) {
315
+ requestItem.walletId = matchingChiaWallet.id;
316
+ }
317
+ else {
318
+ tempAssetsToAddArray.push({ ...requestItem });
319
+ }
320
+ });
321
+ if (tempAssetsToAddArray.length) {
322
+ store_js_1.default.dispatch((0, completeWithWalletSlice_js_1.setUserMustAddTheseAssetsToWallet)(tempAssetsToAddArray));
323
+ store_js_1.default.dispatch((0, completeWithWalletSlice_js_1.setRequestStep)("addAssets"));
324
+ // We now have a list of assets which need adding. We keep track of the list length. When it's 0, we can continue as all assets are added.
325
+ const checkIfAssetsHaveBeenAdded = () => {
326
+ return new Promise((resolve, reject) => {
327
+ const unsubscribe = store_js_1.default.subscribe(() => {
328
+ const state = store_js_1.default.getState();
329
+ const userMustAddTheseAssetsToWallet = state.completeWithWallet.userMustAddTheseAssetsToWallet;
330
+ if (userMustAddTheseAssetsToWallet.length === 0 && !state.completeWithWallet.offerRejected) {
331
+ unsubscribe();
332
+ store_js_1.default.dispatch((0, completeWithWalletSlice_js_1.setRequestStep)("getWalletsAgain"));
333
+ resolve();
334
+ }
335
+ else if (state.completeWithWallet.offerRejected) {
336
+ unsubscribe();
337
+ reject();
338
+ }
339
+ // Still more assets to add, wait for next update & check again
340
+ });
341
+ });
342
+ };
343
+ await checkIfAssetsHaveBeenAdded();
344
+ }
345
+ } // End of while loop (will run twice if user has had to add assets to continue)
346
+ }
347
+ store_js_1.default.dispatch((0, completeWithWalletSlice_js_1.setRequestStep)("generateOffer"));
348
+ // Generate offer object
349
+ const offer = {};
350
+ offerAssets.forEach((asset) => {
351
+ if (!asset.walletId)
352
+ return;
353
+ offer[asset.walletId] = -Math.abs(asset.amount);
354
+ });
355
+ // Generate request object
356
+ const request = {};
357
+ requestAssets.forEach((asset) => {
358
+ if (!asset.walletId)
359
+ return;
360
+ request[asset.walletId] = asset.amount;
361
+ });
362
+ // Create final object for WalletConnect request
363
+ const compressedOffer = { ...offer, ...request };
364
+ // Sign client
365
+ const signClient = await this.signClient();
366
+ // Fetch previous connection
367
+ try {
368
+ if (!this.topic || !signClient) {
369
+ react_hot_toast_1.toast.error('Not connected via WalletConnect or could not sign client', { id: 'failed-to-sign-client' });
370
+ return;
371
+ }
372
+ if (walletsResponse?.isSage) {
373
+ logger.info("Sage offer request");
374
+ const resultOffer = await signClient.request({
375
+ topic: this.topic,
376
+ chainId: this.chainId,
377
+ request: {
378
+ method: "chia_createOffer",
379
+ params: {
380
+ offerAssets: offerAssets.map(offerItem => {
381
+ const asset = {
382
+ assetId: offerItem.assetId,
383
+ amount: offerItem.amount
384
+ };
385
+ if (offerItem.hiddenPuzzleHash && offerItem.hiddenPuzzleHash.length == 64) {
386
+ asset.hiddenPuzzleHash = offerItem.hiddenPuzzleHash;
387
+ }
388
+ return asset;
389
+ }),
390
+ requestAssets: requestAssets.map(requestItem => {
391
+ const asset = {
392
+ assetId: requestItem.assetId,
393
+ amount: requestItem.amount
394
+ };
395
+ if (requestItem.hiddenPuzzleHash && requestItem.hiddenPuzzleHash.length == 64) {
396
+ asset.hiddenPuzzleHash = requestItem.hiddenPuzzleHash;
397
+ }
398
+ return asset;
399
+ }),
400
+ fee
401
+ },
402
+ },
403
+ });
404
+ if (resultOffer.error) {
405
+ react_hot_toast_1.toast.error(resultOffer.error);
406
+ // Set offer rejected: true
407
+ store_js_1.default.dispatch((0, completeWithWalletSlice_js_1.setOfferRejected)(true));
408
+ }
409
+ else if (resultOffer.offer) {
410
+ store_js_1.default.dispatch((0, completeWithWalletSlice_js_1.setRequestStep)(null));
411
+ return resultOffer.offer;
412
+ }
413
+ }
414
+ // Send request to generate offer via WalletConnect
415
+ const resultOffer = await signClient.request({
416
+ topic: this.topic,
417
+ chainId: this.chainId,
418
+ request: {
419
+ method: "chia_createOfferForIds",
420
+ params: {
421
+ fingerprint: this.selectedFingerprint,
422
+ offer: compressedOffer,
423
+ fee,
424
+ driverDict: {},
425
+ disableJSONFormatting: true,
426
+ },
427
+ },
428
+ });
429
+ if (resultOffer.error) {
430
+ react_hot_toast_1.toast.error(resultOffer.error?.data.error);
431
+ // Set offer rejected: true
432
+ store_js_1.default.dispatch((0, completeWithWalletSlice_js_1.setOfferRejected)(true));
433
+ }
434
+ else if (resultOffer.data) {
435
+ store_js_1.default.dispatch((0, completeWithWalletSlice_js_1.setRequestStep)(null));
436
+ return resultOffer.data.offer;
437
+ }
438
+ }
439
+ catch (_error) {
440
+ store_js_1.default.dispatch((0, completeWithWalletSlice_js_1.setOfferRejected)(true));
441
+ }
442
+ }
443
+ getBalance() {
444
+ // WalletConnect balance retrieval logic
445
+ }
446
+ async getWallets() {
447
+ // Sign client
448
+ const signClient = await this.signClient();
449
+ // Fetch previous connection
450
+ try {
451
+ if (!this.topic || !signClient) {
452
+ react_hot_toast_1.toast.error('Not connected via WalletConnect or could not sign client', { id: 'failed-to-sign-client' });
453
+ return;
454
+ }
455
+ try {
456
+ // Send request to get Wallets via WalletConnect
457
+ const request = signClient.request({
458
+ topic: this.topic,
459
+ chainId: this.chainId,
460
+ request: {
461
+ method: "chia_getWallets",
462
+ params: {
463
+ fingerprint: this.selectedFingerprint,
464
+ includeData: true
465
+ },
466
+ },
467
+ });
468
+ const wallets = await request;
469
+ if (wallets.isSuccess) {
470
+ return { isSage: false, wallets };
471
+ }
472
+ else {
473
+ throw Error('Fetching wallet request unsuccessful');
474
+ }
475
+ }
476
+ catch (error) {
477
+ if (isWalletConnectError(error) && error.code === 4001 && error.message === "Unsupported method: chia_getWallets") {
478
+ return {
479
+ isSage: true,
480
+ wallets: null,
481
+ };
482
+ }
483
+ else {
484
+ throw error;
485
+ }
486
+ }
487
+ }
488
+ catch (error) {
489
+ if (isWalletConnectError(error)) {
490
+ logger.error('Error generating offer:', error.message);
491
+ }
492
+ else {
493
+ logger.error('Error generating offer:', error);
494
+ }
495
+ }
496
+ }
497
+ async addAsset(assetId, symbol, logo, fullName) {
498
+ const displayName = `${fullName} (${symbol})`;
499
+ // Sign client
500
+ const signClient = await this.signClient();
501
+ // Fetch previous connection
502
+ try {
503
+ if (!this.topic || !signClient) {
504
+ react_hot_toast_1.toast.error('Not connected via WalletConnect or could not sign client', { id: 'failed-to-sign-client' });
505
+ throw Error('Not connected via WalletConnect or could not sign client');
506
+ }
507
+ // Send request to get Wallets via WalletConnect
508
+ const request = signClient.request({
509
+ topic: this.topic,
510
+ chainId: this.chainId,
511
+ request: {
512
+ method: "chia_addCATToken",
513
+ params: {
514
+ fingerprint: this.selectedFingerprint,
515
+ name: displayName,
516
+ assetId: assetId
517
+ },
518
+ },
519
+ });
520
+ await request;
521
+ return true;
522
+ }
523
+ catch (error) {
524
+ if (isWalletConnectError(error)) {
525
+ logger.error(`Wallet - ${error.message}`);
526
+ }
527
+ else {
528
+ logger.error(`Wallet -`, error);
529
+ }
530
+ throw error instanceof Error ? error : new Error(String(error));
531
+ }
532
+ }
533
+ /**
534
+ * Verify connection using CHIA_GET_ADDRESS method (Sage wallet method)
535
+ * This is used to verify that the connection is working correctly
536
+ */
537
+ async verifyConnectionWithSageMethod() {
538
+ logger.debug('verifyConnectionWithSageMethod: Starting verification...');
539
+ let signClient;
540
+ let topic;
541
+ try {
542
+ signClient = await this.signClient();
543
+ const state = store_js_1.default.getState();
544
+ topic = state.walletConnect.selectedSession?.topic || this.topic;
545
+ if (!topic || !signClient) {
546
+ logger.debug('verifyConnectionWithSageMethod: No topic or signClient available');
547
+ throw Error('Not connected via WalletConnect or could not sign client');
548
+ }
549
+ logger.debug('verifyConnectionWithSageMethod: Using method:', sage_methods_js_1.SageMethods.CHIA_GET_ADDRESS);
550
+ logger.debug('verifyConnectionWithSageMethod: Topic:', topic);
551
+ logger.debug('verifyConnectionWithSageMethod: ChainId:', this.chainId);
552
+ const request = signClient.request({
553
+ topic: topic,
554
+ chainId: this.chainId,
555
+ request: {
556
+ method: sage_methods_js_1.SageMethods.CHIA_GET_ADDRESS,
557
+ params: {},
558
+ },
559
+ });
560
+ logger.debug('verifyConnectionWithSageMethod: Request sent, awaiting response...');
561
+ const response = await request;
562
+ logger.debug('verifyConnectionWithSageMethod: Response received:', response);
563
+ const address = response?.address || null;
564
+ if (address) {
565
+ logger.debug('verifyConnectionWithSageMethod: Success! Address:', address);
566
+ store_js_1.default.dispatch((0, walletSlice_js_1.setAddress)(address));
567
+ }
568
+ else {
569
+ logger.debug('verifyConnectionWithSageMethod: No address in response');
570
+ }
571
+ return address;
572
+ }
573
+ catch (error) {
574
+ logger.debug('verifyConnectionWithSageMethod: Error occurred:', error);
575
+ if (isWalletConnectError(error) && error.code === 4001) {
576
+ logger.debug('verifyConnectionWithSageMethod: Method not supported (4001), wallet may not be Sage');
577
+ }
578
+ throw error;
579
+ }
580
+ }
581
+ async getAddress() {
582
+ logger.debug('getAddress: Starting address fetch...');
583
+ let signClient;
584
+ let topic;
585
+ try {
586
+ signClient = await this.signClient();
587
+ const state = store_js_1.default.getState();
588
+ topic = state.walletConnect.selectedSession?.topic;
589
+ if (!topic || !signClient) {
590
+ logger.debug('getAddress: No topic or signClient available');
591
+ react_hot_toast_1.toast.error('Not connected via WalletConnect or could not sign client', { id: 'failed-to-sign-client' });
592
+ throw Error('Not connected via WalletConnect or could not sign client');
593
+ }
594
+ const selectedSession = state?.walletConnect?.selectedSession;
595
+ if (!selectedSession) {
596
+ logger.debug('getAddress: No selected session');
597
+ return null;
598
+ }
599
+ const fingerprint = state.walletConnect.selectedFingerprint[selectedSession.topic];
600
+ if (!fingerprint) {
601
+ logger.debug('getAddress: No fingerprint selected');
602
+ return null;
603
+ }
604
+ const wallet_id = selectedSession?.namespaces?.chia?.accounts.findIndex(account => account.includes(fingerprint.toString()));
605
+ logger.debug('getAddress: Wallet ID:', wallet_id);
606
+ if (wallet_id === undefined) {
607
+ logger.debug('getAddress: Wallet ID is undefined');
608
+ return '';
609
+ }
610
+ logger.debug('getAddress: Requesting address with method chia_getCurrentAddress', {
611
+ topic,
612
+ chainId: this.chainId,
613
+ method: "chia_getCurrentAddress",
614
+ params: {
615
+ fingerprint: fingerprint,
616
+ wallet_id,
617
+ new_address: false
618
+ },
619
+ });
620
+ const request = signClient.request({
621
+ topic,
622
+ chainId: this.chainId,
623
+ request: {
624
+ method: "chia_getCurrentAddress",
625
+ params: {
626
+ fingerprint: fingerprint,
627
+ wallet_id,
628
+ new_address: false
629
+ },
630
+ },
631
+ });
632
+ const response = await request;
633
+ logger.debug('getAddress: Address request response received:', response);
634
+ const address = response?.data || null;
635
+ if (address) {
636
+ logger.debug('getAddress: Success! Address retrieved:', address);
637
+ store_js_1.default.dispatch((0, walletSlice_js_1.setAddress)(address));
638
+ }
639
+ else {
640
+ logger.debug('getAddress: No address in response');
641
+ }
642
+ return address;
643
+ }
644
+ catch (error) {
645
+ // Check for various error formats that indicate the method is not supported
646
+ const isUnsupportedMethod = isWalletConnectError(error) &&
647
+ error.code === 4001 &&
648
+ (error.message === "Unsupported method: chia_getCurrentAddress" ||
649
+ error.message.includes("Missing or invalid") && error.message.includes("chia_getCurrentAddress") ||
650
+ error.message.includes("request() method: chia_getCurrentAddress"));
651
+ if (isUnsupportedMethod) {
652
+ logger.debug('getAddress: chia_getCurrentAddress not supported, trying Sage method chia_getAddress');
653
+ logger.info("Sage wallet detected, using chia_getAddress method");
654
+ try {
655
+ const request = signClient.request({
656
+ topic: topic,
657
+ chainId: this.chainId,
658
+ request: {
659
+ method: "chia_getAddress",
660
+ params: {},
661
+ },
662
+ });
663
+ const response = await request;
664
+ logger.debug('getAddress: Sage address response received:', response);
665
+ const address = response.address;
666
+ if (address) {
667
+ logger.debug('getAddress: Success! Sage address retrieved:', address);
668
+ store_js_1.default.dispatch((0, walletSlice_js_1.setAddress)(address));
669
+ }
670
+ return address;
671
+ }
672
+ catch (sageError) {
673
+ logger.error('getAddress: Sage method also failed:', sageError);
674
+ return null;
675
+ }
676
+ }
677
+ logger.error('getAddress: Error getting address:', error);
678
+ return null;
679
+ }
680
+ }
681
+ async getAllSessions() {
682
+ const signClient = await this.signClient();
683
+ if (signClient)
684
+ return signClient.session.getAll();
685
+ }
686
+ /**
687
+ * Set up a MutationObserver to watch for theme changes (dark class on documentElement)
688
+ * and update the WalletConnect modal theme accordingly
689
+ */
690
+ setupThemeObserver() {
691
+ if (typeof window === 'undefined' || !this.modal) {
692
+ return;
693
+ }
694
+ // Clean up existing observer if any
695
+ if (this.modalThemeObserver) {
696
+ this.modalThemeObserver.disconnect();
697
+ }
698
+ // Create observer to watch for class changes on documentElement
699
+ this.modalThemeObserver = new MutationObserver((mutations) => {
700
+ mutations.forEach((mutation) => {
701
+ if (mutation.type === 'attributes' && mutation.attributeName === 'class') {
702
+ const isDark = document.documentElement.classList.contains('dark');
703
+ const newTheme = isDark ? 'dark' : 'light';
704
+ try {
705
+ // Update modal theme
706
+ // Note: WalletConnectModal may need to be re-initialized or have a setTheme method
707
+ // For now, we'll log the change - the modal should pick up theme changes on next open
708
+ logger.debug('Theme changed, updating WalletConnect modal', { theme: newTheme });
709
+ const modalWithTheme = this.modal;
710
+ if (modalWithTheme && typeof modalWithTheme.setTheme === 'function') {
711
+ modalWithTheme.setTheme(newTheme);
712
+ }
713
+ }
714
+ catch (error) {
715
+ logger.error('Failed to update modal theme:', error);
716
+ }
717
+ }
718
+ });
719
+ });
720
+ // Start observing the documentElement for class changes
721
+ this.modalThemeObserver.observe(document.documentElement, {
722
+ attributes: true,
723
+ attributeFilter: ['class'],
724
+ });
725
+ logger.debug('Theme observer set up for WalletConnect modal');
726
+ }
727
+ async signClient() {
728
+ // If client has been saved to object, return that instead of completing a new sign
729
+ if (this.client)
730
+ return this.client;
731
+ // Use global singleton to prevent multiple initializations
732
+ if (globalSignClient) {
733
+ this.client = globalSignClient;
734
+ return globalSignClient;
735
+ }
736
+ // If initialization is in progress, wait for it
737
+ if (globalSignClientPromise) {
738
+ const client = await globalSignClientPromise;
739
+ this.client = client;
740
+ return client;
741
+ }
742
+ try {
743
+ const projectId = wallet_connect_js_1.SIGN_CLIENT_CONFIG.projectId;
744
+ if (!projectId) {
745
+ throw new Error('WalletConnect project ID is not configured. Please set WALLET_CONNECT_PROJECT_ID or NEXT_PUBLIC_WALLET_CONNECT_PROJECT_ID in your .env file.');
746
+ }
747
+ // Create a filtered pino logger that suppresses non-critical WalletConnect errors
748
+ // WalletConnect logs non-critical internal errors (pairing cleanup, history restore, etc.)
749
+ // that don't affect functionality but clutter the console
750
+ const createFilteredLogger = () => {
751
+ const baseLogger = wallet_connect_js_1.SIGN_CLIENT_CONFIG.logger;
752
+ // Map log level strings to pino levels
753
+ const levelMap = {
754
+ 'error': 'error',
755
+ 'warn': 'warn',
756
+ 'info': 'info',
757
+ 'debug': 'debug',
758
+ 'trace': 'trace',
759
+ };
760
+ const logLevel = levelMap[baseLogger] || 'error';
761
+ // Create a custom stream that filters non-critical messages
762
+ const filteredStream = {
763
+ write: (chunk) => {
764
+ try {
765
+ const logObj = JSON.parse(chunk);
766
+ const context = logObj.context || '';
767
+ const msg = logObj.msg || '';
768
+ // Skip these non-critical errors that don't affect functionality
769
+ const nonCriticalPatterns = [
770
+ 'core/pairing/pairing',
771
+ 'core/history',
772
+ 'Restore will override',
773
+ 'failed to process an inbound message',
774
+ 'onRelayMessage',
775
+ 'Pairing not found',
776
+ ];
777
+ const shouldSkip = nonCriticalPatterns.some(pattern => context.includes(pattern) || msg.includes(pattern) || chunk.includes(pattern));
778
+ if (!shouldSkip) {
779
+ // Use console methods based on log level
780
+ // These console calls are intentional for WalletConnect's internal pino logger
781
+ // eslint-disable-next-line no-console
782
+ const level = logObj.level || 50;
783
+ if (level >= 50) {
784
+ // eslint-disable-next-line no-console
785
+ console.error(chunk);
786
+ }
787
+ else if (level >= 40) {
788
+ if (logLevel === 'warn' || logLevel === 'info' || logLevel === 'debug' || logLevel === 'trace') {
789
+ // eslint-disable-next-line no-console
790
+ console.warn(chunk);
791
+ }
792
+ }
793
+ else if (level >= 30 && (logLevel === 'info' || logLevel === 'debug' || logLevel === 'trace')) {
794
+ // eslint-disable-next-line no-console
795
+ console.info(chunk);
796
+ }
797
+ else if (level >= 20 && (logLevel === 'debug' || logLevel === 'trace')) {
798
+ // eslint-disable-next-line no-console
799
+ console.debug(chunk);
800
+ }
801
+ else if (level >= 10 && logLevel === 'trace') {
802
+ // eslint-disable-next-line no-console
803
+ console.trace(chunk);
804
+ }
805
+ }
806
+ }
807
+ catch (_e) {
808
+ // If parsing fails, log it normally (shouldn't happen with pino)
809
+ if (logLevel === 'error' || logLevel === 'warn') {
810
+ // eslint-disable-next-line no-console
811
+ console.error(chunk);
812
+ }
813
+ }
814
+ }
815
+ };
816
+ // Create pino logger with filtered stream
817
+ return (0, pino_1.default)({
818
+ level: logLevel,
819
+ }, filteredStream);
820
+ };
821
+ // Use custom metadata if provided, otherwise use default from config
822
+ const metadata = this.metadata ? {
823
+ name: this.metadata.name || wallet_connect_js_1.SIGN_CLIENT_CONFIG.metadata.name,
824
+ description: this.metadata.description || wallet_connect_js_1.SIGN_CLIENT_CONFIG.metadata.description,
825
+ url: this.metadata.url || wallet_connect_js_1.SIGN_CLIENT_CONFIG.metadata.url,
826
+ icons: this.metadata.icons || wallet_connect_js_1.SIGN_CLIENT_CONFIG.metadata.icons,
827
+ } : wallet_connect_js_1.SIGN_CLIENT_CONFIG.metadata;
828
+ const initOptions = {
829
+ // Use custom filtered logger or standard logger based on config
830
+ logger: createFilteredLogger(),
831
+ projectId: projectId,
832
+ metadata: metadata,
833
+ };
834
+ // Add relay URL if provided
835
+ if (wallet_connect_js_1.SIGN_CLIENT_CONFIG.relayUrl) {
836
+ initOptions.relayUrl = wallet_connect_js_1.SIGN_CLIENT_CONFIG.relayUrl;
837
+ }
838
+ // Create initialization promise to prevent concurrent initializations
839
+ globalSignClientPromise = sign_client_1.default.init(initOptions).then((signClient) => {
840
+ globalSignClient = signClient;
841
+ this.client = signClient;
842
+ globalSignClientPromise = null;
843
+ return signClient;
844
+ });
845
+ const signClient = await globalSignClientPromise;
846
+ // Initialize native WalletConnect modal for desktop (not iOS)
847
+ // iOS uses custom modal with better clipboard support
848
+ // Only initialize modal once per instance
849
+ if (!this.modal && !(0, deviceDetection_js_1.isIOS)() && typeof window !== 'undefined') {
850
+ const modalConfig = (0, wallet_connect_js_1.getModalConfig)();
851
+ if (modalConfig) {
852
+ try {
853
+ this.modal = new modal_1.WalletConnectModal(modalConfig);
854
+ logger.debug('Native WalletConnect modal initialized for desktop', { theme: modalConfig.themeMode });
855
+ // Set up theme observer to update modal when theme changes
856
+ this.setupThemeObserver();
857
+ }
858
+ catch (modalError) {
859
+ logger.error('Failed to initialize WalletConnect modal:', modalError);
860
+ // Continue without modal - fallback to custom implementation
861
+ }
862
+ }
863
+ else {
864
+ logger.warn('WalletConnect modal not initialized: projectId is required');
865
+ }
866
+ }
867
+ return signClient;
868
+ }
869
+ catch (e) {
870
+ // Clear the promise on error so retry is possible
871
+ globalSignClientPromise = null;
872
+ react_hot_toast_1.toast.error(`Wallet - ${e}`);
873
+ throw e; // Re-throw to allow calling code to handle the error
874
+ }
875
+ }
876
+ async detectEvents() {
877
+ // Sign client
878
+ const signClient = await this.signClient();
879
+ if (!signClient)
880
+ return;
881
+ // If user disconnects from UI or wallet, refresh the page
882
+ signClient.on("session_delete", async ({ id, topic }) => {
883
+ // Check localstorage and ensure it is removed from there
884
+ // await this.deleteTopicFromLocalStorage(topic);
885
+ await this.updateSessions();
886
+ await this.updateConnectedWalletOnDisconnect(topic);
887
+ });
888
+ }
889
+ }
890
+ exports.default = WalletConnectIntegration;
891
+ //# sourceMappingURL=walletConnect.js.map