Amadeus Connect (mobile)
Connect a dApp to the Amadeus mobile wallet with a QR code or deep link, an end-to-end encrypted session and the bridge relay.
Amadeus Connect is the protocol a dApp uses to talk to the Amadeus mobile wallet. It works across devices (a desktop dApp and a phone that scans a QR code) and on the same device (a mobile browser that opens the wallet app through a link). Everything ships in @amadeus-protocol/wallet-sdk; see the Wallet SDK overview for install.
If your users have the browser extension, use the injected provider instead: see Connect a dApp and the extension integration guide.
The protocol has three parts:
| Part | Module | What it does |
|---|---|---|
| Connect handshake | transport/session, transport/uri, crypto/connect | The dApp shows an amadeus://v1/connect URI. The wallet signs a transcript that binds the dApp origin and both session keys, and returns its address. |
| Sealed envelopes | transport/envelope, crypto/box | After connect, every request and response is encrypted with a key that only the dApp and the wallet hold. |
| Bridge relay | transport/bridge | A long-poll relay (https://bridge.ama.one by default) carries frames between the two devices. It only sees ciphertext. |
The wallet only signs. For transactions it returns the signed bytes and your dApp submits them to a node. See Signing and API keys.
Message sequence
Cross-device flow (QR code plus relay), as used by the mobile wallet and the amadeus-connect-demo app:
dApp (browser) Relay Mobile wallet
────────────── ───── ─────────────
createConnectRequest()
show amadeus://v1/connect?… as QR
poll /events (connect channel) ────────►
scan QR → parseConnectUri()
check expiry, bridge URL
user approves
approveConnect()
◄──────── POST /message (connect channel)
ConnectResponseParams, plaintext
◄──────── frame
completeConnect()
= verifyConnect() + derive sharedKey (wallet already has sharedKey)
both sides: deriveBridgeChannels(sharedKey) → { toWallet, toDapp }
poll /events (toWallet)
makeRequest() + sealRequest()
POST /message (toWallet) ──────────────►
──────────► frame
openRequest() + guardRequest()
user approves
handleRequest() + sealResponse()
◄──────── POST /message (toDapp)
poll /events (toDapp)
◄──────── frame
openResponse()
| # | Direction | Carried by | Payload | Encrypted |
|---|---|---|---|---|
| 1 | dApp → wallet | QR code, link or Universal Link | Connect URI | No: public handshake data |
| 2 | wallet → dApp | Relay, channel deriveConnectChannel(dappPublicKey), frame id = request id. Also the redirect URL on the same device. | ConnectResponseParams | No: its integrity is protected by the connect signature |
| 3 | dApp → wallet | Relay, channel toWallet | Sealed WalletRequest | Yes |
| 4 | wallet → dApp | Relay, channel toDapp | Sealed WalletResponse | Yes |
Connect from a dApp
1. Create the request and wait for the wallet
createConnectRequest generates a fresh session keypair, a 16-byte challenge and a request id. It returns the uri to show and the pending state to keep in memory. The request expires after 120 seconds unless you pass ttlSeconds.
The dApp then listens on the connect channel, which is derived from its own public session key, and completes the session when the wallet's response arrives:
import {
BridgeClient,
completeConnect,
createConnectRequest,
DEFAULT_BRIDGE_URL,
deriveConnectChannel,
type ConnectResponseParams,
type EstablishedSession
} from '@amadeus-protocol/wallet-sdk'
declare function renderQrCode(uri: string): void
export function connectMobileWallet(): Promise<EstablishedSession> {
const { uri, pending } = createConnectRequest({ origin: window.location.origin })
renderQrCode(uri)
const bridgeUrl = pending.bridgeUrl ?? DEFAULT_BRIDGE_URL
const listener = new BridgeClient({
bridgeUrl,
clientId: deriveConnectChannel(pending.dappKeypair.publicKey)
})
return new Promise((resolve, reject) => {
const stop = listener.start((frame) => {
try {
const session = completeConnect(pending, frame.payload as ConnectResponseParams)
stop()
clearTimeout(timer)
resolve(session)
} catch {
// The connect channel is public, so skip frames that fail verification.
}
})
const timer = setTimeout(() => {
stop()
reject(new Error('Connect request expired'))
}, pending.exp * 1000 - Date.now())
})
}
completeConnect checks that the response matches pending.requestId (INVALID_ARGUMENT if not), verifies the connect signature against the transcript (BAD_SIGNATURE if it fails) and derives the shared key. The result is an EstablishedSession:
| Field | Type | Meaning |
|---|---|---|
address | string | The wallet account bound to this session (Base58 public key) |
sharedKey | Uint8Array | 32-byte key for sealing and opening envelopes. Keep it in memory only. |
walletPublicKey | string | The wallet's x25519 session public key |
selfPublicKey | string | The dApp's x25519 session public key |
origin | string | The origin the wallet approved |
bridgeUrl | string | undefined | The relay to use for requests |
createConnectRequest always puts a bridge parameter in the URI. When you don't pass bridgeUrl it uses DEFAULT_BRIDGE_URL (https://bridge.ama.one). It does not validate the URL; the BridgeClient constructor does.
2. Send requests over the session
Both sides derive the same two channel ids from the shared key with deriveBridgeChannels: the dApp sends on toWallet and listens on toDapp. The relay drains a channel when it is polled, so keep one listener per session and route responses by id:
import {
BridgeClient,
DEFAULT_BRIDGE_URL,
deriveBridgeChannels,
makeRequest,
openResponse,
randomId,
sealRequest,
type EstablishedSession,
type SealedEnvelope,
type WalletMethod
} from '@amadeus-protocol/wallet-sdk'
interface Waiter {
resolve: (result: unknown) => void
reject: (error: unknown) => void
}
export function openWalletChannel(session: EstablishedSession, timeoutMs = 120_000) {
const channels = deriveBridgeChannels(session.sharedKey)
const client = new BridgeClient({
bridgeUrl: session.bridgeUrl ?? DEFAULT_BRIDGE_URL,
clientId: channels.toDapp
})
const waiters = new Map<string, Waiter>()
const stop = client.start((frame) => {
const waiter = waiters.get(frame.id)
if (!waiter) return
waiters.delete(frame.id)
try {
const response = openResponse(session.sharedKey, frame.payload as SealedEnvelope, frame.id)
if (response.ok) {
waiter.resolve(response.result)
} else {
waiter.reject(new Error(`${response.error.code}: ${response.error.message}`))
}
} catch (error) {
waiter.reject(error)
}
})
const request = async (method: WalletMethod, params: unknown, account?: string) => {
const id = randomId()
const reply = new Promise<unknown>((resolve, reject) => {
waiters.set(id, { resolve, reject })
// The wallet sends nothing back when the user rejects, so time out.
setTimeout(() => {
if (waiters.delete(id)) reject(new Error(`${method} timed out`))
}, timeoutMs)
})
const walletRequest = makeRequest({ id, method, origin: session.origin, params, account })
try {
await client.send(channels.toWallet, id, sealRequest(session.sharedKey, walletRequest))
} catch (error) {
waiters.delete(id)
throw error
}
return reply
}
return { request, close: stop }
}
Then call the wallet through the object openWalletChannel(session) returns. The optional account argument picks which of the wallet's accounts signs, without reconnecting:
import { toAtomicAma } from '@amadeus-protocol/sdk'
import { submitTransaction, verifyMessage } from '@amadeus-protocol/wallet-sdk'
declare const recipientAddress: string
declare const wallet: {
request: (method: 'amadeus_signTransaction' | 'amadeus_signMessage', params: unknown, account?: string) => Promise<unknown>
}
const signed = (await wallet.request('amadeus_signTransaction', {
contract: 'Coin',
method: 'transfer',
args: [recipientAddress, String(toAtomicAma(1)), 'AMA']
})) as { txHash: string; txPacked: number[] }
await submitTransaction(signed.txPacked, { nodeUrl: 'https://mainnet-rpc.ama.one/api', wait: true })
const proof = (await wallet.request('amadeus_signMessage', { message: 'Sign in to Example' })) as {
message: string
signature: string
address: string
}
const isValid = verifyMessage(proof)
Methods over Amadeus Connect
WALLET_METHODS lists the six methods a WalletRequest can carry. This is how the mobile wallet answers them:
| Method | params | Result |
|---|---|---|
amadeus_getAccounts | {} | Answered without a prompt. The mobile wallet returns { accounts: { address, name }[] }; the SDK's handleRequest returns { accounts: string[] }. Accept both shapes. |
amadeus_signTransaction | { contract, method, args, description? } | { txHash, txPacked }. Submit txPacked yourself, to a node on the network selected in the wallet: the signature is bound to it, and no method reports it over this transport. |
amadeus_signMessage | { message } (1 to 4096 UTF-16 code units) | { message, signature, address }. Check it with verifyMessage. |
amadeus_generateApiKey | { aud, exp_in } (exp_in in seconds) | { apiKey } |
amadeus_switchNetwork | Not supported over this transport today. The wallet shows an approval prompt, then answers ok: false (INVALID_ARGUMENT). | |
amadeus_switchAccount | Not supported over this transport today. The wallet shows an approval prompt, then answers ok: false (INVALID_ARGUMENT). Pass account on each request instead. |
Argument encoding, network-specific signing and API keys are covered in Signing and API keys.
The mobile wallet sends no response when the user taps Reject, when a request expires while waiting for approval, or when account is not one of its accounts. Always put a timeout on requests, as in the example above.
Same device: deep links and Universal Links
On a phone, the dApp can open the wallet directly instead of showing a QR code. Pass redirectLink so the wallet can send the user back:
import {
completeConnect,
createConnectRequest,
parseConnectResponseUri,
type PendingConnect
} from '@amadeus-protocol/wallet-sdk'
const { uri, pending } = createConnectRequest({
origin: 'https://app.example.com',
redirectLink: 'https://app.example.com/connected'
})
// Reliable on iOS, where amadeus:// links often never reach the app.
const universalLink = uri.replace(/^amadeus:\/\//, 'https://wallet.ama.one/')
export function finishFromCallback(pendingConnect: PendingConnect, callbackUrl: string) {
return completeConnect(pendingConnect, parseConnectResponseUri(callbackUrl))
}
After approval the wallet opens redirectLink with id, address, wallet_key and sig appended to the query string, and parseConnectResponseUri reads them back. Because the URI also carries a bridge parameter, the wallet also posts the response to the connect channel, so the listener from step 1 completes the session too. With the mobile wallet, requests after connect always go through the relay.
The mobile wallet accepts a connect request in three forms:
| Form | Example | Notes |
|---|---|---|
| Custom scheme | amadeus://v1/connect?… | The only form buildConnectUri and parseConnectUri handle. On iOS it often does not reach the app. |
| Universal Link / App Link | https://wallet.ama.one/v1/connect?… | The reliable way to open the app from a link on iOS. If the app is not installed, the link opens wallet.ama.one in the browser, which does not handle connect requests. |
| Bare path | v1/connect?… | Normalized by the app |
Keep the QR code in the amadeus:// form. The wallet's in-app scanner and paste field call parseConnectUri directly, which rejects any scheme other than amadeus. Use the https://wallet.ama.one/ form only for links the user taps.
URI reference
Connect request
buildConnectUri(params) builds amadeus://v1/connect?… from ConnectRequestParams; parseConnectUri(uri) reverses it. The scheme is exported as URI_SCHEME ('amadeus'). Empty or missing optional values are left out.
| Query key | ConnectRequestParams field | Required | Meaning |
|---|---|---|---|
origin | origin | Yes | The dApp origin shown to the user and bound into the signature |
dapp_key | dappPublicKey | Yes | The dApp's x25519 session public key (Base58, 32 bytes) |
challenge | challenge | Yes | Random nonce chosen by the dApp |
id | requestId | Yes | Unique id for this connect request |
exp | exp | Yes | Expiry in Unix seconds (integer) |
redirect | redirectLink | No | Same-device return URL |
bridge | bridgeUrl | No | Relay base URL for the session |
Example:
amadeus://v1/connect?origin=https%3A%2F%2Fapp.example.com&dapp_key=CE72qwyHfNt5z6ZaHrcfpwpRLQ6wqVY8eufaC2YbrB8U&challenge=DMrMNDSVhmJ2qZ3z9NS3dL&id=6f3b3e7f9de439bf4ef49594898d532b&exp=1794238804&bridge=https%3A%2F%2Fbridge.ama.one
parseConnectUri throws INVALID_ARGUMENT for a wrong scheme or path, when a required field is missing, or when exp is not an integer. It does not check the origin scheme, the key length, the expiry or the bridge URL; a wallet must do that itself (see Wallet side).
Connect response
buildConnectResponseUri(redirectLink, response) appends the response to redirectLink, using ? or & as needed. parseConnectResponseUri(uri) reads it back and throws INVALID_ARGUMENT if a field is missing.
| Query key | ConnectResponseParams field | Meaning |
|---|---|---|
id | requestId | Echo of the request id |
address | address | The wallet account the user chose |
wallet_key | walletPublicKey | The wallet's x25519 session public key |
sig | signature | Base58 BLS signature over the connect transcript |
Over the relay, the same ConnectResponseParams object is sent as the frame payload.
How the handshake is secured
Session keypairs
Each side generates a fresh x25519 keypair per connection with generateSessionKeypair(). The public key is Base58 and travels in the clear; the 32-byte secret key stays in memory. These keys only encrypt the session. They are separate from the account's BLS signing key. Both sides then run deriveSharedKey on the other side's public key to get the same 32-byte sharedKey.
The connect transcript
The wallet does not sign the bare challenge. It signs a ConnectTranscript with five fields: origin, dappPublicKey, walletPublicKey, challenge and requestId, encoded by buildConnectTranscript (byte layout in Connection auth). The signature uses the CONNECT_DST domain, so a connect proof can never be reused as a transaction, message or API-key signature.
Because both session keys and the origin are inside the signed bytes, an attacker who captures a response cannot replay it under their own session keys; changing any field makes verification fail. approveConnect calls signConnect and completeConnect calls verifyConnect for you. To call signConnect, verifyConnect, seal and open directly, see Connection auth and Session encryption.
Sealed envelopes
Every request and response is encrypted with seal (XChaCha20-Poly1305) into a SealedEnvelope, { nonce, ciphertext }, both Base58. The envelope helpers wrap JSON requests and responses in that box:
| Function | Side | What it does |
|---|---|---|
makeRequest({ id, method, origin, params, account?, ttlSeconds? }) | dApp | Builds a WalletRequest with v: 1 and exp = now + ttlSeconds (default 120) |
sealRequest(sharedKey, request) | dApp | Encrypts a request |
openRequest(sharedKey, envelope) | Wallet | Decrypts and validates a request. It does not check expiry or replay. |
guardRequest(request, seenStore, now?) | Wallet | Throws EXPIRED when exp has passed, or INVALID_ARGUMENT for a request id it has seen before, then records the id |
createMemorySeenStore(maxEntries = 10000) | Wallet | In-memory store of seen request ids for guardRequest |
sealResponse(sharedKey, response) | Wallet | Encrypts a response |
openResponse(sharedKey, envelope, expectedId?) | dApp | Decrypts and validates a response. With expectedId, it throws INVALID_ARGUMENT if the response answers a different request. |
import type { WalletMethod } from '@amadeus-protocol/wallet-sdk'
interface WalletRequest {
v: number
id: string // max 128 characters, used once
method: WalletMethod
origin: string
params: unknown
exp: number // Unix seconds
account?: string
}
type WalletResponse =
| { v: number; id: string; ok: true; result: unknown }
| { v: number; id: string; ok: false; error: { code: string; message: string } }
How a wallet should handle requests (handleRequest, approval, replay storage) is covered in Build a wallet integration.
Wallet side of the handshake
A wallet that accepts Amadeus Connect parses the URI, validates what parseConnectUri does not, asks the user, and returns the response over the relay, the redirect link, or both:
import {
approveConnect,
assertAllowedBridgeUrl,
BridgeClient,
buildConnectResponseUri,
deriveConnectChannel,
isConnectRequestExpired,
originSchema,
parseConnectUri,
sessionPublicKeySchema,
WalletSdkError
} from '@amadeus-protocol/wallet-sdk'
declare const account: { seed: string; address: string }
declare function askUserToApprove(origin: string): Promise<boolean>
declare function openUrl(url: string): Promise<void>
export async function handleConnectLink(link: string) {
const request = parseConnectUri(link)
if (!originSchema.safeParse(request.origin).success) {
throw new WalletSdkError('INVALID_ARGUMENT', 'origin must be http(s)')
}
if (!sessionPublicKeySchema.safeParse(request.dappPublicKey).success) {
throw new WalletSdkError('INVALID_ARGUMENT', 'bad dApp session key')
}
if (request.bridgeUrl) assertAllowedBridgeUrl(request.bridgeUrl)
if (isConnectRequestExpired(request)) throw new WalletSdkError('EXPIRED', 'connect request expired')
const approved = await askUserToApprove(request.origin)
if (!approved || isConnectRequestExpired(request)) return null
const session = approveConnect(request, account)
if (session.bridgeUrl) {
const channel = deriveConnectChannel(session.peerPublicKey)
const relay = new BridgeClient({ bridgeUrl: session.bridgeUrl, clientId: channel })
await relay.send(channel, session.response.requestId, session.response)
}
if (request.redirectLink) {
await openUrl(buildConnectResponseUri(request.redirectLink, session.response))
}
return session
}
approveConnect(request, { seed, address }) generates the wallet's session keypair, signs the transcript with seed and derives the shared key. It does not check expiry, so call it only after the checks above and the user's approval. The returned WalletSession holds response, sharedKey, walletKeypair, peerPublicKey (the dApp's session key) and bridgeUrl. The wallet then listens on deriveBridgeChannels(session.sharedKey).toWallet.
The bridge relay
Channels
The relay routes frames by channel id. No channel id is a public key:
| Channel | Derivation | Who listens |
|---|---|---|
| Connect | deriveConnectChannel(dappPublicKey) = base58(sha256("amadeus-bridge/connect/v1" ‖ dappPublicKey)) | dApp, until connect completes |
toWallet | base58(sha256("amadeus-bridge/to-wallet/v1" ‖ sharedKey)) | Wallet |
toDapp | base58(sha256("amadeus-bridge/to-dapp/v1" ‖ sharedKey)) | dApp |
deriveBridgeChannels(sharedKey) returns { toWallet, toDapp }. Because these two ids come from the shared key, someone who only saw the QR code cannot read, drain or flood the session's channels. Anyone who saw the QR code can post to the connect channel, which is why the dApp verifies the signature and skips frames that fail.
BridgeClient
new BridgeClient({ bridgeUrl, clientId, fetchImpl?, pollWaitSeconds? })
The constructor takes a BridgeClientOptions object. Every message on the relay is a BridgeFrame, { from: string; to: string; id: string; payload: unknown }, where payload is a SealedEnvelope or, on the connect channel, a plaintext ConnectResponseParams.
| Member | Behavior |
|---|---|
| constructor | Calls assertAllowedBridgeUrl(bridgeUrl), strips a trailing /, and uses fetchImpl or the global fetch. clientId is the channel this client listens on. pollWaitSeconds defaults to 25. |
send(to, id, payload) | POST {bridgeUrl}/message?to={to} with the frame { from: clientId, to, id, payload }. Throws SUBMIT_FAILED on a non-2xx status. |
start(onFrame, onError?) | Long-polls GET {bridgeUrl}/events?client_id={clientId}&wait={pollWaitSeconds} and calls onFrame once per frame, in order, awaiting each call. A poll response over 8 MiB is rejected. After an error (non-2xx status, bad JSON, oversized response) it calls onError and retries after 1 second. Returns a stop() function. |
If a poll gets no answer within pollWaitSeconds + 10 seconds, BridgeClient aborts it, and in 0.2.0 that also stops the loop for good without calling onError. The reference relay answers within 30 seconds, so this only happens when the network or a proxy in front of the relay holds the request.
assertAllowedBridgeUrl(url) accepts https URLs, and http only for localhost, 127.0.0.1 or ::1. Anything else throws INVALID_ARGUMENT. This stops a malicious connect link from pointing the wallet at an internal or non-HTTP address.
Running your own relay
The relay is the amadeus-wallet-bridge service (MIT). It has no runtime dependencies and runs on Node 20 or later:
npm install
npm run build
node dist/server.js # PORT defaults to 8787; HOST sets the bind address
# or
docker compose up --build # exposes :8787
| Endpoint | Purpose |
|---|---|
POST /message?to=<channel> | Queue a frame for a channel. The body is the JSON frame. |
GET /events?client_id=<channel>&wait=<seconds> | Long-poll. Returns the queued frames as a JSON array and removes them from the queue. |
GET /health | { ok: true, channels: <n> } |
| Limit | Default |
|---|---|
Frames queued per channel (maxQueue) | 200 |
Frame lifetime (ttlMs) | 120 000 ms |
Channels (maxChannels, least recently used evicted) | 50 000 |
Longest long-poll (maxWaitSeconds) | 30 s |
Request body (maxBodyBytes) | 65 536 bytes |
Errors come back as { "error": { "code", "message" } }, for example body_too_large with status 413.
- The relay has no rate limiting and no TLS. Put a reverse proxy such as Caddy, nginx or Cloudflare in front of it.
- Queues live in memory, so run a single instance, or route by channel id to the same instance.
- A phone cannot reach
localhoston your computer, and the wallet only acceptshttpforlocalhost. To test the mobile wallet against your own relay, expose it overhttps. - A frame that is not picked up within 120 seconds is dropped, and a frame over 64 KiB is rejected. Very large transaction arguments do not fit.
Session lifetime
- Keep
pendingand the session in memory. The x25519 secret key andsharedKeyshould never be persisted. - The mobile wallet forgets sessions when it locks. Its sessions live in memory, and it stops listening on lock. It does not notify the dApp, so requests then time out and the user has to connect again.
- Replay protection resets on restart. The mobile wallet uses
createMemorySeenStore. Request expiry (120 seconds by default) still limits replays.
Errors
The functions on this page throw WalletSdkError, which has a code:
| Code | Thrown by |
|---|---|
INVALID_ARGUMENT | parseConnectUri, parseConnectResponseUri, completeConnect (request id mismatch), openRequest and openResponse (bad JSON, schema, id mismatch), guardRequest (duplicate id), assertAllowedBridgeUrl and the BridgeClient constructor |
BAD_SIGNATURE | completeConnect, when the connect proof does not verify |
DECRYPT_FAILED | deriveSharedKey, approveConnect and completeConnect (bad session key), open, openRequest, openResponse |
EXPIRED | guardRequest |
SUBMIT_FAILED | BridgeClient.send (non-2xx status). The poll loop passes the same code to onError instead of throwing. |
Errors from @amadeus-protocol/sdk pass through as plain Errors, for example a bad seed in approveConnect or signConnect, or a key that is not Base58 in deriveConnectChannel.
A WalletResponse with ok: false carries error.code as a plain string. It is usually one of the codes above, and can also be INTERNAL for an unexpected failure in the wallet.
Related
- Wallet SDK overview
- Connect a dApp for the browser extension
- Provider reference
- Signing and API keys
- Build a wallet integration
- Amadeus SDK