Skip to main content

Trustless Flow

Integrate AMA deposits and withdrawals on an exchange with the public RPC and the amadeusd binary, crediting only successful, finalized AMA transfers.

An exchange can run an AMA integration on the public RPC alone. The steps are: record a starting height, generate deposit addresses, detect deposits, wait for finality, and send withdrawals. You can do the key and signing work with the amadeusd binary used as a command-line tool, or with the TypeScript SDK.

The RPC base URLs are https://mainnet-rpc.ama.one/api (mainnet) and https://testnet-rpc.ama.one/api (testnet). See Networks for every endpoint and protocol parameter.

Amounts have 9 decimals​

AMA has 9 decimals: 1 AMA = 1,000,000,000 base units, which the node and the SDK call "flat". On chain, every amount is an integer string of flat units, for example "1000000000" for 1 AMA or "64516000000000" for 64,516 AMA. Store and compare amounts as integers (bigint in TypeScript). Never use floats: amounts above about 9 million AMA lose precision in a JavaScript number.

Download the binary​

amadeusd is the node. It also works as a single-command utility, similar to geth, for generating keys and signing transactions:

wget https://github.com/amadeusprotocol/node/releases/latest/download/amadeusd
chmod +x amadeusd

Running a Node shows how to verify the download against its amadeusd.sig signature.

1. Record your starting height​

When your integration goes live, record the current height. Deposits are scanned forward from there.

curl -s https://mainnet-rpc.ama.one/api/chain/stats \
| jq '{height: .stats.height, rooted_height: .stats.rooted_height, tip_hash: .stats.tip_hash}'
{
"height": 90324568,
"rooted_height": 90324568,
"tip_hash": "BaKW7LKa15N2DExy6j394aDSbG3AMSKdephwZTPttceV"
}
  • height is the tip of the chain. It is also at .stats.tip.header.height.
  • rooted_height is the latest finalized height. Everything at or below it is final.
  • tip_hash is the hash of the tip block. It is also at .stats.tip.hash.

2. Generate deposit addresses​

./amadeusd --bw-command start generate_wallet

The command prints one line with two Base58 values separated by a space:

<public_key_b58> <seed64_b58>
  • The first value is the public key. It is the deposit address you show the user.
  • The second value is the 64-byte secret seed. Anyone who has it can spend the address. Store it in your key management system; you need it later as SEED64 to sweep or withdraw.

In TypeScript, generateKeypair() from @amadeus-protocol/sdk returns the same pair as { publicKey, privateKey } (see Utilities).

What a transfer looks like​

Transaction endpoints return transactions in this shape (in blocks from height_with_txs, metadata has no status). This is a real AMA transfer on mainnet:

curl -s https://mainnet-rpc.ama.one/api/chain/tx/13NCvUdgCn9Rc2J1US4HgcWXQMkzo4JBXwAzDh8CCte5 | jq
{
"metadata": {
"status": "finalized",
"entry_hash": "9QDWVWaXxCbWGLACMvKpKfa6PxCiCXEMqibNPZ9Dam2h",
"entry_height": 90323898
},
"signature": "24LyJ3vnnPYq3aMZAgEje1o93XETiFpBnzoeyzk7MeMGECR68scWRYMhcwpwkmJBpDy32qkkWr3in5XSSMVfEdjEanPCFeHGY57GnVS7mo4p56WsQtyiokBSmvhYXHzageeb",
"result": {
"error": "ok"
},
"hash": "13NCvUdgCn9Rc2J1US4HgcWXQMkzo4JBXwAzDh8CCte5",
"tx": {
"action": {
"args": [
"6Bae26KXwdAsHjCRVLiavjAq8MqRdXQ9Bm5i5wJzSScvpNkGD76SY3SsEimp3HkBNe",
"689770",
"AMA"
],
"function": "transfer",
"op": "call",
"contract": "Coin"
},
"nonce": 1794240284924000000,
"signer": "5xhrsYu1fAu5T1wRpV8NAucrpBwSqqjspWDDRC1ra9dCpLDswRY7mD9rZExZvSB4xr"
},
"receipt": {
"success": true,
"result": "ok",
"logs": [],
"exec_used": "310811"
}
}
  • tx.signer is the sender. tx.action is a single object (older responses had an actions array).
  • For Coin.transfer, tx.action.args is [receiver, amount, symbol]: the receiver's Base58 public key, the amount in flat units as a string, and the token symbol.
  • metadata.entry_height is the block height. metadata.status is pending (still in the mempool), committed (in a block that is not final yet) or finalized.
  • receipt.success tells you whether the transfer executed. receipt.result is "ok" on success and the error otherwise (for example "insufficient_funds"). Read the receipt; the older result.error field is deprecated.

3. Detect deposits​

Credit a transaction only when all of these hold:

  1. tx.action.contract == "Coin" and tx.action.function == "transfer".
  2. tx.action.args[2] == "AMA".
  3. tx.action.args[0] is one of your deposit addresses.
  4. receipt.success == true.
  5. The transaction is finalized (see step 4).

Use the transaction hash as the idempotency key, so that a transaction is never credited twice.

:::warning Checking the function name is not enough Other calls share the transfer name: Nft.transfer, Coin.transfer of tokens other than AMA (user-created tokens and PRIME), and any user contract with a function called transfer. Failed transfers are also included in blocks, with receipt.success: false (for example "insufficient_funds"). An integration that credits every transfer it sees credits failed transfers and non-AMA tokens as AMA deposits. :::

There are two ways to find deposits. Scanning blocks sees every transaction. Polling per-address indexes is simpler, but it needs care with ordering.

Option A: scan finalized blocks​

Read each height from your starting height up to rooted_height with /api/chain/height_with_txs/<height>. A height can hold more than one entry; use the one with in_main_chain: true.

curl -s https://mainnet-rpc.ama.one/api/chain/height_with_txs/90323898 \
| jq '[.entries[] | select(.in_main_chain) | .txs[]
| select(.tx.action.contract == "Coin" and .tx.action.function == "transfer"
and .tx.action.args[2] == "AMA" and .receipt.success)
| {hash, height: .metadata.entry_height, from: .tx.signer, to: .tx.action.args[0], amount_flat: .tx.action.args[1]}]'
[
{
"hash": "3DudhfLWRYYvmwB5bMZ4sShFZ9pHhzcqJV8ZzTs7QvFf",
"height": 90323898,
"from": "75kqjwJTfNCFgRkSzaCgES5ECd3DW23CBVkjwMx9rTs9PBv6oD8Gm871yR5rC4XnKQ",
"to": "6Bae26KXwdAsHjCRVLiavjAq8MqRdXQ9Bm5i5wJzSScvpNkGD76SY3SsEimp3HkBNe",
"amount_flat": "36184"
},
{
"hash": "13NCvUdgCn9Rc2J1US4HgcWXQMkzo4JBXwAzDh8CCte5",
"height": 90323898,
"from": "5xhrsYu1fAu5T1wRpV8NAucrpBwSqqjspWDDRC1ra9dCpLDswRY7mD9rZExZvSB4xr",
"to": "6Bae26KXwdAsHjCRVLiavjAq8MqRdXQ9Bm5i5wJzSScvpNkGD76SY3SsEimp3HkBNe",
"amount_flat": "689770"
}
]

Then keep only the transactions whose to is one of your deposit addresses. In TypeScript, the same loop looks like this. Run it on a schedule and persist nextHeight together with the deposits it returns:

const RPC = 'https://mainnet-rpc.ama.one/api'

interface ChainTx {
hash: string
tx: { signer: string; action: { contract: string; function: string; args: string[] } }
metadata: { entry_hash: string; entry_height: number }
receipt: { success: boolean; result: string }
}

interface ChainEntry {
hash: string
in_main_chain: boolean
txs: ChainTx[]
}

interface Deposit {
txHash: string
height: number
from: string
to: string
amountFlat: bigint
}

// Load these from your database
const depositAddresses = new Set<string>(['<deposit_address_b58>'])

async function getJson<T>(path: string): Promise<T> {
const response = await fetch(`${RPC}${path}`)
if (!response.ok) throw new Error(`${path}: HTTP ${response.status}`)
return (await response.json()) as T
}

function toDeposit(chainTx: ChainTx): Deposit | null {
const { action } = chainTx.tx
const [receiver, amount, symbol] = action.args
const isAmaTransfer =
action.contract === 'Coin' && action.function === 'transfer' && symbol === 'AMA'
if (!isAmaTransfer || !chainTx.receipt.success || !depositAddresses.has(receiver)) return null
return {
txHash: chainTx.hash,
height: chainTx.metadata.entry_height,
from: chainTx.tx.signer,
to: receiver,
amountFlat: BigInt(amount)
}
}

// Scans finalized heights from `fromHeight`; store `nextHeight` with the deposits
export async function scanFinalized(
fromHeight: number,
maxBlocks = 500
): Promise<{ deposits: Deposit[]; nextHeight: number }> {
const { stats } = await getJson<{ stats: { rooted_height: number } }>('/chain/stats')
const lastHeight = Math.min(stats.rooted_height, fromHeight + maxBlocks - 1)
const heights = Array.from(
{ length: Math.max(0, lastHeight - fromHeight + 1) },
(_unused, index) => fromHeight + index
)
const deposits: Deposit[] = []
for (const height of heights) {
const { entries } = await getJson<{ entries: ChainEntry[] }>(`/chain/height_with_txs/${height}`)
const mainEntry = entries.find((entry) => entry.in_main_chain)
if (!mainEntry) throw new Error(`no main-chain entry at finalized height ${height}`)
deposits.push(...mainEntry.txs.map(toDeposit).filter((deposit) => deposit !== null))
}
return { deposits, nextHeight: fromHeight + heights.length }
}

Blocks come every 500 ms, so the scanner has to read about two heights per second to keep up.

Option B: poll per-address indexes​

The node indexes transactions by receiver, so you can ask for the incoming transfers of one deposit address. Two endpoints serve the same index:

  • GET /api/chain/tx_events_by_account/<address>?type=recv&contract=Coin&function=transfer&limit=<n>&cursor_b58=<cursor>
  • GET /api/chain/tx_by_filter?receiver=<address>&contract=Coin&function=transfer&limit=<n>&cursor=<cursor> (arg0= is an alias of receiver=)
curl -s "https://mainnet-rpc.ama.one/api/chain/tx_events_by_account/7gtsTXviGdwUU2pdFhfJRXjBPQMvuzq1NVdMs25VedjCaAQgP8iHTUSXfRrsn5LMyx?type=recv&contract=Coin&function=transfer&limit=100" \
| jq '{cursor, txs: [.txs[] | {hash, height: .metadata.entry_height, status: .metadata.status, success: .receipt.success, amount_flat: .tx.action.args[1], symbol: .tx.action.args[2]}]}'
{
"cursor": "NEnZVLDnL6CNuaVjBzsm5i8kxJhMW7gUY",
"txs": [
{
"hash": "HQptKEem5F5YdJ5Vysh8vqaYQWr4q9FxmJfxm147m3j",
"height": 28269167,
"status": "finalized",
"success": true,
"amount_flat": "1000000000",
"symbol": "AMA"
},
{
"hash": "CkKhdjXHf4fPiXAm7VNBDrMBGq7CB2xueJWzT3V1NASf",
"height": 28269227,
"status": "finalized",
"success": true,
"amount_flat": "1000000000000",
"symbol": "AMA"
},
{
"hash": "8zRZ4u2kxTSJYqEbvwehJQwa9EK9aufRcgnPuNC63ZcK",
"height": 28348400,
"status": "finalized",
"success": true,
"amount_flat": "100000000000",
"symbol": "AMA"
}
]
}

How paging works:

  • limit defaults to 100 and goes up to 1000. tx_events_by_account lowers a larger value to 1000; tx_by_filter fails with an error.
  • Pass the cursor of the previous response to get the next page. tx_events_by_account takes it as cursor_b58=; with cursor= it returns an empty page. tx_by_filter takes it as cursor=.
  • The last page with results still returns a cursor. You have read everything when a page comes back with an empty txs array (its cursor is null).
  • Results are ordered by the transaction nonce (sort=asc by default, or sort=desc), not by block height. The sender chooses the nonce: the SDK and the node use a timestamp, but other senders use small counters (mainnet transfer 5uvc1djXbqS4Hz1hpJoihE4jaLitNB755DFycTJeTcNp has nonce 1120). A cursor you saved earlier is therefore not a safe "since" marker: a new deposit can sort before it. Re-read the full list of each address, or use Option A, and deduplicate by hash.
  • The index does not include the token symbol, and it also returns failed transfers. Apply all five checks above to every result.
  • The index stores one entry per receiver and nonce. If two senders pay the same address with the same nonce, only one of the two transfers is listed. Block scanning (Option A) does not have this gap.

With the SDK, sdk.chain.getByFilter calls tx_by_filter:

import { AmadeusSDK, type Transaction } from '@amadeus-protocol/sdk'

const sdk = new AmadeusSDK({ baseUrl: 'https://mainnet-rpc.ama.one/api' })

async function incomingTransfers(depositAddress: string, cursor?: string): Promise<Transaction[]> {
const page = await sdk.chain.getByFilter({
arg0: depositAddress,
contract: 'Coin',
function: 'transfer',
limit: 1000,
cursor
})
if (page.txs.length === 0 || !page.cursor) return page.txs
return [...page.txs, ...(await incomingTransfers(depositAddress, page.cursor))]
}

export async function creditableDeposits(depositAddress: string): Promise<Transaction[]> {
const transfers = await incomingTransfers(depositAddress)
return transfers.filter(
(transfer) =>
transfer.tx.action.contract === 'Coin' &&
transfer.tx.action.function === 'transfer' &&
transfer.tx.action.args[0] === depositAddress &&
transfer.tx.action.args[2] === 'AMA' &&
transfer.receipt.success &&
transfer.metadata.status === 'finalized'
)
}

4. Wait for finality​

Credit a deposit only once it is final:

  • With block scanning, read only heights at or below stats.rooted_height.
  • With a single transaction, check that GET /api/chain/tx/<hash> returns metadata.status == "finalized". A committed transaction is in a block that is not final yet.
curl -s https://mainnet-rpc.ama.one/api/chain/tx/3DudhfLWRYYvmwB5bMZ4sShFZ9pHhzcqJV8ZzTs7QvFf \
| jq '{status: .metadata.status, entry_height: .metadata.entry_height, success: .receipt.success, result: .receipt.result}'
{
"status": "finalized",
"entry_height": 90323898,
"success": true,
"result": "ok"
}

5. Send withdrawals​

A withdrawal is a Coin.transfer from your hot wallet with three arguments: the receiver's public key as raw 48 bytes, the amount as an integer string of flat units, and "AMA".

The receiver must be decoded from Base58. If you pass the Base58 string itself, the transaction is still included in a block, but it fails with invalid_receiver_pk.

With amadeusd​

buildtx signs the transaction with SEED64 and prints it as one Base58 line. It does not send anything, so you can run it on an offline signing machine. Put the argument list in single quotes so the shell passes it as one argument, and wrap the receiver in Base58.decode(...):

SEED64='<hot_wallet_seed64_b58>' ./amadeusd --bw-command start buildtx Coin transfer \
'[Base58.decode("<receiver_public_key_b58>"), "1000000000", "AMA"]'
<packed_tx_b58>

Here "1000000000" is 1 AMA. Submit the packed transaction to the RPC:

curl -s -X POST --data-binary '<packed_tx_b58>' https://mainnet-rpc.ama.one/api/tx/submit
{"error":"ok","hash":"<tx_hash_b58>"}

Any other error value means the node refused the transaction, and nothing was sent.

build_and_broadcasttx takes the same arguments, signs the transaction and submits it in one step. It prints the transaction hash when the node accepts it and prints nothing when it does not. It submits to the RPC in the RPC_URL variable, which defaults to https://mainnet-rpc.ama.one:

SEED64='<hot_wallet_seed64_b58>' ./amadeusd --bw-command start build_and_broadcasttx Coin transfer \
'[Base58.decode("<receiver_public_key_b58>"), "1000000000", "AMA"]'

For testnet, also set TESTNET=true (testnet transactions are signed under a different domain) and RPC_URL=https://testnet-rpc.ama.one.

With the SDK​

TransactionBuilder.signCall builds and signs the same call. sdk.transaction.submit posts it to /api/tx/submit. The example converts the amount from a decimal string without floating point, then waits for finality:

import {
AmadeusSDK,
AmadeusSDKError,
TransactionBuilder,
fromBase58,
type Transaction
} from '@amadeus-protocol/sdk'

const sdk = new AmadeusSDK({ baseUrl: 'https://mainnet-rpc.ama.one/api' })

// Exact decimal string to flat units (9 decimals), no floating point
export function amaToFlat(amount: string): bigint {
const [whole, fraction = ''] = amount.split('.')
if (!/^\d+$/.test(whole) || !/^\d{0,9}$/.test(fraction)) {
throw new Error(`invalid AMA amount: ${amount}`)
}
return BigInt(whole) * 1_000_000_000n + BigInt(fraction.padEnd(9, '0'))
}

// hotWalletSeed is the Base58 seed64, loaded from your secret store
export function buildWithdrawal(hotWalletSeed: string, receiver: string, amountFlat: bigint) {
return TransactionBuilder.signCall(hotWalletSeed, {
contract: 'Coin',
method: 'transfer',
args: [fromBase58(receiver), amountFlat.toString(), 'AMA']
})
}

const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))

async function findTx(txHash: string): Promise<Transaction | null> {
try {
return await sdk.transaction.get(txHash)
} catch (error) {
if (error instanceof AmadeusSDKError && error.status === 404) return null
throw error
}
}

export async function waitForFinalized(txHash: string, attemptsLeft = 120): Promise<Transaction> {
const found = await findTx(txHash)
if (found?.metadata.status === 'finalized') return found
if (attemptsLeft <= 1) throw new Error(`${txHash} is not finalized yet: check it again, never rebuild it`)
await sleep(1000)
return waitForFinalized(txHash, attemptsLeft - 1)
}

export async function sendWithdrawal(
hotWalletSeed: string,
receiver: string,
amount: string
): Promise<Transaction> {
const { txHash, txPacked } = buildWithdrawal(hotWalletSeed, receiver, amaToFlat(amount))
// Persist txHash and txPacked before submitting so a crash cannot cause a second payout
const submitted = await sdk.transaction.submit(txPacked)
if (submitted.hash !== txHash) throw new Error(`submit rejected: ${JSON.stringify(submitted)}`)
const finalized = await waitForFinalized(txHash)
if (!finalized.receipt.success) throw new Error(`withdrawal failed on chain: ${finalized.receipt.result}`)
return finalized
}

TransactionBuilder.signCall signs for mainnet unless you give it a network. On testnet with SDK 1.8.0 or later, pass NetworkType.TESTNET as its last argument, or create the builder with new TransactionBuilder(hotWalletSeed, { network: NetworkType.TESTNET }) and call buildAndSignCall(call) (see Networks and testnet). Older versions always sign for mainnet, so call signContractCall(hotWalletSeed, call, NetworkType.TESTNET) instead.

Confirm the withdrawal​

A withdrawal is done when GET /api/chain/tx/<hash> returns metadata.status == "finalized" and receipt.success == true. If receipt.success is false, the transfer is in a block but did not move funds; receipt.result says why.

POST /api/tx/submit_and_wait?finalized=true submits and waits in one call, and returns {error, hash, metadata, receipt}. The node only waits about 6 seconds (60 checks, 100 ms apart). If the transaction is not finalized by then, the call fails instead of returning a receipt, even though the transaction may still land. Treat that failure as "unknown" and look the hash up as above.

:::warning Never rebuild a withdrawal to retry it Every build picks a new nonce, so a rebuilt transaction is a second payment. Save the hash and the packed transaction before you submit. If the outcome is unclear, look up the saved hash, and if you need to, resubmit the same packed bytes. The chain only applies a signer's transactions with increasing nonces, so the same transaction can never be applied twice. :::

Trusting the RPC​

The flow above trusts the answers of the RPC you query. There are two ways to remove that trust.

Run your own node. See Running a Node. By default a node keeps only the last 10 epochs of history (about 6 days, HISTORY_KEEP_EPOCHS=10) and forwards lookups of blocks and transactions it no longer has to the RPC in RPC_URL. While pruning is on, the node never answers tx_by_filter or tx_events_by_account itself: it forwards them to RPC_URL too, or returns not_found if it has not pruned anything yet. This holds for any HISTORY_KEEP_EPOCHS above 0, so a larger value only widens the window for block scanning. To serve your full deposit history and the per-address indexes from your own node, run it with ARCHIVALNODE=true (plan for 2 TB or more of disk). Node configuration lists the variables.

Verify proofs. Balances can be checked against the validators' signatures without running a node. /api/chain/consensus/<height> returns the BLS quorum signature over the state root of a finalized block. /api/proof/contractstate/<key> proves the key account:<pk>:balance:AMA against that root. See Advanced Verification.