Provider reference
The AmadeusProvider contract in @amadeus-protocol/wallet-sdk 0.2.0: methods, events, window events, error codes, PROTOCOL_VERSION and the zod wire schemas.
This page lists the typed contract that @amadeus-protocol/wallet-sdk defines for the injected window.amadeus provider, plus the error type, protocol constants and wire schemas shared by every transport. Every export named on this page comes from the package root:
npm i @amadeus-protocol/wallet-sdk @amadeus-protocol/sdk
For a step-by-step integration, see Connect a dApp. For the React hook, see React. For the QR and deep-link transport used by the mobile wallet, see Amadeus Connect (mobile).
This reference covers version 0.2.0. The provider types match what the Amadeus Chrome extension injects, including its ISO string event timestamps, the shown event and the pending-request methods. Where the extension still behaves differently from the types, it is called out in Chrome extension behavior.
Finding the provider
| Export | Signature | Description |
|---|---|---|
getAmadeusProvider | () => AmadeusProvider | null | Returns globalThis.amadeus only if it exists and isAmadeus === true. Otherwise returns null. |
isProviderAvailable | () => boolean | true when getAmadeusProvider() is not null. |
PROVIDER_GLOBAL | 'amadeus' | The name of the global the wallet injects. |
The package also declares var amadeus: AmadeusProvider | undefined on the global scope, so globalThis.amadeus is typed once you import the package.
Initialization event
The extension can inject the provider after your script runs. When it is ready, it dispatches a CustomEvent on window named amadeus-wallet#initialized, exported as WALLET_INITIALIZED_EVENT.
Some older dApps listen for amadeus#initialized. The wallet never dispatches that name. Use WALLET_INITIALIZED_EVENT instead of a hard-coded string.
import { getAmadeusProvider, WALLET_INITIALIZED_EVENT, type AmadeusProvider } from '@amadeus-protocol/wallet-sdk'
export function waitForProvider(): Promise<AmadeusProvider> {
const injected = getAmadeusProvider()
if (injected) return Promise.resolve(injected)
return new Promise((resolve) => {
window.addEventListener(
WALLET_INITIALIZED_EVENT,
() => {
const provider = getAmadeusProvider()
if (provider) resolve(provider)
},
{ once: true }
)
})
}
AmadeusProvider methods
| Method | Params | Returns | Description |
|---|---|---|---|
isAmadeus | (read-only property) | boolean | Feature flag. getAmadeusProvider() only accepts a provider where this is true. |
isConnected() | none | Promise<boolean> | Whether the wallet reports a connected account. See Chrome extension behavior for what the extension checks. |
getAccount() | none | Promise<string | null> | The active account's Base58 address, or null. |
getNetwork() | none | Promise<string> | The active network name, normally one of NETWORKS. |
requestAccounts() | none | Promise<string[]> | Asks the user to connect. Resolves to Base58 addresses. |
requestSwitchNetwork(network) | network: string | Promise<string> | Asks the wallet to switch network. Resolves to the new network. |
requestSwitchAccount?(target?) | target?: string (Base58 address hint) | Promise<string> | Optional. Asks the wallet to make another of its accounts active. The wallet always confirms with the user, so a dApp cannot switch silently. Resolves to the new active address. Older wallets do not have this method. |
getPendingRequests?() | none | Promise<PendingRequestSummary[]> | Optional. This origin's requests still waiting in the wallet, oldest first. Extension 1.6.0 or later. |
cancelRequest?(requestId) | requestId: string | void | Optional. Withdraws one of this origin's own pending requests. Extension 1.6.0 or later. |
signTransaction(params) | SignTransactionRequest | Promise<SignTransactionResponse> | Asks the user to sign a contract call. The wallet signs only; you submit. |
generateApiKey(params) | GenerateApiKeyRequest | Promise<GenerateApiKeyResponse> | Asks the user to issue a signed API key (bearer token). |
on(event, callback) | event: AmadeusProviderEvent, callback: (data) => void | void | Subscribes to a provider event. data is typed per event. |
off(event, callback) | same as on | void | Removes a callback added with on. |
requestSwitchAccount, getPendingRequests and cancelRequest are optional in the type, because older extensions lack them. Call them with ?., for example provider.requestSwitchAccount?.(target). For account switching you can also use client.switchAccount() from createInjectedWalletClient, which rejects with UNSUPPORTED when the method is missing. See Connect a dApp. The client does not wrap the pending-request methods; call them on client.getProvider().
Request and response types
| Type | Fields |
|---|---|
SignTransactionRequest | contract: string, method: string, args: any[], description?: string |
SignTransactionResponse | txHash: string, txPacked: number[] (packed bytes as plain numbers; wrap with new Uint8Array(...)) |
GenerateApiKeyRequest | aud: string, exp_in: number (lifetime in seconds, snake_case) |
GenerateApiKeyResponse | apiKey: string |
PendingRequestSummary | type: 'sign' | 'apiKey' | 'switchNetwork' | 'switchAccount' | 'connection', id: string, timestamp: number (milliseconds since epoch, when the wallet queued the request) |
AmadeusNetwork | 'mainnet' | 'testnet' | 'custom' |
AmadeusProviderEvent | 'accountsChanged' | 'connect' | 'disconnect' | 'lock' | 'unlock' | 'networkChanged' | 'shown' |
AmadeusEventTimestamp | string, an ISO 8601 date such as '2026-11-09T12:00:00.000Z' |
AmadeusShownAs | 'sidepanel' | 'popup' | 'window' |
How args are encoded, how txPacked is submitted, and how API keys are verified are covered in Signing and API keys.
getNetwork() and requestSwitchNetwork() are typed as string, not AmadeusNetwork. Narrow the value with networkSchema (see Wire schemas) if you need the union type.
Provider events
Subscribe with provider.on(name, callback). Each callback receives one payload object, typed by AmadeusEventPayloadMap.
| Event | Payload | When |
|---|---|---|
accountsChanged | { accounts: string[]; previousAccounts: string[]; timestamp: AmadeusEventTimestamp } | The accounts the provider reports changed, including on connect and disconnect. |
connect | { accounts: string[]; network: string; timestamp: AmadeusEventTimestamp } | The provider went from no accounts to at least one account. |
disconnect | { reason?: string; timestamp: AmadeusEventTimestamp } | The provider went from having accounts to none. |
lock | { reason?: string; timestamp: AmadeusEventTimestamp } | The wallet was locked. |
unlock | { accounts: string[]; network: string; timestamp: AmadeusEventTimestamp } | The wallet was unlocked. |
networkChanged | { network: string; previousNetwork: string; timestamp: AmadeusEventTimestamp } | The active network changed. |
shown | { requestId: string; shownAs: AmadeusShownAs; timestamp: AmadeusEventTimestamp } | The approval screen for a signTransaction() request opened. The sign promise still settles later. |
The names are also exported as the tuple PROVIDER_EVENTS. Every timestamp is an ISO 8601 string; parse it with new Date(timestamp) or Date.parse(timestamp).
import { getAmadeusProvider, type AmadeusEventPayloadMap } from '@amadeus-protocol/wallet-sdk'
const provider = getAmadeusProvider()
const handleAccountsChanged = (payload: AmadeusEventPayloadMap['accountsChanged']) => {
console.log('active account:', payload.accounts[0] ?? null)
console.log('previous:', payload.previousAccounts)
}
provider?.on('accountsChanged', handleAccountsChanged)
// off() needs the same function reference that was passed to on()
provider?.off('accountsChanged', handleAccountsChanged)
Window events
The wallet also dispatches CustomEvents on window. They are exported as WALLET_WINDOW_EVENTS. The detail of each event is the same payload as the matching provider event.
| Key | Event name | detail |
|---|---|---|
initialized | amadeus-wallet#initialized | { provider: 'amadeus' } in the extension. Not typed by the SDK. |
connected | amadeus-wallet#connected | Same as connect |
disconnected | amadeus-wallet#disconnected | Same as disconnect |
locked | amadeus-wallet#locked | Same as lock |
unlocked | amadeus-wallet#unlocked | Same as unlock |
networkChanged | amadeus-wallet#networkChanged | Same as networkChanged |
There is no window event for accountsChanged or shown. Use the provider events for those.
import { WALLET_WINDOW_EVENTS, type AmadeusEventPayloadMap } from '@amadeus-protocol/wallet-sdk'
window.addEventListener(WALLET_WINDOW_EVENTS.networkChanged, (event) => {
const { detail } = event as CustomEvent<AmadeusEventPayloadMap['networkChanged']>
console.log(`network: ${detail.previousNetwork} -> ${detail.network}`)
})
Chrome extension behavior
These details come from the extension's injected script, not from the SDK types. Check them if your dApp depends on exact runtime behavior.
| Behavior | Detail |
|---|---|
| Connection scope | The extension has no per-origin connection list. isConnected() is true when a wallet exists and is unlocked, and getAccount() returns the active account whenever the wallet is unlocked (null when locked). Lock, unlock and account changes are broadcast to every tab. |
accounts | requestAccounts() and the account events carry only the active account, so the array has at most one entry. |
network in connect and unlock | Can be null if the page has not learned the network yet, although the type says string. useWallet() ignores a null network and keeps the last known value; in your own handlers, fall back to getNetwork(). |
Default reason | lock uses 'manual' and disconnect uses 'disconnected' when the wallet gives no reason. An auto-lock sends 'auto-lock'. |
| Rejections | Promises reject with a plain Error, not WalletSdkError. Messages include 'User rejected the request', 'Network switch rejected', 'Account switch rejected', 'Request cancelled', 'Request timeout' and 'WALLET_LOCKED'. |
| Auto-lock | From extension 1.9.2, an auto-lock rejects every pending request with 'WALLET_LOCKED' and broadcasts the lock to every tab (reason: 'auto-lock'). The wallet auto-locks when an open wallet window has been idle, or all wallet windows have been closed, for the user's auto-lock time. Older versions dropped the requests, which then hit their timeouts. |
isConnected() timeout | Resolves false after 5 s with no answer. |
getNetwork() timeout | Resolves the last known network, or 'mainnet', after 5 s. |
getAccount() timeout | Rejects after 10 s. |
requestAccounts(), requestSwitchNetwork() timeout | Rejects after 30 s. |
requestSwitchAccount(), signTransaction(), generateApiKey() timeout | Rejects after 120 s. |
signTransaction() args | The extension wraps Uint8Array and other binary args with the __amadeusBytes__ tag before sending them, the same encoding as encodeBinaryValues. |
getPendingRequests() | Lists only this origin's requests. Resolves [] after 5 s with no answer. |
cancelRequest() | The wallet withdraws only sign, apiKey and switchAccount requests, and only from the tab that created them. For switchNetwork and connection the prompt stays open in the wallet. In every case the page's pending call rejects with 'Request cancelled'. |
shown event | Only for signTransaction() requests, and not sent when the request first waits for the user to unlock the wallet. |
| Message signing | The provider has no signMessage. Message signing only exists over Amadeus Connect. See Signing and API keys. |
| Provider object | Defined on window as frozen, non-writable and non-configurable. |
This tracks signing prompts with the shown event and withdraws any that are still open:
import { getAmadeusProvider, type AmadeusEventPayloadMap } from '@amadeus-protocol/wallet-sdk'
const provider = getAmadeusProvider()
provider?.on('shown', ({ requestId, shownAs, timestamp }: AmadeusEventPayloadMap['shown']) => {
const shownAt = new Date(timestamp).toLocaleTimeString()
console.log(`Sign request ${requestId} shown in the ${shownAs} at ${shownAt}`)
})
export async function cancelOpenSignRequests(): Promise<void> {
// Undefined on extensions older than 1.6.0
const pending = (await provider?.getPendingRequests?.()) ?? []
pending
.filter((request) => request.type === 'sign')
.forEach((request) => provider?.cancelRequest?.(request.id))
}
For the extension's own guide to window.amadeus, see the Integration Guide.
Errors
WalletSdkError
Every error the SDK itself throws is a WalletSdkError, a subclass of Error:
| Member | Type | Value |
|---|---|---|
code | WalletSdkErrorCode (read-only) | One of the error codes |
name | string | 'WalletSdkError' |
message | string | Human-readable detail |
The constructor is new WalletSdkError(code, message). The prototype chain is restored, so instanceof WalletSdkError works after transpiling. Branch on code, not on message.
Error codes
| Code | Thrown by |
|---|---|
INVALID_ARGUMENT | createInjectedWalletClient methods when no provider is injected ('Amadeus wallet is not available') or requestAccounts() returned nothing ('no account returned'); submitTransaction with a non-http(s) nodeUrl; the wallet-side generateApiKey function with an empty aud or a non-positive-integer expIn; signMessage with an empty or too long message; parseConnectUri and parseConnectResponseUri; openRequest and openResponse on bad JSON, a schema failure or a mismatched response id; guardRequest on a replayed id; completeConnect on a request id mismatch; assertAllowedBridgeUrl and the BridgeClient constructor. |
UNSUPPORTED | client.switchAccount() when the provider has no requestSwitchAccount. |
EXPIRED | guardRequest when the request's exp has passed. |
BAD_SIGNATURE | completeConnect when the wallet's connect proof does not verify. |
DECRYPT_FAILED | open, deriveSharedKey, openRequest, openResponse, approveConnect and completeConnect when a key or envelope is invalid. |
INVALID_API_KEY | decodeApiKey on a malformed token. |
INVALID_ADDRESS | publicKeyFromAddress when the address is not Base58 that decodes to 48 bytes. |
INVALID_SIGNATURE | signatureFromBase58 when the signature is not Base58 that decodes to 96 bytes. |
SUBMIT_FAILED | submitTransaction and client.signAndSubmit() on a non-2xx node response; BridgeClient.send() on a non-2xx relay response. Poll failures in BridgeClient.start() go to its onError callback instead of being thrown. |
AUD_MISMATCH | Declared but never thrown in 0.2.0. verifyApiKey returns { valid: false, reason: 'aud_mismatch' } instead. |
handleRequest never throws. Invalid params, amadeus_switchNetwork and amadeus_switchAccount come back as an INVALID_ARGUMENT error response (see Errors in transport responses).
With no provider injected, some createInjectedWalletClient methods throw synchronously instead of rejecting. See Handle errors for which ones.
import { createInjectedWalletClient, WalletSdkError } from '@amadeus-protocol/wallet-sdk'
const client = createInjectedWalletClient()
try {
const account = await client.switchAccount()
console.log('switched to', account)
} catch (error) {
if (error instanceof WalletSdkError && error.code === 'UNSUPPORTED') {
console.warn('This wallet version cannot switch accounts')
} else if (error instanceof WalletSdkError) {
console.error(error.code, error.message)
} else {
// Rejections from the wallet itself are plain Error objects
console.error((error as Error).message)
}
}
Errors in transport responses
Over Amadeus Connect, errors travel inside the response instead of being thrown: { v, id, ok: false, error: { code: string; message: string } }. handleRequest fills code from the WalletSdkError, or uses 'INTERNAL' for any other thrown value. 'INTERNAL' is not part of WalletSdkErrorCode, so treat error.code as a plain string. See Build a wallet integration.
Protocol version
| Export | Value | Used in |
|---|---|---|
PROTOCOL_VERSION | 1 | The v field of every WalletRequest (set by makeRequest) and WalletResponse (set by handleRequest), and the connect URI path amadeus://v1/connect. |
CONNECT_TRANSCRIPT_LABEL | 'amadeus-connect/v1' | Label at the start of the signed connect transcript bytes. |
The injected extension provider does not carry a protocol version.
parseConnectUri rejects any path other than v1/connect. openRequest and openResponse only check that v is an integer and do not compare it with PROTOCOL_VERSION. If you want to refuse other versions there, check it yourself.
import { openRequest, PROTOCOL_VERSION, WalletSdkError, type SealedEnvelope } from '@amadeus-protocol/wallet-sdk'
declare const sharedKey: Uint8Array
declare const envelope: SealedEnvelope
const request = openRequest(sharedKey, envelope)
if (request.v !== PROTOCOL_VERSION) {
throw new WalletSdkError('UNSUPPORTED', `unsupported protocol version ${request.v}`)
}
Wire methods
Requests over Amadeus Connect use the method names in WALLET_METHODS. They map to the provider methods like this:
| Wire method | Provider equivalent | Params schema | Result |
|---|---|---|---|
amadeus_getAccounts | requestAccounts() | none | { accounts: string[] } from handleRequest (the session's bound address) |
amadeus_signTransaction | signTransaction() | signTransactionRequestSchema | { txHash, txPacked } |
amadeus_generateApiKey | generateApiKey() | generateApiKeyRequestSchema | { apiKey } |
amadeus_signMessage | none | signMessageRequestSchema | { message, signature, address } |
amadeus_switchNetwork | requestSwitchNetwork() | none | handleRequest returns an INVALID_ARGUMENT error; the wallet app must implement it. |
amadeus_switchAccount | requestSwitchAccount() | switchAccountRequestSchema (exported, not applied by handleRequest) | handleRequest returns an INVALID_ARGUMENT error; the wallet app must implement it. |
The Amadeus mobile wallet answers amadeus_getAccounts itself with { accounts: { address, name }[] }, not string[]. Accept both shapes. Details are in Amadeus Connect (mobile).
Wire schemas
The package exports zod schemas for validating untrusted input such as deep links, QR payloads, bridge frames and cross-origin messages. Validate before you show a request for approval or sign anything.
| Schema | Validates | Inferred type |
|---|---|---|
originSchema | A string that starts with http:// or https://. Prefix check only; it does not parse the URL. | none |
addressSchema | A Base58 string that decodes to exactly 48 bytes (an Amadeus public key). | none |
sessionPublicKeySchema | A Base58 string that decodes to exactly 32 bytes (an x25519 session key). | none |
networkSchema | 'mainnet', 'testnet' or 'custom' (z.enum(NETWORKS)). | none |
signTransactionRequestSchema | { contract: string (min 1), method: string (min 1), args: unknown[], description?: string } | SignTransactionRequestInput |
generateApiKeyRequestSchema | { aud: string (min 1), exp_in: positive integer } | GenerateApiKeyRequestInput |
signMessageRequestSchema | { message: string }, 1 to MAX_MESSAGE_LENGTH (4096) characters | SignMessageRequestInput |
switchAccountRequestSchema | { account?: address }, where account must pass addressSchema when present | SwitchAccountRequestInput |
connectTranscriptSchema | { origin, dappPublicKey, walletPublicKey, challenge, requestId }: origin passes originSchema, both keys pass sessionPublicKeySchema, challenge and requestId are non-empty strings | ConnectTranscriptInput |
handleRequest applies signTransactionRequestSchema, generateApiKeyRequestSchema and signMessageRequestSchema to request params. The others are exported for your own checks; the SDK does not apply them internally.
MAX_MESSAGE_LENGTH counts JavaScript string length (UTF-16 code units), not bytes.
import { signTransactionRequestSchema, WalletSdkError } from '@amadeus-protocol/wallet-sdk'
declare const untrustedParams: unknown
const parsed = signTransactionRequestSchema.safeParse(untrustedParams)
if (!parsed.success) {
throw new WalletSdkError('INVALID_ARGUMENT', parsed.error.message)
}
const { contract, method, args, description } = parsed.data
console.log(contract, method, args.length, description ?? '(no description)')
Envelope validation
openRequest and openResponse validate the decrypted JSON against internal schemas that are not exported:
| Envelope | Fields checked |
|---|---|
| Request | v integer; id string of 1 to 128 characters; method one of WALLET_METHODS; origin non-empty string; params any value; exp integer (Unix seconds); account optional string of 1 to 128 characters |
| Response (success) | v integer; id 1 to 128 characters; ok: true; result any value |
| Response (error) | v integer; id 1 to 128 characters; ok: false; error: { code: string; message: string } |
These schemas do not check expiry, replay, the origin scheme or the account format. Expiry and replay are checked by guardRequest; see Build a wallet integration.
Related constants
| Export | Value |
|---|---|
NETWORKS | ['mainnet', 'testnet', 'custom'] |
PROVIDER_EVENTS | ['accountsChanged', 'connect', 'disconnect', 'lock', 'unlock', 'networkChanged', 'shown'] |
WALLET_INITIALIZED_EVENT | 'amadeus-wallet#initialized' |
WALLET_WINDOW_EVENTS | See Window events |
WALLET_METHODS | See Wire methods |
PROVIDER_GLOBAL | 'amadeus' |
MAX_MESSAGE_LENGTH | 4096 |
MAX_API_KEY_STRING_LENGTH | 1024 |
PUBLIC_KEY_BYTE_LENGTH | 48 |
SIGNATURE_BYTE_LENGTH | 96 |
SEED_BYTE_LENGTH | 64 |
SESSION_PUBLIC_KEY_BYTE_LENGTH | 32 |
SESSION_SECRET_KEY_BYTE_LENGTH | 32 |
SESSION_NONCE_BYTE_LENGTH | 24 |
URI_SCHEME | 'amadeus' |
DEFAULT_BRIDGE_URL | 'https://bridge.ama.one' |
Signature domain tags (TX_DST, API_KEY_DST, MESSAGE_DST, CONNECT_DST) are covered in Signing and API keys. For the core SDK that builds and submits transactions, see the Amadeus SDK introduction.