@etherplay/connect 0.12.0 → 0.14.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,3 +1,4 @@
1
+ import { walletPrompts } from '@etherplay/wallet-connector';
1
2
  import { EthereumWalletConnector } from '@etherplay/wallet-connector-ethereum';
2
3
  import { writable } from 'sveltore';
3
4
  import { createPopupLauncher } from './popup.js';
@@ -8,6 +9,7 @@ export { fromEntropyKeyToMnemonic, originPublicKeyPublicationMessage, originKeyM
8
9
  // digest, the ABI of the contract that verifies it, and the lookup that picks the credential for
9
10
  // a (chainId, contract) pair out of `savedDelegations`.
10
11
  delegationMessage, delegationDigest, DELEGATION_ABI, findSavedDelegation, };
12
+ export { walletPrompts };
11
13
  // THE TARGET STEPS ARE ORDERED, and this array is the only place that says so.
12
14
  //
13
15
  // `SignedIn` implies `WalletConnected` implies `WalletChosen`, so "has this connection reached the
@@ -139,18 +141,87 @@ function withoutEntropyKey(account) {
139
141
  const { mnemonicKey, ...signer } = account.signer;
140
142
  return { ...account, signer };
141
143
  }
142
- // Error thrown by `ensureConnected` when a connection attempt ends without reaching the target step.
143
- // `cause` (and the convenience `code` copied from it) is the underlying error reported by the wallet,
144
- // so callers can distinguish a user rejection (EIP-1193 code 4001) from a genuine failure.
144
+ /**
145
+ * Error thrown by `ensureConnected` when a connection attempt ends without reaching the target step.
146
+ *
147
+ * Three fields, answering three different questions:
148
+ *
149
+ * - `reason` — WHAT HAPPENED TO THIS CALL, in a closed vocabulary this library controls. Read this
150
+ * one to decide what to do. See `ConnectionFailureReason`, including its note on new members.
151
+ * - `cause` — the underlying error, exactly as whoever raised it wrote it (a wallet's EIP-1193
152
+ * error, the wallet host's `{type, message}` refusal). Unchanged by the arrival of `reason`.
153
+ * - `code` — the convenience copy of `cause.code`, so a user rejection is still `code === 4001`.
154
+ * `reason === 'wallet-rejected'` now says the same thing without the reach into `cause`.
155
+ *
156
+ * `message` is unchanged on every path, deliberately, including `'Connection cancelled'` for a
157
+ * dismissed `addressUnavailable`: the shape stays the safe one every consumer already maps to "the
158
+ * user chose not to", and `reason` says which of those it was.
159
+ *
160
+ * The third constructor argument is optional so that constructing one by hand (a test double, a
161
+ * consumer's own re-throw) keeps compiling; inside this library every failure comes from one place
162
+ * that always supplies it.
163
+ */
145
164
  export class ConnectionFailure extends Error {
146
165
  name = 'ConnectionFailure';
147
166
  code;
148
- constructor(message, cause) {
167
+ reason;
168
+ constructor(message, cause, reason = 'failed') {
149
169
  super(message);
150
170
  this.cause = cause;
151
171
  this.code = cause?.code;
172
+ this.reason = reason;
152
173
  }
153
174
  }
175
+ /**
176
+ * What an error THROWN AT US means, in the vocabulary above.
177
+ *
178
+ * One function rather than a test repeated at each catch site, because the mapping is the part that
179
+ * has to stay consistent: the same rejected wallet prompt must read as `wallet-rejected` whether it
180
+ * arrives from `eth_requestAccounts`, from a signature request, or from an attempt that rejected
181
+ * before it published anything.
182
+ *
183
+ * Only shapes this library can actually VERIFY are mapped. EIP-1193 codes are a standard the wallet
184
+ * and this library both agree on, and `cross-origin-blocked` is minted by `@etherplay/connect-core`
185
+ * in this same repo. Everything else keeps its own words on `cause` and lands on the catch-all.
186
+ *
187
+ * Note what this deliberately does NOT do: an unknown `{type}` does not become `host-refused` here,
188
+ * because an arbitrary thrown object carrying a `type` is not evidence that a HOST refused
189
+ * anything. Host refusals reach the connection through the popup catch, which uses
190
+ * `reasonForHostRefusal` instead. No path currently throws a host refusal INTO this function; if
191
+ * one ever does, it will read as `failed`, and this is the comment that says to route it through
192
+ * `reasonForHostRefusal` at that point rather than loosening the test here.
193
+ */
194
+ function reasonForError(err) {
195
+ const code = err?.code;
196
+ if (code === 4001) {
197
+ return 'wallet-rejected';
198
+ }
199
+ if (code === 4100) {
200
+ return 'wallet-unavailable';
201
+ }
202
+ if (err?.type === 'cross-origin-blocked') {
203
+ return 'cross-origin-blocked';
204
+ }
205
+ return 'failed';
206
+ }
207
+ /**
208
+ * What a WALLET HOST refusal means, in the vocabulary above.
209
+ *
210
+ * The host is deployed separately and picks its own `type` strings, so only types this library can
211
+ * verify are mapped, and everything else passes through as `host-refused` with the host's own
212
+ * `type` left intact on `cause`. Inventing a member per host vocabulary word would be claiming to
213
+ * know something this package cannot check, and would go stale the moment the host shipped a new
214
+ * one.
215
+ *
216
+ * Exactly ONE type is mapped here, `cross-origin-blocked`, which comes from
217
+ * `@etherplay/connect-core` in this repo. The other verifiable type, `cancelation` (raised by this
218
+ * package's own popup, `src/popup.ts`), is handled by the CALLER and never reaches this function:
219
+ * closing the popup sets no error at all, and `ensureConnected` reports it through its own
220
+ * cancellation branch. A `undefined` refusal likewise cannot arrive, for the same reason.
221
+ */
222
+ function reasonForHostRefusal(refusal) {
223
+ return refusal?.type === 'cross-origin-blocked' ? 'cross-origin-blocked' : 'host-refused';
224
+ }
154
225
  // Steps where a connection attempt is actively in progress: reaching one of them means an attempt started,
155
226
  // and staying in one means we should keep waiting.
156
227
  const stepsInProgress = [
@@ -200,6 +271,10 @@ export function createConnection(settings) {
200
271
  // For SignedIn target, we can auto-request signature if configured
201
272
  // For WalletConnected target, this is always false (we never auto-request signature)
202
273
  const requestSignatureAutomaticallyIfPossible = targetStep === 'SignedIn' ? settings.requestSignatureAutomaticallyIfPossible || false : false;
274
+ // Whether each in-flight request is one the user will ever be asked about, decided once when it
275
+ // starts. Declared up here because the first published state already reads the list. See `silenced`
276
+ // below for what puts an entry in it and why both answers are recorded.
277
+ const requestSilencing = new Map();
203
278
  // The list as last published. Kept so that an UNCHANGED list keeps its identity across publishes:
204
279
  // the wrapper hands back a fresh array every call, and publishing a new array (and so a new
205
280
  // `wallet` object) on every unrelated `set` would invalidate `derived` stores, `{#key}` blocks and
@@ -207,7 +282,9 @@ export function createConnection(settings) {
207
282
  // `PendingRequest` is created once and never mutated.
208
283
  let publishedPendingRequests = [];
209
284
  function currentPendingRequests() {
210
- const latest = alwaysOnProviderWrapper.getPendingRequests();
285
+ const latest = alwaysOnProviderWrapper
286
+ .getPendingRequests()
287
+ .filter((request) => requestSilencing.get(request.id) !== true);
211
288
  if (latest.length === publishedPendingRequests.length &&
212
289
  latest.every((request, i) => request === publishedPendingRequests[i])) {
213
290
  return publishedPendingRequests;
@@ -269,12 +346,26 @@ export function createConnection(settings) {
269
346
  // list has not changed, the wallet object keeps its identity and consumers' `derived` stores,
270
347
  // `{#key}` blocks and effect dependencies do not re-run on an unrelated publish.
271
348
  const incomingWallet = connection.wallet;
349
+ // WHICH wallet this provider belongs to.
350
+ //
351
+ // The live wallet's own `info` when the state is about the live wallet, which is every state this
352
+ // library builds and is the EXACT answer: it came from the handle that was chosen, rather than
353
+ // from a scan over a list where provider identity may not be unique.
354
+ //
355
+ // The scan is the fallback for anything else, and what the caller spread in is the fallback after
356
+ // that, so a state rebuilt from a published one keeps the `info` it was published with even once
357
+ // the handle has left the list. That last one is deliberately allowed to be STALE: a name that is
358
+ // one publish old is better than a state that cannot say which wallet it is about, and the field
359
+ // is re-derived on the next transition.
360
+ const info = (_wallet && _wallet.provider === connection.wallet.provider ? _wallet.info : undefined) ??
361
+ walletInfoIn(connection.wallets, connection.wallet.provider) ??
362
+ incomingWallet.info;
272
363
  $connection = {
273
364
  ...connection,
274
365
  pendingRequests,
275
- wallet: incomingWallet.pendingRequests === pendingRequests
366
+ wallet: incomingWallet.pendingRequests === pendingRequests && incomingWallet.info === info
276
367
  ? incomingWallet
277
- : { ...connection.wallet, pendingRequests },
368
+ : { ...connection.wallet, pendingRequests, info },
278
369
  };
279
370
  _store.set($connection);
280
371
  return $connection;
@@ -299,12 +390,77 @@ export function createConnection(settings) {
299
390
  // disconnect followed by a reconnect left the app blind to every subsequent wallet prompt. The
300
391
  // wrapper is created here and lives exactly as long as this connection, so there is nothing to
301
392
  // release.
302
- alwaysOnProviderWrapper.onRequest(() => {
393
+ alwaysOnProviderWrapper.onRequest((event) => {
394
+ // Decide, and RECORD, whether this request is one the user will ever be asked about, before the
395
+ // list below is read. See `silenced`.
396
+ silenced(event);
303
397
  // Republish. `set` re-reads the wrapper, so this needs to say nothing about the list itself,
304
398
  // and it must run whether or not a wallet is currently in the state: a request outstanding
305
399
  // while the flow rests on `wallet: undefined` is exactly the case that used to go unreported.
306
400
  set($connection);
307
401
  });
402
+ // NOTHING CAN BE OUTSTANDING WITH A WALLET THAT ANSWERS BY ITSELF.
403
+ //
404
+ // `pendingRequests` means "your wallet is holding something and is waiting for you", and every
405
+ // consumer renders it as a question on the user's screen: a modal saying the wallet will ask them
406
+ // to confirm, a cancel affordance, an unload guard. A wallet that declares `info.autoApproves`
407
+ // signs with no dialog, so all three describe an event that does not happen, and each consumer
408
+ // would otherwise have to infer that for itself from a fact only the wallet knows.
409
+ //
410
+ // So the announcement is dropped HERE, at the connection, and not in the wrapper. The wrapper's
411
+ // own bookkeeping stays honest and complete (it is what tells a request's end from its start, and
412
+ // it is per-connector, so silencing there would have to be implemented again by every connector).
413
+ // This library's published surface is the one that claims a user is being asked, and it is the one
414
+ // that stops claiming it.
415
+ //
416
+ // The decision is made ONCE, when the request STARTS, and then remembered by id. A request can
417
+ // outlive the wallet that started it (the user is free to switch wallet while one is outstanding,
418
+ // see the ADR), and "was anybody ever going to be asked about this" is a fact about the wallet that
419
+ // TOOK it, not about whichever wallet is current when it ends. Deciding again at the end would
420
+ // silence a real prompt, or announce the end of something never announced as started.
421
+ //
422
+ // `walletPrompts` is the default: a wallet that says nothing prompts, so every existing caller and
423
+ // every discovered wallet is untouched by this.
424
+ function activeWalletAutoApproves() {
425
+ // `_wallet.info` and not a lookup: see the declaration of `_wallet`. This is the one answer that
426
+ // must not be guessed, because guessing it wrong in the silencing direction hides a prompt the
427
+ // user is looking at.
428
+ return !!_wallet && !walletPrompts(_wallet.info);
429
+ }
430
+ /**
431
+ * Is this event about a request the user was never going to see?
432
+ *
433
+ * Idempotent, and order-independent: the store's own subscription and every consumer subscription
434
+ * ask, in whatever order they were registered, and the first to ask about a `requestStart` is the
435
+ * one that decides. Every later ask reads that decision back, INCLUDING A NEGATIVE ONE.
436
+ *
437
+ * Recording the negative answer too is what makes the order not matter. The decision is a question
438
+ * about the live wallet, and publishing between handlers (the store's own subscription calls `set`,
439
+ * which runs consumer subscribers synchronously) is an opportunity for the live wallet to change
440
+ * under the remaining handlers. Nothing reachable today flips it in that window, but a half-silenced
441
+ * request is exactly the split this feature exists to avoid: announced on `pendingRequests` and
442
+ * missing from `onRequest`, or the reverse.
443
+ */
444
+ function silenced(event) {
445
+ const decided = requestSilencing.get(event.request.id);
446
+ if (decided !== undefined) {
447
+ if (event.type === 'requestEnd') {
448
+ // Forgotten only once every handler has been given this event, so that a consumer cannot be
449
+ // handed the END of a request whose START it never saw. A native microtask rather than a
450
+ // timer: the whole synchronous emit loop has run by then, and no test clock can defer it.
451
+ Promise.resolve().then(() => requestSilencing.delete(event.request.id));
452
+ }
453
+ return decided;
454
+ }
455
+ if (event.type !== 'requestStart') {
456
+ // An end with no decision on record is a request that started before this connection was
457
+ // listening. It was never silenced, so it is not silenced now.
458
+ return false;
459
+ }
460
+ const silence = activeWalletAutoApproves();
461
+ requestSilencing.set(event.request.id, silence);
462
+ return silence;
463
+ }
308
464
  // Where the flow comes to rest when a connection attempt fails.
309
465
  //
310
466
  // The rule: rest on the step that offers the user a real next decision, and never on a step this app has
@@ -318,6 +474,11 @@ export function createConnection(settings) {
318
474
  //
319
475
  // Auto-connect failures follow the same rule and rest on `Idle`: the user asked for nothing, so there is
320
476
  // no decision to offer them. A cancelled popup is likewise a cancellation, not a failure, and rests on `Idle`.
477
+ //
478
+ // `error` carries a REQUIRED `reason` (see `ConnectionFailureReason`). That is not decoration: a
479
+ // pending `ensureConnected` copies it onto the `ConnectionFailure` it rejects with, so what the
480
+ // app renders and what the caller catches cannot disagree, and requiring it here is what makes
481
+ // the compiler enumerate the producers instead of leaving the next one to remember.
321
482
  function setConnectionFailure(error) {
322
483
  const wallets = $connection.wallets;
323
484
  // Every resting state below has `wallet: undefined`, so `set` tears the live wallet down.
@@ -400,6 +561,51 @@ export function createConnection(settings) {
400
561
  // The reason most recently PUBLISHED, so that a dismissal arriving in the brief window where an
401
562
  // attempt has cleared the field still names the address the user was actually looking at.
402
563
  let lastPublishedAddressUnavailable;
564
+ /**
565
+ * The address-bound `ensureConnected` calls that are still live on this connection, in the order
566
+ * they were made. Mirrors `addressUnavailableAcknowledgements` above: per connection, per address,
567
+ * kept by the one thing that knows.
568
+ *
569
+ * WHY IT EXISTS. A connection has one wallet, one account and one `addressUnavailable` slot, so a
570
+ * second call naming a DIFFERENT address supersedes the first: the newer request takes the slot,
571
+ * the older one loses the state it was resting on and comes to rest with nothing in progress. That
572
+ * is a real answer and it was already delivered honestly (`could not reach ...`, never a
573
+ * cancellation the user did not make), but it arrived looking exactly like every other
574
+ * come-to-rest, so no consumer could tell "your own app asked for something else" from "this
575
+ * connection cannot get there". Only ONE call knows the difference and it is not the one being
576
+ * answered, which is why supersession cannot be read off the connection state and needs a
577
+ * registry.
578
+ *
579
+ * Registration is a monotonic id rather than a set, because the question is ordered: an OLDER
580
+ * request is superseded by a NEWER one, never the other way round.
581
+ *
582
+ * WHAT IT IS AND IS NOT. `superseded` says "a later live request names another account", which is
583
+ * an over-approximation of "that request is what displaced me": if some third thing (the app's own
584
+ * `connect()`, a disconnect) ends both at once, the older is still labelled superseded. That is
585
+ * the harmless direction, since the newer request was going to take the slot anyway, and the
586
+ * remedy the label implies (retry) is the right one either way. The opposite error is avoided by
587
+ * construction: a call that resolves without ever waiting returns before it registers.
588
+ *
589
+ * An entry lives exactly as long as its promise is unsettled, which for an abandoned call means as
590
+ * long as the promise itself: this map holds no more than the pending calls already do.
591
+ */
592
+ let addressBoundRequests = 0;
593
+ const liveAddressBoundRequests = new Map();
594
+ function registerAddressBoundRequest(address) {
595
+ const id = ++addressBoundRequests;
596
+ liveAddressBoundRequests.set(id, address.toLowerCase());
597
+ return id;
598
+ }
599
+ /** Is a LATER live request naming a DIFFERENT address, i.e. holding the slot this one needs? */
600
+ function isSupersededBy(id, address) {
601
+ const asked = address.toLowerCase();
602
+ for (const [otherId, otherAddress] of liveAddressBoundRequests) {
603
+ if (otherId > id && otherAddress !== asked) {
604
+ return true;
605
+ }
606
+ }
607
+ return false;
608
+ }
403
609
  // How many times the user's WALLET has announced a DIFFERENT set of accounts. It is the unit
404
610
  // `ensureConnected` retries on, and it is the honest one: a retry is a response to the user
405
611
  // having done something in their wallet, so at most one attempt per announcement bounds the work
@@ -413,6 +619,18 @@ export function createConnection(settings) {
413
619
  // re-prompting for an account because the user switched network answers a question they did not
414
620
  // ask.
415
621
  let walletAnnouncements = 0;
622
+ // THE LIVE WALLET, and WHICH wallet it is.
623
+ //
624
+ // `info` is carried here, from the handle that was chosen, rather than looked up from the provider
625
+ // when it is needed. The lookup is a scan of `wallets` by provider identity, and provider identity
626
+ // is not a key: two handles supplied by a caller may wrap the SAME provider object under different
627
+ // names, at which point the scan answers with whichever comes first. That is a wrong name on the
628
+ // published state, and, worse, a wrong answer to "does this wallet prompt", which could silence a
629
+ // request the user is genuinely being asked about. Every site that registers a wallet has the
630
+ // handle in hand, so the exact answer is free.
631
+ //
632
+ // The key is REQUIRED (and may hold `undefined`) so that a new registration site has to say what it
633
+ // knows rather than inherit a default by forgetting.
416
634
  let _wallet;
417
635
  let popup;
418
636
  // Wallet announcements are not guaranteed to be unique.
@@ -434,17 +652,53 @@ export function createConnection(settings) {
434
652
  }
435
653
  return !!a.info.rdns && a.info.rdns === b.info.rdns;
436
654
  }
655
+ function announceWallet(detail) {
656
+ const existingWallets = $connection.wallets;
657
+ if (existingWallets.some((existing) => isSameWallet(existing, detail))) {
658
+ return;
659
+ }
660
+ set({
661
+ ...$connection,
662
+ wallets: [...existingWallets, detail],
663
+ });
664
+ }
665
+ // WHERE THIS CONNECTION'S WALLETS COME FROM: the caller, or the page.
666
+ //
667
+ // A caller that supplies `wallets` gets exactly those and DISCOVERY IS NOT RUN, so no
668
+ // `eip6963:requestProvider` is dispatched and no installed extension can announce itself into this
669
+ // list. See the setting's doc on the implementation signature: a wallet the app constructed and a
670
+ // wallet the user installed are two different populations, and the whole reason to supply one is
671
+ // to say which of them this connection is about.
672
+ //
673
+ // The supplied handles go through the same `announceWallet` as discovered ones, so a caller that
674
+ // hands over the same wallet twice gets it once, exactly as a wallet announcing itself twice does.
437
675
  function fetchWallets() {
438
- walletConnector.fetchWallets((detail) => {
439
- const existingWallets = $connection.wallets;
440
- if (existingWallets.some((existing) => isSameWallet(existing, detail))) {
441
- return;
676
+ // `!== undefined`, so an EMPTY supplied list is still a supplied list: see the setting's doc.
677
+ if (settings.wallets !== undefined) {
678
+ for (const walletHandle of settings.wallets) {
679
+ announceWallet(walletHandle);
442
680
  }
443
- set({
444
- ...$connection,
445
- wallets: [...existingWallets, detail],
446
- });
447
- });
681
+ return;
682
+ }
683
+ walletConnector.fetchWallets(announceWallet);
684
+ }
685
+ /**
686
+ * The `info` of the announced handle this provider belongs to, or NOTHING IF IT IS AMBIGUOUS.
687
+ *
688
+ * The fallback for a wallet this connection did not register itself (a custom connector may hand
689
+ * over a provider without a handle behind it), which is why it is a scan rather than a key lookup:
690
+ * provider identity is not a key, and a caller supplying two handles that wrap the same provider
691
+ * object under different names makes it answer with whichever comes first.
692
+ *
693
+ * So an ambiguous scan answers with nothing at all. Absent is read as the LOUD default everywhere
694
+ * it matters, which is the direction a wrong guess must fail in: naming the wrong wallet is a
695
+ * cosmetic error, while inheriting the wrong wallet's `autoApproves` would silence a request the
696
+ * user is genuinely being asked about. `_wallet.info` is the exact answer and is preferred over
697
+ * this wherever it is available.
698
+ */
699
+ function walletInfoIn(wallets, provider) {
700
+ const matches = wallets.filter((walletHandle) => walletHandle.walletProvider === provider);
701
+ return matches.length === 1 ? matches[0].info : undefined;
448
702
  }
449
703
  function waitForWallet(name) {
450
704
  return new Promise((resolve, reject) => {
@@ -503,7 +757,7 @@ export function createConnection(settings) {
503
757
  const walletProvider = walletDetails.walletProvider;
504
758
  const chainIdAsHex = await withTimeout(walletProvider.getChainId());
505
759
  const chainId = Number(chainIdAsHex).toString();
506
- _wallet = { provider: walletProvider, chainId };
760
+ _wallet = { provider: walletProvider, chainId, info: walletDetails.info };
507
761
  alwaysOnProviderWrapper.setWalletProvider(walletProvider.underlyingProvider);
508
762
  watchForChainIdChange(_wallet.provider);
509
763
  let accounts = [];
@@ -558,7 +812,7 @@ export function createConnection(settings) {
558
812
  const walletProvider = walletDetails.walletProvider;
559
813
  const chainIdAsHex = await withTimeout(walletProvider.getChainId());
560
814
  const chainId = Number(chainIdAsHex).toString();
561
- _wallet = { provider: walletProvider, chainId };
815
+ _wallet = { provider: walletProvider, chainId, info: walletDetails.info };
562
816
  alwaysOnProviderWrapper.setWalletProvider(walletProvider.underlyingProvider);
563
817
  alwaysOnProviderWrapper.setWalletStatus('disconnected');
564
818
  watchForChainIdChange(_wallet.provider);
@@ -600,7 +854,7 @@ export function createConnection(settings) {
600
854
  const walletProvider = walletDetails.walletProvider;
601
855
  const chainIdAsHex = await withTimeout(walletProvider.getChainId());
602
856
  const chainId = Number(chainIdAsHex).toString();
603
- _wallet = { provider: walletProvider, chainId };
857
+ _wallet = { provider: walletProvider, chainId, info: walletDetails.info };
604
858
  alwaysOnProviderWrapper.setWalletProvider(walletProvider.underlyingProvider);
605
859
  watchForChainIdChange(_wallet.provider);
606
860
  let accounts = [];
@@ -776,7 +1030,10 @@ export function createConnection(settings) {
776
1030
  name: $connection.mechanism.name,
777
1031
  address: $connection.mechanism.address,
778
1032
  },
779
- error: { message: 'failed to sign message', cause: err },
1033
+ // A declined signature prompt is the same 4001 a declined connect is, and the same
1034
+ // mapping names it: an app that offers "try again" on a rejection must not have to know
1035
+ // which prompt was rejected to recognise one.
1036
+ error: { message: 'failed to sign message', cause: err, reason: reasonForError(err) },
780
1037
  });
781
1038
  return;
782
1039
  }
@@ -1030,7 +1287,11 @@ export function createConnection(settings) {
1030
1287
  //
1031
1288
  // Returns false when the flow was not upgrading from WalletChosen (no chosen mechanism or
1032
1289
  // wallet was captured), so the caller falls back to the ordinary connection-failure handling.
1033
- function restoreWalletChosenAfterFailedConnect(errorMessage, cause, chosenMechanism, chosenWallet) {
1290
+ function restoreWalletChosenAfterFailedConnect(errorMessage, cause,
1291
+ // Taken as an argument rather than derived from `cause` here: this function is the RESTING
1292
+ // half of a failure whose other half is `setConnectionFailure`, and the two must label the
1293
+ // same event identically. An empty accounts answer has no `cause` to derive anything from.
1294
+ reason, chosenMechanism, chosenWallet) {
1034
1295
  if (!chosenMechanism || !chosenWallet) {
1035
1296
  return false;
1036
1297
  }
@@ -1043,7 +1304,7 @@ export function createConnection(settings) {
1043
1304
  // The fresher chainId wins: `onChainChanged` keeps updating the live `_wallet`, so when
1044
1305
  // the attempt was on the same provider its chainId may be newer than the captured one.
1045
1306
  const chainId = _wallet && _wallet.provider === chosenWallet.provider ? _wallet.chainId : chosenWallet.chainId;
1046
- _wallet = { provider: chosenWallet.provider, chainId };
1307
+ _wallet = { provider: chosenWallet.provider, chainId, info: chosenWallet.info };
1047
1308
  stopWatchingForAccountChange(_wallet.provider);
1048
1309
  // Re-establish what the start of connect() tore down. If the failure happened early
1049
1310
  // (getChainId threw), the wrapper provider and the chain watcher were never
@@ -1068,7 +1329,7 @@ export function createConnection(settings) {
1068
1329
  invalidChainId: alwaysOnChainId != chainId,
1069
1330
  switchingChain: false,
1070
1331
  },
1071
- error: { message: errorMessage, cause },
1332
+ error: { message: errorMessage, cause, reason },
1072
1333
  });
1073
1334
  return true;
1074
1335
  }
@@ -1219,6 +1480,7 @@ export function createConnection(settings) {
1219
1480
  _wallet = {
1220
1481
  chainId,
1221
1482
  provider,
1483
+ info: wallet.info,
1222
1484
  };
1223
1485
  // TODO
1224
1486
  alwaysOnProviderWrapper.setWalletProvider(_wallet.provider.underlyingProvider);
@@ -1303,8 +1565,12 @@ export function createConnection(settings) {
1303
1565
  // An empty accounts answer after a successful request is a failed
1304
1566
  // upgrade when coming from WalletChosen: keep the choice, exactly as
1305
1567
  // the catch block does for a REJECTED accounts request.
1306
- if (!restoreWalletChosenAfterFailedConnect('could not get any accounts', undefined, chosenMechanismBeforeConnect, chosenWalletBeforeConnect)) {
1307
- setConnectionFailure({ message: 'could not get any accounts' });
1568
+ if (!restoreWalletChosenAfterFailedConnect('could not get any accounts', undefined,
1569
+ // `no-accounts`, NOT a cancellation. The wallet answered, and answered with
1570
+ // nothing: from the outside that looks like a refusal and it is not one, which
1571
+ // is exactly the aliasing a consumer's own sniffing module got wrong.
1572
+ 'no-accounts', chosenMechanismBeforeConnect, chosenWalletBeforeConnect)) {
1573
+ setConnectionFailure({ message: 'could not get any accounts', reason: 'no-accounts' });
1308
1574
  }
1309
1575
  }
1310
1576
  }
@@ -1377,6 +1643,12 @@ export function createConnection(settings) {
1377
1643
  // read-only, locked, or not yet configured (e.g. werust's keyless
1378
1644
  // provider). 4001 (User Rejected Request): the user actively declined in
1379
1645
  // the wallet popup. Anything else is a genuine failure.
1646
+ // The message picked per code below and the `reason` a consumer reads instead of
1647
+ // re-deriving it are two lists over the same two codes. They agree today and nothing
1648
+ // COUPLES them: a third message added here without a matching member in
1649
+ // `reasonForError` would be prose the discriminant does not know about. Deriving the
1650
+ // message from the reason would fix that and would change every message string, which
1651
+ // this change is not allowed to do.
1380
1652
  const code = err?.code;
1381
1653
  let errorMessage = `failed to connect to wallet`;
1382
1654
  if (code === 4100) {
@@ -1394,14 +1666,21 @@ export function createConnection(settings) {
1394
1666
  // also tears the wallet down, because every failure state's `wallet` is
1395
1667
  // `undefined` — a failed attempt must not keep routing requests (including
1396
1668
  // read-only RPC calls like eth_call) through the failed wallet.
1397
- if (!restoreWalletChosenAfterFailedConnect(errorMessage, err, chosenMechanismBeforeConnect, chosenWalletBeforeConnect)) {
1398
- setConnectionFailure({ message: errorMessage, cause: err });
1669
+ // ONE derivation, read by both halves of the failure. The restore path and
1670
+ // `setConnectionFailure` are two landings for the same event, so a reason computed
1671
+ // twice is two chances to compute it differently.
1672
+ const reason = reasonForError(err);
1673
+ if (!restoreWalletChosenAfterFailedConnect(errorMessage, err, reason, chosenMechanismBeforeConnect, chosenWalletBeforeConnect)) {
1674
+ setConnectionFailure({ message: errorMessage, cause: err, reason });
1399
1675
  }
1400
1676
  }
1401
1677
  }
1402
1678
  else {
1403
1679
  console.error(`failed to get wallet ${walletName}`, $connection.wallets);
1404
- setConnectionFailure({ message: `failed to get wallet ${walletName}` });
1680
+ // The catch-all, deliberately: the named wallet is not among the announced ones (a typo, an
1681
+ // extension uninstalled between render and click). It gets no member of its own because it
1682
+ // is not a state the user can answer, and the message already names the wallet.
1683
+ setConnectionFailure({ message: `failed to get wallet ${walletName}`, reason: 'failed' });
1405
1684
  }
1406
1685
  }
1407
1686
  else {
@@ -1533,7 +1812,11 @@ export function createConnection(settings) {
1533
1812
  loading: false,
1534
1813
  wallet: undefined,
1535
1814
  wallets: $connection.wallets,
1536
- error: canceled ? undefined : { message: refusal.message || 'sign in failed', cause: refusal },
1815
+ // The host's own `type` stays on `cause`, untouched; `reason` pins only what this library
1816
+ // can verify (`cross-origin-blocked`) and passes anything else through as `host-refused`.
1817
+ error: canceled
1818
+ ? undefined
1819
+ : { message: refusal.message || 'sign in failed', cause: refusal, reason: reasonForHostRefusal(refusal) },
1537
1820
  });
1538
1821
  }
1539
1822
  finally {
@@ -1678,6 +1961,10 @@ export function createConnection(settings) {
1678
1961
  // Dismissals of the address-unavailable state that happened BEFORE this call: only a later one
1679
1962
  // is this call's answer.
1680
1963
  const acknowledgementsOnEntry = askedAddress ? acknowledgementsFor(askedAddress) : 0;
1964
+ // THIS CALL'S PLACE IN THE QUEUE for the connection's one account slot, kept only while the
1965
+ // call is live (see `settle`). Registered here, after the early resolve above has already
1966
+ // returned, so a call that never waited never claims the slot at all.
1967
+ const addressBoundRequestId = askedAddress ? registerAddressBoundRequest(askedAddress) : undefined;
1681
1968
  // WHAT STOPS "try again" FROM BECOMING A LOOP: at most one attempt per wallet announcement.
1682
1969
  //
1683
1970
  // Our own attempts do not bump `walletAnnouncements`, so an attempt can never start another one
@@ -1715,9 +2002,36 @@ export function createConnection(settings) {
1715
2002
  settled = true;
1716
2003
  // unsubscribe can still be undefined here if the store settles during the initial (synchronous) subscription
1717
2004
  unsubscribe?.();
2005
+ // This call is over, so it stops competing for the account slot and stops being counted
2006
+ // against anybody.
2007
+ //
2008
+ // HONEST NOTE, because no test fails if this is deleted: it is defensive. For it to change
2009
+ // an observable label, a NEWER address-bound call would have to settle while an OLDER one
2010
+ // stays live, and every way a newer call can settle publishes a state that also ends an
2011
+ // older call resting on it — while an older call that is still waiting is waiting on
2012
+ // something in progress, which publishes again in its turn. Kept anyway: it also bounds the
2013
+ // map, and "the registry contains the live requests" is cheaper to keep true than to reason
2014
+ // about every time somebody adds a settle path.
2015
+ if (addressBoundRequestId !== undefined) {
2016
+ liveAddressBoundRequests.delete(addressBoundRequestId);
2017
+ }
1718
2018
  perform();
1719
2019
  };
1720
- const cancelled = () => settle(() => reject(new ConnectionFailure('Connection cancelled')));
2020
+ /**
2021
+ * THE ONE PLACE A `ConnectionFailure` IS BUILT, and it takes the reason first.
2022
+ *
2023
+ * Not tidiness: `reason` is the field that must never be forgotten, and a rule kept at four
2024
+ * call sites is a rule that is kept at three of them a year from now. This codebase has
2025
+ * twice fixed bugs whose root cause was exactly that (`pendingRequests`, wallet teardown).
2026
+ */
2027
+ const failWith = (reason, message, cause) => settle(() => reject(new ConnectionFailure(message, cause, reason)));
2028
+ /**
2029
+ * The MESSAGE is the same for both, and that is the point: every consumer already maps
2030
+ * `'Connection cancelled'` to "the user chose not to" and shows nothing, so a dismissed
2031
+ * `addressUnavailable` must keep arriving in that shape and must not paint a red banner over
2032
+ * a decision. What was missing is WHICH decision, and that is what `reason` adds.
2033
+ */
2034
+ const cancelled = (reason) => failWith(reason, 'Connection cancelled');
1721
2035
  /**
1722
2036
  * Start an attempt and stay honest about it while it runs.
1723
2037
  *
@@ -1743,7 +2057,7 @@ export function createConnection(settings) {
1743
2057
  evaluate($connection);
1744
2058
  }, (err) => {
1745
2059
  attemptsInFlight--;
1746
- settle(() => reject(new ConnectionFailure(err?.message || `could not reach ${step}`, err)));
2060
+ failWith(reasonForError(err), err?.message || `could not reach ${step}`, err);
1747
2061
  });
1748
2062
  };
1749
2063
  /** Is the connection sitting on the account the caller asked for, ready to be asked to sign? */
@@ -1944,7 +2258,7 @@ export function createConnection(settings) {
1944
2258
  // disappearing. Several things clear that field and only one of them is a decision; and a
1945
2259
  // decision about one address is not an answer to a request about another.
1946
2260
  if (askedAddress && acknowledgementsFor(askedAddress) !== acknowledgementsOnEntry) {
1947
- cancelled();
2261
+ cancelled('address-unavailable-acknowledged');
1948
2262
  return;
1949
2263
  }
1950
2264
  if (stepsInProgress.includes(connection.step)) {
@@ -1958,18 +2272,21 @@ export function createConnection(settings) {
1958
2272
  // a generic cancellation.
1959
2273
  const error = connection.error;
1960
2274
  if (error && error !== errorOnEntry) {
1961
- settle(() => reject(new ConnectionFailure(error.message, error.cause)));
2275
+ // The reason is COPIED, never re-derived. Deriving it again here from `message` or from
2276
+ // `cause` is how the state an app renders and the error a caller catches come to disagree
2277
+ // about one event: they are the same failure, so they carry the same label by construction.
2278
+ failWith(error.reason, error.message, error.cause);
1962
2279
  return;
1963
2280
  }
1964
2281
  // Reject on disconnect/back to Idle
1965
2282
  if (connection.step === 'Idle' && idlePassed) {
1966
- cancelled();
2283
+ cancelled('cancelled');
1967
2284
  return;
1968
2285
  }
1969
2286
  // The attempt went back to a resting step without an error: it was aborted (back/cancel).
1970
2287
  // This must never trigger on a resting step we merely started from, hence `attemptStarted`.
1971
2288
  if (attemptStarted && stepsAtRest.includes(connection.step)) {
1972
- cancelled();
2289
+ cancelled('cancelled');
1973
2290
  return;
1974
2291
  }
1975
2292
  // THE WALLET IS NOT ON THE ACCOUNT THIS CALL ASKED FOR, and the connection is resting on a
@@ -2007,13 +2324,26 @@ export function createConnection(settings) {
2007
2324
  // make impossible, and it is stated as a POSITIVE list (`awaitingUserReason`) on purpose:
2008
2325
  // a new step, or a new resting reason, is unreachable-by-default rather than a fresh way
2009
2326
  // to hang.
2010
- const reason = awaitingUserReason(connection);
2011
- if (!reason) {
2327
+ const waitReason = awaitingUserReason(connection);
2328
+ if (!waitReason) {
2012
2329
  // The message names where the connection actually is, including the wallet's status,
2013
2330
  // because the likeliest way to arrive here is a wallet that went locked or was revoked
2014
2331
  // between the attempt finishing and this state being published.
2015
2332
  const wallet = connection.wallet ? ` (wallet ${connection.wallet.status})` : '';
2016
- settle(() => reject(new ConnectionFailure(`could not reach ${step}: the connection is at ${connection.step}${wallet} and nothing is in progress`)));
2333
+ // SUPERSEDED, when a NEWER address-bound call is holding the connection's one account
2334
+ // slot: this call did not come to rest because the connection cannot get there, it came to
2335
+ // rest because the app itself asked for a different account in the meantime. The two are
2336
+ // indistinguishable from the state (the newer request took the `addressUnavailable` slot
2337
+ // with it, so there is nothing left on the connection to read), and telling them apart is
2338
+ // the difference between "this connection is stuck" and "retry, it was your own doing".
2339
+ //
2340
+ // The MESSAGE is unchanged, deliberately: it is the honest `could not reach ...` this path
2341
+ // has always produced, and specifically not a cancellation, because the user decided
2342
+ // nothing.
2343
+ const superseded = askedAddress !== undefined &&
2344
+ addressBoundRequestId !== undefined &&
2345
+ isSupersededBy(addressBoundRequestId, askedAddress);
2346
+ failWith(superseded ? 'superseded' : 'unreachable', `could not reach ${step}: the connection is at ${connection.step}${wallet} and nothing is in progress`);
2017
2347
  }
2018
2348
  };
2019
2349
  unsubscribe = _store.subscribe(evaluate);
@@ -2068,7 +2398,7 @@ export function createConnection(settings) {
2068
2398
  // through it) and report the error on the CURRENT state — throwing the choice away
2069
2399
  // over a typo or a wallet uninstalled between render and click would deselect the
2070
2400
  // user's read path without them refusing anything.
2071
- setError({ message: `failed to get wallet ${walletName}` });
2401
+ setError({ message: `failed to get wallet ${walletName}`, reason: 'failed' });
2072
2402
  return;
2073
2403
  }
2074
2404
  // Clear old wallet watchers if switching from a previously chosen/connected wallet.
@@ -2083,7 +2413,7 @@ export function createConnection(settings) {
2083
2413
  const provider = wallet.walletProvider;
2084
2414
  const chainIdAsHex = await withTimeout(provider.getChainId());
2085
2415
  const chainId = Number(chainIdAsHex).toString();
2086
- _wallet = { chainId, provider };
2416
+ _wallet = { chainId, provider, info: wallet.info };
2087
2417
  alwaysOnProviderWrapper.setWalletProvider(provider.underlyingProvider);
2088
2418
  alwaysOnProviderWrapper.setWalletStatus('disconnected');
2089
2419
  watchForChainIdChange(provider);
@@ -2113,7 +2443,7 @@ export function createConnection(settings) {
2113
2443
  // setConnectionFailure tears down the previously chosen wallet (provider still on
2114
2444
  // the wrapper if the new wallet's getChainId threw before setWalletProvider) before
2115
2445
  // landing on its `wallet: undefined` resting step.
2116
- setConnectionFailure({ message: `failed to select wallet ${walletName}`, cause: err });
2446
+ setConnectionFailure({ message: `failed to select wallet ${walletName}`, cause: err, reason: reasonForError(err) });
2117
2447
  }
2118
2448
  }
2119
2449
  function back(step) {
@@ -2435,7 +2765,7 @@ export function createConnection(settings) {
2435
2765
  // this library's summary and the branch is reached both from a refusal to switch and
2436
2766
  // from a wallet reporting its error as a result.
2437
2767
  const message = `Chain "${named}" is not available on your wallet`;
2438
- doneAsking({ message, cause: err });
2768
+ doneAsking({ message, cause: err, reason: reasonForError(err) });
2439
2769
  throw new Error(message);
2440
2770
  }
2441
2771
  }
@@ -2462,7 +2792,7 @@ export function createConnection(settings) {
2462
2792
  return;
2463
2793
  }
2464
2794
  const message = `Failed to add new chain: ${named}`;
2465
- doneAsking({ message, cause: err });
2795
+ doneAsking({ message, cause: err, reason: reasonForError(err) });
2466
2796
  throw err;
2467
2797
  }
2468
2798
  }
@@ -2496,7 +2826,16 @@ export function createConnection(settings) {
2496
2826
  provider: alwaysOnProviderWrapper.provider,
2497
2827
  chainId: '' + settings.chainInfo.id,
2498
2828
  chainInfo: settings.chainInfo,
2499
- onRequest: (handler) => alwaysOnProviderWrapper.onRequest(handler),
2829
+ // Wrapped rather than passed straight through, so that a consumer driving its own UI from the
2830
+ // event stream sees exactly what `pendingRequests` shows: nothing at all for a wallet that
2831
+ // answers by itself. A consumer given the END of a request whose START it never saw would be
2832
+ // asked to close a dialog it never opened, so both halves are dropped or neither is.
2833
+ onRequest: (handler) => alwaysOnProviderWrapper.onRequest((event) => {
2834
+ if (silenced(event)) {
2835
+ return;
2836
+ }
2837
+ handler(event);
2838
+ }),
2500
2839
  };
2501
2840
  return store;
2502
2841
  }