Build a wallet integration
Answer dApp requests from your own wallet with @amadeus-protocol/wallet-sdk: the request pipeline, handleRequest, user approval, app-delegated account and network switching, and sending responses back over the relay.
Overview
This page is for teams that build a wallet: a mobile app, a browser extension or a third-party signer. It covers the wallet side of a request: receiving it, checking it, asking the user, signing and replying.
The core of the wallet side is handleRequest from wallet/handler. It takes one request that is already decrypted, checked and approved, and returns a response that is ready to encrypt. It routes each method to the right signing helper, so every wallet signs requests the same way.
Its signature is handleRequest(request: WalletRequest, ctx: WalletHandlerContext): WalletResponse. The context tells it who signs:
WalletHandlerContext field | Type | Meaning |
|---|---|---|
seed | string | Base58 seed (private key) of the account that signs |
address | string | Base58 address of that account |
network | NetworkType (optional) | Network to sign transactions for, from @amadeus-protocol/sdk. Defaults to mainnet. |
handleRequest does not ask the user, check expiry, prevent replays, pick the account or send anything. Your wallet does those steps around it, as described below.
This page covers version 0.2.0. The dApp side of the same protocol is in Amadeus Connect (mobile). The connect handshake (parseConnectUri, approveConnect and the connect response) is covered in Wallet side of the handshake. This page starts after the handshake, when your wallet holds a WalletSession.
How the Amadeus wallets use it
| Wallet | Uses wallet-sdk | What it uses |
|---|---|---|
| Amadeus mobile wallet | Yes (^0.1.5, locked to 0.1.5) | The full transport path. Connect: parseConnectUri, isConnectRequestExpired, assertAllowedBridgeUrl, approveConnect, buildConnectResponseUri and deriveConnectChannel. Requests: BridgeClient, deriveBridgeChannels, openRequest, guardRequest, createMemorySeenStore, handleRequest and sealResponse. |
| Amadeus Chrome extension | No | It implements the injected window.amadeus provider with its own background handlers. Its request types and signing behavior match the SDK, but it does not import the package. |
If you build a wallet for the QR, deep-link and relay transport, follow the mobile wallet's pattern, which is the one shown on this page. If you build an injected browser wallet, see Injected (extension-style) wallets.
The request pipeline
Every request from a connected dApp goes through these steps in order:
- Receive a sealed frame on the session's
toWalletrelay channel. - Open it with
openRequest. This decrypts the frame and checks its structure. - Guard it with
guardRequest. This rejects expired and replayed requests. - Route it by method. Some methods need no approval, some are handled by your app, and the rest go to the approval queue.
- Validate and show the params using the zod schemas, then ask the user.
- Re-check expiry after the user approves, then resolve the signer from
request.account. - Sign with
handleRequest. - Respond: seal the response with
sealResponseand send it to the session'stoDappchannel.
On rejection, or when any step after 3 fails, send an error response instead of staying silent. Otherwise the dApp waits until it gives up.
1. Listen for requests
After the connect handshake, both sides hold the same 32-byte sharedKey. deriveBridgeChannels(sharedKey) turns it into two secret channel ids: the wallet listens on toWallet and sends to toDapp. Because the ids come from the shared key, someone who only saw the connect QR code cannot read from or write to the session's channels.
import {
BridgeClient,
createMemorySeenStore,
DEFAULT_BRIDGE_URL,
deriveBridgeChannels,
guardRequest,
openRequest,
type SealedEnvelope
} from '@amadeus-protocol/wallet-sdk'
const seenStore = createMemorySeenStore()
const channels = deriveBridgeChannels(session.sharedKey)
const client = new BridgeClient({
bridgeUrl: session.bridgeUrl ?? DEFAULT_BRIDGE_URL,
clientId: channels.toWallet
})
const stop = client.start((frame) => {
try {
const request = openRequest(session.sharedKey, frame.payload as SealedEnvelope)
guardRequest(request, seenStore)
routeRequest(request)
} catch {
// Undecryptable, malformed, expired or replayed: drop it.
}
})
Here session is the WalletSession returned by approveConnect. start also takes an optional second onError callback for failed polls; the client retries after one second either way, except after a hung poll (see the BridgeClient warning). Keep client, channels and stop per session. Call stop() when the user disconnects the dApp or locks the wallet. The mobile wallet stops every session listener on lock.
What each call checks:
| Call | Checks | Throws |
|---|---|---|
new BridgeClient(...) | The relay URL is https, or http on localhost, 127.0.0.1 or ::1 only | INVALID_ARGUMENT |
openRequest(sharedKey, envelope) | The envelope decrypts under the session key, the plaintext is JSON, and it matches the request envelope schema | DECRYPT_FAILED or INVALID_ARGUMENT |
guardRequest(request, store, now?) | exp is in the future, and the id was not seen before. It then records the id. | EXPIRED or INVALID_ARGUMENT (duplicate request id (replay)) |
openRequest does not check expiry or replay; only guardRequest does. Always call both, in this order, before you act on a request. To reject unknown protocol versions, also compare request.v with PROTOCOL_VERSION; see Provider reference.
createMemorySeenStore() keeps request ids in memory, up to 10,000 by default. When the app restarts, a captured request can be replayed until its exp passes, which is 120 seconds after creation by default. The SDK recommends a persisted SeenStore (for example on top of secure storage) where has and add are atomic. The mobile wallet uses the in-memory store. Its sessions, and their shared keys, are also kept only in memory, so after a restart old frames can no longer be opened.
2. Route by method
WALLET_METHODS lists the six methods a dApp can send. Your wallet must handle each of them:
| Method | Who handles it | Needs approval | Result sent back |
|---|---|---|---|
amadeus_signTransaction | handleRequest | Yes | { txHash, txPacked } |
amadeus_signMessage | handleRequest | Yes | { message, signature, address } |
amadeus_generateApiKey | handleRequest | Yes | { apiKey } |
amadeus_getAccounts | handleRequest, or your app | Your choice | { accounts: string[] } from handleRequest |
amadeus_switchAccount | Your app | Yes, always | Not defined by the SDK; see below |
amadeus_switchNetwork | Your app | Yes | Not defined by the SDK |
handleRequest refuses amadeus_switchAccount and amadeus_switchNetwork on purpose, because they change the wallet's state. It returns INVALID_ARGUMENT with the message amadeus_switchAccount must be handled by the wallet app (it changes the active account) or amadeus_switchNetwork must be handled by the wallet app (it changes runtime state). Catch these two methods before you call it:
import type { WalletRequest } from '@amadeus-protocol/wallet-sdk'
function routeRequest(request: WalletRequest): void {
switch (request.method) {
case 'amadeus_getAccounts':
void answerGetAccounts(request)
return
case 'amadeus_switchAccount':
void promptSwitchAccount(request)
return
case 'amadeus_switchNetwork':
void promptSwitchNetwork(request)
return
default:
enqueueForApproval(request)
}
}
The mobile wallet answers amadeus_getAccounts without asking the user and without calling handleRequest. It returns every wallet account as { accounts: { address, name }[] }. handleRequest returns only the context account, as { accounts: [address] }. dApps are told to accept both shapes. Pick one for your wallet and document it.
3. Validate and ask the user
handleRequest has no approval hooks or callbacks. Approval is entirely up to your app: show the request, wait for the user, and call handleRequest only after an explicit approve. The mobile wallet also asks for biometric or device authentication before it signs.
Request params are untrusted input. Parse them with the same schemas that handleRequest uses before you render anything, so the screen shows exactly what will be signed:
import {
describeBinaryValues,
generateApiKeyRequestSchema,
signMessageRequestSchema,
signTransactionRequestSchema,
type WalletRequest
} from '@amadeus-protocol/wallet-sdk'
type ApprovalSummary =
| { kind: 'transaction'; contract: string; method: string; args: unknown; isTransfer: boolean }
| { kind: 'message'; message: string }
| { kind: 'apiKey'; audience: string; expiresInSeconds: number }
| { kind: 'invalid' }
function summarizeRequest(request: WalletRequest): ApprovalSummary {
if (request.method === 'amadeus_signTransaction') {
const parsed = signTransactionRequestSchema.safeParse(request.params)
if (!parsed.success) return { kind: 'invalid' }
const { contract, method, args } = parsed.data
return {
kind: 'transaction',
contract,
method,
args: describeBinaryValues(args),
isTransfer: contract === 'Coin' && method === 'transfer'
}
}
if (request.method === 'amadeus_signMessage') {
const parsed = signMessageRequestSchema.safeParse(request.params)
return parsed.success ? { kind: 'message', message: parsed.data.message } : { kind: 'invalid' }
}
if (request.method === 'amadeus_generateApiKey') {
const parsed = generateApiKeyRequestSchema.safeParse(request.params)
return parsed.success
? { kind: 'apiKey', audience: parsed.data.aud, expiresInSeconds: parsed.data.exp_in }
: { kind: 'invalid' }
}
return { kind: 'invalid' }
}
If the summary is invalid, reply with an INVALID_ARGUMENT error right away instead of showing a screen. The full list of schemas is in Provider reference.
What to show for each method:
| Method | Show | Warn about |
|---|---|---|
amadeus_signTransaction | contract.method and all arguments, plus the amount and recipient for Coin.transfer | Any call that is not Coin.transfer: the user should check the contract, method and arguments |
amadeus_signMessage | The full message text, up to 4,096 characters | The signature proves control of the account and can be used to log in |
amadeus_generateApiKey | aud (audience) and exp_in (lifetime in seconds) | The token is a bearer credential until it expires |
| Every request | The session origin and the account that will sign |
Rules that apply to every approval screen:
- Show the session's origin, not
request.origin.request.originis a string the dApp puts inside the envelope. The trusted origin is the one the user approved during the connect handshake, which is bound into the connect signature. The mobile wallet shows the session origin. - Show binary arguments readably. Arguments that hold raw bytes arrive tagged as
{ "__amadeusBytes__": "<base64>" }.describeBinaryValuesreplaces each tag with"<bytes[N] base64:...>"for display.handleRequestdecodes the tags itself before signing. See Signing and API keys. - Do not trust
description. The optionaldescriptiononsignTransactionis set by the dApp and is not part of what gets signed. If you show it, label it as text from the dApp. - Show requests one at a time. The mobile wallet keeps a single pending request and queues up to 20 more; it drops requests beyond that, so a dApp cannot flood the user with prompts.
4. Sign and respond
When the user approves, re-check expiry, because the request may have waited in the queue past its exp. Then pick the signing account, call handleRequest and send the sealed response to the toDapp channel:
import type { NetworkType } from '@amadeus-protocol/sdk'
import {
type BridgeClient,
deriveBridgeChannels,
handleRequest,
PROTOCOL_VERSION,
sealResponse,
type WalletRequest,
type WalletResponse,
type WalletSession
} from '@amadeus-protocol/wallet-sdk'
interface WalletAccount {
id: string
address: string
}
function errorResponse(request: WalletRequest, code: string, message: string): WalletResponse {
return { v: PROTOCOL_VERSION, id: request.id, ok: false, error: { code, message } }
}
async function sendResponse(response: WalletResponse): Promise<void> {
const channels = deriveBridgeChannels(session.sharedKey)
await client.send(channels.toDapp, response.id, sealResponse(session.sharedKey, response))
}
function buildApprovedResponse(request: WalletRequest): WalletResponse {
// The request may have waited in the approval queue past its TTL.
if (request.exp <= Math.floor(Date.now() / 1000)) {
return errorResponse(request, 'EXPIRED', 'request has expired')
}
const signer = request.account
? accounts.find((account) => account.address === request.account)
: boundAccount
if (!signer) {
return errorResponse(request, 'INVALID_ARGUMENT', 'requested account is not in this wallet')
}
return handleRequest(request, {
seed: getAccountSeed(signer.id),
address: signer.address,
network: activeNetwork
})
}
async function onApprove(request: WalletRequest): Promise<void> {
await sendResponse(buildApprovedResponse(request))
}
async function onReject(request: WalletRequest): Promise<void> {
await sendResponse(errorResponse(request, 'USER_REJECTED', 'User rejected the request'))
}
In this example, accounts is the list of accounts in your wallet, boundAccount is the account the user chose during connect, activeNetwork is the wallet's current NetworkType, and getAccountSeed reads a seed from your vault. It should throw when the wallet is locked, so signing is blocked while locked.
How each context field is used:
| Field | Rule |
|---|---|
seed, address | handleRequest ignores request.account, so you pick the signer. If request.account is set, it must be one of your wallet's accounts; otherwise use the account bound to the session at connect. This lets a dApp with several accounts choose the signer per request without reconnecting. Make sure address belongs to seed: getAccounts returns address, but signMessage reports the address derived from seed. |
network | Pass the wallet's active network. Transactions are signed with that network's domain separation tag, so a testnet transaction cannot be replayed on mainnet. If you leave it out, mainnet is used. Only testnet has its own tag: custom signs with the mainnet tag. The type is the NetworkType enum from @amadeus-protocol/sdk. A string that passed networkSchema has to be converted to it. |
handleRequest never throws. Every failure becomes an error response:
error.code | When |
|---|---|
INVALID_ARGUMENT | Params fail their schema (invalid signTransaction params, invalid generateApiKey params, invalid signMessage params), the method is amadeus_switchAccount or amadeus_switchNetwork, or the method is unknown |
INTERNAL | Anything other than a WalletSdkError was thrown, for example by the core SDK while it built the transaction (such as an invalid Base58 Coin.transfer recipient) |
A WalletSdkError thrown inside a signing helper keeps its own code, but in 0.2.0 those helpers only throw INVALID_ARGUMENT. INTERNAL is not one of the WalletSdkErrorCode values, and WalletResponse.error.code is typed as string. The wallet only signs. For transactions, the dApp submits txPacked to a node itself. The result shapes are described in Signing and API keys.
Always answer a rejected request. Version 0.2.0 defines no standard rejection code, so the example uses USER_REJECTED with the same message the Chrome extension uses. Choose a code and document it for dApps. The mobile wallet currently closes the prompt on Reject without replying, so the dApp gets no answer. It also shows a local error, without replying, when an approved request has expired or names an account it does not hold.
App-delegated switchAccount and switchNetwork
amadeus_switchAccount and amadeus_switchNetwork change wallet state, so the SDK leaves them to your app. Implement them yourself and never pass them to handleRequest.
For amadeus_switchAccount:
- Validate
paramswithswitchAccountRequestSchema, which accepts{ account?: string }. Whenaccountis present, it must be a valid 48-byte Base58 address. - Treat
accountonly as a hint. Always open your own account picker and let the user confirm or choose another account. A dApp must never switch accounts silently. - On approval, make the chosen account the one this session signs with when
request.accountis absent. - Reply with a success response, or with your rejection code if the user cancels.
import {
PROTOCOL_VERSION,
switchAccountRequestSchema,
type WalletRequest
} from '@amadeus-protocol/wallet-sdk'
async function promptSwitchAccount(request: WalletRequest): Promise<void> {
const parsed = switchAccountRequestSchema.safeParse(request.params)
if (!parsed.success) {
await sendResponse(errorResponse(request, 'INVALID_ARGUMENT', 'invalid switchAccount params'))
return
}
const chosen = await chooseAccount(parsed.data.account)
if (!chosen) {
await sendResponse(errorResponse(request, 'USER_REJECTED', 'User rejected the request'))
return
}
bindSessionAccount(chosen)
await sendResponse({ v: PROTOCOL_VERSION, id: request.id, ok: true, result: chosen })
}
sendResponse and errorResponse are the helpers from step 4. chooseAccount is your account picker; it resolves to the chosen address, or to null if the user cancels.
Version 0.2.0 does not define a result shape for amadeus_switchAccount or amadeus_switchNetwork over the relay, and no SDK client sends them yet. The example returns the new Base58 address, which matches what requestSwitchAccount() resolves to on the injected provider. The mobile wallet does not handle these two methods yet: it shows them as a generic request and, if the user approves, passes them to handleRequest, so the dApp gets INVALID_ARGUMENT. On reject it sends nothing.
For amadeus_switchNetwork, version 0.2.0 defines no params schema or shape; the SDK's own tests send { network: 'testnet' }. Use networkSchema to check that the requested network is mainnet, testnet or custom, ask the user, switch, and reply. After a switch, pass the new network to handleRequest so later transactions are signed for it.
The Chrome extension's requestSwitchAccount flow, which predates the relay, is a good model:
- The address hint is not checked against the vault before the user acts. A known address and an unknown one take the same path, so a page cannot use the request to learn which addresses the wallet holds.
- If the wallet is unlocked and the hinted account is already active, the extension resolves at once without a prompt. This reveals only the active address, which
requestAccountsalready shares. - The account the user picks is checked against the unlocked vault before the active account changes.
- Pending switch requests expire after 120 seconds, and are rejected when the tab closes or navigates away.
Injected (extension-style) wallets
A browser wallet that injects window.amadeus implements the AmadeusProvider interface instead of the relay transport. The interface, its events and the window events are listed in Provider reference. The extension's own dApp guide is the Integration Guide.
The same rules apply: validate params with the schemas, show every argument, ask the user, then sign. One difference: take the origin from the browser (for example chrome.runtime.MessageSender), never from the page. The Amadeus extension does this.
You can reuse handleRequest in an injected wallet by wrapping a validated page message in a WalletRequest:
import type { NetworkType } from '@amadeus-protocol/sdk'
import { handleRequest, makeRequest } from '@amadeus-protocol/wallet-sdk'
const request = makeRequest({
id: pageRequestId,
method: 'amadeus_signTransaction',
origin: senderOrigin,
params: pageParams
})
const response = handleRequest(request, {
seed: activeAccount.seed,
address: activeAccount.address,
network: activeNetwork
})
Then turn response into your provider's resolve or reject. The Amadeus extension does not do this today: it has its own handlers with matching behavior, including the __amadeusBytes__ binary encoding and the Coin.transfer recipient conversion. requestSwitchAccount is optional in the type, and WalletClient.switchAccount fails with UNSUPPORTED when a provider does not implement it. Message signing has no provider method.
Checklist
Before you ship, check that your wallet:
- calls
openRequestand thenguardRequeston every frame, and drops anything that throws; - uses a persisted, atomic
SeenStoreif replay protection must survive a restart; - validates params with the zod schemas before showing an approval screen;
- shows the session origin, the signing account,
contract.methodand every argument; - calls
handleRequestonly after an explicit approval, and re-checksexpfirst; - resolves the signer from
request.accountagainst its own accounts, and falls back to the session's bound account; - passes the active
networkso testnet transactions are signed for testnet; - handles
amadeus_switchAccountandamadeus_switchNetworkitself, with a user prompt every time; - replies to every request, including rejections, so the dApp is not left waiting;
- stops relay listeners and blocks signing while the wallet is locked.
Related
- Wallet SDK overview: install, entry points and module map
- Amadeus Connect (mobile): the connect handshake and the dApp side of the relay
- Provider reference:
AmadeusProvider, wire methods, schemas and error codes - Signing and API keys: the helpers
handleRequestcalls, binary arguments and result shapes - Connect a dApp and React: the dApp side of the injected provider
- Core SDK:
NetworkType, transaction building and submission