@etherplay/connect 0.11.2 → 0.12.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 +150 -4
- package/dist/index.d.ts +89 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +642 -84
- package/dist/index.js.map +1 -1
- package/package.json +3 -3
- package/src/index.ts +838 -110
package/src/index.ts
CHANGED
|
@@ -150,6 +150,125 @@ export type FullfilledMechanism = AuthMechanism | WalletMechanism<string, `0x${s
|
|
|
150
150
|
|
|
151
151
|
export type TargetStep = 'WalletChosen' | 'WalletConnected' | 'SignedIn';
|
|
152
152
|
|
|
153
|
+
// THE TARGET STEPS ARE ORDERED, and this array is the only place that says so.
|
|
154
|
+
//
|
|
155
|
+
// `SignedIn` implies `WalletConnected` implies `WalletChosen`, so "has this connection reached the
|
|
156
|
+
// target" is a comparison on this array rather than a hand-written comparison per step. It used to
|
|
157
|
+
// be written out three times, and one of the three (`ensureConnected`'s own `canResolve`) got the
|
|
158
|
+
// order right for `WalletChosen` and then compared the other two exactly, which did not answer
|
|
159
|
+
// wrong so much as never answer at all: a connection resting at `SignedIn` and asked for
|
|
160
|
+
// `WalletConnected` satisfied nothing, initiated nothing, and waited forever.
|
|
161
|
+
//
|
|
162
|
+
// A fourth step added to `TargetStep` lands here once, in order, and every satisfaction check
|
|
163
|
+
// follows.
|
|
164
|
+
const orderedTargetSteps: readonly TargetStep[] = ['WalletChosen', 'WalletConnected', 'SignedIn'];
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* Is the connection AT OR BEYOND the target step?
|
|
168
|
+
*
|
|
169
|
+
* `requireWallet` is for the one case the order does not capture: `SignedIn` is the only target
|
|
170
|
+
* step reachable without a wallet (the hosted email/oauth/mnemonic mechanisms), so a wallet target
|
|
171
|
+
* is never satisfied by a state that has none, and a `SignedIn` target is only wallet-bound when
|
|
172
|
+
* the caller says so.
|
|
173
|
+
*/
|
|
174
|
+
function stepIsAtOrBeyond<WalletProviderType>(
|
|
175
|
+
connection: Connection<WalletProviderType>,
|
|
176
|
+
target: TargetStep,
|
|
177
|
+
options?: {requireWallet?: boolean},
|
|
178
|
+
): boolean {
|
|
179
|
+
const reached = orderedTargetSteps.indexOf(connection.step as TargetStep);
|
|
180
|
+
if (reached === -1) {
|
|
181
|
+
// An in-progress or picker step is not a resting point at any target.
|
|
182
|
+
return false;
|
|
183
|
+
}
|
|
184
|
+
if (reached < orderedTargetSteps.indexOf(target)) {
|
|
185
|
+
return false;
|
|
186
|
+
}
|
|
187
|
+
if ((target !== 'SignedIn' || options?.requireWallet) && connection.wallet === undefined) {
|
|
188
|
+
return false;
|
|
189
|
+
}
|
|
190
|
+
return true;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* The wallet is not on the account a caller asked this connection to act as.
|
|
195
|
+
*
|
|
196
|
+
* A RESTING STATE RATHER THAN AN ERROR, because it is not one: the user has a wallet, it works,
|
|
197
|
+
* and it is simply on a different account than the one this request needs (replacing a stuck
|
|
198
|
+
* transaction reuses its nonce, so it must be signed by the same key, and no other account will
|
|
199
|
+
* do). There is a remedy and the user is the only one who can apply it, so this is published as an
|
|
200
|
+
* instruction to render — "this was paid from 0xabc…, your wallet is on 0xdef…, switch or cancel" —
|
|
201
|
+
* next to a connection that is still usable.
|
|
202
|
+
*
|
|
203
|
+
* Only a CALLER-SUPPLIED address produces it. An address this library replayed from the connection's
|
|
204
|
+
* own state is a preference and keeps degrading to an ordinary connect, because the user never asked
|
|
205
|
+
* for it.
|
|
206
|
+
*
|
|
207
|
+
* Two ways out, and the app has to offer both:
|
|
208
|
+
* - the user switches account in their wallet, and the original request proceeds on its own (driven
|
|
209
|
+
* by `accountsChanged`, which is what makes this work on wallets that expose one account at a
|
|
210
|
+
* time and can therefore never offer the requested one in a list);
|
|
211
|
+
* - the user acknowledges it (`acknowledgeAddressUnavailable()`), which is a CANCELLATION: the
|
|
212
|
+
* pending `ensureConnected` rejects with `ConnectionFailure('Connection cancelled')`, the same
|
|
213
|
+
* shape as any other "the user chose not to".
|
|
214
|
+
*/
|
|
215
|
+
export type AddressUnavailable = {
|
|
216
|
+
/** The address the caller asked the connection to be able to act as. */
|
|
217
|
+
requested: `0x${string}`;
|
|
218
|
+
/** The wallet the request went to, by the name this connection knows it by, when known. */
|
|
219
|
+
walletName?: string;
|
|
220
|
+
// The three fields below describe the wallet AS IT IS NOW, not as it was when the attempt ran:
|
|
221
|
+
// they are re-derived when the wallet announces a change, because "switch to the account we need"
|
|
222
|
+
// is not advice a user can follow if it names an account they have already left. The state clears
|
|
223
|
+
// itself outright once the wallet does offer `requested`.
|
|
224
|
+
/**
|
|
225
|
+
* The account that wallet is on instead. Absent only when the wallet is offering none at all,
|
|
226
|
+
* which is what a wallet that has since been LOCKED reports: this state is kept up to date as
|
|
227
|
+
* the wallet moves, so it can go from naming an account to naming none.
|
|
228
|
+
*/
|
|
229
|
+
selected?: `0x${string}`;
|
|
230
|
+
/**
|
|
231
|
+
* What the wallet is EXPOSING right now. Not what the user owns, and not a picker.
|
|
232
|
+
*
|
|
233
|
+
* MetaMask answers `eth_accounts` with every account the user permitted; Rabby (among others)
|
|
234
|
+
* answers with the one account it is currently on. So this list is frequently a single entry that
|
|
235
|
+
* does not contain `requested`, while the user is holding `requested` all along. An app that
|
|
236
|
+
* renders it as an exhaustive choice, or reads "absent" as "the user does not have it", is wrong
|
|
237
|
+
* for those wallets. `message` is the remedy that works everywhere: switch in the wallet.
|
|
238
|
+
*
|
|
239
|
+
* Empty when the wallet is offering no account at all, which is what a locked wallet reports.
|
|
240
|
+
*/
|
|
241
|
+
available: `0x${string}`[];
|
|
242
|
+
/**
|
|
243
|
+
* A sentence an app can render as an INSTRUCTION rather than an error. Addresses are not
|
|
244
|
+
* shortened here: how to abbreviate an address is the app's decision, and every field the
|
|
245
|
+
* sentence is built from is on this object.
|
|
246
|
+
*/
|
|
247
|
+
message: string;
|
|
248
|
+
};
|
|
249
|
+
|
|
250
|
+
/**
|
|
251
|
+
* The resting reason, built in ONE place.
|
|
252
|
+
*
|
|
253
|
+
* Two sites produce it: the attempt that discovers the address is not on offer, and the account
|
|
254
|
+
* handler that keeps it true afterwards. They must word it identically, and a sentence written
|
|
255
|
+
* twice is a sentence that will disagree once.
|
|
256
|
+
*/
|
|
257
|
+
function describeAddressUnavailable(details: {
|
|
258
|
+
requested: `0x${string}`;
|
|
259
|
+
walletName?: string;
|
|
260
|
+
selected?: `0x${string}`;
|
|
261
|
+
available: `0x${string}`[];
|
|
262
|
+
}): AddressUnavailable {
|
|
263
|
+
const named = details.walletName ? `Wallet "${details.walletName}"` : 'The wallet';
|
|
264
|
+
return {
|
|
265
|
+
...details,
|
|
266
|
+
message: details.selected
|
|
267
|
+
? `${named} is on ${details.selected} and cannot act as ${details.requested}. Switch to that account in the wallet, or cancel.`
|
|
268
|
+
: `${named} is not offering ${details.requested}. Select that account in the wallet, or cancel.`,
|
|
269
|
+
};
|
|
270
|
+
}
|
|
271
|
+
|
|
153
272
|
type WalletStateCommon<WalletProviderType> = {
|
|
154
273
|
provider: WalletProvider<WalletProviderType>;
|
|
155
274
|
accounts: `0x${string}`[];
|
|
@@ -232,6 +351,17 @@ type ConnectionCommon<WalletProviderType> = {
|
|
|
232
351
|
// a banner or other mechanism to show error should be used.
|
|
233
352
|
// error should be dismissable
|
|
234
353
|
error?: {message: string; cause?: any};
|
|
354
|
+
/**
|
|
355
|
+
* Set when a caller asked this connection to act as an address the wallet is not offering.
|
|
356
|
+
*
|
|
357
|
+
* It sits BESIDE `error` rather than in it, and for the same reason it is not a throw: nothing
|
|
358
|
+
* failed. It is a resting reason with a remedy only the user can apply, so an app renders it as
|
|
359
|
+
* an instruction (see `AddressUnavailable`), not as a red banner.
|
|
360
|
+
*
|
|
361
|
+
* Like `error`, it survives a state built by spreading the current one and is dropped by any
|
|
362
|
+
* fresh transition, so a new attempt clears it without anybody remembering to.
|
|
363
|
+
*/
|
|
364
|
+
addressUnavailable?: AddressUnavailable;
|
|
235
365
|
// wallets represent the web3 wallet installed on the user browser
|
|
236
366
|
wallets: WalletHandle<WalletProviderType>[];
|
|
237
367
|
/**
|
|
@@ -342,6 +472,12 @@ export type WalletChosenState<WalletProviderType> = Extract<Connection<WalletPro
|
|
|
342
472
|
// Type representing wallet-connected states (both WalletConnected and SignedIn-via-wallet)
|
|
343
473
|
// This is what you get when targetStep is 'WalletConnected' and target is reached
|
|
344
474
|
// Both variants have WalletMechanism and wallet
|
|
475
|
+
//
|
|
476
|
+
// It is also what `ensureConnected('WalletConnected')` RESOLVES to, and that is the honest type
|
|
477
|
+
// rather than a widening for its own sake: the steps are ordered, so a signed-in connection
|
|
478
|
+
// satisfies the target and is handed back as itself. Typing that result as `WalletConnected` said
|
|
479
|
+
// `step: 'WalletConnected'` about a state whose step is `'SignedIn'`, and described its `account`
|
|
480
|
+
// as `{address}` when it is a whole `OriginAccount`.
|
|
345
481
|
export type ConnectedWithWallet<WalletProviderType> =
|
|
346
482
|
| WalletConnectedState<WalletProviderType>
|
|
347
483
|
| SignedInWithWallet<WalletProviderType>;
|
|
@@ -373,26 +509,55 @@ export function isTargetStepReached<WalletProviderType, Target extends TargetSte
|
|
|
373
509
|
: WalletOnly extends true
|
|
374
510
|
? SignedInWithWallet<WalletProviderType>
|
|
375
511
|
: SignedInState<WalletProviderType> {
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
512
|
+
// One ordered comparison, shared with the store's own `isTargetStepReached` and with
|
|
513
|
+
// `ensureConnected`. `walletOnly` narrows the RETURN TYPE and, for a `SignedIn` target, also the
|
|
514
|
+
// check: a hosted sign-in has no wallet to act through.
|
|
515
|
+
return stepIsAtOrBeyond(connection, targetStep, {requireWallet: !!walletOnly});
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
/**
|
|
519
|
+
* Can this connection sign as `address` RIGHT NOW, with no flow initiated and nothing prompted?
|
|
520
|
+
*
|
|
521
|
+
* The question `connection.account.address` does not answer. That field is the address the
|
|
522
|
+
* connection AGREED ON, which is the right thing for it to be: it survives the user locking their
|
|
523
|
+
* wallet, revoking the site, or switching account behind the connection's back, all of which keep
|
|
524
|
+
* `step: 'WalletConnected'` and change nothing about who was agreed on. What they change is whether
|
|
525
|
+
* anybody can sign, and that is what this reads (`wallet.status`, and the accounts the wallet is
|
|
526
|
+
* actually offering).
|
|
527
|
+
*
|
|
528
|
+
* It exists because a consumer needed it, wrote the comparison itself against `account.address`,
|
|
529
|
+
* and got a locked wallet wrong: it skipped its `ensureConnected` call, let the transaction out,
|
|
530
|
+
* and reported the provider's `{code: 4001}` as "transaction rejected by user" about a prompt
|
|
531
|
+
* nobody was ever shown. Use this to RENDER readiness (enable a button, show "unlock to pay"), and
|
|
532
|
+
* `ensureConnected(step, {type: 'wallet', address})` to actually reach it.
|
|
533
|
+
*
|
|
534
|
+
* Chain is deliberately not part of the answer: signing as an address is chain-independent, and
|
|
535
|
+
* `wallet.invalidChainId` is the separate question with its own separate remedy.
|
|
536
|
+
*/
|
|
537
|
+
export function canActAs<WalletProviderType>(
|
|
538
|
+
connection: Connection<WalletProviderType>,
|
|
539
|
+
address: `0x${string}`,
|
|
540
|
+
): boolean {
|
|
541
|
+
const wanted = address.toLowerCase();
|
|
542
|
+
if (!connection.wallet || connection.wallet.status !== 'connected') {
|
|
543
|
+
return false;
|
|
383
544
|
}
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
return
|
|
545
|
+
const agreedOn = 'account' in connection ? connection.account?.address : undefined;
|
|
546
|
+
if (!agreedOn || agreedOn.toLowerCase() !== wanted) {
|
|
547
|
+
return false;
|
|
387
548
|
}
|
|
388
|
-
|
|
389
|
-
//
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
549
|
+
const offered = connection.wallet.accounts;
|
|
550
|
+
// An empty list is what a wallet that was never asked reports, not a denial; `status` is the
|
|
551
|
+
// authority there. A non-empty one that does not contain the address IS a denial.
|
|
552
|
+
//
|
|
553
|
+
// Defensive, and marked as such: no state this library builds reaches here with an empty list
|
|
554
|
+
// (the states that have one, like `WalletChosen`, carry no `account` and are answered above). It
|
|
555
|
+
// is kept for a custom connector that publishes `connected` before it has read any accounts, and
|
|
556
|
+
// it is deliberately not counted as covered by any test.
|
|
557
|
+
if (offered.length > 0 && !offered.some((account) => account.toLowerCase() === wanted)) {
|
|
558
|
+
return false;
|
|
393
559
|
}
|
|
394
|
-
|
|
395
|
-
return connection.step === 'SignedIn';
|
|
560
|
+
return true;
|
|
396
561
|
}
|
|
397
562
|
|
|
398
563
|
function viemChainInfoToSwitchChainInfo(chainInfo: BasicChainInfo): {
|
|
@@ -510,6 +675,14 @@ export type ConnectionStore<
|
|
|
510
675
|
cancel: () => void;
|
|
511
676
|
back: (step: 'MechanismToChoose' | 'Idle' | 'WalletToChoose') => void;
|
|
512
677
|
clearError: () => void;
|
|
678
|
+
// Dismiss a resting `connection.addressUnavailable`, which settles any `ensureConnected` waiting
|
|
679
|
+
// on it as a cancellation. The connection is left connected, on whatever account the wallet is
|
|
680
|
+
// offering. See `AddressUnavailable`.
|
|
681
|
+
acknowledgeAddressUnavailable: () => void;
|
|
682
|
+
// Can this connection sign as `address` right now? Reads the current state and initiates
|
|
683
|
+
// nothing, so it is safe to call while rendering. The standalone `canActAs(connection, address)`
|
|
684
|
+
// is the same answer against a state you already hold (a `$connection` in a reactive block).
|
|
685
|
+
canActAs: (address: `0x${string}`) => boolean;
|
|
513
686
|
requestSignature: () => Promise<void>;
|
|
514
687
|
connectToAddress: (
|
|
515
688
|
address: `0x${string}`,
|
|
@@ -548,12 +721,12 @@ export type ConnectionStore<
|
|
|
548
721
|
}
|
|
549
722
|
: Target extends 'WalletConnected'
|
|
550
723
|
? {
|
|
551
|
-
(options?: EnsureConnectedOptions): Promise<
|
|
724
|
+
(options?: EnsureConnectedOptions): Promise<ConnectedWithWallet<WalletProviderType>>;
|
|
552
725
|
(
|
|
553
726
|
step: 'WalletConnected',
|
|
554
727
|
mechanism?: WalletMechanism<string | undefined, `0x${string}` | undefined>,
|
|
555
728
|
options?: EnsureConnectedOptions,
|
|
556
|
-
): Promise<
|
|
729
|
+
): Promise<ConnectedWithWallet<WalletProviderType>>;
|
|
557
730
|
}
|
|
558
731
|
: WalletOnly extends true
|
|
559
732
|
? {
|
|
@@ -563,7 +736,7 @@ export type ConnectionStore<
|
|
|
563
736
|
step: 'WalletConnected',
|
|
564
737
|
mechanism?: WalletMechanism<string | undefined, `0x${string}` | undefined>,
|
|
565
738
|
options?: EnsureConnectedOptions,
|
|
566
|
-
): Promise<
|
|
739
|
+
): Promise<ConnectedWithWallet<WalletProviderType>>;
|
|
567
740
|
(
|
|
568
741
|
step: 'SignedIn',
|
|
569
742
|
mechanism?: WalletMechanism<string | undefined, `0x${string}` | undefined>,
|
|
@@ -576,7 +749,7 @@ export type ConnectionStore<
|
|
|
576
749
|
step: 'WalletConnected',
|
|
577
750
|
mechanism?: WalletMechanism<string | undefined, `0x${string}` | undefined>,
|
|
578
751
|
options?: EnsureConnectedOptions,
|
|
579
|
-
): Promise<
|
|
752
|
+
): Promise<ConnectedWithWallet<WalletProviderType>>;
|
|
580
753
|
(
|
|
581
754
|
step: 'SignedIn',
|
|
582
755
|
mechanism?: Mechanism,
|
|
@@ -894,6 +1067,11 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
894
1067
|
if (!connection.wallet && connection.step !== 'WaitingForWalletConnection') {
|
|
895
1068
|
teardownWallet();
|
|
896
1069
|
}
|
|
1070
|
+
// The address a resting reason last named, kept so a dismissal can be attributed to the request
|
|
1071
|
+
// the user was looking at even if an attempt clears the field a moment before they click.
|
|
1072
|
+
if (connection.addressUnavailable) {
|
|
1073
|
+
lastPublishedAddressUnavailable = connection.addressUnavailable.requested;
|
|
1074
|
+
}
|
|
897
1075
|
const pendingRequests = currentPendingRequests();
|
|
898
1076
|
if (!connection.wallet) {
|
|
899
1077
|
$connection = {...connection, pendingRequests};
|
|
@@ -989,6 +1167,72 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
989
1167
|
}
|
|
990
1168
|
}
|
|
991
1169
|
|
|
1170
|
+
/**
|
|
1171
|
+
* The user has read "your wallet is not on that account" and chosen not to switch.
|
|
1172
|
+
*
|
|
1173
|
+
* THAT IS A CANCELLATION, and it settles the pending `ensureConnected` as one: the same
|
|
1174
|
+
* `ConnectionFailure('Connection cancelled')` a `cancel()` or a `back()` produces, so an app that
|
|
1175
|
+
* already maps a refusal to "the user chose not to" needs no new branch and shows no red error
|
|
1176
|
+
* for a decision.
|
|
1177
|
+
*
|
|
1178
|
+
* The connection itself is left exactly as it is, deliberately. It is CONNECTED, on the account
|
|
1179
|
+
* the wallet is actually offering, and "connected as somebody else, and saying so" is a better
|
|
1180
|
+
* place to leave a user than "not connected at all" — which is what the alternative, failing the
|
|
1181
|
+
* attempt, produced: every failure state carries `wallet: undefined`.
|
|
1182
|
+
*/
|
|
1183
|
+
function acknowledgeAddressUnavailable() {
|
|
1184
|
+
// WHICH request the user dismissed: the one on screen, or the one that was on screen a moment
|
|
1185
|
+
// ago if an attempt has just cleared the field out from under them.
|
|
1186
|
+
const dismissed = $connection.addressUnavailable?.requested ?? lastPublishedAddressUnavailable;
|
|
1187
|
+
if (dismissed) {
|
|
1188
|
+
const key = dismissed.toLowerCase();
|
|
1189
|
+
addressUnavailableAcknowledgements.set(key, (addressUnavailableAcknowledgements.get(key) ?? 0) + 1);
|
|
1190
|
+
}
|
|
1191
|
+
// COUNTED, not inferred. A pending `ensureConnected` used to read the reason DISAPPEARING as
|
|
1192
|
+
// the dismissal, which is true of this method and of nothing else — and plenty else clears it:
|
|
1193
|
+
// the app calling `connect()` itself, a `useCurrentAccount` store following the wallet onto
|
|
1194
|
+
// another account, the reason ceasing to be true. Each of those was reported to the caller as
|
|
1195
|
+
// `Connection cancelled`, which consumers are told to treat as "the user chose not to", so an
|
|
1196
|
+
// event the user never caused was invisible to them.
|
|
1197
|
+
//
|
|
1198
|
+
// Republished even when the field is already gone (an attempt may have cleared it a moment
|
|
1199
|
+
// ago): the publish is what wakes a pending `ensureConnected` to notice the dismissal. Without
|
|
1200
|
+
// it, a click landing in that window is counted and then never acted on, which is a wait that
|
|
1201
|
+
// nothing ends.
|
|
1202
|
+
set({
|
|
1203
|
+
...$connection,
|
|
1204
|
+
addressUnavailable: undefined,
|
|
1205
|
+
});
|
|
1206
|
+
}
|
|
1207
|
+
|
|
1208
|
+
// Dismissals of "your wallet is not on that account", COUNTED PER ADDRESS. See
|
|
1209
|
+
// `acknowledgeAddressUnavailable`: a pending `ensureConnected` watches the count for the address
|
|
1210
|
+
// IT asked about, so that a decision is told apart both from the several other things that clear
|
|
1211
|
+
// the same field and from a decision about somebody else's request. A single global count made
|
|
1212
|
+
// one dismissal cancel every address-bound call on the connection, including one whose wallet
|
|
1213
|
+
// prompt was open at that moment.
|
|
1214
|
+
const addressUnavailableAcknowledgements = new Map<string, number>();
|
|
1215
|
+
function acknowledgementsFor(address: `0x${string}`): number {
|
|
1216
|
+
return addressUnavailableAcknowledgements.get(address.toLowerCase()) ?? 0;
|
|
1217
|
+
}
|
|
1218
|
+
// The reason most recently PUBLISHED, so that a dismissal arriving in the brief window where an
|
|
1219
|
+
// attempt has cleared the field still names the address the user was actually looking at.
|
|
1220
|
+
let lastPublishedAddressUnavailable: `0x${string}` | undefined;
|
|
1221
|
+
|
|
1222
|
+
// How many times the user's WALLET has announced a DIFFERENT set of accounts. It is the unit
|
|
1223
|
+
// `ensureConnected` retries on, and it is the honest one: a retry is a response to the user
|
|
1224
|
+
// having done something in their wallet, so at most one attempt per announcement bounds the work
|
|
1225
|
+
// while never refusing to act on a real gesture. Counting distinct STATES instead looks stricter
|
|
1226
|
+
// and refuses the retry when the user returns to a state seen before, which is a normal thing for
|
|
1227
|
+
// a person to do.
|
|
1228
|
+
//
|
|
1229
|
+
// Only a CHANGE counts, and only an account one. The lock poll re-announces an empty list every
|
|
1230
|
+
// second, which is the absence of news rather than news, and would otherwise re-license an attempt
|
|
1231
|
+
// per second on a locked wallet; a chain change is news, but not news about accounts, and
|
|
1232
|
+
// re-prompting for an account because the user switched network answers a question they did not
|
|
1233
|
+
// ask.
|
|
1234
|
+
let walletAnnouncements = 0;
|
|
1235
|
+
|
|
992
1236
|
let _wallet: {provider: WalletProvider<WalletProviderType>; chainId: string} | undefined;
|
|
993
1237
|
|
|
994
1238
|
let popup: PopupPromise<OriginAccount> | undefined;
|
|
@@ -1452,6 +1696,26 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
1452
1696
|
// TODO lastAccount
|
|
1453
1697
|
// console.log('account changed', accounts);
|
|
1454
1698
|
const accountsFormated = accounts.map((a) => a.toLowerCase()) as `0x${string}`[];
|
|
1699
|
+
// NEWS is an announcement that differs from what the connection currently believes — not one
|
|
1700
|
+
// that differs from the previous announcement. The two come apart exactly where it matters: an
|
|
1701
|
+
// attempt can go and find something else in between, so a wallet announcing the same list twice
|
|
1702
|
+
// with a contradicting answer in the middle is telling us something the second time too.
|
|
1703
|
+
if (accountsFormated.join(',') !== ($connection.wallet?.accounts ?? []).join(',')) {
|
|
1704
|
+
walletAnnouncements++;
|
|
1705
|
+
}
|
|
1706
|
+
|
|
1707
|
+
// A RESTING "your wallet is not on that account" MUST KEEP DESCRIBING THE WALLET AS IT IS.
|
|
1708
|
+
//
|
|
1709
|
+
// Every `set` below rebuilds the state by spreading the current one, so the reason would
|
|
1710
|
+
// survive an account change untouched: right about the FACT (the wallet still cannot act as
|
|
1711
|
+
// the requested account) and wrong about the DETAIL, since it would go on naming an account
|
|
1712
|
+
// the user has already left, and the app renders that sentence as the instruction. Telling
|
|
1713
|
+
// somebody to switch away from an account they are not on is worse than saying nothing.
|
|
1714
|
+
//
|
|
1715
|
+
// Computed here and published WITH the accounts rather than corrected afterwards, so that no
|
|
1716
|
+
// intermediate state is ever published in which the two disagree — a correction one publish
|
|
1717
|
+
// later is a frame of wrong instruction, which is exactly what an app renders.
|
|
1718
|
+
const addressUnavailable = refreshedAddressUnavailable(accountsFormated);
|
|
1455
1719
|
|
|
1456
1720
|
if ($connection.wallet) {
|
|
1457
1721
|
const locked = accountsFormated.length == 0;
|
|
@@ -1460,6 +1724,7 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
1460
1724
|
if (locked) {
|
|
1461
1725
|
set({
|
|
1462
1726
|
...$connection,
|
|
1727
|
+
addressUnavailable,
|
|
1463
1728
|
wallet: {
|
|
1464
1729
|
...$connection.wallet,
|
|
1465
1730
|
status: 'locked',
|
|
@@ -1473,6 +1738,7 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
1473
1738
|
if (disconnected) {
|
|
1474
1739
|
set({
|
|
1475
1740
|
...$connection,
|
|
1741
|
+
addressUnavailable,
|
|
1476
1742
|
wallet: {
|
|
1477
1743
|
...$connection.wallet,
|
|
1478
1744
|
status: 'disconnected',
|
|
@@ -1483,6 +1749,7 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
1483
1749
|
} else {
|
|
1484
1750
|
set({
|
|
1485
1751
|
...$connection,
|
|
1752
|
+
addressUnavailable,
|
|
1486
1753
|
wallet: {
|
|
1487
1754
|
...$connection.wallet,
|
|
1488
1755
|
status: 'connected',
|
|
@@ -1502,6 +1769,7 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
1502
1769
|
} else {
|
|
1503
1770
|
set({
|
|
1504
1771
|
...$connection,
|
|
1772
|
+
addressUnavailable,
|
|
1505
1773
|
wallet: {
|
|
1506
1774
|
...$connection.wallet,
|
|
1507
1775
|
accountChanged: accountsFormated[0],
|
|
@@ -1512,6 +1780,7 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
1512
1780
|
} else {
|
|
1513
1781
|
set({
|
|
1514
1782
|
...$connection,
|
|
1783
|
+
addressUnavailable,
|
|
1515
1784
|
wallet: {
|
|
1516
1785
|
...$connection.wallet,
|
|
1517
1786
|
accountChanged: undefined,
|
|
@@ -1522,6 +1791,33 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
1522
1791
|
}
|
|
1523
1792
|
}
|
|
1524
1793
|
|
|
1794
|
+
/**
|
|
1795
|
+
* The resting reason, re-derived against what the wallet is offering now.
|
|
1796
|
+
*
|
|
1797
|
+
* `undefined` once the wallet DOES offer the requested account: the reason has simply stopped
|
|
1798
|
+
* being true. A pending `ensureConnected` loses nothing by that — it watches the accounts the
|
|
1799
|
+
* wallet offers rather than this field, precisely so that the state going away because the user
|
|
1800
|
+
* fixed it cannot be mistaken for the user dismissing it.
|
|
1801
|
+
*/
|
|
1802
|
+
function refreshedAddressUnavailable(offered: `0x${string}`[]): AddressUnavailable | undefined {
|
|
1803
|
+
const unavailable = $connection.addressUnavailable;
|
|
1804
|
+
if (!unavailable) {
|
|
1805
|
+
return undefined;
|
|
1806
|
+
}
|
|
1807
|
+
if (offered.some((account) => account.toLowerCase() === unavailable.requested.toLowerCase())) {
|
|
1808
|
+
return undefined;
|
|
1809
|
+
}
|
|
1810
|
+
if (offered.join(',') === unavailable.available.join(',')) {
|
|
1811
|
+
return unavailable;
|
|
1812
|
+
}
|
|
1813
|
+
return describeAddressUnavailable({
|
|
1814
|
+
requested: unavailable.requested,
|
|
1815
|
+
walletName: unavailable.walletName,
|
|
1816
|
+
selected: offered[0],
|
|
1817
|
+
available: offered,
|
|
1818
|
+
});
|
|
1819
|
+
}
|
|
1820
|
+
|
|
1525
1821
|
// TODO lastAccounts
|
|
1526
1822
|
let lockCheckInterval: number | undefined;
|
|
1527
1823
|
async function checkLockStatus() {
|
|
@@ -1672,12 +1968,27 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
1672
1968
|
|
|
1673
1969
|
let remember: boolean = false;
|
|
1674
1970
|
/**
|
|
1675
|
-
* @param internal not part of the public `connect` surface.
|
|
1676
|
-
*
|
|
1677
|
-
*
|
|
1678
|
-
* `
|
|
1971
|
+
* @param internal not part of the public `connect` surface. THREE things an address can mean,
|
|
1972
|
+
* and they are told apart here rather than by inspecting the caller:
|
|
1973
|
+
*
|
|
1974
|
+
* - nothing set: a DEMAND. `connectToAddress(a)` and `connect({type: 'wallet', address: a})` mean
|
|
1975
|
+
* that account and no other, so a wallet that cannot offer it fails the attempt.
|
|
1976
|
+
* - `addressIsPreference`: a mechanism this library REPLAYED from the current state rather than
|
|
1977
|
+
* one anybody asked for, so a vanished address degrades to an ordinary connect.
|
|
1978
|
+
* - `reportUnavailableAddress`: a demand the caller wants REPORTED rather than thrown, which is
|
|
1979
|
+
* what `ensureConnected` asks for. Failing the attempt tears the wallet down (every failure
|
|
1980
|
+
* state carries `wallet: undefined`), which is the worst of the three endings: the user is left
|
|
1981
|
+
* with no wallet at all over a wallet that is working and merely on another account. So the
|
|
1982
|
+
* attempt completes on what the wallet does offer and comes to rest carrying
|
|
1983
|
+
* `addressUnavailable`, which is a state the app can render and the user can answer.
|
|
1984
|
+
*
|
|
1985
|
+
* See `resolveRequestedAddress` below.
|
|
1679
1986
|
*/
|
|
1680
|
-
async function connect(
|
|
1987
|
+
async function connect(
|
|
1988
|
+
mechanism?: Mechanism,
|
|
1989
|
+
options?: ConnectOptions,
|
|
1990
|
+
internal?: {addressIsPreference?: boolean; reportUnavailableAddress?: boolean},
|
|
1991
|
+
) {
|
|
1681
1992
|
if (!mechanism && (targetStep === 'WalletConnected' || walletOnly)) {
|
|
1682
1993
|
mechanism = {type: 'wallet'};
|
|
1683
1994
|
}
|
|
@@ -1691,7 +2002,14 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
1691
2002
|
// different wallet.
|
|
1692
2003
|
const chosenMechanismBeforeConnect = $connection.step === 'WalletChosen' ? $connection.mechanism : undefined;
|
|
1693
2004
|
const chosenWalletBeforeConnect = $connection.step === 'WalletChosen' ? _wallet : undefined;
|
|
1694
|
-
|
|
2005
|
+
// LOWERCASED HERE, at the boundary, because everything downstream compares against the
|
|
2006
|
+
// wallet's accounts, which are lowercased on arrival. A checksummed address (what a viem
|
|
2007
|
+
// local account hands back, so a perfectly ordinary thing for a caller to be holding) would
|
|
2008
|
+
// otherwise fail to match a wallet that is holding that very account. It was a latent
|
|
2009
|
+
// papercut while an unmatched address merely failed the attempt; now that a caller's address
|
|
2010
|
+
// is a requirement, it would send the user an instruction to switch to the account they are
|
|
2011
|
+
// already on.
|
|
2012
|
+
const specificAddress = mechanism.address?.toLowerCase() as `0x${string}` | undefined;
|
|
1695
2013
|
// WHICH ACCOUNT THE ATTEMPT IS FOR, once the wallet has said what it has.
|
|
1696
2014
|
//
|
|
1697
2015
|
// An address the CALLER named is a demand: `connectToAddress(a)` and
|
|
@@ -1706,6 +2024,13 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
1706
2024
|
// threw, which landed in the catch and tore the wallet down: the reconnect performed the
|
|
1707
2025
|
// very teardown it exists to prevent, one step later. Degrading to an ordinary connect is
|
|
1708
2026
|
// what the caller asked for anyway, since it asked to be connected and named nothing.
|
|
2027
|
+
//
|
|
2028
|
+
// The third possibility is `reportUnavailableAddress`: the demand stands, but the answer is
|
|
2029
|
+
// a state rather than a failure. `unavailableAddress` is what records it, and it is read
|
|
2030
|
+
// twice below — once to keep the flow off `ChooseWalletAccount` (the caller named an
|
|
2031
|
+
// account; offering a picker instead of saying why they cannot have it is answering a
|
|
2032
|
+
// different question), and once to stamp `addressUnavailable` on the resting state.
|
|
2033
|
+
let unavailableAddress: `0x${string}` | undefined;
|
|
1709
2034
|
const resolveRequestedAddress = (available: `0x${string}`[]): `0x${string}` | undefined => {
|
|
1710
2035
|
if (!specificAddress || available.includes(specificAddress)) {
|
|
1711
2036
|
return specificAddress;
|
|
@@ -1713,12 +2038,30 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
1713
2038
|
if (internal?.addressIsPreference) {
|
|
1714
2039
|
return undefined;
|
|
1715
2040
|
}
|
|
2041
|
+
if (internal?.reportUnavailableAddress) {
|
|
2042
|
+
unavailableAddress = specificAddress;
|
|
2043
|
+
return undefined;
|
|
2044
|
+
}
|
|
1716
2045
|
throw new Error(`could not find address ${specificAddress}`);
|
|
1717
2046
|
};
|
|
1718
2047
|
const walletName =
|
|
1719
2048
|
mechanism.name ||
|
|
1720
2049
|
($connection.step === 'WalletChosen' ? $connection.mechanism.name : undefined) ||
|
|
1721
2050
|
($connection.wallets.length == 1 ? $connection.wallets[0].info.name : undefined);
|
|
2051
|
+
/**
|
|
2052
|
+
* The resting reason to publish beside a connection that came back as somebody else.
|
|
2053
|
+
*
|
|
2054
|
+
* Everything the app needs to write the instruction is on it, including the accounts the
|
|
2055
|
+
* wallet IS offering: "switch account" is not actionable advice if the user cannot see
|
|
2056
|
+
* which account the wallet thinks it is on.
|
|
2057
|
+
*/
|
|
2058
|
+
const addressUnavailableFor = (
|
|
2059
|
+
available: `0x${string}`[],
|
|
2060
|
+
selected: `0x${string}` | undefined,
|
|
2061
|
+
): AddressUnavailable | undefined =>
|
|
2062
|
+
unavailableAddress
|
|
2063
|
+
? describeAddressUnavailable({requested: unavailableAddress, walletName, selected, available})
|
|
2064
|
+
: undefined;
|
|
1722
2065
|
if (walletName) {
|
|
1723
2066
|
const wallet = $connection.wallets.find((v) => v.info.name == walletName || v.info.uuid == walletName);
|
|
1724
2067
|
if (wallet) {
|
|
@@ -1763,8 +2106,11 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
1763
2106
|
accounts = accounts.map((v) => v.toLowerCase()) as `0x${string}`[];
|
|
1764
2107
|
if (accounts.length > 0) {
|
|
1765
2108
|
const requestedAddress = resolveRequestedAddress(accounts);
|
|
2109
|
+
// `!unavailableAddress`: the caller named an account and cannot have it. An account
|
|
2110
|
+
// picker would answer a question they did not ask; they get the wallet's current
|
|
2111
|
+
// account plus a resting reason naming every account it does offer.
|
|
1766
2112
|
const nextStep =
|
|
1767
|
-
!settings?.useCurrentAccount && !requestedAddress && accounts.length > 1
|
|
2113
|
+
!settings?.useCurrentAccount && !requestedAddress && !unavailableAddress && accounts.length > 1
|
|
1768
2114
|
? 'ChooseWalletAccount'
|
|
1769
2115
|
: 'WalletConnected';
|
|
1770
2116
|
const account = requestedAddress || accounts[0];
|
|
@@ -1803,9 +2149,14 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
1803
2149
|
switchingChain: false,
|
|
1804
2150
|
},
|
|
1805
2151
|
account: {address: account},
|
|
2152
|
+
addressUnavailable: addressUnavailableFor(accounts, account),
|
|
1806
2153
|
};
|
|
2154
|
+
// `!unavailableAddress`: do not raise a SIGNATURE prompt for an account the caller
|
|
2155
|
+
// did not ask to sign as. The instruction has to reach the user before anything
|
|
2156
|
+
// else asks them for something.
|
|
1807
2157
|
if (
|
|
1808
2158
|
newState.step === 'WalletConnected' &&
|
|
2159
|
+
!unavailableAddress &&
|
|
1809
2160
|
(requestSignatureAutomaticallyIfPossible || options?.requestSignatureRightAway) &&
|
|
1810
2161
|
!options?.requireUserConfirmationBeforeSignatureRequest
|
|
1811
2162
|
) {
|
|
@@ -1842,8 +2193,10 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
1842
2193
|
} else {
|
|
1843
2194
|
const requestedAddress = resolveRequestedAddress(accounts);
|
|
1844
2195
|
const account = requestedAddress || accounts[0];
|
|
2196
|
+
// See the same expression on the requestAccounts branch above: a caller who named an
|
|
2197
|
+
// account gets a reason, not a picker.
|
|
1845
2198
|
const nextStep =
|
|
1846
|
-
!settings?.useCurrentAccount && !requestedAddress && accounts.length > 1
|
|
2199
|
+
!settings?.useCurrentAccount && !requestedAddress && !unavailableAddress && accounts.length > 1
|
|
1847
2200
|
? 'ChooseWalletAccount'
|
|
1848
2201
|
: 'WalletConnected';
|
|
1849
2202
|
const newState: ConnectionInput<WalletProviderType> =
|
|
@@ -1879,9 +2232,11 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
1879
2232
|
switchingChain: false,
|
|
1880
2233
|
},
|
|
1881
2234
|
account: {address: account},
|
|
2235
|
+
addressUnavailable: addressUnavailableFor(accounts, account),
|
|
1882
2236
|
};
|
|
1883
2237
|
if (
|
|
1884
2238
|
newState.step === 'WalletConnected' &&
|
|
2239
|
+
!unavailableAddress &&
|
|
1885
2240
|
(requestSignatureAutomaticallyIfPossible || options?.requestSignatureRightAway) &&
|
|
1886
2241
|
!options?.requireUserConfirmationBeforeSignatureRequest
|
|
1887
2242
|
) {
|
|
@@ -2084,17 +2439,42 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
2084
2439
|
}
|
|
2085
2440
|
|
|
2086
2441
|
/**
|
|
2087
|
-
*
|
|
2442
|
+
* Reach `step`, as the mechanism describes it, doing whatever that takes.
|
|
2443
|
+
*
|
|
2444
|
+
* A TARGET, NOT A STEP COMPARISON. The target is satisfied when the connection is at or beyond
|
|
2445
|
+
* `step` (they are ordered: `SignedIn` implies `WalletConnected` implies `WalletChosen`), AND is
|
|
2446
|
+
* on the wallet the caller named, AND can act as the address the caller named, AND is on the
|
|
2447
|
+
* right chain (unless `skipChainCheck`). Anything the caller did not name is not part of it, so a
|
|
2448
|
+
* bare `ensureConnected()` is unchanged.
|
|
2449
|
+
*
|
|
2450
|
+
* An address or a wallet name a CALLER passes is a REQUIREMENT rather than a hint: the whole
|
|
2451
|
+
* reason to pass one is that this request only means anything for that account (replacing a stuck
|
|
2452
|
+
* transaction reuses its nonce, so it must be signed by the same key). A connection already at
|
|
2453
|
+
* the requested step but holding a different account therefore initiates an attempt rather than
|
|
2454
|
+
* resolving instantly with somebody else. An address this library REPLAYED from the connection's
|
|
2455
|
+
* own state stays a preference, because nobody asked for it.
|
|
2088
2456
|
*
|
|
2089
|
-
*
|
|
2090
|
-
*
|
|
2091
|
-
*
|
|
2457
|
+
* IT ALWAYS ANSWERS. There is no timeout, deliberately: a human is in the loop, so any timer is
|
|
2458
|
+
* either long enough to be useless or short enough to cut a user off mid-decision, and it would
|
|
2459
|
+
* report "timed out" for a wallet dialog that is open and perfectly healthy. The rule is narrower
|
|
2460
|
+
* and checkable instead: WAITING IS ONLY LEGITIMATE WHILE SOMETHING IS ACTUALLY IN PROGRESS. See
|
|
2461
|
+
* `awaitingUserReason` below for the closed list of what counts, each of which is a state the app
|
|
2462
|
+
* renders and the user answers. If the target is not satisfied, nothing is in progress and
|
|
2463
|
+
* nothing can be initiated, that is an ANSWER and it is delivered rather than awaited.
|
|
2092
2464
|
*
|
|
2093
|
-
*
|
|
2094
|
-
*
|
|
2095
|
-
*
|
|
2096
|
-
*
|
|
2097
|
-
*
|
|
2465
|
+
* So it ends in one of four ways: it resolves at the target; it rejects with a `ConnectionFailure`
|
|
2466
|
+
* (`cause`/`code` carry the underlying wallet error, so a user rejection is EIP-1193 code 4001);
|
|
2467
|
+
* it rejects with `ConnectionFailure('Connection cancelled')` when the user backs out, including
|
|
2468
|
+
* by acknowledging an `addressUnavailable`; or it stays pending while one of the listed things is
|
|
2469
|
+
* in progress.
|
|
2470
|
+
*
|
|
2471
|
+
* It initiates from `Idle`, from `WalletChosen` (the wallet is chosen, upgrading it is exactly
|
|
2472
|
+
* what was asked), from a resting state that does not satisfy the target, and from a picker step
|
|
2473
|
+
* (`MechanismToChoose`, `WalletToChoose`) that still carries the error of a previous failed
|
|
2474
|
+
* attempt, which is what makes a retry after a rejected wallet prompt work. It deliberately does
|
|
2475
|
+
* NOT initiate from a picker step without an error: that means the user is mid-choice with the
|
|
2476
|
+
* picker on screen, and connecting there would hijack their choice. In that case it waits for the
|
|
2477
|
+
* user to pick (or cancel). Pass `{forceConnect: true}` to connect anyway.
|
|
2098
2478
|
*/
|
|
2099
2479
|
// ensureConnected overloads - the default step depends on targetStep
|
|
2100
2480
|
function ensureConnected(
|
|
@@ -2109,7 +2489,7 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
2109
2489
|
step: 'WalletConnected',
|
|
2110
2490
|
mechanismOrOptions?: WalletMechanism<string | undefined, `0x${string}` | undefined> | EnsureConnectedOptions,
|
|
2111
2491
|
options?: EnsureConnectedOptions,
|
|
2112
|
-
): Promise<
|
|
2492
|
+
): Promise<ConnectedWithWallet<WalletProviderType>>;
|
|
2113
2493
|
function ensureConnected(
|
|
2114
2494
|
step: 'SignedIn',
|
|
2115
2495
|
mechanism?: Mechanism,
|
|
@@ -2134,7 +2514,13 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
2134
2514
|
opts = options;
|
|
2135
2515
|
} else {
|
|
2136
2516
|
mechanism = undefined;
|
|
2137
|
-
|
|
2517
|
+
// `?? options`: the second argument may be an EXPLICIT `undefined` mechanism, which is what
|
|
2518
|
+
// a caller writes when it has options but nothing to name (`ensureConnected('SignedIn',
|
|
2519
|
+
// undefined, {requestSignatureRightAway: true})`, and any call passing a mechanism variable
|
|
2520
|
+
// that happens to be unset). Reading only the second argument silently dropped the third,
|
|
2521
|
+
// so the options were ignored and the call waited for something the caller had asked it to
|
|
2522
|
+
// do itself.
|
|
2523
|
+
opts = (mechanismOrOptions as EnsureConnectedOptions | undefined) ?? options;
|
|
2138
2524
|
}
|
|
2139
2525
|
} else if (stepOrMechanismOrOptions && 'type' in (stepOrMechanismOrOptions as any)) {
|
|
2140
2526
|
// First arg is a mechanism
|
|
@@ -2156,6 +2542,17 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
2156
2542
|
const promise = new Promise<
|
|
2157
2543
|
WalletChosen<WalletProviderType> | WalletConnected<WalletProviderType> | SignedIn<WalletProviderType>
|
|
2158
2544
|
>((resolve, reject) => {
|
|
2545
|
+
// WHAT THE CALLER ASKED FOR, captured before `mechanism` can be reassigned below. An address
|
|
2546
|
+
// or a wallet name that arrives HERE came from the caller, so it is a requirement; anything
|
|
2547
|
+
// this library replays from the current state is a preference and never lands in these.
|
|
2548
|
+
const asked = mechanism && mechanism.type === 'wallet' ? mechanism : undefined;
|
|
2549
|
+
const askedWalletName = asked?.name;
|
|
2550
|
+
// Ignored for a `WalletChosen` target, and that is not an oversight: choosing a wallet never
|
|
2551
|
+
// asks it for accounts, so no state that target can reach could ever satisfy an address.
|
|
2552
|
+
// Requiring one there would guarantee the hang this rework exists to remove.
|
|
2553
|
+
const askedAddress =
|
|
2554
|
+
step === 'WalletChosen' ? undefined : (asked?.address?.toLowerCase() as `0x${string}` | undefined);
|
|
2555
|
+
|
|
2159
2556
|
let forceConnect = false;
|
|
2160
2557
|
// Whether the mechanism below was REPLAYED from the current state rather than asked for.
|
|
2161
2558
|
let reconnecting = false;
|
|
@@ -2164,66 +2561,115 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
2164
2561
|
// Only an error that appears after this point tells us that *our* attempt failed.
|
|
2165
2562
|
const errorOnEntry = $connection.error;
|
|
2166
2563
|
|
|
2167
|
-
|
|
2168
|
-
const
|
|
2169
|
-
if (
|
|
2170
|
-
|
|
2171
|
-
return (
|
|
2172
|
-
connection.step === 'WalletChosen' ||
|
|
2173
|
-
connection.step === 'WalletConnected' ||
|
|
2174
|
-
(connection.step === 'SignedIn' && connection.wallet !== undefined)
|
|
2175
|
-
);
|
|
2564
|
+
/** Is this connection on the wallet the caller named? Nothing named, nothing to check. */
|
|
2565
|
+
const walletNameMatches = (connection: Connection<WalletProviderType>): boolean => {
|
|
2566
|
+
if (!askedWalletName) {
|
|
2567
|
+
return true;
|
|
2176
2568
|
}
|
|
2177
|
-
|
|
2178
|
-
|
|
2179
|
-
|
|
2180
|
-
|
|
2181
|
-
if (step === 'WalletConnected' && !opts?.skipChainCheck) {
|
|
2182
|
-
// connection.wallet should exist when step is WalletConnected
|
|
2183
|
-
if (connection.wallet?.invalidChainId) {
|
|
2184
|
-
return false; // Wrong chain, wait for chain change
|
|
2185
|
-
}
|
|
2569
|
+
const current =
|
|
2570
|
+
'mechanism' in connection ? (connection.mechanism as {type?: string; name?: string}) : undefined;
|
|
2571
|
+
if (current?.type !== 'wallet' || !current.name) {
|
|
2572
|
+
return false;
|
|
2186
2573
|
}
|
|
2187
|
-
|
|
2188
|
-
|
|
2574
|
+
if (current.name === askedWalletName) {
|
|
2575
|
+
return true;
|
|
2576
|
+
}
|
|
2577
|
+
// A name may be an EIP-6963 uuid: that is what `connect` looks wallets up by too, so the
|
|
2578
|
+
// two spellings of the same wallet must not read as two different wallets here.
|
|
2579
|
+
const handle = connection.wallets.find(
|
|
2580
|
+
(v) => v.info.name === askedWalletName || v.info.uuid === askedWalletName,
|
|
2581
|
+
);
|
|
2582
|
+
return !!handle && (handle.info.name === current.name || handle.info.uuid === current.name);
|
|
2189
2583
|
};
|
|
2190
2584
|
|
|
2585
|
+
/**
|
|
2586
|
+
* The part of the target a connection ATTEMPT could fix: the step, the wallet, the account.
|
|
2587
|
+
*
|
|
2588
|
+
* Split from the chain check below because the two call for opposite responses. Reconnecting
|
|
2589
|
+
* moves the step and the account; it does not move the chain, so initiating an attempt over a
|
|
2590
|
+
* chain mismatch would prompt the user for nothing and rebuild a wallet that was fine.
|
|
2591
|
+
*/
|
|
2592
|
+
const targetReached = (connection: Connection<WalletProviderType>): boolean =>
|
|
2593
|
+
stepIsAtOrBeyond(connection, step) &&
|
|
2594
|
+
walletNameMatches(connection) &&
|
|
2595
|
+
(!askedAddress || canActAs(connection, askedAddress)) &&
|
|
2596
|
+
// A `WalletConnected` connection whose wallet has gone locked or revoked is AT the step and
|
|
2597
|
+
// cannot act, so it does not satisfy a target that needs it to: that is the one and only
|
|
2598
|
+
// reason `ensureConnected` reconnects such a wallet where `connect()` would not (ADR-0002).
|
|
2599
|
+
// A `WalletChosen` target is exempt because it never needed accounts in the first place, and
|
|
2600
|
+
// `SignedIn` because a signed-in app acts through its session account, which a locked wallet
|
|
2601
|
+
// does not invalidate.
|
|
2602
|
+
(step === 'WalletChosen' || connection.step !== 'WalletConnected' || connection.wallet.status === 'connected');
|
|
2603
|
+
|
|
2604
|
+
/** The part it could not: only the user, or their wallet, moves the chain. */
|
|
2605
|
+
const chainIsRight = (connection: Connection<WalletProviderType>): boolean =>
|
|
2606
|
+
step !== 'WalletConnected' || !!opts?.skipChainCheck || !connection.wallet?.invalidChainId;
|
|
2607
|
+
|
|
2608
|
+
const canResolve = (connection: Connection<WalletProviderType>): boolean =>
|
|
2609
|
+
targetReached(connection) && chainIsRight(connection);
|
|
2610
|
+
|
|
2191
2611
|
const reconnect = mechanismToReconnect();
|
|
2192
|
-
if (reconnect) {
|
|
2193
|
-
// we reuse existing mechanism as we just want to reconnect
|
|
2194
|
-
forceConnect = true;
|
|
2195
|
-
mechanism = reconnect;
|
|
2196
|
-
// ...but its ADDRESS is only a preference, because the user may unlock on another
|
|
2197
|
-
// account, and a replayed address is not something the caller asked for.
|
|
2198
|
-
reconnecting = true;
|
|
2199
|
-
} else if (canResolve($connection)) {
|
|
2200
|
-
// Only resolve if step matches AND chain is valid (or skipChainCheck)
|
|
2612
|
+
if (!reconnect && canResolve($connection)) {
|
|
2201
2613
|
resolve($connection as any);
|
|
2202
2614
|
return;
|
|
2203
2615
|
}
|
|
2204
|
-
|
|
2205
|
-
|
|
2206
|
-
|
|
2207
|
-
|
|
2208
|
-
|
|
2209
|
-
|
|
2210
|
-
|
|
2211
|
-
|
|
2212
|
-
|
|
2213
|
-
|
|
2214
|
-
|
|
2215
|
-
|
|
2216
|
-
|
|
2217
|
-
|
|
2218
|
-
selectWallet(walletName, opts);
|
|
2616
|
+
if (reconnect) {
|
|
2617
|
+
// A locked or revoked wallet: reconnecting it is the only way to hand back something usable.
|
|
2618
|
+
forceConnect = true;
|
|
2619
|
+
if (askedAddress) {
|
|
2620
|
+
// The replayed mechanism MUST NOT overrule what the caller named. Substituting the stored
|
|
2621
|
+
// address here is precisely how a caller's requirement used to become somebody else's
|
|
2622
|
+
// account: the reconnect would come back on the stored one and the caller's address was
|
|
2623
|
+
// never looked at again. The wallet name is still worth reusing, since it is the wallet
|
|
2624
|
+
// this connection is on and the caller usually did not name one.
|
|
2625
|
+
mechanism = {type: 'wallet', name: askedWalletName || reconnect.name, address: askedAddress};
|
|
2626
|
+
} else if (askedWalletName && askedWalletName !== reconnect.name) {
|
|
2627
|
+
// A different wallet was named: replaying THIS wallet's account would demand an address
|
|
2628
|
+
// from a wallet that has no reason to have it.
|
|
2629
|
+
mechanism = {type: 'wallet', name: askedWalletName};
|
|
2219
2630
|
} else {
|
|
2220
|
-
|
|
2631
|
+
mechanism = reconnect;
|
|
2632
|
+
// ...and its ADDRESS is only a preference, because the user may unlock on another
|
|
2633
|
+
// account, and a replayed address is not something the caller asked for.
|
|
2634
|
+
reconnecting = true;
|
|
2221
2635
|
}
|
|
2222
2636
|
}
|
|
2637
|
+
let idlePassed = $connection.step != 'Idle';
|
|
2223
2638
|
|
|
2224
2639
|
// An attempt is considered started once we observe a step where the connection is in progress.
|
|
2225
2640
|
// Falling back to a resting step from there means the attempt ended without reaching the target.
|
|
2226
2641
|
let attemptStarted = false;
|
|
2642
|
+
// Dismissals of the address-unavailable state that happened BEFORE this call: only a later one
|
|
2643
|
+
// is this call's answer.
|
|
2644
|
+
const acknowledgementsOnEntry = askedAddress ? acknowledgementsFor(askedAddress) : 0;
|
|
2645
|
+
// WHAT STOPS "try again" FROM BECOMING A LOOP: at most one attempt per wallet announcement.
|
|
2646
|
+
//
|
|
2647
|
+
// Our own attempts do not bump `walletAnnouncements`, so an attempt can never start another one
|
|
2648
|
+
// off its own result, however the wallet answers. Anything past that requires the user to act
|
|
2649
|
+
// in their wallet again, which is a person, not a loop.
|
|
2650
|
+
//
|
|
2651
|
+
// Two earlier versions of this rule are worth not repeating. "One attempt per distinct wallet
|
|
2652
|
+
// ANSWER" read well and measured false (the reset that stopped it suppressing legitimate
|
|
2653
|
+
// retries forgot the answer every time). "One attempt per distinct STATE" is provably
|
|
2654
|
+
// terminating and refuses the retry when the user switches back to an account they were on
|
|
2655
|
+
// before, which is an ordinary thing to do and leaves them following an instruction that no
|
|
2656
|
+
// longer does anything.
|
|
2657
|
+
//
|
|
2658
|
+
// Load-bearing, and pinned the hard way: delete this guard and `test/ensure-connected-settles`
|
|
2659
|
+
// does not fail, it HANGS, which is the honest signature of the bug it prevents.
|
|
2660
|
+
let attemptedAtEvent: number | undefined;
|
|
2661
|
+
// An attempt decided on but not started yet: see `scheduleAttempt`.
|
|
2662
|
+
let attemptScheduled = false;
|
|
2663
|
+
// How many attempts THIS call has started that have not finished yet.
|
|
2664
|
+
//
|
|
2665
|
+
// The store is not enough to know that. `connect` publishes `WaitingForWalletConnection`
|
|
2666
|
+
// before its first await, but `selectWallet` awaits `getChainId` before publishing anything at
|
|
2667
|
+
// all, and the popup path can await a key generation first. In that window the store still
|
|
2668
|
+
// holds the entry state, nothing is "in progress" as far as any published state is concerned,
|
|
2669
|
+
// and the answer branch below would report "nothing is in progress" about an attempt that is
|
|
2670
|
+
// running and about to succeed. It did exactly that, for `ensureConnected('WalletChosen')`
|
|
2671
|
+
// from any non-Idle state: rejected, and then reached the target anyway.
|
|
2672
|
+
let attemptsInFlight = 0;
|
|
2227
2673
|
let settled = false;
|
|
2228
2674
|
let unsubscribe: (() => void) | undefined;
|
|
2229
2675
|
const settle = (perform: () => void) => {
|
|
@@ -2235,8 +2681,234 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
2235
2681
|
unsubscribe?.();
|
|
2236
2682
|
perform();
|
|
2237
2683
|
};
|
|
2684
|
+
const cancelled = () => settle(() => reject(new ConnectionFailure('Connection cancelled')));
|
|
2685
|
+
|
|
2686
|
+
/**
|
|
2687
|
+
* Start an attempt and stay honest about it while it runs.
|
|
2688
|
+
*
|
|
2689
|
+
* Everything these calls do, they normally do by moving the store, and the subscription below
|
|
2690
|
+
* reads the answer off it. Two things break that, and both are handled here rather than by
|
|
2691
|
+
* guessing from published states:
|
|
2692
|
+
*
|
|
2693
|
+
* - an attempt can be RUNNING while the store still shows the state it started from, because
|
|
2694
|
+
* `selectWallet` (and the popup path) await before their first publish;
|
|
2695
|
+
* - an attempt can FAIL before its first publish (a hosted mechanism with no `walletHost`),
|
|
2696
|
+
* after which nothing has changed and nothing will publish again.
|
|
2697
|
+
*
|
|
2698
|
+
* A late rejection, after the flow moved on, settles nothing: `settle` is idempotent and the
|
|
2699
|
+
* store has already answered.
|
|
2700
|
+
*/
|
|
2701
|
+
const runAttempt = (attempt: Promise<unknown>) => {
|
|
2702
|
+
attemptsInFlight++;
|
|
2703
|
+
attempt.then(
|
|
2704
|
+
() => {
|
|
2705
|
+
attemptsInFlight--;
|
|
2706
|
+
// Decide again now that it is over. The store may have published its last state while
|
|
2707
|
+
// this attempt still counted as in progress, and nothing else will publish again: an
|
|
2708
|
+
// attempt that ends without reaching the target has to be answered here or nowhere.
|
|
2709
|
+
evaluate($connection);
|
|
2710
|
+
},
|
|
2711
|
+
(err) => {
|
|
2712
|
+
attemptsInFlight--;
|
|
2713
|
+
settle(() => reject(new ConnectionFailure((err as Error)?.message || `could not reach ${step}`, err)));
|
|
2714
|
+
},
|
|
2715
|
+
);
|
|
2716
|
+
};
|
|
2717
|
+
|
|
2718
|
+
/** Is the connection sitting on the account the caller asked for, ready to be asked to sign? */
|
|
2719
|
+
const readyToSign = (connection: Connection<WalletProviderType>): boolean =>
|
|
2720
|
+
connection.step === 'WalletConnected' &&
|
|
2721
|
+
connection.wallet.status === 'connected' &&
|
|
2722
|
+
walletNameMatches(connection) &&
|
|
2723
|
+
(!askedAddress || canActAs(connection, askedAddress));
|
|
2724
|
+
|
|
2725
|
+
/**
|
|
2726
|
+
* Do whatever can be done from where the connection is right now.
|
|
2727
|
+
*
|
|
2728
|
+
* It may deliberately do NOTHING, in the one case where the pending thing is a click in the
|
|
2729
|
+
* app rather than anything this library can start: a `WalletConnected` connection asked for
|
|
2730
|
+
* `SignedIn` on a store that did not ask for the signature to be requested automatically. That
|
|
2731
|
+
* app renders its own "sign in" button, and prompting over the top of it would ask the user
|
|
2732
|
+
* for a signature the app deliberately deferred. `awaitingUserReason` names that state, so it
|
|
2733
|
+
* is a legitimate wait rather than a silent one.
|
|
2734
|
+
*/
|
|
2735
|
+
const initiate = (): boolean => {
|
|
2736
|
+
if (step === 'WalletChosen') {
|
|
2737
|
+
runAttempt(selectWallet(askedWalletName, opts));
|
|
2738
|
+
return true;
|
|
2739
|
+
}
|
|
2740
|
+
if (step === 'SignedIn' && readyToSign($connection)) {
|
|
2741
|
+
const mayRequestSignature =
|
|
2742
|
+
(requestSignatureAutomaticallyIfPossible || opts?.requestSignatureRightAway) &&
|
|
2743
|
+
!opts?.requireUserConfirmationBeforeSignatureRequest;
|
|
2744
|
+
if (mayRequestSignature) {
|
|
2745
|
+
// The narrow remedy: the wallet is already connected on the right account, so the only
|
|
2746
|
+
// thing between here and `SignedIn` is the signature. Reconnecting would prompt twice.
|
|
2747
|
+
// Failures land on the state as an error, which the subscription below reports.
|
|
2748
|
+
runAttempt(requestSignature());
|
|
2749
|
+
return true;
|
|
2750
|
+
}
|
|
2751
|
+
// Nothing started: the pending thing is a click in the app. Reported honestly, so the
|
|
2752
|
+
// caller falls through to the wait reasons instead of being told an attempt is running.
|
|
2753
|
+
return false;
|
|
2754
|
+
}
|
|
2755
|
+
runAttempt(
|
|
2756
|
+
connect(mechanism, opts, {addressIsPreference: reconnecting, reportUnavailableAddress: !!askedAddress}),
|
|
2757
|
+
);
|
|
2758
|
+
return true;
|
|
2759
|
+
};
|
|
2760
|
+
|
|
2761
|
+
// WHEN AN ATTEMPT MAY BE INITIATED.
|
|
2762
|
+
//
|
|
2763
|
+
// Not while one is already running (`stepsInProgress`), and not while the user is mid-choice
|
|
2764
|
+
// with a picker on screen, since connecting there would hijack their choice. A picker still
|
|
2765
|
+
// carrying the error of a previous attempt is the exception: that attempt failed and nothing
|
|
2766
|
+
// has driven the flow since, so re-initiating is exactly what the caller asked for. It cannot
|
|
2767
|
+
// hijack a choice either, because when a choice is genuinely needed `connect` re-enters the
|
|
2768
|
+
// same picker (clearing the stale error) and we keep waiting.
|
|
2769
|
+
//
|
|
2770
|
+
// Everything else initiates, INCLUDING the resting steps that used to fall through every
|
|
2771
|
+
// branch and wait forever: a `WalletChosen` connection asked to connect, and a connection at
|
|
2772
|
+
// rest holding an account the caller did not ask for.
|
|
2773
|
+
/**
|
|
2774
|
+
* Start an attempt from this state, if one is called for and would not be a repeat.
|
|
2775
|
+
*
|
|
2776
|
+
* Used at entry AND from `evaluate`, which is the fix for an answer that depended on timing:
|
|
2777
|
+
* initiating only at entry meant a call made while some OTHER flow was in progress (a picker
|
|
2778
|
+
* the user was mid-way through, say) got "nothing is in progress" the moment that flow ended
|
|
2779
|
+
* without satisfying it — while the identical call, made one tick later, initiated and
|
|
2780
|
+
* succeeded. Same store, same request, opposite answers.
|
|
2781
|
+
*/
|
|
2782
|
+
/**
|
|
2783
|
+
* Would attempting AGAINST THIS STATE be wrong, whatever the caller asked for?
|
|
2784
|
+
*
|
|
2785
|
+
* Pulled out because it has to be asked TWICE: once when the attempt is decided on, and again
|
|
2786
|
+
* when a deferred attempt actually runs. The deferral exists precisely because the state moves
|
|
2787
|
+
* in between, so re-checking less than was checked the first time is backwards — and it was:
|
|
2788
|
+
* the microtask used to re-check only the target, so a `useCurrentAccount` store that had
|
|
2789
|
+
* meanwhile started its own connect got a SECOND concurrent one, two `eth_requestAccounts` at
|
|
2790
|
+
* once, and a wallet answering the second with "already processing" would have rejected a call
|
|
2791
|
+
* whose real attempt was still running and about to succeed.
|
|
2792
|
+
*/
|
|
2793
|
+
const attemptWouldBeWrongNow = (connection: Connection<WalletProviderType>): boolean => {
|
|
2794
|
+
if (targetReached(connection) || attemptsInFlight > 0) {
|
|
2795
|
+
return true;
|
|
2796
|
+
}
|
|
2797
|
+
if (stepsInProgress.includes(connection.step)) {
|
|
2798
|
+
return true;
|
|
2799
|
+
}
|
|
2800
|
+
// A picker the user is mid-choice on is theirs, not ours to hijack. One carrying the error
|
|
2801
|
+
// of a previous attempt is different: that attempt failed and nothing has driven the flow
|
|
2802
|
+
// since, so re-initiating is what the caller asked for.
|
|
2803
|
+
const userIsChoosing =
|
|
2804
|
+
(connection.step === 'MechanismToChoose' || connection.step === 'WalletToChoose') && !errorOnEntry;
|
|
2805
|
+
return userIsChoosing && !opts?.forceConnect && !forceConnect;
|
|
2806
|
+
};
|
|
2807
|
+
|
|
2808
|
+
const initiateIfWorthwhile = (
|
|
2809
|
+
connection: Connection<WalletProviderType>,
|
|
2810
|
+
start: () => boolean = initiate,
|
|
2811
|
+
): boolean => {
|
|
2812
|
+
if (attemptScheduled || attemptWouldBeWrongNow(connection)) {
|
|
2813
|
+
return false;
|
|
2814
|
+
}
|
|
2815
|
+
if (attemptedAtEvent === walletAnnouncements) {
|
|
2816
|
+
return false;
|
|
2817
|
+
}
|
|
2818
|
+
attemptedAtEvent = walletAnnouncements;
|
|
2819
|
+
return start();
|
|
2820
|
+
};
|
|
2821
|
+
|
|
2822
|
+
initiateIfWorthwhile($connection);
|
|
2823
|
+
|
|
2824
|
+
/**
|
|
2825
|
+
* WHY WAITING IS LEGITIMATE RIGHT NOW, or `undefined` if it is not.
|
|
2826
|
+
*
|
|
2827
|
+
* The closed list, and the whole of the settle guarantee: every entry is something IN
|
|
2828
|
+
* PROGRESS, and every one of them is published on the connection for the app to render and
|
|
2829
|
+
* for the user to answer. Anything not on this list is not a wait, it is an unanswered
|
|
2830
|
+
* question, and the caller gets an answer instead (see the end of the subscription).
|
|
2831
|
+
*
|
|
2832
|
+
* Deliberately NOT a timeout. A human is in the loop: a timer long enough not to cut someone
|
|
2833
|
+
* off mid-decision is too long to be useful, and it would report "timed out" about a wallet
|
|
2834
|
+
* dialog that is open and healthy.
|
|
2835
|
+
*/
|
|
2836
|
+
const awaitingUserReason = (connection: Connection<WalletProviderType>): string | undefined => {
|
|
2837
|
+
if (attemptsInFlight > 0 || attemptScheduled) {
|
|
2838
|
+
// Not inferred from the state: this call started something and it has not come back.
|
|
2839
|
+
// Covers the window before an attempt's first publish, which the store cannot show, and
|
|
2840
|
+
// the window between deciding to attempt and the microtask that runs it.
|
|
2841
|
+
return 'an attempt this call started is still running';
|
|
2842
|
+
}
|
|
2843
|
+
if (stepsInProgress.includes(connection.step)) {
|
|
2844
|
+
return 'an attempt is in progress';
|
|
2845
|
+
}
|
|
2846
|
+
if (connection.step === 'MechanismToChoose' || connection.step === 'WalletToChoose') {
|
|
2847
|
+
return 'the user is choosing';
|
|
2848
|
+
}
|
|
2849
|
+
if (
|
|
2850
|
+
askedAddress &&
|
|
2851
|
+
connection.addressUnavailable?.requested.toLowerCase() === askedAddress &&
|
|
2852
|
+
// ...and it is still TRUE. A reason that has gone stale (the wallet does offer the
|
|
2853
|
+
// account now) licenses a wait that nothing can end: the user has already done the only
|
|
2854
|
+
// thing it asks of them. The same freshness test guards the resting branch in `evaluate`,
|
|
2855
|
+
// and the two must agree or the disagreement IS the hang.
|
|
2856
|
+
!(connection.wallet?.accounts ?? []).some((account) => account.toLowerCase() === askedAddress)
|
|
2857
|
+
) {
|
|
2858
|
+
// Only OUR request licenses this wait. A reason left on the connection by a different
|
|
2859
|
+
// call describes an account this call never asked about, and waiting on somebody else's
|
|
2860
|
+
// unanswered question is how a wait becomes unending.
|
|
2861
|
+
return 'the wallet is not on the account that was asked for';
|
|
2862
|
+
}
|
|
2863
|
+
if (targetReached(connection) && !chainIsRight(connection)) {
|
|
2864
|
+
return 'the wallet is on another chain';
|
|
2865
|
+
}
|
|
2866
|
+
if (step === 'SignedIn' && readyToSign(connection)) {
|
|
2867
|
+
// The app's own "sign in" button is the pending decision — but only while the connection
|
|
2868
|
+
// could actually be asked to sign. On a wallet that has since locked or moved account,
|
|
2869
|
+
// `requestSignature()` is not a remedy the user can take, so this is not a wait, and the
|
|
2870
|
+
// caller gets an answer instead.
|
|
2871
|
+
return 'the signature has not been requested yet';
|
|
2872
|
+
}
|
|
2873
|
+
return undefined;
|
|
2874
|
+
};
|
|
2875
|
+
|
|
2876
|
+
/**
|
|
2877
|
+
* Start an attempt AFTER the current publish, never during it.
|
|
2878
|
+
*
|
|
2879
|
+
* `evaluate` runs inside `set`, and a wallet event does not produce one state: `onAccountChanged`
|
|
2880
|
+
* publishes the new status first and the new accounts second. Starting a connection attempt
|
|
2881
|
+
* from inside the first of those re-enters the store while the handler is still mid-way through
|
|
2882
|
+
* its own transitions, which then continue on top of a state the attempt has replaced — rebuilding
|
|
2883
|
+
* a wallet from one that is no longer there. So the decision is taken synchronously (which is
|
|
2884
|
+
* what keeps the accounting honest) and the work is done once the dust settles, against whatever
|
|
2885
|
+
* state the handler finally left behind.
|
|
2886
|
+
*/
|
|
2887
|
+
const scheduleAttempt = (): boolean => {
|
|
2888
|
+
attemptScheduled = true;
|
|
2889
|
+
queueMicrotask(() => {
|
|
2890
|
+
attemptScheduled = false;
|
|
2891
|
+
if (settled) {
|
|
2892
|
+
return;
|
|
2893
|
+
}
|
|
2894
|
+
// EVERY guard re-applied against the state as it now is, not just the target: the rest of
|
|
2895
|
+
// the handler that published may have satisfied the request, started its own attempt, or
|
|
2896
|
+
// moved the connection somewhere attempting would be wrong (a popup, an account picker,
|
|
2897
|
+
// another wallet). The event guard is NOT re-applied, because this attempt already
|
|
2898
|
+
// consumed it when it was scheduled.
|
|
2899
|
+
if (attemptWouldBeWrongNow($connection) || !initiate()) {
|
|
2900
|
+
evaluate($connection);
|
|
2901
|
+
}
|
|
2902
|
+
});
|
|
2903
|
+
return true;
|
|
2904
|
+
};
|
|
2238
2905
|
|
|
2239
|
-
|
|
2906
|
+
/**
|
|
2907
|
+
* Decide, against one state. Called for every publish, AND once more whenever an attempt this
|
|
2908
|
+
* call started comes back, because the last publish may have happened while that attempt was
|
|
2909
|
+
* still running and nothing will publish again afterwards.
|
|
2910
|
+
*/
|
|
2911
|
+
const evaluate = (connection: Connection<WalletProviderType>) => {
|
|
2240
2912
|
if (settled) {
|
|
2241
2913
|
return;
|
|
2242
2914
|
}
|
|
@@ -2249,6 +2921,20 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
2249
2921
|
return;
|
|
2250
2922
|
}
|
|
2251
2923
|
|
|
2924
|
+
// THE USER DISMISSED the "your wallet is not on that account" state for the address THIS
|
|
2925
|
+
// call asked about. Checked before anything else that can return: a decision is an answer
|
|
2926
|
+
// whatever else is happening on the connection, and this call may be resting while a
|
|
2927
|
+
// DIFFERENT one has the flow in progress — in which case the in-progress branch below would
|
|
2928
|
+
// swallow the dismissal, and nothing would publish again to bring it back.
|
|
2929
|
+
//
|
|
2930
|
+
// Read from the acknowledgement count FOR THAT ADDRESS rather than from the reason
|
|
2931
|
+
// disappearing. Several things clear that field and only one of them is a decision; and a
|
|
2932
|
+
// decision about one address is not an answer to a request about another.
|
|
2933
|
+
if (askedAddress && acknowledgementsFor(askedAddress) !== acknowledgementsOnEntry) {
|
|
2934
|
+
cancelled();
|
|
2935
|
+
return;
|
|
2936
|
+
}
|
|
2937
|
+
|
|
2252
2938
|
if (stepsInProgress.includes(connection.step)) {
|
|
2253
2939
|
// still going, nothing to decide yet
|
|
2254
2940
|
attemptStarted = true;
|
|
@@ -2267,16 +2953,73 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
2267
2953
|
|
|
2268
2954
|
// Reject on disconnect/back to Idle
|
|
2269
2955
|
if (connection.step === 'Idle' && idlePassed) {
|
|
2270
|
-
|
|
2956
|
+
cancelled();
|
|
2271
2957
|
return;
|
|
2272
2958
|
}
|
|
2273
2959
|
|
|
2274
2960
|
// The attempt went back to a resting step without an error: it was aborted (back/cancel).
|
|
2275
2961
|
// This must never trigger on a resting step we merely started from, hence `attemptStarted`.
|
|
2276
2962
|
if (attemptStarted && stepsAtRest.includes(connection.step)) {
|
|
2277
|
-
|
|
2963
|
+
cancelled();
|
|
2964
|
+
return;
|
|
2278
2965
|
}
|
|
2279
|
-
|
|
2966
|
+
|
|
2967
|
+
// THE WALLET IS NOT ON THE ACCOUNT THIS CALL ASKED FOR, and the connection is resting on a
|
|
2968
|
+
// state that says so. That is the app's to render and the user's to answer, so nothing is
|
|
2969
|
+
// attempted while it stands: re-attempting would prompt them again for the account they are
|
|
2970
|
+
// being asked to switch to.
|
|
2971
|
+
//
|
|
2972
|
+
// The moment the wallet DOES offer it, this stops applying and the ordinary rule below picks
|
|
2973
|
+
// the request back up, which is what carries the user through without a click in the app.
|
|
2974
|
+
const unavailable = connection.addressUnavailable;
|
|
2975
|
+
if (
|
|
2976
|
+
askedAddress &&
|
|
2977
|
+
unavailable?.requested.toLowerCase() === askedAddress &&
|
|
2978
|
+
!(connection.wallet?.accounts ?? []).some((account) => account.toLowerCase() === askedAddress)
|
|
2979
|
+
) {
|
|
2980
|
+
return;
|
|
2981
|
+
}
|
|
2982
|
+
|
|
2983
|
+
// A REQUIREMENT THE CALLER NAMED IS UNMET, and no attempt has been made from this state.
|
|
2984
|
+
//
|
|
2985
|
+
// Re-initiating here, and only here, is the fix for an answer that depended on timing: a
|
|
2986
|
+
// call made while some OTHER flow was in progress (an account picker the user was part-way
|
|
2987
|
+
// through, say) used to get "nothing is in progress" the moment that flow ended on the wrong
|
|
2988
|
+
// account, while the identical call one tick later initiated and succeeded.
|
|
2989
|
+
//
|
|
2990
|
+
// Deliberately NOT extended to an unmet STEP. A connection that comes to rest below the
|
|
2991
|
+
// target has chosen to rest there and the app renders that (a `WalletConnected` state under
|
|
2992
|
+
// a `SignedIn` target is waiting for the app's own sign-in button), and re-running `connect`
|
|
2993
|
+
// from a state that names no wallet opens the picker — which is `connect`'s meaning, and
|
|
2994
|
+
// nobody's idea of what a promise-shaped call should do behind their back.
|
|
2995
|
+
if (!walletNameMatches(connection) || (askedAddress && !canActAs(connection, askedAddress))) {
|
|
2996
|
+
if (initiateIfWorthwhile(connection, scheduleAttempt)) {
|
|
2997
|
+
return;
|
|
2998
|
+
}
|
|
2999
|
+
}
|
|
3000
|
+
|
|
3001
|
+
// NOTHING IS IN PROGRESS AND NOTHING CAN BE INITIATED: that is an answer, and it is
|
|
3002
|
+
// delivered rather than awaited. Silently waiting here is the failure this guard exists to
|
|
3003
|
+
// make impossible, and it is stated as a POSITIVE list (`awaitingUserReason`) on purpose:
|
|
3004
|
+
// a new step, or a new resting reason, is unreachable-by-default rather than a fresh way
|
|
3005
|
+
// to hang.
|
|
3006
|
+
const reason = awaitingUserReason(connection);
|
|
3007
|
+
if (!reason) {
|
|
3008
|
+
// The message names where the connection actually is, including the wallet's status,
|
|
3009
|
+
// because the likeliest way to arrive here is a wallet that went locked or was revoked
|
|
3010
|
+
// between the attempt finishing and this state being published.
|
|
3011
|
+
const wallet = connection.wallet ? ` (wallet ${connection.wallet.status})` : '';
|
|
3012
|
+
settle(() =>
|
|
3013
|
+
reject(
|
|
3014
|
+
new ConnectionFailure(
|
|
3015
|
+
`could not reach ${step}: the connection is at ${connection.step}${wallet} and nothing is in progress`,
|
|
3016
|
+
),
|
|
3017
|
+
),
|
|
3018
|
+
);
|
|
3019
|
+
}
|
|
3020
|
+
};
|
|
3021
|
+
|
|
3022
|
+
unsubscribe = _store.subscribe(evaluate);
|
|
2280
3023
|
if (settled) {
|
|
2281
3024
|
unsubscribe();
|
|
2282
3025
|
}
|
|
@@ -2763,27 +3506,10 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
2763
3506
|
|
|
2764
3507
|
// Method on the store to check if target step is reached
|
|
2765
3508
|
function storeIsTargetStepReached(connection: Connection<WalletProviderType>): boolean {
|
|
2766
|
-
|
|
2767
|
-
|
|
2768
|
-
|
|
2769
|
-
|
|
2770
|
-
connection.step === 'WalletConnected' ||
|
|
2771
|
-
(connection.step === 'SignedIn' && connection.wallet !== undefined)
|
|
2772
|
-
);
|
|
2773
|
-
}
|
|
2774
|
-
if (targetStep === 'WalletConnected') {
|
|
2775
|
-
// For WalletConnected target, accept WalletConnected OR SignedIn-with-wallet
|
|
2776
|
-
return (
|
|
2777
|
-
connection.step === 'WalletConnected' || (connection.step === 'SignedIn' && connection.wallet !== undefined)
|
|
2778
|
-
);
|
|
2779
|
-
}
|
|
2780
|
-
// For SignedIn target
|
|
2781
|
-
if (walletOnly) {
|
|
2782
|
-
// With walletOnly, only accept SignedIn-with-wallet
|
|
2783
|
-
return connection.step === 'SignedIn' && connection.wallet !== undefined;
|
|
2784
|
-
}
|
|
2785
|
-
// Accept any SignedIn variant
|
|
2786
|
-
return connection.step === 'SignedIn';
|
|
3509
|
+
// The same ordered comparison the exported `isTargetStepReached` makes, against this store's
|
|
3510
|
+
// configured target. `walletOnly` only bites on a `SignedIn` target: the lower two are
|
|
3511
|
+
// wallet-bound by definition.
|
|
3512
|
+
return stepIsAtOrBeyond(connection, targetStep, {requireWallet: walletOnly});
|
|
2787
3513
|
}
|
|
2788
3514
|
|
|
2789
3515
|
const store = {
|
|
@@ -2801,6 +3527,8 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
2801
3527
|
switchWalletChain,
|
|
2802
3528
|
unlock,
|
|
2803
3529
|
ensureConnected: ensureConnected as any, // Cast to bypass complex conditional typing
|
|
3530
|
+
acknowledgeAddressUnavailable,
|
|
3531
|
+
canActAs: (address: `0x${string}`) => canActAs($connection, address),
|
|
2804
3532
|
isTargetStepReached: storeIsTargetStepReached as any, // Cast for type guard
|
|
2805
3533
|
targetStep,
|
|
2806
3534
|
walletOnly,
|