@etherplay/connect 0.0.8 → 0.0.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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,gBAAgB,EAAE,aAAa,EAAC,MAAM,oBAAoB,CAAC;AAGxE,OAAO,KAAK,EAAC,cAAc,EAAE,2BAA2B,EAAC,MAAM,UAAU,CAAC;AAC1E,OAAO,EACN,wBAAwB,EAGxB,gBAAgB,EAChB,iCAAiC,EACjC,MAAM,oBAAoB,CAAC;AAI5B,OAAO,EAAC,wBAAwB,EAAE,iCAAiC,EAAE,gBAAgB,EAAC,CAAC;AACvF,YAAY,EAAC,aAAa,EAAC,CAAC;AAE5B,MAAM,MAAM,aAAa,GAAG;IAC3B,UAAU,EAAE,MAAM,CAAC;IACnB,SAAS,EAAE,gBAAgB,CAAC;CAE5B,CAAC;AAEF,MAAM,MAAM,eAAe,CAAC,UAAU,SAAS,MAAM,GAAG,SAAS,EAAE,OAAO,SAAS,KAAK,MAAM,EAAE,GAAG,SAAS,IAAI;IAC/G,IAAI,EAAE,QAAQ,CAAC;CACf,GAAG,CAAC,UAAU,SAAS,SAAS,GAAG;IAAC,IAAI,CAAC,EAAE,SAAS,CAAA;CAAC,GAAG;IAAC,IAAI,EAAE,UAAU,CAAA;CAAC,CAAC,GAC3E,CAAC,OAAO,SAAS,SAAS,GAAG;IAAC,OAAO,CAAC,EAAE,SAAS,CAAA;CAAC,GAAG;IAAC,OAAO,EAAE,OAAO,CAAA;CAAC,CAAC,CAAC;AAE1E,MAAM,MAAM,SAAS,GAAG,gBAAgB,GAAG,eAAe,CAAC,MAAM,GAAG,SAAS,EAAE,KAAK,MAAM,EAAE,GAAG,SAAS,CAAC,CAAC;AAE1G,MAAM,MAAM,mBAAmB,GAAG,gBAAgB,GAAG,eAAe,CAAC,MAAM,E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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;kBA5rBsB,CAAC;kBAAqB,CAAC;;;;;;;;;;EAi2B/C;AAED,MAAM,MAAM,eAAe,GAAG,UAAU,CAAC,OAAO,gBAAgB,CAAC,CAAC"}
package/dist/index.js CHANGED
@@ -1,10 +1,18 @@
1
1
  import { writable } from 'svelte/store';
2
2
  import { createPopupLauncher } from './popup.js';
3
- import { fromEntropyKeyToMnemonic, fromMnemonicToFirstAccount, fromSignatureToKey, originKeyMessage, originPublicKeyPublicationMessage } from '@etherplay/alchemy';
3
+ import { fromEntropyKeyToMnemonic, fromMnemonicToFirstAccount, fromSignatureToKey, originKeyMessage, originPublicKeyPublicationMessage, } from '@etherplay/alchemy';
4
4
  import { hashMessage } from './utils.js';
5
+ import { createProvider } from './provider.js';
5
6
  export { fromEntropyKeyToMnemonic, originPublicKeyPublicationMessage, originKeyMessage };
6
7
  const storageAccountKey = '__origin_account';
7
8
  export function createConnection(settings) {
9
+ const alwaysOnChainId = settings.node.chainId;
10
+ const alwaysOnProvider = createProvider({
11
+ endpoint: settings.node.url,
12
+ chainId: settings.node.chainId,
13
+ prioritizeWalletProvider: settings.node.prioritizeWalletProvider,
14
+ requestsPerSecond: settings.node.requestsPerSecond,
15
+ });
8
16
  let autoConnect = true;
9
17
  if (typeof settings.autoConnect !== 'undefined') {
10
18
  autoConnect = settings.autoConnect;
@@ -20,14 +28,14 @@ export function createConnection(settings) {
20
28
  if ($connection) {
21
29
  set({
22
30
  ...$connection,
23
- error
31
+ error,
24
32
  });
25
33
  }
26
34
  else {
27
35
  throw new Error(`no connection`);
28
36
  }
29
37
  }
30
- let walletProvider;
38
+ let _wallet;
31
39
  let popup;
32
40
  function fetchWallets() {
33
41
  if (typeof window !== 'undefined') {
@@ -45,7 +53,7 @@ export function createConnection(settings) {
45
53
  existingWallets.push(detail);
46
54
  set({
47
55
  ...$connection,
48
- wallets: existingWallets
56
+ wallets: existingWallets,
49
57
  });
50
58
  });
51
59
  window.dispatchEvent(new Event('eip6963:requestProvider'));
@@ -77,14 +85,25 @@ export function createConnection(settings) {
77
85
  if (existingAccount.mechanismUsed.type == 'wallet') {
78
86
  const walletMechanism = existingAccount.mechanismUsed;
79
87
  waitForWallet(walletMechanism.name)
80
- .then((walletDetails) => {
81
- walletProvider = walletDetails.provider;
88
+ .then(async (walletDetails) => {
89
+ const walletProvider = walletDetails.provider;
90
+ const chainIdAsHex = await walletProvider.request({ method: 'eth_chainId' });
91
+ const chainId = Number(chainIdAsHex).toString();
92
+ _wallet = { provider: walletProvider, chainId };
93
+ alwaysOnProvider.setWalletProvider(walletProvider);
94
+ watchForChainIdChange(_wallet.provider);
82
95
  set({
83
96
  step: 'SignedIn',
84
97
  account: existingAccount,
85
98
  mechanism: existingAccount.mechanismUsed,
86
99
  wallets: $connection.wallets,
87
- walletAccountChanged: undefined
100
+ wallet: {
101
+ provider: walletProvider,
102
+ accountChanged: undefined,
103
+ chainId,
104
+ invalidChainId: alwaysOnChainId != chainId,
105
+ switchingChain: false,
106
+ },
88
107
  });
89
108
  walletProvider.request({ method: 'eth_accounts' }).then(onAccountChanged);
90
109
  watchForAccountChange(walletProvider);
@@ -99,7 +118,7 @@ export function createConnection(settings) {
99
118
  account: existingAccount,
100
119
  mechanism: existingAccount.mechanismUsed,
101
120
  wallets: $connection.wallets,
102
- walletAccountChanged: undefined
121
+ wallet: undefined,
103
122
  });
104
123
  }
105
124
  }
@@ -139,22 +158,24 @@ export function createConnection(settings) {
139
158
  if ($connection.step !== 'NeedWalletSignature') {
140
159
  throw new Error(`invalid step: ${$connection.step}, needs to be NeedWalletSignature`);
141
160
  }
142
- const provider = walletProvider;
143
- if (!provider) {
161
+ if (!_wallet) {
144
162
  // TODO error ?
145
163
  throw new Error(`no wallet provided initialised`);
146
164
  }
165
+ const provider = _wallet.provider;
166
+ const chainId = _wallet.chainId;
147
167
  const message = originKeyMessage(origin);
148
168
  const msg = hashMessage(message);
149
169
  set({
150
170
  ...$connection,
151
- step: 'WaitingForSignature'
171
+ step: 'WaitingForSignature',
152
172
  });
153
173
  let signature;
154
174
  try {
175
+ // TODO timeout
155
176
  signature = await provider.request({
156
177
  method: 'personal_sign',
157
- params: [msg, $connection.mechanism.address]
178
+ params: [msg, $connection.mechanism.address],
158
179
  });
159
180
  }
160
181
  catch (err) {
@@ -165,9 +186,9 @@ export function createConnection(settings) {
165
186
  mechanism: {
166
187
  type: 'wallet',
167
188
  name: $connection.mechanism.name,
168
- address: $connection.mechanism.address
189
+ address: $connection.mechanism.address,
169
190
  },
170
- error: { message: 'failed to sign message', cause: err }
191
+ error: { message: 'failed to sign message', cause: err },
171
192
  });
172
193
  return;
173
194
  }
@@ -181,11 +202,11 @@ export function createConnection(settings) {
181
202
  address: originAccount.address,
182
203
  publicKey: originAccount.publicKey,
183
204
  privateKey: originAccount.privateKey,
184
- mnemonicKey: originKey
205
+ mnemonicKey: originKey,
185
206
  },
186
207
  metadata: {},
187
208
  mechanismUsed: $connection.mechanism,
188
- savedPublicKeyPublicationSignature: undefined
209
+ savedPublicKeyPublicationSignature: undefined,
189
210
  };
190
211
  set({
191
212
  ...$connection,
@@ -193,10 +214,16 @@ export function createConnection(settings) {
193
214
  mechanism: {
194
215
  type: 'wallet',
195
216
  name: $connection.mechanism.name,
196
- address: $connection.mechanism.address
217
+ address: $connection.mechanism.address,
197
218
  },
198
219
  account,
199
- walletAccountChanged: undefined // TODO check account list
220
+ wallet: {
221
+ chainId,
222
+ provider: provider,
223
+ accountChanged: undefined, // TODO check account list
224
+ invalidChainId: alwaysOnChainId != chainId,
225
+ switchingChain: false,
226
+ },
200
227
  });
201
228
  if (remember) {
202
229
  saveOriginAccount(account);
@@ -207,13 +234,29 @@ export function createConnection(settings) {
207
234
  connect({
208
235
  type: 'wallet',
209
236
  address,
210
- name: $connection.mechanism.name
237
+ name: $connection.mechanism.name,
211
238
  });
212
239
  }
213
240
  else {
214
241
  throw new Error(`need to be using a mechanism of type wallet and be SignedIN`);
215
242
  }
216
243
  }
244
+ function onChainChanged(chainIdAsHex) {
245
+ const chainId = Number(chainIdAsHex).toString();
246
+ if (_wallet) {
247
+ _wallet.chainId = chainId;
248
+ }
249
+ if ($connection.step === 'SignedIn' && $connection.wallet && $connection.wallet.chainId != chainId) {
250
+ set({
251
+ ...$connection,
252
+ wallet: {
253
+ ...$connection.wallet,
254
+ chainId,
255
+ invalidChainId: alwaysOnChainId != chainId,
256
+ },
257
+ });
258
+ }
259
+ }
217
260
  function onAccountChanged(accounts) {
218
261
  const accountsFormated = accounts.map((a) => a.toLowerCase());
219
262
  if ($connection.step === 'SignedIn' && $connection.mechanism.type === 'wallet') {
@@ -226,16 +269,22 @@ export function createConnection(settings) {
226
269
  // },
227
270
  // { requireUserConfirmationBeforeSIgnatureRequest: true }
228
271
  // );
229
- if (accountsFormated.length > 0 && accountsFormated[0] != $connection.account.address) {
272
+ if ($connection.wallet && accountsFormated.length > 0 && accountsFormated[0] != $connection.account.address) {
230
273
  set({
231
274
  ...$connection,
232
- walletAccountChanged: accountsFormated[0]
275
+ wallet: {
276
+ ...$connection.wallet,
277
+ accountChanged: accountsFormated[0],
278
+ },
233
279
  });
234
280
  }
235
- else if ($connection.walletAccountChanged) {
281
+ else if ($connection.wallet) {
236
282
  set({
237
283
  ...$connection,
238
- walletAccountChanged: undefined
284
+ wallet: {
285
+ ...$connection.wallet,
286
+ accountChanged: undefined,
287
+ },
239
288
  });
240
289
  }
241
290
  }
@@ -247,6 +296,12 @@ export function createConnection(settings) {
247
296
  function stopatchingForAccountChange(walletProvider) {
248
297
  walletProvider.removeListener('accountsChanged', onAccountChanged);
249
298
  }
299
+ function watchForChainIdChange(walletProvider) {
300
+ walletProvider.on('chainChanged', onChainChanged);
301
+ }
302
+ function stopatchingForChainIdChange(walletProvider) {
303
+ walletProvider.removeListener('chainChanged', onChainChanged);
304
+ }
250
305
  let remember = false;
251
306
  async function connect(mechanism, options) {
252
307
  remember = !(options?.doNotStoreLocally || false);
@@ -256,40 +311,49 @@ export function createConnection(settings) {
256
311
  if (walletName) {
257
312
  const wallet = $connection.wallets.find((v) => v.info.name == walletName || v.info.uuid == walletName);
258
313
  if (wallet) {
259
- if (walletProvider) {
260
- stopatchingForAccountChange(walletProvider);
314
+ if (_wallet) {
315
+ alwaysOnProvider.setWalletProvider(undefined);
316
+ stopatchingForAccountChange(_wallet.provider);
317
+ stopatchingForChainIdChange(_wallet.provider);
261
318
  }
262
- walletProvider = wallet.provider;
263
319
  const mechanism = {
264
320
  type: 'wallet',
265
- name: walletName
321
+ name: walletName,
266
322
  };
267
323
  set({
268
324
  step: 'WaitingForWalletConnection', // TODO FetchingAccounts
269
325
  mechanism,
270
- wallets: $connection.wallets
326
+ wallets: $connection.wallets,
271
327
  });
272
328
  const provider = wallet.provider;
329
+ const chainIdAsHex = await provider.request({ method: 'eth_chainId' });
330
+ const chainId = Number(chainIdAsHex).toString();
331
+ _wallet = {
332
+ chainId,
333
+ provider,
334
+ };
335
+ alwaysOnProvider.setWalletProvider(_wallet.provider);
336
+ watchForChainIdChange(_wallet.provider);
273
337
  let accounts = await provider.request({ method: 'eth_accounts' });
274
338
  accounts = accounts.map((v) => v.toLowerCase());
275
339
  if (accounts.length === 0) {
276
340
  set({
277
341
  step: 'WaitingForWalletConnection',
278
342
  mechanism,
279
- wallets: $connection.wallets
343
+ wallets: $connection.wallets,
280
344
  });
281
345
  accounts = await provider.request({ method: 'eth_requestAccounts' });
282
346
  accounts = accounts.map((v) => v.toLowerCase());
283
347
  if (accounts.length > 0) {
284
348
  if (options?.requestSignatureRightAway) {
285
- watchForAccountChange(walletProvider);
349
+ watchForAccountChange(_wallet.provider);
286
350
  set({
287
351
  step: 'NeedWalletSignature',
288
352
  mechanism: {
289
353
  ...mechanism,
290
- address: accounts[0]
354
+ address: accounts[0],
291
355
  },
292
- wallets: $connection.wallets
356
+ wallets: $connection.wallets,
293
357
  });
294
358
  await requestSignature();
295
359
  }
@@ -298,18 +362,18 @@ export function createConnection(settings) {
298
362
  step: 'NeedWalletSignature',
299
363
  mechanism: {
300
364
  ...mechanism,
301
- address: accounts[0]
365
+ address: accounts[0],
302
366
  },
303
- wallets: $connection.wallets
367
+ wallets: $connection.wallets,
304
368
  });
305
- watchForAccountChange(walletProvider);
369
+ watchForAccountChange(_wallet.provider);
306
370
  }
307
371
  }
308
372
  else {
309
373
  set({
310
374
  step: 'MechanismToChoose',
311
375
  wallets: $connection.wallets,
312
- error: { message: 'could not get any accounts' }
376
+ error: { message: 'could not get any accounts' },
313
377
  });
314
378
  }
315
379
  }
@@ -319,21 +383,21 @@ export function createConnection(settings) {
319
383
  step: 'NeedWalletSignature',
320
384
  mechanism: {
321
385
  ...mechanism,
322
- address: accounts[0]
386
+ address: accounts[0],
323
387
  },
324
- wallets: $connection.wallets
388
+ wallets: $connection.wallets,
325
389
  });
326
- watchForAccountChange(walletProvider);
390
+ watchForAccountChange(_wallet.provider);
327
391
  }
328
392
  else {
329
- watchForAccountChange(walletProvider);
393
+ watchForAccountChange(_wallet.provider);
330
394
  set({
331
395
  step: 'NeedWalletSignature',
332
396
  mechanism: {
333
397
  ...mechanism,
334
- address: accounts[0]
398
+ address: accounts[0],
335
399
  },
336
- wallets: $connection.wallets
400
+ wallets: $connection.wallets,
337
401
  });
338
402
  await requestSignature();
339
403
  }
@@ -344,7 +408,7 @@ export function createConnection(settings) {
344
408
  set({
345
409
  step: 'MechanismToChoose',
346
410
  wallets: $connection.wallets,
347
- error: { message: `failed to get wallet ${walletName}` }
411
+ error: { message: `failed to get wallet ${walletName}` },
348
412
  });
349
413
  }
350
414
  }
@@ -357,27 +421,27 @@ export function createConnection(settings) {
357
421
  set({
358
422
  step: 'WalletToChoose',
359
423
  mechanism: { type: 'wallet' },
360
- wallets: $connection.wallets
424
+ wallets: $connection.wallets,
361
425
  });
362
426
  }
363
427
  }
364
428
  else {
365
429
  popup = connectViaPopup({
366
430
  mechanism,
367
- walletHost: settings.walletHost
431
+ walletHost: settings.walletHost,
368
432
  });
369
433
  set({
370
434
  step: 'PopupLaunched',
371
435
  popupClosed: false,
372
436
  mechanism,
373
- wallets: $connection.wallets
437
+ wallets: $connection.wallets,
374
438
  });
375
439
  const unsubscribe = popup.subscribe(($popup) => {
376
440
  if ($connection?.step === 'PopupLaunched') {
377
441
  if ($popup.closed) {
378
442
  set({
379
443
  ...$connection,
380
- popupClosed: true
444
+ popupClosed: true,
381
445
  });
382
446
  }
383
447
  }
@@ -390,7 +454,7 @@ export function createConnection(settings) {
390
454
  account: result,
391
455
  mechanism,
392
456
  wallets: $connection.wallets,
393
- walletAccountChanged: undefined
457
+ wallet: undefined,
394
458
  });
395
459
  if (remember) {
396
460
  saveOriginAccount(result);
@@ -408,20 +472,22 @@ export function createConnection(settings) {
408
472
  else {
409
473
  set({
410
474
  step: 'MechanismToChoose',
411
- wallets: $connection.wallets
475
+ wallets: $connection.wallets,
412
476
  });
413
477
  }
414
478
  }
415
479
  function disconnect() {
416
480
  deleteOriginAccount();
417
- if (walletProvider) {
418
- stopatchingForAccountChange(walletProvider);
481
+ if (_wallet) {
482
+ alwaysOnProvider.setWalletProvider(undefined);
483
+ stopatchingForAccountChange(_wallet.provider);
484
+ stopatchingForChainIdChange(_wallet.provider);
419
485
  }
420
- walletProvider = undefined;
486
+ _wallet = undefined;
421
487
  set({
422
488
  step: 'Idle',
423
489
  loading: false,
424
- wallets: $connection.wallets
490
+ wallets: $connection.wallets,
425
491
  });
426
492
  }
427
493
  function back(step) {
@@ -475,11 +541,11 @@ export function createConnection(settings) {
475
541
  // }
476
542
  const currentURL = new URL(location.href);
477
543
  const entriesToAdd = [];
478
- for (const entry of currentURL.searchParams.entries()) {
479
- if (entry[0].startsWith('renraku_')) {
480
- entriesToAdd.push([entry[0].slice(`renraku_`.length), entry[1]]);
544
+ currentURL.searchParams.forEach((value, key) => {
545
+ if (key.startsWith('renraku_')) {
546
+ entriesToAdd.push([key.slice(`renraku_`.length), value]);
481
547
  }
482
- }
548
+ });
483
549
  if (currentURL.searchParams.has('eruda')) {
484
550
  entriesToAdd.push(['eruda', currentURL.searchParams.get('eruda') || '']);
485
551
  }
@@ -501,14 +567,14 @@ export function createConnection(settings) {
501
567
  }
502
568
  const account = $connection.account;
503
569
  if ($connection.mechanism.type === 'wallet') {
504
- if (!walletProvider) {
570
+ if (!_wallet) {
505
571
  throw new Error(`no provider`);
506
572
  }
507
573
  const message = originPublicKeyPublicationMessage(origin, account.signer.publicKey);
508
574
  const msg = hashMessage(message);
509
- return walletProvider.request({
575
+ return _wallet.provider.request({
510
576
  method: 'personal_sign',
511
- params: [msg, account.address]
577
+ params: [msg, account.address],
512
578
  });
513
579
  }
514
580
  if (account.savedPublicKeyPublicationSignature) {
@@ -518,6 +584,159 @@ export function createConnection(settings) {
518
584
  // this would require saving mnemonic or privatekey on etherplay localstorage though
519
585
  throw new Error(`no saved public key publication signature for ${account.address}`);
520
586
  }
587
+ async function switchWalletChain(chainId, config) {
588
+ if ($connection.step !== 'SignedIn' || !$connection.wallet) {
589
+ throw new Error(`invali state`);
590
+ }
591
+ const wallet = $connection.wallet;
592
+ // if (!wallet) {
593
+ // throw new Error(`no wallet`);
594
+ // }
595
+ try {
596
+ // attempt to switch...
597
+ set({
598
+ ...$connection,
599
+ wallet: { ...$connection.wallet, switchingChain: 'switchingChain' },
600
+ });
601
+ const result = await wallet.provider.request({
602
+ method: 'wallet_switchEthereumChain',
603
+ params: [
604
+ {
605
+ chainId: ('0x' + parseInt(chainId).toString(16)),
606
+ },
607
+ ],
608
+ });
609
+ if (!result) {
610
+ if ($connection.wallet) {
611
+ set({
612
+ ...$connection,
613
+ wallet: { ...$connection.wallet, switchingChain: false },
614
+ });
615
+ }
616
+ // logger.info(`wallet_switchEthereumChain: complete`);
617
+ // this will be taken care with `chainChanged` (but maybe it should be done there ?)
618
+ // handleNetwork(chainId);
619
+ }
620
+ else {
621
+ if ($connection.wallet) {
622
+ set({
623
+ ...$connection,
624
+ wallet: { ...$connection.wallet, switchingChain: false },
625
+ error: {
626
+ message: `Failed to switch to ${config?.chainName || `chain with id = ${chainId}`}`,
627
+ cause: result,
628
+ },
629
+ });
630
+ }
631
+ throw result;
632
+ }
633
+ }
634
+ catch (err) {
635
+ if (err.code === 4001) {
636
+ // logger.info(`wallet_addEthereumChain: failed but error code === 4001, we ignore as user rejected it`, err);
637
+ if ($connection.wallet) {
638
+ set({
639
+ ...$connection,
640
+ wallet: { ...$connection.wallet, switchingChain: false },
641
+ });
642
+ }
643
+ return;
644
+ }
645
+ // if ((err as any).code === 4902) {
646
+ else if (config && config.rpcUrls && config.rpcUrls.length > 0) {
647
+ if ($connection.wallet) {
648
+ set({
649
+ ...$connection,
650
+ wallet: { ...$connection.wallet, switchingChain: 'addingChain' },
651
+ });
652
+ }
653
+ // logger.info(`wallet_switchEthereumChain: could not switch, try adding the chain via "wallet_addEthereumChain"`);
654
+ try {
655
+ const result = await wallet.provider.request({
656
+ method: 'wallet_addEthereumChain',
657
+ params: [
658
+ {
659
+ chainId: ('0x' + parseInt(chainId).toString(16)),
660
+ rpcUrls: config.rpcUrls,
661
+ chainName: config.chainName,
662
+ blockExplorerUrls: config.blockExplorerUrls,
663
+ iconUrls: config.iconUrls,
664
+ nativeCurrency: config.nativeCurrency,
665
+ },
666
+ ],
667
+ });
668
+ if (!result) {
669
+ if ($connection.wallet) {
670
+ set({
671
+ ...$connection,
672
+ wallet: { ...$connection.wallet, switchingChain: false },
673
+ });
674
+ }
675
+ // this will be taken care with `chainChanged` (but maybe it should be done there ?)
676
+ // handleNetwork(chainId);
677
+ }
678
+ else {
679
+ if ($connection.wallet) {
680
+ set({
681
+ ...$connection,
682
+ wallet: { ...$connection.wallet, switchingChain: false },
683
+ error: {
684
+ message: `Failed to add new chain: ${config?.chainName || `chain with id = ${chainId}`}`,
685
+ cause: result,
686
+ },
687
+ });
688
+ }
689
+ // logger.info(`wallet_addEthereumChain: a non-undefinded result means an error`, result);
690
+ throw result;
691
+ }
692
+ }
693
+ catch (err) {
694
+ if (err.code !== 4001) {
695
+ if ($connection.wallet) {
696
+ set({
697
+ ...$connection,
698
+ wallet: { ...$connection.wallet, switchingChain: false },
699
+ error: {
700
+ message: `Failed to add new chain: ${config?.chainName || `chain with id = ${chainId}`}`,
701
+ cause: err,
702
+ },
703
+ });
704
+ }
705
+ // logger.info(`wallet_addEthereumChain: failed`, err);
706
+ // TODO ?
707
+ // set({
708
+ // error: {message: `Failed to add new chain`, cause: err},
709
+ // });
710
+ // for now:
711
+ throw err;
712
+ }
713
+ else {
714
+ if ($connection.wallet) {
715
+ set({
716
+ ...$connection,
717
+ wallet: { ...$connection.wallet, switchingChain: false },
718
+ });
719
+ }
720
+ // logger.info(`wallet_addEthereumChain: failed but error code === 4001, we ignore as user rejected it`, err);
721
+ return;
722
+ }
723
+ }
724
+ }
725
+ else {
726
+ const errorMessage = `Chain "${config?.chainName || `with chainId = ${chainId}`} " is not available on your wallet`;
727
+ if ($connection.wallet) {
728
+ set({
729
+ ...$connection,
730
+ wallet: { ...$connection.wallet, switchingChain: false },
731
+ error: {
732
+ message: errorMessage,
733
+ },
734
+ });
735
+ }
736
+ throw new Error(errorMessage);
737
+ }
738
+ }
739
+ }
521
740
  return {
522
741
  subscribe: _store.subscribe,
523
742
  connect,
@@ -526,6 +745,9 @@ export function createConnection(settings) {
526
745
  requestSignature,
527
746
  connectOnCurrentWalletAccount,
528
747
  disconnect,
529
- getSignatureForPublicKeyPublication
748
+ getSignatureForPublicKeyPublication,
749
+ switchWalletChain,
750
+ provider: alwaysOnProvider,
530
751
  };
531
752
  }
753
+ //# sourceMappingURL=index.js.map