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

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.
@@ -1,475 +0,0 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- var _tslib = require('../../_virtual/_tslib.cjs');
6
- var Provider = require('@walletconnect/universal-provider');
7
- var EventEmitter = require('eventemitter3');
8
- var viem = require('viem');
9
- var walletConnectorCore = require('@dynamic-labs/wallet-connector-core');
10
- var walletBook = require('@dynamic-labs/wallet-book');
11
- var utils = require('@dynamic-labs/utils');
12
- var EthWalletConnector = require('../EthWalletConnector.cjs');
13
- var parseIntSafe = require('../utils/parseIntSafe.cjs');
14
-
15
- function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
16
-
17
- var Provider__default = /*#__PURE__*/_interopDefaultLegacy(Provider);
18
- var EventEmitter__default = /*#__PURE__*/_interopDefaultLegacy(EventEmitter);
19
-
20
- const activeAccountKey = (walletName) => `dynamic-wc2-active-account-${walletName}`;
21
- const sessionTopicKey = (walletName) => `dynamic-wc2-session-topic-${walletName}`;
22
- const swicthedNetworkKey = (walletName) => `dynamic-wc2-switched-network-${walletName}`;
23
- const currentChainKey = (walletName) => `dynamic-wc2-current-chain-${walletName}`;
24
- const ee = new EventEmitter__default["default"]();
25
- class WalletConnectV2 extends EthWalletConnector.EthWalletConnector {
26
- constructor(opts) {
27
- var _a;
28
- super(opts);
29
- this.supportedChains = ['EVM', 'ETH'];
30
- this.connectedChain = 'EVM';
31
- this.isInitialized = false;
32
- this.canConnectViaQrCode = true;
33
- this.isWalletConnect = true;
34
- this.preferredChains = [];
35
- // When trying to switch network for MetaMask, the switch promise gets stuck
36
- // if the switch got trigged once already, so we need to keep track of that
37
- this._hasSwitchedNetwork = false;
38
- this.name = opts.walletName;
39
- this.projectId = opts.projectId;
40
- this.deepLinkPreference = opts.deepLinkPreference || 'native';
41
- this.preferredChains = opts.walletConnectPreferredChains || [];
42
- this.hasSwitchedNetwork =
43
- (_a = Boolean(localStorage.getItem(this.swicthedNetworkKey))) !== null && _a !== void 0 ? _a : false;
44
- const lsCurrentChain = localStorage.getItem(this.currentChainKey);
45
- this.currentChainId = lsCurrentChain
46
- ? parseIntSafe.parseIntSafe(lsCurrentChain)
47
- : undefined;
48
- }
49
- getMappedChains() {
50
- return (this.evmNetworks
51
- // Filters out palm that crashes Trust Wallet
52
- .filter((network) => network.chainId !== 11297108109)
53
- .map((network) => `eip155:${network.chainId}`));
54
- }
55
- getMappedChainsByPreferredOrder() {
56
- // adding Ethereum to avoid an error connecting if none of the evm networks are supported by the wallet
57
- const allChains = this.getMappedChains();
58
- if (!allChains.includes('eip155:1')) {
59
- allChains.push('eip155:1');
60
- }
61
- const reorderedChains = this.preferredChains.filter((chain) => allChains.includes(chain));
62
- const remainingChains = allChains.filter((chain) => !this.preferredChains.includes(chain));
63
- return [...reorderedChains, ...remainingChains];
64
- }
65
- initConnection() {
66
- return _tslib.__awaiter(this, void 0, void 0, function* () {
67
- const { provider } = WalletConnectV2;
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.uri) {
73
- return;
74
- }
75
- const optionalNamespaces = {
76
- eip155: {
77
- chains: this.getMappedChainsByPreferredOrder(),
78
- events: ['chainChanged', 'accountsChanged'],
79
- methods: [
80
- 'eth_chainId',
81
- 'eth_signTypedData',
82
- 'eth_signTransaction',
83
- 'eth_sign',
84
- 'personal_sign',
85
- 'eth_sendTransaction',
86
- 'eth_signTypedData_v4',
87
- 'wallet_switchEthereumChain',
88
- 'wallet_addEthereumChain',
89
- ],
90
- rpcMap: this.evmNetworkRpcMap(),
91
- },
92
- };
93
- provider
94
- .connect({
95
- optionalNamespaces,
96
- })
97
- .catch((e) => {
98
- walletConnectorCore.logger.error(e);
99
- ee.emit('walletconnect_connection_failed', e);
100
- });
101
- });
102
- }
103
- createInitProviderPromise() {
104
- return _tslib.__awaiter(this, void 0, void 0, function* () {
105
- const provider = yield Provider__default["default"].init({
106
- logger: walletConnectorCore.logger.logLevel.toLowerCase() === 'debug' ? 'debug' : undefined,
107
- projectId: this.projectId,
108
- });
109
- WalletConnectV2.provider = provider;
110
- this.teardownEventListeners();
111
- this.setupEventListeners();
112
- });
113
- }
114
- initProvider() {
115
- return _tslib.__awaiter(this, void 0, void 0, function* () {
116
- const { provider } = WalletConnectV2;
117
- if (!provider) {
118
- if (this.initializePromise === undefined) {
119
- this.initializePromise = this.createInitProviderPromise();
120
- }
121
- yield this.initializePromise;
122
- }
123
- });
124
- }
125
- refreshSession() {
126
- var _a, _b, _c, _d, _e;
127
- if ((_b = (_a = WalletConnectV2.provider) === null || _a === void 0 ? void 0 : _a.session) === null || _b === void 0 ? void 0 : _b.topic) {
128
- if (localStorage.getItem(this.sessionTopicKey) ===
129
- ((_d = (_c = WalletConnectV2.provider) === null || _c === void 0 ? void 0 : _c.session) === null || _d === void 0 ? void 0 : _d.topic)) {
130
- this.session = WalletConnectV2.provider.session;
131
- this.activeAccount = ((_e = localStorage.getItem(this.activeAccountKey)) !== null && _e !== void 0 ? _e : undefined);
132
- }
133
- }
134
- }
135
- init() {
136
- return _tslib.__awaiter(this, void 0, void 0, function* () {
137
- yield this.initProvider();
138
- yield this.initConnection();
139
- this.isInitialized = true;
140
- });
141
- }
142
- get sessionTopicKey() {
143
- return sessionTopicKey(this.key);
144
- }
145
- get activeAccountKey() {
146
- return activeAccountKey(this.key);
147
- }
148
- get swicthedNetworkKey() {
149
- return swicthedNetworkKey(this.key);
150
- }
151
- get currentChainKey() {
152
- return currentChainKey(this.key);
153
- }
154
- set currentChainId(value) {
155
- this._currentChainId = value;
156
- if (value) {
157
- localStorage.setItem(this.currentChainKey, value.toString());
158
- }
159
- else {
160
- localStorage.removeItem(this.currentChainKey);
161
- }
162
- }
163
- get currentChainId() {
164
- return this._currentChainId;
165
- }
166
- set hasSwitchedNetwork(value) {
167
- this._hasSwitchedNetwork = value;
168
- if (value) {
169
- localStorage.setItem(this.swicthedNetworkKey, value.toString());
170
- }
171
- else {
172
- localStorage.removeItem(this.swicthedNetworkKey);
173
- }
174
- }
175
- get hasSwitchedNetwork() {
176
- return this._hasSwitchedNetwork;
177
- }
178
- supportsNetworkSwitching() {
179
- return true;
180
- }
181
- setupEventListeners() {
182
- if (!WalletConnectV2.provider) {
183
- return;
184
- }
185
- WalletConnectV2.provider.client.on('session_event', ({ params }) => {
186
- walletConnectorCore.logger.debug('session_event was called', { params });
187
- if (!params || !params.event) {
188
- walletConnectorCore.logger.debug('session_event was called without params or params.event');
189
- return;
190
- }
191
- const { name, data } = params.event;
192
- if (name === 'chainChanged') {
193
- const chainId = parseIntSafe.parseIntSafe(data);
194
- if (chainId === undefined) {
195
- walletConnectorCore.logger.debug(`received unexpected data for chainChanged: ${data} with type ${typeof data}}`);
196
- return;
197
- }
198
- this.currentChainId = chainId;
199
- this.emit('chainChange', { chain: String(chainId) });
200
- // When a user switches network from their wallet, we need the provider to change network
201
- // such that any future calls to `getNetwork` will return the correct network
202
- this.switchNetwork({ networkChainId: chainId });
203
- }
204
- else if (name === 'accountsChanged') {
205
- if (!Array.isArray(data)) {
206
- walletConnectorCore.logger.debug(`received unexpected data for accountsChanged: ${data} with type ${typeof data}}`);
207
- return;
208
- }
209
- // eslint-disable-next-line prefer-destructuring
210
- const account = data[0].split(':')[2];
211
- this.setActiveAccount(account);
212
- }
213
- });
214
- WalletConnectV2.provider.client.on('session_delete', () => _tslib.__awaiter(this, void 0, void 0, function* () {
215
- this.endSession();
216
- this.emit('disconnect');
217
- }));
218
- }
219
- teardownEventListeners() {
220
- if (!WalletConnectV2.provider) {
221
- return;
222
- }
223
- WalletConnectV2.provider.client.removeAllListeners('session_event');
224
- WalletConnectV2.provider.client.removeAllListeners('session_delete');
225
- }
226
- getWalletClient() {
227
- if (!WalletConnectV2.provider) {
228
- return;
229
- }
230
- return viem.createWalletClient({
231
- transport: viem.custom(WalletConnectV2.provider),
232
- });
233
- }
234
- fetchPublicAddress(opts) {
235
- var _a, _b;
236
- return _tslib.__awaiter(this, void 0, void 0, function* () {
237
- if (this.activeAccount) {
238
- return this.activeAccount;
239
- }
240
- if (!WalletConnectV2.provider || !((_a = WalletConnectV2.provider) === null || _a === void 0 ? void 0 : _a.uri)) {
241
- walletConnectorCore.logger.debug('No WC2 provider found, re-initializing...');
242
- yield this.endSession();
243
- yield this.init();
244
- // sleep 1 s to wait for connect call to finish
245
- // the connect call isn't await-ed because it only resolves once
246
- // the connection is established, but we need to wait for it to
247
- // finish setting up the connection URI and making it available
248
- // on the provider
249
- yield new Promise((resolve) => setTimeout(resolve, 1000));
250
- if (!WalletConnectV2.provider || !((_b = WalletConnectV2.provider) === null || _b === void 0 ? void 0 : _b.uri)) {
251
- walletConnectorCore.logger.debug('No WC2 provider found, escaping and throwing error');
252
- throw new utils.DynamicError('No provider found');
253
- }
254
- }
255
- const metadata = walletBook.getWalletBookWallet(this.walletBook, this.key);
256
- walletConnectorCore.performPlatformSpecificConnectionMethod(WalletConnectV2.provider.uri, metadata, {
257
- onDesktopUri: opts === null || opts === void 0 ? void 0 : opts.onDesktopUri,
258
- onDisplayUri: opts === null || opts === void 0 ? void 0 : opts.onDisplayUri,
259
- }, this.deepLinkPreference);
260
- return new Promise((resolve, reject) => {
261
- if (!WalletConnectV2.provider) {
262
- reject(new utils.DynamicError('No provider found'));
263
- return;
264
- }
265
- ee.on('walletconnect_connection_failed', () => {
266
- const error = new utils.DynamicError('Connection rejected. Please try again.');
267
- error.code = 'connection_rejected';
268
- if (WalletConnectV2.provider) {
269
- WalletConnectV2.provider.uri = undefined;
270
- }
271
- reject(error);
272
- });
273
- WalletConnectV2.provider.on('connect', ({ session }) => {
274
- if (!session) {
275
- reject(new utils.DynamicError('No session found'));
276
- }
277
- this.setSession(session);
278
- this.setActiveAccount(session.namespaces.eip155.accounts[0].split(':')[2]);
279
- resolve(this.activeAccount);
280
- });
281
- });
282
- });
283
- }
284
- /**
285
- * WalletConnect V2 will fail to send the sign message request if the chainId
286
- * is not the same as the one in the session. This method will wait for the
287
- * chainId to change and then retry the sign message request.
288
- *
289
- * Otherwise it will just return the result of the sign message request.
290
- *
291
- * @param signMessageFn - Function to sign message with provider
292
- * @param messageToSign - Message to sign
293
- * @returns
294
- */
295
- waitForSignMessage(signMessageFn, messageToSign) {
296
- return _tslib.__awaiter(this, void 0, void 0, function* () {
297
- const raceConditionPromise = new Promise((resolve) => {
298
- // Create listener for chain change event
299
- this.on('chainChange', () => resolve({ success: false }));
300
- signMessageFn(messageToSign).then((result) => resolve({ signedMessage: result, success: true }));
301
- });
302
- const signedMessageResult = yield raceConditionPromise;
303
- if (signedMessageResult.success === false) {
304
- return signMessageFn(messageToSign);
305
- }
306
- return signedMessageResult.signedMessage;
307
- });
308
- }
309
- getDeepLink() {
310
- var _a;
311
- if (!this.session) {
312
- return;
313
- }
314
- const metadata = walletBook.getWalletBookWallet(this.walletBook, this.key);
315
- const deepLink = walletConnectorCore.getDeepLink({
316
- metadata,
317
- mode: 'regular',
318
- preference: this.deepLinkPreference,
319
- uri: (_a = WalletConnectV2.provider) === null || _a === void 0 ? void 0 : _a.uri,
320
- });
321
- if (!deepLink) {
322
- return;
323
- }
324
- // we need to include the session topic here because it helps the wallet
325
- // auto redirect back to the dapp after signing
326
- return `${deepLink}?sessionTopic=${this.session.topic}`;
327
- }
328
- signMessage(messageToSign) {
329
- return _tslib.__awaiter(this, void 0, void 0, function* () {
330
- if (!this.session) {
331
- throw new utils.DynamicError('no session');
332
- }
333
- const web3Provider = this.getWalletClient();
334
- if (!web3Provider) {
335
- throw new utils.DynamicError('No WalletConnect provider found to handle signing');
336
- }
337
- const deepLink = this.getDeepLink();
338
- if (utils.isMobile() && deepLink) {
339
- window.location.href = deepLink;
340
- }
341
- const signMessageFn = (messageToSign) => _tslib.__awaiter(this, void 0, void 0, function* () {
342
- const { activeAccount } = this;
343
- if (!activeAccount) {
344
- return;
345
- }
346
- return web3Provider.signMessage({
347
- account: activeAccount,
348
- message: messageToSign,
349
- });
350
- });
351
- const response = yield this.waitForSignMessage(signMessageFn, messageToSign);
352
- return response;
353
- });
354
- }
355
- clearActiveAccount() {
356
- localStorage.removeItem(this.activeAccountKey);
357
- this.activeAccount = undefined;
358
- }
359
- clearSession() {
360
- localStorage.removeItem(this.sessionTopicKey);
361
- this.session = undefined;
362
- }
363
- setActiveAccount(account) {
364
- localStorage.setItem(this.activeAccountKey, account);
365
- this.activeAccount = account;
366
- this.emit('accountChange', { accounts: [account] });
367
- }
368
- setSession(session) {
369
- localStorage.setItem(this.sessionTopicKey, session.topic);
370
- this.session = session;
371
- }
372
- endSession() {
373
- var _a;
374
- return _tslib.__awaiter(this, void 0, void 0, function* () {
375
- this.clearActiveAccount();
376
- this.clearSession();
377
- this.hasSwitchedNetwork = false;
378
- this.currentChainId = undefined;
379
- if (!((_a = WalletConnectV2.provider) === null || _a === void 0 ? void 0 : _a.session)) {
380
- return;
381
- }
382
- try {
383
- yield WalletConnectV2.provider.disconnect();
384
- // We must unset provider on logout so that a new session can be established
385
- // If we don't then the provider will still have the old session and will hang
386
- WalletConnectV2.provider = undefined;
387
- }
388
- catch (e) {
389
- walletConnectorCore.logger.debug(e);
390
- }
391
- });
392
- }
393
- getNetwork() {
394
- const _super = Object.create(null, {
395
- getNetwork: { get: () => super.getNetwork }
396
- });
397
- return _tslib.__awaiter(this, void 0, void 0, function* () {
398
- if (this.currentChainId) {
399
- return this.currentChainId;
400
- }
401
- yield this.initProvider();
402
- return _super.getNetwork.call(this);
403
- });
404
- }
405
- providerSwitchNetwork({ network, provider, }) {
406
- const _super = Object.create(null, {
407
- providerSwitchNetwork: { get: () => super.providerSwitchNetwork }
408
- });
409
- return _tslib.__awaiter(this, void 0, void 0, function* () {
410
- const currentNetworkId = yield this.getNetwork();
411
- if (currentNetworkId && currentNetworkId === network.chainId) {
412
- return;
413
- }
414
- if (this.switchNetworkOnlyFromWallet) {
415
- throw new utils.DynamicError('Network switching is only supported through the wallet');
416
- }
417
- if (!this.supportsNetworkSwitching()) {
418
- throw new utils.DynamicError('Network switching not supported');
419
- }
420
- if (!provider) {
421
- throw new utils.DynamicError('Provider not found');
422
- }
423
- yield _super.providerSwitchNetwork.call(this, { network, provider });
424
- this.currentChainId = network.chainId;
425
- this.hasSwitchedNetwork = true;
426
- this.emit('chainChange', { chain: String(network.chainId) });
427
- });
428
- }
429
- getConnectedAccounts() {
430
- return _tslib.__awaiter(this, void 0, void 0, function* () {
431
- if (this.isInitialized === false) {
432
- yield this.initProvider();
433
- this.refreshSession();
434
- this.isInitialized = true;
435
- }
436
- if (!this.activeAccount) {
437
- return [];
438
- }
439
- return [this.activeAccount];
440
- });
441
- }
442
- isMetaMask() {
443
- var _a, _b, _c, _d, _e;
444
- 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);
445
- }
446
- getSupportedNetworks() {
447
- var _a;
448
- return _tslib.__awaiter(this, void 0, void 0, function* () {
449
- // MM allows you to switch to any network the first time, even if it's not enabled in MM
450
- // so we should consider all networks as supported if network switching hasn't been triggered yet
451
- if (this.isMetaMask() && !this.hasSwitchedNetwork) {
452
- return this.evmNetworks.map((network) => network.chainId.toString());
453
- }
454
- yield this.initProvider();
455
- this.refreshSession();
456
- if (!this.session) {
457
- return [];
458
- }
459
- const chains = [];
460
- // Some wallet (i.e ZenGo) use namespaces.account to list supported chains
461
- // while others use keys within the namespaces object
462
- Object.keys(this.session.namespaces).forEach((key) => {
463
- if (key.startsWith('eip155:')) {
464
- chains.push(key.split(':')[1]);
465
- }
466
- });
467
- (_a = this.session.namespaces.eip155) === null || _a === void 0 ? void 0 : _a.accounts.forEach((account) => chains.push(account.split(':')[1]));
468
- return chains.length
469
- ? chains
470
- : this.evmNetworks.map((network) => network.chainId.toString());
471
- });
472
- }
473
- }
474
-
475
- exports.WalletConnectV2 = WalletConnectV2;