@etherplay/connect 0.11.1 → 0.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +150 -4
- package/dist/index.d.ts +89 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +731 -213
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/src/index.ts +929 -238
package/dist/index.js
CHANGED
|
@@ -8,30 +8,107 @@ export { fromEntropyKeyToMnemonic, originPublicKeyPublicationMessage, originKeyM
|
|
|
8
8
|
// digest, the ABI of the contract that verifies it, and the lookup that picks the credential for
|
|
9
9
|
// a (chainId, contract) pair out of `savedDelegations`.
|
|
10
10
|
delegationMessage, delegationDigest, DELEGATION_ABI, findSavedDelegation, };
|
|
11
|
+
// THE TARGET STEPS ARE ORDERED, and this array is the only place that says so.
|
|
12
|
+
//
|
|
13
|
+
// `SignedIn` implies `WalletConnected` implies `WalletChosen`, so "has this connection reached the
|
|
14
|
+
// target" is a comparison on this array rather than a hand-written comparison per step. It used to
|
|
15
|
+
// be written out three times, and one of the three (`ensureConnected`'s own `canResolve`) got the
|
|
16
|
+
// order right for `WalletChosen` and then compared the other two exactly, which did not answer
|
|
17
|
+
// wrong so much as never answer at all: a connection resting at `SignedIn` and asked for
|
|
18
|
+
// `WalletConnected` satisfied nothing, initiated nothing, and waited forever.
|
|
19
|
+
//
|
|
20
|
+
// A fourth step added to `TargetStep` lands here once, in order, and every satisfaction check
|
|
21
|
+
// follows.
|
|
22
|
+
const orderedTargetSteps = ['WalletChosen', 'WalletConnected', 'SignedIn'];
|
|
23
|
+
/**
|
|
24
|
+
* Is the connection AT OR BEYOND the target step?
|
|
25
|
+
*
|
|
26
|
+
* `requireWallet` is for the one case the order does not capture: `SignedIn` is the only target
|
|
27
|
+
* step reachable without a wallet (the hosted email/oauth/mnemonic mechanisms), so a wallet target
|
|
28
|
+
* is never satisfied by a state that has none, and a `SignedIn` target is only wallet-bound when
|
|
29
|
+
* the caller says so.
|
|
30
|
+
*/
|
|
31
|
+
function stepIsAtOrBeyond(connection, target, options) {
|
|
32
|
+
const reached = orderedTargetSteps.indexOf(connection.step);
|
|
33
|
+
if (reached === -1) {
|
|
34
|
+
// An in-progress or picker step is not a resting point at any target.
|
|
35
|
+
return false;
|
|
36
|
+
}
|
|
37
|
+
if (reached < orderedTargetSteps.indexOf(target)) {
|
|
38
|
+
return false;
|
|
39
|
+
}
|
|
40
|
+
if ((target !== 'SignedIn' || options?.requireWallet) && connection.wallet === undefined) {
|
|
41
|
+
return false;
|
|
42
|
+
}
|
|
43
|
+
return true;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* The resting reason, built in ONE place.
|
|
47
|
+
*
|
|
48
|
+
* Two sites produce it: the attempt that discovers the address is not on offer, and the account
|
|
49
|
+
* handler that keeps it true afterwards. They must word it identically, and a sentence written
|
|
50
|
+
* twice is a sentence that will disagree once.
|
|
51
|
+
*/
|
|
52
|
+
function describeAddressUnavailable(details) {
|
|
53
|
+
const named = details.walletName ? `Wallet "${details.walletName}"` : 'The wallet';
|
|
54
|
+
return {
|
|
55
|
+
...details,
|
|
56
|
+
message: details.selected
|
|
57
|
+
? `${named} is on ${details.selected} and cannot act as ${details.requested}. Switch to that account in the wallet, or cancel.`
|
|
58
|
+
: `${named} is not offering ${details.requested}. Select that account in the wallet, or cancel.`,
|
|
59
|
+
};
|
|
60
|
+
}
|
|
11
61
|
// Type guard - narrows Connection based on targetStep and walletOnly
|
|
12
62
|
// For 'WalletChosen' target: narrows to ChosenOrBetter (WalletChosen | WalletConnected | SignedIn-with-wallet)
|
|
13
63
|
// For 'WalletConnected' target: narrows to ConnectedWithWallet (WalletConnected | SignedIn-with-wallet)
|
|
14
64
|
// For 'SignedIn' target with walletOnly: narrows to SignedInWithWallet
|
|
15
65
|
// For 'SignedIn' target (default): narrows to SignedIn
|
|
16
66
|
export function isTargetStepReached(connection, targetStep, walletOnly) {
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
67
|
+
// One ordered comparison, shared with the store's own `isTargetStepReached` and with
|
|
68
|
+
// `ensureConnected`. `walletOnly` narrows the RETURN TYPE and, for a `SignedIn` target, also the
|
|
69
|
+
// check: a hosted sign-in has no wallet to act through.
|
|
70
|
+
return stepIsAtOrBeyond(connection, targetStep, { requireWallet: !!walletOnly });
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Can this connection sign as `address` RIGHT NOW, with no flow initiated and nothing prompted?
|
|
74
|
+
*
|
|
75
|
+
* The question `connection.account.address` does not answer. That field is the address the
|
|
76
|
+
* connection AGREED ON, which is the right thing for it to be: it survives the user locking their
|
|
77
|
+
* wallet, revoking the site, or switching account behind the connection's back, all of which keep
|
|
78
|
+
* `step: 'WalletConnected'` and change nothing about who was agreed on. What they change is whether
|
|
79
|
+
* anybody can sign, and that is what this reads (`wallet.status`, and the accounts the wallet is
|
|
80
|
+
* actually offering).
|
|
81
|
+
*
|
|
82
|
+
* It exists because a consumer needed it, wrote the comparison itself against `account.address`,
|
|
83
|
+
* and got a locked wallet wrong: it skipped its `ensureConnected` call, let the transaction out,
|
|
84
|
+
* and reported the provider's `{code: 4001}` as "transaction rejected by user" about a prompt
|
|
85
|
+
* nobody was ever shown. Use this to RENDER readiness (enable a button, show "unlock to pay"), and
|
|
86
|
+
* `ensureConnected(step, {type: 'wallet', address})` to actually reach it.
|
|
87
|
+
*
|
|
88
|
+
* Chain is deliberately not part of the answer: signing as an address is chain-independent, and
|
|
89
|
+
* `wallet.invalidChainId` is the separate question with its own separate remedy.
|
|
90
|
+
*/
|
|
91
|
+
export function canActAs(connection, address) {
|
|
92
|
+
const wanted = address.toLowerCase();
|
|
93
|
+
if (!connection.wallet || connection.wallet.status !== 'connected') {
|
|
94
|
+
return false;
|
|
22
95
|
}
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
return
|
|
96
|
+
const agreedOn = 'account' in connection ? connection.account?.address : undefined;
|
|
97
|
+
if (!agreedOn || agreedOn.toLowerCase() !== wanted) {
|
|
98
|
+
return false;
|
|
26
99
|
}
|
|
27
|
-
|
|
28
|
-
//
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
100
|
+
const offered = connection.wallet.accounts;
|
|
101
|
+
// An empty list is what a wallet that was never asked reports, not a denial; `status` is the
|
|
102
|
+
// authority there. A non-empty one that does not contain the address IS a denial.
|
|
103
|
+
//
|
|
104
|
+
// Defensive, and marked as such: no state this library builds reaches here with an empty list
|
|
105
|
+
// (the states that have one, like `WalletChosen`, carry no `account` and are answered above). It
|
|
106
|
+
// is kept for a custom connector that publishes `connected` before it has read any accounts, and
|
|
107
|
+
// it is deliberately not counted as covered by any test.
|
|
108
|
+
if (offered.length > 0 && !offered.some((account) => account.toLowerCase() === wanted)) {
|
|
109
|
+
return false;
|
|
32
110
|
}
|
|
33
|
-
|
|
34
|
-
return connection.step === 'SignedIn';
|
|
111
|
+
return true;
|
|
35
112
|
}
|
|
36
113
|
function viemChainInfoToSwitchChainInfo(chainInfo) {
|
|
37
114
|
return {
|
|
@@ -176,6 +253,11 @@ export function createConnection(settings) {
|
|
|
176
253
|
if (!connection.wallet && connection.step !== 'WaitingForWalletConnection') {
|
|
177
254
|
teardownWallet();
|
|
178
255
|
}
|
|
256
|
+
// The address a resting reason last named, kept so a dismissal can be attributed to the request
|
|
257
|
+
// the user was looking at even if an attempt clears the field a moment before they click.
|
|
258
|
+
if (connection.addressUnavailable) {
|
|
259
|
+
lastPublishedAddressUnavailable = connection.addressUnavailable.requested;
|
|
260
|
+
}
|
|
179
261
|
const pendingRequests = currentPendingRequests();
|
|
180
262
|
if (!connection.wallet) {
|
|
181
263
|
$connection = { ...connection, pendingRequests };
|
|
@@ -268,6 +350,69 @@ export function createConnection(settings) {
|
|
|
268
350
|
});
|
|
269
351
|
}
|
|
270
352
|
}
|
|
353
|
+
/**
|
|
354
|
+
* The user has read "your wallet is not on that account" and chosen not to switch.
|
|
355
|
+
*
|
|
356
|
+
* THAT IS A CANCELLATION, and it settles the pending `ensureConnected` as one: the same
|
|
357
|
+
* `ConnectionFailure('Connection cancelled')` a `cancel()` or a `back()` produces, so an app that
|
|
358
|
+
* already maps a refusal to "the user chose not to" needs no new branch and shows no red error
|
|
359
|
+
* for a decision.
|
|
360
|
+
*
|
|
361
|
+
* The connection itself is left exactly as it is, deliberately. It is CONNECTED, on the account
|
|
362
|
+
* the wallet is actually offering, and "connected as somebody else, and saying so" is a better
|
|
363
|
+
* place to leave a user than "not connected at all" — which is what the alternative, failing the
|
|
364
|
+
* attempt, produced: every failure state carries `wallet: undefined`.
|
|
365
|
+
*/
|
|
366
|
+
function acknowledgeAddressUnavailable() {
|
|
367
|
+
// WHICH request the user dismissed: the one on screen, or the one that was on screen a moment
|
|
368
|
+
// ago if an attempt has just cleared the field out from under them.
|
|
369
|
+
const dismissed = $connection.addressUnavailable?.requested ?? lastPublishedAddressUnavailable;
|
|
370
|
+
if (dismissed) {
|
|
371
|
+
const key = dismissed.toLowerCase();
|
|
372
|
+
addressUnavailableAcknowledgements.set(key, (addressUnavailableAcknowledgements.get(key) ?? 0) + 1);
|
|
373
|
+
}
|
|
374
|
+
// COUNTED, not inferred. A pending `ensureConnected` used to read the reason DISAPPEARING as
|
|
375
|
+
// the dismissal, which is true of this method and of nothing else — and plenty else clears it:
|
|
376
|
+
// the app calling `connect()` itself, a `useCurrentAccount` store following the wallet onto
|
|
377
|
+
// another account, the reason ceasing to be true. Each of those was reported to the caller as
|
|
378
|
+
// `Connection cancelled`, which consumers are told to treat as "the user chose not to", so an
|
|
379
|
+
// event the user never caused was invisible to them.
|
|
380
|
+
//
|
|
381
|
+
// Republished even when the field is already gone (an attempt may have cleared it a moment
|
|
382
|
+
// ago): the publish is what wakes a pending `ensureConnected` to notice the dismissal. Without
|
|
383
|
+
// it, a click landing in that window is counted and then never acted on, which is a wait that
|
|
384
|
+
// nothing ends.
|
|
385
|
+
set({
|
|
386
|
+
...$connection,
|
|
387
|
+
addressUnavailable: undefined,
|
|
388
|
+
});
|
|
389
|
+
}
|
|
390
|
+
// Dismissals of "your wallet is not on that account", COUNTED PER ADDRESS. See
|
|
391
|
+
// `acknowledgeAddressUnavailable`: a pending `ensureConnected` watches the count for the address
|
|
392
|
+
// IT asked about, so that a decision is told apart both from the several other things that clear
|
|
393
|
+
// the same field and from a decision about somebody else's request. A single global count made
|
|
394
|
+
// one dismissal cancel every address-bound call on the connection, including one whose wallet
|
|
395
|
+
// prompt was open at that moment.
|
|
396
|
+
const addressUnavailableAcknowledgements = new Map();
|
|
397
|
+
function acknowledgementsFor(address) {
|
|
398
|
+
return addressUnavailableAcknowledgements.get(address.toLowerCase()) ?? 0;
|
|
399
|
+
}
|
|
400
|
+
// The reason most recently PUBLISHED, so that a dismissal arriving in the brief window where an
|
|
401
|
+
// attempt has cleared the field still names the address the user was actually looking at.
|
|
402
|
+
let lastPublishedAddressUnavailable;
|
|
403
|
+
// How many times the user's WALLET has announced a DIFFERENT set of accounts. It is the unit
|
|
404
|
+
// `ensureConnected` retries on, and it is the honest one: a retry is a response to the user
|
|
405
|
+
// having done something in their wallet, so at most one attempt per announcement bounds the work
|
|
406
|
+
// while never refusing to act on a real gesture. Counting distinct STATES instead looks stricter
|
|
407
|
+
// and refuses the retry when the user returns to a state seen before, which is a normal thing for
|
|
408
|
+
// a person to do.
|
|
409
|
+
//
|
|
410
|
+
// Only a CHANGE counts, and only an account one. The lock poll re-announces an empty list every
|
|
411
|
+
// second, which is the absence of news rather than news, and would otherwise re-license an attempt
|
|
412
|
+
// per second on a locked wallet; a chain change is news, but not news about accounts, and
|
|
413
|
+
// re-prompting for an account because the user switched network answers a question they did not
|
|
414
|
+
// ask.
|
|
415
|
+
let walletAnnouncements = 0;
|
|
271
416
|
let _wallet;
|
|
272
417
|
let popup;
|
|
273
418
|
// Wallet announcements are not guaranteed to be unique.
|
|
@@ -708,12 +853,32 @@ export function createConnection(settings) {
|
|
|
708
853
|
// TODO lastAccount
|
|
709
854
|
// console.log('account changed', accounts);
|
|
710
855
|
const accountsFormated = accounts.map((a) => a.toLowerCase());
|
|
856
|
+
// NEWS is an announcement that differs from what the connection currently believes — not one
|
|
857
|
+
// that differs from the previous announcement. The two come apart exactly where it matters: an
|
|
858
|
+
// attempt can go and find something else in between, so a wallet announcing the same list twice
|
|
859
|
+
// with a contradicting answer in the middle is telling us something the second time too.
|
|
860
|
+
if (accountsFormated.join(',') !== ($connection.wallet?.accounts ?? []).join(',')) {
|
|
861
|
+
walletAnnouncements++;
|
|
862
|
+
}
|
|
863
|
+
// A RESTING "your wallet is not on that account" MUST KEEP DESCRIBING THE WALLET AS IT IS.
|
|
864
|
+
//
|
|
865
|
+
// Every `set` below rebuilds the state by spreading the current one, so the reason would
|
|
866
|
+
// survive an account change untouched: right about the FACT (the wallet still cannot act as
|
|
867
|
+
// the requested account) and wrong about the DETAIL, since it would go on naming an account
|
|
868
|
+
// the user has already left, and the app renders that sentence as the instruction. Telling
|
|
869
|
+
// somebody to switch away from an account they are not on is worse than saying nothing.
|
|
870
|
+
//
|
|
871
|
+
// Computed here and published WITH the accounts rather than corrected afterwards, so that no
|
|
872
|
+
// intermediate state is ever published in which the two disagree — a correction one publish
|
|
873
|
+
// later is a frame of wrong instruction, which is exactly what an app renders.
|
|
874
|
+
const addressUnavailable = refreshedAddressUnavailable(accountsFormated);
|
|
711
875
|
if ($connection.wallet) {
|
|
712
876
|
const locked = accountsFormated.length == 0;
|
|
713
877
|
const addressSignedIn = $connection.mechanism.address;
|
|
714
878
|
if (locked) {
|
|
715
879
|
set({
|
|
716
880
|
...$connection,
|
|
881
|
+
addressUnavailable,
|
|
717
882
|
wallet: {
|
|
718
883
|
...$connection.wallet,
|
|
719
884
|
status: 'locked',
|
|
@@ -727,6 +892,7 @@ export function createConnection(settings) {
|
|
|
727
892
|
if (disconnected) {
|
|
728
893
|
set({
|
|
729
894
|
...$connection,
|
|
895
|
+
addressUnavailable,
|
|
730
896
|
wallet: {
|
|
731
897
|
...$connection.wallet,
|
|
732
898
|
status: 'disconnected',
|
|
@@ -738,6 +904,7 @@ export function createConnection(settings) {
|
|
|
738
904
|
else {
|
|
739
905
|
set({
|
|
740
906
|
...$connection,
|
|
907
|
+
addressUnavailable,
|
|
741
908
|
wallet: {
|
|
742
909
|
...$connection.wallet,
|
|
743
910
|
status: 'connected',
|
|
@@ -755,6 +922,7 @@ export function createConnection(settings) {
|
|
|
755
922
|
else {
|
|
756
923
|
set({
|
|
757
924
|
...$connection,
|
|
925
|
+
addressUnavailable,
|
|
758
926
|
wallet: {
|
|
759
927
|
...$connection.wallet,
|
|
760
928
|
accountChanged: accountsFormated[0],
|
|
@@ -766,6 +934,7 @@ export function createConnection(settings) {
|
|
|
766
934
|
else {
|
|
767
935
|
set({
|
|
768
936
|
...$connection,
|
|
937
|
+
addressUnavailable,
|
|
769
938
|
wallet: {
|
|
770
939
|
...$connection.wallet,
|
|
771
940
|
accountChanged: undefined,
|
|
@@ -775,6 +944,32 @@ export function createConnection(settings) {
|
|
|
775
944
|
}
|
|
776
945
|
}
|
|
777
946
|
}
|
|
947
|
+
/**
|
|
948
|
+
* The resting reason, re-derived against what the wallet is offering now.
|
|
949
|
+
*
|
|
950
|
+
* `undefined` once the wallet DOES offer the requested account: the reason has simply stopped
|
|
951
|
+
* being true. A pending `ensureConnected` loses nothing by that — it watches the accounts the
|
|
952
|
+
* wallet offers rather than this field, precisely so that the state going away because the user
|
|
953
|
+
* fixed it cannot be mistaken for the user dismissing it.
|
|
954
|
+
*/
|
|
955
|
+
function refreshedAddressUnavailable(offered) {
|
|
956
|
+
const unavailable = $connection.addressUnavailable;
|
|
957
|
+
if (!unavailable) {
|
|
958
|
+
return undefined;
|
|
959
|
+
}
|
|
960
|
+
if (offered.some((account) => account.toLowerCase() === unavailable.requested.toLowerCase())) {
|
|
961
|
+
return undefined;
|
|
962
|
+
}
|
|
963
|
+
if (offered.join(',') === unavailable.available.join(',')) {
|
|
964
|
+
return unavailable;
|
|
965
|
+
}
|
|
966
|
+
return describeAddressUnavailable({
|
|
967
|
+
requested: unavailable.requested,
|
|
968
|
+
walletName: unavailable.walletName,
|
|
969
|
+
selected: offered[0],
|
|
970
|
+
available: offered,
|
|
971
|
+
});
|
|
972
|
+
}
|
|
778
973
|
// TODO lastAccounts
|
|
779
974
|
let lockCheckInterval;
|
|
780
975
|
async function checkLockStatus() {
|
|
@@ -914,10 +1109,21 @@ export function createConnection(settings) {
|
|
|
914
1109
|
}
|
|
915
1110
|
let remember = false;
|
|
916
1111
|
/**
|
|
917
|
-
* @param internal not part of the public `connect` surface.
|
|
918
|
-
*
|
|
919
|
-
*
|
|
920
|
-
* `
|
|
1112
|
+
* @param internal not part of the public `connect` surface. THREE things an address can mean,
|
|
1113
|
+
* and they are told apart here rather than by inspecting the caller:
|
|
1114
|
+
*
|
|
1115
|
+
* - nothing set: a DEMAND. `connectToAddress(a)` and `connect({type: 'wallet', address: a})` mean
|
|
1116
|
+
* that account and no other, so a wallet that cannot offer it fails the attempt.
|
|
1117
|
+
* - `addressIsPreference`: a mechanism this library REPLAYED from the current state rather than
|
|
1118
|
+
* one anybody asked for, so a vanished address degrades to an ordinary connect.
|
|
1119
|
+
* - `reportUnavailableAddress`: a demand the caller wants REPORTED rather than thrown, which is
|
|
1120
|
+
* what `ensureConnected` asks for. Failing the attempt tears the wallet down (every failure
|
|
1121
|
+
* state carries `wallet: undefined`), which is the worst of the three endings: the user is left
|
|
1122
|
+
* with no wallet at all over a wallet that is working and merely on another account. So the
|
|
1123
|
+
* attempt completes on what the wallet does offer and comes to rest carrying
|
|
1124
|
+
* `addressUnavailable`, which is a state the app can render and the user can answer.
|
|
1125
|
+
*
|
|
1126
|
+
* See `resolveRequestedAddress` below.
|
|
921
1127
|
*/
|
|
922
1128
|
async function connect(mechanism, options, internal) {
|
|
923
1129
|
if (!mechanism && (targetStep === 'WalletConnected' || walletOnly)) {
|
|
@@ -933,7 +1139,14 @@ export function createConnection(settings) {
|
|
|
933
1139
|
// different wallet.
|
|
934
1140
|
const chosenMechanismBeforeConnect = $connection.step === 'WalletChosen' ? $connection.mechanism : undefined;
|
|
935
1141
|
const chosenWalletBeforeConnect = $connection.step === 'WalletChosen' ? _wallet : undefined;
|
|
936
|
-
|
|
1142
|
+
// LOWERCASED HERE, at the boundary, because everything downstream compares against the
|
|
1143
|
+
// wallet's accounts, which are lowercased on arrival. A checksummed address (what a viem
|
|
1144
|
+
// local account hands back, so a perfectly ordinary thing for a caller to be holding) would
|
|
1145
|
+
// otherwise fail to match a wallet that is holding that very account. It was a latent
|
|
1146
|
+
// papercut while an unmatched address merely failed the attempt; now that a caller's address
|
|
1147
|
+
// is a requirement, it would send the user an instruction to switch to the account they are
|
|
1148
|
+
// already on.
|
|
1149
|
+
const specificAddress = mechanism.address?.toLowerCase();
|
|
937
1150
|
// WHICH ACCOUNT THE ATTEMPT IS FOR, once the wallet has said what it has.
|
|
938
1151
|
//
|
|
939
1152
|
// An address the CALLER named is a demand: `connectToAddress(a)` and
|
|
@@ -948,6 +1161,13 @@ export function createConnection(settings) {
|
|
|
948
1161
|
// threw, which landed in the catch and tore the wallet down: the reconnect performed the
|
|
949
1162
|
// very teardown it exists to prevent, one step later. Degrading to an ordinary connect is
|
|
950
1163
|
// what the caller asked for anyway, since it asked to be connected and named nothing.
|
|
1164
|
+
//
|
|
1165
|
+
// The third possibility is `reportUnavailableAddress`: the demand stands, but the answer is
|
|
1166
|
+
// a state rather than a failure. `unavailableAddress` is what records it, and it is read
|
|
1167
|
+
// twice below — once to keep the flow off `ChooseWalletAccount` (the caller named an
|
|
1168
|
+
// account; offering a picker instead of saying why they cannot have it is answering a
|
|
1169
|
+
// different question), and once to stamp `addressUnavailable` on the resting state.
|
|
1170
|
+
let unavailableAddress;
|
|
951
1171
|
const resolveRequestedAddress = (available) => {
|
|
952
1172
|
if (!specificAddress || available.includes(specificAddress)) {
|
|
953
1173
|
return specificAddress;
|
|
@@ -955,11 +1175,25 @@ export function createConnection(settings) {
|
|
|
955
1175
|
if (internal?.addressIsPreference) {
|
|
956
1176
|
return undefined;
|
|
957
1177
|
}
|
|
1178
|
+
if (internal?.reportUnavailableAddress) {
|
|
1179
|
+
unavailableAddress = specificAddress;
|
|
1180
|
+
return undefined;
|
|
1181
|
+
}
|
|
958
1182
|
throw new Error(`could not find address ${specificAddress}`);
|
|
959
1183
|
};
|
|
960
1184
|
const walletName = mechanism.name ||
|
|
961
1185
|
($connection.step === 'WalletChosen' ? $connection.mechanism.name : undefined) ||
|
|
962
1186
|
($connection.wallets.length == 1 ? $connection.wallets[0].info.name : undefined);
|
|
1187
|
+
/**
|
|
1188
|
+
* The resting reason to publish beside a connection that came back as somebody else.
|
|
1189
|
+
*
|
|
1190
|
+
* Everything the app needs to write the instruction is on it, including the accounts the
|
|
1191
|
+
* wallet IS offering: "switch account" is not actionable advice if the user cannot see
|
|
1192
|
+
* which account the wallet thinks it is on.
|
|
1193
|
+
*/
|
|
1194
|
+
const addressUnavailableFor = (available, selected) => unavailableAddress
|
|
1195
|
+
? describeAddressUnavailable({ requested: unavailableAddress, walletName, selected, available })
|
|
1196
|
+
: undefined;
|
|
963
1197
|
if (walletName) {
|
|
964
1198
|
const wallet = $connection.wallets.find((v) => v.info.name == walletName || v.info.uuid == walletName);
|
|
965
1199
|
if (wallet) {
|
|
@@ -1002,7 +1236,10 @@ export function createConnection(settings) {
|
|
|
1002
1236
|
accounts = accounts.map((v) => v.toLowerCase());
|
|
1003
1237
|
if (accounts.length > 0) {
|
|
1004
1238
|
const requestedAddress = resolveRequestedAddress(accounts);
|
|
1005
|
-
|
|
1239
|
+
// `!unavailableAddress`: the caller named an account and cannot have it. An account
|
|
1240
|
+
// picker would answer a question they did not ask; they get the wallet's current
|
|
1241
|
+
// account plus a resting reason naming every account it does offer.
|
|
1242
|
+
const nextStep = !settings?.useCurrentAccount && !requestedAddress && !unavailableAddress && accounts.length > 1
|
|
1006
1243
|
? 'ChooseWalletAccount'
|
|
1007
1244
|
: 'WalletConnected';
|
|
1008
1245
|
const account = requestedAddress || accounts[0];
|
|
@@ -1038,8 +1275,13 @@ export function createConnection(settings) {
|
|
|
1038
1275
|
switchingChain: false,
|
|
1039
1276
|
},
|
|
1040
1277
|
account: { address: account },
|
|
1278
|
+
addressUnavailable: addressUnavailableFor(accounts, account),
|
|
1041
1279
|
};
|
|
1280
|
+
// `!unavailableAddress`: do not raise a SIGNATURE prompt for an account the caller
|
|
1281
|
+
// did not ask to sign as. The instruction has to reach the user before anything
|
|
1282
|
+
// else asks them for something.
|
|
1042
1283
|
if (newState.step === 'WalletConnected' &&
|
|
1284
|
+
!unavailableAddress &&
|
|
1043
1285
|
(requestSignatureAutomaticallyIfPossible || options?.requestSignatureRightAway) &&
|
|
1044
1286
|
!options?.requireUserConfirmationBeforeSignatureRequest) {
|
|
1045
1287
|
watchForAccountChange(_wallet.provider);
|
|
@@ -1069,7 +1311,9 @@ export function createConnection(settings) {
|
|
|
1069
1311
|
else {
|
|
1070
1312
|
const requestedAddress = resolveRequestedAddress(accounts);
|
|
1071
1313
|
const account = requestedAddress || accounts[0];
|
|
1072
|
-
|
|
1314
|
+
// See the same expression on the requestAccounts branch above: a caller who named an
|
|
1315
|
+
// account gets a reason, not a picker.
|
|
1316
|
+
const nextStep = !settings?.useCurrentAccount && !requestedAddress && !unavailableAddress && accounts.length > 1
|
|
1073
1317
|
? 'ChooseWalletAccount'
|
|
1074
1318
|
: 'WalletConnected';
|
|
1075
1319
|
const newState = nextStep === 'ChooseWalletAccount'
|
|
@@ -1104,8 +1348,10 @@ export function createConnection(settings) {
|
|
|
1104
1348
|
switchingChain: false,
|
|
1105
1349
|
},
|
|
1106
1350
|
account: { address: account },
|
|
1351
|
+
addressUnavailable: addressUnavailableFor(accounts, account),
|
|
1107
1352
|
};
|
|
1108
1353
|
if (newState.step === 'WalletConnected' &&
|
|
1354
|
+
!unavailableAddress &&
|
|
1109
1355
|
(requestSignatureAutomaticallyIfPossible || options?.requestSignatureRightAway) &&
|
|
1110
1356
|
!options?.requireUserConfirmationBeforeSignatureRequest) {
|
|
1111
1357
|
set(newState);
|
|
@@ -1319,7 +1565,13 @@ export function createConnection(settings) {
|
|
|
1319
1565
|
}
|
|
1320
1566
|
else {
|
|
1321
1567
|
mechanism = undefined;
|
|
1322
|
-
|
|
1568
|
+
// `?? options`: the second argument may be an EXPLICIT `undefined` mechanism, which is what
|
|
1569
|
+
// a caller writes when it has options but nothing to name (`ensureConnected('SignedIn',
|
|
1570
|
+
// undefined, {requestSignatureRightAway: true})`, and any call passing a mechanism variable
|
|
1571
|
+
// that happens to be unset). Reading only the second argument silently dropped the third,
|
|
1572
|
+
// so the options were ignored and the call waited for something the caller had asked it to
|
|
1573
|
+
// do itself.
|
|
1574
|
+
opts = mechanismOrOptions ?? options;
|
|
1323
1575
|
}
|
|
1324
1576
|
}
|
|
1325
1577
|
else if (stepOrMechanismOrOptions && 'type' in stepOrMechanismOrOptions) {
|
|
@@ -1339,67 +1591,121 @@ export function createConnection(settings) {
|
|
|
1339
1591
|
mechanism = { type: 'wallet' };
|
|
1340
1592
|
}
|
|
1341
1593
|
const promise = new Promise((resolve, reject) => {
|
|
1594
|
+
// WHAT THE CALLER ASKED FOR, captured before `mechanism` can be reassigned below. An address
|
|
1595
|
+
// or a wallet name that arrives HERE came from the caller, so it is a requirement; anything
|
|
1596
|
+
// this library replays from the current state is a preference and never lands in these.
|
|
1597
|
+
const asked = mechanism && mechanism.type === 'wallet' ? mechanism : undefined;
|
|
1598
|
+
const askedWalletName = asked?.name;
|
|
1599
|
+
// Ignored for a `WalletChosen` target, and that is not an oversight: choosing a wallet never
|
|
1600
|
+
// asks it for accounts, so no state that target can reach could ever satisfy an address.
|
|
1601
|
+
// Requiring one there would guarantee the hang this rework exists to remove.
|
|
1602
|
+
const askedAddress = step === 'WalletChosen' ? undefined : asked?.address?.toLowerCase();
|
|
1342
1603
|
let forceConnect = false;
|
|
1343
1604
|
// Whether the mechanism below was REPLAYED from the current state rather than asked for.
|
|
1344
1605
|
let reconnecting = false;
|
|
1345
1606
|
// The error (if any) already sitting in the store before we start.
|
|
1346
1607
|
// Only an error that appears after this point tells us that *our* attempt failed.
|
|
1347
1608
|
const errorOnEntry = $connection.error;
|
|
1348
|
-
|
|
1349
|
-
const
|
|
1350
|
-
if (
|
|
1351
|
-
|
|
1352
|
-
return (connection.step === 'WalletChosen' ||
|
|
1353
|
-
connection.step === 'WalletConnected' ||
|
|
1354
|
-
(connection.step === 'SignedIn' && connection.wallet !== undefined));
|
|
1609
|
+
/** Is this connection on the wallet the caller named? Nothing named, nothing to check. */
|
|
1610
|
+
const walletNameMatches = (connection) => {
|
|
1611
|
+
if (!askedWalletName) {
|
|
1612
|
+
return true;
|
|
1355
1613
|
}
|
|
1356
|
-
|
|
1357
|
-
if (
|
|
1614
|
+
const current = 'mechanism' in connection ? connection.mechanism : undefined;
|
|
1615
|
+
if (current?.type !== 'wallet' || !current.name) {
|
|
1358
1616
|
return false;
|
|
1359
|
-
// For WalletConnected step, check chain validity unless skipped
|
|
1360
|
-
if (step === 'WalletConnected' && !opts?.skipChainCheck) {
|
|
1361
|
-
// connection.wallet should exist when step is WalletConnected
|
|
1362
|
-
if (connection.wallet?.invalidChainId) {
|
|
1363
|
-
return false; // Wrong chain, wait for chain change
|
|
1364
|
-
}
|
|
1365
1617
|
}
|
|
1366
|
-
|
|
1618
|
+
if (current.name === askedWalletName) {
|
|
1619
|
+
return true;
|
|
1620
|
+
}
|
|
1621
|
+
// A name may be an EIP-6963 uuid: that is what `connect` looks wallets up by too, so the
|
|
1622
|
+
// two spellings of the same wallet must not read as two different wallets here.
|
|
1623
|
+
const handle = connection.wallets.find((v) => v.info.name === askedWalletName || v.info.uuid === askedWalletName);
|
|
1624
|
+
return !!handle && (handle.info.name === current.name || handle.info.uuid === current.name);
|
|
1367
1625
|
};
|
|
1626
|
+
/**
|
|
1627
|
+
* The part of the target a connection ATTEMPT could fix: the step, the wallet, the account.
|
|
1628
|
+
*
|
|
1629
|
+
* Split from the chain check below because the two call for opposite responses. Reconnecting
|
|
1630
|
+
* moves the step and the account; it does not move the chain, so initiating an attempt over a
|
|
1631
|
+
* chain mismatch would prompt the user for nothing and rebuild a wallet that was fine.
|
|
1632
|
+
*/
|
|
1633
|
+
const targetReached = (connection) => stepIsAtOrBeyond(connection, step) &&
|
|
1634
|
+
walletNameMatches(connection) &&
|
|
1635
|
+
(!askedAddress || canActAs(connection, askedAddress)) &&
|
|
1636
|
+
// A `WalletConnected` connection whose wallet has gone locked or revoked is AT the step and
|
|
1637
|
+
// cannot act, so it does not satisfy a target that needs it to: that is the one and only
|
|
1638
|
+
// reason `ensureConnected` reconnects such a wallet where `connect()` would not (ADR-0002).
|
|
1639
|
+
// A `WalletChosen` target is exempt because it never needed accounts in the first place, and
|
|
1640
|
+
// `SignedIn` because a signed-in app acts through its session account, which a locked wallet
|
|
1641
|
+
// does not invalidate.
|
|
1642
|
+
(step === 'WalletChosen' || connection.step !== 'WalletConnected' || connection.wallet.status === 'connected');
|
|
1643
|
+
/** The part it could not: only the user, or their wallet, moves the chain. */
|
|
1644
|
+
const chainIsRight = (connection) => step !== 'WalletConnected' || !!opts?.skipChainCheck || !connection.wallet?.invalidChainId;
|
|
1645
|
+
const canResolve = (connection) => targetReached(connection) && chainIsRight(connection);
|
|
1368
1646
|
const reconnect = mechanismToReconnect();
|
|
1369
|
-
if (reconnect) {
|
|
1370
|
-
// we reuse existing mechanism as we just want to reconnect
|
|
1371
|
-
forceConnect = true;
|
|
1372
|
-
mechanism = reconnect;
|
|
1373
|
-
// ...but its ADDRESS is only a preference, because the user may unlock on another
|
|
1374
|
-
// account, and a replayed address is not something the caller asked for.
|
|
1375
|
-
reconnecting = true;
|
|
1376
|
-
}
|
|
1377
|
-
else if (canResolve($connection)) {
|
|
1378
|
-
// Only resolve if step matches AND chain is valid (or skipChainCheck)
|
|
1647
|
+
if (!reconnect && canResolve($connection)) {
|
|
1379
1648
|
resolve($connection);
|
|
1380
1649
|
return;
|
|
1381
1650
|
}
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
|
|
1393
|
-
|
|
1394
|
-
|
|
1651
|
+
if (reconnect) {
|
|
1652
|
+
// A locked or revoked wallet: reconnecting it is the only way to hand back something usable.
|
|
1653
|
+
forceConnect = true;
|
|
1654
|
+
if (askedAddress) {
|
|
1655
|
+
// The replayed mechanism MUST NOT overrule what the caller named. Substituting the stored
|
|
1656
|
+
// address here is precisely how a caller's requirement used to become somebody else's
|
|
1657
|
+
// account: the reconnect would come back on the stored one and the caller's address was
|
|
1658
|
+
// never looked at again. The wallet name is still worth reusing, since it is the wallet
|
|
1659
|
+
// this connection is on and the caller usually did not name one.
|
|
1660
|
+
mechanism = { type: 'wallet', name: askedWalletName || reconnect.name, address: askedAddress };
|
|
1661
|
+
}
|
|
1662
|
+
else if (askedWalletName && askedWalletName !== reconnect.name) {
|
|
1663
|
+
// A different wallet was named: replaying THIS wallet's account would demand an address
|
|
1664
|
+
// from a wallet that has no reason to have it.
|
|
1665
|
+
mechanism = { type: 'wallet', name: askedWalletName };
|
|
1395
1666
|
}
|
|
1396
1667
|
else {
|
|
1397
|
-
|
|
1668
|
+
mechanism = reconnect;
|
|
1669
|
+
// ...and its ADDRESS is only a preference, because the user may unlock on another
|
|
1670
|
+
// account, and a replayed address is not something the caller asked for.
|
|
1671
|
+
reconnecting = true;
|
|
1398
1672
|
}
|
|
1399
1673
|
}
|
|
1674
|
+
let idlePassed = $connection.step != 'Idle';
|
|
1400
1675
|
// An attempt is considered started once we observe a step where the connection is in progress.
|
|
1401
1676
|
// Falling back to a resting step from there means the attempt ended without reaching the target.
|
|
1402
1677
|
let attemptStarted = false;
|
|
1678
|
+
// Dismissals of the address-unavailable state that happened BEFORE this call: only a later one
|
|
1679
|
+
// is this call's answer.
|
|
1680
|
+
const acknowledgementsOnEntry = askedAddress ? acknowledgementsFor(askedAddress) : 0;
|
|
1681
|
+
// WHAT STOPS "try again" FROM BECOMING A LOOP: at most one attempt per wallet announcement.
|
|
1682
|
+
//
|
|
1683
|
+
// Our own attempts do not bump `walletAnnouncements`, so an attempt can never start another one
|
|
1684
|
+
// off its own result, however the wallet answers. Anything past that requires the user to act
|
|
1685
|
+
// in their wallet again, which is a person, not a loop.
|
|
1686
|
+
//
|
|
1687
|
+
// Two earlier versions of this rule are worth not repeating. "One attempt per distinct wallet
|
|
1688
|
+
// ANSWER" read well and measured false (the reset that stopped it suppressing legitimate
|
|
1689
|
+
// retries forgot the answer every time). "One attempt per distinct STATE" is provably
|
|
1690
|
+
// terminating and refuses the retry when the user switches back to an account they were on
|
|
1691
|
+
// before, which is an ordinary thing to do and leaves them following an instruction that no
|
|
1692
|
+
// longer does anything.
|
|
1693
|
+
//
|
|
1694
|
+
// Load-bearing, and pinned the hard way: delete this guard and `test/ensure-connected-settles`
|
|
1695
|
+
// does not fail, it HANGS, which is the honest signature of the bug it prevents.
|
|
1696
|
+
let attemptedAtEvent;
|
|
1697
|
+
// An attempt decided on but not started yet: see `scheduleAttempt`.
|
|
1698
|
+
let attemptScheduled = false;
|
|
1699
|
+
// How many attempts THIS call has started that have not finished yet.
|
|
1700
|
+
//
|
|
1701
|
+
// The store is not enough to know that. `connect` publishes `WaitingForWalletConnection`
|
|
1702
|
+
// before its first await, but `selectWallet` awaits `getChainId` before publishing anything at
|
|
1703
|
+
// all, and the popup path can await a key generation first. In that window the store still
|
|
1704
|
+
// holds the entry state, nothing is "in progress" as far as any published state is concerned,
|
|
1705
|
+
// and the answer branch below would report "nothing is in progress" about an attempt that is
|
|
1706
|
+
// running and about to succeed. It did exactly that, for `ensureConnected('WalletChosen')`
|
|
1707
|
+
// from any non-Idle state: rejected, and then reached the target anyway.
|
|
1708
|
+
let attemptsInFlight = 0;
|
|
1403
1709
|
let settled = false;
|
|
1404
1710
|
let unsubscribe;
|
|
1405
1711
|
const settle = (perform) => {
|
|
@@ -1411,7 +1717,212 @@ export function createConnection(settings) {
|
|
|
1411
1717
|
unsubscribe?.();
|
|
1412
1718
|
perform();
|
|
1413
1719
|
};
|
|
1414
|
-
|
|
1720
|
+
const cancelled = () => settle(() => reject(new ConnectionFailure('Connection cancelled')));
|
|
1721
|
+
/**
|
|
1722
|
+
* Start an attempt and stay honest about it while it runs.
|
|
1723
|
+
*
|
|
1724
|
+
* Everything these calls do, they normally do by moving the store, and the subscription below
|
|
1725
|
+
* reads the answer off it. Two things break that, and both are handled here rather than by
|
|
1726
|
+
* guessing from published states:
|
|
1727
|
+
*
|
|
1728
|
+
* - an attempt can be RUNNING while the store still shows the state it started from, because
|
|
1729
|
+
* `selectWallet` (and the popup path) await before their first publish;
|
|
1730
|
+
* - an attempt can FAIL before its first publish (a hosted mechanism with no `walletHost`),
|
|
1731
|
+
* after which nothing has changed and nothing will publish again.
|
|
1732
|
+
*
|
|
1733
|
+
* A late rejection, after the flow moved on, settles nothing: `settle` is idempotent and the
|
|
1734
|
+
* store has already answered.
|
|
1735
|
+
*/
|
|
1736
|
+
const runAttempt = (attempt) => {
|
|
1737
|
+
attemptsInFlight++;
|
|
1738
|
+
attempt.then(() => {
|
|
1739
|
+
attemptsInFlight--;
|
|
1740
|
+
// Decide again now that it is over. The store may have published its last state while
|
|
1741
|
+
// this attempt still counted as in progress, and nothing else will publish again: an
|
|
1742
|
+
// attempt that ends without reaching the target has to be answered here or nowhere.
|
|
1743
|
+
evaluate($connection);
|
|
1744
|
+
}, (err) => {
|
|
1745
|
+
attemptsInFlight--;
|
|
1746
|
+
settle(() => reject(new ConnectionFailure(err?.message || `could not reach ${step}`, err)));
|
|
1747
|
+
});
|
|
1748
|
+
};
|
|
1749
|
+
/** Is the connection sitting on the account the caller asked for, ready to be asked to sign? */
|
|
1750
|
+
const readyToSign = (connection) => connection.step === 'WalletConnected' &&
|
|
1751
|
+
connection.wallet.status === 'connected' &&
|
|
1752
|
+
walletNameMatches(connection) &&
|
|
1753
|
+
(!askedAddress || canActAs(connection, askedAddress));
|
|
1754
|
+
/**
|
|
1755
|
+
* Do whatever can be done from where the connection is right now.
|
|
1756
|
+
*
|
|
1757
|
+
* It may deliberately do NOTHING, in the one case where the pending thing is a click in the
|
|
1758
|
+
* app rather than anything this library can start: a `WalletConnected` connection asked for
|
|
1759
|
+
* `SignedIn` on a store that did not ask for the signature to be requested automatically. That
|
|
1760
|
+
* app renders its own "sign in" button, and prompting over the top of it would ask the user
|
|
1761
|
+
* for a signature the app deliberately deferred. `awaitingUserReason` names that state, so it
|
|
1762
|
+
* is a legitimate wait rather than a silent one.
|
|
1763
|
+
*/
|
|
1764
|
+
const initiate = () => {
|
|
1765
|
+
if (step === 'WalletChosen') {
|
|
1766
|
+
runAttempt(selectWallet(askedWalletName, opts));
|
|
1767
|
+
return true;
|
|
1768
|
+
}
|
|
1769
|
+
if (step === 'SignedIn' && readyToSign($connection)) {
|
|
1770
|
+
const mayRequestSignature = (requestSignatureAutomaticallyIfPossible || opts?.requestSignatureRightAway) &&
|
|
1771
|
+
!opts?.requireUserConfirmationBeforeSignatureRequest;
|
|
1772
|
+
if (mayRequestSignature) {
|
|
1773
|
+
// The narrow remedy: the wallet is already connected on the right account, so the only
|
|
1774
|
+
// thing between here and `SignedIn` is the signature. Reconnecting would prompt twice.
|
|
1775
|
+
// Failures land on the state as an error, which the subscription below reports.
|
|
1776
|
+
runAttempt(requestSignature());
|
|
1777
|
+
return true;
|
|
1778
|
+
}
|
|
1779
|
+
// Nothing started: the pending thing is a click in the app. Reported honestly, so the
|
|
1780
|
+
// caller falls through to the wait reasons instead of being told an attempt is running.
|
|
1781
|
+
return false;
|
|
1782
|
+
}
|
|
1783
|
+
runAttempt(connect(mechanism, opts, { addressIsPreference: reconnecting, reportUnavailableAddress: !!askedAddress }));
|
|
1784
|
+
return true;
|
|
1785
|
+
};
|
|
1786
|
+
// WHEN AN ATTEMPT MAY BE INITIATED.
|
|
1787
|
+
//
|
|
1788
|
+
// Not while one is already running (`stepsInProgress`), and not while the user is mid-choice
|
|
1789
|
+
// with a picker on screen, since connecting there would hijack their choice. A picker still
|
|
1790
|
+
// carrying the error of a previous attempt is the exception: that attempt failed and nothing
|
|
1791
|
+
// has driven the flow since, so re-initiating is exactly what the caller asked for. It cannot
|
|
1792
|
+
// hijack a choice either, because when a choice is genuinely needed `connect` re-enters the
|
|
1793
|
+
// same picker (clearing the stale error) and we keep waiting.
|
|
1794
|
+
//
|
|
1795
|
+
// Everything else initiates, INCLUDING the resting steps that used to fall through every
|
|
1796
|
+
// branch and wait forever: a `WalletChosen` connection asked to connect, and a connection at
|
|
1797
|
+
// rest holding an account the caller did not ask for.
|
|
1798
|
+
/**
|
|
1799
|
+
* Start an attempt from this state, if one is called for and would not be a repeat.
|
|
1800
|
+
*
|
|
1801
|
+
* Used at entry AND from `evaluate`, which is the fix for an answer that depended on timing:
|
|
1802
|
+
* initiating only at entry meant a call made while some OTHER flow was in progress (a picker
|
|
1803
|
+
* the user was mid-way through, say) got "nothing is in progress" the moment that flow ended
|
|
1804
|
+
* without satisfying it — while the identical call, made one tick later, initiated and
|
|
1805
|
+
* succeeded. Same store, same request, opposite answers.
|
|
1806
|
+
*/
|
|
1807
|
+
/**
|
|
1808
|
+
* Would attempting AGAINST THIS STATE be wrong, whatever the caller asked for?
|
|
1809
|
+
*
|
|
1810
|
+
* Pulled out because it has to be asked TWICE: once when the attempt is decided on, and again
|
|
1811
|
+
* when a deferred attempt actually runs. The deferral exists precisely because the state moves
|
|
1812
|
+
* in between, so re-checking less than was checked the first time is backwards — and it was:
|
|
1813
|
+
* the microtask used to re-check only the target, so a `useCurrentAccount` store that had
|
|
1814
|
+
* meanwhile started its own connect got a SECOND concurrent one, two `eth_requestAccounts` at
|
|
1815
|
+
* once, and a wallet answering the second with "already processing" would have rejected a call
|
|
1816
|
+
* whose real attempt was still running and about to succeed.
|
|
1817
|
+
*/
|
|
1818
|
+
const attemptWouldBeWrongNow = (connection) => {
|
|
1819
|
+
if (targetReached(connection) || attemptsInFlight > 0) {
|
|
1820
|
+
return true;
|
|
1821
|
+
}
|
|
1822
|
+
if (stepsInProgress.includes(connection.step)) {
|
|
1823
|
+
return true;
|
|
1824
|
+
}
|
|
1825
|
+
// A picker the user is mid-choice on is theirs, not ours to hijack. One carrying the error
|
|
1826
|
+
// of a previous attempt is different: that attempt failed and nothing has driven the flow
|
|
1827
|
+
// since, so re-initiating is what the caller asked for.
|
|
1828
|
+
const userIsChoosing = (connection.step === 'MechanismToChoose' || connection.step === 'WalletToChoose') && !errorOnEntry;
|
|
1829
|
+
return userIsChoosing && !opts?.forceConnect && !forceConnect;
|
|
1830
|
+
};
|
|
1831
|
+
const initiateIfWorthwhile = (connection, start = initiate) => {
|
|
1832
|
+
if (attemptScheduled || attemptWouldBeWrongNow(connection)) {
|
|
1833
|
+
return false;
|
|
1834
|
+
}
|
|
1835
|
+
if (attemptedAtEvent === walletAnnouncements) {
|
|
1836
|
+
return false;
|
|
1837
|
+
}
|
|
1838
|
+
attemptedAtEvent = walletAnnouncements;
|
|
1839
|
+
return start();
|
|
1840
|
+
};
|
|
1841
|
+
initiateIfWorthwhile($connection);
|
|
1842
|
+
/**
|
|
1843
|
+
* WHY WAITING IS LEGITIMATE RIGHT NOW, or `undefined` if it is not.
|
|
1844
|
+
*
|
|
1845
|
+
* The closed list, and the whole of the settle guarantee: every entry is something IN
|
|
1846
|
+
* PROGRESS, and every one of them is published on the connection for the app to render and
|
|
1847
|
+
* for the user to answer. Anything not on this list is not a wait, it is an unanswered
|
|
1848
|
+
* question, and the caller gets an answer instead (see the end of the subscription).
|
|
1849
|
+
*
|
|
1850
|
+
* Deliberately NOT a timeout. A human is in the loop: a timer long enough not to cut someone
|
|
1851
|
+
* off mid-decision is too long to be useful, and it would report "timed out" about a wallet
|
|
1852
|
+
* dialog that is open and healthy.
|
|
1853
|
+
*/
|
|
1854
|
+
const awaitingUserReason = (connection) => {
|
|
1855
|
+
if (attemptsInFlight > 0 || attemptScheduled) {
|
|
1856
|
+
// Not inferred from the state: this call started something and it has not come back.
|
|
1857
|
+
// Covers the window before an attempt's first publish, which the store cannot show, and
|
|
1858
|
+
// the window between deciding to attempt and the microtask that runs it.
|
|
1859
|
+
return 'an attempt this call started is still running';
|
|
1860
|
+
}
|
|
1861
|
+
if (stepsInProgress.includes(connection.step)) {
|
|
1862
|
+
return 'an attempt is in progress';
|
|
1863
|
+
}
|
|
1864
|
+
if (connection.step === 'MechanismToChoose' || connection.step === 'WalletToChoose') {
|
|
1865
|
+
return 'the user is choosing';
|
|
1866
|
+
}
|
|
1867
|
+
if (askedAddress &&
|
|
1868
|
+
connection.addressUnavailable?.requested.toLowerCase() === askedAddress &&
|
|
1869
|
+
// ...and it is still TRUE. A reason that has gone stale (the wallet does offer the
|
|
1870
|
+
// account now) licenses a wait that nothing can end: the user has already done the only
|
|
1871
|
+
// thing it asks of them. The same freshness test guards the resting branch in `evaluate`,
|
|
1872
|
+
// and the two must agree or the disagreement IS the hang.
|
|
1873
|
+
!(connection.wallet?.accounts ?? []).some((account) => account.toLowerCase() === askedAddress)) {
|
|
1874
|
+
// Only OUR request licenses this wait. A reason left on the connection by a different
|
|
1875
|
+
// call describes an account this call never asked about, and waiting on somebody else's
|
|
1876
|
+
// unanswered question is how a wait becomes unending.
|
|
1877
|
+
return 'the wallet is not on the account that was asked for';
|
|
1878
|
+
}
|
|
1879
|
+
if (targetReached(connection) && !chainIsRight(connection)) {
|
|
1880
|
+
return 'the wallet is on another chain';
|
|
1881
|
+
}
|
|
1882
|
+
if (step === 'SignedIn' && readyToSign(connection)) {
|
|
1883
|
+
// The app's own "sign in" button is the pending decision — but only while the connection
|
|
1884
|
+
// could actually be asked to sign. On a wallet that has since locked or moved account,
|
|
1885
|
+
// `requestSignature()` is not a remedy the user can take, so this is not a wait, and the
|
|
1886
|
+
// caller gets an answer instead.
|
|
1887
|
+
return 'the signature has not been requested yet';
|
|
1888
|
+
}
|
|
1889
|
+
return undefined;
|
|
1890
|
+
};
|
|
1891
|
+
/**
|
|
1892
|
+
* Start an attempt AFTER the current publish, never during it.
|
|
1893
|
+
*
|
|
1894
|
+
* `evaluate` runs inside `set`, and a wallet event does not produce one state: `onAccountChanged`
|
|
1895
|
+
* publishes the new status first and the new accounts second. Starting a connection attempt
|
|
1896
|
+
* from inside the first of those re-enters the store while the handler is still mid-way through
|
|
1897
|
+
* its own transitions, which then continue on top of a state the attempt has replaced — rebuilding
|
|
1898
|
+
* a wallet from one that is no longer there. So the decision is taken synchronously (which is
|
|
1899
|
+
* what keeps the accounting honest) and the work is done once the dust settles, against whatever
|
|
1900
|
+
* state the handler finally left behind.
|
|
1901
|
+
*/
|
|
1902
|
+
const scheduleAttempt = () => {
|
|
1903
|
+
attemptScheduled = true;
|
|
1904
|
+
queueMicrotask(() => {
|
|
1905
|
+
attemptScheduled = false;
|
|
1906
|
+
if (settled) {
|
|
1907
|
+
return;
|
|
1908
|
+
}
|
|
1909
|
+
// EVERY guard re-applied against the state as it now is, not just the target: the rest of
|
|
1910
|
+
// the handler that published may have satisfied the request, started its own attempt, or
|
|
1911
|
+
// moved the connection somewhere attempting would be wrong (a popup, an account picker,
|
|
1912
|
+
// another wallet). The event guard is NOT re-applied, because this attempt already
|
|
1913
|
+
// consumed it when it was scheduled.
|
|
1914
|
+
if (attemptWouldBeWrongNow($connection) || !initiate()) {
|
|
1915
|
+
evaluate($connection);
|
|
1916
|
+
}
|
|
1917
|
+
});
|
|
1918
|
+
return true;
|
|
1919
|
+
};
|
|
1920
|
+
/**
|
|
1921
|
+
* Decide, against one state. Called for every publish, AND once more whenever an attempt this
|
|
1922
|
+
* call started comes back, because the last publish may have happened while that attempt was
|
|
1923
|
+
* still running and nothing will publish again afterwards.
|
|
1924
|
+
*/
|
|
1925
|
+
const evaluate = (connection) => {
|
|
1415
1926
|
if (settled) {
|
|
1416
1927
|
return;
|
|
1417
1928
|
}
|
|
@@ -1423,6 +1934,19 @@ export function createConnection(settings) {
|
|
|
1423
1934
|
settle(() => resolve(connection));
|
|
1424
1935
|
return;
|
|
1425
1936
|
}
|
|
1937
|
+
// THE USER DISMISSED the "your wallet is not on that account" state for the address THIS
|
|
1938
|
+
// call asked about. Checked before anything else that can return: a decision is an answer
|
|
1939
|
+
// whatever else is happening on the connection, and this call may be resting while a
|
|
1940
|
+
// DIFFERENT one has the flow in progress — in which case the in-progress branch below would
|
|
1941
|
+
// swallow the dismissal, and nothing would publish again to bring it back.
|
|
1942
|
+
//
|
|
1943
|
+
// Read from the acknowledgement count FOR THAT ADDRESS rather than from the reason
|
|
1944
|
+
// disappearing. Several things clear that field and only one of them is a decision; and a
|
|
1945
|
+
// decision about one address is not an answer to a request about another.
|
|
1946
|
+
if (askedAddress && acknowledgementsFor(askedAddress) !== acknowledgementsOnEntry) {
|
|
1947
|
+
cancelled();
|
|
1948
|
+
return;
|
|
1949
|
+
}
|
|
1426
1950
|
if (stepsInProgress.includes(connection.step)) {
|
|
1427
1951
|
// still going, nothing to decide yet
|
|
1428
1952
|
attemptStarted = true;
|
|
@@ -1439,15 +1963,60 @@ export function createConnection(settings) {
|
|
|
1439
1963
|
}
|
|
1440
1964
|
// Reject on disconnect/back to Idle
|
|
1441
1965
|
if (connection.step === 'Idle' && idlePassed) {
|
|
1442
|
-
|
|
1966
|
+
cancelled();
|
|
1443
1967
|
return;
|
|
1444
1968
|
}
|
|
1445
1969
|
// The attempt went back to a resting step without an error: it was aborted (back/cancel).
|
|
1446
1970
|
// This must never trigger on a resting step we merely started from, hence `attemptStarted`.
|
|
1447
1971
|
if (attemptStarted && stepsAtRest.includes(connection.step)) {
|
|
1448
|
-
|
|
1972
|
+
cancelled();
|
|
1973
|
+
return;
|
|
1449
1974
|
}
|
|
1450
|
-
|
|
1975
|
+
// THE WALLET IS NOT ON THE ACCOUNT THIS CALL ASKED FOR, and the connection is resting on a
|
|
1976
|
+
// state that says so. That is the app's to render and the user's to answer, so nothing is
|
|
1977
|
+
// attempted while it stands: re-attempting would prompt them again for the account they are
|
|
1978
|
+
// being asked to switch to.
|
|
1979
|
+
//
|
|
1980
|
+
// The moment the wallet DOES offer it, this stops applying and the ordinary rule below picks
|
|
1981
|
+
// the request back up, which is what carries the user through without a click in the app.
|
|
1982
|
+
const unavailable = connection.addressUnavailable;
|
|
1983
|
+
if (askedAddress &&
|
|
1984
|
+
unavailable?.requested.toLowerCase() === askedAddress &&
|
|
1985
|
+
!(connection.wallet?.accounts ?? []).some((account) => account.toLowerCase() === askedAddress)) {
|
|
1986
|
+
return;
|
|
1987
|
+
}
|
|
1988
|
+
// A REQUIREMENT THE CALLER NAMED IS UNMET, and no attempt has been made from this state.
|
|
1989
|
+
//
|
|
1990
|
+
// Re-initiating here, and only here, is the fix for an answer that depended on timing: a
|
|
1991
|
+
// call made while some OTHER flow was in progress (an account picker the user was part-way
|
|
1992
|
+
// through, say) used to get "nothing is in progress" the moment that flow ended on the wrong
|
|
1993
|
+
// account, while the identical call one tick later initiated and succeeded.
|
|
1994
|
+
//
|
|
1995
|
+
// Deliberately NOT extended to an unmet STEP. A connection that comes to rest below the
|
|
1996
|
+
// target has chosen to rest there and the app renders that (a `WalletConnected` state under
|
|
1997
|
+
// a `SignedIn` target is waiting for the app's own sign-in button), and re-running `connect`
|
|
1998
|
+
// from a state that names no wallet opens the picker — which is `connect`'s meaning, and
|
|
1999
|
+
// nobody's idea of what a promise-shaped call should do behind their back.
|
|
2000
|
+
if (!walletNameMatches(connection) || (askedAddress && !canActAs(connection, askedAddress))) {
|
|
2001
|
+
if (initiateIfWorthwhile(connection, scheduleAttempt)) {
|
|
2002
|
+
return;
|
|
2003
|
+
}
|
|
2004
|
+
}
|
|
2005
|
+
// NOTHING IS IN PROGRESS AND NOTHING CAN BE INITIATED: that is an answer, and it is
|
|
2006
|
+
// delivered rather than awaited. Silently waiting here is the failure this guard exists to
|
|
2007
|
+
// make impossible, and it is stated as a POSITIVE list (`awaitingUserReason`) on purpose:
|
|
2008
|
+
// a new step, or a new resting reason, is unreachable-by-default rather than a fresh way
|
|
2009
|
+
// to hang.
|
|
2010
|
+
const reason = awaitingUserReason(connection);
|
|
2011
|
+
if (!reason) {
|
|
2012
|
+
// The message names where the connection actually is, including the wallet's status,
|
|
2013
|
+
// because the likeliest way to arrive here is a wallet that went locked or was revoked
|
|
2014
|
+
// between the attempt finishing and this state being published.
|
|
2015
|
+
const wallet = connection.wallet ? ` (wallet ${connection.wallet.status})` : '';
|
|
2016
|
+
settle(() => reject(new ConnectionFailure(`could not reach ${step}: the connection is at ${connection.step}${wallet} and nothing is in progress`)));
|
|
2017
|
+
}
|
|
2018
|
+
};
|
|
2019
|
+
unsubscribe = _store.subscribe(evaluate);
|
|
1451
2020
|
if (settled) {
|
|
1452
2021
|
unsubscribe();
|
|
1453
2022
|
}
|
|
@@ -1789,173 +2358,120 @@ export function createConnection(settings) {
|
|
|
1789
2358
|
});
|
|
1790
2359
|
}
|
|
1791
2360
|
}
|
|
2361
|
+
/**
|
|
2362
|
+
* Ask the user's wallet to move to a chain, adding it first if the wallet has never seen it.
|
|
2363
|
+
*
|
|
2364
|
+
* TWO PROMPTS, not one, and which of them is up is published as `wallet.switchingChain`
|
|
2365
|
+
* (`'switchingChain'` then `'addingChain'`). That distinction is not cosmetic: "add this
|
|
2366
|
+
* network" is a different question from "switch network", and a consumer wording them the same
|
|
2367
|
+
* way asks the user to approve something other than what the wallet is showing.
|
|
2368
|
+
*
|
|
2369
|
+
* That state is also the whole justification for these two calls bypassing the always-on
|
|
2370
|
+
* wrapper, which is where every other request the user answers is announced. See
|
|
2371
|
+
* `docs/adr/0001-wallet-requests-are-announced-through-the-wrapper.md`: "each already publishes
|
|
2372
|
+
* a dedicated state the consumer renders... if any of those states is removed, that call moves
|
|
2373
|
+
* onto the wrapper." So collapsing these two values into a boolean, or dropping them, is not a
|
|
2374
|
+
* simplification: it is a decision to route these through the wrapper instead.
|
|
2375
|
+
*/
|
|
1792
2376
|
async function switchWalletChain(chainInfo) {
|
|
1793
2377
|
if (!$connection.wallet) {
|
|
1794
|
-
throw new Error(`
|
|
2378
|
+
throw new Error(`invalid state: no wallet to ask`);
|
|
1795
2379
|
}
|
|
2380
|
+
const wallet = $connection.wallet;
|
|
1796
2381
|
const chainInfoToUse = chainInfo || settings.chainInfo;
|
|
1797
2382
|
const params = viemChainInfoToSwitchChainInfo(chainInfoToUse);
|
|
1798
2383
|
const chainId = '' + chainInfoToUse.id;
|
|
1799
2384
|
const chainIdAsHex = params.chainId;
|
|
1800
|
-
|
|
1801
|
-
|
|
1802
|
-
//
|
|
1803
|
-
//
|
|
2385
|
+
/** How to name this chain to the user, whether or not the app gave it a name. */
|
|
2386
|
+
const named = params?.chainName || `chain with id = ${chainId}`;
|
|
2387
|
+
// A wallet prompt is up, and WHICH one. Guarded because the user is free to disconnect while
|
|
2388
|
+
// they look at it, and a state with no wallet has nothing to say about a switch.
|
|
2389
|
+
const nowAsking = (prompt) => {
|
|
2390
|
+
if ($connection.wallet) {
|
|
2391
|
+
set({ ...$connection, wallet: { ...$connection.wallet, switchingChain: prompt } });
|
|
2392
|
+
}
|
|
2393
|
+
};
|
|
2394
|
+
// THE SINGLE EXIT. Every path out of this function comes through here, which is what makes
|
|
2395
|
+
// the rule legible rather than remembered: an error is set by whoever GIVES UP, and by
|
|
2396
|
+
// nobody on the way past. Setting one before a recovery that then worked is exactly the bug
|
|
2397
|
+
// this shape prevents, and it shipped: the user landed on the requested chain with a banner
|
|
2398
|
+
// saying it had failed.
|
|
2399
|
+
//
|
|
2400
|
+
// `error` is omitted rather than set to `undefined` when there is none, so a successful
|
|
2401
|
+
// switch does not silently clear an unrelated error the app has not shown yet.
|
|
2402
|
+
const doneAsking = (error) => {
|
|
2403
|
+
if ($connection.wallet) {
|
|
2404
|
+
set({
|
|
2405
|
+
...$connection,
|
|
2406
|
+
wallet: { ...$connection.wallet, switchingChain: false },
|
|
2407
|
+
...(error ? { error } : {}),
|
|
2408
|
+
});
|
|
2409
|
+
}
|
|
2410
|
+
};
|
|
2411
|
+
/** 4001 is the user saying no. A refusal is not a failure and has nothing to report. */
|
|
2412
|
+
const isRefusal = (err) => err?.code === 4001;
|
|
1804
2413
|
try {
|
|
1805
|
-
|
|
1806
|
-
|
|
1807
|
-
|
|
1808
|
-
|
|
1809
|
-
});
|
|
2414
|
+
nowAsking('switchingChain');
|
|
2415
|
+
// These methods report success as `null`, so a non-null RESULT is an error reported
|
|
2416
|
+
// without throwing. Turning it into a throw here is what puts both shapes on one road,
|
|
2417
|
+
// including the road to the recovery below.
|
|
1810
2418
|
const result = await wallet.provider.switchChain(chainIdAsHex);
|
|
1811
|
-
if (
|
|
1812
|
-
if ($connection.wallet) {
|
|
1813
|
-
set({
|
|
1814
|
-
...$connection,
|
|
1815
|
-
wallet: { ...$connection.wallet, switchingChain: false },
|
|
1816
|
-
});
|
|
1817
|
-
}
|
|
1818
|
-
// logger.info(`wallet_switchEthereumChain: complete`);
|
|
1819
|
-
// this will be taken care with `chainChanged` (but maybe it should be done there ?)
|
|
1820
|
-
// handleNetwork(chainId);
|
|
1821
|
-
}
|
|
1822
|
-
else {
|
|
1823
|
-
// A non-null RESULT is how these methods report an error without throwing, so this is a
|
|
1824
|
-
// failure and not a value. It is reported by THROWING and nothing else, because this
|
|
1825
|
-
// throw lands in the catch below, which may still recover by adding the chain.
|
|
1826
|
-
//
|
|
1827
|
-
// Setting an error here as well used to leave `Failed to switch to <chain>` on the state
|
|
1828
|
-
// after a recovery that WORKED: the add path spreads `...$connection` on its way out and
|
|
1829
|
-
// carried it along, so the user ended up on the requested chain being told it had failed.
|
|
1830
|
-
// Whoever gives up sets the error; nobody sets one on the way past.
|
|
2419
|
+
if (result) {
|
|
1831
2420
|
throw result;
|
|
1832
2421
|
}
|
|
2422
|
+
// The chain itself is not recorded here: the wallet announces `chainChanged`, and that is
|
|
2423
|
+
// what moves the connection, exactly as when the user switches chain in the wallet.
|
|
2424
|
+
doneAsking();
|
|
2425
|
+
return;
|
|
1833
2426
|
}
|
|
1834
2427
|
catch (err) {
|
|
1835
|
-
if (err
|
|
1836
|
-
|
|
1837
|
-
if ($connection.wallet) {
|
|
1838
|
-
set({
|
|
1839
|
-
...$connection,
|
|
1840
|
-
wallet: { ...$connection.wallet, switchingChain: false },
|
|
1841
|
-
});
|
|
1842
|
-
}
|
|
2428
|
+
if (isRefusal(err)) {
|
|
2429
|
+
doneAsking();
|
|
1843
2430
|
return;
|
|
1844
2431
|
}
|
|
1845
|
-
|
|
1846
|
-
|
|
1847
|
-
|
|
1848
|
-
|
|
1849
|
-
|
|
1850
|
-
|
|
1851
|
-
|
|
1852
|
-
|
|
1853
|
-
// logger.info(`wallet_switchEthereumChain: could not switch, try adding the chain via "wallet_addEthereumChain"`);
|
|
1854
|
-
try {
|
|
1855
|
-
const result = await wallet.provider.addChain({
|
|
1856
|
-
chainId: chainIdAsHex,
|
|
1857
|
-
rpcUrls: params.rpcUrls,
|
|
1858
|
-
chainName: params.chainName,
|
|
1859
|
-
blockExplorerUrls: params.blockExplorerUrls,
|
|
1860
|
-
iconUrls: params.iconUrls,
|
|
1861
|
-
nativeCurrency: params.nativeCurrency,
|
|
1862
|
-
});
|
|
1863
|
-
if (!result) {
|
|
1864
|
-
if ($connection.wallet) {
|
|
1865
|
-
set({
|
|
1866
|
-
...$connection,
|
|
1867
|
-
wallet: { ...$connection.wallet, switchingChain: false },
|
|
1868
|
-
});
|
|
1869
|
-
}
|
|
1870
|
-
// this will be taken care with `chainChanged` (but maybe it should be done there ?)
|
|
1871
|
-
// handleNetwork(chainId);
|
|
1872
|
-
}
|
|
1873
|
-
else {
|
|
1874
|
-
if ($connection.wallet) {
|
|
1875
|
-
set({
|
|
1876
|
-
...$connection,
|
|
1877
|
-
wallet: { ...$connection.wallet, switchingChain: false },
|
|
1878
|
-
error: {
|
|
1879
|
-
message: `Failed to add new chain: ${params?.chainName || `chain with id = ${chainId}`}`,
|
|
1880
|
-
cause: result,
|
|
1881
|
-
},
|
|
1882
|
-
});
|
|
1883
|
-
}
|
|
1884
|
-
// logger.info(`wallet_addEthereumChain: a non-undefinded result means an error`, result);
|
|
1885
|
-
throw result;
|
|
1886
|
-
}
|
|
1887
|
-
}
|
|
1888
|
-
catch (err) {
|
|
1889
|
-
if (err.code !== 4001) {
|
|
1890
|
-
if ($connection.wallet) {
|
|
1891
|
-
set({
|
|
1892
|
-
...$connection,
|
|
1893
|
-
wallet: { ...$connection.wallet, switchingChain: false },
|
|
1894
|
-
error: {
|
|
1895
|
-
message: `Failed to add new chain: ${params?.chainName || `chain with id = ${chainId}`}`,
|
|
1896
|
-
cause: err,
|
|
1897
|
-
},
|
|
1898
|
-
});
|
|
1899
|
-
}
|
|
1900
|
-
// logger.info(`wallet_addEthereumChain: failed`, err);
|
|
1901
|
-
// TODO ?
|
|
1902
|
-
// set({
|
|
1903
|
-
// error: {message: `Failed to add new chain`, cause: err},
|
|
1904
|
-
// });
|
|
1905
|
-
// for now:
|
|
1906
|
-
throw err;
|
|
1907
|
-
}
|
|
1908
|
-
else {
|
|
1909
|
-
if ($connection.wallet) {
|
|
1910
|
-
set({
|
|
1911
|
-
...$connection,
|
|
1912
|
-
wallet: { ...$connection.wallet, switchingChain: false },
|
|
1913
|
-
});
|
|
1914
|
-
}
|
|
1915
|
-
// logger.info(`wallet_addEthereumChain: failed but error code === 4001, we ignore as user rejected it`, err);
|
|
1916
|
-
return;
|
|
1917
|
-
}
|
|
1918
|
-
}
|
|
2432
|
+
if (!params?.rpcUrls || params.rpcUrls.length === 0) {
|
|
2433
|
+
// Nothing left to try: the wallet cannot switch to this chain, and there is no rpcUrl to
|
|
2434
|
+
// add it with. `cause` keeps what the wallet actually said, since the message below is
|
|
2435
|
+
// this library's summary and the branch is reached both from a refusal to switch and
|
|
2436
|
+
// from a wallet reporting its error as a result.
|
|
2437
|
+
const message = `Chain "${named}" is not available on your wallet`;
|
|
2438
|
+
doneAsking({ message, cause: err });
|
|
2439
|
+
throw new Error(message);
|
|
1919
2440
|
}
|
|
1920
|
-
|
|
1921
|
-
|
|
1922
|
-
|
|
1923
|
-
|
|
1924
|
-
|
|
1925
|
-
|
|
1926
|
-
|
|
1927
|
-
|
|
1928
|
-
|
|
1929
|
-
|
|
1930
|
-
|
|
1931
|
-
|
|
1932
|
-
|
|
1933
|
-
|
|
1934
|
-
|
|
1935
|
-
|
|
1936
|
-
|
|
2441
|
+
}
|
|
2442
|
+
// The wallet does not know this chain. Asking it to ADD one is a second prompt, with the
|
|
2443
|
+
// details the wallet needs to describe the chain to the user.
|
|
2444
|
+
nowAsking('addingChain');
|
|
2445
|
+
try {
|
|
2446
|
+
const result = await wallet.provider.addChain({
|
|
2447
|
+
chainId: chainIdAsHex,
|
|
2448
|
+
rpcUrls: params.rpcUrls,
|
|
2449
|
+
chainName: params.chainName,
|
|
2450
|
+
blockExplorerUrls: params.blockExplorerUrls,
|
|
2451
|
+
iconUrls: params.iconUrls,
|
|
2452
|
+
nativeCurrency: params.nativeCurrency,
|
|
2453
|
+
});
|
|
2454
|
+
if (result) {
|
|
2455
|
+
throw result;
|
|
2456
|
+
}
|
|
2457
|
+
doneAsking();
|
|
2458
|
+
}
|
|
2459
|
+
catch (err) {
|
|
2460
|
+
if (isRefusal(err)) {
|
|
2461
|
+
doneAsking();
|
|
2462
|
+
return;
|
|
1937
2463
|
}
|
|
2464
|
+
const message = `Failed to add new chain: ${named}`;
|
|
2465
|
+
doneAsking({ message, cause: err });
|
|
2466
|
+
throw err;
|
|
1938
2467
|
}
|
|
1939
2468
|
}
|
|
1940
2469
|
// Method on the store to check if target step is reached
|
|
1941
2470
|
function storeIsTargetStepReached(connection) {
|
|
1942
|
-
|
|
1943
|
-
|
|
1944
|
-
|
|
1945
|
-
|
|
1946
|
-
(connection.step === 'SignedIn' && connection.wallet !== undefined));
|
|
1947
|
-
}
|
|
1948
|
-
if (targetStep === 'WalletConnected') {
|
|
1949
|
-
// For WalletConnected target, accept WalletConnected OR SignedIn-with-wallet
|
|
1950
|
-
return (connection.step === 'WalletConnected' || (connection.step === 'SignedIn' && connection.wallet !== undefined));
|
|
1951
|
-
}
|
|
1952
|
-
// For SignedIn target
|
|
1953
|
-
if (walletOnly) {
|
|
1954
|
-
// With walletOnly, only accept SignedIn-with-wallet
|
|
1955
|
-
return connection.step === 'SignedIn' && connection.wallet !== undefined;
|
|
1956
|
-
}
|
|
1957
|
-
// Accept any SignedIn variant
|
|
1958
|
-
return connection.step === 'SignedIn';
|
|
2471
|
+
// The same ordered comparison the exported `isTargetStepReached` makes, against this store's
|
|
2472
|
+
// configured target. `walletOnly` only bites on a `SignedIn` target: the lower two are
|
|
2473
|
+
// wallet-bound by definition.
|
|
2474
|
+
return stepIsAtOrBeyond(connection, targetStep, { requireWallet: walletOnly });
|
|
1959
2475
|
}
|
|
1960
2476
|
const store = {
|
|
1961
2477
|
subscribe: _store.subscribe,
|
|
@@ -1972,6 +2488,8 @@ export function createConnection(settings) {
|
|
|
1972
2488
|
switchWalletChain,
|
|
1973
2489
|
unlock,
|
|
1974
2490
|
ensureConnected: ensureConnected, // Cast to bypass complex conditional typing
|
|
2491
|
+
acknowledgeAddressUnavailable,
|
|
2492
|
+
canActAs: (address) => canActAs($connection, address),
|
|
1975
2493
|
isTargetStepReached: storeIsTargetStepReached, // Cast for type guard
|
|
1976
2494
|
targetStep,
|
|
1977
2495
|
walletOnly,
|