@etherplay/connect 0.13.0 → 0.14.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@etherplay/connect",
3
- "version": "0.13.0",
3
+ "version": "0.14.0",
4
4
  "description": "Main connection library for Etherplay Accounts - provides seamless wallet and social authentication with session account management",
5
5
  "keywords": [
6
6
  "web3",
@@ -45,9 +45,9 @@
45
45
  ],
46
46
  "dependencies": {
47
47
  "sveltore": "^1.0.0",
48
- "@etherplay/connect-core": "0.7.2",
49
- "@etherplay/wallet-connector": "0.1.0",
50
- "@etherplay/wallet-connector-ethereum": "0.1.0"
48
+ "@etherplay/connect-core": "0.7.3",
49
+ "@etherplay/wallet-connector": "0.2.0",
50
+ "@etherplay/wallet-connector-ethereum": "0.1.1"
51
51
  },
52
52
  "devDependencies": {
53
53
  "@vitest/coverage-v8": "^4.0.18",
package/src/index.ts CHANGED
@@ -1,12 +1,14 @@
1
1
  import type {
2
2
  WalletConnector,
3
3
  WalletHandle,
4
+ WalletInfo,
4
5
  WalletProvider,
5
6
  PendingRequest,
6
7
  RequestEvent,
7
8
  RequestEventHandler,
8
9
  RequestPurpose,
9
10
  } from '@etherplay/wallet-connector';
11
+ import {walletPrompts} from '@etherplay/wallet-connector';
10
12
  import {EthereumWalletConnector, type UnderlyingEthereumProvider} from '@etherplay/wallet-connector-ethereum';
11
13
  import {writable} from 'sveltore';
12
14
  import {createPopupLauncher, type PopupPromise} from './popup.js';
@@ -49,6 +51,12 @@ export type {OriginAccount, AuthMechanism, PermissionRequest, PermissionOutcome,
49
51
  // "your wallet is asking for something" can name WHICH thing without a second dependency.
50
52
  export type {PendingRequest, RequestEvent, RequestEventHandler, RequestPurpose};
51
53
 
54
+ // What a caller needs to BRING a wallet (`wallets`) or to read what one declared, for the same
55
+ // reason: an app that hands this library a wallet of its own should not need a second dependency
56
+ // to name the shape of the thing it is handing over.
57
+ export type {WalletHandle, WalletInfo, WalletProvider, WalletConnector};
58
+ export {walletPrompts};
59
+
52
60
  export type {UnderlyingEthereumProvider};
53
61
 
54
62
  export type BasicChainInfo = {
@@ -271,6 +279,30 @@ function describeAddressUnavailable(details: {
271
279
 
272
280
  type WalletStateCommon<WalletProviderType> = {
273
281
  provider: WalletProvider<WalletProviderType>;
282
+ /**
283
+ * WHICH wallet this is: the `info` of the handle the provider came from, name, icon and
284
+ * `autoApproves` included.
285
+ *
286
+ * Stamped by `set` rather than supplied, for the same reason `pendingRequests` is (see the ADR): a
287
+ * fact that every construction site would otherwise have to remember to copy is a fact in the wrong
288
+ * place. No construction site can supply one, because `WalletStateInput` omits it.
289
+ *
290
+ * It exists because the state that says a wallet is CONNECTED said nothing about which wallet it
291
+ * was: a consumer had to take `mechanism.name` and look it up in `wallets` to render the wallet's
292
+ * own name, and had to do the same to find out whether that wallet prompts at all. Reading
293
+ * `walletPrompts(connection.wallet.info)` is the whole of that question now.
294
+ *
295
+ * For every state this library builds it is the live wallet's own `info`, taken from the handle
296
+ * that was chosen, so it is exact. Two weaker cases exist and are worth knowing about:
297
+ *
298
+ * - ABSENT. A custom connector may hand over a provider that no announced handle belongs to, and a
299
+ * list in which that provider is ambiguous answers with nothing rather than with a guess. Absent
300
+ * means "not known", which `walletPrompts` reads as the loud default.
301
+ * - ONE PUBLISH STALE. A state spread from a published one keeps the `info` it was published with
302
+ * if the handle has since left the list, which beats a state that cannot say which wallet it is
303
+ * about. The next transition re-derives it.
304
+ */
305
+ info?: WalletInfo;
274
306
  accounts: `0x${string}`[];
275
307
  accountChanged?: `0x${string}`;
276
308
  chainId: string;
@@ -298,11 +330,11 @@ type WalletStatus =
298
330
 
299
331
  export type WalletState<WalletProviderType> = WalletStateCommon<WalletProviderType> & WalletStatus;
300
332
 
301
- // The same wallet state MINUS the deprecated list, which `set` stamps. Nothing inside this file
302
- // supplies `pendingRequests` when it builds a wallet: that is the whole point of having one
303
- // construction site, and this type is what stops a hand-written eleventh rebuild from supplying a
304
- // wrong one instead.
305
- type WalletStateInput<WalletProviderType> = Omit<WalletStateCommon<WalletProviderType>, 'pendingRequests'> &
333
+ // The same wallet state MINUS the fields `set` stamps: the deprecated request list, and the `info`
334
+ // of the wallet the provider belongs to. Nothing inside this file supplies either when it builds a
335
+ // wallet: that is the whole point of having one construction site, and this type is what stops a
336
+ // hand-written eleventh rebuild from supplying a wrong one instead.
337
+ type WalletStateInput<WalletProviderType> = Omit<WalletStateCommon<WalletProviderType>, 'pendingRequests' | 'info'> &
306
338
  WalletStatus;
307
339
 
308
340
  // The step types below take the wallet state as a parameter so that the same union can describe
@@ -942,51 +974,64 @@ export type AnyConnectionStore<WalletProviderType> =
942
974
 
943
975
  // Function overloads for proper typing
944
976
  //
945
- // `walletHost` is optional exactly when no popup can be reached: on both `WalletConnected`
946
- // overloads (which never sign in) and on the `walletOnly: true` `SignedIn` overloads (where
947
- // `connect` always defaults the mechanism to `{type: 'wallet'}`, so the mechanism picker is never
948
- // shown). It stays REQUIRED on the `walletOnly?: false` `SignedIn` overloads, which can reach the
949
- // hosted email/oauth/mnemonic popups. That split is the promise; see the README section
950
- // "Wallet-only sign-in with no backend", and `test/types/wallet-only-no-host.types.ts` which fails
951
- // to compile if it is flattened.
977
+ // ONE OVERLOAD PER CONFIGURATION, and the configuration is named by `targetStep` and `walletOnly`
978
+ // ONLY. Nothing else in the settings selects an overload, which is a property worth stating because
979
+ // it used to be false and cost a consumer real time.
980
+ //
981
+ // There used to be two overloads per configuration, split on `walletConnector`: one requiring it
982
+ // (generic in the provider type) and one requiring it to be ABSENT (pinned to the Ethereum
983
+ // connector). That made an ordinary optional setting into a discriminant, and a discriminant is a
984
+ // thing a caller must spell exactly:
985
+ //
986
+ // const settings = {...base, ...(connector ? {walletConnector: connector} : {})};
987
+ // createConnection(settings); // matched NEITHER overload
988
+ // createConnection({...base, walletConnector}); // `WalletConnector<P> | undefined` matched neither
989
+ // createConnection({...base, walletConnector: undefined}); // silently selected the OTHER one
990
+ //
991
+ // None of those are exotic: they are what building settings conditionally looks like. So the
992
+ // provider type is now a defaulted type parameter and `walletConnector` is an ordinary optional
993
+ // setting. With no connector and no other mention of the provider type there is nothing to infer
994
+ // from, and the default (`UnderlyingEthereumProvider`) applies, which is exactly what the removed
995
+ // overloads said. With a connector, `wallets`, or a `chainInfo` carrying a `provider`, the provider
996
+ // type is inferred from those. `test/types/connection-settings.types.ts` pins all of it, including
997
+ // the three call shapes above.
998
+ //
999
+ // `walletHost` is optional exactly when no popup can be reached: on `WalletConnected` and
1000
+ // `WalletChosen` (which never sign in) and on `walletOnly: true` `SignedIn` (where `connect` always
1001
+ // defaults the mechanism to `{type: 'wallet'}`, so the mechanism picker is never shown). It stays
1002
+ // REQUIRED on the `walletOnly?: false` `SignedIn` overload, which can reach the hosted
1003
+ // email/oauth/mnemonic popups. That split is the promise; see the README section "Wallet-only
1004
+ // sign-in with no backend", and `test/types/wallet-only-no-host.types.ts` which fails to compile if
1005
+ // it is flattened.
952
1006
  //
953
1007
  // The `WalletChosen` and `WalletConnected` overloads report `WalletOnly = true`, because that is
954
1008
  // what the runtime computes: `walletOnly = settings.walletOnly || targetStep === 'WalletChosen' ||
955
1009
  // targetStep === 'WalletConnected'`, so both stores always expose `walletOnly === true`.
956
1010
 
957
- // WalletChosen target with custom wallet connector - walletHost optional
958
- export function createConnection<WalletProviderType>(settings: {
1011
+ // WalletChosen target - walletHost optional
1012
+ export function createConnection<WalletProviderType = UnderlyingEthereumProvider>(settings: {
959
1013
  targetStep: 'WalletChosen';
960
1014
  walletHost?: string;
961
1015
  nodeURL?: string;
962
1016
  chainInfo: ChainInfo<WalletProviderType>;
963
- walletConnector: WalletConnector<WalletProviderType>;
1017
+ walletConnector?: WalletConnector<WalletProviderType> | undefined;
1018
+ // The wallets this app BRINGS. Supplying them replaces discovery: see the implementation
1019
+ // signature below, which is where that is explained.
1020
+ wallets?: WalletHandle<WalletProviderType>[] | undefined;
964
1021
  autoConnect?: boolean;
965
1022
  prioritizeWalletProvider?: boolean;
966
1023
  requestsPerSecond?: number;
967
1024
  storagePrefix?: string;
968
1025
  }): ConnectionStore<WalletProviderType, 'WalletChosen', true>;
969
1026
 
970
- // WalletChosen target with default Ethereum connector - walletHost optional
971
- export function createConnection(settings: {
972
- targetStep: 'WalletChosen';
973
- walletHost?: string;
974
- nodeURL?: string;
975
- chainInfo: ChainInfo<UnderlyingEthereumProvider>;
976
- walletConnector?: undefined;
977
- autoConnect?: boolean;
978
- prioritizeWalletProvider?: boolean;
979
- requestsPerSecond?: number;
980
- storagePrefix?: string;
981
- }): ConnectionStore<UnderlyingEthereumProvider, 'WalletChosen', true>;
982
-
983
- // WalletConnected target with custom wallet connector - walletHost optional
984
- export function createConnection<WalletProviderType>(settings: {
1027
+ // WalletConnected target - walletHost optional
1028
+ export function createConnection<WalletProviderType = UnderlyingEthereumProvider>(settings: {
985
1029
  targetStep: 'WalletConnected';
986
1030
  walletHost?: string;
987
1031
  nodeURL?: string;
988
1032
  chainInfo: ChainInfo<WalletProviderType>;
989
- walletConnector: WalletConnector<WalletProviderType>;
1033
+ walletConnector?: WalletConnector<WalletProviderType> | undefined;
1034
+ wallets?: WalletHandle<WalletProviderType>[] | undefined;
990
1035
  autoConnect?: boolean;
991
1036
  useCurrentAccount?: 'always' | 'whenSingle' | false;
992
1037
  prioritizeWalletProvider?: boolean;
@@ -994,28 +1039,15 @@ export function createConnection<WalletProviderType>(settings: {
994
1039
  storagePrefix?: string;
995
1040
  }): ConnectionStore<WalletProviderType, 'WalletConnected', true>;
996
1041
 
997
- // WalletConnected target with default Ethereum connector - walletHost optional
998
- export function createConnection(settings: {
999
- targetStep: 'WalletConnected';
1000
- walletHost?: string;
1001
- nodeURL?: string;
1002
- chainInfo: ChainInfo<UnderlyingEthereumProvider>;
1003
- walletConnector?: undefined;
1004
- autoConnect?: boolean;
1005
- useCurrentAccount?: 'always' | 'whenSingle' | false;
1006
- prioritizeWalletProvider?: boolean;
1007
- requestsPerSecond?: number;
1008
- storagePrefix?: string;
1009
- }): ConnectionStore<UnderlyingEthereumProvider, 'WalletConnected', true>;
1010
-
1011
- // SignedIn target with walletOnly: true (custom wallet connector) - walletHost optional
1012
- export function createConnection<WalletProviderType>(settings: {
1042
+ // SignedIn target with walletOnly: true - walletHost optional
1043
+ export function createConnection<WalletProviderType = UnderlyingEthereumProvider>(settings: {
1013
1044
  targetStep?: 'SignedIn';
1014
1045
  walletOnly: true;
1015
1046
  walletHost?: string;
1016
1047
  nodeURL?: string;
1017
1048
  chainInfo: ChainInfo<WalletProviderType>;
1018
- walletConnector: WalletConnector<WalletProviderType>;
1049
+ walletConnector?: WalletConnector<WalletProviderType> | undefined;
1050
+ wallets?: WalletHandle<WalletProviderType>[] | undefined;
1019
1051
  signingOrigin?: string;
1020
1052
  autoConnect?: boolean;
1021
1053
  requestSignatureAutomaticallyIfPossible?: boolean;
@@ -1026,32 +1058,15 @@ export function createConnection<WalletProviderType>(settings: {
1026
1058
  storagePrefix?: string;
1027
1059
  }): ConnectionStore<WalletProviderType, 'SignedIn', true>;
1028
1060
 
1029
- // SignedIn target with walletOnly: true (default Ethereum connector) - walletHost optional
1030
- export function createConnection(settings: {
1031
- targetStep?: 'SignedIn';
1032
- walletOnly: true;
1033
- walletHost?: string;
1034
- nodeURL?: string;
1035
- chainInfo: ChainInfo<UnderlyingEthereumProvider>;
1036
- walletConnector?: undefined;
1037
- signingOrigin?: string;
1038
- autoConnect?: boolean;
1039
- requestSignatureAutomaticallyIfPossible?: boolean;
1040
- useCurrentAccount?: 'always' | 'whenSingle' | false;
1041
- prioritizeWalletProvider?: boolean;
1042
- requestsPerSecond?: number;
1043
- domainRedirectBridge?: boolean;
1044
- storagePrefix?: string;
1045
- }): ConnectionStore<UnderlyingEthereumProvider, 'SignedIn', true>;
1046
-
1047
- // SignedIn target (explicit) with custom wallet connector - walletHost required
1048
- export function createConnection<WalletProviderType>(settings: {
1061
+ // SignedIn target (the default) - walletHost required
1062
+ export function createConnection<WalletProviderType = UnderlyingEthereumProvider>(settings: {
1049
1063
  targetStep?: 'SignedIn';
1050
1064
  walletOnly?: false;
1051
1065
  walletHost: string;
1052
1066
  nodeURL?: string;
1053
1067
  chainInfo: ChainInfo<WalletProviderType>;
1054
- walletConnector: WalletConnector<WalletProviderType>;
1068
+ walletConnector?: WalletConnector<WalletProviderType> | undefined;
1069
+ wallets?: WalletHandle<WalletProviderType>[] | undefined;
1055
1070
  signingOrigin?: string;
1056
1071
  // Permissions to ask for at connect time. See `PermissionDeclaration`.
1057
1072
  permissions?: PermissionDeclaration[];
@@ -1064,26 +1079,6 @@ export function createConnection<WalletProviderType>(settings: {
1064
1079
  storagePrefix?: string;
1065
1080
  }): ConnectionStore<WalletProviderType, 'SignedIn', false>;
1066
1081
 
1067
- // SignedIn target (default) with default Ethereum connector - walletHost required
1068
- export function createConnection(settings: {
1069
- targetStep?: 'SignedIn';
1070
- walletOnly?: false;
1071
- walletHost: string;
1072
- nodeURL?: string;
1073
- chainInfo: ChainInfo<UnderlyingEthereumProvider>;
1074
- walletConnector?: undefined;
1075
- signingOrigin?: string;
1076
- // Permissions to ask for at connect time. See `PermissionDeclaration`.
1077
- permissions?: PermissionDeclaration[];
1078
- autoConnect?: boolean;
1079
- requestSignatureAutomaticallyIfPossible?: boolean;
1080
- useCurrentAccount?: 'always' | 'whenSingle' | false;
1081
- prioritizeWalletProvider?: boolean;
1082
- requestsPerSecond?: number;
1083
- domainRedirectBridge?: boolean;
1084
- storagePrefix?: string;
1085
- }): ConnectionStore<UnderlyingEthereumProvider, 'SignedIn', false>;
1086
-
1087
1082
  // Implementation signature
1088
1083
  export function createConnection<WalletProviderType = UnderlyingEthereumProvider>(settings: {
1089
1084
  targetStep?: TargetStep;
@@ -1093,7 +1088,36 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
1093
1088
  permissions?: PermissionDeclaration[];
1094
1089
  walletHost?: string;
1095
1090
  autoConnect?: boolean;
1096
- walletConnector?: WalletConnector<WalletProviderType>;
1091
+ walletConnector?: WalletConnector<WalletProviderType> | undefined;
1092
+ /**
1093
+ * The wallets this app BRINGS, instead of the ones the page happens to have.
1094
+ *
1095
+ * Supplying this REPLACES discovery: the connector's `fetchWallets` is not called, no
1096
+ * `eip6963:requestProvider` is dispatched, and `connection.wallets` is exactly this list, INCLUDING
1097
+ * WHEN IT IS EMPTY. `wallets: []` is a connection about no wallets, not a connection that falls
1098
+ * back to discovery, because `wallets: maybeList ?? []` must not quietly enrol every extension in
1099
+ * the page into a connection the caller meant to keep to itself. Pass `undefined` (or nothing) to
1100
+ * ask for discovery. That is
1101
+ * the point rather than a side effect. A wallet an app constructs (a chain running in the tab
1102
+ * with a key it generated, a burner signer, a test double) is not a member of the same population
1103
+ * as the extensions a user installed: it belongs to ONE connection, and announcing it into a
1104
+ * page-wide list, or letting page-wide announcements into this connection's list, mixes two
1105
+ * populations that answer for different things. An app that wants both runs two connections, or
1106
+ * supplies a list containing both.
1107
+ *
1108
+ * With ONE wallet supplied, no picker can ever be shown: `connect({type: 'wallet'})` resolves the
1109
+ * name from the single entry, exactly as it does for a single installed wallet.
1110
+ *
1111
+ * The handles are used as given and never mutated. `info.autoApproves` is how such a wallet says
1112
+ * it prompts for nothing, which is usually true of one an app constructs: see `WalletInfo`.
1113
+ *
1114
+ * This exists so that bringing a wallet does not require SUBCLASSING a connector. The alternative
1115
+ * a consumer had was to extend `EthereumWalletConnector` and override `fetchWallets` to announce
1116
+ * one handle, inheriting `createAlwaysOnProvider` and `accountGenerator` unchanged: a class whose
1117
+ * entire content was a list. `walletConnector` remains the right answer for a DIFFERENT CHAIN
1118
+ * FAMILY, which is what it is for.
1119
+ */
1120
+ wallets?: WalletHandle<WalletProviderType>[] | undefined;
1097
1121
  requestSignatureAutomaticallyIfPossible?: boolean;
1098
1122
  useCurrentAccount?: 'always' | 'whenSingle' | false;
1099
1123
  nodeURL?: string;
@@ -1156,6 +1180,11 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
1156
1180
  const requestSignatureAutomaticallyIfPossible =
1157
1181
  targetStep === 'SignedIn' ? settings.requestSignatureAutomaticallyIfPossible || false : false;
1158
1182
 
1183
+ // Whether each in-flight request is one the user will ever be asked about, decided once when it
1184
+ // starts. Declared up here because the first published state already reads the list. See `silenced`
1185
+ // below for what puts an entry in it and why both answers are recorded.
1186
+ const requestSilencing = new Map<string, boolean>();
1187
+
1159
1188
  // The list as last published. Kept so that an UNCHANGED list keeps its identity across publishes:
1160
1189
  // the wrapper hands back a fresh array every call, and publishing a new array (and so a new
1161
1190
  // `wallet` object) on every unrelated `set` would invalidate `derived` stores, `{#key}` blocks and
@@ -1163,7 +1192,9 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
1163
1192
  // `PendingRequest` is created once and never mutated.
1164
1193
  let publishedPendingRequests: PendingRequest[] = [];
1165
1194
  function currentPendingRequests(): PendingRequest[] {
1166
- const latest = alwaysOnProviderWrapper.getPendingRequests();
1195
+ const latest = alwaysOnProviderWrapper
1196
+ .getPendingRequests()
1197
+ .filter((request) => requestSilencing.get(request.id) !== true);
1167
1198
  if (
1168
1199
  latest.length === publishedPendingRequests.length &&
1169
1200
  latest.every((request, i) => request === publishedPendingRequests[i])
@@ -1229,14 +1260,30 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
1229
1260
  // `{#key}` blocks and effect dependencies do not re-run on an unrelated publish.
1230
1261
  const incomingWallet = connection.wallet as WalletStateInput<WalletProviderType> & {
1231
1262
  pendingRequests?: PendingRequest[];
1263
+ info?: WalletInfo;
1232
1264
  };
1265
+ // WHICH wallet this provider belongs to.
1266
+ //
1267
+ // The live wallet's own `info` when the state is about the live wallet, which is every state this
1268
+ // library builds and is the EXACT answer: it came from the handle that was chosen, rather than
1269
+ // from a scan over a list where provider identity may not be unique.
1270
+ //
1271
+ // The scan is the fallback for anything else, and what the caller spread in is the fallback after
1272
+ // that, so a state rebuilt from a published one keeps the `info` it was published with even once
1273
+ // the handle has left the list. That last one is deliberately allowed to be STALE: a name that is
1274
+ // one publish old is better than a state that cannot say which wallet it is about, and the field
1275
+ // is re-derived on the next transition.
1276
+ const info =
1277
+ (_wallet && _wallet.provider === connection.wallet.provider ? _wallet.info : undefined) ??
1278
+ walletInfoIn(connection.wallets, connection.wallet.provider) ??
1279
+ incomingWallet.info;
1233
1280
  $connection = {
1234
1281
  ...connection,
1235
1282
  pendingRequests,
1236
1283
  wallet:
1237
- incomingWallet.pendingRequests === pendingRequests
1284
+ incomingWallet.pendingRequests === pendingRequests && incomingWallet.info === info
1238
1285
  ? (incomingWallet as WalletState<WalletProviderType>)
1239
- : {...connection.wallet, pendingRequests},
1286
+ : {...connection.wallet, pendingRequests, info},
1240
1287
  };
1241
1288
  _store.set($connection);
1242
1289
  return $connection;
@@ -1262,12 +1309,78 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
1262
1309
  // disconnect followed by a reconnect left the app blind to every subsequent wallet prompt. The
1263
1310
  // wrapper is created here and lives exactly as long as this connection, so there is nothing to
1264
1311
  // release.
1265
- alwaysOnProviderWrapper.onRequest(() => {
1312
+ alwaysOnProviderWrapper.onRequest((event) => {
1313
+ // Decide, and RECORD, whether this request is one the user will ever be asked about, before the
1314
+ // list below is read. See `silenced`.
1315
+ silenced(event);
1266
1316
  // Republish. `set` re-reads the wrapper, so this needs to say nothing about the list itself,
1267
1317
  // and it must run whether or not a wallet is currently in the state: a request outstanding
1268
1318
  // while the flow rests on `wallet: undefined` is exactly the case that used to go unreported.
1269
1319
  set($connection);
1270
1320
  });
1321
+
1322
+ // NOTHING CAN BE OUTSTANDING WITH A WALLET THAT ANSWERS BY ITSELF.
1323
+ //
1324
+ // `pendingRequests` means "your wallet is holding something and is waiting for you", and every
1325
+ // consumer renders it as a question on the user's screen: a modal saying the wallet will ask them
1326
+ // to confirm, a cancel affordance, an unload guard. A wallet that declares `info.autoApproves`
1327
+ // signs with no dialog, so all three describe an event that does not happen, and each consumer
1328
+ // would otherwise have to infer that for itself from a fact only the wallet knows.
1329
+ //
1330
+ // So the announcement is dropped HERE, at the connection, and not in the wrapper. The wrapper's
1331
+ // own bookkeeping stays honest and complete (it is what tells a request's end from its start, and
1332
+ // it is per-connector, so silencing there would have to be implemented again by every connector).
1333
+ // This library's published surface is the one that claims a user is being asked, and it is the one
1334
+ // that stops claiming it.
1335
+ //
1336
+ // The decision is made ONCE, when the request STARTS, and then remembered by id. A request can
1337
+ // outlive the wallet that started it (the user is free to switch wallet while one is outstanding,
1338
+ // see the ADR), and "was anybody ever going to be asked about this" is a fact about the wallet that
1339
+ // TOOK it, not about whichever wallet is current when it ends. Deciding again at the end would
1340
+ // silence a real prompt, or announce the end of something never announced as started.
1341
+ //
1342
+ // `walletPrompts` is the default: a wallet that says nothing prompts, so every existing caller and
1343
+ // every discovered wallet is untouched by this.
1344
+ function activeWalletAutoApproves(): boolean {
1345
+ // `_wallet.info` and not a lookup: see the declaration of `_wallet`. This is the one answer that
1346
+ // must not be guessed, because guessing it wrong in the silencing direction hides a prompt the
1347
+ // user is looking at.
1348
+ return !!_wallet && !walletPrompts(_wallet.info);
1349
+ }
1350
+ /**
1351
+ * Is this event about a request the user was never going to see?
1352
+ *
1353
+ * Idempotent, and order-independent: the store's own subscription and every consumer subscription
1354
+ * ask, in whatever order they were registered, and the first to ask about a `requestStart` is the
1355
+ * one that decides. Every later ask reads that decision back, INCLUDING A NEGATIVE ONE.
1356
+ *
1357
+ * Recording the negative answer too is what makes the order not matter. The decision is a question
1358
+ * about the live wallet, and publishing between handlers (the store's own subscription calls `set`,
1359
+ * which runs consumer subscribers synchronously) is an opportunity for the live wallet to change
1360
+ * under the remaining handlers. Nothing reachable today flips it in that window, but a half-silenced
1361
+ * request is exactly the split this feature exists to avoid: announced on `pendingRequests` and
1362
+ * missing from `onRequest`, or the reverse.
1363
+ */
1364
+ function silenced(event: RequestEvent): boolean {
1365
+ const decided = requestSilencing.get(event.request.id);
1366
+ if (decided !== undefined) {
1367
+ if (event.type === 'requestEnd') {
1368
+ // Forgotten only once every handler has been given this event, so that a consumer cannot be
1369
+ // handed the END of a request whose START it never saw. A native microtask rather than a
1370
+ // timer: the whole synchronous emit loop has run by then, and no test clock can defer it.
1371
+ Promise.resolve().then(() => requestSilencing.delete(event.request.id));
1372
+ }
1373
+ return decided;
1374
+ }
1375
+ if (event.type !== 'requestStart') {
1376
+ // An end with no decision on record is a request that started before this connection was
1377
+ // listening. It was never silenced, so it is not silenced now.
1378
+ return false;
1379
+ }
1380
+ const silence = activeWalletAutoApproves();
1381
+ requestSilencing.set(event.request.id, silence);
1382
+ return silence;
1383
+ }
1271
1384
  // Where the flow comes to rest when a connection attempt fails.
1272
1385
  //
1273
1386
  // The rule: rest on the step that offers the user a real next decision, and never on a step this app has
@@ -1429,7 +1542,21 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
1429
1542
  // ask.
1430
1543
  let walletAnnouncements = 0;
1431
1544
 
1432
- let _wallet: {provider: WalletProvider<WalletProviderType>; chainId: string} | undefined;
1545
+ // THE LIVE WALLET, and WHICH wallet it is.
1546
+ //
1547
+ // `info` is carried here, from the handle that was chosen, rather than looked up from the provider
1548
+ // when it is needed. The lookup is a scan of `wallets` by provider identity, and provider identity
1549
+ // is not a key: two handles supplied by a caller may wrap the SAME provider object under different
1550
+ // names, at which point the scan answers with whichever comes first. That is a wrong name on the
1551
+ // published state, and, worse, a wrong answer to "does this wallet prompt", which could silence a
1552
+ // request the user is genuinely being asked about. Every site that registers a wallet has the
1553
+ // handle in hand, so the exact answer is free.
1554
+ //
1555
+ // The key is REQUIRED (and may hold `undefined`) so that a new registration site has to say what it
1556
+ // knows rather than inherit a default by forgetting.
1557
+ let _wallet:
1558
+ | {provider: WalletProvider<WalletProviderType>; chainId: string; info: WalletInfo | undefined}
1559
+ | undefined;
1433
1560
 
1434
1561
  let popup: PopupPromise<OriginAccount> | undefined;
1435
1562
 
@@ -1453,18 +1580,59 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
1453
1580
  return !!a.info.rdns && a.info.rdns === b.info.rdns;
1454
1581
  }
1455
1582
 
1583
+ function announceWallet(detail: WalletHandle<WalletProviderType>) {
1584
+ const existingWallets = $connection.wallets;
1585
+ if (existingWallets.some((existing) => isSameWallet(existing, detail))) {
1586
+ return;
1587
+ }
1588
+
1589
+ set({
1590
+ ...$connection,
1591
+ wallets: [...existingWallets, detail],
1592
+ });
1593
+ }
1594
+
1595
+ // WHERE THIS CONNECTION'S WALLETS COME FROM: the caller, or the page.
1596
+ //
1597
+ // A caller that supplies `wallets` gets exactly those and DISCOVERY IS NOT RUN, so no
1598
+ // `eip6963:requestProvider` is dispatched and no installed extension can announce itself into this
1599
+ // list. See the setting's doc on the implementation signature: a wallet the app constructed and a
1600
+ // wallet the user installed are two different populations, and the whole reason to supply one is
1601
+ // to say which of them this connection is about.
1602
+ //
1603
+ // The supplied handles go through the same `announceWallet` as discovered ones, so a caller that
1604
+ // hands over the same wallet twice gets it once, exactly as a wallet announcing itself twice does.
1456
1605
  function fetchWallets() {
1457
- walletConnector.fetchWallets((detail) => {
1458
- const existingWallets = $connection.wallets;
1459
- if (existingWallets.some((existing) => isSameWallet(existing, detail))) {
1460
- return;
1606
+ // `!== undefined`, so an EMPTY supplied list is still a supplied list: see the setting's doc.
1607
+ if (settings.wallets !== undefined) {
1608
+ for (const walletHandle of settings.wallets) {
1609
+ announceWallet(walletHandle);
1461
1610
  }
1611
+ return;
1612
+ }
1613
+ walletConnector.fetchWallets(announceWallet);
1614
+ }
1462
1615
 
1463
- set({
1464
- ...$connection,
1465
- wallets: [...existingWallets, detail],
1466
- });
1467
- });
1616
+ /**
1617
+ * The `info` of the announced handle this provider belongs to, or NOTHING IF IT IS AMBIGUOUS.
1618
+ *
1619
+ * The fallback for a wallet this connection did not register itself (a custom connector may hand
1620
+ * over a provider without a handle behind it), which is why it is a scan rather than a key lookup:
1621
+ * provider identity is not a key, and a caller supplying two handles that wrap the same provider
1622
+ * object under different names makes it answer with whichever comes first.
1623
+ *
1624
+ * So an ambiguous scan answers with nothing at all. Absent is read as the LOUD default everywhere
1625
+ * it matters, which is the direction a wrong guess must fail in: naming the wrong wallet is a
1626
+ * cosmetic error, while inheriting the wrong wallet's `autoApproves` would silence a request the
1627
+ * user is genuinely being asked about. `_wallet.info` is the exact answer and is preferred over
1628
+ * this wherever it is available.
1629
+ */
1630
+ function walletInfoIn(
1631
+ wallets: WalletHandle<WalletProviderType>[],
1632
+ provider: WalletProvider<WalletProviderType>,
1633
+ ): WalletInfo | undefined {
1634
+ const matches = wallets.filter((walletHandle) => walletHandle.walletProvider === provider);
1635
+ return matches.length === 1 ? matches[0].info : undefined;
1468
1636
  }
1469
1637
 
1470
1638
  function waitForWallet(name: string): Promise<WalletHandle<WalletProviderType>> {
@@ -1527,7 +1695,7 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
1527
1695
  const walletProvider = walletDetails.walletProvider;
1528
1696
  const chainIdAsHex = await withTimeout(walletProvider.getChainId());
1529
1697
  const chainId = Number(chainIdAsHex).toString();
1530
- _wallet = {provider: walletProvider, chainId};
1698
+ _wallet = {provider: walletProvider, chainId, info: walletDetails.info};
1531
1699
  alwaysOnProviderWrapper.setWalletProvider(walletProvider.underlyingProvider);
1532
1700
  watchForChainIdChange(_wallet.provider);
1533
1701
  let accounts: `0x${string}`[] = [];
@@ -1582,7 +1750,7 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
1582
1750
  const walletProvider = walletDetails.walletProvider;
1583
1751
  const chainIdAsHex = await withTimeout(walletProvider.getChainId());
1584
1752
  const chainId = Number(chainIdAsHex).toString();
1585
- _wallet = {provider: walletProvider, chainId};
1753
+ _wallet = {provider: walletProvider, chainId, info: walletDetails.info};
1586
1754
  alwaysOnProviderWrapper.setWalletProvider(walletProvider.underlyingProvider);
1587
1755
  alwaysOnProviderWrapper.setWalletStatus('disconnected');
1588
1756
  watchForChainIdChange(_wallet.provider);
@@ -1624,7 +1792,7 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
1624
1792
  const walletProvider = walletDetails.walletProvider;
1625
1793
  const chainIdAsHex = await withTimeout(walletProvider.getChainId());
1626
1794
  const chainId = Number(chainIdAsHex).toString();
1627
- _wallet = {provider: walletProvider, chainId};
1795
+ _wallet = {provider: walletProvider, chainId, info: walletDetails.info};
1628
1796
  alwaysOnProviderWrapper.setWalletProvider(walletProvider.underlyingProvider);
1629
1797
  watchForChainIdChange(_wallet.provider);
1630
1798
 
@@ -2087,7 +2255,9 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
2087
2255
  // same event identically. An empty accounts answer has no `cause` to derive anything from.
2088
2256
  reason: ConnectionFailureReason,
2089
2257
  chosenMechanism: WalletMechanism<string, undefined> | undefined,
2090
- chosenWallet: {provider: WalletProvider<WalletProviderType>; chainId: string} | undefined,
2258
+ chosenWallet:
2259
+ | {provider: WalletProvider<WalletProviderType>; chainId: string; info: WalletInfo | undefined}
2260
+ | undefined,
2091
2261
  ): boolean {
2092
2262
  if (!chosenMechanism || !chosenWallet) {
2093
2263
  return false;
@@ -2101,7 +2271,7 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
2101
2271
  // The fresher chainId wins: `onChainChanged` keeps updating the live `_wallet`, so when
2102
2272
  // the attempt was on the same provider its chainId may be newer than the captured one.
2103
2273
  const chainId = _wallet && _wallet.provider === chosenWallet.provider ? _wallet.chainId : chosenWallet.chainId;
2104
- _wallet = {provider: chosenWallet.provider, chainId};
2274
+ _wallet = {provider: chosenWallet.provider, chainId, info: chosenWallet.info};
2105
2275
  stopWatchingForAccountChange(_wallet.provider);
2106
2276
  // Re-establish what the start of connect() tore down. If the failure happened early
2107
2277
  // (getChainId threw), the wrapper provider and the chain watcher were never
@@ -2292,6 +2462,7 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
2292
2462
  _wallet = {
2293
2463
  chainId,
2294
2464
  provider,
2465
+ info: wallet.info,
2295
2466
  };
2296
2467
  // TODO
2297
2468
  alwaysOnProviderWrapper.setWalletProvider(_wallet.provider.underlyingProvider);
@@ -3361,7 +3532,7 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
3361
3532
  const provider = wallet.walletProvider;
3362
3533
  const chainIdAsHex = await withTimeout(provider.getChainId());
3363
3534
  const chainId = Number(chainIdAsHex).toString();
3364
- _wallet = {chainId, provider};
3535
+ _wallet = {chainId, provider, info: wallet.info};
3365
3536
  alwaysOnProviderWrapper.setWalletProvider(provider.underlyingProvider);
3366
3537
  alwaysOnProviderWrapper.setWalletStatus('disconnected');
3367
3538
  watchForChainIdChange(provider);
@@ -3807,7 +3978,17 @@ export function createConnection<WalletProviderType = UnderlyingEthereumProvider
3807
3978
  provider: alwaysOnProviderWrapper.provider,
3808
3979
  chainId: '' + settings.chainInfo.id,
3809
3980
  chainInfo: settings.chainInfo,
3810
- onRequest: (handler: RequestEventHandler) => alwaysOnProviderWrapper.onRequest(handler),
3981
+ // Wrapped rather than passed straight through, so that a consumer driving its own UI from the
3982
+ // event stream sees exactly what `pendingRequests` shows: nothing at all for a wallet that
3983
+ // answers by itself. A consumer given the END of a request whose START it never saw would be
3984
+ // asked to close a dialog it never opened, so both halves are dropped or neither is.
3985
+ onRequest: (handler: RequestEventHandler) =>
3986
+ alwaysOnProviderWrapper.onRequest((event) => {
3987
+ if (silenced(event)) {
3988
+ return;
3989
+ }
3990
+ handler(event);
3991
+ }),
3811
3992
  };
3812
3993
 
3813
3994
  return store as ConnectionStore<WalletProviderType, TargetStep, boolean>;