@dynamic-labs/ethereum 4.9.1 → 4.9.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 (28) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/package.cjs +1 -1
  3. package/package.js +1 -1
  4. package/package.json +11 -11
  5. package/src/EthereumWalletConnectors.cjs +3 -1
  6. package/src/EthereumWalletConnectors.js +3 -1
  7. package/src/injected/InjectedWalletBase.cjs +8 -2
  8. package/src/injected/InjectedWalletBase.js +8 -2
  9. package/src/metaMask/MetaMaskConnector.cjs +3 -0
  10. package/src/metaMask/MetaMaskConnector.d.ts +1 -0
  11. package/src/metaMask/MetaMaskConnector.js +3 -0
  12. package/src/metaMask/utils/createMetaMaskSDKDisplayUriState.cjs +1 -0
  13. package/src/metaMask/utils/createMetaMaskSDKDisplayUriState.d.ts +1 -0
  14. package/src/metaMask/utils/createMetaMaskSDKDisplayUriState.js +1 -0
  15. package/src/walletConnect/WalletConnectConnector/WalletConnectConnector.cjs +292 -0
  16. package/src/walletConnect/{walletConnect.d.ts → WalletConnectConnector/WalletConnectConnector.d.ts} +14 -53
  17. package/src/walletConnect/WalletConnectConnector/WalletConnectConnector.js +288 -0
  18. package/src/walletConnect/WalletConnectConnector/index.d.ts +1 -0
  19. package/src/walletConnect/WalletConnectProvider/WalletConnectProvider.cjs +212 -0
  20. package/src/walletConnect/WalletConnectProvider/WalletConnectProvider.d.ts +10 -1
  21. package/src/walletConnect/WalletConnectProvider/WalletConnectProvider.js +204 -0
  22. package/src/walletConnect/index.d.ts +1 -1
  23. package/src/walletConnect/utils/fetchWalletConnectWallets.cjs +2 -2
  24. package/src/walletConnect/utils/fetchWalletConnectWallets.js +2 -2
  25. package/src/walletConnect/utils/getWalletConnectConnector.cjs +2 -2
  26. package/src/walletConnect/utils/getWalletConnectConnector.js +2 -2
  27. package/src/walletConnect/walletConnect.cjs +0 -504
  28. package/src/walletConnect/walletConnect.js +0 -495
@@ -0,0 +1,288 @@
1
+ 'use client'
2
+ import { __awaiter } from '../../../_virtual/_tslib.js';
3
+ import { createWalletClient, custom } from 'viem';
4
+ import { toAccount } from 'viem/accounts';
5
+ import { EthereumWalletConnector, chainsMap } from '@dynamic-labs/ethereum-core';
6
+ import { StorageService, parseIntSafe, DynamicError, isMobile, PlatformService } from '@dynamic-labs/utils';
7
+ import { logger, getDeepLink } from '@dynamic-labs/wallet-connector-core';
8
+ import { normalizeRpcError } from '../../utils/normalizeRpcError/normalizeRpcError.js';
9
+ import { WalletConnectProvider } from '../WalletConnectProvider/WalletConnectProvider.js';
10
+
11
+ const WC_CURRENT_CHAIN_KEY = 'dynamic-wc2-current-chain';
12
+ class WalletConnectConnector extends EthereumWalletConnector {
13
+ constructor(opts) {
14
+ super(opts);
15
+ this.canConnectViaQrCode = true;
16
+ this.isWalletConnect = true;
17
+ this.name = opts.walletName;
18
+ this.deepLinkPreference = opts.deepLinkPreference || 'native';
19
+ const storedChainId = StorageService.getItem(WC_CURRENT_CHAIN_KEY);
20
+ if (storedChainId) {
21
+ this.currentChainId = parseIntSafe(storedChainId);
22
+ }
23
+ if (!opts.projectId) {
24
+ throw new DynamicError('WalletConnect project ID is required');
25
+ }
26
+ // set provider props generic to all wallets
27
+ WalletConnectProvider.projectId = opts.projectId;
28
+ WalletConnectProvider.enabledNetworks = opts.evmNetworks;
29
+ WalletConnectProvider.preferredChains =
30
+ opts.walletConnectPreferredChains || [];
31
+ WalletConnectProvider.evmNetworkRpcMap = this.evmNetworkRpcMap();
32
+ }
33
+ init() {
34
+ return __awaiter(this, void 0, void 0, function* () {
35
+ logger.logVerboseTroubleshootingMessage('[WalletConnect] init called', {
36
+ isInitialized: WalletConnectProvider.isInitialized,
37
+ isInitializing: WalletConnectProvider.isInitializing,
38
+ });
39
+ // we should only init the provider once as soon as possible
40
+ // the connection is established when a wallet is selected (with getAddress)
41
+ if (WalletConnectProvider.isInitialized ||
42
+ WalletConnectProvider.isInitializing) {
43
+ logger.debug('[WalletConnect] init - already initialized or initializing - skipping');
44
+ return;
45
+ }
46
+ logger.debug('[WalletConnect] init');
47
+ this.walletConnectorEventsEmitter.emit('connectorInitStarted', 'walletconnect');
48
+ try {
49
+ yield WalletConnectProvider.init();
50
+ }
51
+ catch (error) {
52
+ logger.error('[WalletConnect] init - error', error);
53
+ throw new DynamicError('WalletConnectProvider failed to initialize');
54
+ }
55
+ this.setupWCEventListeners();
56
+ this.walletConnectorEventsEmitter.emit('connectorInitCompleted', 'walletconnect');
57
+ });
58
+ }
59
+ setupWCEventListeners() {
60
+ logger.debug('[WalletConnect] setupWCEventListeners');
61
+ WalletConnectProvider.teardownEventListeners();
62
+ WalletConnectProvider.setupEventListeners({
63
+ onAccountChanged: (account) => {
64
+ logger.debug('[WalletConnect] onAccountChanged', { account });
65
+ this.emit('accountChange', { accounts: [account] });
66
+ },
67
+ onChainChanged: (chainId) => {
68
+ logger.debug('[WalletConnect] onChainChange', { chainId });
69
+ if (chainId === this.currentChainId) {
70
+ logger.debug(`[WalletConnect] onChainChange - ignoring chainChanged event with same chain id as current chain id: ${chainId}`);
71
+ return;
72
+ }
73
+ this.currentChainId = chainId;
74
+ this.emit('chainChange', { chain: String(chainId) });
75
+ },
76
+ onDisconnect: () => {
77
+ logger.debug('[WalletConnect] onDisconnect');
78
+ this.endSession();
79
+ this.emit('disconnect');
80
+ },
81
+ });
82
+ }
83
+ endSession() {
84
+ return __awaiter(this, void 0, void 0, function* () {
85
+ logger.debug('[WalletConnect] endSession');
86
+ this.currentChainId = undefined;
87
+ yield WalletConnectProvider.disconnect();
88
+ });
89
+ }
90
+ getAddress(opts) {
91
+ return __awaiter(this, void 0, void 0, function* () {
92
+ logger.debug('[WalletConnect] getAddress', opts);
93
+ const provider = yield WalletConnectProvider.awaitAndGetProvider();
94
+ logger.debug('[WalletConnect] getAddress - connecting to WalletConnect', {
95
+ provider,
96
+ });
97
+ const addresses = yield WalletConnectProvider.connect({
98
+ connectionOpts: opts,
99
+ deepLinkPreference: this.deepLinkPreference,
100
+ deepLinks: this.metadata.deepLinks,
101
+ });
102
+ logger.debug('[WalletConnect] getAddress - connection result', addresses);
103
+ const address = addresses === null || addresses === void 0 ? void 0 : addresses[0];
104
+ return address;
105
+ });
106
+ }
107
+ getWalletClient(chainId) {
108
+ logger.logVerboseTroubleshootingMessage('[WalletConnect] getWalletClient was called - chainId', chainId);
109
+ const provider = WalletConnectProvider.getProvider();
110
+ if (!provider) {
111
+ logger.debug('[WalletConnect] getWalletClient - provider is not initialized');
112
+ throw new DynamicError('WalletConnectProvider is not initialized');
113
+ }
114
+ const walletClient = createWalletClient({
115
+ account: this.getActiveAccount(),
116
+ chain: chainsMap[chainId !== null && chainId !== void 0 ? chainId : String(this.currentChainId)],
117
+ transport: custom({
118
+ request: (args) => {
119
+ this.deepLinkIfApplicable(args.method);
120
+ return provider.request(args).catch(normalizeRpcError);
121
+ },
122
+ }),
123
+ });
124
+ return walletClient;
125
+ }
126
+ deepLinkIfApplicable(method) {
127
+ const methodsThatRequireDeepLink = [
128
+ 'personal_sign',
129
+ 'eth_sendTransaction',
130
+ 'eth_signTypedData_v4',
131
+ ];
132
+ const deepLink = this.getDeepLink();
133
+ if (isMobile() && deepLink && methodsThatRequireDeepLink.includes(method)) {
134
+ PlatformService.openURL(deepLink);
135
+ }
136
+ }
137
+ signMessage(messageToSign) {
138
+ return __awaiter(this, void 0, void 0, function* () {
139
+ logger.logVerboseTroubleshootingMessage('[WalletConnect] signMessage', messageToSign);
140
+ const activeAccount = this.getActiveAccount();
141
+ logger.logVerboseTroubleshootingMessage('[WalletConnect] signMessage - activeAccount', activeAccount);
142
+ if (!activeAccount) {
143
+ return;
144
+ }
145
+ const walletClient = yield this.getWalletClient();
146
+ return walletClient.signMessage({
147
+ account: activeAccount,
148
+ message: messageToSign,
149
+ });
150
+ });
151
+ }
152
+ getConnectedAccounts() {
153
+ return __awaiter(this, void 0, void 0, function* () {
154
+ const activeAccount = this.getActiveAccount();
155
+ logger.logVerboseTroubleshootingMessage('[WalletConnect] getConnectedAccounts - activeAccount', activeAccount);
156
+ return activeAccount ? [activeAccount.address] : [];
157
+ });
158
+ }
159
+ getActiveAccount() {
160
+ var _a;
161
+ const provider = WalletConnectProvider.getProvider();
162
+ const connectedAccount = (_a = provider === null || provider === void 0 ? void 0 : provider.accounts) === null || _a === void 0 ? void 0 : _a[0];
163
+ logger.logVerboseTroubleshootingMessage('[WalletConnect] getActiveAccount - connectedAccount', connectedAccount);
164
+ if (!connectedAccount) {
165
+ return undefined;
166
+ }
167
+ return toAccount(connectedAccount);
168
+ }
169
+ get currentChainId() {
170
+ const lsCurrentChain = StorageService.getItem(WC_CURRENT_CHAIN_KEY);
171
+ try {
172
+ return lsCurrentChain ? parseIntSafe(lsCurrentChain) : undefined;
173
+ }
174
+ catch (e) {
175
+ logger.debug('[WalletConnect] getCurrentChainId - error', e);
176
+ return undefined;
177
+ }
178
+ }
179
+ set currentChainId(value) {
180
+ if (value) {
181
+ StorageService.setItem(WC_CURRENT_CHAIN_KEY, value.toString());
182
+ }
183
+ else {
184
+ StorageService.removeItem(WC_CURRENT_CHAIN_KEY);
185
+ }
186
+ }
187
+ getActiveChain() {
188
+ if (!this.currentChainId) {
189
+ return undefined;
190
+ }
191
+ return chainsMap[this.currentChainId];
192
+ }
193
+ getNetwork() {
194
+ return __awaiter(this, void 0, void 0, function* () {
195
+ logger.logVerboseTroubleshootingMessage('[WalletConnect] getNetwork');
196
+ const provider = yield WalletConnectProvider.awaitAndGetProvider();
197
+ if (provider === null || provider === void 0 ? void 0 : provider.chainId) {
198
+ const network = provider.chainId;
199
+ this.currentChainId = network;
200
+ logger.logVerboseTroubleshootingMessage('[WalletConnect] getNetwork - provider network', network);
201
+ return network;
202
+ }
203
+ logger.logVerboseTroubleshootingMessage('[WalletConnect] getNetwork - no provider found, returning current chain id', {
204
+ currentChainId: this.currentChainId,
205
+ });
206
+ return this.currentChainId;
207
+ });
208
+ }
209
+ providerSwitchNetwork(_a) {
210
+ const _super = Object.create(null, {
211
+ providerSwitchNetwork: { get: () => super.providerSwitchNetwork }
212
+ });
213
+ return __awaiter(this, arguments, void 0, function* ({ network, }) {
214
+ logger.logVerboseTroubleshootingMessage('[WalletConnect] providerSwitchNetwork - network', {
215
+ network,
216
+ switchNetworkOnlyFromWallet: this.switchNetworkOnlyFromWallet,
217
+ });
218
+ const currentNetworkId = yield this.getNetwork();
219
+ logger.logVerboseTroubleshootingMessage('[WalletConnect] providerSwitchNetwork - currentNetworkId', currentNetworkId);
220
+ if (currentNetworkId && currentNetworkId === network.chainId) {
221
+ return;
222
+ }
223
+ if (this.switchNetworkOnlyFromWallet) {
224
+ throw new DynamicError('Network switching is only supported through the wallet');
225
+ }
226
+ const walletClient = yield this.getWalletClient();
227
+ logger.logVerboseTroubleshootingMessage('[WalletConnect] providerSwitchNetwork - will switch network');
228
+ yield _super.providerSwitchNetwork.call(this, { network, provider: walletClient });
229
+ this.currentChainId = network.chainId;
230
+ logger.logVerboseTroubleshootingMessage('[WalletConnect] providerSwitchNetwork - switched network', network.chainId);
231
+ this.emit('chainChange', { chain: String(network.chainId) });
232
+ });
233
+ }
234
+ supportsNetworkSwitching() {
235
+ return true;
236
+ }
237
+ getSupportedNetworks() {
238
+ return __awaiter(this, void 0, void 0, function* () {
239
+ var _a;
240
+ const provider = yield WalletConnectProvider.awaitAndGetProvider();
241
+ if (!(provider === null || provider === void 0 ? void 0 : provider.session)) {
242
+ return [];
243
+ }
244
+ const chains = [];
245
+ // Some wallet (i.e ZenGo) use namespaces.account to list supported chains
246
+ // while others use keys within the namespaces object
247
+ Object.keys(provider === null || provider === void 0 ? void 0 : provider.session.namespaces).forEach((key) => {
248
+ if (key.startsWith('eip155:')) {
249
+ chains.push(key.split(':')[1]);
250
+ }
251
+ });
252
+ (_a = provider === null || provider === void 0 ? void 0 : provider.session.namespaces.eip155) === null || _a === void 0 ? void 0 : _a.accounts.forEach((account) => chains.push(account.split(':')[1]));
253
+ return chains.length
254
+ ? chains
255
+ : this.evmNetworks.map((network) => network.chainId.toString());
256
+ });
257
+ }
258
+ getDeepLink() {
259
+ var _a;
260
+ const provider = WalletConnectProvider.getProvider();
261
+ logger.debug('[WalletConnect] getDeepLink', {
262
+ hasSession: Boolean(provider === null || provider === void 0 ? void 0 : provider.session),
263
+ topic: (_a = provider === null || provider === void 0 ? void 0 : provider.session) === null || _a === void 0 ? void 0 : _a.topic,
264
+ uri: provider === null || provider === void 0 ? void 0 : provider.signer.uri,
265
+ });
266
+ if (!(provider === null || provider === void 0 ? void 0 : provider.session)) {
267
+ return;
268
+ }
269
+ const deepLink = getDeepLink({
270
+ deepLinks: this.metadata.deepLinks,
271
+ mode: 'regular',
272
+ preference: this.deepLinkPreference,
273
+ uri: provider.signer.uri,
274
+ });
275
+ logger.logVerboseTroubleshootingMessage('[WalletConnect] getDeepLink - deepLink', deepLink);
276
+ if (!deepLink) {
277
+ return;
278
+ }
279
+ // we need to include the session topic here because it helps the wallet
280
+ // auto redirect back to the dapp after signing
281
+ return `${deepLink}?sessionTopic=${provider.session.topic}`;
282
+ }
283
+ getConnectionUri() {
284
+ return WalletConnectProvider.getConnectionUri();
285
+ }
286
+ }
287
+
288
+ export { WalletConnectConnector };
@@ -0,0 +1 @@
1
+ export { WalletConnectConnector } from './WalletConnectConnector';
@@ -0,0 +1,212 @@
1
+ 'use client'
2
+ 'use strict';
3
+
4
+ Object.defineProperty(exports, '__esModule', { value: true });
5
+
6
+ var _tslib = require('../../../_virtual/_tslib.cjs');
7
+ var EthereumProvider = require('@walletconnect/ethereum-provider');
8
+ var walletConnectorCore = require('@dynamic-labs/wallet-connector-core');
9
+ var utils = require('@dynamic-labs/utils');
10
+ var logger = require('../../utils/logger.cjs');
11
+
12
+ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
13
+
14
+ var EthereumProvider__default = /*#__PURE__*/_interopDefaultLegacy(EthereumProvider);
15
+
16
+ var _a;
17
+ class WalletConnectProvider {
18
+ constructor() {
19
+ throw new Error('WalletConnectProvider is not instantiable');
20
+ }
21
+ static getMappedChainsByPreferredOrder() {
22
+ const allChains = _a.enabledNetworks.map((network) => `eip155:${network.chainId}`);
23
+ const reorderedChains = _a.preferredChains.filter((chain) => allChains.includes(chain));
24
+ const remainingChains = allChains.filter((chain) => !_a.preferredChains.includes(chain));
25
+ return [...reorderedChains, ...remainingChains].map((chain) => Number(chain.split(':')[1]));
26
+ }
27
+ }
28
+ _a = WalletConnectProvider;
29
+ WalletConnectProvider.isInitializing = false;
30
+ WalletConnectProvider.isInitialized = false;
31
+ WalletConnectProvider.enabledNetworks = [];
32
+ WalletConnectProvider.preferredChains = [];
33
+ WalletConnectProvider.evmNetworkRpcMap = {};
34
+ WalletConnectProvider.eventListenersSetup = false;
35
+ WalletConnectProvider.accountChangedHandler = () => { };
36
+ WalletConnectProvider.chainChangedHandler = () => { };
37
+ WalletConnectProvider.disconnectHandler = () => { };
38
+ /**
39
+ * Initializes the provider. This method should only be called once.
40
+ * Does not start a connection.
41
+ */
42
+ WalletConnectProvider.init = (...args_1) => _tslib.__awaiter(void 0, [...args_1], void 0, function* ({ storePrefix = 'dynamic-wc2', } = {}) {
43
+ logger.logger.debug('[WalletConnectProvider] init', {
44
+ isInitialized: _a.isInitialized,
45
+ isInitializing: _a.isInitializing,
46
+ });
47
+ if (_a.isInitializing ||
48
+ _a.isInitialized) {
49
+ return;
50
+ }
51
+ _a.isInitializing = true;
52
+ logger.logger.debug('[WalletConnectProvider] initializing');
53
+ _a.providerInitPromise = EthereumProvider__default["default"].init({
54
+ customStoragePrefix: storePrefix,
55
+ disableProviderPing: true,
56
+ optionalChains: _a.getMappedChainsByPreferredOrder(),
57
+ optionalEvents: ['chainChanged', 'accountsChanged'],
58
+ optionalMethods: [
59
+ 'eth_chainId',
60
+ 'eth_signTypedData',
61
+ 'eth_signTransaction',
62
+ 'eth_sign',
63
+ 'personal_sign',
64
+ 'eth_sendTransaction',
65
+ 'eth_signTypedData_v4',
66
+ 'wallet_switchEthereumChain',
67
+ 'wallet_addEthereumChain',
68
+ ],
69
+ projectId: _a.projectId,
70
+ rpcMap: _a.evmNetworkRpcMap,
71
+ showQrModal: false,
72
+ });
73
+ _a.provider =
74
+ yield _a.providerInitPromise;
75
+ _a.isInitialized = true;
76
+ _a.isInitializing = false;
77
+ logger.logger.debug('[WalletConnectProvider] initialized');
78
+ });
79
+ /**
80
+ * Connects to a wallet. This method should be called whenever a new wallet connection is needed.
81
+ * If the wallet is already connected when the page is refreshed, this method does not need to be called.
82
+ */
83
+ WalletConnectProvider.connect = (_b) => _tslib.__awaiter(void 0, [_b], void 0, function* ({ deepLinks, deepLinkPreference, connectionOpts, }) {
84
+ const handleDisplayURI = (uri) => {
85
+ var _b;
86
+ logger.logger.debug('[WalletConnectProvider] handleDisplayURI', uri);
87
+ _a.connectionUri = uri;
88
+ walletConnectorCore.performPlatformSpecificConnectionMethod(_a.connectionUri, deepLinks, {
89
+ onDesktopUri: connectionOpts === null || connectionOpts === void 0 ? void 0 : connectionOpts.onDesktopUri,
90
+ onDisplayUri: connectionOpts === null || connectionOpts === void 0 ? void 0 : connectionOpts.onDisplayUri,
91
+ }, deepLinkPreference);
92
+ logger.logger.debug('[WalletConnectProvider] removing display_uri event listener');
93
+ (_b = _a.provider) === null || _b === void 0 ? void 0 : _b.off('display_uri', handleDisplayURI);
94
+ };
95
+ if (!_a.provider) {
96
+ logger.logger.error('[WalletConnectProvider] connect - provider is not initialized');
97
+ throw new utils.DynamicError('WalletConnectProvider is not initialized');
98
+ }
99
+ // this is in case the user just cancels the deeplink prompt (i.e. in mobile/Safari)
100
+ // in this case, the connection is not rejected, so the "enable" promise is just pending
101
+ // so on retry, we should just use the same uri to handle that promise
102
+ if (_a.connectionUri) {
103
+ handleDisplayURI(_a.connectionUri);
104
+ return;
105
+ }
106
+ logger.logger.debug('[WalletConnectProvider] adding display_uri event listener');
107
+ _a.provider.on('display_uri', handleDisplayURI);
108
+ try {
109
+ // enable = connect to the provider
110
+ const result = yield _a.provider.enable();
111
+ logger.logger.debug('[WalletConnectProvider] connected to WalletConnect', result);
112
+ return result;
113
+ }
114
+ catch (error) {
115
+ logger.logger.error('[WalletConnectProvider] Failed to connect to WalletConnect', error);
116
+ const customError = new utils.DynamicError('Connection rejected. Please try again.');
117
+ customError.code = 'connection_rejected';
118
+ throw customError;
119
+ }
120
+ finally {
121
+ // Reset the connection URI after it's been consumed
122
+ _a.connectionUri = undefined;
123
+ }
124
+ });
125
+ /**
126
+ * Disconnects from a wallet. This method should be called whenever we need to disconnect from a wallet.
127
+ * It will kill the connection, but not the provider.
128
+ */
129
+ WalletConnectProvider.disconnect = () => _tslib.__awaiter(void 0, void 0, void 0, function* () {
130
+ if (!_a.provider) {
131
+ logger.logger.debug('[WalletConnectProvider] disconnect - provider is not initialized');
132
+ return;
133
+ }
134
+ _a.connectionUri = undefined;
135
+ logger.logger.debug('[WalletConnectProvider] disconnecting from WalletConnect');
136
+ try {
137
+ yield _a.provider.disconnect();
138
+ }
139
+ catch (error) {
140
+ logger.logger.error('[WalletConnectProvider] Failed to disconnect from WalletConnect', error);
141
+ }
142
+ });
143
+ /**
144
+ * Waits for the provider to be initialized and returns the EthereumProvider instance.
145
+ * We should use this wherever possible (async methods), to ensure the provider is initialized.
146
+ */
147
+ WalletConnectProvider.awaitAndGetProvider = () => _tslib.__awaiter(void 0, void 0, void 0, function* () { return _a.providerInitPromise; });
148
+ /**
149
+ * Returns the EthereumProvider instance.
150
+ * Used when we need to access the provider synchronously.
151
+ */
152
+ WalletConnectProvider.getProvider = () => _a.provider;
153
+ WalletConnectProvider.getConnectionUri = () => _a.connectionUri;
154
+ WalletConnectProvider.handleChainChangedEvent = (chain, onChainChanged) => {
155
+ logger.logger.debug('[WalletConnectProvider] handling chain change event', {
156
+ chain,
157
+ });
158
+ const chainId = utils.parseIntSafe(chain);
159
+ if (!chainId) {
160
+ return;
161
+ }
162
+ onChainChanged === null || onChainChanged === void 0 ? void 0 : onChainChanged(chainId);
163
+ };
164
+ WalletConnectProvider.handleAccountChangedEvent = (accounts, onAccountChanged) => {
165
+ logger.logger.debug('[WalletConnectProvider] handling account change event', {
166
+ accounts,
167
+ });
168
+ const [account] = accounts;
169
+ const address = account.includes(':') ? account.split(':').pop() : account;
170
+ if (!address) {
171
+ return;
172
+ }
173
+ onAccountChanged === null || onAccountChanged === void 0 ? void 0 : onAccountChanged(address);
174
+ };
175
+ /**
176
+ * Sets up event listeners for the provider.
177
+ */
178
+ WalletConnectProvider.setupEventListeners = ({ onChainChanged, onAccountChanged, onDisconnect, }) => {
179
+ if (!_a.provider ||
180
+ _a.eventListenersSetup) {
181
+ return;
182
+ }
183
+ _a.chainChangedHandler = (chainId) => {
184
+ _a.handleChainChangedEvent(chainId, onChainChanged);
185
+ };
186
+ _a.accountChangedHandler = (account) => {
187
+ _a.handleAccountChangedEvent(account, onAccountChanged);
188
+ };
189
+ _a.disconnectHandler = () => {
190
+ logger.logger.debug('[WalletConnectProvider] handling disconnect event');
191
+ onDisconnect === null || onDisconnect === void 0 ? void 0 : onDisconnect();
192
+ };
193
+ _a.provider.on('accountsChanged', _a.accountChangedHandler);
194
+ _a.provider.on('chainChanged', _a.chainChangedHandler);
195
+ _a.provider.on('disconnect', _a.disconnectHandler);
196
+ _a.eventListenersSetup = true;
197
+ };
198
+ /**
199
+ * Tears down event listeners for the provider.
200
+ */
201
+ WalletConnectProvider.teardownEventListeners = () => {
202
+ if (!_a.provider ||
203
+ !_a.eventListenersSetup) {
204
+ return;
205
+ }
206
+ _a.provider.off('accountsChanged', _a.accountChangedHandler);
207
+ _a.provider.off('chainChanged', _a.chainChangedHandler);
208
+ _a.provider.off('disconnect', _a.disconnectHandler);
209
+ _a.eventListenersSetup = false;
210
+ };
211
+
212
+ exports.WalletConnectProvider = WalletConnectProvider;
@@ -6,16 +6,18 @@ type ProviderInitOpts = {
6
6
  storePrefix?: string;
7
7
  };
8
8
  export declare class WalletConnectProvider {
9
+ static isInitializing: boolean;
9
10
  static isInitialized: boolean;
10
11
  static projectId: string;
11
12
  static enabledNetworks: GenericNetwork[];
12
13
  static preferredChains: `eip155:${number}`[];
13
14
  static evmNetworkRpcMap: Record<string, string>;
15
+ private static providerInitPromise;
14
16
  private static provider;
15
17
  /**
16
18
  * The connection URI for the current connection.
17
19
  */
18
- static connectionUri: string | undefined;
20
+ private static connectionUri;
19
21
  private static eventListenersSetup;
20
22
  private static accountChangedHandler;
21
23
  private static chainChangedHandler;
@@ -40,10 +42,17 @@ export declare class WalletConnectProvider {
40
42
  * It will kill the connection, but not the provider.
41
43
  */
42
44
  static disconnect: () => Promise<void>;
45
+ /**
46
+ * Waits for the provider to be initialized and returns the EthereumProvider instance.
47
+ * We should use this wherever possible (async methods), to ensure the provider is initialized.
48
+ */
49
+ static awaitAndGetProvider: () => Promise<EthereumProvider | undefined>;
43
50
  /**
44
51
  * Returns the EthereumProvider instance.
52
+ * Used when we need to access the provider synchronously.
45
53
  */
46
54
  static getProvider: () => EthereumProvider | undefined;
55
+ static getConnectionUri: () => string | undefined;
47
56
  private static handleChainChangedEvent;
48
57
  private static handleAccountChangedEvent;
49
58
  /**