@dynamic-labs/ethereum 2.0.0-alpha.3 → 2.0.0-alpha.31

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 (53) hide show
  1. package/CHANGELOG.md +407 -0
  2. package/package.json +11 -12
  3. package/src/EthWalletConnector.cjs +13 -21
  4. package/src/EthWalletConnector.d.ts +16 -14
  5. package/src/EthWalletConnector.js +15 -23
  6. package/src/coinbase/client/client.cjs +14 -14
  7. package/src/coinbase/client/client.d.ts +5 -4
  8. package/src/coinbase/client/client.js +13 -13
  9. package/src/coinbase/client/types.d.ts +6 -3
  10. package/src/coinbase/coinbase.cjs +31 -15
  11. package/src/coinbase/coinbase.d.ts +20 -18
  12. package/src/coinbase/coinbase.js +32 -16
  13. package/src/ethProviderHelper.cjs +11 -6
  14. package/src/ethProviderHelper.d.ts +6 -4
  15. package/src/ethProviderHelper.js +11 -6
  16. package/src/index.cjs +9 -13
  17. package/src/index.d.ts +2 -0
  18. package/src/index.js +8 -13
  19. package/src/injected/ExodusEvm.cjs +1 -0
  20. package/src/injected/ExodusEvm.d.ts +1 -0
  21. package/src/injected/ExodusEvm.js +1 -0
  22. package/src/injected/InjectedWalletBase.cjs +28 -19
  23. package/src/injected/InjectedWalletBase.d.ts +2 -2
  24. package/src/injected/InjectedWalletBase.js +28 -19
  25. package/src/injected/PhantomEvm.cjs +4 -3
  26. package/src/injected/PhantomEvm.d.ts +2 -1
  27. package/src/injected/PhantomEvm.js +4 -3
  28. package/src/injected/Zerion.cjs +38 -0
  29. package/src/injected/Zerion.d.ts +10 -0
  30. package/src/injected/Zerion.js +34 -0
  31. package/src/injected/fetchInjectedWalletConnectors.cjs +25 -0
  32. package/src/injected/fetchInjectedWalletConnectors.d.ts +0 -1
  33. package/src/injected/fetchInjectedWalletConnectors.js +25 -0
  34. package/src/utils/index.d.ts +1 -0
  35. package/src/utils/isEthWalletConnector/index.d.ts +1 -0
  36. package/src/utils/isEthWalletConnector/isEthWalletConnector.cjs +7 -0
  37. package/src/utils/isEthWalletConnector/isEthWalletConnector.d.ts +3 -0
  38. package/src/utils/isEthWalletConnector/isEthWalletConnector.js +3 -0
  39. package/src/walletConnect/fetchWalletConnectWallets.cjs +14 -33
  40. package/src/walletConnect/fetchWalletConnectWallets.d.ts +2 -5
  41. package/src/walletConnect/fetchWalletConnectWallets.js +14 -33
  42. package/src/walletConnect/index.d.ts +0 -1
  43. package/src/walletConnect/walletConnect.cjs +452 -78
  44. package/src/walletConnect/walletConnect.d.ts +313 -31
  45. package/src/walletConnect/walletConnect.js +453 -80
  46. package/src/walletConnect/client/client.cjs +0 -201
  47. package/src/walletConnect/client/client.d.ts +0 -17
  48. package/src/walletConnect/client/client.js +0 -187
  49. package/src/walletConnect/client/index.d.ts +0 -1
  50. package/src/walletConnect/client/types.d.ts +0 -4
  51. package/src/walletConnect/walletConnectV2.cjs +0 -475
  52. package/src/walletConnect/walletConnectV2.d.ts +0 -333
  53. package/src/walletConnect/walletConnectV2.js +0 -466
@@ -3,152 +3,526 @@
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
5
  var _tslib = require('../../_virtual/_tslib.cjs');
6
- var WalletConnectProvider = require('@walletconnect/ethereum-provider');
6
+ var EthereumProvider = require('@walletconnect/ethereum-provider');
7
+ var EventEmitter = require('eventemitter3');
7
8
  var viem = require('viem');
8
9
  var walletConnectorCore = require('@dynamic-labs/wallet-connector-core');
9
10
  var walletBook = require('@dynamic-labs/wallet-book');
10
11
  var utils = require('@dynamic-labs/utils');
12
+ var viemUtils = require('@dynamic-labs/viem-utils');
11
13
  var EthWalletConnector = require('../EthWalletConnector.cjs');
12
- var constants = require('../constants.cjs');
13
- var client = require('./client/client.cjs');
14
+ var parseIntSafe = require('../utils/parseIntSafe.cjs');
14
15
 
15
16
  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
16
17
 
17
- var WalletConnectProvider__default = /*#__PURE__*/_interopDefaultLegacy(WalletConnectProvider);
18
+ var EthereumProvider__default = /*#__PURE__*/_interopDefaultLegacy(EthereumProvider);
19
+ var EventEmitter__default = /*#__PURE__*/_interopDefaultLegacy(EventEmitter);
18
20
 
21
+ const activeAccountKey = (walletName) => `dynamic-wc2-active-account-${walletName}`;
22
+ const sessionTopicKey = (walletName) => `dynamic-wc2-session-topic-${walletName}`;
23
+ const swicthedNetworkKey = (walletName) => `dynamic-wc2-switched-network-${walletName}`;
24
+ const currentChainKey = (walletName) => `dynamic-wc2-current-chain-${walletName}`;
25
+ const ee = new EventEmitter__default["default"]();
19
26
  class WalletConnect extends EthWalletConnector.EthWalletConnector {
20
- constructor(_a) {
21
- var { walletConnectV1Bridge, walletName } = _a, props = _tslib.__rest(_a, ["walletConnectV1Bridge", "walletName"]);
22
- super(props);
27
+ constructor(opts) {
28
+ var _a;
29
+ super(opts);
23
30
  this.supportedChains = ['EVM', 'ETH'];
24
31
  this.connectedChain = 'EVM';
25
- this.bridge = 'https://bridge.walletconnect.org';
32
+ this.isInitialized = false;
26
33
  this.canConnectViaQrCode = true;
27
34
  this.isWalletConnect = true;
28
- this.switchNetworkOnlyFromWallet = false;
29
- this.name = walletName;
30
- if (walletConnectV1Bridge) {
31
- this.bridge = walletConnectV1Bridge;
35
+ this.preferredChains = [];
36
+ // When trying to switch network for MetaMask, the switch promise gets stuck
37
+ // if the switch got trigged once already, so we need to keep track of that
38
+ this._hasSwitchedNetwork = false;
39
+ this.sessionEventHandler = () => { };
40
+ this.sessionDeleteHandler = () => { };
41
+ this.name = opts.walletName;
42
+ this.projectId = opts.projectId;
43
+ this.deepLinkPreference = opts.deepLinkPreference || 'native';
44
+ this.preferredChains = opts.walletConnectPreferredChains || [];
45
+ this.hasSwitchedNetwork =
46
+ (_a = Boolean(localStorage.getItem(this.swicthedNetworkKey))) !== null && _a !== void 0 ? _a : false;
47
+ const lsCurrentChain = localStorage.getItem(this.currentChainKey);
48
+ this.currentChainId = lsCurrentChain
49
+ ? parseIntSafe.parseIntSafe(lsCurrentChain)
50
+ : undefined;
51
+ }
52
+ getMappedChains() {
53
+ return (this.evmNetworks
54
+ // Filters out palm that crashes Trust Wallet
55
+ .filter((network) => network.chainId !== 11297108109)
56
+ .map((network) => `eip155:${network.chainId}`));
57
+ }
58
+ getMappedChainsByPreferredOrder() {
59
+ const allChains = this.getMappedChains();
60
+ const reorderedChains = this.preferredChains.filter((chain) => allChains.includes(chain));
61
+ const remainingChains = allChains.filter((chain) => !this.preferredChains.includes(chain));
62
+ return [...reorderedChains, ...remainingChains].map((chain) => Number(chain.split(':')[1]));
63
+ }
64
+ initConnection() {
65
+ return _tslib.__awaiter(this, void 0, void 0, function* () {
66
+ const { provider } = WalletConnect;
67
+ if (!provider) {
68
+ throw new utils.DynamicError('No provider found (init connection)');
69
+ }
70
+ // this means there is already a connection in progress, so don't call connect again
71
+ if (provider === null || provider === void 0 ? void 0 : provider.signer.uri) {
72
+ return;
73
+ }
74
+ provider.connect().catch((e) => {
75
+ walletConnectorCore.logger.error(e);
76
+ ee.emit('walletconnect_connection_failed', e);
77
+ });
78
+ });
79
+ }
80
+ createProvider() {
81
+ return _tslib.__awaiter(this, void 0, void 0, function* () {
82
+ return EthereumProvider__default["default"].init({
83
+ events: ['chainChanged', 'accountsChanged'],
84
+ methods: [],
85
+ optionalChains: this.getMappedChainsByPreferredOrder(),
86
+ optionalMethods: [
87
+ 'eth_chainId',
88
+ 'eth_signTypedData',
89
+ 'eth_signTransaction',
90
+ 'eth_sign',
91
+ 'personal_sign',
92
+ 'eth_sendTransaction',
93
+ 'eth_signTypedData_v4',
94
+ 'wallet_switchEthereumChain',
95
+ 'wallet_addEthereumChain',
96
+ ],
97
+ projectId: this.projectId,
98
+ rpcMap: this.evmNetworkRpcMap(),
99
+ showQrModal: false,
100
+ });
101
+ });
102
+ }
103
+ getWalletClientFromInitializedProvider() {
104
+ return _tslib.__awaiter(this, void 0, void 0, function* () {
105
+ const walletConnect = this.createProvider();
106
+ const walletClient = viem.createWalletClient({
107
+ account: this.getActiveAccount(),
108
+ transport: viem.custom(yield walletConnect),
109
+ });
110
+ return walletClient;
111
+ });
112
+ }
113
+ createInitProviderPromise() {
114
+ return _tslib.__awaiter(this, void 0, void 0, function* () {
115
+ WalletConnect.provider = yield this.createProvider();
116
+ this.teardownEventListeners();
117
+ this.setupEventListeners();
118
+ });
119
+ }
120
+ // We need to add a gate to this method since we will be calling it asynchronously
121
+ // from different places (such as setShowAuthFlow), which means there's a chance for
122
+ // a race condition to happen where createInitProviderPromise is called multiple times
123
+ initProvider() {
124
+ return _tslib.__awaiter(this, void 0, void 0, function* () {
125
+ const { provider } = WalletConnect;
126
+ if (!provider) {
127
+ if (this.initializePromise === undefined) {
128
+ this.initializePromise = this.createInitProviderPromise();
129
+ }
130
+ yield this.initializePromise;
131
+ }
132
+ });
133
+ }
134
+ refreshSession() {
135
+ var _a, _b, _c, _d, _e;
136
+ if ((_b = (_a = WalletConnect.provider) === null || _a === void 0 ? void 0 : _a.session) === null || _b === void 0 ? void 0 : _b.topic) {
137
+ if (localStorage.getItem(this.sessionTopicKey) ===
138
+ ((_d = (_c = WalletConnect.provider) === null || _c === void 0 ? void 0 : _c.session) === null || _d === void 0 ? void 0 : _d.topic)) {
139
+ this.session = WalletConnect.provider.session;
140
+ this.setActiveAccount(((_e = localStorage.getItem(this.activeAccountKey)) !== null && _e !== void 0 ? _e : undefined));
141
+ }
32
142
  }
33
- this.deepLinkPreference = props.deepLinkPreference || 'native';
34
143
  }
35
- getClient() {
36
- if (this.client) {
37
- return this.client;
144
+ init() {
145
+ return _tslib.__awaiter(this, void 0, void 0, function* () {
146
+ yield this.initProvider();
147
+ yield this.initConnection();
148
+ this.isInitialized = true;
149
+ });
150
+ }
151
+ get sessionTopicKey() {
152
+ return sessionTopicKey(this.key);
153
+ }
154
+ get activeAccountKey() {
155
+ return activeAccountKey(this.key);
156
+ }
157
+ get swicthedNetworkKey() {
158
+ return swicthedNetworkKey(this.key);
159
+ }
160
+ get currentChainKey() {
161
+ return currentChainKey(this.key);
162
+ }
163
+ set currentChainId(value) {
164
+ this._currentChainId = value;
165
+ if (value) {
166
+ localStorage.setItem(this.currentChainKey, value.toString());
167
+ }
168
+ else {
169
+ localStorage.removeItem(this.currentChainKey);
38
170
  }
39
- this.client = client.initClient(this.key, this.bridge, this.clientOptions);
40
- return this.client;
41
171
  }
42
- supportsNetworkSwitching() {
43
- if (this.connectedChain === 'EVM') {
44
- return true;
172
+ get currentChainId() {
173
+ return this._currentChainId;
174
+ }
175
+ set hasSwitchedNetwork(value) {
176
+ this._hasSwitchedNetwork = value;
177
+ if (value) {
178
+ localStorage.setItem(this.swicthedNetworkKey, value.toString());
45
179
  }
46
180
  else {
47
- const client = this.getClient();
48
- return Boolean(client === null || client === void 0 ? void 0 : client.chainId);
181
+ localStorage.removeItem(this.swicthedNetworkKey);
49
182
  }
50
183
  }
184
+ get hasSwitchedNetwork() {
185
+ return this._hasSwitchedNetwork;
186
+ }
187
+ supportsNetworkSwitching() {
188
+ return true;
189
+ }
51
190
  setupEventListeners() {
52
- client.setupWalletConnectEventListeners(this, this.getClient());
191
+ if (!WalletConnect.provider) {
192
+ return;
193
+ }
194
+ this.sessionEventHandler = ({ params, }) => {
195
+ walletConnectorCore.logger.debug('session_event was called', { params });
196
+ if (!params || !params.event) {
197
+ walletConnectorCore.logger.debug('session_event was called without params or params.event');
198
+ return;
199
+ }
200
+ const { name, data } = params.event;
201
+ if (name === 'chainChanged') {
202
+ const chainId = parseIntSafe.parseIntSafe(data);
203
+ if (chainId === this.currentChainId) {
204
+ walletConnectorCore.logger.debug(`ignoring chainChanged event with same chain id as current chain id: ${chainId}`);
205
+ return;
206
+ }
207
+ if (chainId === undefined) {
208
+ walletConnectorCore.logger.debug(`received unexpected data for chainChanged: ${data} with type ${typeof data}}`);
209
+ return;
210
+ }
211
+ this.currentChainId = chainId;
212
+ this.emit('chainChange', { chain: String(chainId) });
213
+ this.hasSwitchedNetwork = true;
214
+ // When a user switches network from their wallet, we need the provider to change network
215
+ // such that any future calls to `getNetwork` will return the correct network
216
+ this.switchNetwork({ networkChainId: chainId });
217
+ }
218
+ else if (name === 'accountsChanged') {
219
+ if (!Array.isArray(data)) {
220
+ walletConnectorCore.logger.debug(`received unexpected data for accountsChanged: ${data} with type ${typeof data}}`);
221
+ return;
222
+ }
223
+ // eslint-disable-next-line prefer-destructuring
224
+ const account = data[0].split(':')[2];
225
+ this.setWCActiveAccount(account);
226
+ }
227
+ };
228
+ WalletConnect.provider.on('session_event', this.sessionEventHandler);
229
+ this.sessionDeleteHandler = () => _tslib.__awaiter(this, void 0, void 0, function* () {
230
+ this.endSession();
231
+ this.emit('disconnect');
232
+ });
233
+ WalletConnect.provider.on('session_delete', this.sessionDeleteHandler);
53
234
  }
54
235
  teardownEventListeners() {
55
- client.teardownWalletConnectEventListeners(this.getClient());
56
- }
57
- getWalletClient() {
58
- const client = this.getClient();
59
- return client
60
- ? viem.createWalletClient({
61
- transport: viem.custom(new WalletConnectProvider__default["default"]({
62
- connector: client,
63
- infuraId: constants.INFURA_ID,
64
- rpc: this.evmNetworkRpcMap(),
65
- })),
66
- })
67
- : undefined;
236
+ if (!WalletConnect.provider) {
237
+ return;
238
+ }
239
+ WalletConnect.provider.off('session_event', this.sessionEventHandler);
240
+ WalletConnect.provider.off('session_delete', this.sessionDeleteHandler);
241
+ }
242
+ getWalletClient(chainId) {
243
+ if (!WalletConnect.provider) {
244
+ return;
245
+ }
246
+ return viem.createWalletClient({
247
+ account: this.getActiveAccount(),
248
+ chain: viemUtils.chainsMap[chainId !== null && chainId !== void 0 ? chainId : String(this.currentChainId)],
249
+ transport: viem.custom(WalletConnect.provider),
250
+ });
68
251
  }
69
- fetchPublicAddress(opts) {
252
+ getAddress(opts) {
253
+ var _a, _b;
70
254
  return _tslib.__awaiter(this, void 0, void 0, function* () {
71
- return client.fetchWalletConnectEVMPublicAddress(walletBook.getWalletBookWallet(this.walletBook, this.key), this.getClient(), this.deepLinkPreference, Object.assign(Object.assign({}, opts), { onConnect: (payload) => {
72
- var _a, _b;
73
- (_a = opts === null || opts === void 0 ? void 0 : opts.onConnect) === null || _a === void 0 ? void 0 : _a.call(opts, payload);
74
- this.connectedChain = payload.params[0].chainId ? 'EVM' : 'SOL';
75
- if ((_b = payload.params[0].accounts) === null || _b === void 0 ? void 0 : _b.length) {
76
- this.emit('accountChange', {
77
- accounts: payload.params[0].accounts,
78
- });
255
+ const activeAccount = this.getActiveAccount();
256
+ if (activeAccount === null || activeAccount === void 0 ? void 0 : activeAccount.address) {
257
+ return activeAccount.address;
258
+ }
259
+ if (!WalletConnect.provider || !((_a = WalletConnect.provider) === null || _a === void 0 ? void 0 : _a.signer.uri)) {
260
+ walletConnectorCore.logger.debug('No WC2 provider found, re-initializing...');
261
+ yield this.endSession();
262
+ yield this.init();
263
+ // sleep 1 s to wait for connect call to finish
264
+ // the connect call isn't await-ed because it only resolves once
265
+ // the connection is established, but we need to wait for it to
266
+ // finish setting up the connection URI and making it available
267
+ // on the provider
268
+ yield utils.sleep(1000);
269
+ if (!WalletConnect.provider || !((_b = WalletConnect.provider) === null || _b === void 0 ? void 0 : _b.signer.uri)) {
270
+ walletConnectorCore.logger.debug('No WC2 provider found, escaping and throwing error');
271
+ throw new utils.DynamicError('No provider found');
272
+ }
273
+ }
274
+ const metadata = walletBook.getWalletBookWallet(this.walletBook, this.key, this.walletFallback);
275
+ walletConnectorCore.performPlatformSpecificConnectionMethod(WalletConnect.provider.signer.uri, metadata, {
276
+ onDesktopUri: opts === null || opts === void 0 ? void 0 : opts.onDesktopUri,
277
+ onDisplayUri: opts === null || opts === void 0 ? void 0 : opts.onDisplayUri,
278
+ }, this.deepLinkPreference);
279
+ return new Promise((resolve, reject) => {
280
+ if (!WalletConnect.provider) {
281
+ reject(new utils.DynamicError('No provider found'));
282
+ return;
283
+ }
284
+ const onFail = () => {
285
+ const error = new utils.DynamicError('Connection rejected. Please try again.');
286
+ error.code = 'connection_rejected';
287
+ if (WalletConnect.provider) {
288
+ WalletConnect.provider.signer.uri = undefined;
289
+ // this is needed for mobile to work when using universal links.
290
+ // if the user cancels the connection, we need to re-initialize the provider
291
+ // so that the async work is done ahead of time, before the user tries to connect again,
292
+ // otherwise they will trigger the iOS bug where they are redirected to the app store
293
+ this.init();
294
+ }
295
+ reject(error);
296
+ // We must clean up the onConnect and onFail listeners
297
+ // whenever the connection attempt either succeeds or fails
298
+ cleanupListeners();
299
+ };
300
+ const onConnect = () => {
301
+ var _a;
302
+ const session = (_a = WalletConnect.provider) === null || _a === void 0 ? void 0 : _a.session;
303
+ if (!session) {
304
+ reject(new utils.DynamicError('No session found'));
305
+ return;
79
306
  }
80
- } }));
307
+ this.setSession(session);
308
+ this.setWCActiveAccount(session.namespaces.eip155.accounts[0].split(':')[2]);
309
+ this.getNetwork().then((chainId) => {
310
+ var _a;
311
+ this.currentChainId = chainId;
312
+ resolve((_a = this.getActiveAccount()) === null || _a === void 0 ? void 0 : _a.address);
313
+ });
314
+ // We must clean up the onConnect and onFail listeners
315
+ // whenever the connection attempt either succeeds or fails
316
+ cleanupListeners();
317
+ };
318
+ const cleanupListeners = () => {
319
+ var _a;
320
+ ee.off('walletconnect_connection_failed', onFail);
321
+ (_a = WalletConnect.provider) === null || _a === void 0 ? void 0 : _a.off('connect', onConnect);
322
+ };
323
+ ee.on('walletconnect_connection_failed', onFail);
324
+ WalletConnect.provider.on('connect', onConnect);
325
+ });
326
+ });
327
+ }
328
+ /**
329
+ * WalletConnect V2 will fail to send the sign message request if the chainId
330
+ * is not the same as the one in the session. This method will wait for the
331
+ * chainId to change and then retry the sign message request.
332
+ *
333
+ * Otherwise it will just return the result of the sign message request.
334
+ *
335
+ * @param signMessageFn - Function to sign message with provider
336
+ * @param messageToSign - Message to sign
337
+ * @returns
338
+ */
339
+ waitForSignMessage(signMessageFn, messageToSign) {
340
+ return _tslib.__awaiter(this, void 0, void 0, function* () {
341
+ const raceConditionPromise = new Promise((resolve, reject) => {
342
+ // Create listener for chain change event
343
+ this.on('chainChange', () => resolve({ success: false }));
344
+ signMessageFn(messageToSign)
345
+ .then((result) => resolve({ signedMessage: result, success: true }))
346
+ .catch(reject);
347
+ });
348
+ const signedMessageResult = yield raceConditionPromise;
349
+ if (signedMessageResult.success === false) {
350
+ return signMessageFn(messageToSign);
351
+ }
352
+ return signedMessageResult.signedMessage;
81
353
  });
82
354
  }
83
355
  getDeepLink() {
84
356
  var _a;
85
- const wallet = walletBook.getWalletBookWallet(this.walletBook, this.key);
86
- if (!utils.isMobile() && !((_a = wallet.desktop) === null || _a === void 0 ? void 0 : _a.native)) {
87
- return undefined;
357
+ if (!this.session) {
358
+ return;
88
359
  }
89
- return walletConnectorCore.getDeepLink({
90
- metadata: wallet,
360
+ const metadata = walletBook.getWalletBookWallet(this.walletBook, this.key);
361
+ const deepLink = walletConnectorCore.getDeepLink({
362
+ metadata,
91
363
  mode: 'regular',
92
364
  preference: this.deepLinkPreference,
93
- uri: this.getClient().uri,
365
+ uri: (_a = WalletConnect.provider) === null || _a === void 0 ? void 0 : _a.signer.uri,
94
366
  });
367
+ if (!deepLink) {
368
+ return;
369
+ }
370
+ // we need to include the session topic here because it helps the wallet
371
+ // auto redirect back to the dapp after signing
372
+ return `${deepLink}?sessionTopic=${this.session.topic}`;
95
373
  }
96
374
  signMessage(messageToSign) {
97
375
  return _tslib.__awaiter(this, void 0, void 0, function* () {
98
- return client.signWalletConnectPersonalMessage(messageToSign, walletBook.getWalletBookWallet(this.walletBook, this.key), this.getClient(), this.deepLinkPreference,
99
- // don't call getPublicClient until we really need to
100
- () => _tslib.__awaiter(this, void 0, void 0, function* () { return this.getPublicClient(); }));
376
+ if (!this.session) {
377
+ throw new utils.DynamicError('no session');
378
+ }
379
+ const deepLink = this.getDeepLink();
380
+ if (utils.isMobile() && deepLink) {
381
+ window.location.href = deepLink;
382
+ }
383
+ const signMessageFn = (messageToSign) => _tslib.__awaiter(this, void 0, void 0, function* () {
384
+ const activeAccount = this.getActiveAccount();
385
+ if (!activeAccount) {
386
+ return;
387
+ }
388
+ const walletClient = yield this.getWalletClientFromInitializedProvider();
389
+ return walletClient.signMessage({
390
+ account: activeAccount,
391
+ message: messageToSign,
392
+ });
393
+ });
394
+ const response = yield this.waitForSignMessage(signMessageFn, messageToSign);
395
+ return response;
101
396
  });
102
397
  }
398
+ clearActiveAccount() {
399
+ localStorage.removeItem(this.activeAccountKey);
400
+ this.setActiveAccount(undefined);
401
+ }
402
+ clearSession() {
403
+ localStorage.removeItem(this.sessionTopicKey);
404
+ this.session = undefined;
405
+ }
406
+ setWCActiveAccount(account) {
407
+ localStorage.setItem(this.activeAccountKey, account);
408
+ this.setActiveAccount(account);
409
+ this.emit('accountChange', { accounts: [account] });
410
+ }
411
+ setSession(session) {
412
+ localStorage.setItem(this.sessionTopicKey, session.topic);
413
+ this.session = session;
414
+ }
103
415
  endSession() {
416
+ var _a;
104
417
  return _tslib.__awaiter(this, void 0, void 0, function* () {
105
- client.killWalletConnectSession(this.getClient());
418
+ this.clearActiveAccount();
419
+ this.clearSession();
420
+ this.hasSwitchedNetwork = false;
421
+ this.currentChainId = undefined;
422
+ if (!((_a = WalletConnect.provider) === null || _a === void 0 ? void 0 : _a.session)) {
423
+ return;
424
+ }
425
+ try {
426
+ yield WalletConnect.provider.disconnect();
427
+ // We must unset provider on logout so that a new session can be established
428
+ // If we don't then the provider will still have the old session and will hang
429
+ WalletConnect.provider = undefined;
430
+ }
431
+ catch (e) {
432
+ walletConnectorCore.logger.debug(e);
433
+ }
434
+ });
435
+ }
436
+ getNetwork() {
437
+ const _super = Object.create(null, {
438
+ getNetwork: { get: () => super.getNetwork }
439
+ });
440
+ return _tslib.__awaiter(this, void 0, void 0, function* () {
441
+ if (this.currentChainId) {
442
+ return this.currentChainId;
443
+ }
444
+ yield this.initProvider();
445
+ return _super.getNetwork.call(this);
106
446
  });
107
447
  }
108
- providerSwitchNetwork({ network, provider, }) {
448
+ providerSwitchNetwork({ network, }) {
109
449
  const _super = Object.create(null, {
110
450
  providerSwitchNetwork: { get: () => super.providerSwitchNetwork }
111
451
  });
112
452
  return _tslib.__awaiter(this, void 0, void 0, function* () {
113
- const client = this.getClient();
453
+ const supportedNetworks = yield this.getSupportedNetworks();
454
+ if (!(supportedNetworks === null || supportedNetworks === void 0 ? void 0 : supportedNetworks.includes(network.chainId.toString()))) {
455
+ const error = new utils.DynamicError('Network switching is not available at this time. The user should manually switch network in their wallet');
456
+ error.code = 'network_switching_only_available_in_wallet';
457
+ throw error;
458
+ }
114
459
  const currentNetworkId = yield this.getNetwork();
115
460
  if (currentNetworkId && currentNetworkId === network.chainId) {
116
461
  return;
117
462
  }
118
- if (this.switchNetworkOnlyFromWallet !== undefined &&
119
- this.switchNetworkOnlyFromWallet) {
463
+ if (this.switchNetworkOnlyFromWallet) {
120
464
  throw new utils.DynamicError('Network switching is only supported through the wallet');
121
465
  }
122
466
  if (!this.supportsNetworkSwitching()) {
123
467
  throw new utils.DynamicError('Network switching not supported');
124
468
  }
125
- if (!client) {
126
- throw new utils.DynamicError('Client not found');
469
+ const walletClient = yield this.getWalletClientFromInitializedProvider();
470
+ if (this.isMetaMask()) {
471
+ const deepLink = this.getDeepLink();
472
+ if (deepLink) {
473
+ window.location.href = deepLink;
474
+ }
127
475
  }
128
- if (utils.isMobile()) {
129
- const deepLink = walletConnectorCore.getDeepLink({
130
- metadata: walletBook.getWalletBookWallet(this.walletBook, this.key),
131
- mode: 'regular',
132
- preference: this.deepLinkPreference,
133
- uri: client.uri,
134
- });
135
- window.location.href = deepLink;
136
- }
137
- return _super.providerSwitchNetwork.call(this, { network, provider });
476
+ yield _super.providerSwitchNetwork.call(this, { network, provider: walletClient });
477
+ this.currentChainId = network.chainId;
478
+ this.hasSwitchedNetwork = true;
479
+ this.emit('chainChange', { chain: String(network.chainId) });
138
480
  });
139
481
  }
140
482
  getConnectedAccounts() {
141
483
  return _tslib.__awaiter(this, void 0, void 0, function* () {
142
- const client = this.getClient();
143
- if (!client.connected)
484
+ if (this.isInitialized === false) {
485
+ yield this.initProvider();
486
+ this.refreshSession();
487
+ this.isInitialized = true;
488
+ }
489
+ const activeAccount = this.getActiveAccount();
490
+ if (!(activeAccount === null || activeAccount === void 0 ? void 0 : activeAccount.address)) {
144
491
  return [];
145
- return client.accounts;
492
+ }
493
+ return [activeAccount.address];
146
494
  });
147
495
  }
148
- getSession() {
496
+ isMetaMask() {
497
+ var _a, _b, _c, _d, _e;
498
+ return ((_e = (_d = (_c = (_b = (_a = this.session) === null || _a === void 0 ? void 0 : _a.peer) === null || _b === void 0 ? void 0 : _b.metadata) === null || _c === void 0 ? void 0 : _c.name) === null || _d === void 0 ? void 0 : _d.toLowerCase().startsWith('metamask')) !== null && _e !== void 0 ? _e : false);
499
+ }
500
+ getSupportedNetworks() {
149
501
  var _a;
150
502
  return _tslib.__awaiter(this, void 0, void 0, function* () {
151
- return (_a = this.client) === null || _a === void 0 ? void 0 : _a.session;
503
+ yield this.initProvider();
504
+ this.refreshSession();
505
+ if (this.isMetaMask()) {
506
+ if (this.hasSwitchedNetwork) {
507
+ return [String(this.currentChainId)];
508
+ }
509
+ return this.evmNetworks.map((network) => network.chainId.toString());
510
+ }
511
+ if (!this.session) {
512
+ return [];
513
+ }
514
+ const chains = [];
515
+ // Some wallet (i.e ZenGo) use namespaces.account to list supported chains
516
+ // while others use keys within the namespaces object
517
+ Object.keys(this.session.namespaces).forEach((key) => {
518
+ if (key.startsWith('eip155:')) {
519
+ chains.push(key.split(':')[1]);
520
+ }
521
+ });
522
+ (_a = this.session.namespaces.eip155) === null || _a === void 0 ? void 0 : _a.accounts.forEach((account) => chains.push(account.split(':')[1]));
523
+ return chains.length
524
+ ? chains
525
+ : this.evmNetworks.map((network) => network.chainId.toString());
152
526
  });
153
527
  }
154
528
  }