SynqDocs
Guides

Connected wallets

Keep the wallet your app uses apart from who is signed in, sign in with a wallet in place, and add a wallet to the profile with one signature.

A Solana app tracks two things that are easy to mix up:

  • Who is signed in: a Synq profile at your brand, from any of its ways in (useSession()).
  • Which wallet the app uses right now: the connected wallet, for reading balances or asking for transactions.

@synqauth/solana/react keeps them apart, so your app doesn't write the glue between them. Take Acme Guild, a community app whose members sign in with Google or a wallet and use one of their wallets at a time: a member who signs in with Google still connects a wallet to see their holdings, a member with three wallets switches between them, and a wallet that isn't on the member's profile yet can join it.

The rules

The wallet layer builds these in:

  • A wallet sign-in connects that wallet. Turn it off with connectOnSignIn={false}.
  • Signing out never disconnects, and disconnecting never signs out.
  • Connecting a wallet already on the profile needs no signature. It asks the wallet app for its account (the Wallet Standard's standard:connect), which signs nothing.
  • A connected wallet that isn't on the profile joins it with one signature, from your own page, with no hosted page.
  • Any wallet on the profile signs in to the same profile: a wallet's address is unique within a brand.

Setting up

Your app needs @synqauth/nextjs with the account API on (account: true), a first-party web app with a client secret, and own-UI sign-in turned on for it. Then put SynqWalletProvider inside SynqProvider:

'use client'

import { SynqProvider, type SynqSessionInfo } from '@synqauth/react'
import { SynqWalletProvider } from '@synqauth/solana/react'

export function Providers({
  session,
  children,
}: {
  session: SynqSessionInfo | null
  children: React.ReactNode
}) {
  return (
    <SynqProvider initialSession={session}>
      <SynqWalletProvider>{children}</SynqWalletProvider>
    </SynqProvider>
  )
}

With no account prop, Synq holds the selection itself, over the Wallet Standard: it finds the browser's wallets, remembers the last wallet's name (never an address) in localStorage, reconnects it without a prompt when the page loads where the wallet still allows it (autoConnect), and follows the account when the person switches accounts in their wallet app.

An app that keeps its own wallet stack passes it in instead, and hears every connection Synq makes, such as the one a wallet sign-in leaves:

<SynqWalletProvider
  account={selectedAccount}
  wallet={selectedWallet}
  onConnect={(wallet, account) => selectWallet(wallet, account)}
  onDisconnect={() => clearWallet()}
>
  {children}
</SynqWalletProvider>

Signing in with a wallet, in place

const { signIn, wallets, pending, problem } = useWalletSignIn()

// The connected wallet, or the browser's only one. With several and none
// connected, show `wallets` and pass the one the person picks.
const result = await signIn(pickedWallet)

One signature, no page and no redirect: the page asks the issuer for a Sign In With Solana request, the wallet signs it, and the route mount trades the signature for the session at the issuer's Authorization Challenge Endpoint. The session under SynqProvider follows at once. result.data names the wallet, the account and the profile's sub.

Ask for the request before the tap

Safari lets a tap open a wallet's prompt only while the tap's user activation lasts, and drops it after a short network wait, so a sign-in that asks the issuer for its request after the tap can find its wallet blocked. Call prepare() when the sign-in comes into view: the request is asked for then and kept fresh (asked for again about a minute before it expires, and after each use), and the tap goes straight to the wallet. useAddWallet() has the same prepare(). <AccountPanel> does this itself while it is open.

const { signIn, prepare } = useWalletSignIn()

// While the sign-in is on screen; the effect's cleanup lets it go.
useEffect(() => (open ? prepare() : undefined), [open, prepare])

Without @synqauth/react, prepareSignIn({ issuer, clientId }) from @synqauth/solana does the same, and signInWithWallet and walletSignInUrl take its take() as request; the SIWS plugin has prepare() and a request option on signIn. A request that is missing or no longer fresh is asked for first, and the wallet is still asked once.

problem.code (and result.error.code) is wallet_rejected when the person declines in their wallet, wallet_failed or wallet_expired when the signature didn't count, wallet_required when the browser has several wallets and none was named, no_wallet when it has none, and redirect_to_web when only the hosted page can go on (a token gate, say): send the person there with useAuth().signIn({ method: 'wallet' }).

Confirming it's them

Adding a wallet wants a sign-in on this device within the brand's link_reauth_window (2 hours unless the tenant chose otherwise), whichever way it was made; removing a way in wants one from the last 5 minutes. Outside them the add answers fresh_sign_in_required, whose confirm_with names the way this sign-in was made: tell the person what happens and why on your own page first ("You signed in a while ago, so we check it's still you before adding a new way in. One tap with Telegram, then your wallet opens."), never a sign-in page out of nowhere. reauthenticate() signs the person in again with a wallet already on their profile, in place: the connected wallet when it is on the profile, else their primary wallet (then their others) whose wallet app this browser has. Never the wallet being added: it isn't on the profile yet.

const { reauthenticate } = useWalletSignIn()
const { signIn } = useAuth()
const { addToProfile } = useConnectedWallet()

let added = await addToProfile()
if (added.error?.code === 'fresh_sign_in_required') {
  const confirmed = await reauthenticate()
  if (confirmed.error) {
    // No wallet of theirs in this browser (`wallet_required`): confirm on the hosted page.
    await signIn({ maxAge: 300 })
  } else {
    added = await addToProfile()
  }
}

A wallet that isn't on the profile is refused before it is asked to sign (wallet_required), and Synq refuses another account's wallet itself (other_account): nobody else is signed in, nobody new is signed up, and the session stays as it was. A person with no wallet of theirs in this browser, or who signed in another way, confirms on the hosted page: useAuth().signIn({ maxAge: 300 }).

The connected wallet

const {
  account,
  walletApp,
  status,
  onProfile,
  addToProfile,
  connect,
  disconnect,
  dismiss,
  dismissed,
} = useConnectedWallet()
  • status is disconnected, connecting or connected.
  • walletApp is the wallet app's name and icon, for a chip or a menu.
  • onProfile says whether the connected account is on the signed-in profile: true, false, or null while nothing is connected, nobody is signed in, or the profile's wallets haven't been read yet.
  • Offer Add to profile while onProfile === false && !dismissed. dismiss() puts the offer away for the browser tab.
  • connect(wallet?, address?) connects a wallet, signing nothing. With address, a wallet app that has another account selected answers account_mismatch, and the error's got is the account it has: "Phantom connected 9pQa…2Lm, not 7xKX…3fQ. Switch accounts in Phantom, or use 9pQa…2Lm."
import { isAccountMismatch, useConnectedWallet } from '@synqauth/solana/react'

const { connect } = useConnectedWallet()
const connected = await connect(wallet, address)
if (isAccountMismatch(connected.error)) {
  // connected.error.got is the account the wallet app has selected.
}

The profile's wallets

const { data: wallets } = useProfileWallets()

wallets?.map((wallet) => (
  <WalletRow
    key={wallet.id}
    address={wallet.address}
    app={wallet.walletApp?.name}
    icon={wallet.walletApp?.icon}
    connected={wallet.connected}
    signedInWithThis={wallet.signedInWithThis}
    onSelect={wallet.connect}
  />
))

Each is the account API's wallet with:

  • walletApp: the wallet app that last signed with it (the account API's wallet_app), with its icon and the browser's wallet when this browser has it.
  • connected: whether it's the wallet the app uses now.
  • signedInWithThis: whether the session's sign-in was with it. With the app’s sign-in claims on, the ID token's sign_in_wallet says so on every device; without them, only for a sign-in the wallet layer made in this browser tab.
  • connect(): connects it, with no signature, in the wallet app that last signed with it when the browser has it. A different account selected there is account_mismatch.

Adding a wallet to the profile

addToProfile() (or useAddWallet().add(wallet?, account?), or useProfileWallet({ account }).add() for any account) has the wallet sign a new request and sends it to the account API's POST /v1/wallets. The first wallet becomes the primary one. It needs a recent sign-in, as above.

A wallet another profile has is never merged, unless that profile is empty and the brand merges empty accounts (below). Otherwise it answers wallet_in_use, and useAddWallet().conflict says what's possible:

const { add, move, conflict, merged } = useAddWallet()

await add()
if (merged) {
  // The wallet was a forgotten profile's only way in: that profile is now
  // part of this one. Move anything your app keeps under `merged` (its old
  // `sub`) to the signed-in user.
} else if (conflict?.move_ticket) {
  // "This wallet is on another profile." with a "Move this wallet to this profile" button:
  await move()
} else if (conflict) {
  // "This wallet is on another profile. Sign in with it to use that one."
}

A wallet moves where the other profile keeps another way in (only_way_in: false) and the brand moves a way in on its own proof (move_proved_identities, on by default, see Linking) or lets ways in move between accounts (link_conflicts: "move"). Then the conflict carries a move_ticket, and move() sends it to POST /v1/wallet-moves within 15 minutes, with no second signature: the signature it was added with proved the wallet. The other profile keeps everything else, its wallet sessions end, its owner is emailed ("A wallet was moved off your account"), and both profiles' Discord roles and Telegram groups are checked again at once. A wallet that is the other profile's only way in never moves: the person signs in with it to use that profile.

Where the brand merges empty accounts (merge_empty_accounts, on by default, see Linking) and the other profile holds nothing but that wallet, the add merges it in instead: 201 with the wallet, whose merged_from (and useAddWallet().merged) is the old profile's sub. That profile is deleted at once, and your webhooks get user.merged and then user.deleted for it.

From any other code, @synqauth/js's account client does the same: wallets.add(siws), wallets.move(ticket), and walletConflict(error) to read the conflict.

Your API and the person's wallets

An API that keys what it keeps by wallet, such as PATCH /v1/profiles/{wallet}, checks from the access token alone that the wallet is the caller's: name wallets in the API's identity_claims, and each token lists the person's wallets as { address, chain, primary }. On its server, ownsWallet(claims, wallet) from @synqauth/js/server does the check. Authorizing by wallet is the whole recipe, and Tokens and claims has the claim's every field. In your app, the wallets scope puts the same list in the ID token and at userinfo, and each wallet the account API lists says its chain too.

On phones

  • Android, in Chrome. registerMobileWallet from @synqauth/solana-mobile/web registers Mobile Wallet Adapter as a Wallet Standard wallet, so the wallet layer lists the person's wallet app beside any other and every hook above works with it.
  • iPhone. Wallet apps open web pages in their own browsers, which hold their own wallet and their own cookies: someone who opens your page in their wallet app's browser signs in there.
  • React Native, on Android. @synqauth/solana-mobile/react-native is the same wallet layer for a native app, below.

In a React Native app

SynqMobileWalletProvider goes inside @synqauth/react-native's SynqNativeProvider, with Mobile Wallet Adapter's own transact. The connected wallet is the wallet app's MWA authorization: its auth_token and the accounts it authorized. Keep it in the device's secure storage with secureAuthorizationCache, so the app stays connected between launches (memory alone by default).

import { transact } from '@solana-mobile/mobile-wallet-adapter-protocol'
import * as SecureStore from 'expo-secure-store'
import {
  SynqMobileWalletProvider,
  secureAuthorizationCache,
} from '@synqauth/solana-mobile/react-native'

export function Providers({ children }: { children: React.ReactNode }) {
  return (
    <SynqNativeProvider synq={synq} issuer={issuer}>
      <SynqMobileWalletProvider
        transact={transact}
        appOrigin="https://app.acme-guild.example"
        identity={{ name: 'Acme Guild', uri: 'https://app.acme-guild.example' }}
        authorizationCache={secureAuthorizationCache(SecureStore)}
      >
        {children}
      </SynqMobileWalletProvider>
    </SynqNativeProvider>
  )
}
  • The app's https identity. appOrigin is the origin of an https redirect URI the app claims with an App Link: the issuer answers a wallet's sign-in request only from the app's own origins, and the wallet app shows and checks it. An app whose only redirect URI is a scheme of its own gets invalid_options from every call, before anyone is asked. See From a native app.
  • One approval. useWalletSignIn().signIn() asks the wallet app for MWA's authorize with the auth_token the app holds and the issuer's request as its sign_in_payload, inside one transact: a connected app's person approves the sign-in alone, with no new connect. The signature is traded for a session at the Authorization Challenge Endpoint, so no browser opens. It needs own-UI sign-in on for the app and its token for the account API (createSynqNative({ resource: accountApiUrl(issuer) })) for the profile's hooks.
  • The token is never dropped. Whatever the wallet app authorized is kept as the connected wallet, even when the sign-in then fails: a refused signature, a message that isn't the issuer's, or a person who declines the signature after the wallet reauthorized. Each such failure is a MobileWalletError whose authorization holds it. A wallet app that no longer knows the token answers as a decline (wallet_rejected, MWA's ERROR_AUTHORIZATION_FAILED): disconnect() forgets it, and the next sign-in connects again.
  • The same hooks. useConnectedWallet() (account, authorization, onProfile, addToProfile, connect, which signs nothing, and disconnect, with { revoke: true } to end the authorization at the wallet app too), useProfileWallets() and useAddWallet() (add, move and conflict, as on the web), and useWalletSignIn() (signIn, reauthenticate with a wallet on the profile, and prepare). Signing out never disconnects, and disconnecting never signs out.
  • No wallet app on the phone is no_wallet. What only the hosted page can go on with (a token gate, say) is redirect_to_web: useAuth().signIn({ method: 'wallet' }) signs in on the hosted page in the system browser, which reaches the wallet app the same way.

An app with its own MWA session calls mobileWalletSignIn(wallet, { request, identity, authToken }) from @synqauth/solana-mobile/core inside its own transact and keeps the authToken it answers, then trades siws with synq.client.startSignIn().wallet.signIn(siws).

On this page