|
| 1 | +import type { Wallet } from "ethers5"; |
| 2 | +import { getDefaultWallets } from "src/react/native/wallets/defaultWallets.js"; |
| 3 | +import { webLocalStorage } from "src/utils/storage/webStorage.js"; |
| 4 | +import { createWallet } from "../create-wallet.js"; |
| 5 | +import { getInstalledWalletProviders } from "../injected/mipdStore.js"; |
| 6 | +import type { ConnectionManager } from "../manager/index.js"; |
| 7 | +import { autoConnectCore } from "./autoConnectCore.js"; |
| 8 | +import type { AutoConnectProps } from "./types.js"; |
| 9 | + |
| 10 | +/** |
| 11 | + * Attempts to automatically connect to a wallet based on the provided configuration. |
| 12 | + * It combines both specified wallets and installed wallet providers that aren't already specified. |
| 13 | + * |
| 14 | + * @example |
| 15 | + * |
| 16 | + * ```tsx |
| 17 | + * import { autoConnect } from "thirdweb/wallets"; |
| 18 | + * |
| 19 | + * const walletManager = createConnectionManager(); |
| 20 | + * const autoConnected = await autoConnect({ |
| 21 | + * client, |
| 22 | + * walletManager, |
| 23 | + * }); |
| 24 | + * ``` |
| 25 | + * |
| 26 | + * |
| 27 | + * @param props - The auto-connect configuration properties |
| 28 | + * @param props.wallets - Array of wallet instances to consider for auto-connection |
| 29 | + * @param walletManager - The connection manager instance handling wallet connections |
| 30 | + * @returns {boolean} a promise resolving to true or false depending on whether the auto connect function connected to a wallet or not |
| 31 | + */ |
| 32 | +export const autoConnect = async ( |
| 33 | + props: AutoConnectProps & { |
| 34 | + wallets: Wallet[]; |
| 35 | + walletManager: ConnectionManager; |
| 36 | + }, |
| 37 | +) => { |
| 38 | + const wallets = props.wallets || getDefaultWallets(props); |
| 39 | + return autoConnectCore({ |
| 40 | + storage: webLocalStorage, |
| 41 | + props: { |
| 42 | + ...props, |
| 43 | + wallets, |
| 44 | + }, |
| 45 | + createWalletFn: createWallet, |
| 46 | + getInstalledWallets: () => { |
| 47 | + const specifiedWalletIds = new Set(wallets.map((x) => x.id)); |
| 48 | + |
| 49 | + // pass the wallets that are not already specified but are installed by the user |
| 50 | + const installedWallets = getInstalledWalletProviders() |
| 51 | + .filter((x) => !specifiedWalletIds.has(x.info.rdns)) |
| 52 | + .map((x) => createWallet(x.info.rdns)); |
| 53 | + |
| 54 | + return installedWallets; |
| 55 | + }, |
| 56 | + manager: props.walletManager, |
| 57 | + }); |
| 58 | +}; |
0 commit comments