Skip to main content

React

Use the useWallet() hook to connect a React dApp to the Amadeus Wallet browser extension.

Overview​

The @amadeus-protocol/wallet-sdk/react subpath wraps the injected extension client in a single React hook. The hook keeps the connection status, the active account and the network in React state, and passes through the client's signing and API key methods.

The subpath exports:

ExportKindDescription
useWallet()HookCreates an injected wallet client and mirrors its state into React.
WalletStatusType'unavailable' | 'disconnected' | 'connecting' | 'connected'
UseWalletResultTypeThe object useWallet() returns.

That is the whole subpath. There is no WalletProvider component; see Share one wallet across components if you need one.

note

useWallet() only talks to the browser extension through the injected window.amadeus provider. To connect to the Amadeus mobile wallet over QR code or deep link, use Amadeus Connect instead.

Installation​

Install the Wallet SDK and its peer dependencies as described in the overview. React is an optional peer dependency (react >=18); you only need it for this subpath.

npm install @amadeus-protocol/wallet-sdk @amadeus-protocol/sdk react

Import the hook from the subpath, not from the package root:

import { useWallet } from '@amadeus-protocol/wallet-sdk/react'

The package root never imports React, so non-React code can use it without pulling React in.

Quick start​

'use client'

import { useWallet } from '@amadeus-protocol/wallet-sdk/react'

export function ConnectButton() {
const { status, account, connect } = useWallet()

if (status === 'unavailable') return <p>Amadeus Wallet extension not detected.</p>
if (status === 'connected') return <p>Connected as {account}</p>

return (
<button disabled={status === 'connecting'} onClick={() => connect().catch(console.error)}>
{status === 'connecting' ? 'Waiting for the wallet…' : 'Connect wallet'}
</button>
)
}

useWallet()​

useWallet() takes no arguments and returns a UseWalletResult. Each call creates its own wallet client (memoized for the lifetime of the component) and returns:

FieldTypeDescription
statusWalletStatusConnection state. See WalletStatus.
accountstring | nullActive account as a Base58 address, or null.
networkstring | nullNetwork reported by the wallet ('mainnet', 'testnet' or 'custom'), or null until it is known. A connect event with network: null does not clear it.
isAvailablebooleanWhether a genuine Amadeus provider is injected. Recomputed on every render, not stored in state.
connect()() => Promise<void>Calls client.connect() and stores the returned account.
disconnect()() => voidClears account and sets status to 'disconnected'. Local state only.
switchAccount(target?)(target?: string) => Promise<string>Asks the wallet to switch the active account. Resolves to the new address.
signTransaction(request)(request: SignTransactionRequest) => Promise<SignTransactionResponse>Asks the wallet to sign a contract call. Resolves to { txHash, txPacked }.
signAndSubmit(request, options)WalletClient['signAndSubmit']Signs, then submits the packed transaction to options.nodeUrl. Resolves to { txHash, submitted }.
ensureApiKey(options)WalletClient['ensureApiKey']Returns a cached API key for options.aud or asks the wallet to mint one.
clientWalletClientThe underlying injected client, for anything the hook does not cover.

signTransaction, signAndSubmit, ensureApiKey and switchAccount are the client's own methods, passed through unchanged. They are described in the WalletClient reference.

What the hook does on mount​

  1. If a provider is already injected, it calls getAccount() and getNetwork(). When the wallet returns an account, status becomes 'connected' without prompting the user. The extension returns its active account to any page while it is unlocked. Errors from either call are ignored.
  2. It subscribes to the provider's accountsChanged, connect, disconnect and networkChanged events and keeps account, network and status in sync. The extension can send connect with network: null before the page knows the network; the hook then keeps the last known network instead of clearing it.
  3. It listens for the amadeus-wallet#initialized window event (WALLET_INITIALIZED_EVENT) so status can move from 'unavailable' to 'disconnected' when the extension injects late. See Late injection for what this does not cover.

connect()​

connect() sets status to 'connecting', calls the provider's requestAccounts() and stores the first account. With the extension, an unlocked wallet answers right away with its active account. A locked wallet opens its unlock screen and answers once the user unlocks; after 30 seconds the extension rejects with Request timeout (see Connect a dApp).

If the call fails, the hook resets status to 'disconnected' (or 'unavailable' if no provider is injected) and rethrows the error. With no provider, or when the wallet returns no account, the error is a WalletSdkError with code 'INVALID_ARGUMENT'. Always handle the rejection:

connect().catch((error) => console.error(error))

switchAccount()​

The wallet always shows its own confirmation and account chooser; target is only a hint. The hook does not write the returned address into state itself: account updates when the wallet emits accountsChanged. Wallets that predate requestSwitchAccount reject with a WalletSdkError whose code is 'UNSUPPORTED'.

WalletStatus​

type WalletStatus = 'unavailable' | 'disconnected' | 'connecting' | 'connected'
StatusWhen
unavailableNo Amadeus provider was found when the component mounted (extension not installed, or not injected yet). Also the value during server rendering.
disconnectedA provider is present but there is no active account. Also set after disconnect(), after a rejected connect(), and when the wallet emits disconnect or an empty accountsChanged (the extension does both when it locks).
connectingA connect() call is waiting for the wallet to return an account (with the extension, for the user to unlock it).
connectedaccount is set: from getAccount() on mount, from connect(), or from a connect/accountsChanged event.

Full component example​

A panel that connects, shows the account and network, switches accounts, and sends AMA with signAndSubmit. Amounts are converted to atomic units with toAtomicAma from the core SDK.

'use client'

import { useState } from 'react'
import { toAtomicAma } from '@amadeus-protocol/sdk'
import { useWallet } from '@amadeus-protocol/wallet-sdk/react'

const NODE_URLS: Partial<Record<string, string>> = {
mainnet: 'https://mainnet-rpc.ama.one/api',
testnet: 'https://testnet-rpc.ama.one/api'
}

export function WalletPanel() {
const { status, account, network, connect, disconnect, switchAccount, signAndSubmit } =
useWallet()
const [recipient, setRecipient] = useState('')
const [amount, setAmount] = useState('')
const [txHash, setTxHash] = useState<string | null>(null)
const [errorMessage, setErrorMessage] = useState<string | null>(null)

const nodeUrl = network ? NODE_URLS[network] : undefined

const runAction = async (action: () => Promise<unknown>) => {
setErrorMessage(null)
try {
await action()
} catch (error) {
setErrorMessage(error instanceof Error ? error.message : String(error))
}
}

const sendTransfer = () =>
runAction(async () => {
if (!nodeUrl) throw new Error(`No node URL configured for network "${network}"`)
const atomicAmount = toAtomicAma(amount)
if (!Number.isFinite(atomicAmount)) throw new Error('Enter a valid amount')
const result = await signAndSubmit(
{
contract: 'Coin',
method: 'transfer',
args: [recipient, String(atomicAmount), 'AMA']
},
{ nodeUrl, wait: true }
)
setTxHash(result.txHash)
})

if (status === 'unavailable') {
return <p>Install the Amadeus Wallet extension to continue.</p>
}

if (status !== 'connected') {
return (
<div>
<button disabled={status === 'connecting'} onClick={() => runAction(connect)}>
{status === 'connecting' ? 'Waiting for the wallet…' : 'Connect wallet'}
</button>
{errorMessage && <p role="alert">{errorMessage}</p>}
</div>
)
}

return (
<div>
<p>
{account} on {network ?? 'unknown network'}
</p>
<button onClick={() => runAction(() => switchAccount())}>Switch account</button>
<button onClick={disconnect}>Disconnect</button>

<input
placeholder="Recipient address"
value={recipient}
onChange={(event) => setRecipient(event.target.value)}
/>
<input
placeholder="Amount (AMA)"
value={amount}
onChange={(event) => setAmount(event.target.value)}
/>
<button disabled={!recipient || !amount} onClick={sendTransfer}>
Send
</button>

{txHash && <p>Submitted: {txHash}</p>}
{errorMessage && <p role="alert">{errorMessage}</p>}
</div>
)
}

Things to note in this example:

  • nodeUrl must include the /api path; signAndSubmit appends /tx/submit_and_wait (with wait: true) or /tx/submit.
  • signAndSubmit always uses a 30 second submit timeout. If you need a different timeout, call signTransaction and then submitTransaction from the package root yourself (see Signing and API keys).
  • When the user rejects in the wallet, the extension rejects with a plain Error (for example "User rejected the request"), not a WalletSdkError.
  • If the node answers with a non-2xx status, signAndSubmit rejects with a WalletSdkError whose code is 'SUBMIT_FAILED'. The transaction was already signed at that point.
  • For Coin.transfer, the recipient is passed as a Base58 string; the wallet converts it to bytes. Other contracts that take byte arguments need different handling, covered in Signing and API keys.

Limitations and workarounds​

The extension can inject after your component mounts​

The extension injects window.amadeus from an asynchronously loaded script, so a fast-loading app can mount before the provider exists. useWallet() only reads the account and subscribes to provider events if the provider was present at mount. When the provider arrives later, the hook flips status from 'unavailable' to 'disconnected', but:

  • the existing account is not read, so an already-connected site still shows 'disconnected';
  • accountsChanged, connect, disconnect and networkChanged are never subscribed, so later changes in the wallet are not reflected;
  • network stays null, because connect() does not read it and networkChanged is not subscribed.

connect() still works, because it reads the provider at call time.

The fix is to mount the component that calls useWallet() only once the provider exists. The gate below uses isProviderAvailable and WALLET_INITIALIZED_EVENT from the package root:

'use client'

import { useEffect, useState, type ReactNode } from 'react'
import { isProviderAvailable, WALLET_INITIALIZED_EVENT } from '@amadeus-protocol/wallet-sdk'

export function WalletGate({ children, fallback }: { children: ReactNode; fallback: ReactNode }) {
const [providerReady, setProviderReady] = useState(false)

useEffect(() => {
const checkProvider = () => setProviderReady(isProviderAvailable())
window.addEventListener(WALLET_INITIALIZED_EVENT, checkProvider)
// The extension may have injected before this effect ran.
checkProvider()
return () => window.removeEventListener(WALLET_INITIALIZED_EVENT, checkProvider)
}, [])

return <>{providerReady ? children : fallback}</>
}

If the extension is not installed, fallback stays on screen, so make it an install prompt. The gate also solves the server rendering mismatch, because the server and the first client render both show fallback.

disconnect() does not disconnect the wallet​

disconnect() only clears the hook's state. The wallet is not notified. The extension has no per-site connection to revoke: while it is unlocked, getAccount() returns its active account to any page. So the hook comes back as 'connected' without a prompt on the next page load, and also in the same session when the wallet emits connect or a non-empty accountsChanged (for example after an unlock). If you need "stay logged out" behavior, persist that choice in your app and skip rendering the connected UI yourself.

Share one wallet across components​

There is no WalletProvider. Every component that calls useWallet() gets its own client, its own state, its own event subscriptions and its own in-memory API key cache. Calling ensureApiKey from two components with the default store can therefore ask the user to approve two keys. Call the hook once and share the result through your own context:

'use client'

import { createContext, useContext, type ReactNode } from 'react'
import { useWallet, type UseWalletResult } from '@amadeus-protocol/wallet-sdk/react'

const WalletContext = createContext<UseWalletResult | null>(null)

export function WalletContextProvider({ children }: { children: ReactNode }) {
const wallet = useWallet()
return <WalletContext.Provider value={wallet}>{children}</WalletContext.Provider>
}

export function useSharedWallet(): UseWalletResult {
const wallet = useContext(WalletContext)
if (!wallet) throw new Error('useSharedWallet must be used inside <WalletContextProvider>')
return wallet
}

To persist API keys across reloads, pass a store to ensureApiKey; see Get an API key for your backend.

Put the gate outside the context provider so the hook mounts after injection:

export function WalletSection() {
return (
<WalletGate fallback={<p>Install the Amadeus Wallet extension to continue.</p>}>
<WalletContextProvider>
<WalletPanel />
</WalletContextProvider>
</WalletGate>
)
}

Lock and unlock events are not handled​

The hook ignores the provider's lock and unlock events, so it has no separate locked state. When the extension locks it also empties its account list, which moves status to 'disconnected'. To tell "locked" apart from "disconnected", subscribe through client:

'use client'

import { useEffect, useState } from 'react'
import type { WalletClient } from '@amadeus-protocol/wallet-sdk'

export function useWalletLocked(client: WalletClient): boolean {
const [locked, setLocked] = useState(false)

useEffect(() => {
if (!client.isAvailable()) return
const onLock = () => setLocked(true)
const onUnlock = () => setLocked(false)
client.on('lock', onLock)
client.on('unlock', onUnlock)
return () => {
client.off('lock', onLock)
client.off('unlock', onUnlock)
}
}, [client])

return locked
}

Pass it the client from useWallet(). The provider has no "is locked" getter, so locked starts as false and only changes on the next lock or unlock event. client.on and client.off throw synchronously when no provider is injected, which is why the effect checks isAvailable() first. The full event list and payloads are in the Provider reference.

No message signing​

useWallet(), the injected client and the extension provider have no signMessage. Message signing is only available over Amadeus Connect with the mobile wallet.

Server-side rendering (Next.js)​

The hook is safe to import on the server: creating the client does not touch window, and the effects only run in the browser. Two things still need care:

  • Mark files that call useWallet() with 'use client'. The published react build has no 'use client' directive, so in the Next.js App Router any component that calls the hook (or imports a file that does) must be a Client Component.
  • Avoid a hydration mismatch. On the server there is no extension, so status renders as 'unavailable'. In a browser where the extension injected before hydration, the first client render computes 'disconnected' instead, and React reports a hydration mismatch. Wrap the wallet UI in a gate like WalletGate, which renders the same fallback on the server and on the first client render.

The package is ESM only ("type": "module", import condition only), which works out of the box with Next.js, Vite and other modern bundlers.