@mysten/dapp-kit-core 1.4.0 → 1.6.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/CHANGELOG.md CHANGED
@@ -1,5 +1,52 @@
1
1
  # @mysten/dapp-kit-core
2
2
 
3
+ ## 1.6.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 0c3eec4: Report `isReconnecting` during the initial auto-connect session restore.
8
+
9
+ Previously, restoring a persisted session on page load jumped the connection straight from
10
+ `disconnected` to `connected`, so for the entire async restore window the connection looked
11
+ identical to a logged-out user (`account: null`, `isConnecting: false`, `isReconnecting: false`,
12
+ `status: "disconnected"`). Consumers had no way to tell "restoring a saved session" apart from
13
+ "logged out", which caused auth gates to incorrectly redirect logged-in users on hard refresh.
14
+
15
+ Auto-connect now eagerly enters the `reconnecting` state on mount whenever a persisted session
16
+ exists — independent of wallet-registration timing, so the window is covered even before the saved
17
+ wallet registers (default wallets such as Slush register asynchronously). It stays `reconnecting`
18
+ until both every configured wallet initializer has settled and a short grace period has elapsed
19
+ (to absorb late-registering wallets such as browser extensions, which have no deterministic
20
+ "registered" signal), then settles to `disconnected` if the saved session still hasn't restored —
21
+ while never interrupting an in-flight restore, so a slow-but-valid wallet always wins, and
22
+ continuing to listen so a very-late wallet can still restore. The `reconnecting` state also now
23
+ reports `isReconnecting: true` while the target wallet/account is still resolving, instead of
24
+ being suppressed to `disconnected`.
25
+
26
+ Adds an `autoConnectTimeout` option (default `5000` ms) to tune that grace period.
27
+
28
+ Consumers can rely on `isReconnecting` to distinguish restoring from logged-out, e.g.
29
+ `if (!isReconnecting && !account) redirect()`.
30
+
31
+ ## 1.5.0
32
+
33
+ ### Minor Changes
34
+
35
+ - 8a03101: Allow `signTransaction`, `signAndExecuteTransaction`, and `signPersonalMessage` to take
36
+ optional `account` and `network` overrides.
37
+
38
+ - `account` (a `UiWalletAccount` belonging to the connected wallet) signs with a specific account
39
+ without changing the globally selected account via `switchAccount`. Throws
40
+ `WalletAccountNotFoundError` if the account does not belong to the connected wallet.
41
+ - `network` signs/executes against a specific configured network without changing the active
42
+ network via `switchNetwork`, which is useful for apps that operate on multiple networks (for
43
+ example mainnet and testnet) at once. The chain is derived from the network and the transaction
44
+ is built against that network's client. Throws `ChainNotSupportedError` if the signing account
45
+ does not support the requested network.
46
+
47
+ Both default to the currently connected account and active network, so existing call sites are
48
+ unaffected.
49
+
3
50
  ## 1.4.0
4
51
 
5
52
  ### Minor Changes
package/dist/index.d.mts CHANGED
@@ -1,5 +1,5 @@
1
- import { a as DAppKit, c as WalletConnection, d as InitializeResult, f as WalletInitializer, i as ResolvedRegister, l as DAppKitCompatibleClient, n as Register, o as createDAppKit, p as StateStorage, r as RegisteredDAppKit, s as TransactionResultWithEffects, t as DefaultExpectedDppKit, u as InitializeArgs } from "./types-Bk3Btq_s.mjs";
2
- import { UiWallet, UiWalletAccount, UiWalletAccount as UiWalletAccount$1, UiWalletHandle } from "@wallet-standard/ui";
1
+ import { a as DAppKit, c as WalletConnection, d as InitializeResult, f as WalletInitializer, i as ResolvedRegister, l as DAppKitCompatibleClient, n as Register, o as createDAppKit, p as StateStorage, r as RegisteredDAppKit, s as TransactionResultWithEffects, t as DefaultExpectedDppKit, u as InitializeArgs } from "./types-Ceigv1q9.mjs";
2
+ import { UiWallet, UiWallet as UiWallet$1, UiWalletAccount, UiWalletAccount as UiWalletAccount$1, UiWalletHandle } from "@wallet-standard/ui";
3
3
  import * as _mysten_wallet_standard0 from "@mysten/wallet-standard";
4
4
  import { Transaction } from "@mysten/sui/transactions";
5
5
  import { ClientWithCoreApi } from "@mysten/sui/client";
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../src/utils/wallets.ts","../src/utils/signer.ts"],"mappings":";;;;;;;;iBAoBgB,yBAAA,CAA0B,YAAA,EAAc,cAAA;;;cCT3C,oBAAA,SAA6B,MAAA;EAAA;cAI7B,OAAA,EAAS,OAAA;EAKZ,YAAA,CAAA,GAAgB,eAAA;EAMhB,YAAA,CAAA,GAAgB,SAAA;EAqBhB,IAAA,CAAK,KAAA,EAAO,UAAA;EAMN,eAAA,CAAgB,KAAA,EAAO,UAAA,GAAU,OAAA,CAAA,wBAAA,CAAA,iBAAA;EAMjC,mBAAA,CAAoB,KAAA,EAAO,UAAA,GAAU,OAAA,CAAA,wBAAA,CAAA,qBAAA;EAMrC,yBAAA,CAAA;IACd;EAAA;IAEA,WAAA,EAAa,WAAA;EAAA,IACV,OAAA,CAAQ,4BAAA;AAAA"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../src/utils/wallets.ts","../src/utils/signer.ts"],"mappings":";;;;;;;;iBAyBgB,yBAAA,CAA0B,YAAA,EAAc,cAAA;;;cCd3C,oBAAA,SAA6B,MAAA;EAAA;cAI7B,OAAA,EAAS,OAAA;EAKZ,YAAA,CAAA,GAAgB,eAAA;EAMhB,YAAA,CAAA,GAAgB,SAAA;EAqBhB,IAAA,CAAK,KAAA,EAAO,UAAA;EAMN,eAAA,CAAgB,KAAA,EAAO,UAAA,GAAU,OAAA,CAAA,wBAAA,CAAA,iBAAA;EAMjC,mBAAA,CAAoB,KAAA,EAAO,UAAA,GAAU,OAAA,CAAA,wBAAA,CAAA,qBAAA;EAMrC,yBAAA,CAAA;IACd;EAAA;IAEA,WAAA,EAAa,WAAA;EAAA,IACV,OAAA,CAAQ,4BAAA;AAAA"}
package/dist/index.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  import { atom, computed, map, onMount, readonlyType, task } from "nanostores";
2
2
  import { getWalletAccountFeature, getWalletFeature, uiWalletAccountBelongsToUiWallet, uiWalletAccountsAreSame } from "@wallet-standard/ui";
3
3
  import { ReadonlyWalletAccount, StandardConnect, StandardDisconnect, StandardEvents, SuiSignAndExecuteTransaction, SuiSignAndExecuteTransactionBlock, SuiSignPersonalMessage, SuiSignTransaction, SuiSignTransactionBlock, WALLET_STANDARD_ERROR__FEATURES__WALLET_ACCOUNT_CHAIN_UNSUPPORTED, WalletStandardError, getWallets } from "@mysten/wallet-standard";
4
- import { getOrCreateUiWalletAccountForStandardWalletAccount_DO_NOT_USE_OR_YOU_WILL_BE_FIRED, getOrCreateUiWalletForStandardWallet_DO_NOT_USE_OR_YOU_WILL_BE_FIRED, getWalletAccountForUiWalletAccount_DO_NOT_USE_OR_YOU_WILL_BE_FIRED, getWalletForHandle_DO_NOT_USE_OR_YOU_WILL_BE_FIRED } from "@wallet-standard/ui-registry";
4
+ import { getOrCreateUiWalletAccountForStandardWalletAccount, getOrCreateUiWalletForStandardWallet, getWalletAccountForUiWalletAccount, getWalletForHandle } from "@wallet-standard/ui-registry";
5
5
  import { Transaction } from "@mysten/sui/transactions";
6
6
  import { bcs } from "@mysten/sui/bcs";
7
7
  import { fromBase64, toBase64 } from "@mysten/utils";
@@ -60,9 +60,21 @@ function createNetworkConfig(networks, createClient) {
60
60
  const requiredWalletFeatures = [StandardConnect, StandardEvents];
61
61
  const signingFeatures = [SuiSignTransaction, SuiSignTransactionBlock];
62
62
  function getWalletUniqueIdentifier(walletHandle) {
63
- const underlyingWallet = getWalletForHandle_DO_NOT_USE_OR_YOU_WILL_BE_FIRED(walletHandle);
63
+ const underlyingWallet = getWalletForHandle(walletHandle);
64
64
  return underlyingWallet.id ?? underlyingWallet.name;
65
65
  }
66
+ /**
67
+ * Resolves the account a signing action should use, defaulting to the currently connected account.
68
+ *
69
+ * Enforces that the wallet, account, and (downstream) network all stay compatible: a wallet must be
70
+ * connected, and any explicitly provided account must belong to that connected wallet. The
71
+ * account-supports-network check happens later in {@link getAccountFeature} via `account.chains`.
72
+ */
73
+ function resolveSigningAccount(connection, account) {
74
+ if (!connection.wallet || !connection.account) throw new WalletNotConnectedError("No wallet is connected.");
75
+ if (account && !uiWalletAccountBelongsToUiWallet(account, connection.wallet)) throw new WalletAccountNotFoundError(`No account with address ${account.address} is connected to ${connection.wallet.name}.`);
76
+ return account ?? connection.account;
77
+ }
66
78
  function getAccountFeature({ account, featureName, chain }) {
67
79
  if (!account.chains.includes(chain)) {
68
80
  const cause = new WalletStandardError(WALLET_STANDARD_ERROR__FEATURES__WALLET_ACCOUNT_CHAIN_UNSUPPORTED, {
@@ -148,20 +160,21 @@ function createStores({ defaultNetwork, getClient }) {
148
160
  isDisconnected: false
149
161
  };
150
162
  case "reconnecting": {
151
- const wallet = wallets.find((w) => uiWalletAccountBelongsToUiWallet(connection.currentAccount, w));
152
- if (!wallet) return {
163
+ const { currentAccount } = connection;
164
+ const wallet = currentAccount ? wallets.find((w) => uiWalletAccountBelongsToUiWallet(currentAccount, w)) ?? null : null;
165
+ if (!currentAccount || !wallet) return {
153
166
  wallet: null,
154
167
  account: null,
155
- status: "disconnected",
168
+ status: connection.status,
156
169
  supportedIntents: [],
157
170
  isConnected: false,
158
171
  isConnecting: false,
159
- isReconnecting: false,
160
- isDisconnected: true
172
+ isReconnecting: true,
173
+ isDisconnected: false
161
174
  };
162
175
  return {
163
176
  wallet,
164
- account: connection.currentAccount,
177
+ account: currentAccount,
165
178
  status: connection.status,
166
179
  supportedIntents: connection.supportedIntents,
167
180
  isConnected: false,
@@ -199,7 +212,7 @@ function syncRegisteredWallets({ $registeredWallets }) {
199
212
  const wallets = walletsApi.get();
200
213
  const uiWallets = [];
201
214
  for (const wallet of wallets) try {
202
- uiWallets.push(getOrCreateUiWalletForStandardWallet_DO_NOT_USE_OR_YOU_WILL_BE_FIRED(wallet));
215
+ uiWallets.push(getOrCreateUiWalletForStandardWallet(wallet));
203
216
  } catch {
204
217
  console.warn(`[dapp-kit] Skipping wallet "${wallet.name}" because it does not comply with the Wallet Standard.`);
205
218
  }
@@ -313,11 +326,11 @@ function connectWalletCreator({ $baseConnection }, supportedNetworks, { storage,
313
326
  async function internalConnectWallet(wallet, supportedNetworks, args) {
314
327
  const { connect } = getWalletFeature(wallet, StandardConnect);
315
328
  const result = await connect(args);
316
- const underlyingWallet = getWalletForHandle_DO_NOT_USE_OR_YOU_WILL_BE_FIRED(wallet);
329
+ const underlyingWallet = getWalletForHandle(wallet);
317
330
  const supportedChains = supportedNetworks.map(getChain);
318
331
  const supportedIntents = result.supportedIntents ?? await getSupportedIntentsFromFeature(wallet);
319
332
  return {
320
- accounts: result.accounts.filter((account) => account.chains.some((chain) => supportedChains.includes(chain))).map(getOrCreateUiWalletAccountForStandardWalletAccount_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.bind(null, underlyingWallet)),
333
+ accounts: result.accounts.filter((account) => account.chains.some((chain) => supportedChains.includes(chain))).map(getOrCreateUiWalletAccountForStandardWalletAccount.bind(null, underlyingWallet)),
321
334
  supportedIntents
322
335
  };
323
336
  }
@@ -330,27 +343,71 @@ async function getSupportedIntentsFromFeature(wallet) {
330
343
  //#region src/core/initializers/autoconnect-wallet.ts
331
344
  /**
332
345
  * Attempts to connect to a previously authorized wallet account on mount and when new wallets are registered.
346
+ *
347
+ * Enters `reconnecting` on mount when a persisted session exists, so consumers can tell a
348
+ * restore apart from a logged-out state while the saved wallet is still resolving. Settles
349
+ * to `disconnected` once every initializer has registered and `timeout` has elapsed without
350
+ * a restore, but never interrupts an in-flight restore and keeps listening afterwards.
333
351
  */
334
- function autoConnectWallet({ networks, stores: { $baseConnection, $compatibleWallets }, storage, storageKey }) {
352
+ function autoConnectWallet({ networks, stores: { $baseConnection, $compatibleWallets }, storage, storageKey, walletsRegistered, timeout }) {
335
353
  onMount($compatibleWallets, () => {
336
- return $compatibleWallets.subscribe(async (wallets, oldWallets) => {
354
+ let done = false;
355
+ let unsubscribe;
356
+ const stop = () => {
357
+ done = true;
358
+ unsubscribe?.();
359
+ };
360
+ const tryRestore = (wallets) => task(async () => {
361
+ if (done) return;
362
+ const { status } = $baseConnection.get();
363
+ if (status !== "disconnected" && status !== "reconnecting") {
364
+ stop();
365
+ return;
366
+ }
367
+ const savedWalletAccount = await getSavedWalletAccount({
368
+ networks,
369
+ storage,
370
+ storageKey,
371
+ wallets
372
+ });
373
+ if (done) return;
374
+ if (savedWalletAccount) {
375
+ $baseConnection.set({
376
+ status: "connected",
377
+ currentAccount: savedWalletAccount.account,
378
+ supportedIntents: savedWalletAccount.supportedIntents
379
+ });
380
+ stop();
381
+ }
382
+ });
383
+ unsubscribe = $compatibleWallets.subscribe((wallets, oldWallets) => {
337
384
  if (!wallets) return;
338
385
  if (oldWallets && oldWallets.length > wallets.length) return;
339
- if ($baseConnection.get().status !== "disconnected") return;
340
- const savedWalletAccount = await task(() => {
341
- return getSavedWalletAccount({
342
- networks,
343
- storage,
344
- storageKey,
345
- wallets
346
- });
386
+ tryRestore(wallets);
387
+ });
388
+ task(async () => {
389
+ const hasSavedSession = Boolean(await storage.getItem(storageKey));
390
+ if (done) return;
391
+ if (!hasSavedSession) {
392
+ stop();
393
+ return;
394
+ }
395
+ if ($baseConnection.get().status === "disconnected") $baseConnection.set({
396
+ status: "reconnecting",
397
+ currentAccount: null,
398
+ supportedIntents: []
347
399
  });
348
- if (savedWalletAccount) $baseConnection.set({
349
- status: "connected",
350
- currentAccount: savedWalletAccount.account,
351
- supportedIntents: savedWalletAccount.supportedIntents
400
+ const gracePeriod = new Promise((resolve) => setTimeout(resolve, timeout));
401
+ await Promise.all([walletsRegistered.catch(() => {}), gracePeriod]);
402
+ if (done) return;
403
+ await tryRestore($compatibleWallets.get() ?? []);
404
+ if (done) return;
405
+ if ($baseConnection.get().status === "reconnecting") $baseConnection.set({
406
+ status: "disconnected",
407
+ currentAccount: null
352
408
  });
353
409
  });
410
+ return stop;
354
411
  });
355
412
  }
356
413
  async function getSavedWalletAccount({ networks, storage, storageKey, wallets }) {
@@ -460,17 +517,16 @@ function signPersonalMessageCreator({ $connection, $currentNetwork }) {
460
517
  /**
461
518
  * Prompts the specified wallet account to sign a personal message.
462
519
  */
463
- return async function signPersonalMessage({ ...standardArgs }) {
464
- const { account } = $connection.get();
465
- if (!account) throw new WalletNotConnectedError("No wallet is connected.");
466
- const chain = getChain($currentNetwork.get());
520
+ return async function signPersonalMessage({ account: accountOverride, network, ...standardArgs }) {
521
+ const account = resolveSigningAccount($connection.get(), accountOverride);
522
+ const chain = getChain(network ?? $currentNetwork.get());
467
523
  return await getAccountFeature({
468
524
  account,
469
525
  chain,
470
526
  featureName: SuiSignPersonalMessage
471
527
  }).signPersonalMessage({
472
528
  ...standardArgs,
473
- account: getWalletAccountForUiWalletAccount_DO_NOT_USE_OR_YOU_WILL_BE_FIRED(account),
529
+ account: getWalletAccountForUiWalletAccount(account),
474
530
  chain
475
531
  });
476
532
  };
@@ -509,16 +565,18 @@ function buildTransactionResult(digest, signature, transactionBytes, effectsByte
509
565
 
510
566
  //#endregion
511
567
  //#region src/core/actions/sign-and-execute-transaction.ts
512
- function signAndExecuteTransactionCreator({ $connection, $currentClient }) {
568
+ function signAndExecuteTransactionCreator({ $connection, $currentNetwork }, getClient) {
513
569
  /**
514
570
  * Prompts the specified wallet account to sign and execute a transaction.
515
571
  */
516
- return async function signAndExecuteTransaction({ transaction, ...standardArgs }) {
517
- const { account, supportedIntents } = $connection.get();
518
- if (!account) throw new WalletNotConnectedError("No wallet is connected.");
519
- const underlyingAccount = getWalletAccountForUiWalletAccount_DO_NOT_USE_OR_YOU_WILL_BE_FIRED(account);
520
- const suiClient = $currentClient.get();
521
- const chain = getChain(suiClient.network);
572
+ return async function signAndExecuteTransaction({ transaction, account: accountOverride, network, ...standardArgs }) {
573
+ const connection = $connection.get();
574
+ const account = resolveSigningAccount(connection, accountOverride);
575
+ const supportedIntents = [...connection.supportedIntents];
576
+ const underlyingAccount = getWalletAccountForUiWalletAccount(account);
577
+ const resolvedNetwork = network ?? $currentNetwork.get();
578
+ const suiClient = getClient(resolvedNetwork);
579
+ const chain = getChain(resolvedNetwork);
522
580
  const transactionWrapper = { toJSON: async () => {
523
581
  if (typeof transaction === "string") return transaction;
524
582
  transaction.setSenderIfNotSet(account.address);
@@ -551,7 +609,7 @@ function signAndExecuteTransactionCreator({ $connection, $currentClient }) {
551
609
  if (signAndExecuteTransactionBlockFeature) {
552
610
  const transactionBlock = Transaction.from(await transactionWrapper.toJSON());
553
611
  const { digest, rawEffects, rawTransaction } = await signAndExecuteTransactionBlockFeature.signAndExecuteTransactionBlock({
554
- account,
612
+ account: underlyingAccount,
555
613
  chain,
556
614
  transactionBlock,
557
615
  options: {
@@ -568,16 +626,18 @@ function signAndExecuteTransactionCreator({ $connection, $currentClient }) {
568
626
 
569
627
  //#endregion
570
628
  //#region src/core/actions/sign-transaction.ts
571
- function signTransactionCreator({ $connection, $currentClient }) {
629
+ function signTransactionCreator({ $connection, $currentNetwork }, getClient) {
572
630
  /**
573
631
  * Prompts the specified wallet account to sign a transaction.
574
632
  */
575
- return async function signTransaction({ transaction, ...standardArgs }) {
576
- const { account, supportedIntents } = $connection.get();
577
- if (!account) throw new WalletNotConnectedError("No wallet is connected.");
578
- const underlyingAccount = getWalletAccountForUiWalletAccount_DO_NOT_USE_OR_YOU_WILL_BE_FIRED(account);
579
- const suiClient = $currentClient.get();
580
- const chain = getChain(suiClient.network);
633
+ return async function signTransaction({ transaction, account: accountOverride, network, ...standardArgs }) {
634
+ const connection = $connection.get();
635
+ const account = resolveSigningAccount(connection, accountOverride);
636
+ const supportedIntents = [...connection.supportedIntents];
637
+ const underlyingAccount = getWalletAccountForUiWalletAccount(account);
638
+ const resolvedNetwork = network ?? $currentNetwork.get();
639
+ const suiClient = getClient(resolvedNetwork);
640
+ const chain = getChain(resolvedNetwork);
581
641
  const transactionWrapper = { toJSON: async () => {
582
642
  if (typeof transaction === "string") return transaction;
583
643
  transaction.setSenderIfNotSet(account.address);
@@ -766,7 +826,7 @@ var UnsafeBurnerWallet = class {
766
826
 
767
827
  //#endregion
768
828
  //#region src/core/index.ts
769
- function createDAppKit({ autoConnect = true, networks, createClient, defaultNetwork = networks[0], enableBurnerWallet = false, slushWalletConfig, storage = getDefaultStorage(), storageKey = DEFAULT_STORAGE_KEY, walletInitializers = [] }) {
829
+ function createDAppKit({ autoConnect = true, networks, createClient, defaultNetwork = networks[0], enableBurnerWallet = false, slushWalletConfig, storage = getDefaultStorage(), storageKey = DEFAULT_STORAGE_KEY, walletInitializers = [], autoConnectTimeout = 5e3 }) {
770
830
  const networkConfig = createNetworkConfig(networks, createClient);
771
831
  const stores = createStores({
772
832
  defaultNetwork,
@@ -778,13 +838,7 @@ function createDAppKit({ autoConnect = true, networks, createClient, defaultNetw
778
838
  storage ||= createInMemoryStorage();
779
839
  syncRegisteredWallets(stores);
780
840
  manageWalletConnection(stores);
781
- if (autoConnect) autoConnectWallet({
782
- networks,
783
- stores,
784
- storageKey,
785
- storage
786
- });
787
- registerAdditionalWallets([
841
+ const walletsRegistered = registerAdditionalWallets([
788
842
  ...walletInitializers,
789
843
  ...enableBurnerWallet ? [unsafeBurnerWalletInitializer()] : [],
790
844
  ...slushWalletConfig !== null ? [slushWebWalletInitializer(slushWalletConfig)] : []
@@ -792,11 +846,19 @@ function createDAppKit({ autoConnect = true, networks, createClient, defaultNetw
792
846
  networks,
793
847
  getClient
794
848
  });
849
+ if (autoConnect) autoConnectWallet({
850
+ networks,
851
+ stores,
852
+ storageKey,
853
+ storage,
854
+ walletsRegistered,
855
+ timeout: autoConnectTimeout
856
+ });
795
857
  return {
796
858
  networks,
797
859
  getClient,
798
- signTransaction: signTransactionCreator(stores),
799
- signAndExecuteTransaction: signAndExecuteTransactionCreator(stores),
860
+ signTransaction: signTransactionCreator(stores, networkConfig.getClient),
861
+ signAndExecuteTransaction: signAndExecuteTransactionCreator(stores, networkConfig.getClient),
800
862
  signPersonalMessage: signPersonalMessageCreator(stores),
801
863
  connectWallet: connectWalletCreator(stores, networks, {
802
864
  storage,