5. API Modules
Every API module of @amadeus-protocol/sdk 1.8.0, with signatures, return shapes and the node behavior behind them.
An AmadeusSDK instance groups the node's HTTP API into modules. Most methods validate their input, call one endpoint and return the parsed JSON. contract.getPrefixEntries and sdk.staking follow several pages and decode binary answers. This page covers version 1.8.0.
Setup
import { AmadeusSDK } from '@amadeus-protocol/sdk'
const sdk = new AmadeusSDK({ baseUrl: 'https://mainnet-rpc.ama.one/api' })
sdk.chain // entries, transactions, stats, KPIs
sdk.wallet // balances
sdk.transaction // submit and look up transactions
sdk.contract // contract state, view calls, richlist
sdk.epoch // validator scores, emission addresses
sdk.peer // nodes, validators, ANR records
sdk.proof // contract state, validator record and block proofs
sdk.staking // LockupVault staking positions
The rest of this page uses this sdk. Strings such as '5Kd3N...' stand for a Base58 public key or hash. For testnet, use https://testnet-rpc.ama.one/api as baseUrl.
AmadeusSDKConfig accepts three optional fields:
| Field | Default | Description |
|---|---|---|
baseUrl | https://mainnet-rpc.ama.one/api | Node API URL. Must be http: or https:, otherwise the constructor throws. |
timeout | 30000 | Milliseconds to wait for response headers before the request fails with status 408. |
headers | none | Extra headers merged into every request. |
Every request also sends X-Client-Type: @amadeus-protocol/sdk/1.8.0.
Instance methods
| Method | Description |
|---|---|
AmadeusSDK.getVersion() | Static. Returns the SDK version ('1.8.0'). |
sdk.getConfig() | Returns a copy of the resolved config (baseUrl, timeout, headers). |
sdk.setBaseUrl(url) | Points every module at another node. Throws AmadeusSDKError on an invalid URL. |
sdk.setHeaders(headers) | Merges headers into the existing ones. |
sdk.cancel() | Aborts every request in flight on this instance. Each aborted call rejects with AmadeusSDKError('Request cancelled', 0). |
Since 1.7.0 each request has its own abort controller, so parallel calls on one instance no longer cancel each other.
Low-level client
sdk.client is the AmadeusClient the modules share. Use it for endpoints the modules do not wrap:
| Method | Description |
|---|---|
client.get<T>(endpoint, params?) | GET. params become query parameters (undefined and null are dropped). |
client.post<T>(endpoint, data?) | POST. A Uint8Array, ArrayBuffer or Node.js Buffer is sent as application/octet-stream. Any other value is sent as JSON, so a string arrives as a quoted JSON string. |
client.postBinary(endpoint, data?) | POST that returns the raw body as a Uint8Array. Use it for binary answers such as /api/contract/get_prefix. |
Pass endpoints with the /api prefix ('/api/chain/stats'). The client resolves them against the origin of baseUrl.
How responses are handled
Most node answers carry an error field. The SDK reads it before returning:
error: 'ok'is removed, and you get the rest of the object. A successful response never haserror: 'ok', so do not test for it.error: 'not_found'throwsAmadeusSDKErrorwith status404and the message'Resource not found'. Public RPCs also set HTTP 404 on these answers, so in practice the message is'HTTP 404: not_found'.- Any other
errorvalue throwsAmadeusSDKError(<code>, 400). The code, for exampleinvalid_epochorinsufficient_funds, is the error message. - A non-2xx HTTP status throws
AmadeusSDKError('HTTP <status>: <message>', <status>).
See Error handling for the error object.
Chain API
sdk.chain reads entries (blocks), transactions and network statistics.
getTip()
Returns the latest entry as { entry: ChainEntry }.
const { entry } = await sdk.chain.getTip()
console.log('Height:', entry.header.height)
console.log('Slot:', entry.header.slot)
console.log('Signer:', entry.header.signer)
console.log('Hash:', entry.hash)
console.log('Transactions:', entry.tx_count)
Height, slot and signer live under entry.header, not at the top level. Headers carry no block timestamp. The node also sends seen_time_ms (Unix milliseconds when that node stored the entry) and in_main_chain, which the 1.8.0 type does not declare. Node 1.6.5 headers also carry root_chain as raw bytes rather than Base58, so it reads as garbled text; ignore it.
ChainEntry fields:
| Field | Type | Description |
|---|---|---|
header | ChainEntryHeader | slot, height, prev_slot, prev_hash, dr, vr, signer, and optionally root_tx, root_validator. Hashes and keys are Base58. |
hash | string | Entry hash (Base58). |
tx_count | number | Number of transactions in the entry. |
consensus | { score, finality_reached, mut_hash } (optional) | score is the share of validators that signed (0 to 1). finality_reached turns true once at least 67% have signed. |
mask, mask_size | optional | Validator participation mask. |
next_entry_hash_finality_reached | optional | Only on getByHash. |
txs_filtered | Transaction[] (optional) | Only on getByHash with filterOnFunction. |
getStats()
Returns { stats: ChainStats }.
const { stats } = await sdk.chain.getStats()
console.log('Tip height:', stats.height)
console.log('Finalized height:', stats.rooted_height)
console.log('Mempool size:', stats.tx_pool_size)
console.log('Circulating AMA:', stats.circulating)
console.log('Burned AMA:', stats.burned)
console.log('Staked AMA:', stats.total_locked)
console.log('Emission this epoch:', stats.emission_for_epoch)
| Field | Description |
|---|---|
height | Tip height. |
rooted_height | Latest finalized height. |
tip_hash, tip | Hash and full ChainEntry of the tip. |
tx_pool_size | Pending transactions in the node's mempool. |
cur_validator, next_validator | Validators scheduled for the current and next entry (Base58). |
emission_for_epoch | AMA emitted in the current epoch. It decreases from epoch to epoch, so read it here instead of hard-coding it. |
circulating, burned | Circulating and burned AMA. |
total_supply, total_supply_y3, total_supply_y30 | Supply emitted so far, and the projected supply at year 3 and year 30. |
total_locked | AMA locked in LockupVault stakes. |
supply_computed_at_height | Height the supply figures were computed at. |
diff_bits, pflops, txs_per_sec, segment_vr_hash | Mining difficulty, estimated compute, recent throughput, segment VRF hash. |
validators | Per-validator record keyed by Base58 public key (see below). |
total_supply, total_locked, supply_computed_at_height and validators are optional in the type. The node recomputes the supply figures every 6 hours, so supply_computed_at_height usually trails height. Each stats.validators[publicKey] entry has commission_bps, an optional commission_pending ({ bps, epoch }), sols, in_validator_set, staked (AMA) and staked_flat (atomic units).
The epoch is Math.floor(stats.height / 100_000), or call sdk.staking.getCurrentEpoch().
getByHeight(height) and getByHeightWithTxs(height)
Both return { entries: ChainEntry[] } for one height. getByHeightWithTxs also includes each entry's transactions. height must be a non-negative integer.
const { stats } = await sdk.chain.getStats()
const { entries } = await sdk.chain.getByHeight(stats.rooted_height)
for (const entry of entries) {
console.log(entry.hash, entry.header.height, entry.consensus?.finality_reached)
}
Nodes serve only recent entries. Default nodes prune entries older than 10 epochs (HISTORY_KEEP_EPOCHS), and on the public RPC an old height or entry hash fails with HTTP 520. Transaction lookups by hash still work for older entries.
getByHash(hash, filterOnFunction?)
Returns { entry: ChainEntry } for one entry hash. With filterOnFunction, the entry also carries txs_filtered: its transactions that call that function name.
const { entry } = await sdk.chain.getByHash('5Kd3N...', 'transfer')
console.log(entry.header.height, entry.txs_filtered?.length)
getTransaction(txid)
Returns one Transaction by hash. It calls the same endpoint as sdk.transaction.get.
getTransactionsInEntry(entryHash)
Returns { txs: Transaction[] } for one entry. sdk.transaction.getByEntry is the same call.
const { txs } = await sdk.chain.getTransactionsInEntry('5Kd3N...')
for (const tx of txs) {
console.log(tx.hash, tx.tx.action.contract, tx.tx.action.function, tx.receipt.success)
}
getTransactionEventsByAccount(account, filters?)
Returns the transactions an account sent or received, as { cursor, txs }. Since 1.8.0 the type matches the node: txs is Transaction[] and cursor is string | null.
import { AmadeusSDK, TransactionEventType } from '@amadeus-protocol/sdk'
const sdk = new AmadeusSDK({ baseUrl: 'https://mainnet-rpc.ama.one/api' })
const account = '5Kd3N...'
const firstPage = await sdk.chain.getTransactionEventsByAccount(account, {
type: TransactionEventType.SENT,
limit: 20,
sort: 'desc'
})
for (const tx of firstPage.txs) {
console.log(tx.hash, tx.metadata.tx_event, tx.tx.action.function, tx.receipt.success)
}
if (firstPage.cursor) {
const nextPage = await sdk.chain.getTransactionEventsByAccount(account, {
type: TransactionEventType.SENT,
limit: 20,
sort: 'desc',
cursor: firstPage.cursor
})
console.log('Next page:', nextPage.txs.length)
}
TransactionFilters:
| Field | Description |
|---|---|
type | TransactionEventType.SENT ('sent') or TransactionEventType.RECEIVED ('recv'). The TypeScript type does not accept the plain string. |
limit | Page size. Default 100, capped at 1,000. |
sort | 'asc' (default) or 'desc'. |
contract, contract_b58 | Contract name, or a Base58 contract address. |
function | Function name. |
cursor | The cursor from the previous page. Since 1.8.0 the SDK sends it as cursor_b58, the query parameter the node Base58-decodes. (1.7.0 sent it as cursor, which the node read as raw bytes.) |
cursor_b58 | Sent unchanged. When you set it, cursor is not renamed. |
offset | Accepted by the type. The node ignores it. |
Each item is a Transaction with metadata.tx_event set to 'sent' or 'recv'.
Paging needs type. Without it, the node merges sent and received transactions into one page and returns cursor: null. To walk an account's full history, page through SENT and RECEIVED separately.
getByFilter(filters?)
Queries transactions by signer, first argument, contract and function, as { cursor, txs }. All fields are optional.
const firstPage = await sdk.chain.getByFilter({
contract: 'Coin',
function: 'transfer',
signer: '5Kd3N...',
limit: 50,
sort: 'desc'
})
console.log(firstPage.txs.length)
if (firstPage.cursor) {
const nextPage = await sdk.chain.getByFilter({
contract: 'Coin',
function: 'transfer',
signer: '5Kd3N...',
limit: 50,
sort: 'desc',
cursor: firstPage.cursor
})
console.log(nextPage.txs.length)
}
| Field | Description |
|---|---|
signer | Base58 public key of the sender. |
arg0 | Base58 value of the first argument. For Coin.transfer this is the receiver. |
contract | Contract name, such as 'Coin'. |
contract_b58 | Base58 contract address. Use instead of contract. |
function | Function name. |
limit | Page size. Default 100, maximum 1,000. A larger value fails: the node raises limit_exceeded and the public RPC answers HTTP 520. |
sort | 'asc' (default) or 'desc'. |
cursor | The cursor from the previous page. It is null on the last page. |
A page can hold fewer than limit transactions and still return a cursor, and the next page may be empty. Keep paging until cursor is null.
To list an account's incoming transfers, filter on arg0. To list its outgoing ones, filter on signer.
getKpi()
Returns protocol-wide counters as { kpi: ChainKpi }. The node caches them for 10 seconds.
const { kpi } = await sdk.chain.getKpi()
console.log('Transactions:', kpi.total_tx)
console.log('Burned AMA:', kpi.ama_burned)
console.log('Active validator keys:', kpi.active_validator_keys)
| Field | Description |
|---|---|
total_tx | Transactions ever processed. |
ama_burned | AMA burned, rounded to two decimals. |
fees_paid | ama_burned × 2, because half of each fee is burned. |
active_validator_keys | Distinct keys that are validators for the next height or have a score this epoch. |
active_peers | Peers this node has handshaked with and sees online. |
block_time | Milliseconds per entry (500). |
uaw | Number of accounts with a stored token balance or NFT record. |
getMetricsBlock(height)
Deprecated since 1.8.0. It still calls /api/chain/metrics/block/{height}, for custom nodes that serve it, but node 1.6.5 and the public RPCs do not. A 404 is rethrown as a deprecation error: AmadeusSDKError with status 404 and the message chain.getMetricsBlock is deprecated: this node has no /api/chain/metrics/block route. A height that is not a non-negative safe integer throws a plain Error before any request. See Metrics API.
Wallet API
sdk.wallet reads balances. It has no transaction-history method: use chain.getTransactionEventsByAccount or chain.getByFilter.
getBalance(address, symbol?)
Returns { balance: { float, flat, symbol } }. symbol defaults to 'AMA'.
const { balance } = await sdk.wallet.getBalance('5Kd3N...')
console.log(`${balance.float} ${balance.symbol}`)
console.log('Atomic units:', balance.flat)
flat is in atomic units (1 AMA = 1,000,000,000). It is a JavaScript number, so values above 2^53 (about 9 million AMA) lose precision. Use float for display.
getAllBalances(address)
Returns { balances: TokenBalance[] }, an array with one { float, symbol, flat } per token the account holds.
const { balances } = await sdk.wallet.getAllBalances('5Kd3N...')
for (const token of balances) {
console.log(`${token.symbol}: ${token.float}`)
}
Transaction API
sdk.transaction submits signed transactions and looks them up. Build txPacked with TransactionBuilder (see 4. Transaction Building). Both submit methods accept the packed bytes or a Base58 string.
submit(txPacked)
Sends a transaction and returns { hash } once the node accepts it into its mempool. A rejected transaction throws with the validation code as the message.
import { AmadeusSDKError } from '@amadeus-protocol/sdk'
try {
const { hash } = await sdk.transaction.submit(txPacked)
console.log('Submitted:', hash)
} catch (error) {
if (error instanceof AmadeusSDKError) {
console.error('Rejected:', error.message, error.status)
}
}
Acceptance only means the transaction passed validation. Look it up later, or use submitAndWait, to learn whether it executed.
submitAndWait(txPacked, options?)
Sends a transaction and waits until it is in an entry. Returns { hash, metadata, receipt }.
const { hash, metadata, receipt } = await sdk.transaction.submitAndWait(txPacked, {
finalized: true
})
if (receipt.success) {
console.log('Executed in entry', metadata.entry_height, hash)
} else {
console.error('Included but failed:', receipt.result, receipt.logs)
}
| Option | Default | Description |
|---|---|---|
finalized | false | false returns once the transaction is in an entry (confirmed). true waits until metadata.status is 'finalized'. |
The call resolves for a transaction that was included but failed to execute, so check receipt.success. The node polls for about 6 seconds (60 tries, 100 ms apart). If the transaction is not found in that window, the node fails the request and the call throws.
get(txid)
Returns one Transaction.
const tx = await sdk.transaction.get('5Kd3N...')
console.log('Signer:', tx.tx.signer)
console.log('Call:', tx.tx.action.contract, tx.tx.action.function, tx.tx.action.args)
console.log('Status:', tx.metadata.status)
console.log('Success:', tx.receipt.success, tx.receipt.result)
| Field | Description |
|---|---|
hash, signature | Base58. |
tx | { signer, nonce, action: { op, contract, function, args, attached_symbol?, attached_amount? } }. Binary arguments come back as Base58. |
metadata | { entry_hash, entry_height, status? }. status is 'finalized' once the entry is final. |
tx.nonce | A number. Nonces are often larger than 2^53, so the parsed value can lose its last digits. |
receipt | { success, result, logs, exec_used }. Prefer it to the deprecated result field. |
A transaction still in the mempool comes back with metadata: { status: 'pending' } and no receipt, although the TypeScript type does not show this.
getByEntry(entryHash)
Returns { txs: Transaction[] } for one entry, the same as chain.getTransactionsInEntry.
const { txs } = await sdk.transaction.getByEntry('5Kd3N...')
console.log(txs.map((tx) => tx.hash))
Contract API
sdk.contract reads contract state and the AMA richlist. The prefix reads, decoders and proofs are covered in depth on Contract state.
get(key)
Reads one contract-state value by its raw key. Text values, such as balances, come back as strings. A missing key returns null.
import { AmadeusSDK, fromBase58 } from '@amadeus-protocol/sdk'
const sdk = new AmadeusSDK({ baseUrl: 'https://mainnet-rpc.ama.one/api' })
const encoder = new TextEncoder()
const account = fromBase58('5Kd3N...')
// account:{48-byte public key}:balance:AMA
const key = new Uint8Array([
...encoder.encode('account:'),
...account,
...encoder.encode(':balance:AMA')
])
const balanceFlat = await sdk.contract.get(key)
console.log(balanceFlat === null ? 'no balance' : BigInt(String(balanceFlat)))
Pass the key as bytes. The method also accepts a Base58 string, but sends it as JSON text, so the node looks up the wrong key and returns null.
getPrefixEntries(prefix)
Reads every key under a prefix and returns Array<[Uint8Array, Uint8Array]>, with keys stripped of the prefix. The node rejects prefixes shorter than 8 bytes. Details and samples: Contract state.
getPrefix(prefix)
Do not use it for /api/contract/get_prefix. That endpoint answers with a binary VecPack body, which getPrefix reads as text and returns as a garbled string. Use getPrefixEntries.
view(params)
Runs a deployed contract's function read-only against the current tip and returns { success, result, logs }. Since 1.8.0, a Base58 contract address is sent as its 48 raw bytes, so deployed contracts are reachable. Details and limits: Contract state.
getRichlist()
Returns the top 1,000 AMA holders as { richlist: RichlistEntry[] }, sorted by balance. The node recomputes it at most once an hour.
const { richlist } = await sdk.contract.getRichlist()
richlist.slice(0, 10).forEach((holder, index) => {
console.log(`#${index + 1} ${holder.pk} ${holder.float} ${holder.symbol}`)
})
Each entry is { pk, symbol, flat, float }. float is truncated to whole AMA. The rank is the array position.
validateBytecode(bytecode)
Deprecated since 1.8.0. The node has no /api/contract/validate_bytecode route, so the method sends no request and always throws a deprecation error: AmadeusSDKError with status 404 and the message contract.validateBytecode is deprecated: the node has no /api/contract/validate_bytecode route. Contracts are RISC-V programs, checked when they are deployed. For building and testing them, see the contract samples in the node repository.
Epoch API
sdk.epoch reads validator scores and emission settings for the current epoch.
getScore(publicKey?)
Without an argument, returns every validator's score this epoch as [publicKey, score][]. With a public key, returns { score }. The return type is the union EpochScore, so prefer the two helpers below.
getAllScores()
Returns Promise<[string, number][]>, the [publicKey, score] pairs.
const scores = await sdk.epoch.getAllScores()
for (const [publicKey, score] of scores) {
console.log(publicKey, score)
}
getValidatorScore(publicKey)
Returns Promise<number>, one validator's score.
const score = await sdk.epoch.getValidatorScore('5Kd3N...')
getTopValidators(limit?)
Returns the limit highest [publicKey, score] pairs, highest first. limit defaults to 10.
const top = await sdk.epoch.getTopValidators(5)
top.forEach(([publicKey, score], index) => console.log(index + 1, publicKey, score))
getEmissionAddress(publicKey)
Returns { emission_address } for a validator: the Base58 address that receives its emissions, or null if none is set. publicKey is required.
const { emission_address } = await sdk.epoch.getEmissionAddress('5Kd3N...')
console.log(emission_address ?? 'not set')
getSolInEpoch(epoch, solHash)
Checks whether a solution was submitted in the current epoch. It resolves to {} when the solution is found and throws otherwise.
import { AmadeusSDK, AmadeusSDKError } from '@amadeus-protocol/sdk'
const sdk = new AmadeusSDK({ baseUrl: 'https://mainnet-rpc.ama.one/api' })
const currentEpoch = await sdk.staking.getCurrentEpoch()
try {
await sdk.epoch.getSolInEpoch(currentEpoch, '5Kd3N...')
console.log('Solution found')
} catch (error) {
if (error instanceof AmadeusSDKError) {
console.log(error.message) // 'sol_not_found' or 'invalid_epoch'
}
}
- Only the current epoch is accepted. Any other epoch throws
invalid_epoch. - The node checks a bloom filter, so a found result means "probably submitted" and can be a false positive.
- Pass
solHashas a Base58 string. AUint8Arrayis converted withtoString()into a comma-separated list, which the node cannot read.
Peer API
sdk.peer lists the nodes and validators this node knows. Every method returns a wrapper object, not a bare array.
| Method | Returns | Description |
|---|---|---|
getNodes() | { nodes: PeerInfo[] } | Peers this node has handshaked with and sees online. |
getTrainers() | { trainers: PeerInfo[] } | The validators among those peers. |
getRemovedTrainers() | { removed_trainers: PeerInfo[] } | Validators that were in the set at the start of this epoch and are not in it now. The node sends Base58 public keys, not PeerInfo objects. |
getANRs() | { anrs: ANRInfo[] } | Up to 100 signed node records (ANRs), in random order. |
getANRValidators() | { anrs: ANRInfo[] } | ANR records of validators. |
getANRByPk(publicKey) | { anr: ANRInfo | null } | One node's ANR record. anr is null for a key the node does not know (typed since 1.8.0). |
const { nodes } = await sdk.peer.getNodes()
for (const node of nodes) {
console.log(node.pk, node.version, node.temporal_height, node.rooted_height, node.is_trainer)
}
const { anrs } = await sdk.peer.getANRValidators()
console.log(anrs.map((record) => `${record.ip4}:${record.port}`))
const { anr } = await sdk.peer.getANRByPk('5Kd3N...')
console.log(anr?.version, anr?.handshaked)
PeerInfo has pk and version, plus optional latency, temporal_height, temporal_hash, rooted_height, rooted_hash, is_trainer, slot_speed, online and in_slot. The node sends is_trainer: null for peers that are not validators, and slot_speed only from getTrainers. ANRInfo has pk, pop, signature, ip4, port, handshaked, isChainPop, version and ts.
Proof API
sdk.proof returns proofs you can check against data the validators signed. The Proof tag page explains how the proof types fit together.
getContractStateProof(key)
Fetches an HB-SMT proof for a contract-state key, taken at the current tip, as a ContractStateProof ({ entry_height, entry_hash, root_contractstate, proofs }). Since 1.8.0 the type matches the node. Fields and a sample: Contract state proofs.
The value argument (getContractStateProof(key, value)) is deprecated since 1.8.0. The node no longer verifies a value, so the call throws a deprecation error without sending a request. Compare proofs[0].proof.terminus.value_hash yourself.
getValidatorRecord(height)
New in 1.8.0. Returns the validator-set record stored for height, with an HB-SMT proof against the contract-state root of block height - 1, the block that wrote it. Calls /api/proof/validator_record/{height}.
const record = await sdk.proof.getValidatorRecord(90500000)
console.log(record.entry_height, record.entry_hash) // the block that wrote the record
console.log(record.key, record.value) // Base58
console.log(record.proof.root, record.proof.siblings.length)
ValidatorRecordProof has entry_height (height - 1), entry_hash, key, value and proof (an HbsmtProof: { root, siblings, terminus }, with Base58 hashes). Records exist only at heights where the validator set was written, such as epoch starts (90500000). Any other height throws AmadeusSDKError with status 404. To trust the root, compare it with the signed consensus from /api/chain/consensus/{entry_height}.
getBlockProof(height, options?)
New in 1.8.0. Returns an MMR inclusion proof that the canonical block at height is committed in the chain. Calls /api/proof/block/{height}.
// A recent rooted block against the latest rooted MMR
const { stats } = await sdk.chain.getStats()
const latest = await sdk.proof.getBlockProof(stats.rooted_height - 100)
// An older block against the MMR committed by the header at height 90540000
const pinned = await sdk.proof.getBlockProof(90500000, { atHeight: 90540000 })
console.log(pinned.block_hash, pinned.root_chain, pinned.siblings.length, pinned.other_peaks.length)
BlockProof field | Description |
|---|---|
height, block_hash | The proven block. |
claim | Packed block claim (Base58), or null below the claim fork height. |
at_height, at_hash | The MMR state proven against. |
chain_id, root_chain | Chain id and MMR root. Trust root_chain only from a header whose signature you verified. |
peak_pos, siblings, other_peaks | The MMR path (Base58 hashes). |
options.atHeight defaults to the rooted tip. The node refuses a path that is too long with proof_too_costly: on mainnet today, a block more than a few tens of thousands of heights below atHeight (or the rooted tip) gets it, so prove an older block with an atHeight shortly after it. Node errors such as target_not_rooted, commitment_not_rooted, height_not_in_main_chain, snapshot_unavailable, pruned_history and proof_too_costly throw as AmadeusSDKError with status 400 and the code as the message.
getValidators(entryHash)
Deprecated since 1.8.0. The node has no /api/proof/validators/{hash} route, so the method sends no request and always throws a deprecation error: AmadeusSDKError with status 404. Use getValidatorRecord(height) for the proven validator set.
Staking API
sdk.staking reads LockupVault staking positions: vaults, totals, APY and validator commissions. Its amounts are bigint. See Staking for the full reference.
| Method | Returns |
|---|---|
getPosition(publicKey, options?) | The account's vaults plus a StakingSummary and the epoch used. |
getVaults(publicKey, options?) | LockupVaultEntry[] for one account. |
getAllVaults(options?) | Every vault on the chain. |
getValidatorCommissions(options?) | Record<string, ValidatorCommission> keyed by validator. |
getCurrentEpoch() | The epoch number at the tip. |
const position = await sdk.staking.getPosition('5Kd3N...')
console.log(`${position.totalStaked} AMA in ${position.vaultCount} vaults`)
Metrics API
MetricsAPI reads daily activity from a separate analytics service, not from a node. There is no public deployment, so you must pass that service's origin yourself. It is not part of AmadeusSDK.
import { MetricsAPI } from '@amadeus-protocol/sdk'
const metrics = new MetricsAPI({ baseUrl: 'https://YOUR-METRICS-ORIGIN' })
const report = await metrics.getDaily('2026-11-01', '2026-11-08')
for (const day of report.days) {
if (day.status === 'complete') {
console.log(day.date, day.transactions, day.unique_active_addresses)
} else {
console.log(day.date, 'incomplete:', day.reasons)
}
}
getDaily(start, end) takes UTC dates as YYYY-MM-DD. end is exclusive and the range must cover 1 to 31 days, otherwise the call throws before sending anything. Each day has blocks, transactions, successful_transactions, unique_active_addresses and new_addresses. Counts the service could not compute are null, never 0. Active addresses count signers of successful transactions, bots included.
Error handling
Module methods throw AmadeusSDKError:
import { AmadeusSDK, AmadeusSDKError } from '@amadeus-protocol/sdk'
const sdk = new AmadeusSDK({ baseUrl: 'https://mainnet-rpc.ama.one/api' })
try {
await sdk.chain.getByHash('5Kd3N...')
} catch (error) {
if (error instanceof AmadeusSDKError) {
console.error(error.message) // e.g. 'HTTP 404: not_found'
console.error(error.status) // e.g. 404
console.error(error.response) // the parsed error body, when there is one
}
}
status | Cause |
|---|---|
undefined | An input check failed before any request was sent, or you passed value to getContractStateProof. |
400 | The node answered with an error code. message is the code. |
404 | not_found, a route the node does not serve, or a deprecated method (validateBytecode, getValidators, getMetricsBlock). |
408 | The request timed out (timeout in the config). |
0 | Network failure, or the request was cancelled with sdk.cancel(). |
| other | The HTTP status of a failed request. |
Input checks run before any request is sent. A key or hash with characters outside the Base58 alphabet, or a negative height, throws at once without reaching the node. The checks test the alphabet only, not the length. A few helpers throw a plain Error instead: getMetricsBlock on a bad height, getSolInEpoch on an empty hash and getValidatorScore on an unexpected answer.
Next steps
- Contract state: prefix reads, decoders, view calls and proofs
- Staking: LockupVault positions and amounts
- 6. Utilities: encoding, conversion and crypto helpers
- 7. Examples: complete programs
- HTTP API: the raw endpoints behind these modules