SuiModule Component
Relevant source files
The following files were used as context for generating this wiki page:The SuiModule is the core provider component for the sui-svelte-wallet-kit. It is designed to wrap your Svelte application, managing all aspects of wallet interaction, state, and connection to the Sui blockchain. It initializes wallet discovery, handles connection persistence, manages account state, and exposes a rich set of reactive stores and functions for dApp development.
By leveraging Svelte 5 runes, SuiModule provides a reactive and efficient way to access wallet status, account details, SUI balance, and SuiNS names. It also orchestrates interactions with other components like the ConnectButton and the internally used ConnectModal.
Sources: README.md, src/lib/SuiModule/SuiModule.svelte
Architecture and Core Concepts
SuiModule acts as a central state manager and service provider. It does not render any UI itself but instead provides a context for its child components and the rest of the application. Its primary responsibilities include wallet discovery, connection management, state synchronization, and exposing an API for interaction.
The diagram below illustrates the high-level architecture, showing SuiModule as the root provider for wallet functionalities.
This diagram shows SuiModule wrapping the main application, managing the ConnectModal, and interfacing with underlying Sui SDKs to provide wallet features.
Sources: src/lib/SuiModule/SuiModule.svelte:1-12, src/lib/SuiModule/SuiModule.svelte:1078-1089, README.md
Component Props and Configuration
The behavior of SuiModule can be customized through several props.
| Prop | Type | Default | Description |
|---|---|---|---|
onConnect | () => void | undefined | A callback function that is executed when a wallet successfully connects. |
autoConnect | boolean | false | If true, the module attempts to automatically reconnect to the last used wallet on page load, using localStorage for persistence. |
autoSuiNS | boolean | true | If true, automatically fetches SuiNS names for the connected account. |
autoSuiBalance | boolean | true | If true, automatically fetches the SUI balance for the connected account. |
walletConfig | WalletConfig | {} | An object to customize wallet display names and ordering in the ConnectModal. See WalletConfig for details. |
zkLoginGoogle | ZkLoginGoogleConfig | null | null | Configuration object to enable Google zkLogin via Enoki. If provided, "Sign in with Google" appears in the modal. See ZkLoginGoogleConfig for details. |
children | any | undefined | The content to be rendered inside the module. Typically, this is your main application component. |
Sources: src/lib/SuiModule/SuiModule.svelte:1092-1102, src/lib/SuiModule/types.ts:150-158, README.md
WalletConfig
The walletConfig object allows for customization of the wallet list presented in the connection modal.
| Field | Type | Description |
|---|---|---|
customNames | Record<string, string> | A map of original wallet names to custom display names. |
ordering | string[] | An array of wallet names defining the preferred display order. Wallets not in this list appear afterward. |
Sources: src/lib/SuiModule/types.ts:68-71, src/lib/SuiModule/SuiModule.svelte:872-908
ZkLoginGoogleConfig
This configuration is required to enable "Sign in with Google" functionality via Enoki's zkLogin.
| Field | Type | Description |
|---|---|---|
apiKey | string | Your Enoki API key from the Enoki Portal. The module probes this key for validity. |
googleClientId | string | Your Google OAuth Client ID. The module performs a basic validation check on this ID. |
network | SuiNetwork | Optional. The Sui network to use (mainnet, testnet, or devnet). Defaults to mainnet. |
redirectUrl | string | Optional. A single redirect URL for the OAuth flow. |
redirectUrls | string[] | Optional. A list of allowed redirect URLs. The module will pick the most appropriate one. If neither redirectUrl nor redirectUrls is provided, a safe default is generated. |
Sources: src/lib/SuiModule/types.ts:76-82, src/lib/SuiModule/SuiModule.svelte:157-170, src/lib/SuiModule/SuiModule.svelte:1044-1065
State Management and Reactivity
SuiModule uses Svelte 5 runes ($state) to manage its internal state, which is exposed to the application through exported functions and stores.
Key internal state variables include:
status: The current connection status (CONNECTED,DISCONNECTED,CONNECTING)._account: The currently activeSuiAccount._wallet: Information about the connectedWalletWithStatus._suiNamesByAddress: A cache mapping addresses to their SuiNS names._suiBalanceByAddress: A cache mapping addresses to their SUI balance._accountsSnapshot: An array of all accounts available from the connected wallet.
Reactive $effect blocks are used to trigger side effects when state changes, such as fetching data when an account is connected or switched.
This diagram shows how an action like switchAccount updates the internal state, which in turn triggers reactive effects to fetch new data and update the UI.
Sources: src/lib/SuiModule/SuiModule.svelte:20-53, src/lib/SuiModule/SuiModule.svelte:1138-1153, src/lib/SuiModule/SuiModule.svelte:1156-1165
Wallet Discovery and Connection
Discovery Process
Wallet discovery is initiated by initWalletDiscovery(). This function runs on component mount and uses a combination of @suiet/wallet-sdk's WalletRadar and @wallet-standard/core's getWallets() to find all available wallet adapters, including browser extensions and injected providers like Enoki.
The discovery process runs multiple times with slight delays after mounting to catch any late-initializing wallets. It also subscribes to the Wallet Standard registry's register event to detect wallets that appear dynamically.
This sequence diagram details the wallet discovery flow, from component mount to updating the list of available wallets.
Sources: src/lib/SuiModule/SuiModule.svelte:979-1042, src/lib/SuiModule/SuiModule.svelte:927-977
Connection Flow
The connection process can be initiated manually via connectWithModal() or automatically if autoConnect is true.
- Auto-Connect: If
autoConnectis enabled,SuiModulereads the last connected wallet's name fromlocalStorage(sui-module-connectionkey) and attempts to connect if that wallet is installed. - Manual Connect:
connectWithModal()opens theConnectModal, which displays the list of available wallets. When a user selects an installed wallet, theconnect()function is called. connect()Logic: This function sets the connection status toCONNECTING, calls the wallet adapter'sconnectmethod, retrieves the accounts, sets the active account, and saves the connection details tolocalStorage.disconnect()Logic: This function calls the adapter'sdisconnectmethod, clears all local state (account, balance, etc.), and removes the connection data fromlocalStorage.
Sources: src/lib/SuiModule/SuiModule.svelte:312-326, src/lib/SuiModule/SuiModule.svelte:692-738, src/lib/SuiModule/SuiModule.svelte:740-776
Data Fetching
SuiModule can automatically fetch and cache SuiNS names and SUI balances.
SUI Balance
- Automatic Fetching: Triggered by
autoSuiBalance={true}when the account or network changes. - Manual Refresh: Can be triggered by calling
refreshSuiBalance(address, options). - Caching: Balance results are cached with a default TTL of 2000ms. The TTL can be globally configured with
setSuiBalanceCacheTTL(ms)or overridden per-call withoptions.ttlMs. A request can bypass the cache usingoptions.force = true. - Deduplication: Concurrent requests for the same balance are deduplicated; subsequent callers receive the promise from the in-flight request.
Sources: src/lib/SuiModule/SuiModule.svelte:370-418, src/lib/SuiModule/SuiModule.svelte:420-424
SuiNS Names
- Automatic Fetching: Triggered by
autoSuiNS={true}when the account or network changes. - Logic: On the first connection, it fetches names for all available accounts (
refreshSuiNamesForAll). On subsequent account switches, it only fetches for the newly active account (refreshSuiNamesForActive). - Labeling: If an account does not have a custom label, the first fetched SuiNS name is automatically assigned as its label.
Sources: src/lib/SuiModule/SuiModule.svelte:329-367, src/lib/SuiModule/SuiModule.svelte:426-480
Transaction and Message Signing
SuiModule provides standardized functions for signing. It abstracts away the differences between wallet adapter implementations.
signAndExecuteTransaction(transaction): Signs and executes a transaction. It intelligently finds the correct method on the adapter, tryingsignAndExecuteTransaction,sui:signAndExecuteTransaction, andsui:signAndExecuteTransactionBlockin order. It also automatically sets the transaction sender to the current account's address.signMessage(message): Signs a personal message. It prefers thesui:signMessagestandard but falls back tosui:signPersonalMessageor the adapter-specificsignPersonalMessageif necessary.canSignMessage(): A utility function that returnstrueif the currently connected wallet supports any form of message signing.
Sources: src/lib/SuiModule/SuiModule.svelte:814-845, src/lib/SuiModule/SuiModule.svelte:847-908, src/lib/SuiModule/SuiModule.svelte:910-925
Exported API
SuiModule exports a comprehensive set of functions and reactive stores (getters) for dApp integration.
| Export | Type | Description |
|---|---|---|
SuiModule | SvelteComponent | The main provider component. |
useCurrentAccount() | SuiAccount | undefined | A reactive getter for the currently connected account. |
useAccounts() | SuiAccount[] | A reactive getter for all accounts provided by the wallet. |
useCurrentWallet() | SuiWallet | undefined | A reactive getter for the currently connected wallet's information. |
useSuiClient() | SuiClient | A reactive getter for an initialized SuiClient instance for the active network. |
suiBalance | ReadableStore<string | null> | A reactive store holding the SUI balance of the current account. |
suiNames | ReadableStore<string[]> | A reactive store holding the SuiNS names of the current account. |
connectWithModal() | () => Promise<ConnectionResult> | Opens the connection modal for the user to select a wallet. |
disconnect() | () => void | Disconnects the current wallet and clears all session state. |
switchWallet() | () => Promise<ConnectionResult> | Opens the modal to allow the user to switch to a different wallet. |
switchAccount() | (number | string) => boolean | Switches the active account to the one specified by index or address. |
signAndExecuteTransaction() | (tx) => Promise<any> | Signs and executes a Sui transaction. |
signMessage() | (msg) => Promise<SignMessageResult> | Signs a personal message. |
refreshSuiBalance() | (addr, opts) => Promise<string> | Manually triggers a refresh of the SUI balance for a given address. |
isZkLoginWallet() | () => boolean | Returns true if the connected wallet is a zkLogin (Enoki) wallet. |
getZkLoginInfo() | () => Promise<ZkLoginInfo> | Retrieves session and metadata for a zkLogin wallet. |
availableWallets | WalletWithStatus[] | A live-bound array of all discovered wallets. |
Sources: src/lib/SuiModule/index.js, src/lib/SuiModule/index.d.ts, src/lib/SuiModule/SuiModule.svelte:514-689
Usage Example
Here is a basic example of how to use the SuiModule and access reactive state.
<script lang="ts">
import { SuiModule, ConnectButton, useCurrentAccount, suiBalance } from 'sui-svelte-wallet-kit';
// Use a derived rune to get the current account reactively
const account = $derived(useCurrentAccount());
</script>
<SuiModule autoConnect={true}>
<header>
<ConnectButton />
</header>
{#if account}
<main>
<p>Connected Address: {account.address}</p>
<p>SUI Balance: {suiBalance.value ?? 'Loading...'}</p>
</main>
{/if}
</SuiModule>
Sources: README.md, src/routes/+page.svelte
Summary
The SuiModule component is the cornerstone of the sui-svelte-wallet-kit, providing a powerful and easy-to-use foundation for building dApps on the Sui network with Svelte 5. It handles the complexities of wallet discovery, connection state, data fetching, and signing, exposing a clean, reactive API that allows developers to focus on building their application's features. Its configurability through props for auto-connection, data fetching, and zkLogin makes it adaptable to a wide range of use cases.
Sources: README.md, src/lib/SuiModule/SuiModule.svelte