@dynamic-labs/ethereum 4.9.0 → 4.9.1-preview.0

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