@etherplay/connect 0.7.1 → 0.9.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.
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { EthereumWalletConnector } from '@etherplay/wallet-connector-ethereum';
2
- import { writable } from 'svelte/store';
2
+ import { writable } from 'sveltore';
3
3
  import { createPopupLauncher } from './popup.js';
4
4
  import { withTimeout } from './utils.js';
5
5
  import { fromEntropyKeyToMnemonic, originPublicKeyPublicationMessage, originKeyMessage, delegationMessage, delegationDigest, DELEGATION_ABI, findSavedDelegation, parsePermissionRequests, fromSignatureToKey, generateEcdhKeyPair, exportPublicKeyB64, } from '@etherplay/connect-core';
@@ -9,10 +9,17 @@ export { fromEntropyKeyToMnemonic, originPublicKeyPublicationMessage, originKeyM
9
9
  // a (chainId, contract) pair out of `savedDelegations`.
10
10
  delegationMessage, delegationDigest, DELEGATION_ABI, findSavedDelegation, };
11
11
  // Type guard - narrows Connection based on targetStep and walletOnly
12
+ // For 'WalletChosen' target: narrows to ChosenOrBetter (WalletChosen | WalletConnected | SignedIn-with-wallet)
12
13
  // For 'WalletConnected' target: narrows to ConnectedWithWallet (WalletConnected | SignedIn-with-wallet)
13
14
  // For 'SignedIn' target with walletOnly: narrows to SignedInWithWallet
14
15
  // For 'SignedIn' target (default): narrows to SignedIn
15
16
  export function isTargetStepReached(connection, targetStep, walletOnly) {
17
+ if (targetStep === 'WalletChosen') {
18
+ // For WalletChosen target, accept WalletChosen OR any higher step (WalletConnected, SignedIn-with-wallet)
19
+ return (connection.step === 'WalletChosen' ||
20
+ connection.step === 'WalletConnected' ||
21
+ (connection.step === 'SignedIn' && connection.wallet !== undefined));
22
+ }
16
23
  if (targetStep === 'WalletConnected') {
17
24
  // For WalletConnected target, accept WalletConnected OR SignedIn-with-wallet
18
25
  return connection.step === 'WalletConnected' || (connection.step === 'SignedIn' && connection.wallet !== undefined);
@@ -79,7 +86,10 @@ const stepsInProgress = [
79
86
  // Steps where the flow is at rest, waiting for a brand new user decision.
80
87
  // Note these are also the steps `ensureConnected` is commonly called from (the picker is showing),
81
88
  // so being in one of them is NOT a failure by itself: only a transition back into one after an attempt started is.
82
- const stepsAtRest = ['Idle', 'MechanismToChoose', 'WalletToChoose'];
89
+ // `WalletChosen` counts as at rest too: a failed upgrade restores it WITH a fresh error, so the
90
+ // error branch rejects before this list is even reached — and a resting `WalletChosen` carrying a
91
+ // stale error is as retryable as a picker carrying one.
92
+ const stepsAtRest = ['Idle', 'MechanismToChoose', 'WalletToChoose', 'WalletChosen'];
83
93
  // Implementation signature
84
94
  export function createConnection(settings) {
85
95
  function originToSignWith() {
@@ -119,7 +129,7 @@ export function createConnection(settings) {
119
129
  // Determine target step (defaults to 'SignedIn')
120
130
  const targetStep = settings.targetStep || 'SignedIn';
121
131
  // Determine walletOnly (defaults to false, but true implies WalletConnected target behavior for mechanism)
122
- const walletOnly = settings.walletOnly || targetStep === 'WalletConnected';
132
+ const walletOnly = settings.walletOnly || targetStep === 'WalletChosen' || targetStep === 'WalletConnected';
123
133
  let autoConnect = true;
124
134
  if (typeof settings.autoConnect !== 'undefined') {
125
135
  autoConnect = settings.autoConnect;
@@ -149,6 +159,10 @@ export function createConnection(settings) {
149
159
  // no decision to offer them. A cancelled popup is likewise a cancellation, not a failure, and rests on `Idle`.
150
160
  function setConnectionFailure(error) {
151
161
  const wallets = $connection.wallets;
162
+ // The resting states below all have `wallet: undefined`: tear down any live wallet
163
+ // first, or the wrapper would keep routing — and, while its status is 'connected',
164
+ // even SIGNING — through a wallet the state no longer shows.
165
+ teardownWallet();
152
166
  if (!walletOnly) {
153
167
  set({ step: 'MechanismToChoose', wallets, wallet: undefined, error });
154
168
  }
@@ -295,6 +309,10 @@ export function createConnection(settings) {
295
309
  watchForAccountChange(walletProvider);
296
310
  })
297
311
  .catch((err) => {
312
+ // The wallet may have been registered on the wrapper before the
313
+ // failure (e.g. getAccounts threw): tear it down — Idle carries no
314
+ // wallet, so it must not keep routing requests.
315
+ teardownWallet();
298
316
  set({ step: 'Idle', loading: false, wallet: undefined, wallets: $connection.wallets });
299
317
  });
300
318
  }
@@ -309,10 +327,59 @@ export function createConnection(settings) {
309
327
  }
310
328
  }
311
329
  }
330
+ // For WalletChosen target, restore the wallet choice without requesting accounts.
331
+ // This is the auto-connect path for the "chosen but unconnected" feature: the
332
+ // wallet provider is set so reads route through it, but no eth_requestAccounts or
333
+ // eth_accounts is called. The wallet is in 'disconnected' status.
334
+ if (targetStep === 'WalletChosen') {
335
+ autoConnectHandled = true;
336
+ const lastWallet = getLastWallet();
337
+ if (lastWallet) {
338
+ waitForWallet(lastWallet.name)
339
+ .then(async (walletDetails) => {
340
+ const walletProvider = walletDetails.walletProvider;
341
+ const chainIdAsHex = await withTimeout(walletProvider.getChainId());
342
+ const chainId = Number(chainIdAsHex).toString();
343
+ _wallet = { provider: walletProvider, chainId };
344
+ alwaysOnProviderWrapper.setWalletProvider(walletProvider.underlyingProvider);
345
+ alwaysOnProviderWrapper.setWalletStatus('disconnected');
346
+ watchForChainIdChange(_wallet.provider);
347
+ set({
348
+ step: 'WalletChosen',
349
+ mechanism: { type: 'wallet', name: lastWallet.name },
350
+ wallets: $connection.wallets,
351
+ wallet: {
352
+ provider: walletProvider,
353
+ accounts: [],
354
+ status: 'disconnected',
355
+ connecting: false,
356
+ accountChanged: undefined,
357
+ chainId,
358
+ invalidChainId: alwaysOnChainId != chainId,
359
+ switchingChain: false,
360
+ pendingRequests: [],
361
+ },
362
+ });
363
+ })
364
+ .catch((err) => {
365
+ // The wallet may have been registered on the wrapper before the
366
+ // failure (e.g. getAccounts threw): tear it down — Idle carries no
367
+ // wallet, so it must not keep routing requests.
368
+ teardownWallet();
369
+ set({ step: 'Idle', loading: false, wallet: undefined, wallets: $connection.wallets });
370
+ });
371
+ }
372
+ else {
373
+ set({ step: 'Idle', loading: false, wallet: undefined, wallets: $connection.wallets });
374
+ }
375
+ }
312
376
  // For both targets, fallback to lastWallet if no account found (or WalletConnected target)
313
377
  if (!autoConnectHandled) {
314
378
  const lastWallet = getLastWallet();
315
- if (lastWallet) {
379
+ // A lastWallet without an address was saved by selectWallet (WalletChosen flow).
380
+ // The WalletConnected/SignedIn auto-connect needs an address to restore the
381
+ // account; without one, fall back to Idle rather than constructing an invalid state.
382
+ if (lastWallet && lastWallet.address) {
316
383
  waitForWallet(lastWallet.name)
317
384
  .then(async (walletDetails) => {
318
385
  const walletProvider = walletDetails.walletProvider;
@@ -345,6 +412,10 @@ export function createConnection(settings) {
345
412
  watchForAccountChange(walletProvider);
346
413
  })
347
414
  .catch((err) => {
415
+ // The wallet may have been registered on the wrapper before the
416
+ // failure (e.g. getAccounts threw): tear it down — Idle carries no
417
+ // wallet, so it must not keep routing requests.
418
+ teardownWallet();
348
419
  set({ step: 'Idle', loading: false, wallet: undefined, wallets: $connection.wallets });
349
420
  });
350
421
  }
@@ -673,6 +744,73 @@ export function createConnection(settings) {
673
744
  function stopWatchingForChainIdChange(walletProvider) {
674
745
  walletProvider.stopListenForChainChanged(onChainChanged);
675
746
  }
747
+ // Tear down the live wallet: stop routing requests through it, stop watching it, and
748
+ // refuse signing. Any transition to a state whose `wallet` is `undefined` must go through
749
+ // this (or re-register a different wallet immediately after), otherwise the always-on
750
+ // wrapper keeps routing — and, while its status is 'connected', even SIGNING — through a
751
+ // wallet the state no longer shows.
752
+ function teardownWallet() {
753
+ if (_wallet) {
754
+ alwaysOnProviderWrapper.setWalletProvider(undefined);
755
+ alwaysOnProviderWrapper.setWalletStatus('disconnected');
756
+ stopWatchingForAccountChange(_wallet.provider);
757
+ stopWatchingForChainIdChange(_wallet.provider);
758
+ _wallet = undefined;
759
+ }
760
+ }
761
+ // Restore the WalletChosen state after a failed upgrade attempt (a rejected accounts
762
+ // request, an empty accounts answer, a dropped chainId, ...). The wallet was successfully
763
+ // CHOSEN — only the connect/accounts step failed — so the choice must not be thrown away:
764
+ // reads keep routing through the CHOSEN wallet (status: 'disconnected') and the failure is
765
+ // set as the error on the restored state. This holds even when the failed attempt targeted
766
+ // a DIFFERENT wallet: a refused accounts prompt on wallet B must not silently move the
767
+ // read path the user had chosen on wallet A.
768
+ //
769
+ // Returns false when the flow was not upgrading from WalletChosen (no chosen mechanism or
770
+ // wallet was captured), so the caller falls back to the ordinary connection-failure handling.
771
+ function restoreWalletChosenAfterFailedConnect(errorMessage, cause, chosenMechanism, chosenWallet) {
772
+ if (!chosenMechanism || !chosenWallet) {
773
+ return false;
774
+ }
775
+ if (_wallet && _wallet.provider !== chosenWallet.provider) {
776
+ // The attempt got far enough to register a DIFFERENT wallet on the wrapper: stop
777
+ // watching it before the chosen one takes the wrapper back.
778
+ stopWatchingForAccountChange(_wallet.provider);
779
+ stopWatchingForChainIdChange(_wallet.provider);
780
+ }
781
+ // The fresher chainId wins: `onChainChanged` keeps updating the live `_wallet`, so when
782
+ // the attempt was on the same provider its chainId may be newer than the captured one.
783
+ const chainId = _wallet && _wallet.provider === chosenWallet.provider ? _wallet.chainId : chosenWallet.chainId;
784
+ _wallet = { provider: chosenWallet.provider, chainId };
785
+ stopWatchingForAccountChange(_wallet.provider);
786
+ // Re-establish what the start of connect() tore down. If the failure happened early
787
+ // (getChainId threw), the wrapper provider and the chain watcher were never
788
+ // re-registered: without this the restored state would claim reads route through the
789
+ // wallet while they silently fall back to the configured endpoint. stop-then-start so
790
+ // a late failure (after re-registration) cannot register the watcher twice.
791
+ alwaysOnProviderWrapper.setWalletProvider(_wallet.provider.underlyingProvider);
792
+ alwaysOnProviderWrapper.setWalletStatus('disconnected');
793
+ stopWatchingForChainIdChange(_wallet.provider);
794
+ watchForChainIdChange(_wallet.provider);
795
+ set({
796
+ step: 'WalletChosen',
797
+ mechanism: chosenMechanism,
798
+ wallets: $connection.wallets,
799
+ wallet: {
800
+ provider: _wallet.provider,
801
+ accounts: [],
802
+ status: 'disconnected',
803
+ connecting: false,
804
+ accountChanged: undefined,
805
+ chainId,
806
+ invalidChainId: alwaysOnChainId != chainId,
807
+ switchingChain: false,
808
+ pendingRequests: [],
809
+ },
810
+ error: { message: errorMessage, cause },
811
+ });
812
+ return true;
813
+ }
676
814
  let remember = false;
677
815
  async function connect(mechanism, options) {
678
816
  if (!mechanism && (targetStep === 'WalletConnected' || walletOnly)) {
@@ -681,8 +819,17 @@ export function createConnection(settings) {
681
819
  remember = !(options?.doNotStoreLocally || false);
682
820
  if (mechanism) {
683
821
  if (mechanism.type === 'wallet') {
822
+ // Remember what connect() is about to modify, so the catch block can distinguish
823
+ // "was upgrading from WalletChosen" from "first-time connect". A failed upgrade
824
+ // restores WalletChosen, and the restored state must describe the wallet that was
825
+ // CHOSEN, which stays the read path even when the failed attempt targeted a
826
+ // different wallet.
827
+ const chosenMechanismBeforeConnect = $connection.step === 'WalletChosen' ? $connection.mechanism : undefined;
828
+ const chosenWalletBeforeConnect = $connection.step === 'WalletChosen' ? _wallet : undefined;
684
829
  const specificAddress = mechanism.address;
685
- const walletName = mechanism.name || ($connection.wallets.length == 1 ? $connection.wallets[0].info.name : undefined);
830
+ const walletName = mechanism.name ||
831
+ ($connection.step === 'WalletChosen' ? $connection.mechanism.name : undefined) ||
832
+ ($connection.wallets.length == 1 ? $connection.wallets[0].info.name : undefined);
686
833
  if (walletName) {
687
834
  const wallet = $connection.wallets.find((v) => v.info.name == walletName || v.info.uuid == walletName);
688
835
  if (wallet) {
@@ -791,7 +938,12 @@ export function createConnection(settings) {
791
938
  }
792
939
  }
793
940
  else {
794
- setConnectionFailure({ message: 'could not get any accounts' });
941
+ // An empty accounts answer after a successful request is a failed
942
+ // upgrade when coming from WalletChosen: keep the choice, exactly as
943
+ // the catch block does for a REJECTED accounts request.
944
+ if (!restoreWalletChosenAfterFailedConnect('could not get any accounts', undefined, chosenMechanismBeforeConnect, chosenWalletBeforeConnect)) {
945
+ setConnectionFailure({ message: 'could not get any accounts' });
946
+ }
795
947
  }
796
948
  }
797
949
  else {
@@ -863,36 +1015,31 @@ export function createConnection(settings) {
863
1015
  }
864
1016
  }
865
1017
  catch (err) {
866
- // Clean up the wallet provider that was set mid-connect: if the
867
- // attempt fails (4100, 4001, timeout, …) the always-on
868
- // provider wrapper would otherwise keep routing ALL requests
869
- // (including read-only RPC calls like eth_call) through the
870
- // failed wallet, breaking the dapp's data fetches.
871
- if (_wallet) {
872
- stopWatchingForChainIdChange(_wallet.provider);
873
- stopWatchingForAccountChange(_wallet.provider);
874
- alwaysOnProviderWrapper.setWalletProvider(undefined);
875
- _wallet = undefined;
876
- }
877
- // Distinguish EIP-1193 error codes so the dapp can surface a
878
- // meaningful message instead of a generic "failed to connect".
879
- // 4100 (Unauthorized): the wallet cannot authorise accounts —
880
- // it may be read-only, locked, or not yet configured (e.g.
881
- // werust's keyless provider). 4001 (User Rejected Request):
882
- // the user actively declined in the wallet popup. Anything
883
- // else is a genuine failure.
1018
+ // Distinguish EIP-1193 error codes so the dapp can surface a meaningful
1019
+ // message instead of a generic "failed to connect".
1020
+ // 4100 (Unauthorized): the wallet cannot authorise accounts — it may be
1021
+ // read-only, locked, or not yet configured (e.g. werust's keyless
1022
+ // provider). 4001 (User Rejected Request): the user actively declined in
1023
+ // the wallet popup. Anything else is a genuine failure.
884
1024
  const code = err?.code;
1025
+ let errorMessage = `failed to connect to wallet`;
885
1026
  if (code === 4100) {
886
- setConnectionFailure({
887
- message: 'The wallet is not authorized to provide accounts. It may be read-only, locked, or not yet configured.',
888
- cause: err,
889
- });
1027
+ errorMessage =
1028
+ 'The wallet is not authorized to provide accounts. It may be read-only, locked, or not yet configured.';
890
1029
  }
891
1030
  else if (code === 4001) {
892
- setConnectionFailure({ message: 'Connection request was declined.', cause: err });
1031
+ errorMessage = 'Connection request was declined.';
893
1032
  }
894
- else {
895
- setConnectionFailure({ message: `failed to connect to wallet`, cause: err });
1033
+ // If the user was upgrading from WalletChosen (they had already picked a
1034
+ // wallet for reads and then tried to connect for accounts), a failed
1035
+ // connect must NOT throw away the choice: restore WalletChosen so reads
1036
+ // keep routing through the wallet (status: 'disconnected').
1037
+ // Otherwise setConnectionFailure lands the flow on its resting step; it
1038
+ // also tears the wallet down, because every failure state's `wallet` is
1039
+ // `undefined` — a failed attempt must not keep routing requests (including
1040
+ // read-only RPC calls like eth_call) through the failed wallet.
1041
+ if (!restoreWalletChosenAfterFailedConnect(errorMessage, err, chosenMechanismBeforeConnect, chosenWalletBeforeConnect)) {
1042
+ setConnectionFailure({ message: errorMessage, cause: err });
896
1043
  }
897
1044
  }
898
1045
  }
@@ -907,6 +1054,9 @@ export function createConnection(settings) {
907
1054
  // step: 'FetchingWallets',
908
1055
  // mechanism: { type: 'wallet', wallet: undefined }
909
1056
  // });
1057
+ // The picker state drops the wallet, so any live one must be torn down here or
1058
+ // the wrapper would keep routing through a wallet the state no longer shows.
1059
+ teardownWallet();
910
1060
  set({
911
1061
  step: 'WalletToChoose',
912
1062
  mechanism: { type: 'wallet' },
@@ -1047,8 +1197,8 @@ export function createConnection(settings) {
1047
1197
  mechanism = undefined;
1048
1198
  opts = stepOrMechanismOrOptions;
1049
1199
  }
1050
- // For WalletConnected step, default to wallet mechanism
1051
- if (!mechanism && step === 'WalletConnected') {
1200
+ // For WalletConnected or WalletChosen step, default to wallet mechanism
1201
+ if (!mechanism && (step === 'WalletConnected' || step === 'WalletChosen')) {
1052
1202
  mechanism = { type: 'wallet' };
1053
1203
  }
1054
1204
  const promise = new Promise((resolve, reject) => {
@@ -1058,6 +1208,12 @@ export function createConnection(settings) {
1058
1208
  const errorOnEntry = $connection.error;
1059
1209
  // Helper to check if resolution conditions are met
1060
1210
  const canResolve = (connection) => {
1211
+ if (step === 'WalletChosen') {
1212
+ // For WalletChosen, accept WalletChosen OR any higher step
1213
+ return (connection.step === 'WalletChosen' ||
1214
+ connection.step === 'WalletConnected' ||
1215
+ (connection.step === 'SignedIn' && connection.wallet !== undefined));
1216
+ }
1061
1217
  // Must be at the target step
1062
1218
  if (connection.step !== step)
1063
1219
  return false;
@@ -1088,7 +1244,15 @@ export function createConnection(settings) {
1088
1244
  // re-enters the same picker (and clears the stale error), and we keep waiting for the user.
1089
1245
  const retryingAfterFailure = idlePassed && stepsAtRest.includes($connection.step) && !!errorOnEntry;
1090
1246
  if (!idlePassed || forceConnect || opts?.forceConnect || retryingAfterFailure) {
1091
- connect(mechanism, opts);
1247
+ if (step === 'WalletChosen') {
1248
+ const walletName = mechanism && typeof mechanism === 'object' && 'name' in mechanism
1249
+ ? mechanism.name
1250
+ : undefined;
1251
+ selectWallet(walletName, opts);
1252
+ }
1253
+ else {
1254
+ connect(mechanism, opts);
1255
+ }
1092
1256
  }
1093
1257
  // An attempt is considered started once we observe a step where the connection is in progress.
1094
1258
  // Falling back to a resting step from there means the attempt ended without reaching the target.
@@ -1150,12 +1314,7 @@ export function createConnection(settings) {
1150
1314
  function disconnect() {
1151
1315
  deleteOriginAccount();
1152
1316
  deleteLastWallet();
1153
- if (_wallet) {
1154
- alwaysOnProviderWrapper.setWalletProvider(undefined);
1155
- stopWatchingForAccountChange(_wallet.provider);
1156
- stopWatchingForChainIdChange(_wallet.provider);
1157
- }
1158
- _wallet = undefined;
1317
+ teardownWallet();
1159
1318
  unsubscribeRequestEvents();
1160
1319
  set({
1161
1320
  step: 'Idle',
@@ -1164,8 +1323,93 @@ export function createConnection(settings) {
1164
1323
  wallets: $connection.wallets,
1165
1324
  });
1166
1325
  }
1326
+ // Pick a wallet via EIP-6963 and set it as the read provider WITHOUT going through the
1327
+ // connect/accounts flow. The wallet's provider is set on the always-on wrapper so reads route
1328
+ // through it (when `prioritizeWalletProvider` is true), but no accounts are requested and
1329
+ // signing is refused (status: 'disconnected').
1330
+ //
1331
+ // This is the entry point for the `targetStep: 'WalletChosen'` flow: a blockchain indexer (or
1332
+ // any read-only consumer) can let the user pick their wallet as a decentralised read node
1333
+ // without the friction of eth_requestAccounts.
1334
+ //
1335
+ // If `name` is omitted and only one wallet is detected, auto-selects it; if multiple wallets
1336
+ // are detected, transitions to `WalletToChoose` for the user to pick.
1337
+ async function selectWallet(name, options) {
1338
+ const walletName = name || ($connection.wallets.length == 1 ? $connection.wallets[0].info.name : undefined);
1339
+ if (!walletName) {
1340
+ // Multiple wallets, no name specified - show picker. The picker state drops the
1341
+ // wallet, so a previously chosen one must be torn down here or the wrapper would
1342
+ // keep routing through a wallet the state no longer shows.
1343
+ teardownWallet();
1344
+ set({
1345
+ step: 'WalletToChoose',
1346
+ mechanism: { type: 'wallet' },
1347
+ wallets: $connection.wallets,
1348
+ wallet: undefined,
1349
+ });
1350
+ return;
1351
+ }
1352
+ const wallet = $connection.wallets.find((v) => v.info.name == walletName || v.info.uuid == walletName);
1353
+ if (!wallet) {
1354
+ // A name lookup miss attempts nothing: keep the current choice (and the read path
1355
+ // through it) and report the error on the CURRENT state — throwing the choice away
1356
+ // over a typo or a wallet uninstalled between render and click would deselect the
1357
+ // user's read path without them refusing anything.
1358
+ setError({ message: `failed to get wallet ${walletName}` });
1359
+ return;
1360
+ }
1361
+ // Clear old wallet watchers if switching from a previously chosen/connected wallet.
1362
+ // The provider is deliberately left on the wrapper until the new one replaces it
1363
+ // (below or, on failure, via setConnectionFailure's teardown), so reads do not flap
1364
+ // to the configured endpoint during the switch.
1365
+ if (_wallet) {
1366
+ stopWatchingForAccountChange(_wallet.provider);
1367
+ stopWatchingForChainIdChange(_wallet.provider);
1368
+ }
1369
+ try {
1370
+ const provider = wallet.walletProvider;
1371
+ const chainIdAsHex = await withTimeout(provider.getChainId());
1372
+ const chainId = Number(chainIdAsHex).toString();
1373
+ _wallet = { chainId, provider };
1374
+ alwaysOnProviderWrapper.setWalletProvider(provider.underlyingProvider);
1375
+ alwaysOnProviderWrapper.setWalletStatus('disconnected');
1376
+ watchForChainIdChange(provider);
1377
+ // Persist the choice so it survives reloads. The address is undefined because we
1378
+ // have not requested accounts; getLastWallet restores it as a chosen-but-unconnected
1379
+ // wallet (the WalletChosen auto-connect path).
1380
+ if (!options?.doNotStoreLocally) {
1381
+ saveLastWallet({ type: 'wallet', name: walletName });
1382
+ }
1383
+ set({
1384
+ step: 'WalletChosen',
1385
+ mechanism: { type: 'wallet', name: walletName },
1386
+ wallets: $connection.wallets,
1387
+ wallet: {
1388
+ provider: provider,
1389
+ accounts: [],
1390
+ status: 'disconnected',
1391
+ connecting: false,
1392
+ accountChanged: undefined,
1393
+ chainId,
1394
+ invalidChainId: alwaysOnChainId != chainId,
1395
+ switchingChain: false,
1396
+ pendingRequests: [],
1397
+ },
1398
+ });
1399
+ }
1400
+ catch (err) {
1401
+ // setConnectionFailure tears down the previously chosen wallet (provider still on
1402
+ // the wrapper if the new wallet's getChainId threw before setWalletProvider) before
1403
+ // landing on its `wallet: undefined` resting step.
1404
+ setConnectionFailure({ message: `failed to select wallet ${walletName}`, cause: err });
1405
+ }
1406
+ }
1167
1407
  function back(step) {
1168
1408
  popup?.cancel();
1409
+ // Every back() target drops the wallet from the state, so the live wallet goes
1410
+ // with it: leaving it would let the wrapper keep routing (and signing) through a
1411
+ // wallet the state no longer shows.
1412
+ teardownWallet();
1169
1413
  if (step === 'MechanismToChoose') {
1170
1414
  set({ step, wallets: $connection.wallets, wallet: undefined });
1171
1415
  }
@@ -1273,6 +1517,10 @@ export function createConnection(settings) {
1273
1517
  function cancel() {
1274
1518
  popup?.cancel();
1275
1519
  deleteLastWallet();
1520
+ // Landing on Idle drops the wallet from the state: tear it down too, or the
1521
+ // wrapper would keep routing (and, while its status is 'connected', SIGNING)
1522
+ // through a wallet the state no longer shows.
1523
+ teardownWallet();
1276
1524
  set({ step: 'Idle', wallet: undefined, loading: false, wallets: $connection.wallets });
1277
1525
  }
1278
1526
  // The answer a live-signing owner gives to a connect-time declaration.
@@ -1528,6 +1776,12 @@ export function createConnection(settings) {
1528
1776
  }
1529
1777
  // Method on the store to check if target step is reached
1530
1778
  function storeIsTargetStepReached(connection) {
1779
+ if (targetStep === 'WalletChosen') {
1780
+ // For WalletChosen target, accept WalletChosen OR any higher step
1781
+ return (connection.step === 'WalletChosen' ||
1782
+ connection.step === 'WalletConnected' ||
1783
+ (connection.step === 'SignedIn' && connection.wallet !== undefined));
1784
+ }
1531
1785
  if (targetStep === 'WalletConnected') {
1532
1786
  // For WalletConnected target, accept WalletConnected OR SignedIn-with-wallet
1533
1787
  return (connection.step === 'WalletConnected' || (connection.step === 'SignedIn' && connection.wallet !== undefined));
@@ -1549,6 +1803,7 @@ export function createConnection(settings) {
1549
1803
  requestSignature,
1550
1804
  connectToAddress,
1551
1805
  disconnect,
1806
+ selectWallet,
1552
1807
  getSignatureForPublicKeyPublication,
1553
1808
  getDelegation,
1554
1809
  switchWalletChain,