Connect a dApp
Framework-agnostic quickstart for connecting a web dApp to the Amadeus browser extension with createInjectedWalletClient, from detecting the wallet to signing, submitting and handling errors.
This page walks through the injected client in @amadeus-protocol/wallet-sdk. It wraps the window.amadeus provider that the Amadeus browser extension injects into every page, and it works with plain TypeScript or any framework.
By the end you will have a page that:
- Detects the extension.
- Connects and reads the active account and network.
- Signs a transfer, submits it to a node and checks the result.
- Reacts to account, network and lock changes.
- Asks the user to switch accounts.
- Gets an API key for your backend.
- Handles errors by code.
The injected client only covers the browser extension on the same device. For the mobile wallet, use Amadeus Connect (mobile). For React, the React page wraps this same client in a useWallet hook.
Install
npm i @amadeus-protocol/wallet-sdk @amadeus-protocol/sdk
The package is ESM only and needs a bundler or native ES modules. See the Wallet SDK overview for requirements and peer dependencies.
Detect the wallet
Create one client for your app with createInjectedWalletClient(). The client reads window.amadeus on every call, so you can create it before the extension has injected the provider.
The extension can inject the provider after your script runs. When it is ready, it dispatches WALLET_INITIALIZED_EVENT on window. Check isAvailable() first, then wait for the event with a timeout:
import { createInjectedWalletClient, WALLET_INITIALIZED_EVENT } from '@amadeus-protocol/wallet-sdk'
const wallet = createInjectedWalletClient()
function waitForWallet(timeoutMs = 3000): Promise<boolean> {
if (wallet.isAvailable()) return Promise.resolve(true)
return new Promise((resolve) => {
const onReady = () => {
clearTimeout(timer)
resolve(true)
}
const timer = setTimeout(() => {
window.removeEventListener(WALLET_INITIALIZED_EVENT, onReady)
resolve(wallet.isAvailable())
}, timeoutMs)
window.addEventListener(WALLET_INITIALIZED_EVENT, onReady, { once: true })
})
}
const hasWallet = await waitForWallet()
if (!hasWallet) {
console.log('Amadeus Wallet not found. Ask the user to install the extension.')
}
isAvailable() is true only when window.amadeus exists and has isAmadeus === true. The standalone helpers isProviderAvailable() and getAmadeusProvider() do the same check without a client.
Listen for amadeus-wallet#initialized, not amadeus#initialized. Some older dApps use the second name, but the wallet never dispatches it. Use the WALLET_INITIALIZED_EVENT constant instead of a hard-coded string.
Connect and read the account and network
connect() asks the wallet for its account and resolves to it as a Base58 address. If the wallet is unlocked, it answers right away with the active account. If it is locked, the extension opens its unlock screen and answers once the user unlocks:
const account = await wallet.connect()
const network = await wallet.getNetwork()
console.log(`Connected ${account} on ${network}`)
The extension gives up after 30 seconds and rejects with Request timeout, so a user who takes longer to unlock has to click your connect button again.
getNetwork() resolves to 'mainnet', 'testnet' or 'custom'. Use it to pick the node your dApp talks to.
To restore state on page load without opening a prompt, call getAccount(). It resolves to the wallet's active account, or null when the wallet is locked:
const activeAccount = await wallet.getAccount()
if (activeAccount) {
console.log('Wallet is unlocked, active account:', activeAccount)
}
Sign and submit a transaction
signAndSubmit() asks the wallet to sign a contract call, then posts the signed bytes to a node. The wallet only signs; your dApp chooses the node. Pick the node URL from the wallet's network so a testnet transaction does not go to mainnet. In this example, recipient is a Base58 address:
import { toAtomicAma } from '@amadeus-protocol/sdk'
const NODE_URLS: Record<string, string> = {
mainnet: 'https://mainnet-rpc.ama.one/api',
testnet: 'https://testnet-rpc.ama.one/api'
}
const network = await wallet.getNetwork()
const nodeUrl = NODE_URLS[network]
if (!nodeUrl) throw new Error(`No node URL configured for network "${network}"`)
const { txHash, submitted } = await wallet.signAndSubmit(
{
contract: 'Coin',
method: 'transfer',
args: [recipient, String(toAtomicAma('1.5')), 'AMA'],
description: 'Send 1.5 AMA'
},
{ nodeUrl, wait: true }
)
A few things to know about the request:
nodeUrlmust start withhttp://orhttps://and must include the/apipath. The client appends/tx/submit_and_waitwhenwaitistrue, or/tx/submitotherwise.- For
Coin.transfer, pass the recipient as a Base58 address and the amount in atomic units as a string.toAtomicAmafrom the core SDK does the conversion. - For other contracts, pass byte arguments as
Uint8Array. Encoding rules are in Signing and API keys. - The submit request times out after 30 seconds.
signAndSubmitdoes not let you change that.
submitted is the node's parsed JSON reply, typed as unknown. The node answers with HTTP 200 even when it rejects a transaction, so check the reply yourself:
import type { TransactionReceipt } from '@amadeus-protocol/sdk'
type SubmitReply = { error?: string; hash?: string; receipt?: TransactionReceipt }
function assertExecuted(submitted: unknown): void {
const reply = submitted as SubmitReply
if (reply.error !== 'ok') throw new Error(`Node rejected the transaction: ${reply.error}`)
if (reply.receipt && !reply.receipt.success) {
throw new Error(`Transaction failed: ${JSON.stringify(reply.receipt.result)}`)
}
}
signAndSubmit throws SUBMIT_FAILED only for non-2xx responses. A transaction the node refuses comes back as { error: '<reason>' } with status 200, and a transaction that runs but fails comes back with receipt.success === false. Always inspect submitted.
If you want to submit the transaction yourself, for example through AmadeusSDK from the core SDK, call signTransaction() instead. It resolves to the hash and the packed bytes without sending anything:
const { txHash, txPacked } = await wallet.signTransaction({
contract: 'Coin',
method: 'transfer',
args: ['5KJvsngHeMoo884xkJ6Cyb5StvnRN6f9tYiqwqJzLpQq', '1500000000', 'AMA']
})
txPacked is a plain number[]. Pass it to submitTransaction from the wallet SDK, or wrap it in new Uint8Array(txPacked) for the core SDK.
Listen for events
Subscribe with on() and unsubscribe with off(), passing the same function reference. Payloads are typed by AmadeusEventPayloadMap:
import type { AmadeusEventPayloadMap } from '@amadeus-protocol/wallet-sdk'
const onAccountsChanged = ({ accounts }: AmadeusEventPayloadMap['accountsChanged']) => {
console.log('Active account:', accounts[0] ?? 'none')
}
const onNetworkChanged = ({ network, previousNetwork }: AmadeusEventPayloadMap['networkChanged']) => {
console.log(`Network changed from ${previousNetwork} to ${network}`)
}
const onDisconnect = ({ reason }: AmadeusEventPayloadMap['disconnect']) => {
console.log('Wallet disconnected:', reason)
}
wallet.on('accountsChanged', onAccountsChanged)
wallet.on('networkChanged', onNetworkChanged)
wallet.on('disconnect', onDisconnect)
wallet.on('lock', () => console.log('Wallet locked'))
// Later, for example when your component unmounts
wallet.off('accountsChanged', onAccountsChanged)
wallet.off('networkChanged', onNetworkChanged)
wallet.off('disconnect', onDisconnect)
The events are accountsChanged, connect, disconnect, lock, unlock, networkChanged and shown, which fires when the wallet opens the approval screen for a signing request. Every payload carries a timestamp as an ISO 8601 string. When the wallet locks, the account list empties, so you get accountsChanged with an empty array and disconnect. When the network changes, re-read anything you fetched from the old network, such as balances.
The extension fires lock and unlock only after the page's provider already knows the lock state, from an earlier lock or unlock or a call to isConnected() on the raw provider. The first lock after a page load usually arrives as accountsChanged and disconnect alone, so use an empty accountsChanged as your "account lost" signal rather than lock.
on() and off() need the provider to be injected. Subscribe after waitForWallet() resolves to true. The full payload table is in the Provider reference.
Switch accounts
switchAccount() asks the wallet to make another of the user's accounts active. The wallet shows its own confirmation and account chooser (after its unlock screen if it is locked), so a dApp can never switch accounts silently. It resolves to the new active address. When the active account actually changes, the wallet also emits accountsChanged.
You can pass an address as a hint, wallet.switchAccount(address). The user can still pick a different account. If the hint is already the active account and the wallet is unlocked, the call resolves right away without a prompt.
The extension added this method in version 1.9.0. On older versions the provider lacks it, and the client throws WalletSdkError with code UNSUPPORTED:
import { WalletSdkError } from '@amadeus-protocol/wallet-sdk'
try {
const newAccount = await wallet.switchAccount()
console.log('Now using', newAccount)
} catch (error) {
if (error instanceof WalletSdkError && error.code === 'UNSUPPORTED') {
console.log('This wallet version cannot switch accounts. Ask the user to switch in the wallet.')
} else {
throw error
}
}
To switch networks, call requestSwitchNetwork(network) on the raw provider from wallet.getProvider(). The client does not wrap it. See the Provider reference.
Get an API key for your backend
To prove to your own backend that the user controls an address, ask the wallet for an API key, a short-lived signed token. ensureApiKey() returns a cached key while it is still valid and only asks the wallet for a new one when it is missing or about to expire:
import type { ApiKeyStore } from '@amadeus-protocol/wallet-sdk'
const storageKey = (aud = '') => `amadeus-api-key:${aud}`
const apiKeyStore: ApiKeyStore = {
get: (aud) => sessionStorage.getItem(storageKey(aud)),
set: (apiKey, aud) => sessionStorage.setItem(storageKey(aud), apiKey)
}
const apiKey = await wallet.ensureApiKey({
aud: 'https://api.example.com',
expIn: 60 * 60,
store: apiKeyStore
})
| Option | Meaning |
|---|---|
aud | Audience your backend expects. Required. |
expIn | Lifetime of a new key in seconds. The client sends it to the wallet as exp_in. |
store | Optional ApiKeyStore, an object with get(aud?: string): string | null and set(apiKey: string, aud?: string): void. The client passes the request's aud to both, so a store can keep one key per audience. The default is an in-memory store owned by this client that does this, so keys are lost on reload. |
leewaySeconds | Optional, default 60. A cached key is reused only while its exp is more than this many seconds away. |
When a new key is needed, the client calls the provider's generateApiKey({ aud, exp_in }) and the user approves it in the wallet. Concurrent calls for the same aud share one wallet request; calls for different audiences each get their own. A cached key is reused only when its aud matches the request, so a store that ignores aud still works, but switching audiences asks the wallet for a new key each time. Send the key to your backend, which checks it with verifyApiKey as shown in Signing and API keys.
Handle errors
Errors reach your dApp in two forms:
WalletSdkError, thrown by the SDK itself. Branch onerror.code, never on the message.- A plain
Error, thrown by the extension when the user rejects a request, a request times out or the wallet auto-locks, or byfetchwhensignAndSubmitcannot reach the node or hits its 30-second timeout. Showerror.message.
These are the codes the injected client can throw:
| Code | When |
|---|---|
INVALID_ARGUMENT | No wallet is injected (Amadeus wallet is not available), the wallet returned no account on connect(), or nodeUrl is not an http(s) URL. |
UNSUPPORTED | switchAccount() on a wallet that predates it. |
SUBMIT_FAILED | The node answered signAndSubmit with a non-2xx status. The message includes the status and body. |
The extension rejects with User rejected the request (or a specific reason) when the user declines, and with Request timeout when nobody answers. A signing request times out after 2 minutes. If the wallet auto-locks while a request is waiting, extension 1.9.2 and later reject it at once with WALLET_LOCKED; ask again after the user unlocks. Older versions dropped it, so it ended with Request timeout.
If the submit step of signAndSubmit fails, the call rejects and you do not get the txHash of the transaction the user already signed. If you need the hash in that case, call signTransaction() and then submitTransaction() yourself.
import { WalletSdkError } from '@amadeus-protocol/wallet-sdk'
function describeError(error: unknown): string {
if (error instanceof WalletSdkError) {
switch (error.code) {
case 'UNSUPPORTED':
return 'Your wallet version does not support this action. Update the extension.'
case 'SUBMIT_FAILED':
return `The node did not accept the request: ${error.message}`
case 'INVALID_ARGUMENT':
return error.message
default:
return `${error.code}: ${error.message}`
}
}
// Wallet rejections, timeouts and fetch failures are plain Errors
if (error instanceof Error && error.message === 'WALLET_LOCKED') {
return 'The wallet locked. Unlock it and try again.'
}
return error instanceof Error ? error.message : String(error)
}
When no provider is injected, getAccount, getNetwork, signTransaction, on, off and ensureApiKey (when it has no valid cached key) throw synchronously instead of returning a rejected promise. Inside an async function with await this is caught by try. Elsewhere, check wallet.isAvailable() first.
The full list of WalletSdkErrorCode values is in the Provider reference.
WalletClient reference
createInjectedWalletClient(providerOverride?) returns a WalletClient. Pass an AmadeusProvider as providerOverride to use it instead of window.amadeus, for example a mock in tests.
| Member | Returns | Description |
|---|---|---|
isAvailable() | boolean | Whether a provider with isAmadeus === true is injected |
getProvider() | AmadeusProvider | null | The raw provider, for methods the client does not wrap such as requestSwitchNetwork, getPendingRequests and cancelRequest |
connect() | Promise<string> | Calls requestAccounts() and resolves to the first account |
getAccount() | Promise<string | null> | The active account, without a prompt |
getNetwork() | Promise<string> | The active network |
switchAccount(target?) | Promise<string> | Asks the user to switch accounts; UNSUPPORTED if the provider lacks requestSwitchAccount |
signTransaction(request) | Promise<SignTransactionResponse> | Signs without submitting |
signAndSubmit(request, { nodeUrl, wait? }) | Promise<{ txHash: string; submitted: unknown }> | Signs, then calls submitTransaction |
ensureApiKey({ aud, expIn, store?, leewaySeconds? }) | Promise<string> | Cached or newly issued API key for aud |
on(event, callback), off(event, callback) | void | Subscribe to and unsubscribe from provider events |
End-to-end example
This example puts everything together in one page with no framework. It runs in any bundler that serves ES modules, for example Vite. On load it reads the active account and network with getAccount() and getNetwork(), which never open a prompt, so a returning user with an unlocked wallet does not need to click Connect.
index.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Amadeus dApp</title>
</head>
<body>
<p id="status">Looking for Amadeus Wallet...</p>
<button id="connect">Connect</button>
<button id="switch" disabled>Switch account</button>
<p>
<input id="recipient" placeholder="Recipient address" />
<input id="amount" placeholder="Amount in AMA" value="1" />
<button id="send" disabled>Send</button>
</p>
<script type="module" src="./main.ts"></script>
</body>
</html>
main.ts:
import { toAtomicAma, type TransactionReceipt } from '@amadeus-protocol/sdk'
import {
createInjectedWalletClient,
WALLET_INITIALIZED_EVENT,
WalletSdkError
} from '@amadeus-protocol/wallet-sdk'
const NODE_URLS: Record<string, string> = {
mainnet: 'https://mainnet-rpc.ama.one/api',
testnet: 'https://testnet-rpc.ama.one/api'
}
const wallet = createInjectedWalletClient()
const element = <ElementType extends HTMLElement>(id: string) =>
document.getElementById(id) as ElementType
const statusText = element<HTMLParagraphElement>('status')
const connectButton = element<HTMLButtonElement>('connect')
const switchButton = element<HTMLButtonElement>('switch')
const sendButton = element<HTMLButtonElement>('send')
const recipientInput = element<HTMLInputElement>('recipient')
const amountInput = element<HTMLInputElement>('amount')
const state = { account: null as string | null, network: null as string | null }
function render(message?: string): void {
const connected = state.account
? `Connected: ${state.account} (${state.network})`
: 'Not connected'
statusText.textContent = message ? `${connected}. ${message}` : connected
switchButton.disabled = !state.account
sendButton.disabled = !state.account
}
function describeError(error: unknown): string {
if (error instanceof WalletSdkError) {
return error.code === 'UNSUPPORTED'
? 'Update the Amadeus Wallet extension to use this action.'
: `${error.code}: ${error.message}`
}
return error instanceof Error ? error.message : String(error)
}
function waitForWallet(timeoutMs = 3000): Promise<boolean> {
if (wallet.isAvailable()) return Promise.resolve(true)
return new Promise((resolve) => {
const onReady = () => {
clearTimeout(timer)
resolve(true)
}
const timer = setTimeout(() => {
window.removeEventListener(WALLET_INITIALIZED_EVENT, onReady)
resolve(wallet.isAvailable())
}, timeoutMs)
window.addEventListener(WALLET_INITIALIZED_EVENT, onReady, { once: true })
})
}
function assertExecuted(submitted: unknown): void {
const reply = submitted as { error?: string; receipt?: TransactionReceipt }
if (reply.error !== 'ok') throw new Error(`Node rejected the transaction: ${reply.error}`)
if (reply.receipt && !reply.receipt.success) {
throw new Error(`Transaction failed: ${JSON.stringify(reply.receipt.result)}`)
}
}
async function connect(): Promise<void> {
try {
state.account = await wallet.connect()
state.network = await wallet.getNetwork()
render()
} catch (error) {
render(describeError(error))
}
}
async function switchAccount(): Promise<void> {
try {
state.account = await wallet.switchAccount()
render()
} catch (error) {
render(describeError(error))
}
}
async function send(): Promise<void> {
const nodeUrl = state.network ? NODE_URLS[state.network] : undefined
if (!nodeUrl) {
render(`No node URL configured for network "${state.network}".`)
return
}
const atomicAmount = toAtomicAma(amountInput.value)
if (!Number.isFinite(atomicAmount) || atomicAmount <= 0) {
render('Enter a valid amount.')
return
}
try {
render('Waiting for approval in the wallet...')
const { txHash, submitted } = await wallet.signAndSubmit(
{
contract: 'Coin',
method: 'transfer',
args: [recipientInput.value.trim(), String(atomicAmount), 'AMA']
},
{ nodeUrl, wait: true }
)
assertExecuted(submitted)
render(`Sent. Transaction ${txHash}`)
} catch (error) {
render(describeError(error))
}
}
async function start(): Promise<void> {
if (!(await waitForWallet())) {
statusText.textContent = 'Install the Amadeus Wallet extension, then reload this page.'
connectButton.disabled = true
return
}
wallet.on('accountsChanged', ({ accounts }) => {
state.account = accounts[0] ?? null
render()
})
wallet.on('networkChanged', ({ network }) => {
state.network = network
render()
})
wallet.on('disconnect', () => {
state.account = null
render()
})
connectButton.addEventListener('click', () => void connect())
switchButton.addEventListener('click', () => void switchAccount())
sendButton.addEventListener('click', () => void send())
try {
state.network = await wallet.getNetwork()
state.account = await wallet.getAccount()
render()
} catch (error) {
render(describeError(error))
}
}
void start()
Try it on testnet first. Switch the extension to testnet, get testnet AMA as described in Testnet faucet, and the example sends through https://testnet-rpc.ama.one/api. A wallet on the custom network has no entry in NODE_URLS, so the example refuses to send.
Next steps
- React: the same flow with the
useWallethook. - Signing and API keys: byte arguments, network-bound signatures and verifying API keys on your backend.
- Provider reference: every provider method, event payload and error code.
- Amadeus Connect (mobile): connect to the mobile wallet with a QR code or deep link.
- Integration Guide: the extension's own guide to the raw
window.amadeusAPI.