@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/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}`[];
|
|
@@ -223,6 +342,79 @@ type SignedIn<WalletProviderType, WS = WalletState<WalletProviderType>> =
|
|
|
223
342
|
wallet: WS;
|
|
224
343
|
};
|
|
225
344
|
|
|
345
|
+
/**
|
|
346
|
+
* WHY a connection attempt ended without reaching what was asked for.
|
|
347
|
+
*
|
|
348
|
+
* A machine-readable discriminant, so an app never has to parse `message` or infer from which
|
|
349
|
+
* fields happen to be absent. It is called `reason` and not `code` because `ConnectionFailure.code`
|
|
350
|
+
* is taken: that one carries the EIP-1193 code off `cause`, and the two answer different questions
|
|
351
|
+
* ("what did the wallet say" versus "what happened to my call").
|
|
352
|
+
*
|
|
353
|
+
* FORWARD COMPATIBILITY, decided rather than left implicit. This is a closed union so the type
|
|
354
|
+
* system can exhaust it, but **new members may appear in a MINOR version**, because a reason this
|
|
355
|
+
* library cannot yet tell apart is a reason it may learn to tell apart. That is why `'failed'`
|
|
356
|
+
* exists as a catch-all: most future causes land there and need no new member, and anything that
|
|
357
|
+
* does get one was previously indistinguishable from a generic failure anyway. **Keep a `default`
|
|
358
|
+
* branch in your switch.** An exhaustive switch with no default is the one shape a new member can
|
|
359
|
+
* break, and the trade was taken knowingly: a union you cannot switch on is worth less than one
|
|
360
|
+
* that may grow.
|
|
361
|
+
*
|
|
362
|
+
* - `cancelled` — the user closed or dismissed the connect flow (`cancel()`, `back(...)`, closing
|
|
363
|
+
* the hosted popup, or a disconnect while the call was waiting). Nothing failed and nothing is
|
|
364
|
+
* worth showing: they decided. **Say nothing.**
|
|
365
|
+
* - `address-unavailable-acknowledged` — the user read `connection.addressUnavailable` ("your
|
|
366
|
+
* wallet is not on that account") and chose not to switch. Also a decision, also not an error,
|
|
367
|
+
* and deliberately carrying the SAME `message` as `cancelled` (`'Connection cancelled'`) so that
|
|
368
|
+
* every existing "a refusal maps to cancelled" path keeps working untouched. Tell the two apart
|
|
369
|
+
* by THIS field, not by the shape.
|
|
370
|
+
* - `superseded` — a newer `ensureConnected` naming a DIFFERENT address took the connection's one
|
|
371
|
+
* account slot. The user decided nothing; the app asked for two things at once. Retry it, or use
|
|
372
|
+
* two connections with different `storagePrefix`es.
|
|
373
|
+
* - `unreachable` — the connection came to rest, nothing is in progress, and nothing can be
|
|
374
|
+
* initiated from here, so the target cannot be reached without a fresh gesture. An outcome to
|
|
375
|
+
* REPORT ("could not connect, try again"), not a silent no-op.
|
|
376
|
+
* - `wallet-rejected` — the wallet prompt was declined (EIP-1193 4001). Offer a retry.
|
|
377
|
+
* - `wallet-unavailable` — the wallet cannot authorise accounts (EIP-1193 4100): read-only,
|
|
378
|
+
* locked, or not configured. Retrying the same prompt will not help; the user must act in the
|
|
379
|
+
* wallet.
|
|
380
|
+
* - `no-accounts` — the wallet answered the request with an empty account list. It looks like a
|
|
381
|
+
* refusal and is not one, which is why it does not alias onto `cancelled`.
|
|
382
|
+
* - `cross-origin-blocked` — the wallet host refused a cross-origin request. The remedy is a
|
|
383
|
+
* registered delegate, not retrying the same popup. `cause` is the host's
|
|
384
|
+
* `{type: 'cross-origin-blocked', windowOrigin, signingOrigin}`.
|
|
385
|
+
* - `host-refused` — the wallet host refused for a reason of ITS own, which this library does not
|
|
386
|
+
* model. The host is deployed separately and chooses its own vocabulary, so its `type` is passed
|
|
387
|
+
* through untouched on `cause` rather than being mapped to a member this library cannot verify:
|
|
388
|
+
* read `(err.cause as {type?: string})?.type` and `err.message` to distinguish them.
|
|
389
|
+
* - `failed` — anything else, with the underlying error on `cause`. The catch-all: treat it as "it
|
|
390
|
+
* did not work", show `message`, offer a retry.
|
|
391
|
+
*/
|
|
392
|
+
export type ConnectionFailureReason =
|
|
393
|
+
| 'cancelled'
|
|
394
|
+
| 'address-unavailable-acknowledged'
|
|
395
|
+
| 'superseded'
|
|
396
|
+
| 'unreachable'
|
|
397
|
+
| 'wallet-rejected'
|
|
398
|
+
| 'wallet-unavailable'
|
|
399
|
+
| 'no-accounts'
|
|
400
|
+
| 'cross-origin-blocked'
|
|
401
|
+
| 'host-refused'
|
|
402
|
+
| 'failed';
|
|
403
|
+
|
|
404
|
+
/**
|
|
405
|
+
* The error a connection comes to rest carrying, which an app renders.
|
|
406
|
+
*
|
|
407
|
+
* `reason` is REQUIRED, and that is the whole design: it makes the compiler enumerate every place
|
|
408
|
+
* that can put an error on the connection, rather than leaving the next one to remember. This
|
|
409
|
+
* codebase has twice fixed bugs whose root cause was an invariant maintained at N call sites
|
|
410
|
+
* instead of one.
|
|
411
|
+
*
|
|
412
|
+
* It is the same vocabulary as the `ConnectionFailure` a pending `ensureConnected` rejects with,
|
|
413
|
+
* and not by coincidence: that failure COPIES this field, so the state an app renders and the
|
|
414
|
+
* error a caller catches cannot disagree about what happened.
|
|
415
|
+
*/
|
|
416
|
+
export type ConnectionError = {message: string; cause?: any; reason: ConnectionFailureReason};
|
|
417
|
+
|
|
226
418
|
// What the connection is, independently of which step it is at.
|
|
227
419
|
//
|
|
228
420
|
// Named rather than written inline below so that `set` can be given the same thing MINUS
|
|
@@ -231,7 +423,19 @@ type ConnectionCommon<WalletProviderType> = {
|
|
|
231
423
|
// The connection can have an error in every state.
|
|
232
424
|
// a banner or other mechanism to show error should be used.
|
|
233
425
|
// error should be dismissable
|
|
234
|
-
|
|
426
|
+
// `reason` says WHICH failure this is, in a closed vocabulary: see `ConnectionFailureReason`.
|
|
427
|
+
error?: ConnectionError;
|
|
428
|
+
/**
|
|
429
|
+
* Set when a caller asked this connection to act as an address the wallet is not offering.
|
|
430
|
+
*
|
|
431
|
+
* It sits BESIDE `error` rather than in it, and for the same reason it is not a throw: nothing
|
|
432
|
+
* failed. It is a resting reason with a remedy only the user can apply, so an app renders it as
|
|
433
|
+
* an instruction (see `AddressUnavailable`), not as a red banner.
|
|
434
|
+
*
|
|
435
|
+
* Like `error`, it survives a state built by spreading the current one and is dropped by any
|
|
436
|
+
* fresh transition, so a new attempt clears it without anybody remembering to.
|
|
437
|
+
*/
|
|
438
|
+
addressUnavailable?: AddressUnavailable;
|
|
235
439
|
// wallets represent the web3 wallet installed on the user browser
|
|
236
440
|
wallets: WalletHandle<WalletProviderType>[];
|
|
237
441
|
/**
|
|
@@ -342,6 +546,12 @@ export type WalletChosenState<WalletProviderType> = Extract<Connection<WalletPro
|
|
|
342
546
|
// Type representing wallet-connected states (both WalletConnected and SignedIn-via-wallet)
|
|
343
547
|
// This is what you get when targetStep is 'WalletConnected' and target is reached
|
|
344
548
|
// Both variants have WalletMechanism and wallet
|
|
549
|
+
//
|
|
550
|
+
// It is also what `ensureConnected('WalletConnected')` RESOLVES to, and that is the honest type
|
|
551
|
+
// rather than a widening for its own sake: the steps are ordered, so a signed-in connection
|
|
552
|
+
// satisfies the target and is handed back as itself. Typing that result as `WalletConnected` said
|
|
553
|
+
// `step: 'WalletConnected'` about a state whose step is `'SignedIn'`, and described its `account`
|
|
554
|
+
// as `{address}` when it is a whole `OriginAccount`.
|
|
345
555
|
export type ConnectedWithWallet<WalletProviderType> =
|
|
346
556
|
| WalletConnectedState<WalletProviderType>
|
|
347
557
|
| SignedInWithWallet<WalletProviderType>;
|
|
@@ -373,26 +583,55 @@ export function isTargetStepReached<WalletProviderType, Target extends TargetSte
|
|
|
373
583
|
: WalletOnly extends true
|
|
374
584
|
? SignedInWithWallet<WalletProviderType>
|
|
375
585
|
: SignedInState<WalletProviderType> {
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
586
|
+
// One ordered comparison, shared with the store's own `isTargetStepReached` and with
|
|
587
|
+
// `ensureConnected`. `walletOnly` narrows the RETURN TYPE and, for a `SignedIn` target, also the
|
|
588
|
+
// check: a hosted sign-in has no wallet to act through.
|
|
589
|
+
return stepIsAtOrBeyond(connection, targetStep, {requireWallet: !!walletOnly});
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
/**
|
|
593
|
+
* Can this connection sign as `address` RIGHT NOW, with no flow initiated and nothing prompted?
|
|
594
|
+
*
|
|
595
|
+
* The question `connection.account.address` does not answer. That field is the address the
|
|
596
|
+
* connection AGREED ON, which is the right thing for it to be: it survives the user locking their
|
|
597
|
+
* wallet, revoking the site, or switching account behind the connection's back, all of which keep
|
|
598
|
+
* `step: 'WalletConnected'` and change nothing about who was agreed on. What they change is whether
|
|
599
|
+
* anybody can sign, and that is what this reads (`wallet.status`, and the accounts the wallet is
|
|
600
|
+
* actually offering).
|
|
601
|
+
*
|
|
602
|
+
* It exists because a consumer needed it, wrote the comparison itself against `account.address`,
|
|
603
|
+
* and got a locked wallet wrong: it skipped its `ensureConnected` call, let the transaction out,
|
|
604
|
+
* and reported the provider's `{code: 4001}` as "transaction rejected by user" about a prompt
|
|
605
|
+
* nobody was ever shown. Use this to RENDER readiness (enable a button, show "unlock to pay"), and
|
|
606
|
+
* `ensureConnected(step, {type: 'wallet', address})` to actually reach it.
|
|
607
|
+
*
|
|
608
|
+
* Chain is deliberately not part of the answer: signing as an address is chain-independent, and
|
|
609
|
+
* `wallet.invalidChainId` is the separate question with its own separate remedy.
|
|
610
|
+
*/
|
|
611
|
+
export function canActAs<WalletProviderType>(
|
|
612
|
+
connection: Connection<WalletProviderType>,
|
|
613
|
+
address: `0x${string}`,
|
|
614
|
+
): boolean {
|
|
615
|
+
const wanted = address.toLowerCase();
|
|
616
|
+
if (!connection.wallet || connection.wallet.status !== 'connected') {
|
|
617
|
+
return false;
|
|
383
618
|
}
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
return
|
|
619
|
+
const agreedOn = 'account' in connection ? connection.account?.address : undefined;
|
|
620
|
+
if (!agreedOn || agreedOn.toLowerCase() !== wanted) {
|
|
621
|
+
return false;
|
|
387
622
|
}
|
|
388
|
-
|
|
389
|
-
//
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
623
|
+
const offered = connection.wallet.accounts;
|
|
624
|
+
// An empty list is what a wallet that was never asked reports, not a denial; `status` is the
|
|
625
|
+
// authority there. A non-empty one that does not contain the address IS a denial.
|
|
626
|
+
//
|
|
627
|
+
// Defensive, and marked as such: no state this library builds reaches here with an empty list
|
|
628
|
+
// (the states that have one, like `WalletChosen`, carry no `account` and are answered above). It
|
|
629
|
+
// is kept for a custom connector that publishes `connected` before it has read any accounts, and
|
|
630
|
+
// it is deliberately not counted as covered by any test.
|
|
631
|
+
if (offered.length > 0 && !offered.some((account) => account.toLowerCase() === wanted)) {
|
|
632
|
+
return false;
|
|
393
633
|
}
|
|
394
|
-
|
|
395
|
-
return connection.step === 'SignedIn';
|
|
634
|
+
return true;
|
|
396
635
|
}
|
|
397
636
|
|
|
398
637
|
function viemChainInfoToSwitchChainInfo(chainInfo: BasicChainInfo): {
|
|
@@ -463,19 +702,90 @@ export type EnsureConnectedOptions = ConnectOptions & {
|
|
|
463
702
|
forceConnect?: boolean;
|
|
464
703
|
};
|
|
465
704
|
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
705
|
+
/**
|
|
706
|
+
* Error thrown by `ensureConnected` when a connection attempt ends without reaching the target step.
|
|
707
|
+
*
|
|
708
|
+
* Three fields, answering three different questions:
|
|
709
|
+
*
|
|
710
|
+
* - `reason` — WHAT HAPPENED TO THIS CALL, in a closed vocabulary this library controls. Read this
|
|
711
|
+
* one to decide what to do. See `ConnectionFailureReason`, including its note on new members.
|
|
712
|
+
* - `cause` — the underlying error, exactly as whoever raised it wrote it (a wallet's EIP-1193
|
|
713
|
+
* error, the wallet host's `{type, message}` refusal). Unchanged by the arrival of `reason`.
|
|
714
|
+
* - `code` — the convenience copy of `cause.code`, so a user rejection is still `code === 4001`.
|
|
715
|
+
* `reason === 'wallet-rejected'` now says the same thing without the reach into `cause`.
|
|
716
|
+
*
|
|
717
|
+
* `message` is unchanged on every path, deliberately, including `'Connection cancelled'` for a
|
|
718
|
+
* dismissed `addressUnavailable`: the shape stays the safe one every consumer already maps to "the
|
|
719
|
+
* user chose not to", and `reason` says which of those it was.
|
|
720
|
+
*
|
|
721
|
+
* The third constructor argument is optional so that constructing one by hand (a test double, a
|
|
722
|
+
* consumer's own re-throw) keeps compiling; inside this library every failure comes from one place
|
|
723
|
+
* that always supplies it.
|
|
724
|
+
*/
|
|
469
725
|
export class ConnectionFailure extends Error {
|
|
470
726
|
name = 'ConnectionFailure';
|
|
471
727
|
readonly code?: unknown;
|
|
472
|
-
|
|
728
|
+
readonly reason: ConnectionFailureReason;
|
|
729
|
+
constructor(message: string, cause?: unknown, reason: ConnectionFailureReason = 'failed') {
|
|
473
730
|
super(message);
|
|
474
731
|
this.cause = cause;
|
|
475
732
|
this.code = (cause as {code?: unknown} | undefined)?.code;
|
|
733
|
+
this.reason = reason;
|
|
476
734
|
}
|
|
477
735
|
}
|
|
478
736
|
|
|
737
|
+
/**
|
|
738
|
+
* What an error THROWN AT US means, in the vocabulary above.
|
|
739
|
+
*
|
|
740
|
+
* One function rather than a test repeated at each catch site, because the mapping is the part that
|
|
741
|
+
* has to stay consistent: the same rejected wallet prompt must read as `wallet-rejected` whether it
|
|
742
|
+
* arrives from `eth_requestAccounts`, from a signature request, or from an attempt that rejected
|
|
743
|
+
* before it published anything.
|
|
744
|
+
*
|
|
745
|
+
* Only shapes this library can actually VERIFY are mapped. EIP-1193 codes are a standard the wallet
|
|
746
|
+
* and this library both agree on, and `cross-origin-blocked` is minted by `@etherplay/connect-core`
|
|
747
|
+
* in this same repo. Everything else keeps its own words on `cause` and lands on the catch-all.
|
|
748
|
+
*
|
|
749
|
+
* Note what this deliberately does NOT do: an unknown `{type}` does not become `host-refused` here,
|
|
750
|
+
* because an arbitrary thrown object carrying a `type` is not evidence that a HOST refused
|
|
751
|
+
* anything. Host refusals reach the connection through the popup catch, which uses
|
|
752
|
+
* `reasonForHostRefusal` instead. No path currently throws a host refusal INTO this function; if
|
|
753
|
+
* one ever does, it will read as `failed`, and this is the comment that says to route it through
|
|
754
|
+
* `reasonForHostRefusal` at that point rather than loosening the test here.
|
|
755
|
+
*/
|
|
756
|
+
function reasonForError(err: unknown): ConnectionFailureReason {
|
|
757
|
+
const code = (err as {code?: unknown} | undefined)?.code;
|
|
758
|
+
if (code === 4001) {
|
|
759
|
+
return 'wallet-rejected';
|
|
760
|
+
}
|
|
761
|
+
if (code === 4100) {
|
|
762
|
+
return 'wallet-unavailable';
|
|
763
|
+
}
|
|
764
|
+
if ((err as {type?: unknown} | undefined)?.type === 'cross-origin-blocked') {
|
|
765
|
+
return 'cross-origin-blocked';
|
|
766
|
+
}
|
|
767
|
+
return 'failed';
|
|
768
|
+
}
|
|
769
|
+
|
|
770
|
+
/**
|
|
771
|
+
* What a WALLET HOST refusal means, in the vocabulary above.
|
|
772
|
+
*
|
|
773
|
+
* The host is deployed separately and picks its own `type` strings, so only types this library can
|
|
774
|
+
* verify are mapped, and everything else passes through as `host-refused` with the host's own
|
|
775
|
+
* `type` left intact on `cause`. Inventing a member per host vocabulary word would be claiming to
|
|
776
|
+
* know something this package cannot check, and would go stale the moment the host shipped a new
|
|
777
|
+
* one.
|
|
778
|
+
*
|
|
779
|
+
* Exactly ONE type is mapped here, `cross-origin-blocked`, which comes from
|
|
780
|
+
* `@etherplay/connect-core` in this repo. The other verifiable type, `cancelation` (raised by this
|
|
781
|
+
* package's own popup, `src/popup.ts`), is handled by the CALLER and never reaches this function:
|
|
782
|
+
* closing the popup sets no error at all, and `ensureConnected` reports it through its own
|
|
783
|
+
* cancellation branch. A `undefined` refusal likewise cannot arrive, for the same reason.
|
|
784
|
+
*/
|
|
785
|
+
function reasonForHostRefusal(refusal: {type?: string} | undefined): ConnectionFailureReason {
|
|
786
|
+
return refusal?.type === 'cross-origin-blocked' ? 'cross-origin-blocked' : 'host-refused';
|
|
787
|
+
}
|
|
788
|
+
|
|
479
789
|
// Steps where a connection attempt is actively in progress: reaching one of them means an attempt started,
|
|
480
790
|
// and staying in one means we should keep waiting.
|
|
481
791
|
const stepsInProgress: readonly string[] = [
|
|
@@ -510,6 +820,14 @@ export type ConnectionStore<
|
|
|
510
820
|
cancel: () => void;
|
|
511
821
|
back: (step: 'MechanismToChoose' | 'Idle' | 'WalletToChoose') => void;
|
|
512
822
|
clearError: () => void;
|
|
823
|
+
// Dismiss a resting `connection.addressUnavailable`, which settles any `ensureConnected` waiting
|
|
824
|
+
// on it as a cancellation. The connection is left connected, on whatever account the wallet is
|
|
825
|
+
// offering. See `AddressUnavailable`.
|
|
826
|
+
acknowledgeAddressUnavailable: () => void;
|
|
827
|
+
// Can this connection sign as `address` right now? Reads the current state and initiates
|
|
828
|
+
// nothing, so it is safe to call while rendering. The standalone `canActAs(connection, address)`
|
|
829
|
+
// is the same answer against a state you already hold (a `$connection` in a reactive block).
|
|
830
|
+
canActAs: (address: `0x${string}`) => boolean;
|
|
513
831
|
requestSignature: () => Promise<void>;
|
|
514
832
|
connectToAddress: (
|
|
515
833
|
address: `0x${string}`,
|
|
@@ -548,12 +866,12 @@ export type ConnectionStore<
|
|
|
548
866
|
}
|
|
549
867
|
: Target extends 'WalletConnected'
|
|
550
868
|
? {
|
|
551
|
-
(options?: EnsureConnectedOptions): Promise<
|
|
869
|
+
(options?: EnsureConnectedOptions): Promise<ConnectedWithWallet<WalletProviderType>>;
|
|
552
870
|
(
|
|
553
871
|
step: 'WalletConnected',
|
|
554
872
|
mechanism?: WalletMechanism<string | undefined, `0x${string}` | undefined>,
|
|
555
873
|
options?: EnsureConnectedOptions,
|
|
556
|
-
): Promise<
|
|
874
|
+
): Promise<ConnectedWithWallet<WalletProviderType>>;
|
|
557
875
|
}
|
|
558
876
|
: WalletOnly extends true
|
|
559
877
|
? {
|
|
@@ -563,7 +881,7 @@ export type ConnectionStore<
|
|
|
563
881
|
step: 'WalletConnected',
|
|
564
882
|
mechanism?: WalletMechanism<string | undefined, `0x${string}` | undefined>,
|
|
565
883
|
options?: EnsureConnectedOptions,
|
|
566
|
-
): Promise<
|
|
884
|
+
): Promise<ConnectedWithWallet<WalletProviderType>>;
|
|
567
885
|
(
|
|
568
886
|
step: 'SignedIn',
|
|
569
887
|
mechanism?: WalletMechanism<string | undefined, `0x${string}` | undefined>,
|
|
@@ -576,7 +894,7 @@ export type ConnectionStore<
|
|
|
576
894
|
step: 'WalletConnected',
|
|
577
895
|
mechanism?: WalletMechanism<string | undefined, `0x${string}` | undefined>,
|
|
578
896
|
options?: EnsureConnectedOptions,
|
|
579
|
-
): Promise<
|
|
897
|
+
): Promise<ConnectedWithWallet<WalletProviderType>>;
|
|
580
898
|
(
|
|
581
899
|
step: 'SignedIn',
|
|
582
900
|
mechanism?: Mechanism,
|
|
@@ -894,6 +1212,11 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
894
1212
|
if (!connection.wallet && connection.step !== 'WaitingForWalletConnection') {
|
|
895
1213
|
teardownWallet();
|
|
896
1214
|
}
|
|
1215
|
+
// The address a resting reason last named, kept so a dismissal can be attributed to the request
|
|
1216
|
+
// the user was looking at even if an attempt clears the field a moment before they click.
|
|
1217
|
+
if (connection.addressUnavailable) {
|
|
1218
|
+
lastPublishedAddressUnavailable = connection.addressUnavailable.requested;
|
|
1219
|
+
}
|
|
897
1220
|
const pendingRequests = currentPendingRequests();
|
|
898
1221
|
if (!connection.wallet) {
|
|
899
1222
|
$connection = {...connection, pendingRequests};
|
|
@@ -958,7 +1281,12 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
958
1281
|
//
|
|
959
1282
|
// Auto-connect failures follow the same rule and rest on `Idle`: the user asked for nothing, so there is
|
|
960
1283
|
// no decision to offer them. A cancelled popup is likewise a cancellation, not a failure, and rests on `Idle`.
|
|
961
|
-
|
|
1284
|
+
//
|
|
1285
|
+
// `error` carries a REQUIRED `reason` (see `ConnectionFailureReason`). That is not decoration: a
|
|
1286
|
+
// pending `ensureConnected` copies it onto the `ConnectionFailure` it rejects with, so what the
|
|
1287
|
+
// app renders and what the caller catches cannot disagree, and requiring it here is what makes
|
|
1288
|
+
// the compiler enumerate the producers instead of leaving the next one to remember.
|
|
1289
|
+
function setConnectionFailure(error: ConnectionError) {
|
|
962
1290
|
const wallets = $connection.wallets;
|
|
963
1291
|
// Every resting state below has `wallet: undefined`, so `set` tears the live wallet down.
|
|
964
1292
|
if (!walletOnly) {
|
|
@@ -969,7 +1297,7 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
969
1297
|
set({step: 'Idle', loading: false, wallets, wallet: undefined, error});
|
|
970
1298
|
}
|
|
971
1299
|
}
|
|
972
|
-
function setError(error:
|
|
1300
|
+
function setError(error: ConnectionError) {
|
|
973
1301
|
if ($connection) {
|
|
974
1302
|
set({
|
|
975
1303
|
...$connection,
|
|
@@ -989,6 +1317,118 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
989
1317
|
}
|
|
990
1318
|
}
|
|
991
1319
|
|
|
1320
|
+
/**
|
|
1321
|
+
* The user has read "your wallet is not on that account" and chosen not to switch.
|
|
1322
|
+
*
|
|
1323
|
+
* THAT IS A CANCELLATION, and it settles the pending `ensureConnected` as one: the same
|
|
1324
|
+
* `ConnectionFailure('Connection cancelled')` a `cancel()` or a `back()` produces, so an app that
|
|
1325
|
+
* already maps a refusal to "the user chose not to" needs no new branch and shows no red error
|
|
1326
|
+
* for a decision.
|
|
1327
|
+
*
|
|
1328
|
+
* The connection itself is left exactly as it is, deliberately. It is CONNECTED, on the account
|
|
1329
|
+
* the wallet is actually offering, and "connected as somebody else, and saying so" is a better
|
|
1330
|
+
* place to leave a user than "not connected at all" — which is what the alternative, failing the
|
|
1331
|
+
* attempt, produced: every failure state carries `wallet: undefined`.
|
|
1332
|
+
*/
|
|
1333
|
+
function acknowledgeAddressUnavailable() {
|
|
1334
|
+
// WHICH request the user dismissed: the one on screen, or the one that was on screen a moment
|
|
1335
|
+
// ago if an attempt has just cleared the field out from under them.
|
|
1336
|
+
const dismissed = $connection.addressUnavailable?.requested ?? lastPublishedAddressUnavailable;
|
|
1337
|
+
if (dismissed) {
|
|
1338
|
+
const key = dismissed.toLowerCase();
|
|
1339
|
+
addressUnavailableAcknowledgements.set(key, (addressUnavailableAcknowledgements.get(key) ?? 0) + 1);
|
|
1340
|
+
}
|
|
1341
|
+
// COUNTED, not inferred. A pending `ensureConnected` used to read the reason DISAPPEARING as
|
|
1342
|
+
// the dismissal, which is true of this method and of nothing else — and plenty else clears it:
|
|
1343
|
+
// the app calling `connect()` itself, a `useCurrentAccount` store following the wallet onto
|
|
1344
|
+
// another account, the reason ceasing to be true. Each of those was reported to the caller as
|
|
1345
|
+
// `Connection cancelled`, which consumers are told to treat as "the user chose not to", so an
|
|
1346
|
+
// event the user never caused was invisible to them.
|
|
1347
|
+
//
|
|
1348
|
+
// Republished even when the field is already gone (an attempt may have cleared it a moment
|
|
1349
|
+
// ago): the publish is what wakes a pending `ensureConnected` to notice the dismissal. Without
|
|
1350
|
+
// it, a click landing in that window is counted and then never acted on, which is a wait that
|
|
1351
|
+
// nothing ends.
|
|
1352
|
+
set({
|
|
1353
|
+
...$connection,
|
|
1354
|
+
addressUnavailable: undefined,
|
|
1355
|
+
});
|
|
1356
|
+
}
|
|
1357
|
+
|
|
1358
|
+
// Dismissals of "your wallet is not on that account", COUNTED PER ADDRESS. See
|
|
1359
|
+
// `acknowledgeAddressUnavailable`: a pending `ensureConnected` watches the count for the address
|
|
1360
|
+
// IT asked about, so that a decision is told apart both from the several other things that clear
|
|
1361
|
+
// the same field and from a decision about somebody else's request. A single global count made
|
|
1362
|
+
// one dismissal cancel every address-bound call on the connection, including one whose wallet
|
|
1363
|
+
// prompt was open at that moment.
|
|
1364
|
+
const addressUnavailableAcknowledgements = new Map<string, number>();
|
|
1365
|
+
function acknowledgementsFor(address: `0x${string}`): number {
|
|
1366
|
+
return addressUnavailableAcknowledgements.get(address.toLowerCase()) ?? 0;
|
|
1367
|
+
}
|
|
1368
|
+
// The reason most recently PUBLISHED, so that a dismissal arriving in the brief window where an
|
|
1369
|
+
// attempt has cleared the field still names the address the user was actually looking at.
|
|
1370
|
+
let lastPublishedAddressUnavailable: `0x${string}` | undefined;
|
|
1371
|
+
|
|
1372
|
+
/**
|
|
1373
|
+
* The address-bound `ensureConnected` calls that are still live on this connection, in the order
|
|
1374
|
+
* they were made. Mirrors `addressUnavailableAcknowledgements` above: per connection, per address,
|
|
1375
|
+
* kept by the one thing that knows.
|
|
1376
|
+
*
|
|
1377
|
+
* WHY IT EXISTS. A connection has one wallet, one account and one `addressUnavailable` slot, so a
|
|
1378
|
+
* second call naming a DIFFERENT address supersedes the first: the newer request takes the slot,
|
|
1379
|
+
* the older one loses the state it was resting on and comes to rest with nothing in progress. That
|
|
1380
|
+
* is a real answer and it was already delivered honestly (`could not reach ...`, never a
|
|
1381
|
+
* cancellation the user did not make), but it arrived looking exactly like every other
|
|
1382
|
+
* come-to-rest, so no consumer could tell "your own app asked for something else" from "this
|
|
1383
|
+
* connection cannot get there". Only ONE call knows the difference and it is not the one being
|
|
1384
|
+
* answered, which is why supersession cannot be read off the connection state and needs a
|
|
1385
|
+
* registry.
|
|
1386
|
+
*
|
|
1387
|
+
* Registration is a monotonic id rather than a set, because the question is ordered: an OLDER
|
|
1388
|
+
* request is superseded by a NEWER one, never the other way round.
|
|
1389
|
+
*
|
|
1390
|
+
* WHAT IT IS AND IS NOT. `superseded` says "a later live request names another account", which is
|
|
1391
|
+
* an over-approximation of "that request is what displaced me": if some third thing (the app's own
|
|
1392
|
+
* `connect()`, a disconnect) ends both at once, the older is still labelled superseded. That is
|
|
1393
|
+
* the harmless direction, since the newer request was going to take the slot anyway, and the
|
|
1394
|
+
* remedy the label implies (retry) is the right one either way. The opposite error is avoided by
|
|
1395
|
+
* construction: a call that resolves without ever waiting returns before it registers.
|
|
1396
|
+
*
|
|
1397
|
+
* An entry lives exactly as long as its promise is unsettled, which for an abandoned call means as
|
|
1398
|
+
* long as the promise itself: this map holds no more than the pending calls already do.
|
|
1399
|
+
*/
|
|
1400
|
+
let addressBoundRequests = 0;
|
|
1401
|
+
const liveAddressBoundRequests = new Map<number, `0x${string}`>();
|
|
1402
|
+
function registerAddressBoundRequest(address: `0x${string}`): number {
|
|
1403
|
+
const id = ++addressBoundRequests;
|
|
1404
|
+
liveAddressBoundRequests.set(id, address.toLowerCase() as `0x${string}`);
|
|
1405
|
+
return id;
|
|
1406
|
+
}
|
|
1407
|
+
/** Is a LATER live request naming a DIFFERENT address, i.e. holding the slot this one needs? */
|
|
1408
|
+
function isSupersededBy(id: number, address: `0x${string}`): boolean {
|
|
1409
|
+
const asked = address.toLowerCase();
|
|
1410
|
+
for (const [otherId, otherAddress] of liveAddressBoundRequests) {
|
|
1411
|
+
if (otherId > id && otherAddress !== asked) {
|
|
1412
|
+
return true;
|
|
1413
|
+
}
|
|
1414
|
+
}
|
|
1415
|
+
return false;
|
|
1416
|
+
}
|
|
1417
|
+
|
|
1418
|
+
// How many times the user's WALLET has announced a DIFFERENT set of accounts. It is the unit
|
|
1419
|
+
// `ensureConnected` retries on, and it is the honest one: a retry is a response to the user
|
|
1420
|
+
// having done something in their wallet, so at most one attempt per announcement bounds the work
|
|
1421
|
+
// while never refusing to act on a real gesture. Counting distinct STATES instead looks stricter
|
|
1422
|
+
// and refuses the retry when the user returns to a state seen before, which is a normal thing for
|
|
1423
|
+
// a person to do.
|
|
1424
|
+
//
|
|
1425
|
+
// Only a CHANGE counts, and only an account one. The lock poll re-announces an empty list every
|
|
1426
|
+
// second, which is the absence of news rather than news, and would otherwise re-license an attempt
|
|
1427
|
+
// per second on a locked wallet; a chain change is news, but not news about accounts, and
|
|
1428
|
+
// re-prompting for an account because the user switched network answers a question they did not
|
|
1429
|
+
// ask.
|
|
1430
|
+
let walletAnnouncements = 0;
|
|
1431
|
+
|
|
992
1432
|
let _wallet: {provider: WalletProvider<WalletProviderType>; chainId: string} | undefined;
|
|
993
1433
|
|
|
994
1434
|
let popup: PopupPromise<OriginAccount> | undefined;
|
|
@@ -1365,7 +1805,10 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
1365
1805
|
name: $connection.mechanism.name,
|
|
1366
1806
|
address: $connection.mechanism.address,
|
|
1367
1807
|
},
|
|
1368
|
-
|
|
1808
|
+
// A declined signature prompt is the same 4001 a declined connect is, and the same
|
|
1809
|
+
// mapping names it: an app that offers "try again" on a rejection must not have to know
|
|
1810
|
+
// which prompt was rejected to recognise one.
|
|
1811
|
+
error: {message: 'failed to sign message', cause: err, reason: reasonForError(err)},
|
|
1369
1812
|
});
|
|
1370
1813
|
return;
|
|
1371
1814
|
}
|
|
@@ -1452,6 +1895,26 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
1452
1895
|
// TODO lastAccount
|
|
1453
1896
|
// console.log('account changed', accounts);
|
|
1454
1897
|
const accountsFormated = accounts.map((a) => a.toLowerCase()) as `0x${string}`[];
|
|
1898
|
+
// NEWS is an announcement that differs from what the connection currently believes — not one
|
|
1899
|
+
// that differs from the previous announcement. The two come apart exactly where it matters: an
|
|
1900
|
+
// attempt can go and find something else in between, so a wallet announcing the same list twice
|
|
1901
|
+
// with a contradicting answer in the middle is telling us something the second time too.
|
|
1902
|
+
if (accountsFormated.join(',') !== ($connection.wallet?.accounts ?? []).join(',')) {
|
|
1903
|
+
walletAnnouncements++;
|
|
1904
|
+
}
|
|
1905
|
+
|
|
1906
|
+
// A RESTING "your wallet is not on that account" MUST KEEP DESCRIBING THE WALLET AS IT IS.
|
|
1907
|
+
//
|
|
1908
|
+
// Every `set` below rebuilds the state by spreading the current one, so the reason would
|
|
1909
|
+
// survive an account change untouched: right about the FACT (the wallet still cannot act as
|
|
1910
|
+
// the requested account) and wrong about the DETAIL, since it would go on naming an account
|
|
1911
|
+
// the user has already left, and the app renders that sentence as the instruction. Telling
|
|
1912
|
+
// somebody to switch away from an account they are not on is worse than saying nothing.
|
|
1913
|
+
//
|
|
1914
|
+
// Computed here and published WITH the accounts rather than corrected afterwards, so that no
|
|
1915
|
+
// intermediate state is ever published in which the two disagree — a correction one publish
|
|
1916
|
+
// later is a frame of wrong instruction, which is exactly what an app renders.
|
|
1917
|
+
const addressUnavailable = refreshedAddressUnavailable(accountsFormated);
|
|
1455
1918
|
|
|
1456
1919
|
if ($connection.wallet) {
|
|
1457
1920
|
const locked = accountsFormated.length == 0;
|
|
@@ -1460,6 +1923,7 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
1460
1923
|
if (locked) {
|
|
1461
1924
|
set({
|
|
1462
1925
|
...$connection,
|
|
1926
|
+
addressUnavailable,
|
|
1463
1927
|
wallet: {
|
|
1464
1928
|
...$connection.wallet,
|
|
1465
1929
|
status: 'locked',
|
|
@@ -1473,6 +1937,7 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
1473
1937
|
if (disconnected) {
|
|
1474
1938
|
set({
|
|
1475
1939
|
...$connection,
|
|
1940
|
+
addressUnavailable,
|
|
1476
1941
|
wallet: {
|
|
1477
1942
|
...$connection.wallet,
|
|
1478
1943
|
status: 'disconnected',
|
|
@@ -1483,6 +1948,7 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
1483
1948
|
} else {
|
|
1484
1949
|
set({
|
|
1485
1950
|
...$connection,
|
|
1951
|
+
addressUnavailable,
|
|
1486
1952
|
wallet: {
|
|
1487
1953
|
...$connection.wallet,
|
|
1488
1954
|
status: 'connected',
|
|
@@ -1502,6 +1968,7 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
1502
1968
|
} else {
|
|
1503
1969
|
set({
|
|
1504
1970
|
...$connection,
|
|
1971
|
+
addressUnavailable,
|
|
1505
1972
|
wallet: {
|
|
1506
1973
|
...$connection.wallet,
|
|
1507
1974
|
accountChanged: accountsFormated[0],
|
|
@@ -1512,6 +1979,7 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
1512
1979
|
} else {
|
|
1513
1980
|
set({
|
|
1514
1981
|
...$connection,
|
|
1982
|
+
addressUnavailable,
|
|
1515
1983
|
wallet: {
|
|
1516
1984
|
...$connection.wallet,
|
|
1517
1985
|
accountChanged: undefined,
|
|
@@ -1522,6 +1990,33 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
1522
1990
|
}
|
|
1523
1991
|
}
|
|
1524
1992
|
|
|
1993
|
+
/**
|
|
1994
|
+
* The resting reason, re-derived against what the wallet is offering now.
|
|
1995
|
+
*
|
|
1996
|
+
* `undefined` once the wallet DOES offer the requested account: the reason has simply stopped
|
|
1997
|
+
* being true. A pending `ensureConnected` loses nothing by that — it watches the accounts the
|
|
1998
|
+
* wallet offers rather than this field, precisely so that the state going away because the user
|
|
1999
|
+
* fixed it cannot be mistaken for the user dismissing it.
|
|
2000
|
+
*/
|
|
2001
|
+
function refreshedAddressUnavailable(offered: `0x${string}`[]): AddressUnavailable | undefined {
|
|
2002
|
+
const unavailable = $connection.addressUnavailable;
|
|
2003
|
+
if (!unavailable) {
|
|
2004
|
+
return undefined;
|
|
2005
|
+
}
|
|
2006
|
+
if (offered.some((account) => account.toLowerCase() === unavailable.requested.toLowerCase())) {
|
|
2007
|
+
return undefined;
|
|
2008
|
+
}
|
|
2009
|
+
if (offered.join(',') === unavailable.available.join(',')) {
|
|
2010
|
+
return unavailable;
|
|
2011
|
+
}
|
|
2012
|
+
return describeAddressUnavailable({
|
|
2013
|
+
requested: unavailable.requested,
|
|
2014
|
+
walletName: unavailable.walletName,
|
|
2015
|
+
selected: offered[0],
|
|
2016
|
+
available: offered,
|
|
2017
|
+
});
|
|
2018
|
+
}
|
|
2019
|
+
|
|
1525
2020
|
// TODO lastAccounts
|
|
1526
2021
|
let lockCheckInterval: number | undefined;
|
|
1527
2022
|
async function checkLockStatus() {
|
|
@@ -1587,6 +2082,10 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
1587
2082
|
function restoreWalletChosenAfterFailedConnect(
|
|
1588
2083
|
errorMessage: string,
|
|
1589
2084
|
cause: unknown,
|
|
2085
|
+
// Taken as an argument rather than derived from `cause` here: this function is the RESTING
|
|
2086
|
+
// half of a failure whose other half is `setConnectionFailure`, and the two must label the
|
|
2087
|
+
// same event identically. An empty accounts answer has no `cause` to derive anything from.
|
|
2088
|
+
reason: ConnectionFailureReason,
|
|
1590
2089
|
chosenMechanism: WalletMechanism<string, undefined> | undefined,
|
|
1591
2090
|
chosenWallet: {provider: WalletProvider<WalletProviderType>; chainId: string} | undefined,
|
|
1592
2091
|
): boolean {
|
|
@@ -1627,7 +2126,7 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
1627
2126
|
invalidChainId: alwaysOnChainId != chainId,
|
|
1628
2127
|
switchingChain: false,
|
|
1629
2128
|
},
|
|
1630
|
-
error: {message: errorMessage, cause},
|
|
2129
|
+
error: {message: errorMessage, cause, reason},
|
|
1631
2130
|
});
|
|
1632
2131
|
return true;
|
|
1633
2132
|
}
|
|
@@ -1672,12 +2171,27 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
1672
2171
|
|
|
1673
2172
|
let remember: boolean = false;
|
|
1674
2173
|
/**
|
|
1675
|
-
* @param internal not part of the public `connect` surface.
|
|
1676
|
-
*
|
|
1677
|
-
*
|
|
1678
|
-
* `
|
|
2174
|
+
* @param internal not part of the public `connect` surface. THREE things an address can mean,
|
|
2175
|
+
* and they are told apart here rather than by inspecting the caller:
|
|
2176
|
+
*
|
|
2177
|
+
* - nothing set: a DEMAND. `connectToAddress(a)` and `connect({type: 'wallet', address: a})` mean
|
|
2178
|
+
* that account and no other, so a wallet that cannot offer it fails the attempt.
|
|
2179
|
+
* - `addressIsPreference`: a mechanism this library REPLAYED from the current state rather than
|
|
2180
|
+
* one anybody asked for, so a vanished address degrades to an ordinary connect.
|
|
2181
|
+
* - `reportUnavailableAddress`: a demand the caller wants REPORTED rather than thrown, which is
|
|
2182
|
+
* what `ensureConnected` asks for. Failing the attempt tears the wallet down (every failure
|
|
2183
|
+
* state carries `wallet: undefined`), which is the worst of the three endings: the user is left
|
|
2184
|
+
* with no wallet at all over a wallet that is working and merely on another account. So the
|
|
2185
|
+
* attempt completes on what the wallet does offer and comes to rest carrying
|
|
2186
|
+
* `addressUnavailable`, which is a state the app can render and the user can answer.
|
|
2187
|
+
*
|
|
2188
|
+
* See `resolveRequestedAddress` below.
|
|
1679
2189
|
*/
|
|
1680
|
-
async function connect(
|
|
2190
|
+
async function connect(
|
|
2191
|
+
mechanism?: Mechanism,
|
|
2192
|
+
options?: ConnectOptions,
|
|
2193
|
+
internal?: {addressIsPreference?: boolean; reportUnavailableAddress?: boolean},
|
|
2194
|
+
) {
|
|
1681
2195
|
if (!mechanism && (targetStep === 'WalletConnected' || walletOnly)) {
|
|
1682
2196
|
mechanism = {type: 'wallet'};
|
|
1683
2197
|
}
|
|
@@ -1691,7 +2205,14 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
1691
2205
|
// different wallet.
|
|
1692
2206
|
const chosenMechanismBeforeConnect = $connection.step === 'WalletChosen' ? $connection.mechanism : undefined;
|
|
1693
2207
|
const chosenWalletBeforeConnect = $connection.step === 'WalletChosen' ? _wallet : undefined;
|
|
1694
|
-
|
|
2208
|
+
// LOWERCASED HERE, at the boundary, because everything downstream compares against the
|
|
2209
|
+
// wallet's accounts, which are lowercased on arrival. A checksummed address (what a viem
|
|
2210
|
+
// local account hands back, so a perfectly ordinary thing for a caller to be holding) would
|
|
2211
|
+
// otherwise fail to match a wallet that is holding that very account. It was a latent
|
|
2212
|
+
// papercut while an unmatched address merely failed the attempt; now that a caller's address
|
|
2213
|
+
// is a requirement, it would send the user an instruction to switch to the account they are
|
|
2214
|
+
// already on.
|
|
2215
|
+
const specificAddress = mechanism.address?.toLowerCase() as `0x${string}` | undefined;
|
|
1695
2216
|
// WHICH ACCOUNT THE ATTEMPT IS FOR, once the wallet has said what it has.
|
|
1696
2217
|
//
|
|
1697
2218
|
// An address the CALLER named is a demand: `connectToAddress(a)` and
|
|
@@ -1706,6 +2227,13 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
1706
2227
|
// threw, which landed in the catch and tore the wallet down: the reconnect performed the
|
|
1707
2228
|
// very teardown it exists to prevent, one step later. Degrading to an ordinary connect is
|
|
1708
2229
|
// what the caller asked for anyway, since it asked to be connected and named nothing.
|
|
2230
|
+
//
|
|
2231
|
+
// The third possibility is `reportUnavailableAddress`: the demand stands, but the answer is
|
|
2232
|
+
// a state rather than a failure. `unavailableAddress` is what records it, and it is read
|
|
2233
|
+
// twice below — once to keep the flow off `ChooseWalletAccount` (the caller named an
|
|
2234
|
+
// account; offering a picker instead of saying why they cannot have it is answering a
|
|
2235
|
+
// different question), and once to stamp `addressUnavailable` on the resting state.
|
|
2236
|
+
let unavailableAddress: `0x${string}` | undefined;
|
|
1709
2237
|
const resolveRequestedAddress = (available: `0x${string}`[]): `0x${string}` | undefined => {
|
|
1710
2238
|
if (!specificAddress || available.includes(specificAddress)) {
|
|
1711
2239
|
return specificAddress;
|
|
@@ -1713,12 +2241,30 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
1713
2241
|
if (internal?.addressIsPreference) {
|
|
1714
2242
|
return undefined;
|
|
1715
2243
|
}
|
|
2244
|
+
if (internal?.reportUnavailableAddress) {
|
|
2245
|
+
unavailableAddress = specificAddress;
|
|
2246
|
+
return undefined;
|
|
2247
|
+
}
|
|
1716
2248
|
throw new Error(`could not find address ${specificAddress}`);
|
|
1717
2249
|
};
|
|
1718
2250
|
const walletName =
|
|
1719
2251
|
mechanism.name ||
|
|
1720
2252
|
($connection.step === 'WalletChosen' ? $connection.mechanism.name : undefined) ||
|
|
1721
2253
|
($connection.wallets.length == 1 ? $connection.wallets[0].info.name : undefined);
|
|
2254
|
+
/**
|
|
2255
|
+
* The resting reason to publish beside a connection that came back as somebody else.
|
|
2256
|
+
*
|
|
2257
|
+
* Everything the app needs to write the instruction is on it, including the accounts the
|
|
2258
|
+
* wallet IS offering: "switch account" is not actionable advice if the user cannot see
|
|
2259
|
+
* which account the wallet thinks it is on.
|
|
2260
|
+
*/
|
|
2261
|
+
const addressUnavailableFor = (
|
|
2262
|
+
available: `0x${string}`[],
|
|
2263
|
+
selected: `0x${string}` | undefined,
|
|
2264
|
+
): AddressUnavailable | undefined =>
|
|
2265
|
+
unavailableAddress
|
|
2266
|
+
? describeAddressUnavailable({requested: unavailableAddress, walletName, selected, available})
|
|
2267
|
+
: undefined;
|
|
1722
2268
|
if (walletName) {
|
|
1723
2269
|
const wallet = $connection.wallets.find((v) => v.info.name == walletName || v.info.uuid == walletName);
|
|
1724
2270
|
if (wallet) {
|
|
@@ -1763,8 +2309,11 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
1763
2309
|
accounts = accounts.map((v) => v.toLowerCase()) as `0x${string}`[];
|
|
1764
2310
|
if (accounts.length > 0) {
|
|
1765
2311
|
const requestedAddress = resolveRequestedAddress(accounts);
|
|
2312
|
+
// `!unavailableAddress`: the caller named an account and cannot have it. An account
|
|
2313
|
+
// picker would answer a question they did not ask; they get the wallet's current
|
|
2314
|
+
// account plus a resting reason naming every account it does offer.
|
|
1766
2315
|
const nextStep =
|
|
1767
|
-
!settings?.useCurrentAccount && !requestedAddress && accounts.length > 1
|
|
2316
|
+
!settings?.useCurrentAccount && !requestedAddress && !unavailableAddress && accounts.length > 1
|
|
1768
2317
|
? 'ChooseWalletAccount'
|
|
1769
2318
|
: 'WalletConnected';
|
|
1770
2319
|
const account = requestedAddress || accounts[0];
|
|
@@ -1803,9 +2352,14 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
1803
2352
|
switchingChain: false,
|
|
1804
2353
|
},
|
|
1805
2354
|
account: {address: account},
|
|
2355
|
+
addressUnavailable: addressUnavailableFor(accounts, account),
|
|
1806
2356
|
};
|
|
2357
|
+
// `!unavailableAddress`: do not raise a SIGNATURE prompt for an account the caller
|
|
2358
|
+
// did not ask to sign as. The instruction has to reach the user before anything
|
|
2359
|
+
// else asks them for something.
|
|
1807
2360
|
if (
|
|
1808
2361
|
newState.step === 'WalletConnected' &&
|
|
2362
|
+
!unavailableAddress &&
|
|
1809
2363
|
(requestSignatureAutomaticallyIfPossible || options?.requestSignatureRightAway) &&
|
|
1810
2364
|
!options?.requireUserConfirmationBeforeSignatureRequest
|
|
1811
2365
|
) {
|
|
@@ -1832,18 +2386,24 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
1832
2386
|
!restoreWalletChosenAfterFailedConnect(
|
|
1833
2387
|
'could not get any accounts',
|
|
1834
2388
|
undefined,
|
|
2389
|
+
// `no-accounts`, NOT a cancellation. The wallet answered, and answered with
|
|
2390
|
+
// nothing: from the outside that looks like a refusal and it is not one, which
|
|
2391
|
+
// is exactly the aliasing a consumer's own sniffing module got wrong.
|
|
2392
|
+
'no-accounts',
|
|
1835
2393
|
chosenMechanismBeforeConnect,
|
|
1836
2394
|
chosenWalletBeforeConnect,
|
|
1837
2395
|
)
|
|
1838
2396
|
) {
|
|
1839
|
-
setConnectionFailure({message: 'could not get any accounts'});
|
|
2397
|
+
setConnectionFailure({message: 'could not get any accounts', reason: 'no-accounts'});
|
|
1840
2398
|
}
|
|
1841
2399
|
}
|
|
1842
2400
|
} else {
|
|
1843
2401
|
const requestedAddress = resolveRequestedAddress(accounts);
|
|
1844
2402
|
const account = requestedAddress || accounts[0];
|
|
2403
|
+
// See the same expression on the requestAccounts branch above: a caller who named an
|
|
2404
|
+
// account gets a reason, not a picker.
|
|
1845
2405
|
const nextStep =
|
|
1846
|
-
!settings?.useCurrentAccount && !requestedAddress && accounts.length > 1
|
|
2406
|
+
!settings?.useCurrentAccount && !requestedAddress && !unavailableAddress && accounts.length > 1
|
|
1847
2407
|
? 'ChooseWalletAccount'
|
|
1848
2408
|
: 'WalletConnected';
|
|
1849
2409
|
const newState: ConnectionInput<WalletProviderType> =
|
|
@@ -1879,9 +2439,11 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
1879
2439
|
switchingChain: false,
|
|
1880
2440
|
},
|
|
1881
2441
|
account: {address: account},
|
|
2442
|
+
addressUnavailable: addressUnavailableFor(accounts, account),
|
|
1882
2443
|
};
|
|
1883
2444
|
if (
|
|
1884
2445
|
newState.step === 'WalletConnected' &&
|
|
2446
|
+
!unavailableAddress &&
|
|
1885
2447
|
(requestSignatureAutomaticallyIfPossible || options?.requestSignatureRightAway) &&
|
|
1886
2448
|
!options?.requireUserConfirmationBeforeSignatureRequest
|
|
1887
2449
|
) {
|
|
@@ -1906,6 +2468,12 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
1906
2468
|
// read-only, locked, or not yet configured (e.g. werust's keyless
|
|
1907
2469
|
// provider). 4001 (User Rejected Request): the user actively declined in
|
|
1908
2470
|
// the wallet popup. Anything else is a genuine failure.
|
|
2471
|
+
// The message picked per code below and the `reason` a consumer reads instead of
|
|
2472
|
+
// re-deriving it are two lists over the same two codes. They agree today and nothing
|
|
2473
|
+
// COUPLES them: a third message added here without a matching member in
|
|
2474
|
+
// `reasonForError` would be prose the discriminant does not know about. Deriving the
|
|
2475
|
+
// message from the reason would fix that and would change every message string, which
|
|
2476
|
+
// this change is not allowed to do.
|
|
1909
2477
|
const code = (err as {code?: unknown})?.code;
|
|
1910
2478
|
let errorMessage = `failed to connect to wallet`;
|
|
1911
2479
|
if (code === 4100) {
|
|
@@ -1922,20 +2490,28 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
1922
2490
|
// also tears the wallet down, because every failure state's `wallet` is
|
|
1923
2491
|
// `undefined` — a failed attempt must not keep routing requests (including
|
|
1924
2492
|
// read-only RPC calls like eth_call) through the failed wallet.
|
|
2493
|
+
// ONE derivation, read by both halves of the failure. The restore path and
|
|
2494
|
+
// `setConnectionFailure` are two landings for the same event, so a reason computed
|
|
2495
|
+
// twice is two chances to compute it differently.
|
|
2496
|
+
const reason = reasonForError(err);
|
|
1925
2497
|
if (
|
|
1926
2498
|
!restoreWalletChosenAfterFailedConnect(
|
|
1927
2499
|
errorMessage,
|
|
1928
2500
|
err,
|
|
2501
|
+
reason,
|
|
1929
2502
|
chosenMechanismBeforeConnect,
|
|
1930
2503
|
chosenWalletBeforeConnect,
|
|
1931
2504
|
)
|
|
1932
2505
|
) {
|
|
1933
|
-
setConnectionFailure({message: errorMessage, cause: err});
|
|
2506
|
+
setConnectionFailure({message: errorMessage, cause: err, reason});
|
|
1934
2507
|
}
|
|
1935
2508
|
}
|
|
1936
2509
|
} else {
|
|
1937
2510
|
console.error(`failed to get wallet ${walletName}`, $connection.wallets);
|
|
1938
|
-
|
|
2511
|
+
// The catch-all, deliberately: the named wallet is not among the announced ones (a typo, an
|
|
2512
|
+
// extension uninstalled between render and click). It gets no member of its own because it
|
|
2513
|
+
// is not a state the user can answer, and the message already names the wallet.
|
|
2514
|
+
setConnectionFailure({message: `failed to get wallet ${walletName}`, reason: 'failed'});
|
|
1939
2515
|
}
|
|
1940
2516
|
} else {
|
|
1941
2517
|
// TODO can also be done automatically before hand
|
|
@@ -2067,7 +2643,11 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
2067
2643
|
loading: false,
|
|
2068
2644
|
wallet: undefined,
|
|
2069
2645
|
wallets: $connection.wallets,
|
|
2070
|
-
|
|
2646
|
+
// The host's own `type` stays on `cause`, untouched; `reason` pins only what this library
|
|
2647
|
+
// can verify (`cross-origin-blocked`) and passes anything else through as `host-refused`.
|
|
2648
|
+
error: canceled
|
|
2649
|
+
? undefined
|
|
2650
|
+
: {message: refusal.message || 'sign in failed', cause: refusal, reason: reasonForHostRefusal(refusal)},
|
|
2071
2651
|
});
|
|
2072
2652
|
} finally {
|
|
2073
2653
|
unsubscribe();
|
|
@@ -2084,17 +2664,42 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
2084
2664
|
}
|
|
2085
2665
|
|
|
2086
2666
|
/**
|
|
2087
|
-
*
|
|
2667
|
+
* Reach `step`, as the mechanism describes it, doing whatever that takes.
|
|
2668
|
+
*
|
|
2669
|
+
* A TARGET, NOT A STEP COMPARISON. The target is satisfied when the connection is at or beyond
|
|
2670
|
+
* `step` (they are ordered: `SignedIn` implies `WalletConnected` implies `WalletChosen`), AND is
|
|
2671
|
+
* on the wallet the caller named, AND can act as the address the caller named, AND is on the
|
|
2672
|
+
* right chain (unless `skipChainCheck`). Anything the caller did not name is not part of it, so a
|
|
2673
|
+
* bare `ensureConnected()` is unchanged.
|
|
2674
|
+
*
|
|
2675
|
+
* An address or a wallet name a CALLER passes is a REQUIREMENT rather than a hint: the whole
|
|
2676
|
+
* reason to pass one is that this request only means anything for that account (replacing a stuck
|
|
2677
|
+
* transaction reuses its nonce, so it must be signed by the same key). A connection already at
|
|
2678
|
+
* the requested step but holding a different account therefore initiates an attempt rather than
|
|
2679
|
+
* resolving instantly with somebody else. An address this library REPLAYED from the connection's
|
|
2680
|
+
* own state stays a preference, because nobody asked for it.
|
|
2088
2681
|
*
|
|
2089
|
-
*
|
|
2090
|
-
*
|
|
2091
|
-
*
|
|
2682
|
+
* IT ALWAYS ANSWERS. There is no timeout, deliberately: a human is in the loop, so any timer is
|
|
2683
|
+
* either long enough to be useless or short enough to cut a user off mid-decision, and it would
|
|
2684
|
+
* report "timed out" for a wallet dialog that is open and perfectly healthy. The rule is narrower
|
|
2685
|
+
* and checkable instead: WAITING IS ONLY LEGITIMATE WHILE SOMETHING IS ACTUALLY IN PROGRESS. See
|
|
2686
|
+
* `awaitingUserReason` below for the closed list of what counts, each of which is a state the app
|
|
2687
|
+
* renders and the user answers. If the target is not satisfied, nothing is in progress and
|
|
2688
|
+
* nothing can be initiated, that is an ANSWER and it is delivered rather than awaited.
|
|
2092
2689
|
*
|
|
2093
|
-
*
|
|
2094
|
-
*
|
|
2095
|
-
*
|
|
2096
|
-
*
|
|
2097
|
-
*
|
|
2690
|
+
* So it ends in one of four ways: it resolves at the target; it rejects with a `ConnectionFailure`
|
|
2691
|
+
* (`cause`/`code` carry the underlying wallet error, so a user rejection is EIP-1193 code 4001);
|
|
2692
|
+
* it rejects with `ConnectionFailure('Connection cancelled')` when the user backs out, including
|
|
2693
|
+
* by acknowledging an `addressUnavailable`; or it stays pending while one of the listed things is
|
|
2694
|
+
* in progress.
|
|
2695
|
+
*
|
|
2696
|
+
* It initiates from `Idle`, from `WalletChosen` (the wallet is chosen, upgrading it is exactly
|
|
2697
|
+
* what was asked), from a resting state that does not satisfy the target, and from a picker step
|
|
2698
|
+
* (`MechanismToChoose`, `WalletToChoose`) that still carries the error of a previous failed
|
|
2699
|
+
* attempt, which is what makes a retry after a rejected wallet prompt work. It deliberately does
|
|
2700
|
+
* NOT initiate from a picker step without an error: that means the user is mid-choice with the
|
|
2701
|
+
* picker on screen, and connecting there would hijack their choice. In that case it waits for the
|
|
2702
|
+
* user to pick (or cancel). Pass `{forceConnect: true}` to connect anyway.
|
|
2098
2703
|
*/
|
|
2099
2704
|
// ensureConnected overloads - the default step depends on targetStep
|
|
2100
2705
|
function ensureConnected(
|
|
@@ -2109,7 +2714,7 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
2109
2714
|
step: 'WalletConnected',
|
|
2110
2715
|
mechanismOrOptions?: WalletMechanism<string | undefined, `0x${string}` | undefined> | EnsureConnectedOptions,
|
|
2111
2716
|
options?: EnsureConnectedOptions,
|
|
2112
|
-
): Promise<
|
|
2717
|
+
): Promise<ConnectedWithWallet<WalletProviderType>>;
|
|
2113
2718
|
function ensureConnected(
|
|
2114
2719
|
step: 'SignedIn',
|
|
2115
2720
|
mechanism?: Mechanism,
|
|
@@ -2134,7 +2739,13 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
2134
2739
|
opts = options;
|
|
2135
2740
|
} else {
|
|
2136
2741
|
mechanism = undefined;
|
|
2137
|
-
|
|
2742
|
+
// `?? options`: the second argument may be an EXPLICIT `undefined` mechanism, which is what
|
|
2743
|
+
// a caller writes when it has options but nothing to name (`ensureConnected('SignedIn',
|
|
2744
|
+
// undefined, {requestSignatureRightAway: true})`, and any call passing a mechanism variable
|
|
2745
|
+
// that happens to be unset). Reading only the second argument silently dropped the third,
|
|
2746
|
+
// so the options were ignored and the call waited for something the caller had asked it to
|
|
2747
|
+
// do itself.
|
|
2748
|
+
opts = (mechanismOrOptions as EnsureConnectedOptions | undefined) ?? options;
|
|
2138
2749
|
}
|
|
2139
2750
|
} else if (stepOrMechanismOrOptions && 'type' in (stepOrMechanismOrOptions as any)) {
|
|
2140
2751
|
// First arg is a mechanism
|
|
@@ -2156,6 +2767,17 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
2156
2767
|
const promise = new Promise<
|
|
2157
2768
|
WalletChosen<WalletProviderType> | WalletConnected<WalletProviderType> | SignedIn<WalletProviderType>
|
|
2158
2769
|
>((resolve, reject) => {
|
|
2770
|
+
// WHAT THE CALLER ASKED FOR, captured before `mechanism` can be reassigned below. An address
|
|
2771
|
+
// or a wallet name that arrives HERE came from the caller, so it is a requirement; anything
|
|
2772
|
+
// this library replays from the current state is a preference and never lands in these.
|
|
2773
|
+
const asked = mechanism && mechanism.type === 'wallet' ? mechanism : undefined;
|
|
2774
|
+
const askedWalletName = asked?.name;
|
|
2775
|
+
// Ignored for a `WalletChosen` target, and that is not an oversight: choosing a wallet never
|
|
2776
|
+
// asks it for accounts, so no state that target can reach could ever satisfy an address.
|
|
2777
|
+
// Requiring one there would guarantee the hang this rework exists to remove.
|
|
2778
|
+
const askedAddress =
|
|
2779
|
+
step === 'WalletChosen' ? undefined : (asked?.address?.toLowerCase() as `0x${string}` | undefined);
|
|
2780
|
+
|
|
2159
2781
|
let forceConnect = false;
|
|
2160
2782
|
// Whether the mechanism below was REPLAYED from the current state rather than asked for.
|
|
2161
2783
|
let reconnecting = false;
|
|
@@ -2164,66 +2786,119 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
2164
2786
|
// Only an error that appears after this point tells us that *our* attempt failed.
|
|
2165
2787
|
const errorOnEntry = $connection.error;
|
|
2166
2788
|
|
|
2167
|
-
|
|
2168
|
-
const
|
|
2169
|
-
if (
|
|
2170
|
-
|
|
2171
|
-
return (
|
|
2172
|
-
connection.step === 'WalletChosen' ||
|
|
2173
|
-
connection.step === 'WalletConnected' ||
|
|
2174
|
-
(connection.step === 'SignedIn' && connection.wallet !== undefined)
|
|
2175
|
-
);
|
|
2789
|
+
/** Is this connection on the wallet the caller named? Nothing named, nothing to check. */
|
|
2790
|
+
const walletNameMatches = (connection: Connection<WalletProviderType>): boolean => {
|
|
2791
|
+
if (!askedWalletName) {
|
|
2792
|
+
return true;
|
|
2176
2793
|
}
|
|
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
|
-
}
|
|
2794
|
+
const current =
|
|
2795
|
+
'mechanism' in connection ? (connection.mechanism as {type?: string; name?: string}) : undefined;
|
|
2796
|
+
if (current?.type !== 'wallet' || !current.name) {
|
|
2797
|
+
return false;
|
|
2186
2798
|
}
|
|
2187
|
-
|
|
2188
|
-
|
|
2799
|
+
if (current.name === askedWalletName) {
|
|
2800
|
+
return true;
|
|
2801
|
+
}
|
|
2802
|
+
// A name may be an EIP-6963 uuid: that is what `connect` looks wallets up by too, so the
|
|
2803
|
+
// two spellings of the same wallet must not read as two different wallets here.
|
|
2804
|
+
const handle = connection.wallets.find(
|
|
2805
|
+
(v) => v.info.name === askedWalletName || v.info.uuid === askedWalletName,
|
|
2806
|
+
);
|
|
2807
|
+
return !!handle && (handle.info.name === current.name || handle.info.uuid === current.name);
|
|
2189
2808
|
};
|
|
2190
2809
|
|
|
2810
|
+
/**
|
|
2811
|
+
* The part of the target a connection ATTEMPT could fix: the step, the wallet, the account.
|
|
2812
|
+
*
|
|
2813
|
+
* Split from the chain check below because the two call for opposite responses. Reconnecting
|
|
2814
|
+
* moves the step and the account; it does not move the chain, so initiating an attempt over a
|
|
2815
|
+
* chain mismatch would prompt the user for nothing and rebuild a wallet that was fine.
|
|
2816
|
+
*/
|
|
2817
|
+
const targetReached = (connection: Connection<WalletProviderType>): boolean =>
|
|
2818
|
+
stepIsAtOrBeyond(connection, step) &&
|
|
2819
|
+
walletNameMatches(connection) &&
|
|
2820
|
+
(!askedAddress || canActAs(connection, askedAddress)) &&
|
|
2821
|
+
// A `WalletConnected` connection whose wallet has gone locked or revoked is AT the step and
|
|
2822
|
+
// cannot act, so it does not satisfy a target that needs it to: that is the one and only
|
|
2823
|
+
// reason `ensureConnected` reconnects such a wallet where `connect()` would not (ADR-0002).
|
|
2824
|
+
// A `WalletChosen` target is exempt because it never needed accounts in the first place, and
|
|
2825
|
+
// `SignedIn` because a signed-in app acts through its session account, which a locked wallet
|
|
2826
|
+
// does not invalidate.
|
|
2827
|
+
(step === 'WalletChosen' || connection.step !== 'WalletConnected' || connection.wallet.status === 'connected');
|
|
2828
|
+
|
|
2829
|
+
/** The part it could not: only the user, or their wallet, moves the chain. */
|
|
2830
|
+
const chainIsRight = (connection: Connection<WalletProviderType>): boolean =>
|
|
2831
|
+
step !== 'WalletConnected' || !!opts?.skipChainCheck || !connection.wallet?.invalidChainId;
|
|
2832
|
+
|
|
2833
|
+
const canResolve = (connection: Connection<WalletProviderType>): boolean =>
|
|
2834
|
+
targetReached(connection) && chainIsRight(connection);
|
|
2835
|
+
|
|
2191
2836
|
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)
|
|
2837
|
+
if (!reconnect && canResolve($connection)) {
|
|
2201
2838
|
resolve($connection as any);
|
|
2202
2839
|
return;
|
|
2203
2840
|
}
|
|
2204
|
-
|
|
2205
|
-
|
|
2206
|
-
|
|
2207
|
-
|
|
2208
|
-
|
|
2209
|
-
|
|
2210
|
-
|
|
2211
|
-
|
|
2212
|
-
|
|
2213
|
-
|
|
2214
|
-
|
|
2215
|
-
|
|
2216
|
-
|
|
2217
|
-
|
|
2218
|
-
selectWallet(walletName, opts);
|
|
2841
|
+
if (reconnect) {
|
|
2842
|
+
// A locked or revoked wallet: reconnecting it is the only way to hand back something usable.
|
|
2843
|
+
forceConnect = true;
|
|
2844
|
+
if (askedAddress) {
|
|
2845
|
+
// The replayed mechanism MUST NOT overrule what the caller named. Substituting the stored
|
|
2846
|
+
// address here is precisely how a caller's requirement used to become somebody else's
|
|
2847
|
+
// account: the reconnect would come back on the stored one and the caller's address was
|
|
2848
|
+
// never looked at again. The wallet name is still worth reusing, since it is the wallet
|
|
2849
|
+
// this connection is on and the caller usually did not name one.
|
|
2850
|
+
mechanism = {type: 'wallet', name: askedWalletName || reconnect.name, address: askedAddress};
|
|
2851
|
+
} else if (askedWalletName && askedWalletName !== reconnect.name) {
|
|
2852
|
+
// A different wallet was named: replaying THIS wallet's account would demand an address
|
|
2853
|
+
// from a wallet that has no reason to have it.
|
|
2854
|
+
mechanism = {type: 'wallet', name: askedWalletName};
|
|
2219
2855
|
} else {
|
|
2220
|
-
|
|
2856
|
+
mechanism = reconnect;
|
|
2857
|
+
// ...and its ADDRESS is only a preference, because the user may unlock on another
|
|
2858
|
+
// account, and a replayed address is not something the caller asked for.
|
|
2859
|
+
reconnecting = true;
|
|
2221
2860
|
}
|
|
2222
2861
|
}
|
|
2862
|
+
let idlePassed = $connection.step != 'Idle';
|
|
2223
2863
|
|
|
2224
2864
|
// An attempt is considered started once we observe a step where the connection is in progress.
|
|
2225
2865
|
// Falling back to a resting step from there means the attempt ended without reaching the target.
|
|
2226
2866
|
let attemptStarted = false;
|
|
2867
|
+
// Dismissals of the address-unavailable state that happened BEFORE this call: only a later one
|
|
2868
|
+
// is this call's answer.
|
|
2869
|
+
const acknowledgementsOnEntry = askedAddress ? acknowledgementsFor(askedAddress) : 0;
|
|
2870
|
+
// THIS CALL'S PLACE IN THE QUEUE for the connection's one account slot, kept only while the
|
|
2871
|
+
// call is live (see `settle`). Registered here, after the early resolve above has already
|
|
2872
|
+
// returned, so a call that never waited never claims the slot at all.
|
|
2873
|
+
const addressBoundRequestId = askedAddress ? registerAddressBoundRequest(askedAddress) : undefined;
|
|
2874
|
+
// WHAT STOPS "try again" FROM BECOMING A LOOP: at most one attempt per wallet announcement.
|
|
2875
|
+
//
|
|
2876
|
+
// Our own attempts do not bump `walletAnnouncements`, so an attempt can never start another one
|
|
2877
|
+
// off its own result, however the wallet answers. Anything past that requires the user to act
|
|
2878
|
+
// in their wallet again, which is a person, not a loop.
|
|
2879
|
+
//
|
|
2880
|
+
// Two earlier versions of this rule are worth not repeating. "One attempt per distinct wallet
|
|
2881
|
+
// ANSWER" read well and measured false (the reset that stopped it suppressing legitimate
|
|
2882
|
+
// retries forgot the answer every time). "One attempt per distinct STATE" is provably
|
|
2883
|
+
// terminating and refuses the retry when the user switches back to an account they were on
|
|
2884
|
+
// before, which is an ordinary thing to do and leaves them following an instruction that no
|
|
2885
|
+
// longer does anything.
|
|
2886
|
+
//
|
|
2887
|
+
// Load-bearing, and pinned the hard way: delete this guard and `test/ensure-connected-settles`
|
|
2888
|
+
// does not fail, it HANGS, which is the honest signature of the bug it prevents.
|
|
2889
|
+
let attemptedAtEvent: number | undefined;
|
|
2890
|
+
// An attempt decided on but not started yet: see `scheduleAttempt`.
|
|
2891
|
+
let attemptScheduled = false;
|
|
2892
|
+
// How many attempts THIS call has started that have not finished yet.
|
|
2893
|
+
//
|
|
2894
|
+
// The store is not enough to know that. `connect` publishes `WaitingForWalletConnection`
|
|
2895
|
+
// before its first await, but `selectWallet` awaits `getChainId` before publishing anything at
|
|
2896
|
+
// all, and the popup path can await a key generation first. In that window the store still
|
|
2897
|
+
// holds the entry state, nothing is "in progress" as far as any published state is concerned,
|
|
2898
|
+
// and the answer branch below would report "nothing is in progress" about an attempt that is
|
|
2899
|
+
// running and about to succeed. It did exactly that, for `ensureConnected('WalletChosen')`
|
|
2900
|
+
// from any non-Idle state: rejected, and then reached the target anyway.
|
|
2901
|
+
let attemptsInFlight = 0;
|
|
2227
2902
|
let settled = false;
|
|
2228
2903
|
let unsubscribe: (() => void) | undefined;
|
|
2229
2904
|
const settle = (perform: () => void) => {
|
|
@@ -2233,10 +2908,265 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
2233
2908
|
settled = true;
|
|
2234
2909
|
// unsubscribe can still be undefined here if the store settles during the initial (synchronous) subscription
|
|
2235
2910
|
unsubscribe?.();
|
|
2911
|
+
// This call is over, so it stops competing for the account slot and stops being counted
|
|
2912
|
+
// against anybody.
|
|
2913
|
+
//
|
|
2914
|
+
// HONEST NOTE, because no test fails if this is deleted: it is defensive. For it to change
|
|
2915
|
+
// an observable label, a NEWER address-bound call would have to settle while an OLDER one
|
|
2916
|
+
// stays live, and every way a newer call can settle publishes a state that also ends an
|
|
2917
|
+
// older call resting on it — while an older call that is still waiting is waiting on
|
|
2918
|
+
// something in progress, which publishes again in its turn. Kept anyway: it also bounds the
|
|
2919
|
+
// map, and "the registry contains the live requests" is cheaper to keep true than to reason
|
|
2920
|
+
// about every time somebody adds a settle path.
|
|
2921
|
+
if (addressBoundRequestId !== undefined) {
|
|
2922
|
+
liveAddressBoundRequests.delete(addressBoundRequestId);
|
|
2923
|
+
}
|
|
2236
2924
|
perform();
|
|
2237
2925
|
};
|
|
2926
|
+
/**
|
|
2927
|
+
* THE ONE PLACE A `ConnectionFailure` IS BUILT, and it takes the reason first.
|
|
2928
|
+
*
|
|
2929
|
+
* Not tidiness: `reason` is the field that must never be forgotten, and a rule kept at four
|
|
2930
|
+
* call sites is a rule that is kept at three of them a year from now. This codebase has
|
|
2931
|
+
* twice fixed bugs whose root cause was exactly that (`pendingRequests`, wallet teardown).
|
|
2932
|
+
*/
|
|
2933
|
+
const failWith = (reason: ConnectionFailureReason, message: string, cause?: unknown) =>
|
|
2934
|
+
settle(() => reject(new ConnectionFailure(message, cause, reason)));
|
|
2935
|
+
/**
|
|
2936
|
+
* The MESSAGE is the same for both, and that is the point: every consumer already maps
|
|
2937
|
+
* `'Connection cancelled'` to "the user chose not to" and shows nothing, so a dismissed
|
|
2938
|
+
* `addressUnavailable` must keep arriving in that shape and must not paint a red banner over
|
|
2939
|
+
* a decision. What was missing is WHICH decision, and that is what `reason` adds.
|
|
2940
|
+
*/
|
|
2941
|
+
const cancelled = (reason: 'cancelled' | 'address-unavailable-acknowledged') =>
|
|
2942
|
+
failWith(reason, 'Connection cancelled');
|
|
2943
|
+
|
|
2944
|
+
/**
|
|
2945
|
+
* Start an attempt and stay honest about it while it runs.
|
|
2946
|
+
*
|
|
2947
|
+
* Everything these calls do, they normally do by moving the store, and the subscription below
|
|
2948
|
+
* reads the answer off it. Two things break that, and both are handled here rather than by
|
|
2949
|
+
* guessing from published states:
|
|
2950
|
+
*
|
|
2951
|
+
* - an attempt can be RUNNING while the store still shows the state it started from, because
|
|
2952
|
+
* `selectWallet` (and the popup path) await before their first publish;
|
|
2953
|
+
* - an attempt can FAIL before its first publish (a hosted mechanism with no `walletHost`),
|
|
2954
|
+
* after which nothing has changed and nothing will publish again.
|
|
2955
|
+
*
|
|
2956
|
+
* A late rejection, after the flow moved on, settles nothing: `settle` is idempotent and the
|
|
2957
|
+
* store has already answered.
|
|
2958
|
+
*/
|
|
2959
|
+
const runAttempt = (attempt: Promise<unknown>) => {
|
|
2960
|
+
attemptsInFlight++;
|
|
2961
|
+
attempt.then(
|
|
2962
|
+
() => {
|
|
2963
|
+
attemptsInFlight--;
|
|
2964
|
+
// Decide again now that it is over. The store may have published its last state while
|
|
2965
|
+
// this attempt still counted as in progress, and nothing else will publish again: an
|
|
2966
|
+
// attempt that ends without reaching the target has to be answered here or nowhere.
|
|
2967
|
+
evaluate($connection);
|
|
2968
|
+
},
|
|
2969
|
+
(err) => {
|
|
2970
|
+
attemptsInFlight--;
|
|
2971
|
+
failWith(reasonForError(err), (err as Error)?.message || `could not reach ${step}`, err);
|
|
2972
|
+
},
|
|
2973
|
+
);
|
|
2974
|
+
};
|
|
2975
|
+
|
|
2976
|
+
/** Is the connection sitting on the account the caller asked for, ready to be asked to sign? */
|
|
2977
|
+
const readyToSign = (connection: Connection<WalletProviderType>): boolean =>
|
|
2978
|
+
connection.step === 'WalletConnected' &&
|
|
2979
|
+
connection.wallet.status === 'connected' &&
|
|
2980
|
+
walletNameMatches(connection) &&
|
|
2981
|
+
(!askedAddress || canActAs(connection, askedAddress));
|
|
2982
|
+
|
|
2983
|
+
/**
|
|
2984
|
+
* Do whatever can be done from where the connection is right now.
|
|
2985
|
+
*
|
|
2986
|
+
* It may deliberately do NOTHING, in the one case where the pending thing is a click in the
|
|
2987
|
+
* app rather than anything this library can start: a `WalletConnected` connection asked for
|
|
2988
|
+
* `SignedIn` on a store that did not ask for the signature to be requested automatically. That
|
|
2989
|
+
* app renders its own "sign in" button, and prompting over the top of it would ask the user
|
|
2990
|
+
* for a signature the app deliberately deferred. `awaitingUserReason` names that state, so it
|
|
2991
|
+
* is a legitimate wait rather than a silent one.
|
|
2992
|
+
*/
|
|
2993
|
+
const initiate = (): boolean => {
|
|
2994
|
+
if (step === 'WalletChosen') {
|
|
2995
|
+
runAttempt(selectWallet(askedWalletName, opts));
|
|
2996
|
+
return true;
|
|
2997
|
+
}
|
|
2998
|
+
if (step === 'SignedIn' && readyToSign($connection)) {
|
|
2999
|
+
const mayRequestSignature =
|
|
3000
|
+
(requestSignatureAutomaticallyIfPossible || opts?.requestSignatureRightAway) &&
|
|
3001
|
+
!opts?.requireUserConfirmationBeforeSignatureRequest;
|
|
3002
|
+
if (mayRequestSignature) {
|
|
3003
|
+
// The narrow remedy: the wallet is already connected on the right account, so the only
|
|
3004
|
+
// thing between here and `SignedIn` is the signature. Reconnecting would prompt twice.
|
|
3005
|
+
// Failures land on the state as an error, which the subscription below reports.
|
|
3006
|
+
runAttempt(requestSignature());
|
|
3007
|
+
return true;
|
|
3008
|
+
}
|
|
3009
|
+
// Nothing started: the pending thing is a click in the app. Reported honestly, so the
|
|
3010
|
+
// caller falls through to the wait reasons instead of being told an attempt is running.
|
|
3011
|
+
return false;
|
|
3012
|
+
}
|
|
3013
|
+
runAttempt(
|
|
3014
|
+
connect(mechanism, opts, {addressIsPreference: reconnecting, reportUnavailableAddress: !!askedAddress}),
|
|
3015
|
+
);
|
|
3016
|
+
return true;
|
|
3017
|
+
};
|
|
2238
3018
|
|
|
2239
|
-
|
|
3019
|
+
// WHEN AN ATTEMPT MAY BE INITIATED.
|
|
3020
|
+
//
|
|
3021
|
+
// Not while one is already running (`stepsInProgress`), and not while the user is mid-choice
|
|
3022
|
+
// with a picker on screen, since connecting there would hijack their choice. A picker still
|
|
3023
|
+
// carrying the error of a previous attempt is the exception: that attempt failed and nothing
|
|
3024
|
+
// has driven the flow since, so re-initiating is exactly what the caller asked for. It cannot
|
|
3025
|
+
// hijack a choice either, because when a choice is genuinely needed `connect` re-enters the
|
|
3026
|
+
// same picker (clearing the stale error) and we keep waiting.
|
|
3027
|
+
//
|
|
3028
|
+
// Everything else initiates, INCLUDING the resting steps that used to fall through every
|
|
3029
|
+
// branch and wait forever: a `WalletChosen` connection asked to connect, and a connection at
|
|
3030
|
+
// rest holding an account the caller did not ask for.
|
|
3031
|
+
/**
|
|
3032
|
+
* Start an attempt from this state, if one is called for and would not be a repeat.
|
|
3033
|
+
*
|
|
3034
|
+
* Used at entry AND from `evaluate`, which is the fix for an answer that depended on timing:
|
|
3035
|
+
* initiating only at entry meant a call made while some OTHER flow was in progress (a picker
|
|
3036
|
+
* the user was mid-way through, say) got "nothing is in progress" the moment that flow ended
|
|
3037
|
+
* without satisfying it — while the identical call, made one tick later, initiated and
|
|
3038
|
+
* succeeded. Same store, same request, opposite answers.
|
|
3039
|
+
*/
|
|
3040
|
+
/**
|
|
3041
|
+
* Would attempting AGAINST THIS STATE be wrong, whatever the caller asked for?
|
|
3042
|
+
*
|
|
3043
|
+
* Pulled out because it has to be asked TWICE: once when the attempt is decided on, and again
|
|
3044
|
+
* when a deferred attempt actually runs. The deferral exists precisely because the state moves
|
|
3045
|
+
* in between, so re-checking less than was checked the first time is backwards — and it was:
|
|
3046
|
+
* the microtask used to re-check only the target, so a `useCurrentAccount` store that had
|
|
3047
|
+
* meanwhile started its own connect got a SECOND concurrent one, two `eth_requestAccounts` at
|
|
3048
|
+
* once, and a wallet answering the second with "already processing" would have rejected a call
|
|
3049
|
+
* whose real attempt was still running and about to succeed.
|
|
3050
|
+
*/
|
|
3051
|
+
const attemptWouldBeWrongNow = (connection: Connection<WalletProviderType>): boolean => {
|
|
3052
|
+
if (targetReached(connection) || attemptsInFlight > 0) {
|
|
3053
|
+
return true;
|
|
3054
|
+
}
|
|
3055
|
+
if (stepsInProgress.includes(connection.step)) {
|
|
3056
|
+
return true;
|
|
3057
|
+
}
|
|
3058
|
+
// A picker the user is mid-choice on is theirs, not ours to hijack. One carrying the error
|
|
3059
|
+
// of a previous attempt is different: that attempt failed and nothing has driven the flow
|
|
3060
|
+
// since, so re-initiating is what the caller asked for.
|
|
3061
|
+
const userIsChoosing =
|
|
3062
|
+
(connection.step === 'MechanismToChoose' || connection.step === 'WalletToChoose') && !errorOnEntry;
|
|
3063
|
+
return userIsChoosing && !opts?.forceConnect && !forceConnect;
|
|
3064
|
+
};
|
|
3065
|
+
|
|
3066
|
+
const initiateIfWorthwhile = (
|
|
3067
|
+
connection: Connection<WalletProviderType>,
|
|
3068
|
+
start: () => boolean = initiate,
|
|
3069
|
+
): boolean => {
|
|
3070
|
+
if (attemptScheduled || attemptWouldBeWrongNow(connection)) {
|
|
3071
|
+
return false;
|
|
3072
|
+
}
|
|
3073
|
+
if (attemptedAtEvent === walletAnnouncements) {
|
|
3074
|
+
return false;
|
|
3075
|
+
}
|
|
3076
|
+
attemptedAtEvent = walletAnnouncements;
|
|
3077
|
+
return start();
|
|
3078
|
+
};
|
|
3079
|
+
|
|
3080
|
+
initiateIfWorthwhile($connection);
|
|
3081
|
+
|
|
3082
|
+
/**
|
|
3083
|
+
* WHY WAITING IS LEGITIMATE RIGHT NOW, or `undefined` if it is not.
|
|
3084
|
+
*
|
|
3085
|
+
* The closed list, and the whole of the settle guarantee: every entry is something IN
|
|
3086
|
+
* PROGRESS, and every one of them is published on the connection for the app to render and
|
|
3087
|
+
* for the user to answer. Anything not on this list is not a wait, it is an unanswered
|
|
3088
|
+
* question, and the caller gets an answer instead (see the end of the subscription).
|
|
3089
|
+
*
|
|
3090
|
+
* Deliberately NOT a timeout. A human is in the loop: a timer long enough not to cut someone
|
|
3091
|
+
* off mid-decision is too long to be useful, and it would report "timed out" about a wallet
|
|
3092
|
+
* dialog that is open and healthy.
|
|
3093
|
+
*/
|
|
3094
|
+
const awaitingUserReason = (connection: Connection<WalletProviderType>): string | undefined => {
|
|
3095
|
+
if (attemptsInFlight > 0 || attemptScheduled) {
|
|
3096
|
+
// Not inferred from the state: this call started something and it has not come back.
|
|
3097
|
+
// Covers the window before an attempt's first publish, which the store cannot show, and
|
|
3098
|
+
// the window between deciding to attempt and the microtask that runs it.
|
|
3099
|
+
return 'an attempt this call started is still running';
|
|
3100
|
+
}
|
|
3101
|
+
if (stepsInProgress.includes(connection.step)) {
|
|
3102
|
+
return 'an attempt is in progress';
|
|
3103
|
+
}
|
|
3104
|
+
if (connection.step === 'MechanismToChoose' || connection.step === 'WalletToChoose') {
|
|
3105
|
+
return 'the user is choosing';
|
|
3106
|
+
}
|
|
3107
|
+
if (
|
|
3108
|
+
askedAddress &&
|
|
3109
|
+
connection.addressUnavailable?.requested.toLowerCase() === askedAddress &&
|
|
3110
|
+
// ...and it is still TRUE. A reason that has gone stale (the wallet does offer the
|
|
3111
|
+
// account now) licenses a wait that nothing can end: the user has already done the only
|
|
3112
|
+
// thing it asks of them. The same freshness test guards the resting branch in `evaluate`,
|
|
3113
|
+
// and the two must agree or the disagreement IS the hang.
|
|
3114
|
+
!(connection.wallet?.accounts ?? []).some((account) => account.toLowerCase() === askedAddress)
|
|
3115
|
+
) {
|
|
3116
|
+
// Only OUR request licenses this wait. A reason left on the connection by a different
|
|
3117
|
+
// call describes an account this call never asked about, and waiting on somebody else's
|
|
3118
|
+
// unanswered question is how a wait becomes unending.
|
|
3119
|
+
return 'the wallet is not on the account that was asked for';
|
|
3120
|
+
}
|
|
3121
|
+
if (targetReached(connection) && !chainIsRight(connection)) {
|
|
3122
|
+
return 'the wallet is on another chain';
|
|
3123
|
+
}
|
|
3124
|
+
if (step === 'SignedIn' && readyToSign(connection)) {
|
|
3125
|
+
// The app's own "sign in" button is the pending decision — but only while the connection
|
|
3126
|
+
// could actually be asked to sign. On a wallet that has since locked or moved account,
|
|
3127
|
+
// `requestSignature()` is not a remedy the user can take, so this is not a wait, and the
|
|
3128
|
+
// caller gets an answer instead.
|
|
3129
|
+
return 'the signature has not been requested yet';
|
|
3130
|
+
}
|
|
3131
|
+
return undefined;
|
|
3132
|
+
};
|
|
3133
|
+
|
|
3134
|
+
/**
|
|
3135
|
+
* Start an attempt AFTER the current publish, never during it.
|
|
3136
|
+
*
|
|
3137
|
+
* `evaluate` runs inside `set`, and a wallet event does not produce one state: `onAccountChanged`
|
|
3138
|
+
* publishes the new status first and the new accounts second. Starting a connection attempt
|
|
3139
|
+
* from inside the first of those re-enters the store while the handler is still mid-way through
|
|
3140
|
+
* its own transitions, which then continue on top of a state the attempt has replaced — rebuilding
|
|
3141
|
+
* a wallet from one that is no longer there. So the decision is taken synchronously (which is
|
|
3142
|
+
* what keeps the accounting honest) and the work is done once the dust settles, against whatever
|
|
3143
|
+
* state the handler finally left behind.
|
|
3144
|
+
*/
|
|
3145
|
+
const scheduleAttempt = (): boolean => {
|
|
3146
|
+
attemptScheduled = true;
|
|
3147
|
+
queueMicrotask(() => {
|
|
3148
|
+
attemptScheduled = false;
|
|
3149
|
+
if (settled) {
|
|
3150
|
+
return;
|
|
3151
|
+
}
|
|
3152
|
+
// EVERY guard re-applied against the state as it now is, not just the target: the rest of
|
|
3153
|
+
// the handler that published may have satisfied the request, started its own attempt, or
|
|
3154
|
+
// moved the connection somewhere attempting would be wrong (a popup, an account picker,
|
|
3155
|
+
// another wallet). The event guard is NOT re-applied, because this attempt already
|
|
3156
|
+
// consumed it when it was scheduled.
|
|
3157
|
+
if (attemptWouldBeWrongNow($connection) || !initiate()) {
|
|
3158
|
+
evaluate($connection);
|
|
3159
|
+
}
|
|
3160
|
+
});
|
|
3161
|
+
return true;
|
|
3162
|
+
};
|
|
3163
|
+
|
|
3164
|
+
/**
|
|
3165
|
+
* Decide, against one state. Called for every publish, AND once more whenever an attempt this
|
|
3166
|
+
* call started comes back, because the last publish may have happened while that attempt was
|
|
3167
|
+
* still running and nothing will publish again afterwards.
|
|
3168
|
+
*/
|
|
3169
|
+
const evaluate = (connection: Connection<WalletProviderType>) => {
|
|
2240
3170
|
if (settled) {
|
|
2241
3171
|
return;
|
|
2242
3172
|
}
|
|
@@ -2249,6 +3179,20 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
2249
3179
|
return;
|
|
2250
3180
|
}
|
|
2251
3181
|
|
|
3182
|
+
// THE USER DISMISSED the "your wallet is not on that account" state for the address THIS
|
|
3183
|
+
// call asked about. Checked before anything else that can return: a decision is an answer
|
|
3184
|
+
// whatever else is happening on the connection, and this call may be resting while a
|
|
3185
|
+
// DIFFERENT one has the flow in progress — in which case the in-progress branch below would
|
|
3186
|
+
// swallow the dismissal, and nothing would publish again to bring it back.
|
|
3187
|
+
//
|
|
3188
|
+
// Read from the acknowledgement count FOR THAT ADDRESS rather than from the reason
|
|
3189
|
+
// disappearing. Several things clear that field and only one of them is a decision; and a
|
|
3190
|
+
// decision about one address is not an answer to a request about another.
|
|
3191
|
+
if (askedAddress && acknowledgementsFor(askedAddress) !== acknowledgementsOnEntry) {
|
|
3192
|
+
cancelled('address-unavailable-acknowledged');
|
|
3193
|
+
return;
|
|
3194
|
+
}
|
|
3195
|
+
|
|
2252
3196
|
if (stepsInProgress.includes(connection.step)) {
|
|
2253
3197
|
// still going, nothing to decide yet
|
|
2254
3198
|
attemptStarted = true;
|
|
@@ -2261,22 +3205,93 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
2261
3205
|
// a generic cancellation.
|
|
2262
3206
|
const error = connection.error;
|
|
2263
3207
|
if (error && error !== errorOnEntry) {
|
|
2264
|
-
|
|
3208
|
+
// The reason is COPIED, never re-derived. Deriving it again here from `message` or from
|
|
3209
|
+
// `cause` is how the state an app renders and the error a caller catches come to disagree
|
|
3210
|
+
// about one event: they are the same failure, so they carry the same label by construction.
|
|
3211
|
+
failWith(error.reason, error.message, error.cause);
|
|
2265
3212
|
return;
|
|
2266
3213
|
}
|
|
2267
3214
|
|
|
2268
3215
|
// Reject on disconnect/back to Idle
|
|
2269
3216
|
if (connection.step === 'Idle' && idlePassed) {
|
|
2270
|
-
|
|
3217
|
+
cancelled('cancelled');
|
|
2271
3218
|
return;
|
|
2272
3219
|
}
|
|
2273
3220
|
|
|
2274
3221
|
// The attempt went back to a resting step without an error: it was aborted (back/cancel).
|
|
2275
3222
|
// This must never trigger on a resting step we merely started from, hence `attemptStarted`.
|
|
2276
3223
|
if (attemptStarted && stepsAtRest.includes(connection.step)) {
|
|
2277
|
-
|
|
3224
|
+
cancelled('cancelled');
|
|
3225
|
+
return;
|
|
2278
3226
|
}
|
|
2279
|
-
|
|
3227
|
+
|
|
3228
|
+
// THE WALLET IS NOT ON THE ACCOUNT THIS CALL ASKED FOR, and the connection is resting on a
|
|
3229
|
+
// state that says so. That is the app's to render and the user's to answer, so nothing is
|
|
3230
|
+
// attempted while it stands: re-attempting would prompt them again for the account they are
|
|
3231
|
+
// being asked to switch to.
|
|
3232
|
+
//
|
|
3233
|
+
// The moment the wallet DOES offer it, this stops applying and the ordinary rule below picks
|
|
3234
|
+
// the request back up, which is what carries the user through without a click in the app.
|
|
3235
|
+
const unavailable = connection.addressUnavailable;
|
|
3236
|
+
if (
|
|
3237
|
+
askedAddress &&
|
|
3238
|
+
unavailable?.requested.toLowerCase() === askedAddress &&
|
|
3239
|
+
!(connection.wallet?.accounts ?? []).some((account) => account.toLowerCase() === askedAddress)
|
|
3240
|
+
) {
|
|
3241
|
+
return;
|
|
3242
|
+
}
|
|
3243
|
+
|
|
3244
|
+
// A REQUIREMENT THE CALLER NAMED IS UNMET, and no attempt has been made from this state.
|
|
3245
|
+
//
|
|
3246
|
+
// Re-initiating here, and only here, is the fix for an answer that depended on timing: a
|
|
3247
|
+
// call made while some OTHER flow was in progress (an account picker the user was part-way
|
|
3248
|
+
// through, say) used to get "nothing is in progress" the moment that flow ended on the wrong
|
|
3249
|
+
// account, while the identical call one tick later initiated and succeeded.
|
|
3250
|
+
//
|
|
3251
|
+
// Deliberately NOT extended to an unmet STEP. A connection that comes to rest below the
|
|
3252
|
+
// target has chosen to rest there and the app renders that (a `WalletConnected` state under
|
|
3253
|
+
// a `SignedIn` target is waiting for the app's own sign-in button), and re-running `connect`
|
|
3254
|
+
// from a state that names no wallet opens the picker — which is `connect`'s meaning, and
|
|
3255
|
+
// nobody's idea of what a promise-shaped call should do behind their back.
|
|
3256
|
+
if (!walletNameMatches(connection) || (askedAddress && !canActAs(connection, askedAddress))) {
|
|
3257
|
+
if (initiateIfWorthwhile(connection, scheduleAttempt)) {
|
|
3258
|
+
return;
|
|
3259
|
+
}
|
|
3260
|
+
}
|
|
3261
|
+
|
|
3262
|
+
// NOTHING IS IN PROGRESS AND NOTHING CAN BE INITIATED: that is an answer, and it is
|
|
3263
|
+
// delivered rather than awaited. Silently waiting here is the failure this guard exists to
|
|
3264
|
+
// make impossible, and it is stated as a POSITIVE list (`awaitingUserReason`) on purpose:
|
|
3265
|
+
// a new step, or a new resting reason, is unreachable-by-default rather than a fresh way
|
|
3266
|
+
// to hang.
|
|
3267
|
+
const waitReason = awaitingUserReason(connection);
|
|
3268
|
+
if (!waitReason) {
|
|
3269
|
+
// The message names where the connection actually is, including the wallet's status,
|
|
3270
|
+
// because the likeliest way to arrive here is a wallet that went locked or was revoked
|
|
3271
|
+
// between the attempt finishing and this state being published.
|
|
3272
|
+
const wallet = connection.wallet ? ` (wallet ${connection.wallet.status})` : '';
|
|
3273
|
+
// SUPERSEDED, when a NEWER address-bound call is holding the connection's one account
|
|
3274
|
+
// slot: this call did not come to rest because the connection cannot get there, it came to
|
|
3275
|
+
// rest because the app itself asked for a different account in the meantime. The two are
|
|
3276
|
+
// indistinguishable from the state (the newer request took the `addressUnavailable` slot
|
|
3277
|
+
// with it, so there is nothing left on the connection to read), and telling them apart is
|
|
3278
|
+
// the difference between "this connection is stuck" and "retry, it was your own doing".
|
|
3279
|
+
//
|
|
3280
|
+
// The MESSAGE is unchanged, deliberately: it is the honest `could not reach ...` this path
|
|
3281
|
+
// has always produced, and specifically not a cancellation, because the user decided
|
|
3282
|
+
// nothing.
|
|
3283
|
+
const superseded =
|
|
3284
|
+
askedAddress !== undefined &&
|
|
3285
|
+
addressBoundRequestId !== undefined &&
|
|
3286
|
+
isSupersededBy(addressBoundRequestId, askedAddress);
|
|
3287
|
+
failWith(
|
|
3288
|
+
superseded ? 'superseded' : 'unreachable',
|
|
3289
|
+
`could not reach ${step}: the connection is at ${connection.step}${wallet} and nothing is in progress`,
|
|
3290
|
+
);
|
|
3291
|
+
}
|
|
3292
|
+
};
|
|
3293
|
+
|
|
3294
|
+
unsubscribe = _store.subscribe(evaluate);
|
|
2280
3295
|
if (settled) {
|
|
2281
3296
|
unsubscribe();
|
|
2282
3297
|
}
|
|
@@ -2331,7 +3346,7 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
2331
3346
|
// through it) and report the error on the CURRENT state — throwing the choice away
|
|
2332
3347
|
// over a typo or a wallet uninstalled between render and click would deselect the
|
|
2333
3348
|
// user's read path without them refusing anything.
|
|
2334
|
-
setError({message: `failed to get wallet ${walletName}
|
|
3349
|
+
setError({message: `failed to get wallet ${walletName}`, reason: 'failed'});
|
|
2335
3350
|
return;
|
|
2336
3351
|
}
|
|
2337
3352
|
// Clear old wallet watchers if switching from a previously chosen/connected wallet.
|
|
@@ -2375,7 +3390,7 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
2375
3390
|
// setConnectionFailure tears down the previously chosen wallet (provider still on
|
|
2376
3391
|
// the wrapper if the new wallet's getChainId threw before setWalletProvider) before
|
|
2377
3392
|
// landing on its `wallet: undefined` resting step.
|
|
2378
|
-
setConnectionFailure({message: `failed to select wallet ${walletName}`, cause: err});
|
|
3393
|
+
setConnectionFailure({message: `failed to select wallet ${walletName}`, cause: err, reason: reasonForError(err)});
|
|
2379
3394
|
}
|
|
2380
3395
|
}
|
|
2381
3396
|
|
|
@@ -2692,7 +3707,7 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
2692
3707
|
//
|
|
2693
3708
|
// `error` is omitted rather than set to `undefined` when there is none, so a successful
|
|
2694
3709
|
// switch does not silently clear an unrelated error the app has not shown yet.
|
|
2695
|
-
const doneAsking = (error?:
|
|
3710
|
+
const doneAsking = (error?: ConnectionError) => {
|
|
2696
3711
|
if ($connection.wallet) {
|
|
2697
3712
|
set({
|
|
2698
3713
|
...$connection,
|
|
@@ -2729,7 +3744,7 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
2729
3744
|
// this library's summary and the branch is reached both from a refusal to switch and
|
|
2730
3745
|
// from a wallet reporting its error as a result.
|
|
2731
3746
|
const message = `Chain "${named}" is not available on your wallet`;
|
|
2732
|
-
doneAsking({message, cause: err});
|
|
3747
|
+
doneAsking({message, cause: err, reason: reasonForError(err)});
|
|
2733
3748
|
throw new Error(message);
|
|
2734
3749
|
}
|
|
2735
3750
|
}
|
|
@@ -2756,34 +3771,17 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
2756
3771
|
return;
|
|
2757
3772
|
}
|
|
2758
3773
|
const message = `Failed to add new chain: ${named}`;
|
|
2759
|
-
doneAsking({message, cause: err});
|
|
3774
|
+
doneAsking({message, cause: err, reason: reasonForError(err)});
|
|
2760
3775
|
throw err;
|
|
2761
3776
|
}
|
|
2762
3777
|
}
|
|
2763
3778
|
|
|
2764
3779
|
// Method on the store to check if target step is reached
|
|
2765
3780
|
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';
|
|
3781
|
+
// The same ordered comparison the exported `isTargetStepReached` makes, against this store's
|
|
3782
|
+
// configured target. `walletOnly` only bites on a `SignedIn` target: the lower two are
|
|
3783
|
+
// wallet-bound by definition.
|
|
3784
|
+
return stepIsAtOrBeyond(connection, targetStep, {requireWallet: walletOnly});
|
|
2787
3785
|
}
|
|
2788
3786
|
|
|
2789
3787
|
const store = {
|
|
@@ -2801,6 +3799,8 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
|
|
|
2801
3799
|
switchWalletChain,
|
|
2802
3800
|
unlock,
|
|
2803
3801
|
ensureConnected: ensureConnected as any, // Cast to bypass complex conditional typing
|
|
3802
|
+
acknowledgeAddressUnavailable,
|
|
3803
|
+
canActAs: (address: `0x${string}`) => canActAs($connection, address),
|
|
2804
3804
|
isTargetStepReached: storeIsTargetStepReached as any, // Cast for type guard
|
|
2805
3805
|
targetStep,
|
|
2806
3806
|
walletOnly,
|