@mysten/dapp-kit-core 1.0.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.
Files changed (72) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/LICENSE +201 -0
  3. package/README.md +3 -0
  4. package/dist/index.d.mts +9 -0
  5. package/dist/index.d.mts.map +1 -0
  6. package/dist/index.mjs +793 -0
  7. package/dist/index.mjs.map +1 -0
  8. package/dist/types-x68aipir.d.mts +240 -0
  9. package/dist/types-x68aipir.d.mts.map +1 -0
  10. package/dist/web/index.d.mts +270 -0
  11. package/dist/web/index.d.mts.map +1 -0
  12. package/dist/web/index.mjs +1446 -0
  13. package/dist/web/index.mjs.map +1 -0
  14. package/package.json +83 -0
  15. package/src/core/actions/connect-wallet.ts +117 -0
  16. package/src/core/actions/disconnect-wallet.ts +43 -0
  17. package/src/core/actions/sign-and-execute-transaction.ts +119 -0
  18. package/src/core/actions/sign-personal-message.ts +42 -0
  19. package/src/core/actions/sign-transaction.ts +83 -0
  20. package/src/core/actions/switch-account.ts +32 -0
  21. package/src/core/actions/switch-network.ts +16 -0
  22. package/src/core/index.ts +119 -0
  23. package/src/core/initializers/autoconnect-wallet.ts +116 -0
  24. package/src/core/initializers/manage-connection.ts +50 -0
  25. package/src/core/initializers/registered-wallets.ts +68 -0
  26. package/src/core/initializers/sync-state-to-storage.ts +44 -0
  27. package/src/core/store.ts +130 -0
  28. package/src/core/types.ts +87 -0
  29. package/src/index.ts +19 -0
  30. package/src/types.ts +15 -0
  31. package/src/utils/errors.ts +29 -0
  32. package/src/utils/lit.ts +61 -0
  33. package/src/utils/name.ts +26 -0
  34. package/src/utils/networks.ts +35 -0
  35. package/src/utils/signer.ts +75 -0
  36. package/src/utils/storage.ts +40 -0
  37. package/src/utils/transaction-result.ts +50 -0
  38. package/src/utils/wallets.ts +82 -0
  39. package/src/wallets/index.ts +56 -0
  40. package/src/wallets/slush-web.ts +27 -0
  41. package/src/wallets/unsafe-burner.ts +165 -0
  42. package/src/web/dapp-kit-connect-button.stories.ts +88 -0
  43. package/src/web/dapp-kit-connect-button.ts +114 -0
  44. package/src/web/dapp-kit-connect-modal.stories.ts +62 -0
  45. package/src/web/dapp-kit-connect-modal.styles.ts +48 -0
  46. package/src/web/dapp-kit-connect-modal.ts +244 -0
  47. package/src/web/index.ts +12 -0
  48. package/src/web/internal/base-modal.ts +149 -0
  49. package/src/web/internal/button.styles.ts +54 -0
  50. package/src/web/internal/button.ts +49 -0
  51. package/src/web/internal/connected-account-menu-item.ts +116 -0
  52. package/src/web/internal/connected-account-menu.styles.ts +217 -0
  53. package/src/web/internal/connected-account-menu.ts +193 -0
  54. package/src/web/internal/connection-status.styles.ts +47 -0
  55. package/src/web/internal/connection-status.ts +31 -0
  56. package/src/web/internal/icons/arrow-right-up-icon.ts +19 -0
  57. package/src/web/internal/icons/back-icon.ts +19 -0
  58. package/src/web/internal/icons/chevron-down-icon.ts +18 -0
  59. package/src/web/internal/icons/circle-check-icon.ts +19 -0
  60. package/src/web/internal/icons/close-icon.ts +18 -0
  61. package/src/web/internal/icons/copy-icon.ts +18 -0
  62. package/src/web/internal/icons/download-icon.ts +24 -0
  63. package/src/web/internal/icons/plus-icon.ts +18 -0
  64. package/src/web/internal/icons/unlink-icon.ts +18 -0
  65. package/src/web/internal/wallet-list-item.styles.ts +41 -0
  66. package/src/web/internal/wallet-list-item.ts +45 -0
  67. package/src/web/internal/wallet-list.styles.ts +49 -0
  68. package/src/web/internal/wallet-list.ts +46 -0
  69. package/src/web/styles/icon-button.ts +28 -0
  70. package/src/web/styles/index.ts +7 -0
  71. package/src/web/styles/reset.ts +45 -0
  72. package/src/web/styles/theme.ts +56 -0
@@ -0,0 +1,87 @@
1
+ // Copyright (c) Mysten Labs, Inc.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import type { ClientWithCoreApi } from '@mysten/sui/client';
5
+ import type { Networks } from '../utils/networks.js';
6
+ import type { StateStorage } from '../utils/storage.js';
7
+ import type { WalletInitializer } from '../wallets/index.js';
8
+
9
+ export type DAppKitCompatibleClient = ClientWithCoreApi;
10
+
11
+ export type SlushWalletConfig = {
12
+ /**
13
+ * The name of your application, shown to the user when connecting to the wallet.
14
+ * @default The value of the `<meta name="application-name">` tag, or `document.title` if the meta tag is not populated.
15
+ */
16
+ appName?: string;
17
+
18
+ /**
19
+ * The host origin of the wallet.
20
+ * @default https://my.slush.app
21
+ */
22
+ origin?: string;
23
+
24
+ /**
25
+ * The URL to fetch the wallet metadata from.
26
+ * @default https://api.slush.app/api/wallet/metadata
27
+ */
28
+ metadataApiUrl?: string;
29
+ };
30
+
31
+ export type CreateDAppKitOptions<
32
+ TNetworks extends Networks,
33
+ Client extends DAppKitCompatibleClient,
34
+ > = {
35
+ /**
36
+ * Enables automatically connecting to the most recently used wallet account.
37
+ * @default `true`
38
+ */
39
+ autoConnect?: boolean;
40
+
41
+ /**
42
+ * A list of networks supported by the application.
43
+ */
44
+ networks: TNetworks;
45
+
46
+ /**
47
+ * Creates a new client instance for the given network.
48
+ *
49
+ * @param network - A supported network identifier as defined by the `networks` field.
50
+ * @returns A `DAppKitCompatibleClient` that’s pre-configured to interact with the specified network.
51
+ */
52
+ createClient: (network: TNetworks[number]) => Client;
53
+
54
+ /**
55
+ * The name of the network to use by default.
56
+ * @default The first network specified in `networks`.
57
+ */
58
+ defaultNetwork?: TNetworks[number];
59
+
60
+ /**
61
+ * Configuration options for the Slush web wallet. Set to `null` to disable the wallet entirely.
62
+ */
63
+ slushWalletConfig?: SlushWalletConfig | null;
64
+
65
+ /**
66
+ * Enables a "burner" wallet when set to `true`. This setting is intended for development and testing only.
67
+ * @default `false`
68
+ */
69
+ enableBurnerWallet?: boolean;
70
+
71
+ /**
72
+ * Configures how the most recently connected to wallet account is stored. Set to `null` to disable persisting state entirely.
73
+ * @default `localStorage` if available
74
+ */
75
+ storage?: StateStorage | null;
76
+
77
+ /**
78
+ * The key to use to store the most recently connected wallet account.
79
+ * @default `mysten-dapp-kit:selected-wallet-and-address`
80
+ */
81
+ storageKey?: string;
82
+
83
+ /**
84
+ * A list of wallet initializers used for registering additional wallet standard wallets.
85
+ */
86
+ walletInitializers?: WalletInitializer[];
87
+ };
package/src/index.ts ADDED
@@ -0,0 +1,19 @@
1
+ // Copyright (c) Mysten Labs, Inc.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ export { createDAppKit } from './core/index.js';
5
+ export type { DAppKit } from './core/index.js';
6
+
7
+ export type { DAppKitCompatibleClient } from './core/types.js';
8
+ export type { WalletConnection } from './core/store.js';
9
+ export type {
10
+ Register,
11
+ ResolvedRegister,
12
+ RegisteredDAppKit,
13
+ DefaultExpectedDppKit,
14
+ } from './types.js';
15
+ export type { StateStorage } from './utils/storage.js';
16
+ export type { ClientWithCoreApi } from '@mysten/sui/client';
17
+
18
+ export { getWalletUniqueIdentifier } from './utils/wallets.js';
19
+ export type { UiWallet, UiWalletAccount } from '@wallet-standard/ui';
package/src/types.ts ADDED
@@ -0,0 +1,15 @@
1
+ // Copyright (c) Mysten Labs, Inc.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import type { DAppKit } from './core/index.js';
5
+
6
+ export interface Register {}
7
+
8
+ export type ResolvedRegister = {
9
+ dAppKit: Register extends { dAppKit: infer _DAppKit } ? _DAppKit : DAppKit<[]>;
10
+ };
11
+
12
+ export type RegisteredDAppKit = ResolvedRegister['dAppKit'];
13
+
14
+ export type DefaultExpectedDppKit =
15
+ DAppKit<[]> extends RegisteredDAppKit ? DAppKit<any> : RegisteredDAppKit;
@@ -0,0 +1,29 @@
1
+ // Copyright (c) Mysten Labs, Inc.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ export class DAppKitError extends Error {}
5
+
6
+ /**
7
+ * Thown when someone attempts to perform an action that requires an active wallet connection.
8
+ */
9
+ export class WalletNotConnectedError extends DAppKitError {}
10
+
11
+ /**
12
+ * Thown when an account tries to invoke a feature on a chain that doesn't support it.
13
+ */
14
+ export class ChainNotSupportedError extends DAppKitError {}
15
+
16
+ /**
17
+ * Thown when an account tries to invoke a feature that it doesn't support.
18
+ */
19
+ export class FeatureNotSupportedError extends DAppKitError {}
20
+
21
+ /**
22
+ * Thown when a wallet is connected but no accounts are authorized.
23
+ */
24
+ export class WalletNoAccountsConnectedError extends DAppKitError {}
25
+
26
+ /**
27
+ * Thown when an account can't be found for a specific wallet.
28
+ */
29
+ export class WalletAccountNotFoundError extends DAppKitError {}
@@ -0,0 +1,61 @@
1
+ // Copyright (c) Mysten Labs, Inc.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import type { ReactiveElement } from 'lit';
5
+ import { MultiStoreController } from '@nanostores/lit';
6
+ import type { DAppKit } from '../core/index.js';
7
+
8
+ type ValueOf<T> = T[keyof T];
9
+ type StoreValues = ValueOf<DAppKit['stores']>[];
10
+
11
+ /**
12
+ * Property decorator that creates a property that can be assigned different dApp Kit instances.
13
+ * When a property in the internal store changes, it will automatically disconnect the old store's
14
+ * controller and create a new one for the new store.
15
+ *
16
+ * Inspired by https://github.com/nanostores/lit/issues/10#issuecomment-2781516844 :)
17
+ */
18
+ export function storeProperty() {
19
+ return function (target: any, propertyKey: PropertyKey) {
20
+ // Create unique symbols for storing the controller and value:
21
+ const controllerKey = Symbol();
22
+ const valueKey = Symbol();
23
+
24
+ interface Target extends ReactiveElement {
25
+ [controllerKey]: MultiStoreController<StoreValues> | undefined;
26
+ [valueKey]: DAppKit | undefined;
27
+ }
28
+
29
+ Object.defineProperty(target, propertyKey, {
30
+ get(this: Target): DAppKit | undefined {
31
+ return this[valueKey];
32
+ },
33
+ set(this: Target, newInstance: DAppKit | undefined) {
34
+ const oldInstance = this[valueKey];
35
+ if (oldInstance === newInstance) {
36
+ return;
37
+ }
38
+
39
+ this[valueKey] = newInstance;
40
+
41
+ const existingController = this[controllerKey];
42
+ if (existingController) {
43
+ existingController.hostDisconnected();
44
+ this.removeController(existingController);
45
+ }
46
+
47
+ const newController = newInstance
48
+ ? new MultiStoreController(this, Object.values(newInstance.stores))
49
+ : undefined;
50
+ this[controllerKey] = newController;
51
+
52
+ if (existingController && !newController) {
53
+ // If the instance is removed, request an update. Otherwise the controller should handle it.
54
+ this.requestUpdate(propertyKey, oldInstance);
55
+ }
56
+ },
57
+ configurable: true,
58
+ enumerable: true,
59
+ });
60
+ };
61
+ }
@@ -0,0 +1,26 @@
1
+ // Copyright (c) Mysten Labs, Inc.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import { normalizeSuiNSName } from '@mysten/sui/utils';
5
+ import type { DAppKitCompatibleClient } from '../core/types.js';
6
+
7
+ const cache = new Map<string, string | null>();
8
+
9
+ export async function resolveNameServiceName(client: DAppKitCompatibleClient, address: string) {
10
+ if (cache.has(address)) {
11
+ return cache.get(address)!;
12
+ }
13
+
14
+ try {
15
+ const result = await client.core.defaultNameServiceName?.({
16
+ address,
17
+ });
18
+
19
+ const name = result?.data.name;
20
+ cache.set(address, name ? normalizeSuiNSName(name, 'at') : null);
21
+ return name;
22
+ } catch {
23
+ cache.set(address, null);
24
+ return null;
25
+ }
26
+ }
@@ -0,0 +1,35 @@
1
+ // Copyright (c) Mysten Labs, Inc.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import type { SuiClientTypes } from '@mysten/sui/client';
5
+ import type { IdentifierString } from '@mysten/wallet-standard';
6
+ import { DAppKitError } from './errors.js';
7
+ import type { DAppKitCompatibleClient } from '../core/types.js';
8
+
9
+ export type Networks = SuiClientTypes.Network[];
10
+
11
+ export function getChain(network: SuiClientTypes.Network): IdentifierString {
12
+ return `sui:${network}`;
13
+ }
14
+
15
+ export function createNetworkConfig<
16
+ TNetworks extends Networks,
17
+ Client extends DAppKitCompatibleClient,
18
+ >(networks: TNetworks, createClient: (network: TNetworks[number]) => Client) {
19
+ if (networks.length === 0) {
20
+ throw new DAppKitError('You must specify at least one Sui network for your application.');
21
+ }
22
+
23
+ const networkConfig = new Map<TNetworks[number], Client>();
24
+ function getClient<T extends TNetworks[number]>(network: T | TNetworks[number]) {
25
+ if (networkConfig.has(network)) {
26
+ return networkConfig.get(network)!;
27
+ }
28
+
29
+ const client = createClient(network);
30
+ networkConfig.set(network, client);
31
+ return client;
32
+ }
33
+
34
+ return { networkConfig: Object.freeze(networkConfig), getClient };
35
+ }
@@ -0,0 +1,75 @@
1
+ // Copyright (c) Mysten Labs, Inc.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import type { PublicKey, SignatureScheme } from '@mysten/sui/cryptography';
5
+ import { SIGNATURE_FLAG_TO_SCHEME, Signer } from '@mysten/sui/cryptography';
6
+ import type { DAppKit } from '../core/index.js';
7
+ import type { Transaction } from '@mysten/sui/transactions';
8
+ import { toBase64 } from '@mysten/sui/utils';
9
+ import { publicKeyFromSuiBytes } from '@mysten/sui/verify';
10
+ import type { TransactionResultWithEffects } from './transaction-result.js';
11
+
12
+ export class CurrentAccountSigner extends Signer {
13
+ #publicKeyCache = new Map<string, PublicKey>();
14
+ #dAppKit: DAppKit;
15
+
16
+ constructor(dAppKit: DAppKit) {
17
+ super();
18
+ this.#dAppKit = dAppKit;
19
+ }
20
+
21
+ override getKeyScheme(): SignatureScheme {
22
+ return SIGNATURE_FLAG_TO_SCHEME[
23
+ this.getPublicKey().flag() as keyof typeof SIGNATURE_FLAG_TO_SCHEME
24
+ ];
25
+ }
26
+
27
+ override getPublicKey(): PublicKey {
28
+ const { account } = this.#dAppKit.stores.$connection.get();
29
+ const client = this.#dAppKit.stores.$currentClient.get();
30
+
31
+ if (!account) {
32
+ throw new Error('No account is connected.');
33
+ }
34
+
35
+ if (this.#publicKeyCache.has(account.address)) {
36
+ return this.#publicKeyCache.get(account.address)!;
37
+ }
38
+
39
+ const publicKey = publicKeyFromSuiBytes(new Uint8Array(account.publicKey), {
40
+ address: account.address,
41
+ client,
42
+ });
43
+
44
+ this.#publicKeyCache.set(account.address, publicKey);
45
+ return publicKey;
46
+ }
47
+
48
+ override sign(_data: Uint8Array): never {
49
+ throw new Error(
50
+ 'CurrentAccountSigner does not support signing directly. Use `signTransaction` or `signPersonalMessage` instead.',
51
+ );
52
+ }
53
+
54
+ override async signTransaction(bytes: Uint8Array) {
55
+ return this.#dAppKit.signTransaction({
56
+ transaction: toBase64(bytes),
57
+ });
58
+ }
59
+
60
+ override async signPersonalMessage(bytes: Uint8Array) {
61
+ return this.#dAppKit.signPersonalMessage({
62
+ message: bytes,
63
+ });
64
+ }
65
+
66
+ override async signAndExecuteTransaction({
67
+ transaction,
68
+ }: {
69
+ transaction: Transaction;
70
+ }): Promise<TransactionResultWithEffects> {
71
+ return this.#dAppKit.signAndExecuteTransaction({
72
+ transaction,
73
+ });
74
+ }
75
+ }
@@ -0,0 +1,40 @@
1
+ // Copyright (c) Mysten Labs, Inc.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ export type StateStorage = {
5
+ getItem: (name: string) => string | null | Promise<string | null>;
6
+ setItem: (name: string, value: string) => unknown | Promise<unknown>;
7
+ removeItem: (name: string) => unknown | Promise<unknown>;
8
+ };
9
+
10
+ export const DEFAULT_STORAGE_KEY = 'mysten-dapp-kit:selected-wallet-and-address';
11
+
12
+ export function getDefaultStorage() {
13
+ return isLocalStorageAvailable() ? localStorage : createInMemoryStorage();
14
+ }
15
+
16
+ export function createInMemoryStorage(): StateStorage {
17
+ const store = new Map<string, string>();
18
+ return {
19
+ getItem(key: string) {
20
+ return store.get(key) ?? null;
21
+ },
22
+ setItem(key: string, value: string) {
23
+ store.set(key, value);
24
+ },
25
+ removeItem(key: string) {
26
+ store.delete(key);
27
+ },
28
+ };
29
+ }
30
+
31
+ function isLocalStorageAvailable() {
32
+ try {
33
+ const testKey = '__storage_test__';
34
+ localStorage.setItem(testKey, 'test');
35
+ localStorage.removeItem(testKey);
36
+ return true;
37
+ } catch {
38
+ return false;
39
+ }
40
+ }
@@ -0,0 +1,50 @@
1
+ // Copyright (c) Mysten Labs, Inc.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import {
5
+ extractStatusFromEffectsBcs,
6
+ parseTransactionBcs,
7
+ parseTransactionEffectsBcs,
8
+ type SuiClientTypes,
9
+ } from '@mysten/sui/client';
10
+
11
+ export type TransactionResultWithEffects = SuiClientTypes.TransactionResult<{
12
+ effects: true;
13
+ transaction: true;
14
+ bcs: true;
15
+ }>;
16
+
17
+ export function buildTransactionResult(
18
+ digest: string,
19
+ signature: string,
20
+ transactionBytes: Uint8Array,
21
+ effectsBytes: Uint8Array,
22
+ ): TransactionResultWithEffects {
23
+ const status = extractStatusFromEffectsBcs(effectsBytes);
24
+
25
+ let effects: SuiClientTypes.TransactionEffects | null = null;
26
+ try {
27
+ effects = parseTransactionEffectsBcs(effectsBytes);
28
+ } catch {
29
+ console.warn(
30
+ 'Parsing transaction effects failed, you may need to update the SDK to pickup the latest bcs types',
31
+ );
32
+ }
33
+
34
+ const txResult: SuiClientTypes.Transaction<{ effects: true; transaction: true; bcs: true }> = {
35
+ digest,
36
+ signatures: [signature],
37
+ epoch: null,
38
+ status,
39
+ effects: effects as SuiClientTypes.TransactionEffects,
40
+ transaction: parseTransactionBcs(transactionBytes),
41
+ balanceChanges: undefined,
42
+ events: undefined,
43
+ objectTypes: undefined,
44
+ bcs: transactionBytes,
45
+ };
46
+
47
+ return status.success
48
+ ? { $kind: 'Transaction', Transaction: txResult }
49
+ : { $kind: 'FailedTransaction', FailedTransaction: txResult };
50
+ }
@@ -0,0 +1,82 @@
1
+ // Copyright (c) Mysten Labs, Inc.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import {
5
+ StandardConnect,
6
+ StandardEvents,
7
+ SuiSignTransaction,
8
+ SuiSignTransactionBlock,
9
+ WALLET_STANDARD_ERROR__FEATURES__WALLET_ACCOUNT_CHAIN_UNSUPPORTED,
10
+ WalletStandardError,
11
+ } from '@mysten/wallet-standard';
12
+ import type { UiWallet, UiWalletAccount, UiWalletHandle } from '@wallet-standard/ui';
13
+ import { getWalletAccountFeature, uiWalletAccountBelongsToUiWallet } from '@wallet-standard/ui';
14
+ import { getWalletForHandle_DO_NOT_USE_OR_YOU_WILL_BE_FIRED as getWalletForHandle } from '@wallet-standard/ui-registry';
15
+ import { ChainNotSupportedError, DAppKitError, FeatureNotSupportedError } from './errors.js';
16
+
17
+ export const requiredWalletFeatures = [StandardConnect, StandardEvents] as const;
18
+
19
+ export const signingFeatures = [SuiSignTransaction, SuiSignTransactionBlock] as const;
20
+
21
+ export function getAssociatedWalletOrThrow(account: UiWalletAccount, wallets: UiWallet[]) {
22
+ const wallet = wallets.find((wallet) => uiWalletAccountBelongsToUiWallet(account, wallet));
23
+ if (!wallet) {
24
+ throw new DAppKitError(`Wallet not found for account ${account.address}.`);
25
+ }
26
+ return wallet;
27
+ }
28
+
29
+ export function getWalletUniqueIdentifier(walletHandle: UiWalletHandle) {
30
+ const underlyingWallet = getWalletForHandle(walletHandle);
31
+ return underlyingWallet.id ?? underlyingWallet.name;
32
+ }
33
+
34
+ export function getAccountFeature<TAccount extends UiWalletAccount>({
35
+ account,
36
+ featureName,
37
+ chain,
38
+ }: {
39
+ account: TAccount;
40
+ featureName: TAccount['features'][number];
41
+ chain: TAccount['chains'][number];
42
+ }) {
43
+ if (!account.chains.includes(chain)) {
44
+ const cause = new WalletStandardError(
45
+ WALLET_STANDARD_ERROR__FEATURES__WALLET_ACCOUNT_CHAIN_UNSUPPORTED,
46
+ {
47
+ chain,
48
+ featureName,
49
+ supportedChains: [...account.chains],
50
+ supportedFeatures: [...account.features],
51
+ address: account.address,
52
+ },
53
+ );
54
+
55
+ throw new ChainNotSupportedError(
56
+ `The account ${cause.context.address} does not support the chain "${cause.context.chain}".`,
57
+ { cause },
58
+ );
59
+ }
60
+
61
+ try {
62
+ return getWalletAccountFeature(account, featureName);
63
+ } catch (error) {
64
+ throw new FeatureNotSupportedError(
65
+ `The account ${account.address} does not support the feature "${featureName}".`,
66
+ { cause: error },
67
+ );
68
+ }
69
+ }
70
+
71
+ export function tryGetAccountFeature<TAccount extends UiWalletAccount>(
72
+ ...args: Parameters<typeof getAccountFeature<TAccount>>
73
+ ) {
74
+ try {
75
+ return getAccountFeature(...args);
76
+ } catch (error) {
77
+ if (error instanceof FeatureNotSupportedError) {
78
+ return null;
79
+ }
80
+ throw error;
81
+ }
82
+ }
@@ -0,0 +1,56 @@
1
+ // Copyright (c) Mysten Labs, Inc.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import type { Networks } from '../utils/networks.js';
5
+ import type { DAppKitCompatibleClient } from '../core/types.js';
6
+
7
+ export type UnregisterCallback = () => void;
8
+
9
+ type InitializeArgs = {
10
+ networks: Networks;
11
+ getClient: (network?: Networks[number]) => DAppKitCompatibleClient;
12
+ };
13
+
14
+ type InitializeResult = {
15
+ unregister: () => void;
16
+ };
17
+
18
+ export type WalletInitializer = {
19
+ id: string;
20
+ initialize(input: InitializeArgs): InitializeResult | Promise<InitializeResult>;
21
+ };
22
+
23
+ // The wallet standard registers wallets globally and uses object references
24
+ // to keep prevent duplicate wallets from being registered. For applications
25
+ // that register interfaces with hot module replacement enabled locally, this
26
+ // doesn't quite work as expected as the original object reference gets lost.
27
+ //
28
+ // To work around this and other complexities around when nanostore stores mount
29
+ // and unmount, we can simply track initializers at the module level to ensure
30
+ // that wallets get re-registered and de-duped properly when there are multiple
31
+ // dApp Kit instances, across HMR reloads, etc.
32
+ const initializerMap = new Map<string, UnregisterCallback>();
33
+
34
+ export async function registerAdditionalWallets(
35
+ initializers: WalletInitializer[],
36
+ args: InitializeArgs,
37
+ ) {
38
+ initializerMap.forEach((unregister) => unregister());
39
+ initializerMap.clear();
40
+
41
+ const uniqueInitializers = [...new Map(initializers.map((init) => [init.id, init])).values()];
42
+ const initializePromises = uniqueInitializers.map(async (initializer) => {
43
+ const result = await initializer.initialize(args);
44
+ return { initializer, result };
45
+ });
46
+
47
+ const initializerResults = await Promise.allSettled(initializePromises);
48
+ for (const settledResult of initializerResults) {
49
+ if (settledResult.status === 'fulfilled') {
50
+ const { initializer, result } = settledResult.value;
51
+ initializerMap.set(initializer.id, result.unregister);
52
+ } else {
53
+ console.warn(`Skipping wallet initializer: "${settledResult.reason}".`);
54
+ }
55
+ }
56
+ }
@@ -0,0 +1,27 @@
1
+ // Copyright (c) Mysten Labs, Inc.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import { registerSlushWallet } from '@mysten/slush-wallet';
5
+ import type { SlushWalletConfig } from '../core/types.js';
6
+ import type { WalletInitializer } from './index.js';
7
+
8
+ export function slushWebWalletInitializer(config?: SlushWalletConfig): WalletInitializer {
9
+ return {
10
+ id: 'slush-web-wallet-initializer',
11
+ async initialize() {
12
+ const appName = config?.appName || getDefaultAppName();
13
+ const result = await registerSlushWallet(appName, {
14
+ origin: config?.origin,
15
+ metadataApiUrl: config?.metadataApiUrl,
16
+ });
17
+
18
+ if (!result) throw new Error('Registration un-successful.');
19
+ return { unregister: result.unregister };
20
+ },
21
+ };
22
+ }
23
+
24
+ function getDefaultAppName() {
25
+ const appNameElement = document.querySelector<HTMLMetaElement>(`meta[name="application-name"]`);
26
+ return appNameElement?.content || document.title;
27
+ }