Contract state
Read contract state with @amadeus-protocol/sdk 1.8.0: single keys, paged prefix reads, page decoders, value parsers, view calls and state proofs.
Every balance, vault and contract variable on Amadeus lives in one key-value store, the contract state. This page shows how to read it with the SDK, and what the node actually sends back. Samples assume the sdk instance from API Modules.
Keys are bytes
State keys are raw byte strings. Wherever a key contains a public key, it holds the 48 raw bytes, not the Base58 text. Some keys the SDK reads:
| Key | Holds |
|---|---|
account:{pk}:balance:{symbol} | An account's balance of one token, in atomic units, as decimal text. |
bic:lockup_vault:vault:{owner}:{index} | One staking vault (see Staking). |
bic:lockup_vault:validator_commission:{validator} | A validator's commission record. |
Build keys by concatenating bytes:
import { fromBase58 } from '@amadeus-protocol/sdk'
const encoder = new TextEncoder()
const account = fromBase58('5Kd3N...')
// account:{48-byte public key}:balance:
const balancesPrefix = new Uint8Array([
...encoder.encode('account:'),
...account,
...encoder.encode(':balance:')
])
Choosing a read
| You want | Use |
|---|---|
| One value whose full key you know | sdk.contract.get(key) |
| Every key under a prefix | sdk.contract.getPrefixEntries(prefix) |
| Prefix pages through your own HTTP layer | readAllPrefixPages, prefixPagePath, decodeContractStatePage |
| A contract function's answer | sdk.contract.view(params) |
| A Merkle proof for a key | sdk.proof.getContractStateProof(key) |
| A proven validator-set record | sdk.proof.getValidatorRecord(height) (API Modules) |
| An account's staking position | sdk.staking.getPosition(publicKey) (Staking) |
contract.get(key)
Reads one value. Text values come back as strings, and 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 balanceKey = new Uint8Array([
...encoder.encode('account:'),
...fromBase58('5Kd3N...'),
...encoder.encode(':balance:AMA')
])
const value = await sdk.contract.get(balanceKey)
console.log(value === null ? 0n : BigInt(String(value)))
Pass the key as a Uint8Array. A Base58 string passes validation but is sent as JSON text, so the node looks up a different key and returns null.
getPrefixEntries(prefix)
Signature: getPrefixEntries(key: Uint8Array | string): Promise<Array<[Uint8Array, Uint8Array]>>
Returns every [key, value] pair under a prefix, as raw bytes:
- Keys come back with the prefix removed. A query for
account:{pk}:balance:returns keys such asAMA. - A string prefix is sent as its UTF-8 bytes, not decoded from Base58. Pass anything that contains a public key as bytes.
- It follows the node's pages until the last one (see Paged answers). It throws
AmadeusSDKErrorpast 50 pages (about 50,000 rows), on a repeated cursor, or on a page that does not decode. It never returns a cut-off list. - An empty prefix throws before any request. The node rejects prefixes shorter than 8 bytes with
HTTP 400({"error":"prefix_too_short","min":8}). - A prefix with no keys returns
[].
List every token balance of an account:
import { AmadeusSDK, fromBase58, parseStateString } from '@amadeus-protocol/sdk'
const sdk = new AmadeusSDK({ baseUrl: 'https://mainnet-rpc.ama.one/api' })
const encoder = new TextEncoder()
const prefix = new Uint8Array([
...encoder.encode('account:'),
...fromBase58('5Kd3N...'),
...encoder.encode(':balance:')
])
const rows = await sdk.contract.getPrefixEntries(prefix)
for (const [symbolBytes, valueBytes] of rows) {
const symbol = new TextDecoder().decode(symbolBytes)
const flat = BigInt(parseStateString(valueBytes) ?? '0')
console.log(symbol, flat)
}
Do not use sdk.contract.getPrefix() for this. It reads the binary answer as text and returns a garbled string.
Paged answers
POST /api/contract/get_prefix takes the raw prefix bytes as its body and answers with a VecPack map:
| Field | Description |
|---|---|
rows | Map from key (prefix removed) to value. An empty list when nothing matched. |
cursor | Base58 key to resume after, or nil on the last page. |
A page holds at most 1,000 rows, and about 1 MiB of keys and values. Request the next page with ?cursor=<cursor> and the same body. Nodes released before paging answered with a bare row map or an empty list; the SDK decoders read both.
Reading pages yourself
Use these helpers when you send requests through your own HTTP layer.
| Function | Description |
|---|---|
readAllPrefixPages(fetchPage, options?) | Calls fetchPage(cursor) from null until the cursor is null and returns every pair. options.maxPages defaults to 50. Throws past that limit, on a repeated cursor or on an undecodable page. Errors from fetchPage pass through. |
prefixPagePath(cursor, endpoint?) | Returns endpoint plus ?cursor=... when cursor is set. endpoint defaults to '/contract/get_prefix', for appending to a base URL that ends in /api. |
decodeContractStatePage(bytes) | Decodes one page to { entries, cursor }. Throws on a body that is not a prefix answer. |
decodeContractState(bytes) | Decodes one page and returns only its entries. It drops the cursor, so a prefix with more than one page comes back incomplete. |
decodeContractStateToBase64(bytes) | Like decodeContractState, with keys and values as Base64 strings and empty pairs removed. One page only. |
With fetch:
import { readAllPrefixPages, prefixPagePath } from '@amadeus-protocol/sdk'
const apiBase = 'https://mainnet-rpc.ama.one/api'
const prefix = new TextEncoder().encode('bic:lockup_vault:vault:')
const rows = await readAllPrefixPages(async (cursor) => {
const response = await fetch(apiBase + prefixPagePath(cursor), { method: 'POST', body: prefix })
if (!response.ok) throw new Error(`get_prefix failed: ${response.status}`)
return response.arrayBuffer()
})
console.log('Vaults on chain:', rows.length)
With the SDK's own client, which needs the full /api/... path:
import { AmadeusSDK, readAllPrefixPages, prefixPagePath } from '@amadeus-protocol/sdk'
const sdk = new AmadeusSDK({ baseUrl: 'https://mainnet-rpc.ama.one/api' })
const prefix = new TextEncoder().encode('bic:lockup_vault:vault:')
const rows = await readAllPrefixPages(
(cursor) => sdk.client.postBinary(prefixPagePath(cursor, '/api/contract/get_prefix'), prefix),
{ maxPages: 10 }
)
One page at a time:
import { decodeContractStatePage, prefixPagePath } from '@amadeus-protocol/sdk'
const response = await fetch('https://mainnet-rpc.ama.one/api' + prefixPagePath(null), {
method: 'POST',
body: new TextEncoder().encode('bic:lockup_vault:vault:')
})
const { entries, cursor } = decodeContractStatePage(await response.arrayBuffer())
console.log(entries.length, cursor === null ? 'last page' : `next: ${cursor}`)
Parsing values
| Function | Input | Returns |
|---|---|---|
parseStateString(value) | string, number, Uint8Array, null or undefined | The value as text (bytes are decoded as UTF-8), or null for null/undefined. |
parseStateNumber(value) | Same | A number. Bytes are read as decimal text first, then as a little-endian integer. Returns 0 for null, undefined and input it cannot read. |
import { parseStateNumber, parseStateString } from '@amadeus-protocol/sdk'
const valueBytes = new TextEncoder().encode('42')
parseStateNumber(valueBytes) // 42
parseStateString(valueBytes) // '42'
BigInt(parseStateString(valueBytes) ?? '0') // 42n
parseStateNumber returns a JavaScript number. Balances are stored in atomic units (1 AMA = 1,000,000,000), so any amount above 2^53 atomic units (about 9 million AMA) loses its last digits. For amounts, use BigInt(parseStateString(value) ?? '0').
contract.view(params)
Signature: view(params: ContractViewParams): Promise<ContractViewResponse>
Runs a contract function against the current tip in read-only mode. Nothing is written and no transaction is created. The node runs the call, discards any changes and returns:
| Field | Type | Description |
|---|---|---|
success | boolean | false when the call failed. |
result | string | The return value, or the error code when success is false. |
logs | string[] | Log lines the contract emitted. |
ContractViewParams:
| Field | Description |
|---|---|
contract | The deployed contract's address: a Base58 string or its 48 raw bytes. Since 1.8.0 a Base58 address is decoded and sent as the 48 bytes, which is how the node finds deployed code. Any other string, such as 'Coin', is sent as text. |
function | Function name. |
args | Optional arguments. Pass byte values as Uint8Array. Defaults to []. |
pk | Optional caller public key as 48 raw bytes. Defaults to 48 zero bytes. |
Deployed RISC-V contracts run on testnet only today, so point the SDK at testnet:
import { AmadeusSDK } from '@amadeus-protocol/sdk'
const testnet = new AmadeusSDK({ baseUrl: 'https://testnet-rpc.ama.one/api' })
const { success, result, logs } = await testnet.contract.view({
contract: '<deployed contract address, Base58>',
function: 'get',
args: []
})
console.log(success, result, logs)
Limits in SDK 1.8.0 and node 1.6.5:
- Built-in contracts (
Coin,LockupVault,Epochand the rest) only have functions that change state, so a view call on one never returns data. An unknown function answers{ success: false, result: 'invalid_bic_action' }, and a real action fails on its first write (exec_cannot_write_during_view) or on its arguments (invalid_args). A call that writes nothing returns'ok'. Read their state withgetorgetPrefixEntriesinstead. - SDK 1.7.0 and earlier sent a Base58 address as text, so the node treated it as the name of a built-in contract and answered
invalid_bic_action. Upgrade to 1.8.0.
proof.getContractStateProof(key)
Returns an HB-SMT proof for a state key against the contract-state root at the current tip. Pass the key as bytes, or as a string that is already Base58. Since 1.8.0 the ContractStateProof type matches the node's answer:
| Field | Description |
|---|---|
entry_height, entry_hash | The entry whose state root the proof is for. |
root_contractstate | That entry's contract-state root (Base58). |
proofs | One ContractStateKeyProof per key: { key, namespace, proof }. |
proofs[].key | The key, Base58. |
proofs[].namespace | Base58 of the key's namespace (account:{pk} for account keys, coin or bic), or null for other keys. |
proofs[].proof | An HbsmtProof: { root, siblings, terminus }. siblings is a list of Base58 hashes. terminus is 'empty' or { path, identity_hash, value_hash }. |
import { AmadeusSDK, fromBase58 } from '@amadeus-protocol/sdk'
const sdk = new AmadeusSDK({ baseUrl: 'https://mainnet-rpc.ama.one/api' })
const encoder = new TextEncoder()
const key = new Uint8Array([
...encoder.encode('account:'),
...fromBase58('5Kd3N...'),
...encoder.encode(':balance:AMA')
])
const answer = await sdk.proof.getContractStateProof(key)
const [item] = answer.proofs
console.log('Root at height', answer.entry_height, answer.root_contractstate)
console.log('Siblings:', item?.proof.siblings.length)
console.log(item?.proof.terminus === 'empty' ? 'key not set' : item?.proof.terminus.value_hash)
- The node returns a proof for a key that does not exist too. That is an exclusion proof, with
terminus: 'empty'. - The
valueargument is deprecated since 1.8.0: the node no longer verifies a value, sogetContractStateProof(key, value)throws a deprecation error without sending a request. Compareterminus.value_hashyourself. - To trust the root, compare it with the signed consensus from
/api/chain/consensus/{entry_height}. The proof is taken at the tip, so that height may not be rooted yet.
For the validator-set record and block inclusion proofs, see Proof API.
Related pages
- 5. API Modules: the full module reference
- Staking: LockupVault positions, built on
getPrefixEntries - 6. Utilities: Base58 and other encoding helpers
- Contract HTTP API: the raw endpoints