Signing and API keys
The low-level crypto helpers in @amadeus-protocol/wallet-sdk: API-key tokens, transaction signing and submission, message signing, connection proofs, session encryption and binary transaction args.
Overview
Every function on this page is a plain, synchronous helper except submitTransaction. The mobile wallet and dApps import this same code, so both sides produce and check the same bytes. The Chrome extension does not depend on the package yet: it ships its own implementation of the API-key token, transaction signing and binary-argument tag, which produces the same bytes.
Most dApps never call the signing functions directly. The wallet signs for you when you use the injected provider (Connect a dApp) or Amadeus Connect with the mobile wallet. Use this page when you:
- verify API keys or signed messages on a backend;
- build a wallet or a server-side signer (see also Build a wallet integration);
- need to send raw bytes as transaction arguments;
- want to understand what the wallet actually signs.
Functions that take a seed need the account's raw private key (the Base58 64-byte seed). Only call them inside a wallet or a trusted server. A browser dApp should never hold a user's seed: ask the wallet to sign instead.
Everything here is exported from the package root:
npm i @amadeus-protocol/wallet-sdk @amadeus-protocol/sdk
The package is ESM only and needs Node 20 or later. See the Wallet SDK overview for setup.
At a glance
| Task | Sign | Verify | DST |
|---|---|---|---|
| API-key bearer token | generateApiKey | verifyApiKey, decodeApiKey | API_KEY_DST |
| Contract call | signTransaction | the node | mainnet TX_DST, or the testnet TX DST |
| Arbitrary message ("personal sign") | signMessage | verifyMessage | MESSAGE_DST |
| Connection proof | signConnect | verifyConnect | CONNECT_DST |
| Session encryption | seal | open | none (x25519 + XChaCha20-Poly1305) |
Domain separation tags
Every BLS signature in Amadeus is made over sha256(payload) under a domain separation tag (DST). BLS mixes the DST into the hash-to-curve step, so a signature made under one DST never verifies under another. This is what stops a login message or an API key from being replayed as a transaction.
| Constant | Value | Used for |
|---|---|---|
TX_DST | AMADEUS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_TX_ | Transactions on mainnet and custom networks |
| (not exported) | AMADEUS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_TX_TESTNET_ | Transactions on testnet |
API_KEY_DST | AMADEUS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_APIKEY_ | API-key tokens |
MESSAGE_DST | AMADEUS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_MSG_ | signMessage |
CONNECT_DST | AMADEUS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_CONNECT_ | Connect transcripts |
The wallet SDK only exports the mainnet TX_DST. The testnet transaction DST lives in @amadeus-protocol/sdk: call txDstForNetwork(network) from the core SDK if you need it. custom networks sign under the mainnet DST.
Related size constants: PUBLIC_KEY_BYTE_LENGTH (48, a G1 public key, which is also the address), SIGNATURE_BYTE_LENGTH (96, a G2 signature) and SEED_BYTE_LENGTH (64).
API keys
An API key is a short-lived bearer token that proves control of an address to an off-chain service, without a transaction. The wallet extension and the mobile wallet issue the same tokens, and the kbs.ama.one backend verifies this exact format.
Token format
apiKey = base58( jsonBytes ‖ publicKey (48 bytes) ‖ signature (96 bytes) )
jsonBytes = utf8(JSON.stringify({ aud, exp })) // key order: aud, then exp
exp = floor(now_ms / 1000) + expIn // unix seconds
signature = BLS.sign(sha256(jsonBytes ‖ publicKey), sk, API_KEY_DST)
- The public key is folded into the signed hash, which blocks rogue-key attacks.
aud(audience) is a free-form string the verifier compares. Use whatever value your verifier expects.- The field order, concatenation and DST must not change, or existing verifiers reject the token.
Generate a key
import { generateApiKey } from '@amadeus-protocol/wallet-sdk'
const { apiKey, payload } = generateApiKey({
seed,
aud: 'https://app.example.com',
expIn: 60 * 60
})
console.log(apiKey) // Base58 token
console.log(payload.exp) // unix seconds
Parameters (GenerateApiKeyParams):
seed(string): Base58 private key of the signing accountaud(string): audience claim, must not be emptyexpIn(number): lifetime in seconds, a positive integernow(number, optional): current time in milliseconds, for deterministic tests
Returns (GenerateApiKeyResult): { apiKey: string, payload: ApiKeyPayload }, where ApiKeyPayload is { aud: string, exp: number }
Throws: WalletSdkError with code INVALID_ARGUMENT if aud is empty or expIn is not a positive integer.
The lifetime is called expIn here, but exp_in (snake_case) on the wire: in the injected provider's generateApiKey({ aud, exp_in }) and in the amadeus_generateApiKey request. Both are seconds. A dApp gets a key from the wallet with ensureApiKey (see Get an API key for your backend) or amadeus_generateApiKey (see Amadeus Connect).
Verify a key
verifyApiKey runs the full check: structure, BLS signature, expiry, then audience. It never throws; it returns a discriminated result.
import { verifyApiKey } from '@amadeus-protocol/wallet-sdk'
const result = verifyApiKey(apiKey, {
aud: 'https://app.example.com',
leewaySeconds: 30
})
if (!result.valid) {
throw new Error(`API key rejected: ${result.reason}`)
}
console.log(result.address) // Base58 address that signed the token
console.log(result.payload.exp)
Options (VerifyApiKeyOptions):
aud(string, optional): if set, the token'saudmust equal it. If you leave it out, any audience is accepted.leewaySeconds(number, optional, default0): treat the token as expired this many seconds early, to absorb clock skewnow(number, optional): current time in milliseconds, for tests
Returns (VerifyApiKeyResult): { valid: true, payload, address } or { valid: false, reason }, where reason is one of:
| Reason | Meaning |
|---|---|
malformed | Not a decodable token (see decodeApiKey below) |
bad_signature | The BLS signature does not match the payload and public key |
expired | exp <= now + leewaySeconds (a token is expired at its exp second, not after it) |
aud_mismatch | aud was given and differs from the token's |
WalletSdkErrorCode includes AUD_MISMATCH, but nothing throws it. An audience mismatch is only reported as reason: 'aud_mismatch'.
Decode a key
decodeApiKey splits a token into its parts without checking the signature or expiry. Use it to read aud or exp (for example to decide whether a cached key needs refreshing), never to authenticate.
import { decodeApiKey } from '@amadeus-protocol/wallet-sdk'
const decoded = decodeApiKey(apiKey)
console.log(decoded.address) // Base58 of decoded.publicKey
console.log(decoded.payload.aud, decoded.payload.exp)
Returns (DecodedApiKey): payload, publicKey (48 bytes), signature (96 bytes), jsonBytes (the exact signed JSON bytes) and address.
Throws: WalletSdkError with code INVALID_API_KEY when the string is empty or longer than MAX_API_KEY_STRING_LENGTH (1024 characters, checked before the Base58 decode to bound untrusted input), is not Base58, is too short to hold a payload, or the payload is not JSON of the shape { aud: string, exp: number }.
Use the right seed for a recovery phrase
The token's address is the public key of the seed you pass in. A recovery phrase can open two different addresses: the standard eip2333 derivation, and the legacy raw-BIP39 seed used by wallets created with older extension and app builds. If you derive the seed from a phrase yourself and pick the wrong one, the token silently belongs to a different account.
When you know the user's wallet address, resolve the seed with resolveCandidateForAddress from @amadeus-protocol/sdk (1.6.0 or later):
import { resolveCandidateForAddress } from '@amadeus-protocol/sdk'
import { generateApiKey } from '@amadeus-protocol/wallet-sdk'
const candidate = resolveCandidateForAddress(phrase, walletAddress)
if (!candidate) {
throw new Error('This phrase does not open that address')
}
const { apiKey } = generateApiKey({ seed: candidate.seed, aud: 'https://app.example.com', expIn: 3600 })
resolveCandidateForAddress returns the candidate whose publicKey equals the address, or null if neither derivation opens it. It throws if the phrase fails the BIP39 wordlist or checksum check.
Transactions
Sign a contract call
signTransaction builds and signs a contract call with the core SDK's signContractCall, so the packed bytes are identical to what the wallet extension produces.
import { NetworkType, toAtomicAma } from '@amadeus-protocol/sdk'
import { signTransaction } from '@amadeus-protocol/wallet-sdk'
const { txHash, txPacked } = signTransaction({
seed,
contract: 'Coin',
method: 'transfer',
args: [recipientAddress, String(toAtomicAma(1.5)), 'AMA'],
network: NetworkType.TESTNET
})
Parameters (SignTransactionParams):
seed(string): Base58 private keycontract(string),method(string): the call targetargs(unknown[]): call arguments; may contain tagged bytes (see Binary arguments)network(NetworkType, optional): the network whose TX DST the signature binds to. Defaults to mainnet.description(string, optional): accepted for parity with the provider request, but ignored. It is not signed or sent anywhere.
Returns (SignedTransaction): txHash (Base58) and txPacked (the packed transaction as a plain number[], ready to submit).
Before signing, signTransaction does two things to args:
- It restores tagged binary values to
Uint8ArraywithdecodeBinaryValues. - For
Coin.transferonly, if the first argument is a string, it Base58-decodes it to raw bytes. You can pass the recipient as an address string. In that case only the first three arguments (recipient, amount, symbol) are kept.
The Coin.transfer conversion is the only one. For any other contract, an argument that must be bytes has to be a Uint8Array (or tagged bytes). A Base58 string is encoded as a string, and the node will read it as one.
Network binding. network needs @amadeus-protocol/sdk 1.3.0 or later. NetworkType.TESTNET signs under the testnet DST, and MAINNET or CUSTOM under TX_DST, so a testnet transaction cannot be replayed on mainnet. The network does not enter the txHash, which is the SHA-256 of the unsigned transaction (signer, nonce and call); it only changes the signature, and so the packed bytes. network is the core SDK's NetworkType enum, so pass NetworkType.TESTNET rather than the string 'testnet'.
Submit a signed transaction
The wallet only signs. The dApp (or whoever holds txPacked) submits it to a node with submitTransaction:
import { submitTransaction } from '@amadeus-protocol/wallet-sdk'
const result = await submitTransaction(txPacked, {
nodeUrl: 'https://testnet-rpc.ama.one/api',
wait: true,
timeoutMs: 15_000
})
Options (SubmitTransactionOptions):
nodeUrl(string): base URL of the node API, including/api, for examplehttps://mainnet-rpc.ama.one/api. A trailing slash is removed.wait(boolean, optional):trueposts to/tx/submit_and_waitand waits for inclusion; otherwise it posts to/tx/submit.timeoutMs(number, optional, default30000): aborts the request after this many milliseconds.
It POSTs txPacked (a number[] or Uint8Array) as application/octet-stream and returns the parsed JSON body, or the raw text if the body is not JSON.
Throws:
WalletSdkErrorINVALID_ARGUMENTifnodeUrldoes not start withhttp://orhttps://WalletSdkErrorSUBMIT_FAILEDwith the messagenode returned <status>: <body>on a non-2xx response- the platform's own
fetcherrors otherwise, unwrapped: a timeout rejects with anAbortError, not aWalletSdkError
nodeUrl must include /api because this function appends /tx/submit itself. The core SDK's NETWORK_URLS values (for example https://mainnet-rpc.ama.one) do not include it.
WalletClient.signAndSubmit and useWallet().signAndSubmit wrap this call but do not forward timeoutMs, so they always use the 30 second default. See Connect a dApp and React.
Binary arguments
Transaction arguments often travel as JSON: over the extension's message channel, or inside a sealed Amadeus Connect request. JSON.stringify turns a Uint8Array into {"0":7,"1":42,...}, which then gets encoded as a map instead of bytes, and the node rejects the transaction. The binary helpers wrap bytes in a JSON-safe tag instead:
{ "__amadeusBytes__": "<base64>" }
import { fromBase58 } from '@amadeus-protocol/sdk'
import {
decodeBinaryValues,
describeBinaryValues,
encodeBinaryValues
} from '@amadeus-protocol/wallet-sdk'
const wireArgs = encodeBinaryValues([fromBase58(targetAddress), '1000']) as unknown[]
// [{ __amadeusBytes__: 'q2x...' }, '1000']
const display = describeBinaryValues(wireArgs)
// ['<bytes[48] base64:q2x...>', '1000']
const restored = decodeBinaryValues(wireArgs) as unknown[]
// [Uint8Array(48), '1000']
| Function | What it does |
|---|---|
encodeBinaryValues(value) | Recursively replaces typed arrays, DataView and ArrayBuffer with tagged bytes. Already-tagged values pass through, so it is safe to call twice. |
decodeBinaryValues(value) | Recursively restores tagged bytes to Uint8Array. signTransaction calls it for you. |
describeBinaryValues(value) | Replaces tagged bytes with a readable <bytes[N] base64:...> string, for showing args in an approval screen. |
isTaggedBytes(value) | Type guard for TaggedBytes: true for a plain object with exactly one key, __amadeusBytes__, holding a string. |
The tag (BYTES_TAG) and base64 payload are wire-compatible with the wallet extension.
Who needs to encode:
- Injected provider (
window.amadeus): the extension's page script encodes args for you. You can passUint8Arrayvalues directly. - Amadeus Connect (mobile wallet):
makeRequestandsealRequestcallJSON.stringifywithout encoding. WrapargswithencodeBinaryValuesyourself before building anamadeus_signTransactionrequest.
Message signing
signMessage signs a human-readable string, such as a login challenge or a terms acceptance. Nothing goes on chain. The result can be checked by the dApp or its backend with verifyMessage.
import { signMessage, verifyMessage } from '@amadeus-protocol/wallet-sdk'
const signed = signMessage({ seed, message: challenge })
// { message, signature: Base58 (96 bytes), address: Base58 }
const isValid = verifyMessage({
message: challenge,
signature: signed.signature,
address: expectedAddress
})
The signature is BLS.sign(sha256(utf8(message)), sk, MESSAGE_DST). Because of the dedicated DST, a message signature never verifies as a transaction, an API key or a connect proof, and the reverse is also true.
signMessagetakesSignMessageParams({ seed, message }) and returnsSignMessageResult({ message, signature, address }).verifyMessagetakesVerifyMessageParams({ message, signature, address }), so you can pass aSignMessageResultstraight in.signMessagethrowsWalletSdkErrorINVALID_ARGUMENTif the message is empty or longer thanMAX_MESSAGE_LENGTH(4096). The limit counts JavaScript string length (UTF-16 code units), not bytes.verifyMessagenever throws. Bad Base58, a wrong-length address or signature, or an over-long message all returnfalse.
A signed message has no expiry, audience or nonce of its own. For a login flow, put a server-issued nonce and the domain in the message, check them yourself, and verify against the address you expect, not just the address the wallet returned.
A dApp can only ask a wallet to sign a message over Amadeus Connect (amadeus_signMessage, supported by the mobile wallet). The injected extension provider, WalletClient and useWallet have no signMessage in 0.2.0.
Connection auth
When a wallet approves a connection, it proves control of its address by signing a transcript of the whole handshake, not just the dApp's challenge. Signing only the challenge would let an attacker replay a harvested signature under their own session keys. Binding the session keys and origin into the signed bytes closes that.
import { signConnect, verifyConnect } from '@amadeus-protocol/wallet-sdk'
import type { ConnectTranscript } from '@amadeus-protocol/wallet-sdk'
const transcript: ConnectTranscript = {
origin: 'https://app.example.com',
dappPublicKey,
walletPublicKey,
challenge,
requestId
}
const signature = signConnect({ seed, transcript })
const isValid = verifyConnect({ address, transcript, signature })
buildConnectTranscript(transcript)returns the canonical bytes:u32(len(label)) ‖ label ‖ u32(5), thenu32(len) ‖ utf8(field)fororigin,dappPublicKey,walletPublicKey,challengeandrequestId, in that order. The label isCONNECT_TRANSCRIPT_LABEL(amadeus-connect/v1) and lengths are 4-byte big-endian.signConnect({ seed, transcript })(SignConnectParams) returns a Base58 signature underCONNECT_DST.verifyConnect({ address, transcript, signature })(VerifyConnectParams) never throws; changing any field makes it returnfalse.
You rarely call these directly: the wallet's approveConnect calls signConnect, and the dApp's completeConnect calls verifyConnect and throws BAD_SIGNATURE on failure. See Amadeus Connect.
Session encryption
After connecting over Amadeus Connect, the dApp and the wallet exchange sealed requests and responses, over the bridge relay or deep links. Each side holds an ephemeral x25519 keypair, derives a shared 32-byte key, and seals every message with XChaCha20-Poly1305.
import {
bytesToUtf8,
deriveSharedKey,
generateSessionKeypair,
open,
seal,
utf8ToBytes
} from '@amadeus-protocol/wallet-sdk'
const dappKeys = generateSessionKeypair()
const walletKeys = generateSessionKeypair()
const dappSharedKey = deriveSharedKey(walletKeys.publicKey, dappKeys.secretKey)
const walletSharedKey = deriveSharedKey(dappKeys.publicKey, walletKeys.secretKey)
const envelope = seal(dappSharedKey, utf8ToBytes('hello'))
// { nonce: Base58 (24 bytes), ciphertext: Base58 }
const plaintext = bytesToUtf8(open(walletSharedKey, envelope))
| Function | What it does |
|---|---|
generateSessionKeypair() | Returns a SessionKeypair, { publicKey, secretKey }: a Base58 x25519 public key (safe to put in a QR code) and a 32-byte secret key (keep in memory only, never persist) |
deriveSharedKey(theirPublicKey, mySecretKey) | sha256(x25519(mySecretKey, theirPublicKey)). Both sides get the same key. Throws DECRYPT_FAILED on bad Base58, a key that is not 32 bytes, or a low-order point. |
seal(sharedKey, plaintext, aad?) | Encrypts with a fresh random 24-byte nonce. Optional aad is authenticated but not encrypted. |
open(sharedKey, envelope, aad?) | Decrypts. Throws DECRYPT_FAILED if the key is wrong, anything was tampered with, or the envelope is malformed. It fails closed. |
The x25519 session key is completely separate from the account's BLS signing key. Sizes are exported as SESSION_PUBLIC_KEY_BYTE_LENGTH (32), SESSION_SECRET_KEY_BYTE_LENGTH (32) and SESSION_NONCE_BYTE_LENGTH (24). sealRequest, openRequest, sealResponse and openResponse build on seal and open for wallet requests; see Amadeus Connect.
Low-level helpers
These are the primitives the functions above are built on. Prefer the higher-level functions: they pick the right DST for you.
| Function | What it does |
|---|---|
deriveSigner(seed) | Returns SignerKeys, { sk, pk }: the 32-byte secret key and 48-byte public key for a Base58 seed |
signHashed(payload, sk, dst) | BLS.sign(sha256(payload), sk, { DST: dst }). Pass the raw payload; it hashes for you. |
verifyHashed(signature, payload, publicKey, dst) | Verifies a signHashed signature. Never throws. |
publicKeyFromAddress(address) | Decodes a Base58 address to 48 bytes. Throws INVALID_ADDRESS otherwise. |
signatureFromBase58(signature) | Decodes a Base58 signature to 96 bytes. Throws INVALID_SIGNATURE otherwise. |
equalBytes(left, right) | Constant-time byte comparison (length is not treated as secret) |
randomBytes(length), randomId(byteLength?) | CSPRNG bytes, and a random hex id (16 bytes, 32 characters, by default) |
utf8ToBytes, bytesToUtf8, concatBytes, u32be | Encoding helpers used to build signed payloads |
Errors
Helpers throw WalletSdkError, which has a stable code so you can branch without matching messages:
import { WalletSdkError, submitTransaction } from '@amadeus-protocol/wallet-sdk'
try {
await submitTransaction(txPacked, { nodeUrl: 'https://mainnet-rpc.ama.one/api' })
} catch (error) {
if (error instanceof WalletSdkError && error.code === 'SUBMIT_FAILED') {
console.error('Node rejected the transaction:', error.message)
} else {
throw error
}
}
| Code | Thrown by (on this page) |
|---|---|
INVALID_ARGUMENT | generateApiKey, signMessage, submitTransaction |
INVALID_API_KEY | decodeApiKey |
SUBMIT_FAILED | submitTransaction |
DECRYPT_FAILED | deriveSharedKey, open |
INVALID_ADDRESS | publicKeyFromAddress |
INVALID_SIGNATURE | signatureFromBase58 |
AUD_MISMATCH | Nothing. verifyApiKey returns reason: 'aud_mismatch' instead. |
The remaining codes come from other layers: BAD_SIGNATURE from completeConnect, EXPIRED from guardRequest (see Amadeus Connect) and UNSUPPORTED from WalletClient.switchAccount (see Connect a dApp).
verifyApiKey, verifyMessage, verifyConnect and verifyHashed never throw. Errors from @amadeus-protocol/sdk (for example an invalid seed, or a Coin.transfer recipient that is not Base58) pass through as plain Errors.
Security notes
- One DST per purpose. Transactions, API keys, messages and connect proofs each have their own DST, and testnet transactions have their own too. A signature from one context is unusable in another.
- Always set
audwhen verifying API keys. Without it, a token issued for another service is accepted. - Bound untrusted input.
decodeApiKeyrejects strings over 1024 characters before decoding, andsignMessagerejects messages over 4096 characters. - Connect proofs cover the whole handshake: origin, both session keys, challenge and request id.
- The session box fails closed. Any tampering, wrong key or malformed envelope throws
DECRYPT_FAILED. Session secret keys and shared keys belong in memory only. - Show users what they sign. Use
describeBinaryValuesto render byte arguments in approval screens instead of raw JSON. - Never ship a seed to the browser. Signing helpers are for wallets and trusted servers. dApps go through the wallet.
Related
- Wallet SDK overview
- Provider reference: the injected provider's
signTransactionandgenerateApiKey - Build a wallet integration:
handleRequest, which calls these helpers for each wallet request - Core SDK introduction: key derivation,
TransactionBuilderand the node API - Chrome extension integration guide