7. Examples
Real-world usage examples for @amadeus-protocol/sdk 1.8.0. The read-only examples run as they are against mainnet. The transfer examples need a funded key and send real AMA, so try them on testnet first (see Testnet usage).
The SDK is ESM only. Run these samples in a project with "type": "module" in package.json (Node.js 20 or later), with npx tsx file.ts, or through a bundler. See Troubleshooting.
Basic SDK Usage
Initialize SDK and Query Chain
import { AmadeusSDK } from '@amadeus-protocol/sdk'
const sdk = new AmadeusSDK({
baseUrl: 'https://mainnet-rpc.ama.one/api'
})
// height and the other header fields live under entry.header
const { entry } = await sdk.chain.getTip()
console.log('Current height:', entry.header.height)
console.log('Entry hash:', entry.hash)
const { stats } = await sdk.chain.getStats()
console.log('Rooted height:', stats.rooted_height)
console.log('Tx pool size:', stats.tx_pool_size)
console.log('Burned (AMA):', stats.burned)
new AmadeusSDK() with no arguments uses the same mainnet URL, https://mainnet-rpc.ama.one/api.
Key Generation
Generate and Use Keypair
import { generateKeypair, derivePublicKeyFromSeedBase58 } from '@amadeus-protocol/sdk'
const keypair = generateKeypair()
console.log('Public key (address):', keypair.publicKey)
console.log('Private key (seed):', keypair.privateKey) // keep secret
// derive the address from an existing seed
const publicKey = derivePublicKeyFromSeedBase58(keypair.privateKey)
console.log('Derived public key:', publicKey)
To create or restore an account from a 12-word recovery phrase, see Recovery phrases.
Wallet Operations
Check Balance
import { AmadeusSDK } from '@amadeus-protocol/sdk'
const sdk = new AmadeusSDK()
const address = '69TDon8KJp3vicNeFR3dg5x5sKY8PJFLmoizX3RN31YL4fwr266AVcXgwy1mjCLy6M'
const { balance } = await sdk.wallet.getBalance(address, 'AMA')
console.log('AMA balance:', balance.float)
// balances is an array with one entry per token the account holds
const { balances } = await sdk.wallet.getAllBalances(address)
balances.forEach(({ symbol, float }) => {
console.log(`${symbol}: ${float}`)
})
An account that has never held a token is not an error: getBalance returns a zero balance and getAllBalances returns { balances: [] }.
Get Transaction History
There is no wallet.getTransactions. Query the chain index with chain.getByFilter: signer matches transactions the account sent, and arg0 matches the first argument, which for a Coin transfer is the recipient.
import { AmadeusSDK } from '@amadeus-protocol/sdk'
const sdk = new AmadeusSDK()
const address = '69TDon8KJp3vicNeFR3dg5x5sKY8PJFLmoizX3RN31YL4fwr266AVcXgwy1mjCLy6M'
const sent = await sdk.chain.getByFilter({ signer: address, limit: 10, sort: 'desc' })
const received = await sdk.chain.getByFilter({ arg0: address, limit: 10, sort: 'desc' })
sent.txs.forEach((tx) => {
console.log('Hash:', tx.hash)
console.log('Action:', `${tx.tx.action.contract}.${tx.tx.action.function}`, tx.tx.action.args)
console.log('Executed:', tx.receipt.success, tx.receipt.result)
})
console.log('Received:', received.txs.length)
receipt.success is false for a transaction that was included but failed, for example a transfer with receipt.result set to insufficient_funds. Each response also has a cursor for the next page (see below).
Page Through Results
getByFilter returns at most limit transactions (default 100, at most 1,000) and a cursor. Pass the cursor back to read the next page. A page with fewer than limit transactions is the last one, but it still carries a cursor: the cursor is null only when a page comes back empty.
import { AmadeusSDK, type Transaction } from '@amadeus-protocol/sdk'
const sdk = new AmadeusSDK()
const pageSize = 100
async function readTransfers(cursor: string | undefined, pagesLeft: number): Promise<Transaction[]> {
const page = await sdk.chain.getByFilter({
contract: 'Coin',
function: 'transfer',
limit: pageSize,
sort: 'desc',
cursor
})
if (!page.cursor || page.txs.length < pageSize || pagesLeft <= 1) return page.txs
return [...page.txs, ...(await readTransfers(page.cursor, pagesLeft - 1))]
}
const transfers = await readTransfers(undefined, 3)
console.log('Read', transfers.length, 'transfers')
Transaction Building
These examples read the seed from an environment variable. They sign for mainnet. For testnet, create the builder with new TransactionBuilder(seed, { network: NetworkType.TESTNET }) and use the testnet baseUrl, as shown in Testnet usage.
Simple Token Transfer
import { AmadeusSDK, AmadeusSDKError, TransactionBuilder } from '@amadeus-protocol/sdk'
const seed = process.env.AMADEUS_SEED
if (!seed) throw new Error('Set AMADEUS_SEED')
const sdk = new AmadeusSDK()
const builder = new TransactionBuilder(seed)
const { txHash, txPacked } = builder.transfer({
recipient: '69TDon8KJp3vicNeFR3dg5x5sKY8PJFLmoizX3RN31YL4fwr266AVcXgwy1mjCLy6M',
amount: 10.5,
symbol: 'AMA'
})
console.log('Transaction hash:', txHash)
try {
const { hash } = await sdk.transaction.submit(txPacked)
console.log('Accepted into the pool:', hash)
} catch (error) {
// error.message is the node's code, e.g. invalid_tx_nonce
console.error('Rejected:', error instanceof AmadeusSDKError ? error.message : error)
}
submit resolves as soon as the node accepts the transaction into its pool. It has not executed yet: use submitAndWait to get the receipt.
Transfer with Confirmation
submitAndWait submits the transaction and returns once it is included in an entry. Check receipt.success: an included transaction can still fail to execute.
import {
AmadeusSDK,
TransactionBuilder,
getExecutionErrorMessage
} from '@amadeus-protocol/sdk'
const seed = process.env.AMADEUS_SEED
if (!seed) throw new Error('Set AMADEUS_SEED')
const sdk = new AmadeusSDK()
const { txPacked } = new TransactionBuilder(seed).transfer({
recipient: '69TDon8KJp3vicNeFR3dg5x5sKY8PJFLmoizX3RN31YL4fwr266AVcXgwy1mjCLy6M',
amount: 10.5,
symbol: 'AMA'
})
try {
const { hash, metadata, receipt } = await sdk.transaction.submitAndWait(txPacked)
console.log('Included in entry', metadata.entry_hash, 'at height', metadata.entry_height)
if (receipt.success) {
console.log('Executed:', hash)
} else {
console.error('Execution failed:', getExecutionErrorMessage(receipt.result ?? 'unknown'))
}
} catch (error) {
console.error('Rejected or not confirmed in time:', error)
}
Wait for Finality
Pass { finalized: true } when you need finality rather than inclusion, for example before crediting an off-chain ledger.
import { AmadeusSDK } from '@amadeus-protocol/sdk'
declare const txPacked: Uint8Array
const sdk = new AmadeusSDK()
const { hash, metadata } = await sdk.transaction.submitAndWait(txPacked, { finalized: true })
console.log('Finalized:', hash, metadata.status)
The node polls for the transaction for about 6 seconds (60 checks, 100 ms apart) and the call throws if it is not there by then. The transaction may still land: look it up with sdk.transaction.get(hash) before you sign a new one.
Custom Contract Call
buildAndSign signs any contract call. This one is the same Coin.transfer that builder.transfer() builds: the recipient as raw bytes, the amount in atomic units as a string, and the symbol.
import { AmadeusSDK, TransactionBuilder, fromBase58, toAtomicAma } from '@amadeus-protocol/sdk'
declare const seed: string
const sdk = new AmadeusSDK()
const builder = new TransactionBuilder(seed)
const { txHash, txPacked } = builder.buildAndSign('Coin', 'transfer', [
fromBase58('69TDon8KJp3vicNeFR3dg5x5sKY8PJFLmoizX3RN31YL4fwr266AVcXgwy1mjCLy6M'),
toAtomicAma(1).toString(),
'AMA'
])
const { hash } = await sdk.transaction.submit(txPacked)
console.log(txHash === hash)
For contracts with an ABI (Lockup, LockupPrime, NFTs), use builder.contract(ABI) instead. See Contracts and NFTs.
Build Unsigned, Inspect, Then Sign
import { TransactionBuilder, toBase58 } from '@amadeus-protocol/sdk'
declare const seed: string
const builder = new TransactionBuilder(seed)
const unsignedTx = builder.buildTransfer({
recipient: '69TDon8KJp3vicNeFR3dg5x5sKY8PJFLmoizX3RN31YL4fwr266AVcXgwy1mjCLy6M',
amount: 10.5,
symbol: 'AMA'
})
console.log('Nonce:', unsignedTx.tx.nonce.toString())
console.log('Signer:', toBase58(unsignedTx.tx.signer))
console.log('Action:', unsignedTx.tx.action.contract, unsignedTx.tx.action.function)
console.log('Hash:', toBase58(unsignedTx.hash))
const { txHash, txPacked } = builder.sign(unsignedTx)
Contract State
Read an Account's Staking Position
sdk.staking reads the account's LockupVault vaults and rolls them up. Amounts ending in Flat are atomic bigint values; use flatToAma to display them.
import { AmadeusSDK, flatToAma } from '@amadeus-protocol/sdk'
const sdk = new AmadeusSDK()
const owner = '6V668VVot57QvwjY2s1w8RbgeYE2ftBCxUt1uNp5mfJgXPiUoepteUguXUSYpf3a7E'
const position = await sdk.staking.getPosition(owner)
console.log(`${position.totalStaked} AMA in ${position.vaultCount} vaults (epoch ${position.epoch})`)
position.vaults.forEach((vault) => {
console.log(`Vault ${vault.index}: ${vault.tier}, ${flatToAma(vault.totalFlat)} AMA`)
})
See Staking for every field.
Read Raw State by Prefix
/api/contract/get_prefix answers with binary VecPack pages. getPrefixEntries follows every page and returns [key, value] byte pairs, with the queried prefix stripped from each key. The older getPrefix() reads the body as text and cannot decode it.
import { AmadeusSDK, buildOwnerVaultsKeyPrefix } from '@amadeus-protocol/sdk'
const sdk = new AmadeusSDK()
const owner = '6V668VVot57QvwjY2s1w8RbgeYE2ftBCxUt1uNp5mfJgXPiUoepteUguXUSYpf3a7E'
// prefix bytes: bic:lockup_vault:vault:{owner}:
const entries = await sdk.contract.getPrefixEntries(buildOwnerVaultsKeyPrefix(owner))
for (const [key, value] of entries) {
console.log('Vault index:', new TextDecoder().decode(key), `(${value.length} bytes)`)
}
A prefix that matches nothing returns []. To decode the values, see Contract state.
Read One State Key
contract.get reads a single key. An account's AMA balance is stored under account:{public key bytes}:balance:AMA, and the node returns it as a string holding the exact atomic amount (for example "40414833934371491").
import { AmadeusSDK, fromBase58 } from '@amadeus-protocol/sdk'
const sdk = new AmadeusSDK()
const address = '69TDon8KJp3vicNeFR3dg5x5sKY8PJFLmoizX3RN31YL4fwr266AVcXgwy1mjCLy6M'
const encoder = new TextEncoder()
const key = new Uint8Array([
...encoder.encode('account:'),
...fromBase58(address),
...encoder.encode(':balance:AMA')
])
const flat = await sdk.contract.get(key)
console.log('Atomic balance:', flat)
Get Richlist
The richlist holds the top 1,000 AMA accounts, sorted by balance. Each entry is { pk, symbol, flat, float }, where float is rounded down to whole AMA; the rank is the array index. The node recomputes the list at most once an hour.
import { AmadeusSDK } from '@amadeus-protocol/sdk'
const sdk = new AmadeusSDK()
const { richlist } = await sdk.contract.getRichlist()
richlist.slice(0, 10).forEach((entry, index) => {
console.log(`#${index + 1}: ${entry.pk} ${entry.float.toLocaleString()} ${entry.symbol}`)
})
Validate Bytecode
sdk.contract.validateBytecode() is deprecated since 1.8.0. Current nodes do not serve /api/contract/validate_bytecode, so it sends no request and throws a deprecation error (AmadeusSDKError, status 404, message contract.validateBytecode is deprecated: ...). Contracts on Amadeus are RISC-V programs that run on testnet only. See Smart contracts.
Parallel Reads
Since 1.7.0, one AmadeusSDK instance can run requests in parallel.
import { AmadeusSDK } from '@amadeus-protocol/sdk'
const sdk = new AmadeusSDK()
const [tipResponse, statsResponse, kpiResponse] = await Promise.all([
sdk.chain.getTip(),
sdk.chain.getStats(),
sdk.chain.getKpi()
])
console.log('Height:', tipResponse.entry.header.height)
console.log('Circulating:', statsResponse.stats.circulating)
console.log('Total transactions:', kpiResponse.kpi.total_tx)
Earlier versions aborted the request in flight whenever a new one started and reported it as a timeout. On 1.6.x or older, upgrade, or make the calls one after another.
Encryption
Encrypt and Store Private Key
import { encryptWithPassword, decryptWithPassword, generateKeypair } from '@amadeus-protocol/sdk'
const keypair = generateKeypair()
// { encryptedData, iv, salt }, all Base64: store all three
const encrypted = await encryptWithPassword(keypair.privateKey, 'user-password-123')
const decryptedKey = await decryptWithPassword(encrypted, 'user-password-123')
console.log('Decrypted key matches:', decryptedKey === keypair.privateKey)
A wrong password throws Error('Decryption failed. Incorrect password or corrupted data.').
Error Handling
Handle a Missing Resource
Every SDK failure is an AmadeusSDKError. A lookup of something that does not exist, such as an unknown transaction hash, throws with status 404.
import { AmadeusSDK, AmadeusSDKError, type Transaction } from '@amadeus-protocol/sdk'
const sdk = new AmadeusSDK()
async function findTransaction(hash: string): Promise<Transaction | null> {
try {
return await sdk.transaction.get(hash)
} catch (error) {
if (error instanceof AmadeusSDKError && error.status === 404) return null
throw error
}
}
// a real mainnet transfer; an unknown hash prints null
console.log(await findTransaction('94Zdxhm8gk7shZuiiiSoZLLJ64QyxZr7CUSctcyTNrvd'))
Input that is not Base58 is rejected before any request is sent, with status undefined. For every error shape and the transaction error codes, see Error handling.
Complete Transaction Flow
End-to-End Transaction Example
Check the balance, sign, submit once with submitAndWait, then check the receipt. The balance check keeps AMA_TRANSFER_FEE (0.02 AMA) back as a reserve; the chain needs only a 0.01 AMA budget and charges a fraction of it (see Transaction fees).
import {
AMA_TRANSFER_FEE,
AmadeusSDK,
TransactionBuilder,
derivePublicKeyFromSeedBase58,
getExecutionErrorMessage,
makeTransactionUrl,
toAtomicAma
} from '@amadeus-protocol/sdk'
async function sendAma(seed: string, recipient: string, amount: number): Promise<string> {
const sdk = new AmadeusSDK({ baseUrl: 'https://mainnet-rpc.ama.one/api' })
const sender = derivePublicKeyFromSeedBase58(seed)
const { balance } = await sdk.wallet.getBalance(sender, 'AMA')
if (balance.flat < toAtomicAma(amount) + toAtomicAma(AMA_TRANSFER_FEE)) {
throw new Error(`Balance too low: ${balance.float} AMA`)
}
const { txHash, txPacked } = new TransactionBuilder(seed).transfer({
recipient,
amount,
symbol: 'AMA'
})
// one submission: submitAndWait sends the transaction itself
const { metadata, receipt } = await sdk.transaction.submitAndWait(txPacked)
if (!receipt.success) {
throw new Error(getExecutionErrorMessage(receipt.result ?? 'unknown'))
}
console.log(`Included at height ${metadata.entry_height}: ${makeTransactionUrl(txHash)}`)
return txHash
}
const seed = process.env.AMADEUS_SEED
if (!seed) throw new Error('Set AMADEUS_SEED')
await sendAma(seed, '69TDon8KJp3vicNeFR3dg5x5sKY8PJFLmoizX3RN31YL4fwr266AVcXgwy1mjCLy6M', 10.5)
Do not call submit and then submitAndWait with the same txPacked: both send the transaction.
Batch Operations
Submit Multiple Transactions
Build and submit one transaction at a time. The nonce comes from the build time (Date.now() * 1_000_000), so two transactions built in the same millisecond share a nonce and only one can execute. A transaction with a higher nonce that lands first also makes a lower one invalid.
import { AmadeusSDK, AmadeusSDKError, TransactionBuilder } from '@amadeus-protocol/sdk'
type BatchResult =
| { recipient: string; hash: string }
| { recipient: string; error: string }
const sdk = new AmadeusSDK()
async function submitBatch(
seed: string,
transfers: Array<{ recipient: string; amount: number }>
): Promise<BatchResult[]> {
const builder = new TransactionBuilder(seed)
const results: BatchResult[] = []
for (const transfer of transfers) {
try {
const { txPacked } = builder.transfer({ ...transfer, symbol: 'AMA' })
const { hash } = await sdk.transaction.submit(txPacked)
results.push({ recipient: transfer.recipient, hash })
} catch (error) {
const message = error instanceof AmadeusSDKError ? error.message : String(error)
results.push({ recipient: transfer.recipient, error: message })
}
}
return results
}