Skip to main content

Smart contracts

How Amadeus smart contracts work. They are RISC-V (RV64IM) programs written in Rust that run on testnet today. This page covers the execution model, the amadeus_contract SDK, host calls, attachments, gas and limits.

Amadeus contracts are RISC-V ELF binaries: RV64IM plus the Zba and Zbb extensions, with no atomics, no compressed instructions and no floating-point hardware. Floats are emulated in software and are deterministic. You write them in no_std Rust against a small SDK, the amadeus_contract crate, and compile them with nightly Rust. The node runs them in its own interpreter. Nothing is compiled on the node: the ELF is validated when it is deployed and predecoded the first time it is called.

There is no WASM runtime. Older pages and SDK comments that mention WASM bytecode are out of date.

:::caution Testnet only Contracts execute on testnet only for now. Contract.deploy does not exist on mainnet (invalid_bic_action), so a call to any mainnet account fails with account_has_no_bytecode. The node returns riscv_noop for an account that holds bytecode on a network that does not execute contracts. Build and test on a local testnet. Networks lists what differs between mainnet and testnet. :::

The source of truth is the node repository:

ResourceLink
Getting startedhttps://github.com/amadeusprotocol/node/blob/main/contract_samples/GETTINGSTARTED.md
Local testing commandshttps://github.com/amadeusprotocol/node/blob/main/contract_samples/README.md
Rust SDK and sampleshttps://github.com/amadeusprotocol/node/tree/main/contract_samples/riscv
Contract VM and host calls (source)https://github.com/amadeusprotocol/node/tree/main/ex/native/rdb/src/consensus/riscv
Built-in contracts (source)https://github.com/amadeusprotocol/node/tree/main/ex/native/rdb/src/consensus/bic
VM determinism ruleshttps://github.com/amadeusprotocol/node/blob/main/ex/native/rdb/src/consensus/riscv/DETERMINISM.md

To build, deploy and call your first contract, go to Build, test and deploy.

Execution model​

A contract lives in an account. Contract.deploy stores the ELF in the signer's own account (account:<signer>:attribute:bytecode). The contract's address is therefore the public key that deployed it, and you call it by sending a transaction to those 48 bytes. Deploying again from the same key replaces the code and leaves the contract's existing storage in place.

One entry point, many functions. Each call runs the ELF from its entry point. The entry! macro reads the called function name and passes it to your dispatch function, which matches on it:

#![no_std]
#![no_main]

use amadeus_contract as sdk;

fn dispatch(function: &[u8]) {
match function {
b"inc" => {
let total = sdk::kv_increment(b"count", 1);
let mut buffer = [0u8; 48];
sdk::ret(sdk::itoa(total, &mut buffer));
}
_ => sdk::abort(b"unknown function"),
}
}

sdk::entry!(dispatch);

Arguments and results are bytes. A call carries up to 16 arguments, each a byte string. Numbers are passed as decimal strings, and public keys as their 48 raw bytes. ret ends the call successfully with a return value of at most 128 bytes. If the function returns without calling ret, the call also succeeds, with an empty result.

Failure reverts everything. abort(msg), exit with a non-zero code, a trap or running out of gas reverts every state change, attachment and nested call made by the transaction. The receipt's result is then abort, trap or exec_insufficient_exec_budget. An abort message or the trap reason goes into the receipt's logs.

Storage is a per-contract key-value store. A key k written by a contract is stored as account:<contract>:storage:k, so contracts cannot write each other's state. Values are raw bytes. kv_increment treats the value as a signed decimal string.

Contracts can call other contracts. call invokes another contract, or a built-in such as Coin or Nft, and returns its result. Inside the nested call, the caller is the calling contract. This is how a contract spends its own balance: the deposit sample calls Coin.transfer to pay out. Calls can nest up to 16 deep.

Views are read-only calls. A view runs a contract function against the current chain tip without a transaction. It has the same exec cap as a transaction, any write fails with exec_cannot_write_during_view, and the caller is the public key you pass, or 48 zero bytes if you pass none. The HTTP view endpoints replace every byte outside printable ASCII, and the backtick, with ? in result and logs, so view functions should return text.

The amadeus_contract SDK​

The SDK is the library in contract_samples/riscv/src/lib.rs (crate amadeus_contract). It contains the host-call wrappers, a bump allocator with a 256 KiB heap, a panic handler that aborts, a no_std vecpak codec (src/vecpak.rs) and the entry! macro. It is not published to crates.io. You build contracts inside that crate, as files in its examples/ directory (see Build, test and deploy).

AreaFunctions
Entry and flowentry!(dispatch), function(), arg(index) -> Option<Vec<u8>>, arg_count(), ret(value) -> !, abort(message) -> !, exit(code) -> !, log(line)
Storagekv_get(key) -> Option<Vec<u8>>, kv_put(key, value), kv_delete(key), kv_exists(key) -> bool, kv_increment(key, delta: i128) -> i128, kv_get_next(prefix, key) and kv_get_prev(prefix, key) -> Option<(key, value)>
Contextaccount_caller(), account_current(), seed(), attachments() -> Vec<Asset>, env(field), env_u64(field), the field::* constants
Calls and assetscall(contract, function, args, attachments) -> Vec<u8>, Asset::coin(symbol, amount), Asset::nft(collection, token, amount), encode_attachments(assets), BURN_ADDRESS
Hashing and signaturessha256, blake3, keccak256, bls_verify, bls_aggregate_verify, secp256k1_recover, secp256k1_verify, ed25519_verify
Integersitoa(value: i128, &mut [u8; 48]) -> &[u8], parse_int(bytes) -> Option<i128>, atoi(bytes) -> i128 (aborts with invalid integer on bad input)
Encodingvecpak::Term (Nil, Bool, Int(i128), Binary, List, Map), vecpak::encode, vecpak::decode
Rawsyscall(id, [u64; 7]), the id::* constants, NOT_FOUND

The allocator reclaims memory only when you free the most recent allocation, so a contract that allocates in a loop uses up the 256 KiB heap. When the heap runs out, the allocation fails and the call aborts through the panic handler.

seed() returns a 32-byte per-call value. The node derives it from the entry's VRF output, the transaction hash, the transaction's index in the entry and a call counter. The nft and rpg samples use it for dice rolls.

Host calls​

Contracts talk to the node through ecall: the call id goes in a7, arguments in a0 to a6, and the result comes back in a0. Buffers are (pointer, length) pairs in contract memory. Outputs are written to a buffer the caller provides, and the call returns the full length; the copy is truncated to the buffer's size. NOT_FOUND is u64::MAX. A bad pointer or a buffer over 1 MiB fails the call.

idCallArgumentsReturns
1logptr, len
2returnptr, len (max 128 bytes)stops, success
3call contractargs table (contract, function and up to 16 args), attachments ptr, len (0 for none), out, capresult length
4kv_putkey, klen, value, vlen
5kv_incrementkey, klen, delta (decimal string), dlen, out, capnew value length
6kv_deletekey, klen
7kv_getkey, klen, out, capvalue length or NOT_FOUND
8kv_existskey, klen0 / 1
9 / 10kv_get_prev / kv_get_nextprefix, plen, key, klen, out, cap[u32 klen][key][u32 vlen][value] length or NOT_FOUND
11envfield, out, caplength
12arg_countcount
13argindex, out, caplength or NOT_FOUND
14functionout, caplength
15abortmsg ptr, lenstops, reverts (abort), message logged
30 / 31 / 32sha256 / blake3 / keccak256ptr, len, out (32 bytes)
50bls_verifypk (48), sig (96), msg, mlen, dst, dlen0 / 1
51bls_aggregate_verifypks (n * 48), n, sig (96), msg, mlen, dst, dlen0 / 1
52secp256k1_recoverhash (32), sig (64), recid, out (65)65 or NOT_FOUND
53secp256k1_verifypk, pklen (33/65), hash (32), sig (64)0 / 1
54ed25519_verifypk (32), sig (64), msg, mlen (strict: rejects small-order keys)0 / 1
93exitcode0 succeeds, anything else reverts (abort)

The call table for id 3 is [u64 count][(u64 ptr, u64 len) * count], with the contract and the function as the first two entries.

env fields:

GroupFields
Call0 seed
Entry10 slot, 11 height, 12 epoch (u64 LE), 13 signer, 14 prev hash, 15 vr, 16 dr
Transaction30 nonce (u64 LE), 31 signer, 32 hash
Accounts50 current (this contract), 51 caller, 52 origin (the transaction signer)
Attachments70 the canonical vecpak map, empty if none

Attachments​

A call can carry coins and NFTs. They move from the caller to the called contract before it runs. Attachments are one vecpak map: a coin symbol maps to a positive integer amount in base units, and an NFT collection maps to a map of token to amount. Names are 1 to 32 ASCII letters or digits.

Each entry is checked like a built-in transfer: the coin or collection and token must exist, and the caller must hold enough. Paused coins are refused, and so are soulbound coins, collections and tokens. If any entry fails, the whole call reverts. Attaching to a built-in (Coin, Nft, ...) fails with attachments_not_allowed_on_builtin. Attaching to an account without a contract fails like any call to it (account_has_no_bytecode).

Inside the contract, attachments() returns what was attached as Asset::Coin { symbol, amount } and Asset::Nft { collection, token, amount }. To attach assets to a nested call, pass them to call(.., &[sdk::Asset::coin(b"AMA", 5)]).

Decoding attachments costs 3 exec units per byte, and each transfer pays the normal storage costs (about 65,000 to 75,000 units). A transaction fits roughly 25 attachments.

Attached coins land in the contract's account, which is the deploying key's account. That key can still sign ordinary transfers from it.

Gas and fees​

Every transaction locks a budget of 0.01 AMA plus its optional attached_gas, both in base units of AMA (1 AMA = 1,000,000,000). That budget covers three things:

  • The history charge for the transaction's own bytes: 1,111 units per byte.
  • A fixed exec cap, TX_EXEC_LOCK = 2,000,000 units (0.002 AMA). This bounds run time no matter how much gas is attached.
  • Storage, which gets the rest of the budget.

attached_gas therefore buys only storage and history. Unused budget is refunded. What is spent is split like every fee: 50% to the validator that produced the entry and 50% burned. The receipt's exec_used is the total charged, in base units.

A transaction is rejected (tx_exceeds_budget) if its history charge plus the exec cap exceed its budget. That is why large transactions such as deploys must attach gas.

Execution. Instructions cost 1 gas each, except loads and stores (2), mul* (3), div*/rem* (10) and jalr (4). Gas is charged per basic block, and 2 gas = 1 exec unit. The exec cap of 2,000,000 units is therefore 4,000,000 gas, about 10 ms of worst-case code on a Ryzen 7950X.

Per call. Every call pays for setup: 6 units per code word and 140 units per 4 KiB memory page. Every host call costs 10 units, plus 1 unit per 32 bytes copied between contract memory and the host, plus its own cost:

Host operationCost (exec units)
Contract call2,000
sha25610 per 64 B
keccak256100 per 136 B
blake345 per KiB
bls_verify250,000
bls_aggregate_verify+64,000 per key
secp256k1_recover / verify50,000 / 25,000
ed25519_verify10,000

Storage. Storage costs the same as for built-in contracts:

  • A read costs 5,000 units plus 1 per key and value byte.
  • A write costs 25,000 units plus 1 per byte.
  • New state also pays from the storage budget: 5,555 units per byte, plus 711,040 per new key.
  • Log lines, abort messages and the return value go into the receipt and pay the history rate (1,111 per byte) from the storage budget.

Deploying. A deploy is a normal transaction, and the ELF can be at most 512 KiB. Validating it costs 1 exec unit per byte, and writing it costs another 1 per byte. On top of that come the state and history charges of 5,555 + 1,111 units per byte, paid from attached_gas. For a 512 KiB ELF that is about 3.5 AMA. Testnet.deploy attaches enough for the bytecode plus 0.1 AMA for the init call.

For reference, a vecpak decode plus encode inside the VM costs about 8,500 units for a 211-byte map and about 148,000 for a 3 KiB list. All costs are constants in protocol.rs.

Limits​

LimitValue
ELF size512 KiB, at most 16 PT_LOAD segments, loaded below 16 MiB
Arguments per call16 (1 MiB total for a nested call)
Return value128 bytes
Call depth16
Storage key512 bytes including the account:<contract>:storage: prefix
Storage value1 MiB
Logs4,096 bytes per line, 16 KiB and 128 lines per transaction
Host-call buffer1 MiB
SDK heap256 KiB

Determinism​

Every validator must get the same result, gas use, writes and logs for the same call. The VM accepts only RV64IM plus Zba and Zbb. Anything else is an invalid instruction and traps: floating point, atomics, fence.i, ebreak, and compressed or reserved encodings. Nothing in the VM reads time, randomness or thread identity. The full rules are in DETERMINISM.md.

Next steps​