@etherplay/connect 0.11.2 → 0.13.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 +195 -10
- package/dist/index.d.ts +177 -9
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +854 -102
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/src/index.ts +1129 -129
package/dist/index.js
CHANGED
|
@@ -8,30 +8,107 @@ export { fromEntropyKeyToMnemonic, originPublicKeyPublicationMessage, originKeyM
|
|
|
8
8
|
// digest, the ABI of the contract that verifies it, and the lookup that picks the credential for
|
|
9
9
|
// a (chainId, contract) pair out of `savedDelegations`.
|
|
10
10
|
delegationMessage, delegationDigest, DELEGATION_ABI, findSavedDelegation, };
|
|
11
|
+
// THE TARGET STEPS ARE ORDERED, and this array is the only place that says so.
|
|
12
|
+
//
|
|
13
|
+
// `SignedIn` implies `WalletConnected` implies `WalletChosen`, so "has this connection reached the
|
|
14
|
+
// target" is a comparison on this array rather than a hand-written comparison per step. It used to
|
|
15
|
+
// be written out three times, and one of the three (`ensureConnected`'s own `canResolve`) got the
|
|
16
|
+
// order right for `WalletChosen` and then compared the other two exactly, which did not answer
|
|
17
|
+
// wrong so much as never answer at all: a connection resting at `SignedIn` and asked for
|
|
18
|
+
// `WalletConnected` satisfied nothing, initiated nothing, and waited forever.
|
|
19
|
+
//
|
|
20
|
+
// A fourth step added to `TargetStep` lands here once, in order, and every satisfaction check
|
|
21
|
+
// follows.
|
|
22
|
+
const orderedTargetSteps = ['WalletChosen', 'WalletConnected', 'SignedIn'];
|
|
23
|
+
/**
|
|
24
|
+
* Is the connection AT OR BEYOND the target step?
|
|
25
|
+
*
|
|
26
|
+
* `requireWallet` is for the one case the order does not capture: `SignedIn` is the only target
|
|
27
|
+
* step reachable without a wallet (the hosted email/oauth/mnemonic mechanisms), so a wallet target
|
|
28
|
+
* is never satisfied by a state that has none, and a `SignedIn` target is only wallet-bound when
|
|
29
|
+
* the caller says so.
|
|
30
|
+
*/
|
|
31
|
+
function stepIsAtOrBeyond(connection, target, options) {
|
|
32
|
+
const reached = orderedTargetSteps.indexOf(connection.step);
|
|
33
|
+
if (reached === -1) {
|
|
34
|
+
// An in-progress or picker step is not a resting point at any target.
|
|
35
|
+
return false;
|
|
36
|
+
}
|
|
37
|
+
if (reached < orderedTargetSteps.indexOf(target)) {
|
|
38
|
+
return false;
|
|
39
|
+
}
|
|
40
|
+
if ((target !== 'SignedIn' || options?.requireWallet) && connection.wallet === undefined) {
|
|
41
|
+
return false;
|
|
42
|
+
}
|
|
43
|
+
return true;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* The resting reason, built in ONE place.
|
|
47
|
+
*
|
|
48
|
+
* Two sites produce it: the attempt that discovers the address is not on offer, and the account
|
|
49
|
+
* handler that keeps it true afterwards. They must word it identically, and a sentence written
|
|
50
|
+
* twice is a sentence that will disagree once.
|
|
51
|
+
*/
|
|
52
|
+
function describeAddressUnavailable(details) {
|
|
53
|
+
const named = details.walletName ? `Wallet "${details.walletName}"` : 'The wallet';
|
|
54
|
+
return {
|
|
55
|
+
...details,
|
|
56
|
+
message: details.selected
|
|
57
|
+
? `${named} is on ${details.selected} and cannot act as ${details.requested}. Switch to that account in the wallet, or cancel.`
|
|
58
|
+
: `${named} is not offering ${details.requested}. Select that account in the wallet, or cancel.`,
|
|
59
|
+
};
|
|
60
|
+
}
|
|
11
61
|
// Type guard - narrows Connection based on targetStep and walletOnly
|
|
12
62
|
// For 'WalletChosen' target: narrows to ChosenOrBetter (WalletChosen | WalletConnected | SignedIn-with-wallet)
|
|
13
63
|
// For 'WalletConnected' target: narrows to ConnectedWithWallet (WalletConnected | SignedIn-with-wallet)
|
|
14
64
|
// For 'SignedIn' target with walletOnly: narrows to SignedInWithWallet
|
|
15
65
|
// For 'SignedIn' target (default): narrows to SignedIn
|
|
16
66
|
export function isTargetStepReached(connection, targetStep, walletOnly) {
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
67
|
+
// One ordered comparison, shared with the store's own `isTargetStepReached` and with
|
|
68
|
+
// `ensureConnected`. `walletOnly` narrows the RETURN TYPE and, for a `SignedIn` target, also the
|
|
69
|
+
// check: a hosted sign-in has no wallet to act through.
|
|
70
|
+
return stepIsAtOrBeyond(connection, targetStep, { requireWallet: !!walletOnly });
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Can this connection sign as `address` RIGHT NOW, with no flow initiated and nothing prompted?
|
|
74
|
+
*
|
|
75
|
+
* The question `connection.account.address` does not answer. That field is the address the
|
|
76
|
+
* connection AGREED ON, which is the right thing for it to be: it survives the user locking their
|
|
77
|
+
* wallet, revoking the site, or switching account behind the connection's back, all of which keep
|
|
78
|
+
* `step: 'WalletConnected'` and change nothing about who was agreed on. What they change is whether
|
|
79
|
+
* anybody can sign, and that is what this reads (`wallet.status`, and the accounts the wallet is
|
|
80
|
+
* actually offering).
|
|
81
|
+
*
|
|
82
|
+
* It exists because a consumer needed it, wrote the comparison itself against `account.address`,
|
|
83
|
+
* and got a locked wallet wrong: it skipped its `ensureConnected` call, let the transaction out,
|
|
84
|
+
* and reported the provider's `{code: 4001}` as "transaction rejected by user" about a prompt
|
|
85
|
+
* nobody was ever shown. Use this to RENDER readiness (enable a button, show "unlock to pay"), and
|
|
86
|
+
* `ensureConnected(step, {type: 'wallet', address})` to actually reach it.
|
|
87
|
+
*
|
|
88
|
+
* Chain is deliberately not part of the answer: signing as an address is chain-independent, and
|
|
89
|
+
* `wallet.invalidChainId` is the separate question with its own separate remedy.
|
|
90
|
+
*/
|
|
91
|
+
export function canActAs(connection, address) {
|
|
92
|
+
const wanted = address.toLowerCase();
|
|
93
|
+
if (!connection.wallet || connection.wallet.status !== 'connected') {
|
|
94
|
+
return false;
|
|
22
95
|
}
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
return
|
|
96
|
+
const agreedOn = 'account' in connection ? connection.account?.address : undefined;
|
|
97
|
+
if (!agreedOn || agreedOn.toLowerCase() !== wanted) {
|
|
98
|
+
return false;
|
|
26
99
|
}
|
|
27
|
-
|
|
28
|
-
//
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
100
|
+
const offered = connection.wallet.accounts;
|
|
101
|
+
// An empty list is what a wallet that was never asked reports, not a denial; `status` is the
|
|
102
|
+
// authority there. A non-empty one that does not contain the address IS a denial.
|
|
103
|
+
//
|
|
104
|
+
// Defensive, and marked as such: no state this library builds reaches here with an empty list
|
|
105
|
+
// (the states that have one, like `WalletChosen`, carry no `account` and are answered above). It
|
|
106
|
+
// is kept for a custom connector that publishes `connected` before it has read any accounts, and
|
|
107
|
+
// it is deliberately not counted as covered by any test.
|
|
108
|
+
if (offered.length > 0 && !offered.some((account) => account.toLowerCase() === wanted)) {
|
|
109
|
+
return false;
|
|
32
110
|
}
|
|
33
|
-
|
|
34
|
-
return connection.step === 'SignedIn';
|
|
111
|
+
return true;
|
|
35
112
|
}
|
|
36
113
|
function viemChainInfoToSwitchChainInfo(chainInfo) {
|
|
37
114
|
return {
|
|
@@ -62,18 +139,87 @@ function withoutEntropyKey(account) {
|
|
|
62
139
|
const { mnemonicKey, ...signer } = account.signer;
|
|
63
140
|
return { ...account, signer };
|
|
64
141
|
}
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
142
|
+
/**
|
|
143
|
+
* Error thrown by `ensureConnected` when a connection attempt ends without reaching the target step.
|
|
144
|
+
*
|
|
145
|
+
* Three fields, answering three different questions:
|
|
146
|
+
*
|
|
147
|
+
* - `reason` — WHAT HAPPENED TO THIS CALL, in a closed vocabulary this library controls. Read this
|
|
148
|
+
* one to decide what to do. See `ConnectionFailureReason`, including its note on new members.
|
|
149
|
+
* - `cause` — the underlying error, exactly as whoever raised it wrote it (a wallet's EIP-1193
|
|
150
|
+
* error, the wallet host's `{type, message}` refusal). Unchanged by the arrival of `reason`.
|
|
151
|
+
* - `code` — the convenience copy of `cause.code`, so a user rejection is still `code === 4001`.
|
|
152
|
+
* `reason === 'wallet-rejected'` now says the same thing without the reach into `cause`.
|
|
153
|
+
*
|
|
154
|
+
* `message` is unchanged on every path, deliberately, including `'Connection cancelled'` for a
|
|
155
|
+
* dismissed `addressUnavailable`: the shape stays the safe one every consumer already maps to "the
|
|
156
|
+
* user chose not to", and `reason` says which of those it was.
|
|
157
|
+
*
|
|
158
|
+
* The third constructor argument is optional so that constructing one by hand (a test double, a
|
|
159
|
+
* consumer's own re-throw) keeps compiling; inside this library every failure comes from one place
|
|
160
|
+
* that always supplies it.
|
|
161
|
+
*/
|
|
68
162
|
export class ConnectionFailure extends Error {
|
|
69
163
|
name = 'ConnectionFailure';
|
|
70
164
|
code;
|
|
71
|
-
|
|
165
|
+
reason;
|
|
166
|
+
constructor(message, cause, reason = 'failed') {
|
|
72
167
|
super(message);
|
|
73
168
|
this.cause = cause;
|
|
74
169
|
this.code = cause?.code;
|
|
170
|
+
this.reason = reason;
|
|
75
171
|
}
|
|
76
172
|
}
|
|
173
|
+
/**
|
|
174
|
+
* What an error THROWN AT US means, in the vocabulary above.
|
|
175
|
+
*
|
|
176
|
+
* One function rather than a test repeated at each catch site, because the mapping is the part that
|
|
177
|
+
* has to stay consistent: the same rejected wallet prompt must read as `wallet-rejected` whether it
|
|
178
|
+
* arrives from `eth_requestAccounts`, from a signature request, or from an attempt that rejected
|
|
179
|
+
* before it published anything.
|
|
180
|
+
*
|
|
181
|
+
* Only shapes this library can actually VERIFY are mapped. EIP-1193 codes are a standard the wallet
|
|
182
|
+
* and this library both agree on, and `cross-origin-blocked` is minted by `@etherplay/connect-core`
|
|
183
|
+
* in this same repo. Everything else keeps its own words on `cause` and lands on the catch-all.
|
|
184
|
+
*
|
|
185
|
+
* Note what this deliberately does NOT do: an unknown `{type}` does not become `host-refused` here,
|
|
186
|
+
* because an arbitrary thrown object carrying a `type` is not evidence that a HOST refused
|
|
187
|
+
* anything. Host refusals reach the connection through the popup catch, which uses
|
|
188
|
+
* `reasonForHostRefusal` instead. No path currently throws a host refusal INTO this function; if
|
|
189
|
+
* one ever does, it will read as `failed`, and this is the comment that says to route it through
|
|
190
|
+
* `reasonForHostRefusal` at that point rather than loosening the test here.
|
|
191
|
+
*/
|
|
192
|
+
function reasonForError(err) {
|
|
193
|
+
const code = err?.code;
|
|
194
|
+
if (code === 4001) {
|
|
195
|
+
return 'wallet-rejected';
|
|
196
|
+
}
|
|
197
|
+
if (code === 4100) {
|
|
198
|
+
return 'wallet-unavailable';
|
|
199
|
+
}
|
|
200
|
+
if (err?.type === 'cross-origin-blocked') {
|
|
201
|
+
return 'cross-origin-blocked';
|
|
202
|
+
}
|
|
203
|
+
return 'failed';
|
|
204
|
+
}
|
|
205
|
+
/**
|
|
206
|
+
* What a WALLET HOST refusal means, in the vocabulary above.
|
|
207
|
+
*
|
|
208
|
+
* The host is deployed separately and picks its own `type` strings, so only types this library can
|
|
209
|
+
* verify are mapped, and everything else passes through as `host-refused` with the host's own
|
|
210
|
+
* `type` left intact on `cause`. Inventing a member per host vocabulary word would be claiming to
|
|
211
|
+
* know something this package cannot check, and would go stale the moment the host shipped a new
|
|
212
|
+
* one.
|
|
213
|
+
*
|
|
214
|
+
* Exactly ONE type is mapped here, `cross-origin-blocked`, which comes from
|
|
215
|
+
* `@etherplay/connect-core` in this repo. The other verifiable type, `cancelation` (raised by this
|
|
216
|
+
* package's own popup, `src/popup.ts`), is handled by the CALLER and never reaches this function:
|
|
217
|
+
* closing the popup sets no error at all, and `ensureConnected` reports it through its own
|
|
218
|
+
* cancellation branch. A `undefined` refusal likewise cannot arrive, for the same reason.
|
|
219
|
+
*/
|
|
220
|
+
function reasonForHostRefusal(refusal) {
|
|
221
|
+
return refusal?.type === 'cross-origin-blocked' ? 'cross-origin-blocked' : 'host-refused';
|
|
222
|
+
}
|
|
77
223
|
// Steps where a connection attempt is actively in progress: reaching one of them means an attempt started,
|
|
78
224
|
// and staying in one means we should keep waiting.
|
|
79
225
|
const stepsInProgress = [
|
|
@@ -176,6 +322,11 @@ export function createConnection(settings) {
|
|
|
176
322
|
if (!connection.wallet && connection.step !== 'WaitingForWalletConnection') {
|
|
177
323
|
teardownWallet();
|
|
178
324
|
}
|
|
325
|
+
// The address a resting reason last named, kept so a dismissal can be attributed to the request
|
|
326
|
+
// the user was looking at even if an attempt clears the field a moment before they click.
|
|
327
|
+
if (connection.addressUnavailable) {
|
|
328
|
+
lastPublishedAddressUnavailable = connection.addressUnavailable.requested;
|
|
329
|
+
}
|
|
179
330
|
const pendingRequests = currentPendingRequests();
|
|
180
331
|
if (!connection.wallet) {
|
|
181
332
|
$connection = { ...connection, pendingRequests };
|
|
@@ -236,6 +387,11 @@ export function createConnection(settings) {
|
|
|
236
387
|
//
|
|
237
388
|
// Auto-connect failures follow the same rule and rest on `Idle`: the user asked for nothing, so there is
|
|
238
389
|
// no decision to offer them. A cancelled popup is likewise a cancellation, not a failure, and rests on `Idle`.
|
|
390
|
+
//
|
|
391
|
+
// `error` carries a REQUIRED `reason` (see `ConnectionFailureReason`). That is not decoration: a
|
|
392
|
+
// pending `ensureConnected` copies it onto the `ConnectionFailure` it rejects with, so what the
|
|
393
|
+
// app renders and what the caller catches cannot disagree, and requiring it here is what makes
|
|
394
|
+
// the compiler enumerate the producers instead of leaving the next one to remember.
|
|
239
395
|
function setConnectionFailure(error) {
|
|
240
396
|
const wallets = $connection.wallets;
|
|
241
397
|
// Every resting state below has `wallet: undefined`, so `set` tears the live wallet down.
|
|
@@ -268,6 +424,114 @@ export function createConnection(settings) {
|
|
|
268
424
|
});
|
|
269
425
|
}
|
|
270
426
|
}
|
|
427
|
+
/**
|
|
428
|
+
* The user has read "your wallet is not on that account" and chosen not to switch.
|
|
429
|
+
*
|
|
430
|
+
* THAT IS A CANCELLATION, and it settles the pending `ensureConnected` as one: the same
|
|
431
|
+
* `ConnectionFailure('Connection cancelled')` a `cancel()` or a `back()` produces, so an app that
|
|
432
|
+
* already maps a refusal to "the user chose not to" needs no new branch and shows no red error
|
|
433
|
+
* for a decision.
|
|
434
|
+
*
|
|
435
|
+
* The connection itself is left exactly as it is, deliberately. It is CONNECTED, on the account
|
|
436
|
+
* the wallet is actually offering, and "connected as somebody else, and saying so" is a better
|
|
437
|
+
* place to leave a user than "not connected at all" — which is what the alternative, failing the
|
|
438
|
+
* attempt, produced: every failure state carries `wallet: undefined`.
|
|
439
|
+
*/
|
|
440
|
+
function acknowledgeAddressUnavailable() {
|
|
441
|
+
// WHICH request the user dismissed: the one on screen, or the one that was on screen a moment
|
|
442
|
+
// ago if an attempt has just cleared the field out from under them.
|
|
443
|
+
const dismissed = $connection.addressUnavailable?.requested ?? lastPublishedAddressUnavailable;
|
|
444
|
+
if (dismissed) {
|
|
445
|
+
const key = dismissed.toLowerCase();
|
|
446
|
+
addressUnavailableAcknowledgements.set(key, (addressUnavailableAcknowledgements.get(key) ?? 0) + 1);
|
|
447
|
+
}
|
|
448
|
+
// COUNTED, not inferred. A pending `ensureConnected` used to read the reason DISAPPEARING as
|
|
449
|
+
// the dismissal, which is true of this method and of nothing else — and plenty else clears it:
|
|
450
|
+
// the app calling `connect()` itself, a `useCurrentAccount` store following the wallet onto
|
|
451
|
+
// another account, the reason ceasing to be true. Each of those was reported to the caller as
|
|
452
|
+
// `Connection cancelled`, which consumers are told to treat as "the user chose not to", so an
|
|
453
|
+
// event the user never caused was invisible to them.
|
|
454
|
+
//
|
|
455
|
+
// Republished even when the field is already gone (an attempt may have cleared it a moment
|
|
456
|
+
// ago): the publish is what wakes a pending `ensureConnected` to notice the dismissal. Without
|
|
457
|
+
// it, a click landing in that window is counted and then never acted on, which is a wait that
|
|
458
|
+
// nothing ends.
|
|
459
|
+
set({
|
|
460
|
+
...$connection,
|
|
461
|
+
addressUnavailable: undefined,
|
|
462
|
+
});
|
|
463
|
+
}
|
|
464
|
+
// Dismissals of "your wallet is not on that account", COUNTED PER ADDRESS. See
|
|
465
|
+
// `acknowledgeAddressUnavailable`: a pending `ensureConnected` watches the count for the address
|
|
466
|
+
// IT asked about, so that a decision is told apart both from the several other things that clear
|
|
467
|
+
// the same field and from a decision about somebody else's request. A single global count made
|
|
468
|
+
// one dismissal cancel every address-bound call on the connection, including one whose wallet
|
|
469
|
+
// prompt was open at that moment.
|
|
470
|
+
const addressUnavailableAcknowledgements = new Map();
|
|
471
|
+
function acknowledgementsFor(address) {
|
|
472
|
+
return addressUnavailableAcknowledgements.get(address.toLowerCase()) ?? 0;
|
|
473
|
+
}
|
|
474
|
+
// The reason most recently PUBLISHED, so that a dismissal arriving in the brief window where an
|
|
475
|
+
// attempt has cleared the field still names the address the user was actually looking at.
|
|
476
|
+
let lastPublishedAddressUnavailable;
|
|
477
|
+
/**
|
|
478
|
+
* The address-bound `ensureConnected` calls that are still live on this connection, in the order
|
|
479
|
+
* they were made. Mirrors `addressUnavailableAcknowledgements` above: per connection, per address,
|
|
480
|
+
* kept by the one thing that knows.
|
|
481
|
+
*
|
|
482
|
+
* WHY IT EXISTS. A connection has one wallet, one account and one `addressUnavailable` slot, so a
|
|
483
|
+
* second call naming a DIFFERENT address supersedes the first: the newer request takes the slot,
|
|
484
|
+
* the older one loses the state it was resting on and comes to rest with nothing in progress. That
|
|
485
|
+
* is a real answer and it was already delivered honestly (`could not reach ...`, never a
|
|
486
|
+
* cancellation the user did not make), but it arrived looking exactly like every other
|
|
487
|
+
* come-to-rest, so no consumer could tell "your own app asked for something else" from "this
|
|
488
|
+
* connection cannot get there". Only ONE call knows the difference and it is not the one being
|
|
489
|
+
* answered, which is why supersession cannot be read off the connection state and needs a
|
|
490
|
+
* registry.
|
|
491
|
+
*
|
|
492
|
+
* Registration is a monotonic id rather than a set, because the question is ordered: an OLDER
|
|
493
|
+
* request is superseded by a NEWER one, never the other way round.
|
|
494
|
+
*
|
|
495
|
+
* WHAT IT IS AND IS NOT. `superseded` says "a later live request names another account", which is
|
|
496
|
+
* an over-approximation of "that request is what displaced me": if some third thing (the app's own
|
|
497
|
+
* `connect()`, a disconnect) ends both at once, the older is still labelled superseded. That is
|
|
498
|
+
* the harmless direction, since the newer request was going to take the slot anyway, and the
|
|
499
|
+
* remedy the label implies (retry) is the right one either way. The opposite error is avoided by
|
|
500
|
+
* construction: a call that resolves without ever waiting returns before it registers.
|
|
501
|
+
*
|
|
502
|
+
* An entry lives exactly as long as its promise is unsettled, which for an abandoned call means as
|
|
503
|
+
* long as the promise itself: this map holds no more than the pending calls already do.
|
|
504
|
+
*/
|
|
505
|
+
let addressBoundRequests = 0;
|
|
506
|
+
const liveAddressBoundRequests = new Map();
|
|
507
|
+
function registerAddressBoundRequest(address) {
|
|
508
|
+
const id = ++addressBoundRequests;
|
|
509
|
+
liveAddressBoundRequests.set(id, address.toLowerCase());
|
|
510
|
+
return id;
|
|
511
|
+
}
|
|
512
|
+
/** Is a LATER live request naming a DIFFERENT address, i.e. holding the slot this one needs? */
|
|
513
|
+
function isSupersededBy(id, address) {
|
|
514
|
+
const asked = address.toLowerCase();
|
|
515
|
+
for (const [otherId, otherAddress] of liveAddressBoundRequests) {
|
|
516
|
+
if (otherId > id && otherAddress !== asked) {
|
|
517
|
+
return true;
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
return false;
|
|
521
|
+
}
|
|
522
|
+
// How many times the user's WALLET has announced a DIFFERENT set of accounts. It is the unit
|
|
523
|
+
// `ensureConnected` retries on, and it is the honest one: a retry is a response to the user
|
|
524
|
+
// having done something in their wallet, so at most one attempt per announcement bounds the work
|
|
525
|
+
// while never refusing to act on a real gesture. Counting distinct STATES instead looks stricter
|
|
526
|
+
// and refuses the retry when the user returns to a state seen before, which is a normal thing for
|
|
527
|
+
// a person to do.
|
|
528
|
+
//
|
|
529
|
+
// Only a CHANGE counts, and only an account one. The lock poll re-announces an empty list every
|
|
530
|
+
// second, which is the absence of news rather than news, and would otherwise re-license an attempt
|
|
531
|
+
// per second on a locked wallet; a chain change is news, but not news about accounts, and
|
|
532
|
+
// re-prompting for an account because the user switched network answers a question they did not
|
|
533
|
+
// ask.
|
|
534
|
+
let walletAnnouncements = 0;
|
|
271
535
|
let _wallet;
|
|
272
536
|
let popup;
|
|
273
537
|
// Wallet announcements are not guaranteed to be unique.
|
|
@@ -631,7 +895,10 @@ export function createConnection(settings) {
|
|
|
631
895
|
name: $connection.mechanism.name,
|
|
632
896
|
address: $connection.mechanism.address,
|
|
633
897
|
},
|
|
634
|
-
|
|
898
|
+
// A declined signature prompt is the same 4001 a declined connect is, and the same
|
|
899
|
+
// mapping names it: an app that offers "try again" on a rejection must not have to know
|
|
900
|
+
// which prompt was rejected to recognise one.
|
|
901
|
+
error: { message: 'failed to sign message', cause: err, reason: reasonForError(err) },
|
|
635
902
|
});
|
|
636
903
|
return;
|
|
637
904
|
}
|
|
@@ -708,12 +975,32 @@ export function createConnection(settings) {
|
|
|
708
975
|
// TODO lastAccount
|
|
709
976
|
// console.log('account changed', accounts);
|
|
710
977
|
const accountsFormated = accounts.map((a) => a.toLowerCase());
|
|
978
|
+
// NEWS is an announcement that differs from what the connection currently believes — not one
|
|
979
|
+
// that differs from the previous announcement. The two come apart exactly where it matters: an
|
|
980
|
+
// attempt can go and find something else in between, so a wallet announcing the same list twice
|
|
981
|
+
// with a contradicting answer in the middle is telling us something the second time too.
|
|
982
|
+
if (accountsFormated.join(',') !== ($connection.wallet?.accounts ?? []).join(',')) {
|
|
983
|
+
walletAnnouncements++;
|
|
984
|
+
}
|
|
985
|
+
// A RESTING "your wallet is not on that account" MUST KEEP DESCRIBING THE WALLET AS IT IS.
|
|
986
|
+
//
|
|
987
|
+
// Every `set` below rebuilds the state by spreading the current one, so the reason would
|
|
988
|
+
// survive an account change untouched: right about the FACT (the wallet still cannot act as
|
|
989
|
+
// the requested account) and wrong about the DETAIL, since it would go on naming an account
|
|
990
|
+
// the user has already left, and the app renders that sentence as the instruction. Telling
|
|
991
|
+
// somebody to switch away from an account they are not on is worse than saying nothing.
|
|
992
|
+
//
|
|
993
|
+
// Computed here and published WITH the accounts rather than corrected afterwards, so that no
|
|
994
|
+
// intermediate state is ever published in which the two disagree — a correction one publish
|
|
995
|
+
// later is a frame of wrong instruction, which is exactly what an app renders.
|
|
996
|
+
const addressUnavailable = refreshedAddressUnavailable(accountsFormated);
|
|
711
997
|
if ($connection.wallet) {
|
|
712
998
|
const locked = accountsFormated.length == 0;
|
|
713
999
|
const addressSignedIn = $connection.mechanism.address;
|
|
714
1000
|
if (locked) {
|
|
715
1001
|
set({
|
|
716
1002
|
...$connection,
|
|
1003
|
+
addressUnavailable,
|
|
717
1004
|
wallet: {
|
|
718
1005
|
...$connection.wallet,
|
|
719
1006
|
status: 'locked',
|
|
@@ -727,6 +1014,7 @@ export function createConnection(settings) {
|
|
|
727
1014
|
if (disconnected) {
|
|
728
1015
|
set({
|
|
729
1016
|
...$connection,
|
|
1017
|
+
addressUnavailable,
|
|
730
1018
|
wallet: {
|
|
731
1019
|
...$connection.wallet,
|
|
732
1020
|
status: 'disconnected',
|
|
@@ -738,6 +1026,7 @@ export function createConnection(settings) {
|
|
|
738
1026
|
else {
|
|
739
1027
|
set({
|
|
740
1028
|
...$connection,
|
|
1029
|
+
addressUnavailable,
|
|
741
1030
|
wallet: {
|
|
742
1031
|
...$connection.wallet,
|
|
743
1032
|
status: 'connected',
|
|
@@ -755,6 +1044,7 @@ export function createConnection(settings) {
|
|
|
755
1044
|
else {
|
|
756
1045
|
set({
|
|
757
1046
|
...$connection,
|
|
1047
|
+
addressUnavailable,
|
|
758
1048
|
wallet: {
|
|
759
1049
|
...$connection.wallet,
|
|
760
1050
|
accountChanged: accountsFormated[0],
|
|
@@ -766,6 +1056,7 @@ export function createConnection(settings) {
|
|
|
766
1056
|
else {
|
|
767
1057
|
set({
|
|
768
1058
|
...$connection,
|
|
1059
|
+
addressUnavailable,
|
|
769
1060
|
wallet: {
|
|
770
1061
|
...$connection.wallet,
|
|
771
1062
|
accountChanged: undefined,
|
|
@@ -775,6 +1066,32 @@ export function createConnection(settings) {
|
|
|
775
1066
|
}
|
|
776
1067
|
}
|
|
777
1068
|
}
|
|
1069
|
+
/**
|
|
1070
|
+
* The resting reason, re-derived against what the wallet is offering now.
|
|
1071
|
+
*
|
|
1072
|
+
* `undefined` once the wallet DOES offer the requested account: the reason has simply stopped
|
|
1073
|
+
* being true. A pending `ensureConnected` loses nothing by that — it watches the accounts the
|
|
1074
|
+
* wallet offers rather than this field, precisely so that the state going away because the user
|
|
1075
|
+
* fixed it cannot be mistaken for the user dismissing it.
|
|
1076
|
+
*/
|
|
1077
|
+
function refreshedAddressUnavailable(offered) {
|
|
1078
|
+
const unavailable = $connection.addressUnavailable;
|
|
1079
|
+
if (!unavailable) {
|
|
1080
|
+
return undefined;
|
|
1081
|
+
}
|
|
1082
|
+
if (offered.some((account) => account.toLowerCase() === unavailable.requested.toLowerCase())) {
|
|
1083
|
+
return undefined;
|
|
1084
|
+
}
|
|
1085
|
+
if (offered.join(',') === unavailable.available.join(',')) {
|
|
1086
|
+
return unavailable;
|
|
1087
|
+
}
|
|
1088
|
+
return describeAddressUnavailable({
|
|
1089
|
+
requested: unavailable.requested,
|
|
1090
|
+
walletName: unavailable.walletName,
|
|
1091
|
+
selected: offered[0],
|
|
1092
|
+
available: offered,
|
|
1093
|
+
});
|
|
1094
|
+
}
|
|
778
1095
|
// TODO lastAccounts
|
|
779
1096
|
let lockCheckInterval;
|
|
780
1097
|
async function checkLockStatus() {
|
|
@@ -835,7 +1152,11 @@ export function createConnection(settings) {
|
|
|
835
1152
|
//
|
|
836
1153
|
// Returns false when the flow was not upgrading from WalletChosen (no chosen mechanism or
|
|
837
1154
|
// wallet was captured), so the caller falls back to the ordinary connection-failure handling.
|
|
838
|
-
function restoreWalletChosenAfterFailedConnect(errorMessage, cause,
|
|
1155
|
+
function restoreWalletChosenAfterFailedConnect(errorMessage, cause,
|
|
1156
|
+
// Taken as an argument rather than derived from `cause` here: this function is the RESTING
|
|
1157
|
+
// half of a failure whose other half is `setConnectionFailure`, and the two must label the
|
|
1158
|
+
// same event identically. An empty accounts answer has no `cause` to derive anything from.
|
|
1159
|
+
reason, chosenMechanism, chosenWallet) {
|
|
839
1160
|
if (!chosenMechanism || !chosenWallet) {
|
|
840
1161
|
return false;
|
|
841
1162
|
}
|
|
@@ -873,7 +1194,7 @@ export function createConnection(settings) {
|
|
|
873
1194
|
invalidChainId: alwaysOnChainId != chainId,
|
|
874
1195
|
switchingChain: false,
|
|
875
1196
|
},
|
|
876
|
-
error: { message: errorMessage, cause },
|
|
1197
|
+
error: { message: errorMessage, cause, reason },
|
|
877
1198
|
});
|
|
878
1199
|
return true;
|
|
879
1200
|
}
|
|
@@ -914,10 +1235,21 @@ export function createConnection(settings) {
|
|
|
914
1235
|
}
|
|
915
1236
|
let remember = false;
|
|
916
1237
|
/**
|
|
917
|
-
* @param internal not part of the public `connect` surface.
|
|
918
|
-
*
|
|
919
|
-
*
|
|
920
|
-
* `
|
|
1238
|
+
* @param internal not part of the public `connect` surface. THREE things an address can mean,
|
|
1239
|
+
* and they are told apart here rather than by inspecting the caller:
|
|
1240
|
+
*
|
|
1241
|
+
* - nothing set: a DEMAND. `connectToAddress(a)` and `connect({type: 'wallet', address: a})` mean
|
|
1242
|
+
* that account and no other, so a wallet that cannot offer it fails the attempt.
|
|
1243
|
+
* - `addressIsPreference`: a mechanism this library REPLAYED from the current state rather than
|
|
1244
|
+
* one anybody asked for, so a vanished address degrades to an ordinary connect.
|
|
1245
|
+
* - `reportUnavailableAddress`: a demand the caller wants REPORTED rather than thrown, which is
|
|
1246
|
+
* what `ensureConnected` asks for. Failing the attempt tears the wallet down (every failure
|
|
1247
|
+
* state carries `wallet: undefined`), which is the worst of the three endings: the user is left
|
|
1248
|
+
* with no wallet at all over a wallet that is working and merely on another account. So the
|
|
1249
|
+
* attempt completes on what the wallet does offer and comes to rest carrying
|
|
1250
|
+
* `addressUnavailable`, which is a state the app can render and the user can answer.
|
|
1251
|
+
*
|
|
1252
|
+
* See `resolveRequestedAddress` below.
|
|
921
1253
|
*/
|
|
922
1254
|
async function connect(mechanism, options, internal) {
|
|
923
1255
|
if (!mechanism && (targetStep === 'WalletConnected' || walletOnly)) {
|
|
@@ -933,7 +1265,14 @@ export function createConnection(settings) {
|
|
|
933
1265
|
// different wallet.
|
|
934
1266
|
const chosenMechanismBeforeConnect = $connection.step === 'WalletChosen' ? $connection.mechanism : undefined;
|
|
935
1267
|
const chosenWalletBeforeConnect = $connection.step === 'WalletChosen' ? _wallet : undefined;
|
|
936
|
-
|
|
1268
|
+
// LOWERCASED HERE, at the boundary, because everything downstream compares against the
|
|
1269
|
+
// wallet's accounts, which are lowercased on arrival. A checksummed address (what a viem
|
|
1270
|
+
// local account hands back, so a perfectly ordinary thing for a caller to be holding) would
|
|
1271
|
+
// otherwise fail to match a wallet that is holding that very account. It was a latent
|
|
1272
|
+
// papercut while an unmatched address merely failed the attempt; now that a caller's address
|
|
1273
|
+
// is a requirement, it would send the user an instruction to switch to the account they are
|
|
1274
|
+
// already on.
|
|
1275
|
+
const specificAddress = mechanism.address?.toLowerCase();
|
|
937
1276
|
// WHICH ACCOUNT THE ATTEMPT IS FOR, once the wallet has said what it has.
|
|
938
1277
|
//
|
|
939
1278
|
// An address the CALLER named is a demand: `connectToAddress(a)` and
|
|
@@ -948,6 +1287,13 @@ export function createConnection(settings) {
|
|
|
948
1287
|
// threw, which landed in the catch and tore the wallet down: the reconnect performed the
|
|
949
1288
|
// very teardown it exists to prevent, one step later. Degrading to an ordinary connect is
|
|
950
1289
|
// what the caller asked for anyway, since it asked to be connected and named nothing.
|
|
1290
|
+
//
|
|
1291
|
+
// The third possibility is `reportUnavailableAddress`: the demand stands, but the answer is
|
|
1292
|
+
// a state rather than a failure. `unavailableAddress` is what records it, and it is read
|
|
1293
|
+
// twice below — once to keep the flow off `ChooseWalletAccount` (the caller named an
|
|
1294
|
+
// account; offering a picker instead of saying why they cannot have it is answering a
|
|
1295
|
+
// different question), and once to stamp `addressUnavailable` on the resting state.
|
|
1296
|
+
let unavailableAddress;
|
|
951
1297
|
const resolveRequestedAddress = (available) => {
|
|
952
1298
|
if (!specificAddress || available.includes(specificAddress)) {
|
|
953
1299
|
return specificAddress;
|
|
@@ -955,11 +1301,25 @@ export function createConnection(settings) {
|
|
|
955
1301
|
if (internal?.addressIsPreference) {
|
|
956
1302
|
return undefined;
|
|
957
1303
|
}
|
|
1304
|
+
if (internal?.reportUnavailableAddress) {
|
|
1305
|
+
unavailableAddress = specificAddress;
|
|
1306
|
+
return undefined;
|
|
1307
|
+
}
|
|
958
1308
|
throw new Error(`could not find address ${specificAddress}`);
|
|
959
1309
|
};
|
|
960
1310
|
const walletName = mechanism.name ||
|
|
961
1311
|
($connection.step === 'WalletChosen' ? $connection.mechanism.name : undefined) ||
|
|
962
1312
|
($connection.wallets.length == 1 ? $connection.wallets[0].info.name : undefined);
|
|
1313
|
+
/**
|
|
1314
|
+
* The resting reason to publish beside a connection that came back as somebody else.
|
|
1315
|
+
*
|
|
1316
|
+
* Everything the app needs to write the instruction is on it, including the accounts the
|
|
1317
|
+
* wallet IS offering: "switch account" is not actionable advice if the user cannot see
|
|
1318
|
+
* which account the wallet thinks it is on.
|
|
1319
|
+
*/
|
|
1320
|
+
const addressUnavailableFor = (available, selected) => unavailableAddress
|
|
1321
|
+
? describeAddressUnavailable({ requested: unavailableAddress, walletName, selected, available })
|
|
1322
|
+
: undefined;
|
|
963
1323
|
if (walletName) {
|
|
964
1324
|
const wallet = $connection.wallets.find((v) => v.info.name == walletName || v.info.uuid == walletName);
|
|
965
1325
|
if (wallet) {
|
|
@@ -1002,7 +1362,10 @@ export function createConnection(settings) {
|
|
|
1002
1362
|
accounts = accounts.map((v) => v.toLowerCase());
|
|
1003
1363
|
if (accounts.length > 0) {
|
|
1004
1364
|
const requestedAddress = resolveRequestedAddress(accounts);
|
|
1005
|
-
|
|
1365
|
+
// `!unavailableAddress`: the caller named an account and cannot have it. An account
|
|
1366
|
+
// picker would answer a question they did not ask; they get the wallet's current
|
|
1367
|
+
// account plus a resting reason naming every account it does offer.
|
|
1368
|
+
const nextStep = !settings?.useCurrentAccount && !requestedAddress && !unavailableAddress && accounts.length > 1
|
|
1006
1369
|
? 'ChooseWalletAccount'
|
|
1007
1370
|
: 'WalletConnected';
|
|
1008
1371
|
const account = requestedAddress || accounts[0];
|
|
@@ -1038,8 +1401,13 @@ export function createConnection(settings) {
|
|
|
1038
1401
|
switchingChain: false,
|
|
1039
1402
|
},
|
|
1040
1403
|
account: { address: account },
|
|
1404
|
+
addressUnavailable: addressUnavailableFor(accounts, account),
|
|
1041
1405
|
};
|
|
1406
|
+
// `!unavailableAddress`: do not raise a SIGNATURE prompt for an account the caller
|
|
1407
|
+
// did not ask to sign as. The instruction has to reach the user before anything
|
|
1408
|
+
// else asks them for something.
|
|
1042
1409
|
if (newState.step === 'WalletConnected' &&
|
|
1410
|
+
!unavailableAddress &&
|
|
1043
1411
|
(requestSignatureAutomaticallyIfPossible || options?.requestSignatureRightAway) &&
|
|
1044
1412
|
!options?.requireUserConfirmationBeforeSignatureRequest) {
|
|
1045
1413
|
watchForAccountChange(_wallet.provider);
|
|
@@ -1061,15 +1429,21 @@ export function createConnection(settings) {
|
|
|
1061
1429
|
// An empty accounts answer after a successful request is a failed
|
|
1062
1430
|
// upgrade when coming from WalletChosen: keep the choice, exactly as
|
|
1063
1431
|
// the catch block does for a REJECTED accounts request.
|
|
1064
|
-
if (!restoreWalletChosenAfterFailedConnect('could not get any accounts', undefined,
|
|
1065
|
-
|
|
1432
|
+
if (!restoreWalletChosenAfterFailedConnect('could not get any accounts', undefined,
|
|
1433
|
+
// `no-accounts`, NOT a cancellation. The wallet answered, and answered with
|
|
1434
|
+
// nothing: from the outside that looks like a refusal and it is not one, which
|
|
1435
|
+
// is exactly the aliasing a consumer's own sniffing module got wrong.
|
|
1436
|
+
'no-accounts', chosenMechanismBeforeConnect, chosenWalletBeforeConnect)) {
|
|
1437
|
+
setConnectionFailure({ message: 'could not get any accounts', reason: 'no-accounts' });
|
|
1066
1438
|
}
|
|
1067
1439
|
}
|
|
1068
1440
|
}
|
|
1069
1441
|
else {
|
|
1070
1442
|
const requestedAddress = resolveRequestedAddress(accounts);
|
|
1071
1443
|
const account = requestedAddress || accounts[0];
|
|
1072
|
-
|
|
1444
|
+
// See the same expression on the requestAccounts branch above: a caller who named an
|
|
1445
|
+
// account gets a reason, not a picker.
|
|
1446
|
+
const nextStep = !settings?.useCurrentAccount && !requestedAddress && !unavailableAddress && accounts.length > 1
|
|
1073
1447
|
? 'ChooseWalletAccount'
|
|
1074
1448
|
: 'WalletConnected';
|
|
1075
1449
|
const newState = nextStep === 'ChooseWalletAccount'
|
|
@@ -1104,8 +1478,10 @@ export function createConnection(settings) {
|
|
|
1104
1478
|
switchingChain: false,
|
|
1105
1479
|
},
|
|
1106
1480
|
account: { address: account },
|
|
1481
|
+
addressUnavailable: addressUnavailableFor(accounts, account),
|
|
1107
1482
|
};
|
|
1108
1483
|
if (newState.step === 'WalletConnected' &&
|
|
1484
|
+
!unavailableAddress &&
|
|
1109
1485
|
(requestSignatureAutomaticallyIfPossible || options?.requestSignatureRightAway) &&
|
|
1110
1486
|
!options?.requireUserConfirmationBeforeSignatureRequest) {
|
|
1111
1487
|
set(newState);
|
|
@@ -1131,6 +1507,12 @@ export function createConnection(settings) {
|
|
|
1131
1507
|
// read-only, locked, or not yet configured (e.g. werust's keyless
|
|
1132
1508
|
// provider). 4001 (User Rejected Request): the user actively declined in
|
|
1133
1509
|
// the wallet popup. Anything else is a genuine failure.
|
|
1510
|
+
// The message picked per code below and the `reason` a consumer reads instead of
|
|
1511
|
+
// re-deriving it are two lists over the same two codes. They agree today and nothing
|
|
1512
|
+
// COUPLES them: a third message added here without a matching member in
|
|
1513
|
+
// `reasonForError` would be prose the discriminant does not know about. Deriving the
|
|
1514
|
+
// message from the reason would fix that and would change every message string, which
|
|
1515
|
+
// this change is not allowed to do.
|
|
1134
1516
|
const code = err?.code;
|
|
1135
1517
|
let errorMessage = `failed to connect to wallet`;
|
|
1136
1518
|
if (code === 4100) {
|
|
@@ -1148,14 +1530,21 @@ export function createConnection(settings) {
|
|
|
1148
1530
|
// also tears the wallet down, because every failure state's `wallet` is
|
|
1149
1531
|
// `undefined` — a failed attempt must not keep routing requests (including
|
|
1150
1532
|
// read-only RPC calls like eth_call) through the failed wallet.
|
|
1151
|
-
|
|
1152
|
-
|
|
1533
|
+
// ONE derivation, read by both halves of the failure. The restore path and
|
|
1534
|
+
// `setConnectionFailure` are two landings for the same event, so a reason computed
|
|
1535
|
+
// twice is two chances to compute it differently.
|
|
1536
|
+
const reason = reasonForError(err);
|
|
1537
|
+
if (!restoreWalletChosenAfterFailedConnect(errorMessage, err, reason, chosenMechanismBeforeConnect, chosenWalletBeforeConnect)) {
|
|
1538
|
+
setConnectionFailure({ message: errorMessage, cause: err, reason });
|
|
1153
1539
|
}
|
|
1154
1540
|
}
|
|
1155
1541
|
}
|
|
1156
1542
|
else {
|
|
1157
1543
|
console.error(`failed to get wallet ${walletName}`, $connection.wallets);
|
|
1158
|
-
|
|
1544
|
+
// The catch-all, deliberately: the named wallet is not among the announced ones (a typo, an
|
|
1545
|
+
// extension uninstalled between render and click). It gets no member of its own because it
|
|
1546
|
+
// is not a state the user can answer, and the message already names the wallet.
|
|
1547
|
+
setConnectionFailure({ message: `failed to get wallet ${walletName}`, reason: 'failed' });
|
|
1159
1548
|
}
|
|
1160
1549
|
}
|
|
1161
1550
|
else {
|
|
@@ -1287,7 +1676,11 @@ export function createConnection(settings) {
|
|
|
1287
1676
|
loading: false,
|
|
1288
1677
|
wallet: undefined,
|
|
1289
1678
|
wallets: $connection.wallets,
|
|
1290
|
-
|
|
1679
|
+
// The host's own `type` stays on `cause`, untouched; `reason` pins only what this library
|
|
1680
|
+
// can verify (`cross-origin-blocked`) and passes anything else through as `host-refused`.
|
|
1681
|
+
error: canceled
|
|
1682
|
+
? undefined
|
|
1683
|
+
: { message: refusal.message || 'sign in failed', cause: refusal, reason: reasonForHostRefusal(refusal) },
|
|
1291
1684
|
});
|
|
1292
1685
|
}
|
|
1293
1686
|
finally {
|
|
@@ -1319,7 +1712,13 @@ export function createConnection(settings) {
|
|
|
1319
1712
|
}
|
|
1320
1713
|
else {
|
|
1321
1714
|
mechanism = undefined;
|
|
1322
|
-
|
|
1715
|
+
// `?? options`: the second argument may be an EXPLICIT `undefined` mechanism, which is what
|
|
1716
|
+
// a caller writes when it has options but nothing to name (`ensureConnected('SignedIn',
|
|
1717
|
+
// undefined, {requestSignatureRightAway: true})`, and any call passing a mechanism variable
|
|
1718
|
+
// that happens to be unset). Reading only the second argument silently dropped the third,
|
|
1719
|
+
// so the options were ignored and the call waited for something the caller had asked it to
|
|
1720
|
+
// do itself.
|
|
1721
|
+
opts = mechanismOrOptions ?? options;
|
|
1323
1722
|
}
|
|
1324
1723
|
}
|
|
1325
1724
|
else if (stepOrMechanismOrOptions && 'type' in stepOrMechanismOrOptions) {
|
|
@@ -1339,67 +1738,125 @@ export function createConnection(settings) {
|
|
|
1339
1738
|
mechanism = { type: 'wallet' };
|
|
1340
1739
|
}
|
|
1341
1740
|
const promise = new Promise((resolve, reject) => {
|
|
1741
|
+
// WHAT THE CALLER ASKED FOR, captured before `mechanism` can be reassigned below. An address
|
|
1742
|
+
// or a wallet name that arrives HERE came from the caller, so it is a requirement; anything
|
|
1743
|
+
// this library replays from the current state is a preference and never lands in these.
|
|
1744
|
+
const asked = mechanism && mechanism.type === 'wallet' ? mechanism : undefined;
|
|
1745
|
+
const askedWalletName = asked?.name;
|
|
1746
|
+
// Ignored for a `WalletChosen` target, and that is not an oversight: choosing a wallet never
|
|
1747
|
+
// asks it for accounts, so no state that target can reach could ever satisfy an address.
|
|
1748
|
+
// Requiring one there would guarantee the hang this rework exists to remove.
|
|
1749
|
+
const askedAddress = step === 'WalletChosen' ? undefined : asked?.address?.toLowerCase();
|
|
1342
1750
|
let forceConnect = false;
|
|
1343
1751
|
// Whether the mechanism below was REPLAYED from the current state rather than asked for.
|
|
1344
1752
|
let reconnecting = false;
|
|
1345
1753
|
// The error (if any) already sitting in the store before we start.
|
|
1346
1754
|
// Only an error that appears after this point tells us that *our* attempt failed.
|
|
1347
1755
|
const errorOnEntry = $connection.error;
|
|
1348
|
-
|
|
1349
|
-
const
|
|
1350
|
-
if (
|
|
1351
|
-
|
|
1352
|
-
return (connection.step === 'WalletChosen' ||
|
|
1353
|
-
connection.step === 'WalletConnected' ||
|
|
1354
|
-
(connection.step === 'SignedIn' && connection.wallet !== undefined));
|
|
1756
|
+
/** Is this connection on the wallet the caller named? Nothing named, nothing to check. */
|
|
1757
|
+
const walletNameMatches = (connection) => {
|
|
1758
|
+
if (!askedWalletName) {
|
|
1759
|
+
return true;
|
|
1355
1760
|
}
|
|
1356
|
-
|
|
1357
|
-
if (
|
|
1761
|
+
const current = 'mechanism' in connection ? connection.mechanism : undefined;
|
|
1762
|
+
if (current?.type !== 'wallet' || !current.name) {
|
|
1358
1763
|
return false;
|
|
1359
|
-
// For WalletConnected step, check chain validity unless skipped
|
|
1360
|
-
if (step === 'WalletConnected' && !opts?.skipChainCheck) {
|
|
1361
|
-
// connection.wallet should exist when step is WalletConnected
|
|
1362
|
-
if (connection.wallet?.invalidChainId) {
|
|
1363
|
-
return false; // Wrong chain, wait for chain change
|
|
1364
|
-
}
|
|
1365
1764
|
}
|
|
1366
|
-
|
|
1765
|
+
if (current.name === askedWalletName) {
|
|
1766
|
+
return true;
|
|
1767
|
+
}
|
|
1768
|
+
// A name may be an EIP-6963 uuid: that is what `connect` looks wallets up by too, so the
|
|
1769
|
+
// two spellings of the same wallet must not read as two different wallets here.
|
|
1770
|
+
const handle = connection.wallets.find((v) => v.info.name === askedWalletName || v.info.uuid === askedWalletName);
|
|
1771
|
+
return !!handle && (handle.info.name === current.name || handle.info.uuid === current.name);
|
|
1367
1772
|
};
|
|
1773
|
+
/**
|
|
1774
|
+
* The part of the target a connection ATTEMPT could fix: the step, the wallet, the account.
|
|
1775
|
+
*
|
|
1776
|
+
* Split from the chain check below because the two call for opposite responses. Reconnecting
|
|
1777
|
+
* moves the step and the account; it does not move the chain, so initiating an attempt over a
|
|
1778
|
+
* chain mismatch would prompt the user for nothing and rebuild a wallet that was fine.
|
|
1779
|
+
*/
|
|
1780
|
+
const targetReached = (connection) => stepIsAtOrBeyond(connection, step) &&
|
|
1781
|
+
walletNameMatches(connection) &&
|
|
1782
|
+
(!askedAddress || canActAs(connection, askedAddress)) &&
|
|
1783
|
+
// A `WalletConnected` connection whose wallet has gone locked or revoked is AT the step and
|
|
1784
|
+
// cannot act, so it does not satisfy a target that needs it to: that is the one and only
|
|
1785
|
+
// reason `ensureConnected` reconnects such a wallet where `connect()` would not (ADR-0002).
|
|
1786
|
+
// A `WalletChosen` target is exempt because it never needed accounts in the first place, and
|
|
1787
|
+
// `SignedIn` because a signed-in app acts through its session account, which a locked wallet
|
|
1788
|
+
// does not invalidate.
|
|
1789
|
+
(step === 'WalletChosen' || connection.step !== 'WalletConnected' || connection.wallet.status === 'connected');
|
|
1790
|
+
/** The part it could not: only the user, or their wallet, moves the chain. */
|
|
1791
|
+
const chainIsRight = (connection) => step !== 'WalletConnected' || !!opts?.skipChainCheck || !connection.wallet?.invalidChainId;
|
|
1792
|
+
const canResolve = (connection) => targetReached(connection) && chainIsRight(connection);
|
|
1368
1793
|
const reconnect = mechanismToReconnect();
|
|
1369
|
-
if (reconnect) {
|
|
1370
|
-
// we reuse existing mechanism as we just want to reconnect
|
|
1371
|
-
forceConnect = true;
|
|
1372
|
-
mechanism = reconnect;
|
|
1373
|
-
// ...but its ADDRESS is only a preference, because the user may unlock on another
|
|
1374
|
-
// account, and a replayed address is not something the caller asked for.
|
|
1375
|
-
reconnecting = true;
|
|
1376
|
-
}
|
|
1377
|
-
else if (canResolve($connection)) {
|
|
1378
|
-
// Only resolve if step matches AND chain is valid (or skipChainCheck)
|
|
1794
|
+
if (!reconnect && canResolve($connection)) {
|
|
1379
1795
|
resolve($connection);
|
|
1380
1796
|
return;
|
|
1381
1797
|
}
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
|
|
1393
|
-
|
|
1394
|
-
|
|
1798
|
+
if (reconnect) {
|
|
1799
|
+
// A locked or revoked wallet: reconnecting it is the only way to hand back something usable.
|
|
1800
|
+
forceConnect = true;
|
|
1801
|
+
if (askedAddress) {
|
|
1802
|
+
// The replayed mechanism MUST NOT overrule what the caller named. Substituting the stored
|
|
1803
|
+
// address here is precisely how a caller's requirement used to become somebody else's
|
|
1804
|
+
// account: the reconnect would come back on the stored one and the caller's address was
|
|
1805
|
+
// never looked at again. The wallet name is still worth reusing, since it is the wallet
|
|
1806
|
+
// this connection is on and the caller usually did not name one.
|
|
1807
|
+
mechanism = { type: 'wallet', name: askedWalletName || reconnect.name, address: askedAddress };
|
|
1808
|
+
}
|
|
1809
|
+
else if (askedWalletName && askedWalletName !== reconnect.name) {
|
|
1810
|
+
// A different wallet was named: replaying THIS wallet's account would demand an address
|
|
1811
|
+
// from a wallet that has no reason to have it.
|
|
1812
|
+
mechanism = { type: 'wallet', name: askedWalletName };
|
|
1395
1813
|
}
|
|
1396
1814
|
else {
|
|
1397
|
-
|
|
1815
|
+
mechanism = reconnect;
|
|
1816
|
+
// ...and its ADDRESS is only a preference, because the user may unlock on another
|
|
1817
|
+
// account, and a replayed address is not something the caller asked for.
|
|
1818
|
+
reconnecting = true;
|
|
1398
1819
|
}
|
|
1399
1820
|
}
|
|
1821
|
+
let idlePassed = $connection.step != 'Idle';
|
|
1400
1822
|
// An attempt is considered started once we observe a step where the connection is in progress.
|
|
1401
1823
|
// Falling back to a resting step from there means the attempt ended without reaching the target.
|
|
1402
1824
|
let attemptStarted = false;
|
|
1825
|
+
// Dismissals of the address-unavailable state that happened BEFORE this call: only a later one
|
|
1826
|
+
// is this call's answer.
|
|
1827
|
+
const acknowledgementsOnEntry = askedAddress ? acknowledgementsFor(askedAddress) : 0;
|
|
1828
|
+
// THIS CALL'S PLACE IN THE QUEUE for the connection's one account slot, kept only while the
|
|
1829
|
+
// call is live (see `settle`). Registered here, after the early resolve above has already
|
|
1830
|
+
// returned, so a call that never waited never claims the slot at all.
|
|
1831
|
+
const addressBoundRequestId = askedAddress ? registerAddressBoundRequest(askedAddress) : undefined;
|
|
1832
|
+
// WHAT STOPS "try again" FROM BECOMING A LOOP: at most one attempt per wallet announcement.
|
|
1833
|
+
//
|
|
1834
|
+
// Our own attempts do not bump `walletAnnouncements`, so an attempt can never start another one
|
|
1835
|
+
// off its own result, however the wallet answers. Anything past that requires the user to act
|
|
1836
|
+
// in their wallet again, which is a person, not a loop.
|
|
1837
|
+
//
|
|
1838
|
+
// Two earlier versions of this rule are worth not repeating. "One attempt per distinct wallet
|
|
1839
|
+
// ANSWER" read well and measured false (the reset that stopped it suppressing legitimate
|
|
1840
|
+
// retries forgot the answer every time). "One attempt per distinct STATE" is provably
|
|
1841
|
+
// terminating and refuses the retry when the user switches back to an account they were on
|
|
1842
|
+
// before, which is an ordinary thing to do and leaves them following an instruction that no
|
|
1843
|
+
// longer does anything.
|
|
1844
|
+
//
|
|
1845
|
+
// Load-bearing, and pinned the hard way: delete this guard and `test/ensure-connected-settles`
|
|
1846
|
+
// does not fail, it HANGS, which is the honest signature of the bug it prevents.
|
|
1847
|
+
let attemptedAtEvent;
|
|
1848
|
+
// An attempt decided on but not started yet: see `scheduleAttempt`.
|
|
1849
|
+
let attemptScheduled = false;
|
|
1850
|
+
// How many attempts THIS call has started that have not finished yet.
|
|
1851
|
+
//
|
|
1852
|
+
// The store is not enough to know that. `connect` publishes `WaitingForWalletConnection`
|
|
1853
|
+
// before its first await, but `selectWallet` awaits `getChainId` before publishing anything at
|
|
1854
|
+
// all, and the popup path can await a key generation first. In that window the store still
|
|
1855
|
+
// holds the entry state, nothing is "in progress" as far as any published state is concerned,
|
|
1856
|
+
// and the answer branch below would report "nothing is in progress" about an attempt that is
|
|
1857
|
+
// running and about to succeed. It did exactly that, for `ensureConnected('WalletChosen')`
|
|
1858
|
+
// from any non-Idle state: rejected, and then reached the target anyway.
|
|
1859
|
+
let attemptsInFlight = 0;
|
|
1403
1860
|
let settled = false;
|
|
1404
1861
|
let unsubscribe;
|
|
1405
1862
|
const settle = (perform) => {
|
|
@@ -1409,9 +1866,241 @@ export function createConnection(settings) {
|
|
|
1409
1866
|
settled = true;
|
|
1410
1867
|
// unsubscribe can still be undefined here if the store settles during the initial (synchronous) subscription
|
|
1411
1868
|
unsubscribe?.();
|
|
1869
|
+
// This call is over, so it stops competing for the account slot and stops being counted
|
|
1870
|
+
// against anybody.
|
|
1871
|
+
//
|
|
1872
|
+
// HONEST NOTE, because no test fails if this is deleted: it is defensive. For it to change
|
|
1873
|
+
// an observable label, a NEWER address-bound call would have to settle while an OLDER one
|
|
1874
|
+
// stays live, and every way a newer call can settle publishes a state that also ends an
|
|
1875
|
+
// older call resting on it — while an older call that is still waiting is waiting on
|
|
1876
|
+
// something in progress, which publishes again in its turn. Kept anyway: it also bounds the
|
|
1877
|
+
// map, and "the registry contains the live requests" is cheaper to keep true than to reason
|
|
1878
|
+
// about every time somebody adds a settle path.
|
|
1879
|
+
if (addressBoundRequestId !== undefined) {
|
|
1880
|
+
liveAddressBoundRequests.delete(addressBoundRequestId);
|
|
1881
|
+
}
|
|
1412
1882
|
perform();
|
|
1413
1883
|
};
|
|
1414
|
-
|
|
1884
|
+
/**
|
|
1885
|
+
* THE ONE PLACE A `ConnectionFailure` IS BUILT, and it takes the reason first.
|
|
1886
|
+
*
|
|
1887
|
+
* Not tidiness: `reason` is the field that must never be forgotten, and a rule kept at four
|
|
1888
|
+
* call sites is a rule that is kept at three of them a year from now. This codebase has
|
|
1889
|
+
* twice fixed bugs whose root cause was exactly that (`pendingRequests`, wallet teardown).
|
|
1890
|
+
*/
|
|
1891
|
+
const failWith = (reason, message, cause) => settle(() => reject(new ConnectionFailure(message, cause, reason)));
|
|
1892
|
+
/**
|
|
1893
|
+
* The MESSAGE is the same for both, and that is the point: every consumer already maps
|
|
1894
|
+
* `'Connection cancelled'` to "the user chose not to" and shows nothing, so a dismissed
|
|
1895
|
+
* `addressUnavailable` must keep arriving in that shape and must not paint a red banner over
|
|
1896
|
+
* a decision. What was missing is WHICH decision, and that is what `reason` adds.
|
|
1897
|
+
*/
|
|
1898
|
+
const cancelled = (reason) => failWith(reason, 'Connection cancelled');
|
|
1899
|
+
/**
|
|
1900
|
+
* Start an attempt and stay honest about it while it runs.
|
|
1901
|
+
*
|
|
1902
|
+
* Everything these calls do, they normally do by moving the store, and the subscription below
|
|
1903
|
+
* reads the answer off it. Two things break that, and both are handled here rather than by
|
|
1904
|
+
* guessing from published states:
|
|
1905
|
+
*
|
|
1906
|
+
* - an attempt can be RUNNING while the store still shows the state it started from, because
|
|
1907
|
+
* `selectWallet` (and the popup path) await before their first publish;
|
|
1908
|
+
* - an attempt can FAIL before its first publish (a hosted mechanism with no `walletHost`),
|
|
1909
|
+
* after which nothing has changed and nothing will publish again.
|
|
1910
|
+
*
|
|
1911
|
+
* A late rejection, after the flow moved on, settles nothing: `settle` is idempotent and the
|
|
1912
|
+
* store has already answered.
|
|
1913
|
+
*/
|
|
1914
|
+
const runAttempt = (attempt) => {
|
|
1915
|
+
attemptsInFlight++;
|
|
1916
|
+
attempt.then(() => {
|
|
1917
|
+
attemptsInFlight--;
|
|
1918
|
+
// Decide again now that it is over. The store may have published its last state while
|
|
1919
|
+
// this attempt still counted as in progress, and nothing else will publish again: an
|
|
1920
|
+
// attempt that ends without reaching the target has to be answered here or nowhere.
|
|
1921
|
+
evaluate($connection);
|
|
1922
|
+
}, (err) => {
|
|
1923
|
+
attemptsInFlight--;
|
|
1924
|
+
failWith(reasonForError(err), err?.message || `could not reach ${step}`, err);
|
|
1925
|
+
});
|
|
1926
|
+
};
|
|
1927
|
+
/** Is the connection sitting on the account the caller asked for, ready to be asked to sign? */
|
|
1928
|
+
const readyToSign = (connection) => connection.step === 'WalletConnected' &&
|
|
1929
|
+
connection.wallet.status === 'connected' &&
|
|
1930
|
+
walletNameMatches(connection) &&
|
|
1931
|
+
(!askedAddress || canActAs(connection, askedAddress));
|
|
1932
|
+
/**
|
|
1933
|
+
* Do whatever can be done from where the connection is right now.
|
|
1934
|
+
*
|
|
1935
|
+
* It may deliberately do NOTHING, in the one case where the pending thing is a click in the
|
|
1936
|
+
* app rather than anything this library can start: a `WalletConnected` connection asked for
|
|
1937
|
+
* `SignedIn` on a store that did not ask for the signature to be requested automatically. That
|
|
1938
|
+
* app renders its own "sign in" button, and prompting over the top of it would ask the user
|
|
1939
|
+
* for a signature the app deliberately deferred. `awaitingUserReason` names that state, so it
|
|
1940
|
+
* is a legitimate wait rather than a silent one.
|
|
1941
|
+
*/
|
|
1942
|
+
const initiate = () => {
|
|
1943
|
+
if (step === 'WalletChosen') {
|
|
1944
|
+
runAttempt(selectWallet(askedWalletName, opts));
|
|
1945
|
+
return true;
|
|
1946
|
+
}
|
|
1947
|
+
if (step === 'SignedIn' && readyToSign($connection)) {
|
|
1948
|
+
const mayRequestSignature = (requestSignatureAutomaticallyIfPossible || opts?.requestSignatureRightAway) &&
|
|
1949
|
+
!opts?.requireUserConfirmationBeforeSignatureRequest;
|
|
1950
|
+
if (mayRequestSignature) {
|
|
1951
|
+
// The narrow remedy: the wallet is already connected on the right account, so the only
|
|
1952
|
+
// thing between here and `SignedIn` is the signature. Reconnecting would prompt twice.
|
|
1953
|
+
// Failures land on the state as an error, which the subscription below reports.
|
|
1954
|
+
runAttempt(requestSignature());
|
|
1955
|
+
return true;
|
|
1956
|
+
}
|
|
1957
|
+
// Nothing started: the pending thing is a click in the app. Reported honestly, so the
|
|
1958
|
+
// caller falls through to the wait reasons instead of being told an attempt is running.
|
|
1959
|
+
return false;
|
|
1960
|
+
}
|
|
1961
|
+
runAttempt(connect(mechanism, opts, { addressIsPreference: reconnecting, reportUnavailableAddress: !!askedAddress }));
|
|
1962
|
+
return true;
|
|
1963
|
+
};
|
|
1964
|
+
// WHEN AN ATTEMPT MAY BE INITIATED.
|
|
1965
|
+
//
|
|
1966
|
+
// Not while one is already running (`stepsInProgress`), and not while the user is mid-choice
|
|
1967
|
+
// with a picker on screen, since connecting there would hijack their choice. A picker still
|
|
1968
|
+
// carrying the error of a previous attempt is the exception: that attempt failed and nothing
|
|
1969
|
+
// has driven the flow since, so re-initiating is exactly what the caller asked for. It cannot
|
|
1970
|
+
// hijack a choice either, because when a choice is genuinely needed `connect` re-enters the
|
|
1971
|
+
// same picker (clearing the stale error) and we keep waiting.
|
|
1972
|
+
//
|
|
1973
|
+
// Everything else initiates, INCLUDING the resting steps that used to fall through every
|
|
1974
|
+
// branch and wait forever: a `WalletChosen` connection asked to connect, and a connection at
|
|
1975
|
+
// rest holding an account the caller did not ask for.
|
|
1976
|
+
/**
|
|
1977
|
+
* Start an attempt from this state, if one is called for and would not be a repeat.
|
|
1978
|
+
*
|
|
1979
|
+
* Used at entry AND from `evaluate`, which is the fix for an answer that depended on timing:
|
|
1980
|
+
* initiating only at entry meant a call made while some OTHER flow was in progress (a picker
|
|
1981
|
+
* the user was mid-way through, say) got "nothing is in progress" the moment that flow ended
|
|
1982
|
+
* without satisfying it — while the identical call, made one tick later, initiated and
|
|
1983
|
+
* succeeded. Same store, same request, opposite answers.
|
|
1984
|
+
*/
|
|
1985
|
+
/**
|
|
1986
|
+
* Would attempting AGAINST THIS STATE be wrong, whatever the caller asked for?
|
|
1987
|
+
*
|
|
1988
|
+
* Pulled out because it has to be asked TWICE: once when the attempt is decided on, and again
|
|
1989
|
+
* when a deferred attempt actually runs. The deferral exists precisely because the state moves
|
|
1990
|
+
* in between, so re-checking less than was checked the first time is backwards — and it was:
|
|
1991
|
+
* the microtask used to re-check only the target, so a `useCurrentAccount` store that had
|
|
1992
|
+
* meanwhile started its own connect got a SECOND concurrent one, two `eth_requestAccounts` at
|
|
1993
|
+
* once, and a wallet answering the second with "already processing" would have rejected a call
|
|
1994
|
+
* whose real attempt was still running and about to succeed.
|
|
1995
|
+
*/
|
|
1996
|
+
const attemptWouldBeWrongNow = (connection) => {
|
|
1997
|
+
if (targetReached(connection) || attemptsInFlight > 0) {
|
|
1998
|
+
return true;
|
|
1999
|
+
}
|
|
2000
|
+
if (stepsInProgress.includes(connection.step)) {
|
|
2001
|
+
return true;
|
|
2002
|
+
}
|
|
2003
|
+
// A picker the user is mid-choice on is theirs, not ours to hijack. One carrying the error
|
|
2004
|
+
// of a previous attempt is different: that attempt failed and nothing has driven the flow
|
|
2005
|
+
// since, so re-initiating is what the caller asked for.
|
|
2006
|
+
const userIsChoosing = (connection.step === 'MechanismToChoose' || connection.step === 'WalletToChoose') && !errorOnEntry;
|
|
2007
|
+
return userIsChoosing && !opts?.forceConnect && !forceConnect;
|
|
2008
|
+
};
|
|
2009
|
+
const initiateIfWorthwhile = (connection, start = initiate) => {
|
|
2010
|
+
if (attemptScheduled || attemptWouldBeWrongNow(connection)) {
|
|
2011
|
+
return false;
|
|
2012
|
+
}
|
|
2013
|
+
if (attemptedAtEvent === walletAnnouncements) {
|
|
2014
|
+
return false;
|
|
2015
|
+
}
|
|
2016
|
+
attemptedAtEvent = walletAnnouncements;
|
|
2017
|
+
return start();
|
|
2018
|
+
};
|
|
2019
|
+
initiateIfWorthwhile($connection);
|
|
2020
|
+
/**
|
|
2021
|
+
* WHY WAITING IS LEGITIMATE RIGHT NOW, or `undefined` if it is not.
|
|
2022
|
+
*
|
|
2023
|
+
* The closed list, and the whole of the settle guarantee: every entry is something IN
|
|
2024
|
+
* PROGRESS, and every one of them is published on the connection for the app to render and
|
|
2025
|
+
* for the user to answer. Anything not on this list is not a wait, it is an unanswered
|
|
2026
|
+
* question, and the caller gets an answer instead (see the end of the subscription).
|
|
2027
|
+
*
|
|
2028
|
+
* Deliberately NOT a timeout. A human is in the loop: a timer long enough not to cut someone
|
|
2029
|
+
* off mid-decision is too long to be useful, and it would report "timed out" about a wallet
|
|
2030
|
+
* dialog that is open and healthy.
|
|
2031
|
+
*/
|
|
2032
|
+
const awaitingUserReason = (connection) => {
|
|
2033
|
+
if (attemptsInFlight > 0 || attemptScheduled) {
|
|
2034
|
+
// Not inferred from the state: this call started something and it has not come back.
|
|
2035
|
+
// Covers the window before an attempt's first publish, which the store cannot show, and
|
|
2036
|
+
// the window between deciding to attempt and the microtask that runs it.
|
|
2037
|
+
return 'an attempt this call started is still running';
|
|
2038
|
+
}
|
|
2039
|
+
if (stepsInProgress.includes(connection.step)) {
|
|
2040
|
+
return 'an attempt is in progress';
|
|
2041
|
+
}
|
|
2042
|
+
if (connection.step === 'MechanismToChoose' || connection.step === 'WalletToChoose') {
|
|
2043
|
+
return 'the user is choosing';
|
|
2044
|
+
}
|
|
2045
|
+
if (askedAddress &&
|
|
2046
|
+
connection.addressUnavailable?.requested.toLowerCase() === askedAddress &&
|
|
2047
|
+
// ...and it is still TRUE. A reason that has gone stale (the wallet does offer the
|
|
2048
|
+
// account now) licenses a wait that nothing can end: the user has already done the only
|
|
2049
|
+
// thing it asks of them. The same freshness test guards the resting branch in `evaluate`,
|
|
2050
|
+
// and the two must agree or the disagreement IS the hang.
|
|
2051
|
+
!(connection.wallet?.accounts ?? []).some((account) => account.toLowerCase() === askedAddress)) {
|
|
2052
|
+
// Only OUR request licenses this wait. A reason left on the connection by a different
|
|
2053
|
+
// call describes an account this call never asked about, and waiting on somebody else's
|
|
2054
|
+
// unanswered question is how a wait becomes unending.
|
|
2055
|
+
return 'the wallet is not on the account that was asked for';
|
|
2056
|
+
}
|
|
2057
|
+
if (targetReached(connection) && !chainIsRight(connection)) {
|
|
2058
|
+
return 'the wallet is on another chain';
|
|
2059
|
+
}
|
|
2060
|
+
if (step === 'SignedIn' && readyToSign(connection)) {
|
|
2061
|
+
// The app's own "sign in" button is the pending decision — but only while the connection
|
|
2062
|
+
// could actually be asked to sign. On a wallet that has since locked or moved account,
|
|
2063
|
+
// `requestSignature()` is not a remedy the user can take, so this is not a wait, and the
|
|
2064
|
+
// caller gets an answer instead.
|
|
2065
|
+
return 'the signature has not been requested yet';
|
|
2066
|
+
}
|
|
2067
|
+
return undefined;
|
|
2068
|
+
};
|
|
2069
|
+
/**
|
|
2070
|
+
* Start an attempt AFTER the current publish, never during it.
|
|
2071
|
+
*
|
|
2072
|
+
* `evaluate` runs inside `set`, and a wallet event does not produce one state: `onAccountChanged`
|
|
2073
|
+
* publishes the new status first and the new accounts second. Starting a connection attempt
|
|
2074
|
+
* from inside the first of those re-enters the store while the handler is still mid-way through
|
|
2075
|
+
* its own transitions, which then continue on top of a state the attempt has replaced — rebuilding
|
|
2076
|
+
* a wallet from one that is no longer there. So the decision is taken synchronously (which is
|
|
2077
|
+
* what keeps the accounting honest) and the work is done once the dust settles, against whatever
|
|
2078
|
+
* state the handler finally left behind.
|
|
2079
|
+
*/
|
|
2080
|
+
const scheduleAttempt = () => {
|
|
2081
|
+
attemptScheduled = true;
|
|
2082
|
+
queueMicrotask(() => {
|
|
2083
|
+
attemptScheduled = false;
|
|
2084
|
+
if (settled) {
|
|
2085
|
+
return;
|
|
2086
|
+
}
|
|
2087
|
+
// EVERY guard re-applied against the state as it now is, not just the target: the rest of
|
|
2088
|
+
// the handler that published may have satisfied the request, started its own attempt, or
|
|
2089
|
+
// moved the connection somewhere attempting would be wrong (a popup, an account picker,
|
|
2090
|
+
// another wallet). The event guard is NOT re-applied, because this attempt already
|
|
2091
|
+
// consumed it when it was scheduled.
|
|
2092
|
+
if (attemptWouldBeWrongNow($connection) || !initiate()) {
|
|
2093
|
+
evaluate($connection);
|
|
2094
|
+
}
|
|
2095
|
+
});
|
|
2096
|
+
return true;
|
|
2097
|
+
};
|
|
2098
|
+
/**
|
|
2099
|
+
* Decide, against one state. Called for every publish, AND once more whenever an attempt this
|
|
2100
|
+
* call started comes back, because the last publish may have happened while that attempt was
|
|
2101
|
+
* still running and nothing will publish again afterwards.
|
|
2102
|
+
*/
|
|
2103
|
+
const evaluate = (connection) => {
|
|
1415
2104
|
if (settled) {
|
|
1416
2105
|
return;
|
|
1417
2106
|
}
|
|
@@ -1423,6 +2112,19 @@ export function createConnection(settings) {
|
|
|
1423
2112
|
settle(() => resolve(connection));
|
|
1424
2113
|
return;
|
|
1425
2114
|
}
|
|
2115
|
+
// THE USER DISMISSED the "your wallet is not on that account" state for the address THIS
|
|
2116
|
+
// call asked about. Checked before anything else that can return: a decision is an answer
|
|
2117
|
+
// whatever else is happening on the connection, and this call may be resting while a
|
|
2118
|
+
// DIFFERENT one has the flow in progress — in which case the in-progress branch below would
|
|
2119
|
+
// swallow the dismissal, and nothing would publish again to bring it back.
|
|
2120
|
+
//
|
|
2121
|
+
// Read from the acknowledgement count FOR THAT ADDRESS rather than from the reason
|
|
2122
|
+
// disappearing. Several things clear that field and only one of them is a decision; and a
|
|
2123
|
+
// decision about one address is not an answer to a request about another.
|
|
2124
|
+
if (askedAddress && acknowledgementsFor(askedAddress) !== acknowledgementsOnEntry) {
|
|
2125
|
+
cancelled('address-unavailable-acknowledged');
|
|
2126
|
+
return;
|
|
2127
|
+
}
|
|
1426
2128
|
if (stepsInProgress.includes(connection.step)) {
|
|
1427
2129
|
// still going, nothing to decide yet
|
|
1428
2130
|
attemptStarted = true;
|
|
@@ -1434,20 +2136,81 @@ export function createConnection(settings) {
|
|
|
1434
2136
|
// a generic cancellation.
|
|
1435
2137
|
const error = connection.error;
|
|
1436
2138
|
if (error && error !== errorOnEntry) {
|
|
1437
|
-
|
|
2139
|
+
// The reason is COPIED, never re-derived. Deriving it again here from `message` or from
|
|
2140
|
+
// `cause` is how the state an app renders and the error a caller catches come to disagree
|
|
2141
|
+
// about one event: they are the same failure, so they carry the same label by construction.
|
|
2142
|
+
failWith(error.reason, error.message, error.cause);
|
|
1438
2143
|
return;
|
|
1439
2144
|
}
|
|
1440
2145
|
// Reject on disconnect/back to Idle
|
|
1441
2146
|
if (connection.step === 'Idle' && idlePassed) {
|
|
1442
|
-
|
|
2147
|
+
cancelled('cancelled');
|
|
1443
2148
|
return;
|
|
1444
2149
|
}
|
|
1445
2150
|
// The attempt went back to a resting step without an error: it was aborted (back/cancel).
|
|
1446
2151
|
// This must never trigger on a resting step we merely started from, hence `attemptStarted`.
|
|
1447
2152
|
if (attemptStarted && stepsAtRest.includes(connection.step)) {
|
|
1448
|
-
|
|
2153
|
+
cancelled('cancelled');
|
|
2154
|
+
return;
|
|
1449
2155
|
}
|
|
1450
|
-
|
|
2156
|
+
// THE WALLET IS NOT ON THE ACCOUNT THIS CALL ASKED FOR, and the connection is resting on a
|
|
2157
|
+
// state that says so. That is the app's to render and the user's to answer, so nothing is
|
|
2158
|
+
// attempted while it stands: re-attempting would prompt them again for the account they are
|
|
2159
|
+
// being asked to switch to.
|
|
2160
|
+
//
|
|
2161
|
+
// The moment the wallet DOES offer it, this stops applying and the ordinary rule below picks
|
|
2162
|
+
// the request back up, which is what carries the user through without a click in the app.
|
|
2163
|
+
const unavailable = connection.addressUnavailable;
|
|
2164
|
+
if (askedAddress &&
|
|
2165
|
+
unavailable?.requested.toLowerCase() === askedAddress &&
|
|
2166
|
+
!(connection.wallet?.accounts ?? []).some((account) => account.toLowerCase() === askedAddress)) {
|
|
2167
|
+
return;
|
|
2168
|
+
}
|
|
2169
|
+
// A REQUIREMENT THE CALLER NAMED IS UNMET, and no attempt has been made from this state.
|
|
2170
|
+
//
|
|
2171
|
+
// Re-initiating here, and only here, is the fix for an answer that depended on timing: a
|
|
2172
|
+
// call made while some OTHER flow was in progress (an account picker the user was part-way
|
|
2173
|
+
// through, say) used to get "nothing is in progress" the moment that flow ended on the wrong
|
|
2174
|
+
// account, while the identical call one tick later initiated and succeeded.
|
|
2175
|
+
//
|
|
2176
|
+
// Deliberately NOT extended to an unmet STEP. A connection that comes to rest below the
|
|
2177
|
+
// target has chosen to rest there and the app renders that (a `WalletConnected` state under
|
|
2178
|
+
// a `SignedIn` target is waiting for the app's own sign-in button), and re-running `connect`
|
|
2179
|
+
// from a state that names no wallet opens the picker — which is `connect`'s meaning, and
|
|
2180
|
+
// nobody's idea of what a promise-shaped call should do behind their back.
|
|
2181
|
+
if (!walletNameMatches(connection) || (askedAddress && !canActAs(connection, askedAddress))) {
|
|
2182
|
+
if (initiateIfWorthwhile(connection, scheduleAttempt)) {
|
|
2183
|
+
return;
|
|
2184
|
+
}
|
|
2185
|
+
}
|
|
2186
|
+
// NOTHING IS IN PROGRESS AND NOTHING CAN BE INITIATED: that is an answer, and it is
|
|
2187
|
+
// delivered rather than awaited. Silently waiting here is the failure this guard exists to
|
|
2188
|
+
// make impossible, and it is stated as a POSITIVE list (`awaitingUserReason`) on purpose:
|
|
2189
|
+
// a new step, or a new resting reason, is unreachable-by-default rather than a fresh way
|
|
2190
|
+
// to hang.
|
|
2191
|
+
const waitReason = awaitingUserReason(connection);
|
|
2192
|
+
if (!waitReason) {
|
|
2193
|
+
// The message names where the connection actually is, including the wallet's status,
|
|
2194
|
+
// because the likeliest way to arrive here is a wallet that went locked or was revoked
|
|
2195
|
+
// between the attempt finishing and this state being published.
|
|
2196
|
+
const wallet = connection.wallet ? ` (wallet ${connection.wallet.status})` : '';
|
|
2197
|
+
// SUPERSEDED, when a NEWER address-bound call is holding the connection's one account
|
|
2198
|
+
// slot: this call did not come to rest because the connection cannot get there, it came to
|
|
2199
|
+
// rest because the app itself asked for a different account in the meantime. The two are
|
|
2200
|
+
// indistinguishable from the state (the newer request took the `addressUnavailable` slot
|
|
2201
|
+
// with it, so there is nothing left on the connection to read), and telling them apart is
|
|
2202
|
+
// the difference between "this connection is stuck" and "retry, it was your own doing".
|
|
2203
|
+
//
|
|
2204
|
+
// The MESSAGE is unchanged, deliberately: it is the honest `could not reach ...` this path
|
|
2205
|
+
// has always produced, and specifically not a cancellation, because the user decided
|
|
2206
|
+
// nothing.
|
|
2207
|
+
const superseded = askedAddress !== undefined &&
|
|
2208
|
+
addressBoundRequestId !== undefined &&
|
|
2209
|
+
isSupersededBy(addressBoundRequestId, askedAddress);
|
|
2210
|
+
failWith(superseded ? 'superseded' : 'unreachable', `could not reach ${step}: the connection is at ${connection.step}${wallet} and nothing is in progress`);
|
|
2211
|
+
}
|
|
2212
|
+
};
|
|
2213
|
+
unsubscribe = _store.subscribe(evaluate);
|
|
1451
2214
|
if (settled) {
|
|
1452
2215
|
unsubscribe();
|
|
1453
2216
|
}
|
|
@@ -1499,7 +2262,7 @@ export function createConnection(settings) {
|
|
|
1499
2262
|
// through it) and report the error on the CURRENT state — throwing the choice away
|
|
1500
2263
|
// over a typo or a wallet uninstalled between render and click would deselect the
|
|
1501
2264
|
// user's read path without them refusing anything.
|
|
1502
|
-
setError({ message: `failed to get wallet ${walletName}
|
|
2265
|
+
setError({ message: `failed to get wallet ${walletName}`, reason: 'failed' });
|
|
1503
2266
|
return;
|
|
1504
2267
|
}
|
|
1505
2268
|
// Clear old wallet watchers if switching from a previously chosen/connected wallet.
|
|
@@ -1544,7 +2307,7 @@ export function createConnection(settings) {
|
|
|
1544
2307
|
// setConnectionFailure tears down the previously chosen wallet (provider still on
|
|
1545
2308
|
// the wrapper if the new wallet's getChainId threw before setWalletProvider) before
|
|
1546
2309
|
// landing on its `wallet: undefined` resting step.
|
|
1547
|
-
setConnectionFailure({ message: `failed to select wallet ${walletName}`, cause: err });
|
|
2310
|
+
setConnectionFailure({ message: `failed to select wallet ${walletName}`, cause: err, reason: reasonForError(err) });
|
|
1548
2311
|
}
|
|
1549
2312
|
}
|
|
1550
2313
|
function back(step) {
|
|
@@ -1866,7 +2629,7 @@ export function createConnection(settings) {
|
|
|
1866
2629
|
// this library's summary and the branch is reached both from a refusal to switch and
|
|
1867
2630
|
// from a wallet reporting its error as a result.
|
|
1868
2631
|
const message = `Chain "${named}" is not available on your wallet`;
|
|
1869
|
-
doneAsking({ message, cause: err });
|
|
2632
|
+
doneAsking({ message, cause: err, reason: reasonForError(err) });
|
|
1870
2633
|
throw new Error(message);
|
|
1871
2634
|
}
|
|
1872
2635
|
}
|
|
@@ -1893,29 +2656,16 @@ export function createConnection(settings) {
|
|
|
1893
2656
|
return;
|
|
1894
2657
|
}
|
|
1895
2658
|
const message = `Failed to add new chain: ${named}`;
|
|
1896
|
-
doneAsking({ message, cause: err });
|
|
2659
|
+
doneAsking({ message, cause: err, reason: reasonForError(err) });
|
|
1897
2660
|
throw err;
|
|
1898
2661
|
}
|
|
1899
2662
|
}
|
|
1900
2663
|
// Method on the store to check if target step is reached
|
|
1901
2664
|
function storeIsTargetStepReached(connection) {
|
|
1902
|
-
|
|
1903
|
-
|
|
1904
|
-
|
|
1905
|
-
|
|
1906
|
-
(connection.step === 'SignedIn' && connection.wallet !== undefined));
|
|
1907
|
-
}
|
|
1908
|
-
if (targetStep === 'WalletConnected') {
|
|
1909
|
-
// For WalletConnected target, accept WalletConnected OR SignedIn-with-wallet
|
|
1910
|
-
return (connection.step === 'WalletConnected' || (connection.step === 'SignedIn' && connection.wallet !== undefined));
|
|
1911
|
-
}
|
|
1912
|
-
// For SignedIn target
|
|
1913
|
-
if (walletOnly) {
|
|
1914
|
-
// With walletOnly, only accept SignedIn-with-wallet
|
|
1915
|
-
return connection.step === 'SignedIn' && connection.wallet !== undefined;
|
|
1916
|
-
}
|
|
1917
|
-
// Accept any SignedIn variant
|
|
1918
|
-
return connection.step === 'SignedIn';
|
|
2665
|
+
// The same ordered comparison the exported `isTargetStepReached` makes, against this store's
|
|
2666
|
+
// configured target. `walletOnly` only bites on a `SignedIn` target: the lower two are
|
|
2667
|
+
// wallet-bound by definition.
|
|
2668
|
+
return stepIsAtOrBeyond(connection, targetStep, { requireWallet: walletOnly });
|
|
1919
2669
|
}
|
|
1920
2670
|
const store = {
|
|
1921
2671
|
subscribe: _store.subscribe,
|
|
@@ -1932,6 +2682,8 @@ export function createConnection(settings) {
|
|
|
1932
2682
|
switchWalletChain,
|
|
1933
2683
|
unlock,
|
|
1934
2684
|
ensureConnected: ensureConnected, // Cast to bypass complex conditional typing
|
|
2685
|
+
acknowledgeAddressUnavailable,
|
|
2686
|
+
canActAs: (address) => canActAs($connection, address),
|
|
1935
2687
|
isTargetStepReached: storeIsTargetStepReached, // Cast for type guard
|
|
1936
2688
|
targetStep,
|
|
1937
2689
|
walletOnly,
|