Skip to main content

Connecting to mobile Wallet

To sign messages or send transactions on-chain, your dApp first needs to connect to the wallet. When you do this, you get the user’s wallet address, the wallet type, and most importantly, an auth_token. This token will be reused in future sessions when signing or sending transactions.
Before performing any wallet action, your dApp must first establish a session. The process is the same as the connect flow — the only difference is the context of what you’re doing. A simple rule of thumb: create session (via transact) → authorize it → perform action. If you’re unsure, check out the official docs.
services/mwa/useConnect.ts
import type { KitMobileWallet } from "@solana-mobile/mobile-wallet-adapter-protocol-kit"
import { transact } from "@solana-mobile/mobile-wallet-adapter-protocol-kit"
import { useCallback } from "react"
import { AuthorizeInput } from "./types"
import { Account, AuthToken, SignInResult } from "@solana-mobile/mobile-wallet-adapter-protocol"

type Input = Readonly<Omit<AuthorizeInput, "auth_token">>

type Output = Readonly<{
  accounts: Account[]
  auth_token: AuthToken
  wallet_uri_base: string
}>

export function useConnect(): (input: Input) => Promise<Output> {
  return useCallback(async (input: Input): Promise<Output> => {
    return await transact(async (wallet: KitMobileWallet): Promise<Output> => {
      const connectWallet = await wallet.authorize(input)
      return connectWallet
    })
  }, [])
}

Here, we created a custom hook called useConnect that connects to the user’s wallet and returns the wallet details. Notice that the authorize call, which actually connects to the wallet, is wrapped inside the transact method. This is important because transact sets up the required session for wallet interactions. Also, there’s no separate “connect” method. We’re just using authorize in the context of connecting. That’s why this flow is considered the connect flow.

Disconnecting from mobile Wallet

To disconnect, you just need to pass the auth_token to the wallet adapter’s deauthorize method. Let’s create a hook called useDisconnect, which returns a memoized callback function that deauthorizes the wallet using the provided auth_token.
services/mwa/useDisconnect.ts
import type { KitMobileWallet } from '@solana-mobile/mobile-wallet-adapter-protocol-kit';
import { transact } from '@solana-mobile/mobile-wallet-adapter-protocol-kit';
import { useCallback } from 'react';

type Input = Readonly<{
    auth_token: string;
}>;

type Output = void;

export function useDisconnect(): (input: Input) => Promise<Output> {
    return useCallback(async (input: Input): Promise<Output> => {
        await transact(async (wallet: KitMobileWallet): Promise<void> => {
            await wallet.deauthorize({ auth_token: input.auth_token });
        });
    }, []);
}