@etherplay/connect 0.10.0 → 0.11.1

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/src/index.ts CHANGED
@@ -150,37 +150,66 @@ export type FullfilledMechanism = AuthMechanism | WalletMechanism<string, `0x${s
150
150
 
151
151
  export type TargetStep = 'WalletChosen' | 'WalletConnected' | 'SignedIn';
152
152
 
153
- export type WalletState<WalletProviderType> = {
153
+ type WalletStateCommon<WalletProviderType> = {
154
154
  provider: WalletProvider<WalletProviderType>;
155
155
  accounts: `0x${string}`[];
156
156
  accountChanged?: `0x${string}`;
157
157
  chainId: string;
158
158
  invalidChainId: boolean;
159
159
  switchingChain: 'addingChain' | 'switchingChain' | false;
160
+ /**
161
+ * @deprecated read `connection.pendingRequests` instead. This mirror is kept in step with it
162
+ * (both are stamped from the wrapper at the same moment, so they cannot disagree) and it will be
163
+ * removed in a later major version.
164
+ *
165
+ * It describes what the WRAPPER is holding, not what this wallet state is, and the wrapper
166
+ * outlives any particular wallet state. That is why every rebuild had to be taught to copy it,
167
+ * and why the paths that build no wallet at all — a failed reconnect resting on
168
+ * `wallet: undefined` — could still lose it while the user's wallet was genuinely holding a
169
+ * prompt. A field whose value must be copied at every construction of its container is a field
170
+ * in the wrong container.
171
+ */
160
172
  pendingRequests: PendingRequest[];
161
- } & ({status: 'connected'} | {status: 'locked'; unlocking: boolean} | {status: 'disconnected'; connecting: boolean});
173
+ };
174
+
175
+ type WalletStatus =
176
+ | {status: 'connected'}
177
+ | {status: 'locked'; unlocking: boolean}
178
+ | {status: 'disconnected'; connecting: boolean};
179
+
180
+ export type WalletState<WalletProviderType> = WalletStateCommon<WalletProviderType> & WalletStatus;
162
181
 
163
- type WaitingForSignature<WalletProviderType> = {
182
+ // The same wallet state MINUS the deprecated list, which `set` stamps. Nothing inside this file
183
+ // supplies `pendingRequests` when it builds a wallet: that is the whole point of having one
184
+ // construction site, and this type is what stops a hand-written eleventh rebuild from supplying a
185
+ // wrong one instead.
186
+ type WalletStateInput<WalletProviderType> = Omit<WalletStateCommon<WalletProviderType>, 'pendingRequests'> &
187
+ WalletStatus;
188
+
189
+ // The step types below take the wallet state as a parameter so that the same union can describe
190
+ // both what the store PUBLISHES (`WalletState`, list included) and what `set` ACCEPTS
191
+ // (`WalletStateInput`, list stamped for you). The default keeps every existing use unchanged.
192
+ type WaitingForSignature<WalletProviderType, WS = WalletState<WalletProviderType>> = {
164
193
  step: 'WaitingForSignature';
165
194
  mechanism: WalletMechanism<string, `0x${string}`>;
166
- wallet: WalletState<WalletProviderType>;
195
+ wallet: WS;
167
196
  account: {address: `0x${string}`};
168
197
  };
169
198
 
170
- type WalletChosen<WalletProviderType> = {
199
+ type WalletChosen<WalletProviderType, WS = WalletState<WalletProviderType>> = {
171
200
  step: 'WalletChosen';
172
201
  mechanism: WalletMechanism<string, undefined>;
173
- wallet: WalletState<WalletProviderType>;
202
+ wallet: WS;
174
203
  };
175
204
 
176
- type WalletConnected<WalletProviderType> = {
205
+ type WalletConnected<WalletProviderType, WS = WalletState<WalletProviderType>> = {
177
206
  step: 'WalletConnected';
178
207
  mechanism: WalletMechanism<string, `0x${string}`>;
179
- wallet: WalletState<WalletProviderType>;
208
+ wallet: WS;
180
209
  account: {address: `0x${string}`};
181
210
  };
182
211
 
183
- type SignedIn<WalletProviderType> =
212
+ type SignedIn<WalletProviderType, WS = WalletState<WalletProviderType>> =
184
213
  | {
185
214
  step: 'SignedIn';
186
215
  mechanism: AuthMechanism;
@@ -191,17 +220,40 @@ type SignedIn<WalletProviderType> =
191
220
  step: 'SignedIn';
192
221
  mechanism: WalletMechanism<string, `0x${string}`>;
193
222
  account: OriginAccount;
194
- wallet: WalletState<WalletProviderType>;
223
+ wallet: WS;
195
224
  };
196
225
 
197
- export type Connection<WalletProviderType> = {
226
+ // What the connection is, independently of which step it is at.
227
+ //
228
+ // Named rather than written inline below so that `set` can be given the same thing MINUS
229
+ // `pendingRequests`, which it stamps itself from the wrapper: see `ConnectionInput`.
230
+ type ConnectionCommon<WalletProviderType> = {
198
231
  // The connection can have an error in every state.
199
232
  // a banner or other mechanism to show error should be used.
200
233
  // error should be dismissable
201
234
  error?: {message: string; cause?: any};
202
235
  // wallets represent the web3 wallet installed on the user browser
203
236
  wallets: WalletHandle<WalletProviderType>[];
204
- } & ( // loading can be true initially as the system will try to auto-login and fetch installed web3 wallet // Start in Idle
237
+ /**
238
+ * Requests the user's wallet is holding right now, whatever the connection is doing.
239
+ *
240
+ * It lives HERE, beside `wallet` rather than inside it, because it describes what the always-on
241
+ * wrapper is holding and the wrapper outlives any particular wallet state. A request is
242
+ * outstanding for as long as the user has not answered it, and the connection is free to rebuild
243
+ * its wallet state, or to have no wallet state at all, in the meantime: a locked wallet raises
244
+ * the connection flow while it is still holding the transaction that raised it, and a reconnect
245
+ * that then FAILS comes to rest with no wallet at all. The prompt is still on the user's screen
246
+ * throughout, so the app must still be able to say so.
247
+ *
248
+ * This is the list to read. `wallet.pendingRequests` is the same list and is deprecated.
249
+ *
250
+ * See `docs/adr/0001-wallet-requests-are-announced-through-the-wrapper.md`: a request the user
251
+ * must answer and the app cannot see is a request nothing can explain, cancel or recover from.
252
+ */
253
+ pendingRequests: PendingRequest[];
254
+ };
255
+
256
+ type ConnectionSteps<WalletProviderType, WS = WalletState<WalletProviderType>> = // loading can be true initially as the system will try to auto-login and fetch installed web3 wallet // Start in Idle
205
257
  | {
206
258
  step: 'Idle';
207
259
  loading: boolean;
@@ -237,26 +289,39 @@ export type Connection<WalletProviderType> = {
237
289
  // reads route through it (when `prioritizeWalletProvider` is true), but no
238
290
  // accounts have been requested and signing is refused (status: 'disconnected').
239
291
  // This is the resting step for `targetStep: 'WalletChosen'`.
240
- | WalletChosen<WalletProviderType>
292
+ | WalletChosen<WalletProviderType, WS>
241
293
  // Once the wallet is connected, if multiple account are connected to the site
242
294
  // the user can choose which one to connect to
243
295
  | {
244
296
  step: 'ChooseWalletAccount';
245
297
  mechanism: WalletMechanism<string, undefined>;
246
- wallet: WalletState<WalletProviderType>;
298
+ wallet: WS;
247
299
  }
248
300
  // Once the wallet is connected, the system will need a signature
249
301
  // this state represent the fact and require another user interaction to request the signature
250
- | WalletConnected<WalletProviderType>
302
+ | WalletConnected<WalletProviderType, WS>
251
303
  // This state is triggered once the signature is requested, the user will have to confirm with its wallet
252
- | WaitingForSignature<WalletProviderType>
304
+ | WaitingForSignature<WalletProviderType, WS>
253
305
  // Finally the user is fully signed in
254
306
  // wallet?.accountChanged if set, represent the fact that the user has changed its web3-wallet accounnt.
255
307
  // wallet?.invalidChainId if set, represent the fact that the wallet is connected to a different chain.
256
308
  // wallet?.switchingChain if set, represent the fact that the user is currently switching chain.
257
309
  // a notification could be shown to the user so that he can switch the app to use that other account.
258
- | SignedIn<WalletProviderType>
259
- );
310
+ | SignedIn<WalletProviderType, WS>;
311
+
312
+ export type Connection<WalletProviderType> = ConnectionCommon<WalletProviderType> & ConnectionSteps<WalletProviderType>;
313
+
314
+ // What the store's internal `set` accepts: a connection WITHOUT `pendingRequests`, at either level,
315
+ // because `set` is the one place that fills them in from the wrapper on every publish. Every state
316
+ // the store publishes therefore reports the requests the user's wallet is actually holding,
317
+ // including the states that carry no wallet at all.
318
+ //
319
+ // Expressed as a TYPE rather than as a convention on purpose. The rule used to be "remember to copy
320
+ // the list at every construction", which held at nine sites and was never going to hold at the
321
+ // tenth. Here a construction site cannot supply the field at all, so there is nothing to remember
322
+ // and nothing to get wrong.
323
+ type ConnectionInput<WalletProviderType> = Omit<ConnectionCommon<WalletProviderType>, 'pendingRequests'> &
324
+ ConnectionSteps<WalletProviderType, WalletStateInput<WalletProviderType>>;
260
325
 
261
326
  // Type for SignedIn state that was reached via wallet authentication (not popup-based auth)
262
327
  // This variant always has wallet and WalletMechanism
@@ -757,36 +822,6 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
757
822
  requestsPerSecond: settings.requestsPerSecond,
758
823
  });
759
824
 
760
- // HOW `wallet.pendingRequests` IS MAINTAINED, and the rule every wallet-state rebuild follows.
761
- //
762
- // The wrapper owns the list; the store only mirrors it. That mirror is written HERE, on request
763
- // events, and nowhere else — so any other code that builds a `wallet` object must copy the
764
- // current list rather than assert an empty one.
765
- //
766
- // Asserting `[]` is not a harmless guess, it ERASES an outstanding request, and permanently: the
767
- // next event for that request is the one that ends it, which writes an empty list too, so nothing
768
- // ever puts it back. The user is left holding a wallet popup that the app believes does not
769
- // exist. That was a real bug, and the flow that caused it is the ordinary one: a send against a
770
- // LOCKED wallet raises the connection flow, so `connect()` runs while the wallet is holding the
771
- // transaction and rebuilt the state under it. See
772
- // `docs/adr/0001-wallet-requests-are-announced-through-the-wrapper.md`.
773
- //
774
- // Hence `alwaysOnProviderWrapper.getPendingRequests()` at every `wallet: {...}` construction
775
- // below, rather than the literal.
776
- const unsubscribeRequestEvents = alwaysOnProviderWrapper.onRequest(() => {
777
- // Only update if we have a wallet connected
778
- if ($connection.wallet) {
779
- const currentPending = alwaysOnProviderWrapper.getPendingRequests();
780
- set({
781
- ...$connection,
782
- wallet: {
783
- ...$connection.wallet,
784
- pendingRequests: currentPending,
785
- },
786
- });
787
- }
788
- });
789
-
790
825
  // Determine target step (defaults to 'SignedIn')
791
826
  const targetStep: TargetStep = settings.targetStep || 'SignedIn';
792
827
 
@@ -803,13 +838,113 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
803
838
  const requestSignatureAutomaticallyIfPossible =
804
839
  targetStep === 'SignedIn' ? settings.requestSignatureAutomaticallyIfPossible || false : false;
805
840
 
806
- let $connection: Connection<WalletProviderType> = {step: 'Idle', loading: true, wallet: undefined, wallets: []};
841
+ // The list as last published. Kept so that an UNCHANGED list keeps its identity across publishes:
842
+ // the wrapper hands back a fresh array every call, and publishing a new array (and so a new
843
+ // `wallet` object) on every unrelated `set` would invalidate `derived` stores, `{#key}` blocks and
844
+ // effect dependencies in consumers for no reason. Requests are compared by identity because a
845
+ // `PendingRequest` is created once and never mutated.
846
+ let publishedPendingRequests: PendingRequest[] = [];
847
+ function currentPendingRequests(): PendingRequest[] {
848
+ const latest = alwaysOnProviderWrapper.getPendingRequests();
849
+ if (
850
+ latest.length === publishedPendingRequests.length &&
851
+ latest.every((request, i) => request === publishedPendingRequests[i])
852
+ ) {
853
+ return publishedPendingRequests;
854
+ }
855
+ publishedPendingRequests = latest;
856
+ return latest;
857
+ }
858
+
859
+ let $connection: Connection<WalletProviderType> = {
860
+ step: 'Idle',
861
+ loading: true,
862
+ wallet: undefined,
863
+ wallets: [],
864
+ pendingRequests: currentPendingRequests(),
865
+ };
807
866
  const _store = writable<Connection<WalletProviderType>>($connection);
808
- function set(connection: Connection<WalletProviderType>) {
809
- $connection = connection;
867
+ // THE ONE PLACE A PUBLISHED STATE IS BUILT, which is what makes the announcement rule a
868
+ // property of the store rather than a habit of whoever wrote the last rebuild.
869
+ //
870
+ // `pendingRequests` is stamped here from the wrapper, so no caller can assert an empty list and
871
+ // none has to remember to copy one. `ConnectionInput` does not even carry the field, so the rule
872
+ // is now enforced by the type rather than by nine identical call sites — and by the tenth kind of
873
+ // site, the paths that build NO wallet, which was not a call site at all and so lost the list
874
+ // silently.
875
+ //
876
+ // The deprecated `wallet.pendingRequests` mirror is stamped from the same read, so the two cannot
877
+ // drift while consumers migrate.
878
+ function set(connection: ConnectionInput<WalletProviderType>) {
879
+ // A STATE THAT SHOWS NO WALLET MUST NOT LEAVE ONE LIVE, and this is where that is made true
880
+ // rather than at each of the eleven places that used to remember it. Two of those eleven did
881
+ // not: a bare `connect()` landing on `MechanismToChoose`, and a sign-in popup launched by a
882
+ // user who was already wallet-connected. Both left the wrapper holding the wallet with its
883
+ // status still `connected`, so it kept SIGNING for a state showing no wallet.
884
+ //
885
+ // `WaitingForWalletConnection` is the one exception, and it is a real one rather than an
886
+ // oversight: it is the in-progress step of `connect` itself, which shows no wallet precisely
887
+ // because it is in the middle of registering one. Every other wallet-less step is somewhere the
888
+ // flow RESTS.
889
+ //
890
+ // Enforced here rather than asserted because the failure directions are not symmetric. A
891
+ // forgotten teardown keeps a wallet signing invisibly, which is the bug this exists to stop; an
892
+ // unwanted one makes reads fall back to the configured endpoint and signing refuse, which is
893
+ // loud and safe. So the automatic behaviour is the conservative one.
894
+ if (!connection.wallet && connection.step !== 'WaitingForWalletConnection') {
895
+ teardownWallet();
896
+ }
897
+ const pendingRequests = currentPendingRequests();
898
+ if (!connection.wallet) {
899
+ $connection = {...connection, pendingRequests};
900
+ _store.set($connection);
901
+ return $connection;
902
+ }
903
+ // Callers hand back a wallet they spread from the published state, so it usually already
904
+ // carries the mirror. Read through a widened view rather than rebuilding blindly: when the
905
+ // list has not changed, the wallet object keeps its identity and consumers' `derived` stores,
906
+ // `{#key}` blocks and effect dependencies do not re-run on an unrelated publish.
907
+ const incomingWallet = connection.wallet as WalletStateInput<WalletProviderType> & {
908
+ pendingRequests?: PendingRequest[];
909
+ };
910
+ $connection = {
911
+ ...connection,
912
+ pendingRequests,
913
+ wallet:
914
+ incomingWallet.pendingRequests === pendingRequests
915
+ ? (incomingWallet as WalletState<WalletProviderType>)
916
+ : {...connection.wallet, pendingRequests},
917
+ };
810
918
  _store.set($connection);
811
919
  return $connection;
812
920
  }
921
+
922
+ // HOW `pendingRequests` IS MAINTAINED.
923
+ //
924
+ // The wrapper owns the list; the store only mirrors it. The mirror is stamped in `set` above, on
925
+ // EVERY publish, so a state cannot be built that contradicts the wrapper — including one that
926
+ // carries no wallet. This subscription's job is only to make the store publish again when the
927
+ // list changes, since a request starting or ending is not otherwise a state transition.
928
+ //
929
+ // The rule exists because asserting `[]` is not a harmless guess: it ERASES an outstanding
930
+ // request, and permanently, since the next event for that request is the one that ends it, which
931
+ // writes an empty list too, so nothing ever puts it back. The user is left holding a wallet popup
932
+ // that the app believes does not exist. That was a real bug, and the flow that caused it is the
933
+ // ordinary one: a send against a LOCKED wallet raises the connection flow, so `connect()` runs
934
+ // while the wallet is holding the transaction and rebuilds the state under it. See
935
+ // `docs/adr/0001-wallet-requests-are-announced-through-the-wrapper.md`.
936
+ //
937
+ // Never unsubscribed, deliberately. It used to be torn down by `disconnect()`, which silenced
938
+ // request announcements for the REST OF THE CONNECTION'S LIFE, since nothing re-subscribes: a
939
+ // disconnect followed by a reconnect left the app blind to every subsequent wallet prompt. The
940
+ // wrapper is created here and lives exactly as long as this connection, so there is nothing to
941
+ // release.
942
+ alwaysOnProviderWrapper.onRequest(() => {
943
+ // Republish. `set` re-reads the wrapper, so this needs to say nothing about the list itself,
944
+ // and it must run whether or not a wallet is currently in the state: a request outstanding
945
+ // while the flow rests on `wallet: undefined` is exactly the case that used to go unreported.
946
+ set($connection);
947
+ });
813
948
  // Where the flow comes to rest when a connection attempt fails.
814
949
  //
815
950
  // The rule: rest on the step that offers the user a real next decision, and never on a step this app has
@@ -825,10 +960,7 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
825
960
  // no decision to offer them. A cancelled popup is likewise a cancellation, not a failure, and rests on `Idle`.
826
961
  function setConnectionFailure(error: {message: string; cause?: any}) {
827
962
  const wallets = $connection.wallets;
828
- // The resting states below all have `wallet: undefined`: tear down any live wallet
829
- // first, or the wrapper would keep routing — and, while its status is 'connected',
830
- // even SIGNING — through a wallet the state no longer shows.
831
- teardownWallet();
963
+ // Every resting state below has `wallet: undefined`, so `set` tears the live wallet down.
832
964
  if (!walletOnly) {
833
965
  set({step: 'MechanismToChoose', wallets, wallet: undefined, error});
834
966
  } else if (wallets.length > 1) {
@@ -974,7 +1106,6 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
974
1106
  chainId,
975
1107
  invalidChainId: alwaysOnChainId != chainId,
976
1108
  switchingChain: false,
977
- pendingRequests: alwaysOnProviderWrapper.getPendingRequests(),
978
1109
  },
979
1110
  });
980
1111
  alwaysOnProviderWrapper.setWalletStatus('connected');
@@ -982,10 +1113,8 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
982
1113
  watchForAccountChange(walletProvider);
983
1114
  })
984
1115
  .catch((err) => {
985
- // The wallet may have been registered on the wrapper before the
986
- // failure (e.g. getAccounts threw): tear it down — Idle carries no
987
- // wallet, so it must not keep routing requests.
988
- teardownWallet();
1116
+ // The wallet may have been registered on the wrapper before the failure (e.g.
1117
+ // getAccounts threw). `set` tears it down: Idle carries no wallet.
989
1118
  set({step: 'Idle', loading: false, wallet: undefined, wallets: $connection.wallets});
990
1119
  });
991
1120
  } else {
@@ -1030,15 +1159,12 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
1030
1159
  chainId,
1031
1160
  invalidChainId: alwaysOnChainId != chainId,
1032
1161
  switchingChain: false,
1033
- pendingRequests: alwaysOnProviderWrapper.getPendingRequests(),
1034
1162
  },
1035
1163
  });
1036
1164
  })
1037
1165
  .catch((err) => {
1038
- // The wallet may have been registered on the wrapper before the
1039
- // failure (e.g. getAccounts threw): tear it down — Idle carries no
1040
- // wallet, so it must not keep routing requests.
1041
- teardownWallet();
1166
+ // The wallet may have been registered on the wrapper before the failure (e.g.
1167
+ // getAccounts threw). `set` tears it down: Idle carries no wallet.
1042
1168
  set({step: 'Idle', loading: false, wallet: undefined, wallets: $connection.wallets});
1043
1169
  });
1044
1170
  } else {
@@ -1077,7 +1203,6 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
1077
1203
  chainId,
1078
1204
  invalidChainId: alwaysOnChainId != chainId,
1079
1205
  switchingChain: false,
1080
- pendingRequests: alwaysOnProviderWrapper.getPendingRequests(),
1081
1206
  },
1082
1207
  account: {address: lastWallet.address},
1083
1208
  });
@@ -1086,10 +1211,8 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
1086
1211
  watchForAccountChange(walletProvider);
1087
1212
  })
1088
1213
  .catch((err) => {
1089
- // The wallet may have been registered on the wrapper before the
1090
- // failure (e.g. getAccounts threw): tear it down — Idle carries no
1091
- // wallet, so it must not keep routing requests.
1092
- teardownWallet();
1214
+ // The wallet may have been registered on the wrapper before the failure (e.g.
1215
+ // getAccounts threw). `set` tears it down: Idle carries no wallet.
1093
1216
  set({step: 'Idle', loading: false, wallet: undefined, wallets: $connection.wallets});
1094
1217
  });
1095
1218
  } else {
@@ -1503,15 +1626,58 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
1503
1626
  chainId,
1504
1627
  invalidChainId: alwaysOnChainId != chainId,
1505
1628
  switchingChain: false,
1506
- pendingRequests: alwaysOnProviderWrapper.getPendingRequests(),
1507
1629
  },
1508
1630
  error: {message: errorMessage, cause},
1509
1631
  });
1510
1632
  return true;
1511
1633
  }
1512
1634
 
1635
+ // WHAT `connect` MEANS, AND WHY IT IS NOT WHAT `ensureConnected` MEANS.
1636
+ //
1637
+ // `connect` drives the flow from the USER'S CHOICE. A bare `connect()` means "the user wants to
1638
+ // connect something", so with nothing naming a wallet it opens the picker — including from a
1639
+ // state that already has a wallet, which is how a consumer's switch-wallet button works. It does
1640
+ // not inspect the wallet's status, and it does not acquire a second meaning on a locked one.
1641
+ //
1642
+ // `ensureConnected` promises a TARGET instead, so it must do whatever reaching that target takes.
1643
+ // That is why it, and only it, reconnects a `WalletConnected` wallet that has gone locked or
1644
+ // disconnected: it cannot hand back a connection the caller can use otherwise. Hence this helper
1645
+ // having exactly one caller, which is not an oversight.
1646
+ //
1647
+ // `unlock()` is the narrow remedy in between, and is the one to reach for on a locked wallet: it
1648
+ // prompts the wallet and KEEPS the step, the account and the wallet, where re-running the flow
1649
+ // rebuilds all three. `wallet.status` is published precisely so a consumer can route on it and
1650
+ // offer "Unlock" rather than "Connect" when it says `locked`.
1651
+ //
1652
+ // The asymmetry is DELIBERATE, and used to be only implicit, which is how it came to be read as a
1653
+ // bug: a bare `connect()` on a locked wallet lands on the picker, and the picker tears the live
1654
+ // wallet down. What made that look destructive was a SEPARATE defect, now fixed — the teardown
1655
+ // also erased the announcement of whatever the wallet was still holding. It no longer does, since
1656
+ // `pendingRequests` lives on the connection and survives a state with no wallet, so the picker
1657
+ // costs a click and nothing else.
1658
+ //
1659
+ // Reasoned through in `docs/adr/0002-connect-ensure-connected-and-unlock-are-three-promises.md`,
1660
+ // including the version of this that made `connect` reconnect too, and why it was rejected. The
1661
+ // three behaviours are pinned side by side in `test/locked-wallet-reconnect.test.ts`, so that
1662
+ // collapsing any one of them into another fails.
1663
+ function mechanismToReconnect(): WalletMechanism<string, `0x${string}`> | undefined {
1664
+ if (
1665
+ $connection.step === 'WalletConnected' &&
1666
+ ($connection.wallet.status === 'locked' || $connection.wallet.status === 'disconnected')
1667
+ ) {
1668
+ return $connection.mechanism;
1669
+ }
1670
+ return undefined;
1671
+ }
1672
+
1513
1673
  let remember: boolean = false;
1514
- async function connect(mechanism?: Mechanism, options?: ConnectOptions) {
1674
+ /**
1675
+ * @param internal not part of the public `connect` surface. `addressIsPreference` marks a
1676
+ * mechanism this library REUSED from the current state rather than one the caller asked for, so
1677
+ * that a vanished address degrades to an ordinary connect instead of failing the attempt. See
1678
+ * `resolveRequestedAddress` below.
1679
+ */
1680
+ async function connect(mechanism?: Mechanism, options?: ConnectOptions, internal?: {addressIsPreference?: boolean}) {
1515
1681
  if (!mechanism && (targetStep === 'WalletConnected' || walletOnly)) {
1516
1682
  mechanism = {type: 'wallet'};
1517
1683
  }
@@ -1526,6 +1692,29 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
1526
1692
  const chosenMechanismBeforeConnect = $connection.step === 'WalletChosen' ? $connection.mechanism : undefined;
1527
1693
  const chosenWalletBeforeConnect = $connection.step === 'WalletChosen' ? _wallet : undefined;
1528
1694
  const specificAddress = mechanism.address;
1695
+ // WHICH ACCOUNT THE ATTEMPT IS FOR, once the wallet has said what it has.
1696
+ //
1697
+ // An address the CALLER named is a demand: `connectToAddress(a)` and
1698
+ // `connect({type: 'wallet', address: a})` mean that account and no other, so a wallet that
1699
+ // cannot offer it fails the attempt rather than connecting to something else.
1700
+ //
1701
+ // An address this library REUSED is only a preference. `ensureConnected` reconnects a
1702
+ // locked wallet by replaying the mechanism the connection already had, which keeps the
1703
+ // ordinary case (unlock, come back to the same account) from bouncing a multi-account user
1704
+ // into the account picker. But the user is free to unlock on a DIFFERENT account, and then
1705
+ // the replayed address names something the wallet no longer has. Treating that as a demand
1706
+ // threw, which landed in the catch and tore the wallet down: the reconnect performed the
1707
+ // very teardown it exists to prevent, one step later. Degrading to an ordinary connect is
1708
+ // what the caller asked for anyway, since it asked to be connected and named nothing.
1709
+ const resolveRequestedAddress = (available: `0x${string}`[]): `0x${string}` | undefined => {
1710
+ if (!specificAddress || available.includes(specificAddress)) {
1711
+ return specificAddress;
1712
+ }
1713
+ if (internal?.addressIsPreference) {
1714
+ return undefined;
1715
+ }
1716
+ throw new Error(`could not find address ${specificAddress}`);
1717
+ };
1529
1718
  const walletName =
1530
1719
  mechanism.name ||
1531
1720
  ($connection.step === 'WalletChosen' ? $connection.mechanism.name : undefined) ||
@@ -1573,21 +1762,14 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
1573
1762
  accounts = await provider.requestAccounts();
1574
1763
  accounts = accounts.map((v) => v.toLowerCase()) as `0x${string}`[];
1575
1764
  if (accounts.length > 0) {
1765
+ const requestedAddress = resolveRequestedAddress(accounts);
1576
1766
  const nextStep =
1577
- !settings?.useCurrentAccount && !specificAddress && accounts.length > 1
1767
+ !settings?.useCurrentAccount && !requestedAddress && accounts.length > 1
1578
1768
  ? 'ChooseWalletAccount'
1579
1769
  : 'WalletConnected';
1580
- let account = accounts[0];
1581
- if (specificAddress) {
1582
- if (accounts.find((v) => v === specificAddress)) {
1583
- account = specificAddress;
1584
- } else {
1585
- // TODO error
1586
- throw new Error(`could not find address ${specificAddress}`);
1587
- }
1588
- }
1770
+ const account = requestedAddress || accounts[0];
1589
1771
 
1590
- const newState: Connection<WalletProviderType> =
1772
+ const newState: ConnectionInput<WalletProviderType> =
1591
1773
  nextStep === 'ChooseWalletAccount'
1592
1774
  ? {
1593
1775
  step: nextStep,
@@ -1602,7 +1784,6 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
1602
1784
  chainId,
1603
1785
  invalidChainId: alwaysOnChainId != chainId,
1604
1786
  switchingChain: false,
1605
- pendingRequests: alwaysOnProviderWrapper.getPendingRequests(),
1606
1787
  },
1607
1788
  }
1608
1789
  : {
@@ -1620,7 +1801,6 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
1620
1801
  chainId,
1621
1802
  invalidChainId: alwaysOnChainId != chainId,
1622
1803
  switchingChain: false,
1623
- pendingRequests: alwaysOnProviderWrapper.getPendingRequests(),
1624
1804
  },
1625
1805
  account: {address: account},
1626
1806
  };
@@ -1660,20 +1840,13 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
1660
1840
  }
1661
1841
  }
1662
1842
  } else {
1663
- let account = accounts[0];
1664
- if (specificAddress) {
1665
- if (accounts.find((v) => v === specificAddress)) {
1666
- account = specificAddress;
1667
- } else {
1668
- // TODO error
1669
- throw new Error(`could not find address ${specificAddress}`);
1670
- }
1671
- }
1843
+ const requestedAddress = resolveRequestedAddress(accounts);
1844
+ const account = requestedAddress || accounts[0];
1672
1845
  const nextStep =
1673
- !settings?.useCurrentAccount && !specificAddress && accounts.length > 1
1846
+ !settings?.useCurrentAccount && !requestedAddress && accounts.length > 1
1674
1847
  ? 'ChooseWalletAccount'
1675
1848
  : 'WalletConnected';
1676
- const newState: Connection<WalletProviderType> =
1849
+ const newState: ConnectionInput<WalletProviderType> =
1677
1850
  nextStep === 'ChooseWalletAccount'
1678
1851
  ? {
1679
1852
  step: nextStep,
@@ -1687,7 +1860,6 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
1687
1860
  chainId,
1688
1861
  invalidChainId: alwaysOnChainId != chainId,
1689
1862
  switchingChain: false,
1690
- pendingRequests: alwaysOnProviderWrapper.getPendingRequests(),
1691
1863
  },
1692
1864
  }
1693
1865
  : {
@@ -1705,7 +1877,6 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
1705
1877
  chainId,
1706
1878
  invalidChainId: alwaysOnChainId != chainId,
1707
1879
  switchingChain: false,
1708
- pendingRequests: alwaysOnProviderWrapper.getPendingRequests(),
1709
1880
  },
1710
1881
  account: {address: account},
1711
1882
  };
@@ -1773,9 +1944,13 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
1773
1944
  // mechanism: { type: 'wallet', wallet: undefined }
1774
1945
  // });
1775
1946
 
1776
- // The picker state drops the wallet, so any live one must be torn down here or
1777
- // the wrapper would keep routing through a wallet the state no longer shows.
1778
- teardownWallet();
1947
+ // Reached from a state that HAS a wallet whenever nothing names one: a bare
1948
+ // `connect()` with several wallets announced, including on a locked wallet. That is
1949
+ // this function's contract, not an oversight — see the note on `mechanismToReconnect`
1950
+ // above for why `connect`, `ensureConnected` and `unlock` mean three different things
1951
+ // here, and why a consumer facing a locked wallet wants `unlock()`. The picker state
1952
+ // drops the wallet and `set` tears it down; whatever it is still holding stays
1953
+ // announced, on `pendingRequests`.
1779
1954
  set({
1780
1955
  step: 'WalletToChoose',
1781
1956
  mechanism: {type: 'wallet'},
@@ -1814,6 +1989,19 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
1814
1989
  decryptKeyPair,
1815
1990
  domainRedirectPublicKeyB64,
1816
1991
  });
1992
+ // This attempt's popup, kept so the handlers below can tell "my popup finished" from "a
1993
+ // later launch replaced me". Launching a second popup rejects the first, and without this
1994
+ // the first attempt's failure handler would land on `Idle` on top of the second attempt.
1995
+ const launchedPopup = popup;
1996
+ // `PopupLaunched` carries no wallet, so `set` tears down the one a user who was already
1997
+ // wallet-connected had: it must stop being able to sign from the moment the popup opens,
1998
+ // not whenever the popup happens to finish.
1999
+ //
2000
+ // Under `prioritizeWalletProvider` that also stops READS routing through it for the
2001
+ // popup's duration; they fall back to the configured endpoint, which still answers. Same
2002
+ // trade `back()` and `cancel()` make, and the right way round: a read served by the
2003
+ // endpoint is correct, a signature served by a wallet the state does not show is the
2004
+ // hazard.
1817
2005
  set({
1818
2006
  step: 'PopupLaunched',
1819
2007
  popupClosed: false,
@@ -1823,7 +2011,7 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
1823
2011
  });
1824
2012
 
1825
2013
  const unsubscribe = popup.subscribe(($popup) => {
1826
- if ($connection?.step === 'PopupLaunched') {
2014
+ if (popup === launchedPopup && $connection?.step === 'PopupLaunched') {
1827
2015
  if ($popup.closed) {
1828
2016
  set({
1829
2017
  ...$connection,
@@ -1865,6 +2053,15 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
1865
2053
  // reason is added, which is what `ensureConnected` reports instead of "Connection cancelled".
1866
2054
  const refusal = err as {type?: string; message?: string} | undefined;
1867
2055
  const canceled = !refusal || refusal.type === 'cancelation';
2056
+ // Only this attempt's failure, and only while this attempt still owns the flow.
2057
+ //
2058
+ // `cancel()` and `back(step)` settle this promise on purpose (that is what makes an
2059
+ // awaited `connect()` return at all), and they have ALREADY chosen where the flow comes
2060
+ // to rest. Landing on `Idle` here as well would overrule them, so `back('MechanismToChoose')`
2061
+ // during a popup would bounce the user to `Idle` a microtask later.
2062
+ if (popup !== launchedPopup || $connection.step !== 'PopupLaunched') {
2063
+ return;
2064
+ }
1868
2065
  set({
1869
2066
  step: 'Idle',
1870
2067
  loading: false,
@@ -1877,6 +2074,7 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
1877
2074
  }
1878
2075
  }
1879
2076
  } else {
2077
+ // The mechanism picker drops the wallet, and `set` tears the live one down with it.
1880
2078
  set({
1881
2079
  step: 'MechanismToChoose',
1882
2080
  wallets: $connection.wallets,
@@ -1959,6 +2157,8 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
1959
2157
  WalletChosen<WalletProviderType> | WalletConnected<WalletProviderType> | SignedIn<WalletProviderType>
1960
2158
  >((resolve, reject) => {
1961
2159
  let forceConnect = false;
2160
+ // Whether the mechanism below was REPLAYED from the current state rather than asked for.
2161
+ let reconnecting = false;
1962
2162
 
1963
2163
  // The error (if any) already sitting in the store before we start.
1964
2164
  // Only an error that appears after this point tells us that *our* attempt failed.
@@ -1988,12 +2188,14 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
1988
2188
  return true;
1989
2189
  };
1990
2190
 
1991
- if (
1992
- $connection.step == 'WalletConnected' &&
1993
- ($connection.wallet.status == 'locked' || $connection.wallet.status === 'disconnected')
1994
- ) {
2191
+ const reconnect = mechanismToReconnect();
2192
+ if (reconnect) {
2193
+ // we reuse existing mechanism as we just want to reconnect
1995
2194
  forceConnect = true;
1996
- mechanism = $connection.mechanism; // we reuse existing mechanism as we just want to reconnect
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;
1997
2199
  } else if (canResolve($connection)) {
1998
2200
  // Only resolve if step matches AND chain is valid (or skipChainCheck)
1999
2201
  resolve($connection as any);
@@ -2015,7 +2217,7 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
2015
2217
  : undefined;
2016
2218
  selectWallet(walletName, opts);
2017
2219
  } else {
2018
- connect(mechanism, opts);
2220
+ connect(mechanism, opts, {addressIsPreference: reconnecting});
2019
2221
  }
2020
2222
  }
2021
2223
 
@@ -2086,8 +2288,11 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
2086
2288
  function disconnect() {
2087
2289
  deleteOriginAccount();
2088
2290
  deleteLastWallet();
2089
- teardownWallet();
2090
- unsubscribeRequestEvents();
2291
+ // The wallet goes with the Idle state below, via `set`.
2292
+ // Request announcements are NOT torn down here. Disconnecting drops this app's wallet state;
2293
+ // it does not reach into the user's wallet and withdraw a prompt already on their screen, and
2294
+ // nothing re-subscribes, so unsubscribing here left the connection permanently unable to
2295
+ // report any wallet request for the rest of its life.
2091
2296
  set({
2092
2297
  step: 'Idle',
2093
2298
  loading: false,
@@ -2110,10 +2315,8 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
2110
2315
  async function selectWallet(name?: string, options?: {doNotStoreLocally?: boolean}) {
2111
2316
  const walletName = name || ($connection.wallets.length == 1 ? $connection.wallets[0].info.name : undefined);
2112
2317
  if (!walletName) {
2113
- // Multiple wallets, no name specified - show picker. The picker state drops the
2114
- // wallet, so a previously chosen one must be torn down here or the wrapper would
2115
- // keep routing through a wallet the state no longer shows.
2116
- teardownWallet();
2318
+ // Multiple wallets, no name specified - show picker. The picker state drops the wallet, so
2319
+ // `set` tears down a previously chosen one rather than leaving it routing.
2117
2320
  set({
2118
2321
  step: 'WalletToChoose',
2119
2322
  mechanism: {type: 'wallet'},
@@ -2166,7 +2369,6 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
2166
2369
  chainId,
2167
2370
  invalidChainId: alwaysOnChainId != chainId,
2168
2371
  switchingChain: false,
2169
- pendingRequests: alwaysOnProviderWrapper.getPendingRequests(),
2170
2372
  },
2171
2373
  });
2172
2374
  } catch (err) {
@@ -2179,10 +2381,7 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
2179
2381
 
2180
2382
  function back(step: 'MechanismToChoose' | 'Idle' | 'WalletToChoose') {
2181
2383
  popup?.cancel();
2182
- // Every back() target drops the wallet from the state, so the live wallet goes
2183
- // with it: leaving it would let the wrapper keep routing (and signing) through a
2184
- // wallet the state no longer shows.
2185
- teardownWallet();
2384
+ // Every back() target drops the wallet from the state, and `set` takes the live one with it.
2186
2385
  if (step === 'MechanismToChoose') {
2187
2386
  set({step, wallets: $connection.wallets, wallet: undefined});
2188
2387
  } else if (step === 'Idle') {
@@ -2300,10 +2499,7 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
2300
2499
  function cancel() {
2301
2500
  popup?.cancel();
2302
2501
  deleteLastWallet();
2303
- // Landing on Idle drops the wallet from the state: tear it down too, or the
2304
- // wrapper would keep routing (and, while its status is 'connected', SIGNING)
2305
- // through a wallet the state no longer shows.
2306
- teardownWallet();
2502
+ // Landing on Idle drops the wallet from the state, and `set` tears it down with it.
2307
2503
  set({step: 'Idle', wallet: undefined, loading: false, wallets: $connection.wallets});
2308
2504
  }
2309
2505
 
@@ -2394,7 +2590,13 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
2394
2590
  );
2395
2591
  }
2396
2592
 
2397
- function getSignatureForPublicKeyPublication(): Promise<`0x${string}`> {
2593
+ // `async` is load-bearing, not decoration: without it the `throw`s below leave this function
2594
+ // SYNCHRONOUSLY while its signature promises a rejection, so
2595
+ // `getSignatureForPublicKeyPublication().catch(showTheReason)` never runs its handler and the
2596
+ // app gets an uncaught exception instead of the reason. `getDelegation` beside it is async and
2597
+ // rejects, and two siblings on the same object failing in two different ways is a difference
2598
+ // nothing in either signature would warn a caller about.
2599
+ async function getSignatureForPublicKeyPublication(): Promise<`0x${string}`> {
2398
2600
  if ($connection.step !== 'SignedIn') {
2399
2601
  throw new Error('Not signed in');
2400
2602
  }
@@ -2482,16 +2684,14 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
2482
2684
  // this will be taken care with `chainChanged` (but maybe it should be done there ?)
2483
2685
  // handleNetwork(chainId);
2484
2686
  } else {
2485
- if ($connection.wallet) {
2486
- set({
2487
- ...$connection,
2488
- wallet: {...$connection.wallet, switchingChain: false},
2489
- error: {
2490
- message: `Failed to switch to ${params?.chainName || `chain with id = ${chainId}`}`,
2491
- cause: result,
2492
- },
2493
- });
2494
- }
2687
+ // A non-null RESULT is how these methods report an error without throwing, so this is a
2688
+ // failure and not a value. It is reported by THROWING and nothing else, because this
2689
+ // throw lands in the catch below, which may still recover by adding the chain.
2690
+ //
2691
+ // Setting an error here as well used to leave `Failed to switch to <chain>` on the state
2692
+ // after a recovery that WORKED: the add path spreads `...$connection` on its way out and
2693
+ // carried it along, so the user ended up on the requested chain being told it had failed.
2694
+ // Whoever gives up sets the error; nobody sets one on the way past.
2495
2695
  throw result;
2496
2696
  }
2497
2697
  } catch (err) {
@@ -2577,6 +2777,8 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
2577
2777
  }
2578
2778
  }
2579
2779
  } else {
2780
+ // Nothing left to try: the wallet cannot switch to this chain and there is no rpcUrl to add
2781
+ // it with. This is where the flow gives up, so this is where the error is set.
2580
2782
  const errorMessage = `Chain "${params?.chainName || `with chainId = ${chainId}`} " is not available on your wallet`;
2581
2783
  if ($connection.wallet) {
2582
2784
  set({
@@ -2584,6 +2786,9 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
2584
2786
  wallet: {...$connection.wallet, switchingChain: false},
2585
2787
  error: {
2586
2788
  message: errorMessage,
2789
+ // What the wallet actually said, which is otherwise lost: this branch is reached
2790
+ // both from a refusal and from a wallet reporting an error as a result.
2791
+ cause: err,
2587
2792
  },
2588
2793
  });
2589
2794
  }