Skip to main content

Build, test and deploy a contract

Install the RISC-V toolchain, build the sample contracts, write your own, run a local testnet, deploy and call contracts from the node REPL, and read or call them from TypeScript and HTTP.

This guide follows the node repository's contract getting-started guide and local testing commands. For how contracts execute, the SDK, host calls and gas, see the smart contracts overview.

:::caution Testnet only Contracts run on testnet only. The upstream guide has not finished the public-testnet deploy flow yet, so deploy on a local testnet. Never use mainnet keys on a testnet. :::

Install the toolchain​

Contracts are written in Rust and compiled to RISC-V. Install nightly Rust with the standard library sources:

rustup toolchain install nightly --component rust-src

If you already have nightly, add the sources with rustup +nightly component add rust-src.

Build the sample contracts​

git clone https://github.com/amadeusprotocol/node.git
cd node/contract_samples/riscv
./build.sh

build.sh compiles every file in examples/ for the riscv64im-zba-zbb-none target and copies each one to out/<name>.elf:

cargo +nightly build --release --examples --target riscv64im-zba-zbb-none.json -Zbuild-std=core,alloc -Zjson-target-spec
SampleWhat it shows
counterStorage and return values: inc adds its argument (default 1), get returns the count
depositA vault that holds attached coins per caller, with deposit, withdraw, burn and balance
coinCreates the USDFAKE coin in its init function and airdrops it
nftCreates the AGENTIC collection and mints tokens, using vecpak named arguments
rpgHeroes fight random monsters each turn and loot NFT drops
kitchenExercises every host call; its call function calls another contract
empty, spinTest fixtures

coin and nft call Coin.create_and_mint, Nft.create_collection and Nft.mint. Those built-ins exist on testnet only.

Write your own contract​

The SDK crate (amadeus_contract) is the contract_samples/riscv package itself and is not on crates.io. To add a contract, put a new file in examples/ and run ./build.sh again. For example, examples/hello_counter.rs:

#![no_std]
#![no_main]

use amadeus_contract as sdk;

fn dispatch(function: &[u8]) {
match function {
b"inc" => {
// optional first arg: the step, as a decimal string
let step = sdk::arg(0).map(|raw| sdk::atoi(&raw)).unwrap_or(1);
let total = sdk::kv_increment(b"count", step);
let mut buffer = [0u8; 48];
sdk::ret(sdk::itoa(total, &mut buffer));
}
b"get" => sdk::ret(&sdk::kv_get(b"count").unwrap_or_else(|| b"0".into())),
_ => sdk::abort(b"unknown function"),
}
}

sdk::entry!(dispatch);

This builds to out/hello_counter.elf. Every contract needs #![no_std], #![no_main] and the entry! macro. To use Vec and other heap types, add extern crate alloc; as the deposit sample does.

Run a local testnet​

A local testnet runs on your machine with 10 validator keys and real block production, so you can deploy and redeploy without touching a shared network. The node README lists Ubuntu 24.04 as its tested environment. Build the node from source. build.sh runs the build inside podman:

# from node/contract_samples/riscv, where the previous step left you
cd ../../ex
podman build --tag erlang_builder -f build.Dockerfile
./build.sh
# let a normal user listen on ports 80 and 443
sudo sysctl -w net.ipv4.ip_unprivileged_port_start=80
TESTNET=true WORKFOLDER=/tmp/testnet HTTP_IPV4=127.0.0.1 HTTP_PORT=80 ./amadeusd

On the first start the node writes 10 random seeds to $WORKFOLDER/seeds, prints seeded testnet please restart node and exits. Run the same ./amadeusd command again. The node then starts producing entries and opens an Elixir REPL (iex(1)>). The RPC listens on http://127.0.0.1/api. A testnet node bound to a specific address also opens an HTTPS listener on port 443, which is why both ports need the sysctl setting, as in the node README. See Local testnet for more on running the node.

Deploy and call from the REPL​

Everything below runs in the node's REPL. The Testnet module wraps the transaction calls:

FunctionWhat it does
Testnet.deploy(key, path, init_function \\ nil)Sends a Contract.deploy transaction that stores the ELF at path in key's account. If you pass init_function, that function runs as part of the deploy. Testnet.deploy(path) uses key 0.
Testnet.call(seed, contract, function, args, attachments \\ nil)Signs and submits a call, then waits for it to be included.
Testnet.view(contract, function, args, view_pk \\ nil)Runs a read-only view and returns {success, result, logs}.

path is read by the node process, so use an absolute path. Deploy the counter to key 0's account and call it:

key0 = Application.fetch_env!(:ama, :keys) |> Enum.at(0)
Testnet.deploy key0, "/home/user/node/contract_samples/riscv/out/hello_counter.elf"
Testnet.call key0.seed, key0.pk, "inc", ["1"]
Testnet.call key0.seed, key0.pk, "inc", ["5"]
Testnet.view key0.pk, "get", []

The contract's address is key0.pk, the account that deployed it. Arguments are byte strings, so numbers are passed as decimal strings. A contract that needs setup runs it in an init function on deploy:

key2 = Application.fetch_env!(:ama, :keys) |> Enum.at(2)
Testnet.deploy key2, "/home/user/node/contract_samples/riscv/out/coin.elf", "init"
API.Wallet.balance key2.pk, "USDFAKE"

Contracts call each other through the call host call. The kitchen sample forwards a call to the counter deployed above:

key9 = Application.fetch_env!(:ama, :keys) |> Enum.at(9)
Testnet.deploy key9, "/home/user/node/contract_samples/riscv/out/kitchen.elf"
Testnet.call key0.seed, key9.pk, "call", [key0.pk, "inc", "5"]

More REPL examples are in the sample README: the deposit vault, the NFT claim and the RPG game.

Attach coins and NFTs​

The fifth argument of Testnet.call is the attachments map: a coin symbol maps to an amount in base units (1 AMA = 1,000,000,000), and an NFT collection maps to a map of token to amount. For example, %{"AMA" => 100_000, "USDFAKE" => 5, "RPG" => %{"gold" => 2}}. The assets move from the caller to the contract before it runs. If any transfer is invalid, the whole call reverts.

A tip jar that accepts only AMA and counts tips per caller:

#![no_std]
#![no_main]

extern crate alloc;

use alloc::vec::Vec;
use amadeus_contract as sdk;

fn tips_key(account: &[u8]) -> Vec<u8> {
[b"tips:".as_slice(), account].concat()
}

fn return_int(value: i128) -> ! {
let mut buffer = [0u8; 48];
sdk::ret(sdk::itoa(value, &mut buffer))
}

fn dispatch(function: &[u8]) {
match function {
b"tip" => {
let received: i128 = sdk::attachments()
.into_iter()
.map(|asset| match asset {
sdk::Asset::Coin { symbol, amount } if symbol == b"AMA" => amount,
_ => sdk::abort(b"only AMA tips"),
})
.sum();
if received == 0 {
sdk::abort(b"attach some AMA");
}
sdk::log(b"tip received");
sdk::kv_increment(b"total", received);
return_int(sdk::kv_increment(&tips_key(&sdk::account_caller()), received))
}
b"total" => return_int(sdk::kv_get(b"total").map_or(0, |raw| sdk::atoi(&raw))),
b"tips_of" => {
let account = sdk::arg(0).unwrap_or_else(|| sdk::abort(b"missing account"));
return_int(sdk::kv_get(&tips_key(&account)).map_or(0, |raw| sdk::atoi(&raw)))
}
_ => sdk::abort(b"unknown function"),
}
}

sdk::entry!(dispatch);

Save it as examples/tip_jar.rs, build, deploy it to key 4's account and tip 1 AMA from key 5:

key4 = Application.fetch_env!(:ama, :keys) |> Enum.at(4)
key5 = Application.fetch_env!(:ama, :keys) |> Enum.at(5)
Testnet.deploy key4, "/home/user/node/contract_samples/riscv/out/tip_jar.elf"
Testnet.call key5.seed, key4.pk, "tip", [], %{"AMA" => 1_000_000_000}
Testnet.view key4.pk, "total", []
Testnet.view key4.pk, "tips_of", [key5.pk]

The tipped AMA is now in key 4's balance, because the contract's account is the deploying key's account. A contract pays out by calling Coin.transfer itself, as the deposit sample's withdraw does:

sdk::call(b"Coin", b"transfer", &[&sdk::account_caller(), &amount, &symbol], &[]);

Deploy costs and attached_gas​

A deploy is a Contract.deploy transaction. Its arguments are [elf_bytes], or [elf_bytes, init_function, ...init_args] to run an init function. The ELF can be at most 512 KiB.

A plain transaction's budget is 0.01 AMA. That does not cover storing the bytecode, so a deploy sets attached_gas, an extra budget in base units of AMA. Testnet.deploy attaches:

711,040 + (5,555 + 1,111) × ELF size in bytes + 0.1 AMA

That is the new-key charge, the state and history charges for the bytecode, and 0.1 AMA for the init call. Unused budget is refunded after the transaction runs. The gas section of the overview explains how the budget is split.

Call from TypeScript​

@amadeus-protocol/sdk 1.8.0 can read contract state, run views and call contract functions. Two things to know:

  • Transactions address the contract by its raw bytes. A contract address must go over the wire as its 48 raw public-key bytes. sdk.contract.view takes the Base58 address and decodes it for you. The transaction builders type contract as a string and send it unchanged, so a Base58 string goes out as text and the node treats it as the name of a built-in contract (invalid_bic_action). For buildAndSignRaw, pass fromBase58(address) with a type cast, as in the call sample below.
  • No attachments and no attached_gas. The transaction builders in SDK 1.8.0 (buildUnsigned, buildAndSignRaw, TransactionBuilder) have no field for either one, so from TypeScript you can call functions that need neither, such as inc. Deploy, and send attachments, from the REPL.

Sign testnet transactions with NetworkType.TESTNET. Testnet uses its own signature domain, and a local testnet node uses the testnet domain as well. The seeds in $WORKFOLDER/seeds are Base58 64-byte seeds, the same format the SDK uses for private keys, so you can use them as signing keys against your local node.

Run a view:

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

// local testnet node; use https://testnet-rpc.ama.one/api for the public testnet
const sdk = new AmadeusSDK({ baseUrl: 'http://127.0.0.1/api' })
const contract = '<contract account public key, Base58>'

const { success, result, logs } = await sdk.contract.view({ contract, function: 'get' })
console.log(success, result, logs)

Read the contract's storage directly. Keys are stored under account:<contract>:storage:, and getPrefixEntries returns them with that prefix stripped. Contract state covers paging and decoding.

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

const sdk = new AmadeusSDK({ baseUrl: 'http://127.0.0.1/api' })
const contractAddress = '<contract account public key, Base58>'
const encoder = new TextEncoder()
const prefix = new Uint8Array([
...encoder.encode('account:'),
...fromBase58(contractAddress),
...encoder.encode(':storage:')
])

const decoder = new TextDecoder()
const entries = await sdk.contract.getPrefixEntries(prefix)
for (const [key, value] of entries) {
console.log(decoder.decode(key), decoder.decode(value))
}

Call a function:

import {
AmadeusSDK,
NetworkType,
buildAndSignRaw,
derivePublicKeyFromSeedBase58,
fromBase58
} from '@amadeus-protocol/sdk'

const sdk = new AmadeusSDK({ baseUrl: 'http://127.0.0.1/api' })
const privateKey = '<Base58 seed, e.g. a line of $WORKFOLDER/seeds>'
const contractAddress = '<contract account public key, Base58>'

const signerPk = fromBase58(derivePublicKeyFromSeedBase58(privateKey))
const { txHash, txPacked } = buildAndSignRaw(
signerPk,
privateKey,
fromBase58(contractAddress) as unknown as string,
'inc',
['1'],
NetworkType.TESTNET
)

const { receipt } = await sdk.transaction.submitAndWait(txPacked)
console.log(txHash, receipt.success, receipt.result)

The receipt has success, result (the contract's return value, or the error on failure), logs and exec_used (the total charged, in base units).

The browser wallet extension's signTransaction accepts contract only as a string and passes it through unchanged, so wallet-signed calls can reach the built-in contracts only. For those built-ins (Coin, Nft, lockups) and the ABI helpers, see Contracts and NFTs.

Call over HTTP​

GET /api/contract/view/<contract>/<function> runs a view with no arguments. The contract is given in Base58:

curl -s http://127.0.0.1/api/contract/view/<contract_base58>/get

The response is JSON with success, result and logs. For an account with no contract, this is what you get:

{"success":false,"result":"account_has_no_bytecode","logs":[]}

To run a view with arguments, send POST /api/contract/view with a vecpak body (contract, function, args, optional pk), as the SDK's sdk.contract.view does. Both endpoints replace every byte outside printable ASCII, and the backtick, with ?, so view functions should return text. Reference pages: view (GET) and view (vecpak).

Troubleshooting​

These are the values of the receipt's or view's result when a call fails.

ResultCause
account_has_no_bytecodeThere is no contract at that address. On mainnet every account returns this, because contracts cannot be deployed there.
invalid_bic_actionThe contract was sent as a name the node does not know, for example a Base58 string instead of the 48 raw bytes, or Contract.deploy was sent to mainnet.
riscv_noopThe account holds bytecode, but the network does not execute contracts (mainnet).
abortThe contract called abort or exited with a non-zero code. The message is in logs.
trapThe contract hit an invalid instruction or memory access. The reason is in logs.
exec_insufficient_exec_budgetThe call used more than the 2,000,000-unit exec cap.
exec_insufficient_storage_budgetThe writes, logs or return value cost more than the storage budget. Attach gas.
tx_exceeds_budgetThe transaction is too large for its budget. The transaction pool rejects it, so this comes back as the submit response's error, with no receipt.
exec_cannot_write_during_viewA view tried to write state.
exec_call_depth_exceededNested calls went deeper than 16.
host_return_value_too_largeThe return value is over 128 bytes.
attachments_not_allowed_on_builtinAssets were attached to a built-in contract such as Coin.
attachments_insufficient_funds, attachments_unknown_coin, attachments_paused, attachments_soulboundAn attached coin failed the transfer checks.
attachments_unknown_collection, attachments_unknown_token, attachments_insufficient_tokensAn attached NFT failed the transfer checks.
riscv_bytecode_too_large, riscv_invalid_bytecode, riscv_load_*Deploy only: the file is over 512 KiB, is not an ELF, or fails a loader check (for example riscv_load_not_rv64_little_endian_elf).