@dynamic-labs/ethereum 1.0.0-alpha.0 → 1.0.0-alpha.10

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.
@@ -10,9 +10,12 @@ import { parseIntSafe } from '../utils/parseIntSafe.js';
10
10
 
11
11
  const activeAccountKey = (walletName) => `dynamic-wc2-active-account-${walletName}`;
12
12
  const sessionTopicKey = (walletName) => `dynamic-wc2-session-topic-${walletName}`;
13
+ const swicthedNetworkKey = (walletName) => `dynamic-wc2-switched-network-${walletName}`;
14
+ const currentChainKey = (walletName) => `dynamic-wc2-current-chain-${walletName}`;
13
15
  const ee = new EventEmitter();
14
16
  class WalletConnectV2 extends EthWalletConnector {
15
17
  constructor(opts) {
18
+ var _a;
16
19
  super(opts);
17
20
  this.supportedChains = ['EVM', 'ETH'];
18
21
  this.connectedChain = 'EVM';
@@ -20,6 +23,9 @@ class WalletConnectV2 extends EthWalletConnector {
20
23
  this.canConnectViaQrCode = true;
21
24
  this.isWalletConnect = true;
22
25
  this.preferredChains = [];
26
+ // When trying to switch network for MetaMask, the switch promise gets stuck
27
+ // if the switch got trigged once already, so we need to keep track of that
28
+ this._hasSwitchedNetwork = false;
23
29
  this.name = opts.walletName;
24
30
  this.projectId = opts.projectId;
25
31
  this.deepLinkPreference = opts.deepLinkPreference || 'native';
@@ -27,40 +33,17 @@ class WalletConnectV2 extends EthWalletConnector {
27
33
  if (!this.preferredChains.includes('eip155:1')) {
28
34
  this.preferredChains.push('eip155:1');
29
35
  }
36
+ this.hasSwitchedNetwork =
37
+ (_a = Boolean(localStorage.getItem(this.swicthedNetworkKey))) !== null && _a !== void 0 ? _a : false;
38
+ const lsCurrentChain = localStorage.getItem(this.currentChainKey);
39
+ this.currentChainId = lsCurrentChain
40
+ ? parseIntSafe(lsCurrentChain)
41
+ : undefined;
30
42
  }
31
- defaultChainId() {
32
- const preferredNetwork = this.preferredChains.find((chain) => this.supportedChain(chain));
33
- if (preferredNetwork) {
34
- return preferredNetwork;
35
- }
36
- else if (this.findSupportedChains().length) {
37
- return this.findSupportedChains()[0];
38
- }
39
- else {
40
- return 'eip155:1';
41
- }
42
- }
43
- findSupportedChains() {
44
- var _a;
45
- try {
46
- const wallet = getWalletBookWallet(this.walletBook, this.key);
47
- const supportedChains = (_a = this.evmNetworks) === null || _a === void 0 ? void 0 : _a.filter((network) => { var _a; return (_a = wallet === null || wallet === void 0 ? void 0 : wallet.chains) === null || _a === void 0 ? void 0 : _a.includes(`eip155:${network.chainId}`); }).map((network) => `eip155:${network.chainId}`);
48
- return supportedChains;
49
- }
50
- catch (_b) {
51
- // pass
52
- }
53
- return [];
54
- }
55
- supportedChain(chainId) {
56
- var _a;
57
- return (_a = this.findSupportedChains().filter((chain) => [`eip155:${chainId}`, chainId].includes(chain))) === null || _a === void 0 ? void 0 : _a[0];
58
- }
59
- optionalChains() {
43
+ getMappedChains() {
60
44
  return (this.evmNetworks
61
- // Filters out mainnet which is required and palm that crashes Trust Wallet
62
- .filter((network) => network.chainId !== 11297108109 &&
63
- `eip155:${network.chainId}` !== this.defaultChainId())
45
+ // Filters out palm that crashes Trust Wallet
46
+ .filter((network) => network.chainId !== 11297108109)
64
47
  .map((network) => `eip155:${network.chainId}`));
65
48
  }
66
49
  initConnection() {
@@ -73,34 +56,26 @@ class WalletConnectV2 extends EthWalletConnector {
73
56
  if (provider === null || provider === void 0 ? void 0 : provider.uri) {
74
57
  return;
75
58
  }
76
- let optionalNamespaces = {};
77
- if (this.optionalChains().length) {
78
- optionalNamespaces = {
79
- eip155: {
80
- chains: this.optionalChains(),
81
- events: [],
82
- methods: [
83
- 'eth_signTypedData',
84
- 'eth_signTransaction',
85
- 'eth_sign',
86
- 'personal_sign',
87
- 'eth_sendTransaction',
88
- 'eth_signTypedData_v4',
89
- ],
90
- rpcMap: this.evmNetworkRpcMap(),
91
- },
92
- };
93
- }
59
+ const optionalNamespaces = {
60
+ eip155: {
61
+ chains: this.getMappedChains(),
62
+ events: ['chainChanged', 'accountsChanged'],
63
+ methods: [
64
+ 'eth_chainId',
65
+ 'eth_signTypedData',
66
+ 'eth_signTransaction',
67
+ 'eth_sign',
68
+ 'personal_sign',
69
+ 'eth_sendTransaction',
70
+ 'eth_signTypedData_v4',
71
+ 'wallet_switchEthereumChain',
72
+ 'wallet_addEthereumChain',
73
+ ],
74
+ rpcMap: this.evmNetworkRpcMap(),
75
+ },
76
+ };
94
77
  provider
95
78
  .connect({
96
- namespaces: {
97
- eip155: {
98
- chains: [this.defaultChainId()],
99
- events: ['chainChanged', 'accountsChanged'],
100
- methods: ['personal_sign', 'eth_sendTransaction'],
101
- rpcMap: this.evmNetworkRpcMap(),
102
- },
103
- },
104
79
  optionalNamespaces,
105
80
  })
106
81
  .catch((e) => {
@@ -116,6 +91,8 @@ class WalletConnectV2 extends EthWalletConnector {
116
91
  projectId: this.projectId,
117
92
  });
118
93
  WalletConnectV2.provider = provider;
94
+ this.teardownEventListeners();
95
+ this.setupEventListeners();
119
96
  });
120
97
  }
121
98
  initProvider() {
@@ -152,6 +129,36 @@ class WalletConnectV2 extends EthWalletConnector {
152
129
  get activeAccountKey() {
153
130
  return activeAccountKey(this.key);
154
131
  }
132
+ get swicthedNetworkKey() {
133
+ return swicthedNetworkKey(this.key);
134
+ }
135
+ get currentChainKey() {
136
+ return currentChainKey(this.key);
137
+ }
138
+ set currentChainId(value) {
139
+ this._currentChainId = value;
140
+ if (value) {
141
+ localStorage.setItem(this.currentChainKey, value.toString());
142
+ }
143
+ else {
144
+ localStorage.removeItem(this.currentChainKey);
145
+ }
146
+ }
147
+ get currentChainId() {
148
+ return this._currentChainId;
149
+ }
150
+ set hasSwitchedNetwork(value) {
151
+ this._hasSwitchedNetwork = value;
152
+ if (value) {
153
+ localStorage.setItem(this.swicthedNetworkKey, value.toString());
154
+ }
155
+ else {
156
+ localStorage.removeItem(this.swicthedNetworkKey);
157
+ }
158
+ }
159
+ get hasSwitchedNetwork() {
160
+ return this._hasSwitchedNetwork;
161
+ }
155
162
  supportsNetworkSwitching() {
156
163
  return true;
157
164
  }
@@ -160,6 +167,7 @@ class WalletConnectV2 extends EthWalletConnector {
160
167
  return;
161
168
  }
162
169
  WalletConnectV2.provider.client.on('session_event', ({ params }) => {
170
+ logger.debug('session_event was called', { params });
163
171
  if (!params || !params.event) {
164
172
  logger.debug('session_event was called without params or params.event');
165
173
  return;
@@ -171,6 +179,7 @@ class WalletConnectV2 extends EthWalletConnector {
171
179
  logger.debug(`received unexpected data for chainChanged: ${data} with type ${typeof data}}`);
172
180
  return;
173
181
  }
182
+ this.currentChainId = chainId;
174
183
  this.emit('chainChange', { chain: String(chainId) });
175
184
  // When a user switches network from their wallet, we need the provider to change network
176
185
  // such that any future calls to `getNetwork` will return the correct network
@@ -184,7 +193,6 @@ class WalletConnectV2 extends EthWalletConnector {
184
193
  // eslint-disable-next-line prefer-destructuring
185
194
  const account = data[0].split(':')[2];
186
195
  this.setActiveAccount(account);
187
- this.emit('accountChange', { accounts: [account] });
188
196
  }
189
197
  });
190
198
  WalletConnectV2.provider.client.on('session_delete', () => __awaiter(this, void 0, void 0, function* () {
@@ -339,6 +347,7 @@ class WalletConnectV2 extends EthWalletConnector {
339
347
  setActiveAccount(account) {
340
348
  localStorage.setItem(this.activeAccountKey, account);
341
349
  this.activeAccount = account;
350
+ this.emit('accountChange', { accounts: [account] });
342
351
  }
343
352
  setSession(session) {
344
353
  localStorage.setItem(this.sessionTopicKey, session.topic);
@@ -349,6 +358,8 @@ class WalletConnectV2 extends EthWalletConnector {
349
358
  return __awaiter(this, void 0, void 0, function* () {
350
359
  this.clearActiveAccount();
351
360
  this.clearSession();
361
+ this.hasSwitchedNetwork = false;
362
+ this.currentChainId = undefined;
352
363
  if (!((_a = WalletConnectV2.provider) === null || _a === void 0 ? void 0 : _a.session)) {
353
364
  return;
354
365
  }
@@ -368,6 +379,9 @@ class WalletConnectV2 extends EthWalletConnector {
368
379
  getNetwork: { get: () => super.getNetwork }
369
380
  });
370
381
  return __awaiter(this, void 0, void 0, function* () {
382
+ if (this.currentChainId) {
383
+ return this.currentChainId;
384
+ }
371
385
  yield this.initProvider();
372
386
  return _super.getNetwork.call(this);
373
387
  });
@@ -391,6 +405,8 @@ class WalletConnectV2 extends EthWalletConnector {
391
405
  throw new DynamicError('Provider not found');
392
406
  }
393
407
  yield _super.providerSwitchNetwork.call(this, { network, provider });
408
+ this.currentChainId = network.chainId;
409
+ this.hasSwitchedNetwork = true;
394
410
  this.emit('chainChange', { chain: String(network.chainId) });
395
411
  });
396
412
  }
@@ -408,7 +424,11 @@ class WalletConnectV2 extends EthWalletConnector {
408
424
  });
409
425
  }
410
426
  getSupportedNetworks() {
427
+ var _a;
411
428
  return __awaiter(this, void 0, void 0, function* () {
429
+ if (!this.hasSwitchedNetwork) {
430
+ return undefined;
431
+ }
412
432
  yield this.initProvider();
413
433
  this.refreshSession();
414
434
  if (!this.session) {
@@ -422,7 +442,7 @@ class WalletConnectV2 extends EthWalletConnector {
422
442
  chains.push(key.split(':')[1]);
423
443
  }
424
444
  });
425
- this.session.namespaces.eip155.accounts.forEach((account) => chains.push(account.split(':')[1]));
445
+ (_a = this.session.namespaces.eip155) === null || _a === void 0 ? void 0 : _a.accounts.forEach((account) => chains.push(account.split(':')[1]));
426
446
  return chains.length ? chains : undefined;
427
447
  });
428
448
  }