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

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