Skip to main content

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).

note

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​

ExportSignatureDescription
getAmadeusProvider() => AmadeusProvider | nullReturns globalThis.amadeus only if it exists and isAmadeus === true. Otherwise returns null.
isProviderAvailable() => booleantrue 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.

warning

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​

MethodParamsReturnsDescription
isAmadeus(read-only property)booleanFeature flag. getAmadeusProvider() only accepts a provider where this is true.
isConnected()nonePromise<boolean>Whether the wallet reports a connected account. See Chrome extension behavior for what the extension checks.
getAccount()nonePromise<string | null>The active account's Base58 address, or null.
getNetwork()nonePromise<string>The active network name, normally one of NETWORKS.
requestAccounts()nonePromise<string[]>Asks the user to connect. Resolves to Base58 addresses.
requestSwitchNetwork(network)network: stringPromise<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?()nonePromise<PendingRequestSummary[]>Optional. This origin's requests still waiting in the wallet, oldest first. Extension 1.6.0 or later.
cancelRequest?(requestId)requestId: stringvoidOptional. Withdraws one of this origin's own pending requests. Extension 1.6.0 or later.
signTransaction(params)SignTransactionRequestPromise<SignTransactionResponse>Asks the user to sign a contract call. The wallet signs only; you submit.
generateApiKey(params)GenerateApiKeyRequestPromise<GenerateApiKeyResponse>Asks the user to issue a signed API key (bearer token).
on(event, callback)event: AmadeusProviderEvent, callback: (data) => voidvoidSubscribes to a provider event. data is typed per event.
off(event, callback)same as onvoidRemoves 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​

TypeFields
SignTransactionRequestcontract: string, method: string, args: any[], description?: string
SignTransactionResponsetxHash: string, txPacked: number[] (packed bytes as plain numbers; wrap with new Uint8Array(...))
GenerateApiKeyRequestaud: string, exp_in: number (lifetime in seconds, snake_case)
GenerateApiKeyResponseapiKey: string
PendingRequestSummarytype: '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'
AmadeusEventTimestampstring, 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.

note

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.

EventPayloadWhen
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.

KeyEvent namedetail
initializedamadeus-wallet#initialized{ provider: 'amadeus' } in the extension. Not typed by the SDK.
connectedamadeus-wallet#connectedSame as connect
disconnectedamadeus-wallet#disconnectedSame as disconnect
lockedamadeus-wallet#lockedSame as lock
unlockedamadeus-wallet#unlockedSame as unlock
networkChangedamadeus-wallet#networkChangedSame 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.

BehaviorDetail
Connection scopeThe 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.
accountsrequestAccounts() and the account events carry only the active account, so the array has at most one entry.
network in connect and unlockCan 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 reasonlock uses 'manual' and disconnect uses 'disconnected' when the wallet gives no reason. An auto-lock sends 'auto-lock'.
RejectionsPromises 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-lockFrom 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() timeoutResolves false after 5 s with no answer.
getNetwork() timeoutResolves the last known network, or 'mainnet', after 5 s.
getAccount() timeoutRejects after 10 s.
requestAccounts(), requestSwitchNetwork() timeoutRejects after 30 s.
requestSwitchAccount(), signTransaction(), generateApiKey() timeoutRejects after 120 s.
signTransaction() argsThe 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 eventOnly for signTransaction() requests, and not sent when the request first waits for the user to unlock the wallet.
Message signingThe provider has no signMessage. Message signing only exists over Amadeus Connect. See Signing and API keys.
Provider objectDefined 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:

MemberTypeValue
codeWalletSdkErrorCode (read-only)One of the error codes
namestring'WalletSdkError'
messagestringHuman-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​

CodeThrown by
INVALID_ARGUMENTcreateInjectedWalletClient 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.
UNSUPPORTEDclient.switchAccount() when the provider has no requestSwitchAccount.
EXPIREDguardRequest when the request's exp has passed.
BAD_SIGNATUREcompleteConnect when the wallet's connect proof does not verify.
DECRYPT_FAILEDopen, deriveSharedKey, openRequest, openResponse, approveConnect and completeConnect when a key or envelope is invalid.
INVALID_API_KEYdecodeApiKey on a malformed token.
INVALID_ADDRESSpublicKeyFromAddress when the address is not Base58 that decodes to 48 bytes.
INVALID_SIGNATUREsignatureFromBase58 when the signature is not Base58 that decodes to 96 bytes.
SUBMIT_FAILEDsubmitTransaction 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_MISMATCHDeclared 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).

warning

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​

ExportValueUsed in
PROTOCOL_VERSION1The 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.

note

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 methodProvider equivalentParams schemaResult
amadeus_getAccountsrequestAccounts()none{ accounts: string[] } from handleRequest (the session's bound address)
amadeus_signTransactionsignTransaction()signTransactionRequestSchema{ txHash, txPacked }
amadeus_generateApiKeygenerateApiKey()generateApiKeyRequestSchema{ apiKey }
amadeus_signMessagenonesignMessageRequestSchema{ message, signature, address }
amadeus_switchNetworkrequestSwitchNetwork()nonehandleRequest returns an INVALID_ARGUMENT error; the wallet app must implement it.
amadeus_switchAccountrequestSwitchAccount()switchAccountRequestSchema (exported, not applied by handleRequest)handleRequest returns an INVALID_ARGUMENT error; the wallet app must implement it.
warning

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.

SchemaValidatesInferred type
originSchemaA string that starts with http:// or https://. Prefix check only; it does not parse the URL.none
addressSchemaA Base58 string that decodes to exactly 48 bytes (an Amadeus public key).none
sessionPublicKeySchemaA 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) charactersSignMessageRequestInput
switchAccountRequestSchema{ account?: address }, where account must pass addressSchema when presentSwitchAccountRequestInput
connectTranscriptSchema{ origin, dappPublicKey, walletPublicKey, challenge, requestId }: origin passes originSchema, both keys pass sessionPublicKeySchema, challenge and requestId are non-empty stringsConnectTranscriptInput

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:

EnvelopeFields checked
Requestv 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.

ExportValue
NETWORKS['mainnet', 'testnet', 'custom']
PROVIDER_EVENTS['accountsChanged', 'connect', 'disconnect', 'lock', 'unlock', 'networkChanged', 'shown']
WALLET_INITIALIZED_EVENT'amadeus-wallet#initialized'
WALLET_WINDOW_EVENTSSee Window events
WALLET_METHODSSee Wire methods
PROVIDER_GLOBAL'amadeus'
MAX_MESSAGE_LENGTH4096
MAX_API_KEY_STRING_LENGTH1024
PUBLIC_KEY_BYTE_LENGTH48
SIGNATURE_BYTE_LENGTH96
SEED_BYTE_LENGTH64
SESSION_PUBLIC_KEY_BYTE_LENGTH32
SESSION_SECRET_KEY_BYTE_LENGTH32
SESSION_NONCE_BYTE_LENGTH24
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.