@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/README.md +142 -12
- package/dist/index.d.ts +128 -70
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +384 -45
- package/dist/index.js.map +1 -1
- package/package.json +4 -4
- package/src/index.ts +596 -143
package/src/index.ts
CHANGED
|
@@ -1,12 +1,14 @@
|
|
|
1
1
|
import type {
|
|
2
2
|
WalletConnector,
|
|
3
3
|
WalletHandle,
|
|
4
|
+
WalletInfo,
|
|
4
5
|
WalletProvider,
|
|
5
6
|
PendingRequest,
|
|
6
7
|
RequestEvent,
|
|
7
8
|
RequestEventHandler,
|
|
8
9
|
RequestPurpose,
|
|
9
10
|
} from '@etherplay/wallet-connector';
|
|
11
|
+
import {walletPrompts} from '@etherplay/wallet-connector';
|
|
10
12
|
import {EthereumWalletConnector, type UnderlyingEthereumProvider} from '@etherplay/wallet-connector-ethereum';
|
|
11
13
|
import {writable} from 'sveltore';
|
|
12
14
|
import {createPopupLauncher, type PopupPromise} from './popup.js';
|
|
@@ -49,6 +51,12 @@ export type {OriginAccount, AuthMechanism, PermissionRequest, PermissionOutcome,
|
|
|
49
51
|
// "your wallet is asking for something" can name WHICH thing without a second dependency.
|
|
50
52
|
export type {PendingRequest, RequestEvent, RequestEventHandler, RequestPurpose};
|
|
51
53
|
|
|
54
|
+
// What a caller needs to BRING a wallet (`wallets`) or to read what one declared, for the same
|
|
55
|
+
// reason: an app that hands this library a wallet of its own should not need a second dependency
|
|
56
|
+
// to name the shape of the thing it is handing over.
|
|
57
|
+
export type {WalletHandle, WalletInfo, WalletProvider, WalletConnector};
|
|
58
|
+
export {walletPrompts};
|
|
59
|
+
|
|
52
60
|
export type {UnderlyingEthereumProvider};
|
|
53
61
|
|
|
54
62
|
export type BasicChainInfo = {
|
|
@@ -271,6 +279,30 @@ function describeAddressUnavailable(details: {
|
|
|
271
279
|
|
|
272
280
|
type WalletStateCommon<WalletProviderType> = {
|
|
273
281
|
provider: WalletProvider<WalletProviderType>;
|
|
282
|
+
/**
|
|
283
|
+
* WHICH wallet this is: the `info` of the handle the provider came from, name, icon and
|
|
284
|
+
* `autoApproves` included.
|
|
285
|
+
*
|
|
286
|
+
* Stamped by `set` rather than supplied, for the same reason `pendingRequests` is (see the ADR): a
|
|
287
|
+
* fact that every construction site would otherwise have to remember to copy is a fact in the wrong
|
|
288
|
+
* place. No construction site can supply one, because `WalletStateInput` omits it.
|
|
289
|
+
*
|
|
290
|
+
* It exists because the state that says a wallet is CONNECTED said nothing about which wallet it
|
|
291
|
+
* was: a consumer had to take `mechanism.name` and look it up in `wallets` to render the wallet's
|
|
292
|
+
* own name, and had to do the same to find out whether that wallet prompts at all. Reading
|
|
293
|
+
* `walletPrompts(connection.wallet.info)` is the whole of that question now.
|
|
294
|
+
*
|
|
295
|
+
* For every state this library builds it is the live wallet's own `info`, taken from the handle
|
|
296
|
+
* that was chosen, so it is exact. Two weaker cases exist and are worth knowing about:
|
|
297
|
+
*
|
|
298
|
+
* - ABSENT. A custom connector may hand over a provider that no announced handle belongs to, and a
|
|
299
|
+
* list in which that provider is ambiguous answers with nothing rather than with a guess. Absent
|
|
300
|
+
* means "not known", which `walletPrompts` reads as the loud default.
|
|
301
|
+
* - ONE PUBLISH STALE. A state spread from a published one keeps the `info` it was published with
|
|
302
|
+
* if the handle has since left the list, which beats a state that cannot say which wallet it is
|
|
303
|
+
* about. The next transition re-derives it.
|
|
304
|
+
*/
|
|
305
|
+
info?: WalletInfo;
|
|
274
306
|
accounts: `0x${string}`[];
|
|
275
307
|
accountChanged?: `0x${string}`;
|
|
276
308
|
chainId: string;
|
|
@@ -298,11 +330,11 @@ type WalletStatus =
|
|
|
298
330
|
|
|
299
331
|
export type WalletState<WalletProviderType> = WalletStateCommon<WalletProviderType> & WalletStatus;
|
|
300
332
|
|
|
301
|
-
// The same wallet state MINUS the
|
|
302
|
-
//
|
|
303
|
-
// construction site, and this type is what stops a
|
|
304
|
-
// wrong one instead.
|
|
305
|
-
type WalletStateInput<WalletProviderType> = Omit<WalletStateCommon<WalletProviderType>, 'pendingRequests'> &
|
|
333
|
+
// The same wallet state MINUS the fields `set` stamps: the deprecated request list, and the `info`
|
|
334
|
+
// of the wallet the provider belongs to. Nothing inside this file supplies either when it builds a
|
|
335
|
+
// wallet: that is the whole point of having one construction site, and this type is what stops a
|
|
336
|
+
// hand-written eleventh rebuild from supplying a wrong one instead.
|
|
337
|
+
type WalletStateInput<WalletProviderType> = Omit<WalletStateCommon<WalletProviderType>, 'pendingRequests' | 'info'> &
|
|
306
338
|
WalletStatus;
|
|
307
339
|
|
|
308
340
|
// The step types below take the wallet state as a parameter so that the same union can describe
|
|
@@ -342,6 +374,79 @@ type SignedIn<WalletProviderType, WS = WalletState<WalletProviderType>> =
|
|
|
342
374
|
wallet: WS;
|
|
343
375
|
};
|
|
344
376
|
|
|
377
|
+
/**
|
|
378
|
+
* WHY a connection attempt ended without reaching what was asked for.
|
|
379
|
+
*
|
|
380
|
+
* A machine-readable discriminant, so an app never has to parse `message` or infer from which
|
|
381
|
+
* fields happen to be absent. It is called `reason` and not `code` because `ConnectionFailure.code`
|
|
382
|
+
* is taken: that one carries the EIP-1193 code off `cause`, and the two answer different questions
|
|
383
|
+
* ("what did the wallet say" versus "what happened to my call").
|
|
384
|
+
*
|
|
385
|
+
* FORWARD COMPATIBILITY, decided rather than left implicit. This is a closed union so the type
|
|
386
|
+
* system can exhaust it, but **new members may appear in a MINOR version**, because a reason this
|
|
387
|
+
* library cannot yet tell apart is a reason it may learn to tell apart. That is why `'failed'`
|
|
388
|
+
* exists as a catch-all: most future causes land there and need no new member, and anything that
|
|
389
|
+
* does get one was previously indistinguishable from a generic failure anyway. **Keep a `default`
|
|
390
|
+
* branch in your switch.** An exhaustive switch with no default is the one shape a new member can
|
|
391
|
+
* break, and the trade was taken knowingly: a union you cannot switch on is worth less than one
|
|
392
|
+
* that may grow.
|
|
393
|
+
*
|
|
394
|
+
* - `cancelled` — the user closed or dismissed the connect flow (`cancel()`, `back(...)`, closing
|
|
395
|
+
* the hosted popup, or a disconnect while the call was waiting). Nothing failed and nothing is
|
|
396
|
+
* worth showing: they decided. **Say nothing.**
|
|
397
|
+
* - `address-unavailable-acknowledged` — the user read `connection.addressUnavailable` ("your
|
|
398
|
+
* wallet is not on that account") and chose not to switch. Also a decision, also not an error,
|
|
399
|
+
* and deliberately carrying the SAME `message` as `cancelled` (`'Connection cancelled'`) so that
|
|
400
|
+
* every existing "a refusal maps to cancelled" path keeps working untouched. Tell the two apart
|
|
401
|
+
* by THIS field, not by the shape.
|
|
402
|
+
* - `superseded` — a newer `ensureConnected` naming a DIFFERENT address took the connection's one
|
|
403
|
+
* account slot. The user decided nothing; the app asked for two things at once. Retry it, or use
|
|
404
|
+
* two connections with different `storagePrefix`es.
|
|
405
|
+
* - `unreachable` — the connection came to rest, nothing is in progress, and nothing can be
|
|
406
|
+
* initiated from here, so the target cannot be reached without a fresh gesture. An outcome to
|
|
407
|
+
* REPORT ("could not connect, try again"), not a silent no-op.
|
|
408
|
+
* - `wallet-rejected` — the wallet prompt was declined (EIP-1193 4001). Offer a retry.
|
|
409
|
+
* - `wallet-unavailable` — the wallet cannot authorise accounts (EIP-1193 4100): read-only,
|
|
410
|
+
* locked, or not configured. Retrying the same prompt will not help; the user must act in the
|
|
411
|
+
* wallet.
|
|
412
|
+
* - `no-accounts` — the wallet answered the request with an empty account list. It looks like a
|
|
413
|
+
* refusal and is not one, which is why it does not alias onto `cancelled`.
|
|
414
|
+
* - `cross-origin-blocked` — the wallet host refused a cross-origin request. The remedy is a
|
|
415
|
+
* registered delegate, not retrying the same popup. `cause` is the host's
|
|
416
|
+
* `{type: 'cross-origin-blocked', windowOrigin, signingOrigin}`.
|
|
417
|
+
* - `host-refused` — the wallet host refused for a reason of ITS own, which this library does not
|
|
418
|
+
* model. The host is deployed separately and chooses its own vocabulary, so its `type` is passed
|
|
419
|
+
* through untouched on `cause` rather than being mapped to a member this library cannot verify:
|
|
420
|
+
* read `(err.cause as {type?: string})?.type` and `err.message` to distinguish them.
|
|
421
|
+
* - `failed` — anything else, with the underlying error on `cause`. The catch-all: treat it as "it
|
|
422
|
+
* did not work", show `message`, offer a retry.
|
|
423
|
+
*/
|
|
424
|
+
export type ConnectionFailureReason =
|
|
425
|
+
| 'cancelled'
|
|
426
|
+
| 'address-unavailable-acknowledged'
|
|
427
|
+
| 'superseded'
|
|
428
|
+
| 'unreachable'
|
|
429
|
+
| 'wallet-rejected'
|
|
430
|
+
| 'wallet-unavailable'
|
|
431
|
+
| 'no-accounts'
|
|
432
|
+
| 'cross-origin-blocked'
|
|
433
|
+
| 'host-refused'
|
|
434
|
+
| 'failed';
|
|
435
|
+
|
|
436
|
+
/**
|
|
437
|
+
* The error a connection comes to rest carrying, which an app renders.
|
|
438
|
+
*
|
|
439
|
+
* `reason` is REQUIRED, and that is the whole design: it makes the compiler enumerate every place
|
|
440
|
+
* that can put an error on the connection, rather than leaving the next one to remember. This
|
|
441
|
+
* codebase has twice fixed bugs whose root cause was an invariant maintained at N call sites
|
|
442
|
+
* instead of one.
|
|
443
|
+
*
|
|
444
|
+
* It is the same vocabulary as the `ConnectionFailure` a pending `ensureConnected` rejects with,
|
|
445
|
+
* and not by coincidence: that failure COPIES this field, so the state an app renders and the
|
|
446
|
+
* error a caller catches cannot disagree about what happened.
|
|
447
|
+
*/
|
|
448
|
+
export type ConnectionError = {message: string; cause?: any; reason: ConnectionFailureReason};
|
|
449
|
+
|
|
345
450
|
// What the connection is, independently of which step it is at.
|
|
346
451
|
//
|
|
347
452
|
// Named rather than written inline below so that `set` can be given the same thing MINUS
|
|
@@ -350,7 +455,8 @@ type ConnectionCommon<WalletProviderType> = {
|
|
|
350
455
|
// The connection can have an error in every state.
|
|
351
456
|
// a banner or other mechanism to show error should be used.
|
|
352
457
|
// error should be dismissable
|
|
353
|
-
|
|
458
|
+
// `reason` says WHICH failure this is, in a closed vocabulary: see `ConnectionFailureReason`.
|
|
459
|
+
error?: ConnectionError;
|
|
354
460
|
/**
|
|
355
461
|
* Set when a caller asked this connection to act as an address the wallet is not offering.
|
|
356
462
|
*
|
|
@@ -628,19 +734,90 @@ export type EnsureConnectedOptions = ConnectOptions & {
|
|
|
628
734
|
forceConnect?: boolean;
|
|
629
735
|
};
|
|
630
736
|
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
737
|
+
/**
|
|
738
|
+
* Error thrown by `ensureConnected` when a connection attempt ends without reaching the target step.
|
|
739
|
+
*
|
|
740
|
+
* Three fields, answering three different questions:
|
|
741
|
+
*
|
|
742
|
+
* - `reason` — WHAT HAPPENED TO THIS CALL, in a closed vocabulary this library controls. Read this
|
|
743
|
+
* one to decide what to do. See `ConnectionFailureReason`, including its note on new members.
|
|
744
|
+
* - `cause` — the underlying error, exactly as whoever raised it wrote it (a wallet's EIP-1193
|
|
745
|
+
* error, the wallet host's `{type, message}` refusal). Unchanged by the arrival of `reason`.
|
|
746
|
+
* - `code` — the convenience copy of `cause.code`, so a user rejection is still `code === 4001`.
|
|
747
|
+
* `reason === 'wallet-rejected'` now says the same thing without the reach into `cause`.
|
|
748
|
+
*
|
|
749
|
+
* `message` is unchanged on every path, deliberately, including `'Connection cancelled'` for a
|
|
750
|
+
* dismissed `addressUnavailable`: the shape stays the safe one every consumer already maps to "the
|
|
751
|
+
* user chose not to", and `reason` says which of those it was.
|
|
752
|
+
*
|
|
753
|
+
* The third constructor argument is optional so that constructing one by hand (a test double, a
|
|
754
|
+
* consumer's own re-throw) keeps compiling; inside this library every failure comes from one place
|
|
755
|
+
* that always supplies it.
|
|
756
|
+
*/
|
|
634
757
|
export class ConnectionFailure extends Error {
|
|
635
758
|
name = 'ConnectionFailure';
|
|
636
759
|
readonly code?: unknown;
|
|
637
|
-
|
|
760
|
+
readonly reason: ConnectionFailureReason;
|
|
761
|
+
constructor(message: string, cause?: unknown, reason: ConnectionFailureReason = 'failed') {
|
|
638
762
|
super(message);
|
|
639
763
|
this.cause = cause;
|
|
640
764
|
this.code = (cause as {code?: unknown} | undefined)?.code;
|
|
765
|
+
this.reason = reason;
|
|
641
766
|
}
|
|
642
767
|
}
|
|
643
768
|
|
|
769
|
+
/**
|
|
770
|
+
* What an error THROWN AT US means, in the vocabulary above.
|
|
771
|
+
*
|
|
772
|
+
* One function rather than a test repeated at each catch site, because the mapping is the part that
|
|
773
|
+
* has to stay consistent: the same rejected wallet prompt must read as `wallet-rejected` whether it
|
|
774
|
+
* arrives from `eth_requestAccounts`, from a signature request, or from an attempt that rejected
|
|
775
|
+
* before it published anything.
|
|
776
|
+
*
|
|
777
|
+
* Only shapes this library can actually VERIFY are mapped. EIP-1193 codes are a standard the wallet
|
|
778
|
+
* and this library both agree on, and `cross-origin-blocked` is minted by `@etherplay/connect-core`
|
|
779
|
+
* in this same repo. Everything else keeps its own words on `cause` and lands on the catch-all.
|
|
780
|
+
*
|
|
781
|
+
* Note what this deliberately does NOT do: an unknown `{type}` does not become `host-refused` here,
|
|
782
|
+
* because an arbitrary thrown object carrying a `type` is not evidence that a HOST refused
|
|
783
|
+
* anything. Host refusals reach the connection through the popup catch, which uses
|
|
784
|
+
* `reasonForHostRefusal` instead. No path currently throws a host refusal INTO this function; if
|
|
785
|
+
* one ever does, it will read as `failed`, and this is the comment that says to route it through
|
|
786
|
+
* `reasonForHostRefusal` at that point rather than loosening the test here.
|
|
787
|
+
*/
|
|
788
|
+
function reasonForError(err: unknown): ConnectionFailureReason {
|
|
789
|
+
const code = (err as {code?: unknown} | undefined)?.code;
|
|
790
|
+
if (code === 4001) {
|
|
791
|
+
return 'wallet-rejected';
|
|
792
|
+
}
|
|
793
|
+
if (code === 4100) {
|
|
794
|
+
return 'wallet-unavailable';
|
|
795
|
+
}
|
|
796
|
+
if ((err as {type?: unknown} | undefined)?.type === 'cross-origin-blocked') {
|
|
797
|
+
return 'cross-origin-blocked';
|
|
798
|
+
}
|
|
799
|
+
return 'failed';
|
|
800
|
+
}
|
|
801
|
+
|
|
802
|
+
/**
|
|
803
|
+
* What a WALLET HOST refusal means, in the vocabulary above.
|
|
804
|
+
*
|
|
805
|
+
* The host is deployed separately and picks its own `type` strings, so only types this library can
|
|
806
|
+
* verify are mapped, and everything else passes through as `host-refused` with the host's own
|
|
807
|
+
* `type` left intact on `cause`. Inventing a member per host vocabulary word would be claiming to
|
|
808
|
+
* know something this package cannot check, and would go stale the moment the host shipped a new
|
|
809
|
+
* one.
|
|
810
|
+
*
|
|
811
|
+
* Exactly ONE type is mapped here, `cross-origin-blocked`, which comes from
|
|
812
|
+
* `@etherplay/connect-core` in this repo. The other verifiable type, `cancelation` (raised by this
|
|
813
|
+
* package's own popup, `src/popup.ts`), is handled by the CALLER and never reaches this function:
|
|
814
|
+
* closing the popup sets no error at all, and `ensureConnected` reports it through its own
|
|
815
|
+
* cancellation branch. A `undefined` refusal likewise cannot arrive, for the same reason.
|
|
816
|
+
*/
|
|
817
|
+
function reasonForHostRefusal(refusal: {type?: string} | undefined): ConnectionFailureReason {
|
|
818
|
+
return refusal?.type === 'cross-origin-blocked' ? 'cross-origin-blocked' : 'host-refused';
|
|
819
|
+
}
|
|
820
|
+
|
|
644
821
|
// Steps where a connection attempt is actively in progress: reaching one of them means an attempt started,
|
|
645
822
|
// and staying in one means we should keep waiting.
|
|
646
823
|
const stepsInProgress: readonly string[] = [
|
|
@@ -797,51 +974,64 @@ export type AnyConnectionStore<WalletProviderType> =
|
|
|
797
974
|
|
|
798
975
|
// Function overloads for proper typing
|
|
799
976
|
//
|
|
800
|
-
//
|
|
801
|
-
//
|
|
802
|
-
//
|
|
803
|
-
//
|
|
804
|
-
//
|
|
805
|
-
//
|
|
806
|
-
//
|
|
977
|
+
// ONE OVERLOAD PER CONFIGURATION, and the configuration is named by `targetStep` and `walletOnly`
|
|
978
|
+
// ONLY. Nothing else in the settings selects an overload, which is a property worth stating because
|
|
979
|
+
// it used to be false and cost a consumer real time.
|
|
980
|
+
//
|
|
981
|
+
// There used to be two overloads per configuration, split on `walletConnector`: one requiring it
|
|
982
|
+
// (generic in the provider type) and one requiring it to be ABSENT (pinned to the Ethereum
|
|
983
|
+
// connector). That made an ordinary optional setting into a discriminant, and a discriminant is a
|
|
984
|
+
// thing a caller must spell exactly:
|
|
985
|
+
//
|
|
986
|
+
// const settings = {...base, ...(connector ? {walletConnector: connector} : {})};
|
|
987
|
+
// createConnection(settings); // matched NEITHER overload
|
|
988
|
+
// createConnection({...base, walletConnector}); // `WalletConnector<P> | undefined` matched neither
|
|
989
|
+
// createConnection({...base, walletConnector: undefined}); // silently selected the OTHER one
|
|
990
|
+
//
|
|
991
|
+
// None of those are exotic: they are what building settings conditionally looks like. So the
|
|
992
|
+
// provider type is now a defaulted type parameter and `walletConnector` is an ordinary optional
|
|
993
|
+
// setting. With no connector and no other mention of the provider type there is nothing to infer
|
|
994
|
+
// from, and the default (`UnderlyingEthereumProvider`) applies, which is exactly what the removed
|
|
995
|
+
// overloads said. With a connector, `wallets`, or a `chainInfo` carrying a `provider`, the provider
|
|
996
|
+
// type is inferred from those. `test/types/connection-settings.types.ts` pins all of it, including
|
|
997
|
+
// the three call shapes above.
|
|
998
|
+
//
|
|
999
|
+
// `walletHost` is optional exactly when no popup can be reached: on `WalletConnected` and
|
|
1000
|
+
// `WalletChosen` (which never sign in) and on `walletOnly: true` `SignedIn` (where `connect` always
|
|
1001
|
+
// defaults the mechanism to `{type: 'wallet'}`, so the mechanism picker is never shown). It stays
|
|
1002
|
+
// REQUIRED on the `walletOnly?: false` `SignedIn` overload, which can reach the hosted
|
|
1003
|
+
// email/oauth/mnemonic popups. That split is the promise; see the README section "Wallet-only
|
|
1004
|
+
// sign-in with no backend", and `test/types/wallet-only-no-host.types.ts` which fails to compile if
|
|
1005
|
+
// it is flattened.
|
|
807
1006
|
//
|
|
808
1007
|
// The `WalletChosen` and `WalletConnected` overloads report `WalletOnly = true`, because that is
|
|
809
1008
|
// what the runtime computes: `walletOnly = settings.walletOnly || targetStep === 'WalletChosen' ||
|
|
810
1009
|
// targetStep === 'WalletConnected'`, so both stores always expose `walletOnly === true`.
|
|
811
1010
|
|
|
812
|
-
// WalletChosen target
|
|
813
|
-
export function createConnection<WalletProviderType>(settings: {
|
|
1011
|
+
// WalletChosen target - walletHost optional
|
|
1012
|
+
export function createConnection<WalletProviderType = UnderlyingEthereumProvider>(settings: {
|
|
814
1013
|
targetStep: 'WalletChosen';
|
|
815
1014
|
walletHost?: string;
|
|
816
1015
|
nodeURL?: string;
|
|
817
1016
|
chainInfo: ChainInfo<WalletProviderType>;
|
|
818
|
-
walletConnector
|
|
1017
|
+
walletConnector?: WalletConnector<WalletProviderType> | undefined;
|
|
1018
|
+
// The wallets this app BRINGS. Supplying them replaces discovery: see the implementation
|
|
1019
|
+
// signature below, which is where that is explained.
|
|
1020
|
+
wallets?: WalletHandle<WalletProviderType>[] | undefined;
|
|
819
1021
|
autoConnect?: boolean;
|
|
820
1022
|
prioritizeWalletProvider?: boolean;
|
|
821
1023
|
requestsPerSecond?: number;
|
|
822
1024
|
storagePrefix?: string;
|
|
823
1025
|
}): ConnectionStore<WalletProviderType, 'WalletChosen', true>;
|
|
824
1026
|
|
|
825
|
-
//
|
|
826
|
-
export function createConnection(settings: {
|
|
827
|
-
targetStep: 'WalletChosen';
|
|
828
|
-
walletHost?: string;
|
|
829
|
-
nodeURL?: string;
|
|
830
|
-
chainInfo: ChainInfo<UnderlyingEthereumProvider>;
|
|
831
|
-
walletConnector?: undefined;
|
|
832
|
-
autoConnect?: boolean;
|
|
833
|
-
prioritizeWalletProvider?: boolean;
|
|
834
|
-
requestsPerSecond?: number;
|
|
835
|
-
storagePrefix?: string;
|
|
836
|
-
}): ConnectionStore<UnderlyingEthereumProvider, 'WalletChosen', true>;
|
|
837
|
-
|
|
838
|
-
// WalletConnected target with custom wallet connector - walletHost optional
|
|
839
|
-
export function createConnection<WalletProviderType>(settings: {
|
|
1027
|
+
// WalletConnected target - walletHost optional
|
|
1028
|
+
export function createConnection<WalletProviderType = UnderlyingEthereumProvider>(settings: {
|
|
840
1029
|
targetStep: 'WalletConnected';
|
|
841
1030
|
walletHost?: string;
|
|
842
1031
|
nodeURL?: string;
|
|
843
1032
|
chainInfo: ChainInfo<WalletProviderType>;
|
|
844
|
-
walletConnector
|
|
1033
|
+
walletConnector?: WalletConnector<WalletProviderType> | undefined;
|
|
1034
|
+
wallets?: WalletHandle<WalletProviderType>[] | undefined;
|
|
845
1035
|
autoConnect?: boolean;
|
|
846
1036
|
useCurrentAccount?: 'always' | 'whenSingle' | false;
|
|
847
1037
|
prioritizeWalletProvider?: boolean;
|
|
@@ -849,28 +1039,15 @@ export function createConnection<WalletProviderType>(settings: {
|
|
|
849
1039
|
storagePrefix?: string;
|
|
850
1040
|
}): ConnectionStore<WalletProviderType, 'WalletConnected', true>;
|
|
851
1041
|
|
|
852
|
-
//
|
|
853
|
-
export function createConnection(settings: {
|
|
854
|
-
targetStep: 'WalletConnected';
|
|
855
|
-
walletHost?: string;
|
|
856
|
-
nodeURL?: string;
|
|
857
|
-
chainInfo: ChainInfo<UnderlyingEthereumProvider>;
|
|
858
|
-
walletConnector?: undefined;
|
|
859
|
-
autoConnect?: boolean;
|
|
860
|
-
useCurrentAccount?: 'always' | 'whenSingle' | false;
|
|
861
|
-
prioritizeWalletProvider?: boolean;
|
|
862
|
-
requestsPerSecond?: number;
|
|
863
|
-
storagePrefix?: string;
|
|
864
|
-
}): ConnectionStore<UnderlyingEthereumProvider, 'WalletConnected', true>;
|
|
865
|
-
|
|
866
|
-
// SignedIn target with walletOnly: true (custom wallet connector) - walletHost optional
|
|
867
|
-
export function createConnection<WalletProviderType>(settings: {
|
|
1042
|
+
// SignedIn target with walletOnly: true - walletHost optional
|
|
1043
|
+
export function createConnection<WalletProviderType = UnderlyingEthereumProvider>(settings: {
|
|
868
1044
|
targetStep?: 'SignedIn';
|
|
869
1045
|
walletOnly: true;
|
|
870
1046
|
walletHost?: string;
|
|
871
1047
|
nodeURL?: string;
|
|
872
1048
|
chainInfo: ChainInfo<WalletProviderType>;
|
|
873
|
-
walletConnector
|
|
1049
|
+
walletConnector?: WalletConnector<WalletProviderType> | undefined;
|
|
1050
|
+
wallets?: WalletHandle<WalletProviderType>[] | undefined;
|
|
874
1051
|
signingOrigin?: string;
|
|
875
1052
|
autoConnect?: boolean;
|
|
876
1053
|
requestSignatureAutomaticallyIfPossible?: boolean;
|
|
@@ -881,32 +1058,15 @@ export function createConnection<WalletProviderType>(settings: {
|
|
|
881
1058
|
storagePrefix?: string;
|
|
882
1059
|
}): ConnectionStore<WalletProviderType, 'SignedIn', true>;
|
|
883
1060
|
|
|
884
|
-
// SignedIn target
|
|
885
|
-
export function createConnection(settings: {
|
|
886
|
-
targetStep?: 'SignedIn';
|
|
887
|
-
walletOnly: true;
|
|
888
|
-
walletHost?: string;
|
|
889
|
-
nodeURL?: string;
|
|
890
|
-
chainInfo: ChainInfo<UnderlyingEthereumProvider>;
|
|
891
|
-
walletConnector?: undefined;
|
|
892
|
-
signingOrigin?: string;
|
|
893
|
-
autoConnect?: boolean;
|
|
894
|
-
requestSignatureAutomaticallyIfPossible?: boolean;
|
|
895
|
-
useCurrentAccount?: 'always' | 'whenSingle' | false;
|
|
896
|
-
prioritizeWalletProvider?: boolean;
|
|
897
|
-
requestsPerSecond?: number;
|
|
898
|
-
domainRedirectBridge?: boolean;
|
|
899
|
-
storagePrefix?: string;
|
|
900
|
-
}): ConnectionStore<UnderlyingEthereumProvider, 'SignedIn', true>;
|
|
901
|
-
|
|
902
|
-
// SignedIn target (explicit) with custom wallet connector - walletHost required
|
|
903
|
-
export function createConnection<WalletProviderType>(settings: {
|
|
1061
|
+
// SignedIn target (the default) - walletHost required
|
|
1062
|
+
export function createConnection<WalletProviderType = UnderlyingEthereumProvider>(settings: {
|
|
904
1063
|
targetStep?: 'SignedIn';
|
|
905
1064
|
walletOnly?: false;
|
|
906
1065
|
walletHost: string;
|
|
907
1066
|
nodeURL?: string;
|
|
908
1067
|
chainInfo: ChainInfo<WalletProviderType>;
|
|
909
|
-
walletConnector
|
|
1068
|
+
walletConnector?: WalletConnector<WalletProviderType> | undefined;
|
|
1069
|
+
wallets?: WalletHandle<WalletProviderType>[] | undefined;
|
|
910
1070
|
signingOrigin?: string;
|
|
911
1071
|
// Permissions to ask for at connect time. See `PermissionDeclaration`.
|
|
912
1072
|
permissions?: PermissionDeclaration[];
|
|
@@ -919,26 +1079,6 @@ export function createConnection<WalletProviderType>(settings: {
|
|
|
919
1079
|
storagePrefix?: string;
|
|
920
1080
|
}): ConnectionStore<WalletProviderType, 'SignedIn', false>;
|
|
921
1081
|
|
|
922
|
-
// SignedIn target (default) with default Ethereum connector - walletHost required
|
|
923
|
-
export function createConnection(settings: {
|
|
924
|
-
targetStep?: 'SignedIn';
|
|
925
|
-
walletOnly?: false;
|
|
926
|
-
walletHost: string;
|
|
927
|
-
nodeURL?: string;
|
|
928
|
-
chainInfo: ChainInfo<UnderlyingEthereumProvider>;
|
|
929
|
-
walletConnector?: undefined;
|
|
930
|
-
signingOrigin?: string;
|
|
931
|
-
// Permissions to ask for at connect time. See `PermissionDeclaration`.
|
|
932
|
-
permissions?: PermissionDeclaration[];
|
|
933
|
-
autoConnect?: boolean;
|
|
934
|
-
requestSignatureAutomaticallyIfPossible?: boolean;
|
|
935
|
-
useCurrentAccount?: 'always' | 'whenSingle' | false;
|
|
936
|
-
prioritizeWalletProvider?: boolean;
|
|
937
|
-
requestsPerSecond?: number;
|
|
938
|
-
domainRedirectBridge?: boolean;
|
|
939
|
-
storagePrefix?: string;
|
|
940
|
-
}): ConnectionStore<UnderlyingEthereumProvider, 'SignedIn', false>;
|
|
941
|
-
|
|
942
1082
|
// Implementation signature
|
|
943
1083
|
export function createConnection<WalletProviderType = UnderlyingEthereumProvider>(settings: {
|
|
944
1084
|
targetStep?: TargetStep;
|
|
@@ -948,7 +1088,36 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
948
1088
|
permissions?: PermissionDeclaration[];
|
|
949
1089
|
walletHost?: string;
|
|
950
1090
|
autoConnect?: boolean;
|
|
951
|
-
walletConnector?: WalletConnector<WalletProviderType
|
|
1091
|
+
walletConnector?: WalletConnector<WalletProviderType> | undefined;
|
|
1092
|
+
/**
|
|
1093
|
+
* The wallets this app BRINGS, instead of the ones the page happens to have.
|
|
1094
|
+
*
|
|
1095
|
+
* Supplying this REPLACES discovery: the connector's `fetchWallets` is not called, no
|
|
1096
|
+
* `eip6963:requestProvider` is dispatched, and `connection.wallets` is exactly this list, INCLUDING
|
|
1097
|
+
* WHEN IT IS EMPTY. `wallets: []` is a connection about no wallets, not a connection that falls
|
|
1098
|
+
* back to discovery, because `wallets: maybeList ?? []` must not quietly enrol every extension in
|
|
1099
|
+
* the page into a connection the caller meant to keep to itself. Pass `undefined` (or nothing) to
|
|
1100
|
+
* ask for discovery. That is
|
|
1101
|
+
* the point rather than a side effect. A wallet an app constructs (a chain running in the tab
|
|
1102
|
+
* with a key it generated, a burner signer, a test double) is not a member of the same population
|
|
1103
|
+
* as the extensions a user installed: it belongs to ONE connection, and announcing it into a
|
|
1104
|
+
* page-wide list, or letting page-wide announcements into this connection's list, mixes two
|
|
1105
|
+
* populations that answer for different things. An app that wants both runs two connections, or
|
|
1106
|
+
* supplies a list containing both.
|
|
1107
|
+
*
|
|
1108
|
+
* With ONE wallet supplied, no picker can ever be shown: `connect({type: 'wallet'})` resolves the
|
|
1109
|
+
* name from the single entry, exactly as it does for a single installed wallet.
|
|
1110
|
+
*
|
|
1111
|
+
* The handles are used as given and never mutated. `info.autoApproves` is how such a wallet says
|
|
1112
|
+
* it prompts for nothing, which is usually true of one an app constructs: see `WalletInfo`.
|
|
1113
|
+
*
|
|
1114
|
+
* This exists so that bringing a wallet does not require SUBCLASSING a connector. The alternative
|
|
1115
|
+
* a consumer had was to extend `EthereumWalletConnector` and override `fetchWallets` to announce
|
|
1116
|
+
* one handle, inheriting `createAlwaysOnProvider` and `accountGenerator` unchanged: a class whose
|
|
1117
|
+
* entire content was a list. `walletConnector` remains the right answer for a DIFFERENT CHAIN
|
|
1118
|
+
* FAMILY, which is what it is for.
|
|
1119
|
+
*/
|
|
1120
|
+
wallets?: WalletHandle<WalletProviderType>[] | undefined;
|
|
952
1121
|
requestSignatureAutomaticallyIfPossible?: boolean;
|
|
953
1122
|
useCurrentAccount?: 'always' | 'whenSingle' | false;
|
|
954
1123
|
nodeURL?: string;
|
|
@@ -1011,6 +1180,11 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
1011
1180
|
const requestSignatureAutomaticallyIfPossible =
|
|
1012
1181
|
targetStep === 'SignedIn' ? settings.requestSignatureAutomaticallyIfPossible || false : false;
|
|
1013
1182
|
|
|
1183
|
+
// Whether each in-flight request is one the user will ever be asked about, decided once when it
|
|
1184
|
+
// starts. Declared up here because the first published state already reads the list. See `silenced`
|
|
1185
|
+
// below for what puts an entry in it and why both answers are recorded.
|
|
1186
|
+
const requestSilencing = new Map<string, boolean>();
|
|
1187
|
+
|
|
1014
1188
|
// The list as last published. Kept so that an UNCHANGED list keeps its identity across publishes:
|
|
1015
1189
|
// the wrapper hands back a fresh array every call, and publishing a new array (and so a new
|
|
1016
1190
|
// `wallet` object) on every unrelated `set` would invalidate `derived` stores, `{#key}` blocks and
|
|
@@ -1018,7 +1192,9 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
1018
1192
|
// `PendingRequest` is created once and never mutated.
|
|
1019
1193
|
let publishedPendingRequests: PendingRequest[] = [];
|
|
1020
1194
|
function currentPendingRequests(): PendingRequest[] {
|
|
1021
|
-
const latest = alwaysOnProviderWrapper
|
|
1195
|
+
const latest = alwaysOnProviderWrapper
|
|
1196
|
+
.getPendingRequests()
|
|
1197
|
+
.filter((request) => requestSilencing.get(request.id) !== true);
|
|
1022
1198
|
if (
|
|
1023
1199
|
latest.length === publishedPendingRequests.length &&
|
|
1024
1200
|
latest.every((request, i) => request === publishedPendingRequests[i])
|
|
@@ -1084,14 +1260,30 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
1084
1260
|
// `{#key}` blocks and effect dependencies do not re-run on an unrelated publish.
|
|
1085
1261
|
const incomingWallet = connection.wallet as WalletStateInput<WalletProviderType> & {
|
|
1086
1262
|
pendingRequests?: PendingRequest[];
|
|
1263
|
+
info?: WalletInfo;
|
|
1087
1264
|
};
|
|
1265
|
+
// WHICH wallet this provider belongs to.
|
|
1266
|
+
//
|
|
1267
|
+
// The live wallet's own `info` when the state is about the live wallet, which is every state this
|
|
1268
|
+
// library builds and is the EXACT answer: it came from the handle that was chosen, rather than
|
|
1269
|
+
// from a scan over a list where provider identity may not be unique.
|
|
1270
|
+
//
|
|
1271
|
+
// The scan is the fallback for anything else, and what the caller spread in is the fallback after
|
|
1272
|
+
// that, so a state rebuilt from a published one keeps the `info` it was published with even once
|
|
1273
|
+
// the handle has left the list. That last one is deliberately allowed to be STALE: a name that is
|
|
1274
|
+
// one publish old is better than a state that cannot say which wallet it is about, and the field
|
|
1275
|
+
// is re-derived on the next transition.
|
|
1276
|
+
const info =
|
|
1277
|
+
(_wallet && _wallet.provider === connection.wallet.provider ? _wallet.info : undefined) ??
|
|
1278
|
+
walletInfoIn(connection.wallets, connection.wallet.provider) ??
|
|
1279
|
+
incomingWallet.info;
|
|
1088
1280
|
$connection = {
|
|
1089
1281
|
...connection,
|
|
1090
1282
|
pendingRequests,
|
|
1091
1283
|
wallet:
|
|
1092
|
-
incomingWallet.pendingRequests === pendingRequests
|
|
1284
|
+
incomingWallet.pendingRequests === pendingRequests && incomingWallet.info === info
|
|
1093
1285
|
? (incomingWallet as WalletState<WalletProviderType>)
|
|
1094
|
-
: {...connection.wallet, pendingRequests},
|
|
1286
|
+
: {...connection.wallet, pendingRequests, info},
|
|
1095
1287
|
};
|
|
1096
1288
|
_store.set($connection);
|
|
1097
1289
|
return $connection;
|
|
@@ -1117,12 +1309,78 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
1117
1309
|
// disconnect followed by a reconnect left the app blind to every subsequent wallet prompt. The
|
|
1118
1310
|
// wrapper is created here and lives exactly as long as this connection, so there is nothing to
|
|
1119
1311
|
// release.
|
|
1120
|
-
alwaysOnProviderWrapper.onRequest(() => {
|
|
1312
|
+
alwaysOnProviderWrapper.onRequest((event) => {
|
|
1313
|
+
// Decide, and RECORD, whether this request is one the user will ever be asked about, before the
|
|
1314
|
+
// list below is read. See `silenced`.
|
|
1315
|
+
silenced(event);
|
|
1121
1316
|
// Republish. `set` re-reads the wrapper, so this needs to say nothing about the list itself,
|
|
1122
1317
|
// and it must run whether or not a wallet is currently in the state: a request outstanding
|
|
1123
1318
|
// while the flow rests on `wallet: undefined` is exactly the case that used to go unreported.
|
|
1124
1319
|
set($connection);
|
|
1125
1320
|
});
|
|
1321
|
+
|
|
1322
|
+
// NOTHING CAN BE OUTSTANDING WITH A WALLET THAT ANSWERS BY ITSELF.
|
|
1323
|
+
//
|
|
1324
|
+
// `pendingRequests` means "your wallet is holding something and is waiting for you", and every
|
|
1325
|
+
// consumer renders it as a question on the user's screen: a modal saying the wallet will ask them
|
|
1326
|
+
// to confirm, a cancel affordance, an unload guard. A wallet that declares `info.autoApproves`
|
|
1327
|
+
// signs with no dialog, so all three describe an event that does not happen, and each consumer
|
|
1328
|
+
// would otherwise have to infer that for itself from a fact only the wallet knows.
|
|
1329
|
+
//
|
|
1330
|
+
// So the announcement is dropped HERE, at the connection, and not in the wrapper. The wrapper's
|
|
1331
|
+
// own bookkeeping stays honest and complete (it is what tells a request's end from its start, and
|
|
1332
|
+
// it is per-connector, so silencing there would have to be implemented again by every connector).
|
|
1333
|
+
// This library's published surface is the one that claims a user is being asked, and it is the one
|
|
1334
|
+
// that stops claiming it.
|
|
1335
|
+
//
|
|
1336
|
+
// The decision is made ONCE, when the request STARTS, and then remembered by id. A request can
|
|
1337
|
+
// outlive the wallet that started it (the user is free to switch wallet while one is outstanding,
|
|
1338
|
+
// see the ADR), and "was anybody ever going to be asked about this" is a fact about the wallet that
|
|
1339
|
+
// TOOK it, not about whichever wallet is current when it ends. Deciding again at the end would
|
|
1340
|
+
// silence a real prompt, or announce the end of something never announced as started.
|
|
1341
|
+
//
|
|
1342
|
+
// `walletPrompts` is the default: a wallet that says nothing prompts, so every existing caller and
|
|
1343
|
+
// every discovered wallet is untouched by this.
|
|
1344
|
+
function activeWalletAutoApproves(): boolean {
|
|
1345
|
+
// `_wallet.info` and not a lookup: see the declaration of `_wallet`. This is the one answer that
|
|
1346
|
+
// must not be guessed, because guessing it wrong in the silencing direction hides a prompt the
|
|
1347
|
+
// user is looking at.
|
|
1348
|
+
return !!_wallet && !walletPrompts(_wallet.info);
|
|
1349
|
+
}
|
|
1350
|
+
/**
|
|
1351
|
+
* Is this event about a request the user was never going to see?
|
|
1352
|
+
*
|
|
1353
|
+
* Idempotent, and order-independent: the store's own subscription and every consumer subscription
|
|
1354
|
+
* ask, in whatever order they were registered, and the first to ask about a `requestStart` is the
|
|
1355
|
+
* one that decides. Every later ask reads that decision back, INCLUDING A NEGATIVE ONE.
|
|
1356
|
+
*
|
|
1357
|
+
* Recording the negative answer too is what makes the order not matter. The decision is a question
|
|
1358
|
+
* about the live wallet, and publishing between handlers (the store's own subscription calls `set`,
|
|
1359
|
+
* which runs consumer subscribers synchronously) is an opportunity for the live wallet to change
|
|
1360
|
+
* under the remaining handlers. Nothing reachable today flips it in that window, but a half-silenced
|
|
1361
|
+
* request is exactly the split this feature exists to avoid: announced on `pendingRequests` and
|
|
1362
|
+
* missing from `onRequest`, or the reverse.
|
|
1363
|
+
*/
|
|
1364
|
+
function silenced(event: RequestEvent): boolean {
|
|
1365
|
+
const decided = requestSilencing.get(event.request.id);
|
|
1366
|
+
if (decided !== undefined) {
|
|
1367
|
+
if (event.type === 'requestEnd') {
|
|
1368
|
+
// Forgotten only once every handler has been given this event, so that a consumer cannot be
|
|
1369
|
+
// handed the END of a request whose START it never saw. A native microtask rather than a
|
|
1370
|
+
// timer: the whole synchronous emit loop has run by then, and no test clock can defer it.
|
|
1371
|
+
Promise.resolve().then(() => requestSilencing.delete(event.request.id));
|
|
1372
|
+
}
|
|
1373
|
+
return decided;
|
|
1374
|
+
}
|
|
1375
|
+
if (event.type !== 'requestStart') {
|
|
1376
|
+
// An end with no decision on record is a request that started before this connection was
|
|
1377
|
+
// listening. It was never silenced, so it is not silenced now.
|
|
1378
|
+
return false;
|
|
1379
|
+
}
|
|
1380
|
+
const silence = activeWalletAutoApproves();
|
|
1381
|
+
requestSilencing.set(event.request.id, silence);
|
|
1382
|
+
return silence;
|
|
1383
|
+
}
|
|
1126
1384
|
// Where the flow comes to rest when a connection attempt fails.
|
|
1127
1385
|
//
|
|
1128
1386
|
// The rule: rest on the step that offers the user a real next decision, and never on a step this app has
|
|
@@ -1136,7 +1394,12 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
1136
1394
|
//
|
|
1137
1395
|
// Auto-connect failures follow the same rule and rest on `Idle`: the user asked for nothing, so there is
|
|
1138
1396
|
// no decision to offer them. A cancelled popup is likewise a cancellation, not a failure, and rests on `Idle`.
|
|
1139
|
-
|
|
1397
|
+
//
|
|
1398
|
+
// `error` carries a REQUIRED `reason` (see `ConnectionFailureReason`). That is not decoration: a
|
|
1399
|
+
// pending `ensureConnected` copies it onto the `ConnectionFailure` it rejects with, so what the
|
|
1400
|
+
// app renders and what the caller catches cannot disagree, and requiring it here is what makes
|
|
1401
|
+
// the compiler enumerate the producers instead of leaving the next one to remember.
|
|
1402
|
+
function setConnectionFailure(error: ConnectionError) {
|
|
1140
1403
|
const wallets = $connection.wallets;
|
|
1141
1404
|
// Every resting state below has `wallet: undefined`, so `set` tears the live wallet down.
|
|
1142
1405
|
if (!walletOnly) {
|
|
@@ -1147,7 +1410,7 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
1147
1410
|
set({step: 'Idle', loading: false, wallets, wallet: undefined, error});
|
|
1148
1411
|
}
|
|
1149
1412
|
}
|
|
1150
|
-
function setError(error:
|
|
1413
|
+
function setError(error: ConnectionError) {
|
|
1151
1414
|
if ($connection) {
|
|
1152
1415
|
set({
|
|
1153
1416
|
...$connection,
|
|
@@ -1219,6 +1482,52 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
1219
1482
|
// attempt has cleared the field still names the address the user was actually looking at.
|
|
1220
1483
|
let lastPublishedAddressUnavailable: `0x${string}` | undefined;
|
|
1221
1484
|
|
|
1485
|
+
/**
|
|
1486
|
+
* The address-bound `ensureConnected` calls that are still live on this connection, in the order
|
|
1487
|
+
* they were made. Mirrors `addressUnavailableAcknowledgements` above: per connection, per address,
|
|
1488
|
+
* kept by the one thing that knows.
|
|
1489
|
+
*
|
|
1490
|
+
* WHY IT EXISTS. A connection has one wallet, one account and one `addressUnavailable` slot, so a
|
|
1491
|
+
* second call naming a DIFFERENT address supersedes the first: the newer request takes the slot,
|
|
1492
|
+
* the older one loses the state it was resting on and comes to rest with nothing in progress. That
|
|
1493
|
+
* is a real answer and it was already delivered honestly (`could not reach ...`, never a
|
|
1494
|
+
* cancellation the user did not make), but it arrived looking exactly like every other
|
|
1495
|
+
* come-to-rest, so no consumer could tell "your own app asked for something else" from "this
|
|
1496
|
+
* connection cannot get there". Only ONE call knows the difference and it is not the one being
|
|
1497
|
+
* answered, which is why supersession cannot be read off the connection state and needs a
|
|
1498
|
+
* registry.
|
|
1499
|
+
*
|
|
1500
|
+
* Registration is a monotonic id rather than a set, because the question is ordered: an OLDER
|
|
1501
|
+
* request is superseded by a NEWER one, never the other way round.
|
|
1502
|
+
*
|
|
1503
|
+
* WHAT IT IS AND IS NOT. `superseded` says "a later live request names another account", which is
|
|
1504
|
+
* an over-approximation of "that request is what displaced me": if some third thing (the app's own
|
|
1505
|
+
* `connect()`, a disconnect) ends both at once, the older is still labelled superseded. That is
|
|
1506
|
+
* the harmless direction, since the newer request was going to take the slot anyway, and the
|
|
1507
|
+
* remedy the label implies (retry) is the right one either way. The opposite error is avoided by
|
|
1508
|
+
* construction: a call that resolves without ever waiting returns before it registers.
|
|
1509
|
+
*
|
|
1510
|
+
* An entry lives exactly as long as its promise is unsettled, which for an abandoned call means as
|
|
1511
|
+
* long as the promise itself: this map holds no more than the pending calls already do.
|
|
1512
|
+
*/
|
|
1513
|
+
let addressBoundRequests = 0;
|
|
1514
|
+
const liveAddressBoundRequests = new Map<number, `0x${string}`>();
|
|
1515
|
+
function registerAddressBoundRequest(address: `0x${string}`): number {
|
|
1516
|
+
const id = ++addressBoundRequests;
|
|
1517
|
+
liveAddressBoundRequests.set(id, address.toLowerCase() as `0x${string}`);
|
|
1518
|
+
return id;
|
|
1519
|
+
}
|
|
1520
|
+
/** Is a LATER live request naming a DIFFERENT address, i.e. holding the slot this one needs? */
|
|
1521
|
+
function isSupersededBy(id: number, address: `0x${string}`): boolean {
|
|
1522
|
+
const asked = address.toLowerCase();
|
|
1523
|
+
for (const [otherId, otherAddress] of liveAddressBoundRequests) {
|
|
1524
|
+
if (otherId > id && otherAddress !== asked) {
|
|
1525
|
+
return true;
|
|
1526
|
+
}
|
|
1527
|
+
}
|
|
1528
|
+
return false;
|
|
1529
|
+
}
|
|
1530
|
+
|
|
1222
1531
|
// How many times the user's WALLET has announced a DIFFERENT set of accounts. It is the unit
|
|
1223
1532
|
// `ensureConnected` retries on, and it is the honest one: a retry is a response to the user
|
|
1224
1533
|
// having done something in their wallet, so at most one attempt per announcement bounds the work
|
|
@@ -1233,7 +1542,21 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
1233
1542
|
// ask.
|
|
1234
1543
|
let walletAnnouncements = 0;
|
|
1235
1544
|
|
|
1236
|
-
|
|
1545
|
+
// THE LIVE WALLET, and WHICH wallet it is.
|
|
1546
|
+
//
|
|
1547
|
+
// `info` is carried here, from the handle that was chosen, rather than looked up from the provider
|
|
1548
|
+
// when it is needed. The lookup is a scan of `wallets` by provider identity, and provider identity
|
|
1549
|
+
// is not a key: two handles supplied by a caller may wrap the SAME provider object under different
|
|
1550
|
+
// names, at which point the scan answers with whichever comes first. That is a wrong name on the
|
|
1551
|
+
// published state, and, worse, a wrong answer to "does this wallet prompt", which could silence a
|
|
1552
|
+
// request the user is genuinely being asked about. Every site that registers a wallet has the
|
|
1553
|
+
// handle in hand, so the exact answer is free.
|
|
1554
|
+
//
|
|
1555
|
+
// The key is REQUIRED (and may hold `undefined`) so that a new registration site has to say what it
|
|
1556
|
+
// knows rather than inherit a default by forgetting.
|
|
1557
|
+
let _wallet:
|
|
1558
|
+
| {provider: WalletProvider<WalletProviderType>; chainId: string; info: WalletInfo | undefined}
|
|
1559
|
+
| undefined;
|
|
1237
1560
|
|
|
1238
1561
|
let popup: PopupPromise<OriginAccount> | undefined;
|
|
1239
1562
|
|
|
@@ -1257,18 +1580,59 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
1257
1580
|
return !!a.info.rdns && a.info.rdns === b.info.rdns;
|
|
1258
1581
|
}
|
|
1259
1582
|
|
|
1583
|
+
function announceWallet(detail: WalletHandle<WalletProviderType>) {
|
|
1584
|
+
const existingWallets = $connection.wallets;
|
|
1585
|
+
if (existingWallets.some((existing) => isSameWallet(existing, detail))) {
|
|
1586
|
+
return;
|
|
1587
|
+
}
|
|
1588
|
+
|
|
1589
|
+
set({
|
|
1590
|
+
...$connection,
|
|
1591
|
+
wallets: [...existingWallets, detail],
|
|
1592
|
+
});
|
|
1593
|
+
}
|
|
1594
|
+
|
|
1595
|
+
// WHERE THIS CONNECTION'S WALLETS COME FROM: the caller, or the page.
|
|
1596
|
+
//
|
|
1597
|
+
// A caller that supplies `wallets` gets exactly those and DISCOVERY IS NOT RUN, so no
|
|
1598
|
+
// `eip6963:requestProvider` is dispatched and no installed extension can announce itself into this
|
|
1599
|
+
// list. See the setting's doc on the implementation signature: a wallet the app constructed and a
|
|
1600
|
+
// wallet the user installed are two different populations, and the whole reason to supply one is
|
|
1601
|
+
// to say which of them this connection is about.
|
|
1602
|
+
//
|
|
1603
|
+
// The supplied handles go through the same `announceWallet` as discovered ones, so a caller that
|
|
1604
|
+
// hands over the same wallet twice gets it once, exactly as a wallet announcing itself twice does.
|
|
1260
1605
|
function fetchWallets() {
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1606
|
+
// `!== undefined`, so an EMPTY supplied list is still a supplied list: see the setting's doc.
|
|
1607
|
+
if (settings.wallets !== undefined) {
|
|
1608
|
+
for (const walletHandle of settings.wallets) {
|
|
1609
|
+
announceWallet(walletHandle);
|
|
1265
1610
|
}
|
|
1611
|
+
return;
|
|
1612
|
+
}
|
|
1613
|
+
walletConnector.fetchWallets(announceWallet);
|
|
1614
|
+
}
|
|
1266
1615
|
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
|
|
1616
|
+
/**
|
|
1617
|
+
* The `info` of the announced handle this provider belongs to, or NOTHING IF IT IS AMBIGUOUS.
|
|
1618
|
+
*
|
|
1619
|
+
* The fallback for a wallet this connection did not register itself (a custom connector may hand
|
|
1620
|
+
* over a provider without a handle behind it), which is why it is a scan rather than a key lookup:
|
|
1621
|
+
* provider identity is not a key, and a caller supplying two handles that wrap the same provider
|
|
1622
|
+
* object under different names makes it answer with whichever comes first.
|
|
1623
|
+
*
|
|
1624
|
+
* So an ambiguous scan answers with nothing at all. Absent is read as the LOUD default everywhere
|
|
1625
|
+
* it matters, which is the direction a wrong guess must fail in: naming the wrong wallet is a
|
|
1626
|
+
* cosmetic error, while inheriting the wrong wallet's `autoApproves` would silence a request the
|
|
1627
|
+
* user is genuinely being asked about. `_wallet.info` is the exact answer and is preferred over
|
|
1628
|
+
* this wherever it is available.
|
|
1629
|
+
*/
|
|
1630
|
+
function walletInfoIn(
|
|
1631
|
+
wallets: WalletHandle<WalletProviderType>[],
|
|
1632
|
+
provider: WalletProvider<WalletProviderType>,
|
|
1633
|
+
): WalletInfo | undefined {
|
|
1634
|
+
const matches = wallets.filter((walletHandle) => walletHandle.walletProvider === provider);
|
|
1635
|
+
return matches.length === 1 ? matches[0].info : undefined;
|
|
1272
1636
|
}
|
|
1273
1637
|
|
|
1274
1638
|
function waitForWallet(name: string): Promise<WalletHandle<WalletProviderType>> {
|
|
@@ -1331,7 +1695,7 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
1331
1695
|
const walletProvider = walletDetails.walletProvider;
|
|
1332
1696
|
const chainIdAsHex = await withTimeout(walletProvider.getChainId());
|
|
1333
1697
|
const chainId = Number(chainIdAsHex).toString();
|
|
1334
|
-
_wallet = {provider: walletProvider, chainId};
|
|
1698
|
+
_wallet = {provider: walletProvider, chainId, info: walletDetails.info};
|
|
1335
1699
|
alwaysOnProviderWrapper.setWalletProvider(walletProvider.underlyingProvider);
|
|
1336
1700
|
watchForChainIdChange(_wallet.provider);
|
|
1337
1701
|
let accounts: `0x${string}`[] = [];
|
|
@@ -1386,7 +1750,7 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
1386
1750
|
const walletProvider = walletDetails.walletProvider;
|
|
1387
1751
|
const chainIdAsHex = await withTimeout(walletProvider.getChainId());
|
|
1388
1752
|
const chainId = Number(chainIdAsHex).toString();
|
|
1389
|
-
_wallet = {provider: walletProvider, chainId};
|
|
1753
|
+
_wallet = {provider: walletProvider, chainId, info: walletDetails.info};
|
|
1390
1754
|
alwaysOnProviderWrapper.setWalletProvider(walletProvider.underlyingProvider);
|
|
1391
1755
|
alwaysOnProviderWrapper.setWalletStatus('disconnected');
|
|
1392
1756
|
watchForChainIdChange(_wallet.provider);
|
|
@@ -1428,7 +1792,7 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
1428
1792
|
const walletProvider = walletDetails.walletProvider;
|
|
1429
1793
|
const chainIdAsHex = await withTimeout(walletProvider.getChainId());
|
|
1430
1794
|
const chainId = Number(chainIdAsHex).toString();
|
|
1431
|
-
_wallet = {provider: walletProvider, chainId};
|
|
1795
|
+
_wallet = {provider: walletProvider, chainId, info: walletDetails.info};
|
|
1432
1796
|
alwaysOnProviderWrapper.setWalletProvider(walletProvider.underlyingProvider);
|
|
1433
1797
|
watchForChainIdChange(_wallet.provider);
|
|
1434
1798
|
|
|
@@ -1609,7 +1973,10 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
1609
1973
|
name: $connection.mechanism.name,
|
|
1610
1974
|
address: $connection.mechanism.address,
|
|
1611
1975
|
},
|
|
1612
|
-
|
|
1976
|
+
// A declined signature prompt is the same 4001 a declined connect is, and the same
|
|
1977
|
+
// mapping names it: an app that offers "try again" on a rejection must not have to know
|
|
1978
|
+
// which prompt was rejected to recognise one.
|
|
1979
|
+
error: {message: 'failed to sign message', cause: err, reason: reasonForError(err)},
|
|
1613
1980
|
});
|
|
1614
1981
|
return;
|
|
1615
1982
|
}
|
|
@@ -1883,8 +2250,14 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
1883
2250
|
function restoreWalletChosenAfterFailedConnect(
|
|
1884
2251
|
errorMessage: string,
|
|
1885
2252
|
cause: unknown,
|
|
2253
|
+
// Taken as an argument rather than derived from `cause` here: this function is the RESTING
|
|
2254
|
+
// half of a failure whose other half is `setConnectionFailure`, and the two must label the
|
|
2255
|
+
// same event identically. An empty accounts answer has no `cause` to derive anything from.
|
|
2256
|
+
reason: ConnectionFailureReason,
|
|
1886
2257
|
chosenMechanism: WalletMechanism<string, undefined> | undefined,
|
|
1887
|
-
chosenWallet:
|
|
2258
|
+
chosenWallet:
|
|
2259
|
+
| {provider: WalletProvider<WalletProviderType>; chainId: string; info: WalletInfo | undefined}
|
|
2260
|
+
| undefined,
|
|
1888
2261
|
): boolean {
|
|
1889
2262
|
if (!chosenMechanism || !chosenWallet) {
|
|
1890
2263
|
return false;
|
|
@@ -1898,7 +2271,7 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
1898
2271
|
// The fresher chainId wins: `onChainChanged` keeps updating the live `_wallet`, so when
|
|
1899
2272
|
// the attempt was on the same provider its chainId may be newer than the captured one.
|
|
1900
2273
|
const chainId = _wallet && _wallet.provider === chosenWallet.provider ? _wallet.chainId : chosenWallet.chainId;
|
|
1901
|
-
_wallet = {provider: chosenWallet.provider, chainId};
|
|
2274
|
+
_wallet = {provider: chosenWallet.provider, chainId, info: chosenWallet.info};
|
|
1902
2275
|
stopWatchingForAccountChange(_wallet.provider);
|
|
1903
2276
|
// Re-establish what the start of connect() tore down. If the failure happened early
|
|
1904
2277
|
// (getChainId threw), the wrapper provider and the chain watcher were never
|
|
@@ -1923,7 +2296,7 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
1923
2296
|
invalidChainId: alwaysOnChainId != chainId,
|
|
1924
2297
|
switchingChain: false,
|
|
1925
2298
|
},
|
|
1926
|
-
error: {message: errorMessage, cause},
|
|
2299
|
+
error: {message: errorMessage, cause, reason},
|
|
1927
2300
|
});
|
|
1928
2301
|
return true;
|
|
1929
2302
|
}
|
|
@@ -2089,6 +2462,7 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
2089
2462
|
_wallet = {
|
|
2090
2463
|
chainId,
|
|
2091
2464
|
provider,
|
|
2465
|
+
info: wallet.info,
|
|
2092
2466
|
};
|
|
2093
2467
|
// TODO
|
|
2094
2468
|
alwaysOnProviderWrapper.setWalletProvider(_wallet.provider.underlyingProvider);
|
|
@@ -2183,11 +2557,15 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
2183
2557
|
!restoreWalletChosenAfterFailedConnect(
|
|
2184
2558
|
'could not get any accounts',
|
|
2185
2559
|
undefined,
|
|
2560
|
+
// `no-accounts`, NOT a cancellation. The wallet answered, and answered with
|
|
2561
|
+
// nothing: from the outside that looks like a refusal and it is not one, which
|
|
2562
|
+
// is exactly the aliasing a consumer's own sniffing module got wrong.
|
|
2563
|
+
'no-accounts',
|
|
2186
2564
|
chosenMechanismBeforeConnect,
|
|
2187
2565
|
chosenWalletBeforeConnect,
|
|
2188
2566
|
)
|
|
2189
2567
|
) {
|
|
2190
|
-
setConnectionFailure({message: 'could not get any accounts'});
|
|
2568
|
+
setConnectionFailure({message: 'could not get any accounts', reason: 'no-accounts'});
|
|
2191
2569
|
}
|
|
2192
2570
|
}
|
|
2193
2571
|
} else {
|
|
@@ -2261,6 +2639,12 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
2261
2639
|
// read-only, locked, or not yet configured (e.g. werust's keyless
|
|
2262
2640
|
// provider). 4001 (User Rejected Request): the user actively declined in
|
|
2263
2641
|
// the wallet popup. Anything else is a genuine failure.
|
|
2642
|
+
// The message picked per code below and the `reason` a consumer reads instead of
|
|
2643
|
+
// re-deriving it are two lists over the same two codes. They agree today and nothing
|
|
2644
|
+
// COUPLES them: a third message added here without a matching member in
|
|
2645
|
+
// `reasonForError` would be prose the discriminant does not know about. Deriving the
|
|
2646
|
+
// message from the reason would fix that and would change every message string, which
|
|
2647
|
+
// this change is not allowed to do.
|
|
2264
2648
|
const code = (err as {code?: unknown})?.code;
|
|
2265
2649
|
let errorMessage = `failed to connect to wallet`;
|
|
2266
2650
|
if (code === 4100) {
|
|
@@ -2277,20 +2661,28 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
2277
2661
|
// also tears the wallet down, because every failure state's `wallet` is
|
|
2278
2662
|
// `undefined` — a failed attempt must not keep routing requests (including
|
|
2279
2663
|
// read-only RPC calls like eth_call) through the failed wallet.
|
|
2664
|
+
// ONE derivation, read by both halves of the failure. The restore path and
|
|
2665
|
+
// `setConnectionFailure` are two landings for the same event, so a reason computed
|
|
2666
|
+
// twice is two chances to compute it differently.
|
|
2667
|
+
const reason = reasonForError(err);
|
|
2280
2668
|
if (
|
|
2281
2669
|
!restoreWalletChosenAfterFailedConnect(
|
|
2282
2670
|
errorMessage,
|
|
2283
2671
|
err,
|
|
2672
|
+
reason,
|
|
2284
2673
|
chosenMechanismBeforeConnect,
|
|
2285
2674
|
chosenWalletBeforeConnect,
|
|
2286
2675
|
)
|
|
2287
2676
|
) {
|
|
2288
|
-
setConnectionFailure({message: errorMessage, cause: err});
|
|
2677
|
+
setConnectionFailure({message: errorMessage, cause: err, reason});
|
|
2289
2678
|
}
|
|
2290
2679
|
}
|
|
2291
2680
|
} else {
|
|
2292
2681
|
console.error(`failed to get wallet ${walletName}`, $connection.wallets);
|
|
2293
|
-
|
|
2682
|
+
// The catch-all, deliberately: the named wallet is not among the announced ones (a typo, an
|
|
2683
|
+
// extension uninstalled between render and click). It gets no member of its own because it
|
|
2684
|
+
// is not a state the user can answer, and the message already names the wallet.
|
|
2685
|
+
setConnectionFailure({message: `failed to get wallet ${walletName}`, reason: 'failed'});
|
|
2294
2686
|
}
|
|
2295
2687
|
} else {
|
|
2296
2688
|
// TODO can also be done automatically before hand
|
|
@@ -2422,7 +2814,11 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
2422
2814
|
loading: false,
|
|
2423
2815
|
wallet: undefined,
|
|
2424
2816
|
wallets: $connection.wallets,
|
|
2425
|
-
|
|
2817
|
+
// The host's own `type` stays on `cause`, untouched; `reason` pins only what this library
|
|
2818
|
+
// can verify (`cross-origin-blocked`) and passes anything else through as `host-refused`.
|
|
2819
|
+
error: canceled
|
|
2820
|
+
? undefined
|
|
2821
|
+
: {message: refusal.message || 'sign in failed', cause: refusal, reason: reasonForHostRefusal(refusal)},
|
|
2426
2822
|
});
|
|
2427
2823
|
} finally {
|
|
2428
2824
|
unsubscribe();
|
|
@@ -2642,6 +3038,10 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
2642
3038
|
// Dismissals of the address-unavailable state that happened BEFORE this call: only a later one
|
|
2643
3039
|
// is this call's answer.
|
|
2644
3040
|
const acknowledgementsOnEntry = askedAddress ? acknowledgementsFor(askedAddress) : 0;
|
|
3041
|
+
// THIS CALL'S PLACE IN THE QUEUE for the connection's one account slot, kept only while the
|
|
3042
|
+
// call is live (see `settle`). Registered here, after the early resolve above has already
|
|
3043
|
+
// returned, so a call that never waited never claims the slot at all.
|
|
3044
|
+
const addressBoundRequestId = askedAddress ? registerAddressBoundRequest(askedAddress) : undefined;
|
|
2645
3045
|
// WHAT STOPS "try again" FROM BECOMING A LOOP: at most one attempt per wallet announcement.
|
|
2646
3046
|
//
|
|
2647
3047
|
// Our own attempts do not bump `walletAnnouncements`, so an attempt can never start another one
|
|
@@ -2679,9 +3079,38 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
2679
3079
|
settled = true;
|
|
2680
3080
|
// unsubscribe can still be undefined here if the store settles during the initial (synchronous) subscription
|
|
2681
3081
|
unsubscribe?.();
|
|
3082
|
+
// This call is over, so it stops competing for the account slot and stops being counted
|
|
3083
|
+
// against anybody.
|
|
3084
|
+
//
|
|
3085
|
+
// HONEST NOTE, because no test fails if this is deleted: it is defensive. For it to change
|
|
3086
|
+
// an observable label, a NEWER address-bound call would have to settle while an OLDER one
|
|
3087
|
+
// stays live, and every way a newer call can settle publishes a state that also ends an
|
|
3088
|
+
// older call resting on it — while an older call that is still waiting is waiting on
|
|
3089
|
+
// something in progress, which publishes again in its turn. Kept anyway: it also bounds the
|
|
3090
|
+
// map, and "the registry contains the live requests" is cheaper to keep true than to reason
|
|
3091
|
+
// about every time somebody adds a settle path.
|
|
3092
|
+
if (addressBoundRequestId !== undefined) {
|
|
3093
|
+
liveAddressBoundRequests.delete(addressBoundRequestId);
|
|
3094
|
+
}
|
|
2682
3095
|
perform();
|
|
2683
3096
|
};
|
|
2684
|
-
|
|
3097
|
+
/**
|
|
3098
|
+
* THE ONE PLACE A `ConnectionFailure` IS BUILT, and it takes the reason first.
|
|
3099
|
+
*
|
|
3100
|
+
* Not tidiness: `reason` is the field that must never be forgotten, and a rule kept at four
|
|
3101
|
+
* call sites is a rule that is kept at three of them a year from now. This codebase has
|
|
3102
|
+
* twice fixed bugs whose root cause was exactly that (`pendingRequests`, wallet teardown).
|
|
3103
|
+
*/
|
|
3104
|
+
const failWith = (reason: ConnectionFailureReason, message: string, cause?: unknown) =>
|
|
3105
|
+
settle(() => reject(new ConnectionFailure(message, cause, reason)));
|
|
3106
|
+
/**
|
|
3107
|
+
* The MESSAGE is the same for both, and that is the point: every consumer already maps
|
|
3108
|
+
* `'Connection cancelled'` to "the user chose not to" and shows nothing, so a dismissed
|
|
3109
|
+
* `addressUnavailable` must keep arriving in that shape and must not paint a red banner over
|
|
3110
|
+
* a decision. What was missing is WHICH decision, and that is what `reason` adds.
|
|
3111
|
+
*/
|
|
3112
|
+
const cancelled = (reason: 'cancelled' | 'address-unavailable-acknowledged') =>
|
|
3113
|
+
failWith(reason, 'Connection cancelled');
|
|
2685
3114
|
|
|
2686
3115
|
/**
|
|
2687
3116
|
* Start an attempt and stay honest about it while it runs.
|
|
@@ -2710,7 +3139,7 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
2710
3139
|
},
|
|
2711
3140
|
(err) => {
|
|
2712
3141
|
attemptsInFlight--;
|
|
2713
|
-
|
|
3142
|
+
failWith(reasonForError(err), (err as Error)?.message || `could not reach ${step}`, err);
|
|
2714
3143
|
},
|
|
2715
3144
|
);
|
|
2716
3145
|
};
|
|
@@ -2931,7 +3360,7 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
2931
3360
|
// disappearing. Several things clear that field and only one of them is a decision; and a
|
|
2932
3361
|
// decision about one address is not an answer to a request about another.
|
|
2933
3362
|
if (askedAddress && acknowledgementsFor(askedAddress) !== acknowledgementsOnEntry) {
|
|
2934
|
-
cancelled();
|
|
3363
|
+
cancelled('address-unavailable-acknowledged');
|
|
2935
3364
|
return;
|
|
2936
3365
|
}
|
|
2937
3366
|
|
|
@@ -2947,20 +3376,23 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
2947
3376
|
// a generic cancellation.
|
|
2948
3377
|
const error = connection.error;
|
|
2949
3378
|
if (error && error !== errorOnEntry) {
|
|
2950
|
-
|
|
3379
|
+
// The reason is COPIED, never re-derived. Deriving it again here from `message` or from
|
|
3380
|
+
// `cause` is how the state an app renders and the error a caller catches come to disagree
|
|
3381
|
+
// about one event: they are the same failure, so they carry the same label by construction.
|
|
3382
|
+
failWith(error.reason, error.message, error.cause);
|
|
2951
3383
|
return;
|
|
2952
3384
|
}
|
|
2953
3385
|
|
|
2954
3386
|
// Reject on disconnect/back to Idle
|
|
2955
3387
|
if (connection.step === 'Idle' && idlePassed) {
|
|
2956
|
-
cancelled();
|
|
3388
|
+
cancelled('cancelled');
|
|
2957
3389
|
return;
|
|
2958
3390
|
}
|
|
2959
3391
|
|
|
2960
3392
|
// The attempt went back to a resting step without an error: it was aborted (back/cancel).
|
|
2961
3393
|
// This must never trigger on a resting step we merely started from, hence `attemptStarted`.
|
|
2962
3394
|
if (attemptStarted && stepsAtRest.includes(connection.step)) {
|
|
2963
|
-
cancelled();
|
|
3395
|
+
cancelled('cancelled');
|
|
2964
3396
|
return;
|
|
2965
3397
|
}
|
|
2966
3398
|
|
|
@@ -3003,18 +3435,29 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
3003
3435
|
// make impossible, and it is stated as a POSITIVE list (`awaitingUserReason`) on purpose:
|
|
3004
3436
|
// a new step, or a new resting reason, is unreachable-by-default rather than a fresh way
|
|
3005
3437
|
// to hang.
|
|
3006
|
-
const
|
|
3007
|
-
if (!
|
|
3438
|
+
const waitReason = awaitingUserReason(connection);
|
|
3439
|
+
if (!waitReason) {
|
|
3008
3440
|
// The message names where the connection actually is, including the wallet's status,
|
|
3009
3441
|
// because the likeliest way to arrive here is a wallet that went locked or was revoked
|
|
3010
3442
|
// between the attempt finishing and this state being published.
|
|
3011
3443
|
const wallet = connection.wallet ? ` (wallet ${connection.wallet.status})` : '';
|
|
3012
|
-
|
|
3013
|
-
|
|
3014
|
-
|
|
3015
|
-
|
|
3016
|
-
|
|
3017
|
-
|
|
3444
|
+
// SUPERSEDED, when a NEWER address-bound call is holding the connection's one account
|
|
3445
|
+
// slot: this call did not come to rest because the connection cannot get there, it came to
|
|
3446
|
+
// rest because the app itself asked for a different account in the meantime. The two are
|
|
3447
|
+
// indistinguishable from the state (the newer request took the `addressUnavailable` slot
|
|
3448
|
+
// with it, so there is nothing left on the connection to read), and telling them apart is
|
|
3449
|
+
// the difference between "this connection is stuck" and "retry, it was your own doing".
|
|
3450
|
+
//
|
|
3451
|
+
// The MESSAGE is unchanged, deliberately: it is the honest `could not reach ...` this path
|
|
3452
|
+
// has always produced, and specifically not a cancellation, because the user decided
|
|
3453
|
+
// nothing.
|
|
3454
|
+
const superseded =
|
|
3455
|
+
askedAddress !== undefined &&
|
|
3456
|
+
addressBoundRequestId !== undefined &&
|
|
3457
|
+
isSupersededBy(addressBoundRequestId, askedAddress);
|
|
3458
|
+
failWith(
|
|
3459
|
+
superseded ? 'superseded' : 'unreachable',
|
|
3460
|
+
`could not reach ${step}: the connection is at ${connection.step}${wallet} and nothing is in progress`,
|
|
3018
3461
|
);
|
|
3019
3462
|
}
|
|
3020
3463
|
};
|
|
@@ -3074,7 +3517,7 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
3074
3517
|
// through it) and report the error on the CURRENT state — throwing the choice away
|
|
3075
3518
|
// over a typo or a wallet uninstalled between render and click would deselect the
|
|
3076
3519
|
// user's read path without them refusing anything.
|
|
3077
|
-
setError({message: `failed to get wallet ${walletName}
|
|
3520
|
+
setError({message: `failed to get wallet ${walletName}`, reason: 'failed'});
|
|
3078
3521
|
return;
|
|
3079
3522
|
}
|
|
3080
3523
|
// Clear old wallet watchers if switching from a previously chosen/connected wallet.
|
|
@@ -3089,7 +3532,7 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
3089
3532
|
const provider = wallet.walletProvider;
|
|
3090
3533
|
const chainIdAsHex = await withTimeout(provider.getChainId());
|
|
3091
3534
|
const chainId = Number(chainIdAsHex).toString();
|
|
3092
|
-
_wallet = {chainId, provider};
|
|
3535
|
+
_wallet = {chainId, provider, info: wallet.info};
|
|
3093
3536
|
alwaysOnProviderWrapper.setWalletProvider(provider.underlyingProvider);
|
|
3094
3537
|
alwaysOnProviderWrapper.setWalletStatus('disconnected');
|
|
3095
3538
|
watchForChainIdChange(provider);
|
|
@@ -3118,7 +3561,7 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
3118
3561
|
// setConnectionFailure tears down the previously chosen wallet (provider still on
|
|
3119
3562
|
// the wrapper if the new wallet's getChainId threw before setWalletProvider) before
|
|
3120
3563
|
// landing on its `wallet: undefined` resting step.
|
|
3121
|
-
setConnectionFailure({message: `failed to select wallet ${walletName}`, cause: err});
|
|
3564
|
+
setConnectionFailure({message: `failed to select wallet ${walletName}`, cause: err, reason: reasonForError(err)});
|
|
3122
3565
|
}
|
|
3123
3566
|
}
|
|
3124
3567
|
|
|
@@ -3435,7 +3878,7 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
3435
3878
|
//
|
|
3436
3879
|
// `error` is omitted rather than set to `undefined` when there is none, so a successful
|
|
3437
3880
|
// switch does not silently clear an unrelated error the app has not shown yet.
|
|
3438
|
-
const doneAsking = (error?:
|
|
3881
|
+
const doneAsking = (error?: ConnectionError) => {
|
|
3439
3882
|
if ($connection.wallet) {
|
|
3440
3883
|
set({
|
|
3441
3884
|
...$connection,
|
|
@@ -3472,7 +3915,7 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
3472
3915
|
// this library's summary and the branch is reached both from a refusal to switch and
|
|
3473
3916
|
// from a wallet reporting its error as a result.
|
|
3474
3917
|
const message = `Chain "${named}" is not available on your wallet`;
|
|
3475
|
-
doneAsking({message, cause: err});
|
|
3918
|
+
doneAsking({message, cause: err, reason: reasonForError(err)});
|
|
3476
3919
|
throw new Error(message);
|
|
3477
3920
|
}
|
|
3478
3921
|
}
|
|
@@ -3499,7 +3942,7 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
3499
3942
|
return;
|
|
3500
3943
|
}
|
|
3501
3944
|
const message = `Failed to add new chain: ${named}`;
|
|
3502
|
-
doneAsking({message, cause: err});
|
|
3945
|
+
doneAsking({message, cause: err, reason: reasonForError(err)});
|
|
3503
3946
|
throw err;
|
|
3504
3947
|
}
|
|
3505
3948
|
}
|
|
@@ -3535,7 +3978,17 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
3535
3978
|
provider: alwaysOnProviderWrapper.provider,
|
|
3536
3979
|
chainId: '' + settings.chainInfo.id,
|
|
3537
3980
|
chainInfo: settings.chainInfo,
|
|
3538
|
-
|
|
3981
|
+
// Wrapped rather than passed straight through, so that a consumer driving its own UI from the
|
|
3982
|
+
// event stream sees exactly what `pendingRequests` shows: nothing at all for a wallet that
|
|
3983
|
+
// answers by itself. A consumer given the END of a request whose START it never saw would be
|
|
3984
|
+
// asked to close a dialog it never opened, so both halves are dropped or neither is.
|
|
3985
|
+
onRequest: (handler: RequestEventHandler) =>
|
|
3986
|
+
alwaysOnProviderWrapper.onRequest((event) => {
|
|
3987
|
+
if (silenced(event)) {
|
|
3988
|
+
return;
|
|
3989
|
+
}
|
|
3990
|
+
handler(event);
|
|
3991
|
+
}),
|
|
3539
3992
|
};
|
|
3540
3993
|
|
|
3541
3994
|
return store as ConnectionStore<WalletProviderType, TargetStep, boolean>;
|