Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

The example programs

Five programs, each adding one idea to the one before, with full source (program 2 shows only the function that changes) to type into a crate of your own.

They live at examples/program_deployment/methods/guest/src/bin/, with a runner each under src/bin/. Run everything from examples/program_deployment, with EXAMPLES exported as in the quickstart.

The runners of programs 1 and 2 end with two arguments: the account to send to, and a funded public account to pay the fee. Program 4’s runner takes an optional fifth argument, the id of an already deployed hello_world to call (such as the one run_hello_world printed), and deploys a new instance without it; those of programs 3 and 5 differ, as their sections show. Each private run also pays its fee from a funded private account, so fund one first as in the quickstart. Each runner returns once the sequencer accepts its transaction, so wait a block before the next command.

1. hello_world

Appends its message to its own state. The whole program:

use lee_core::program::{ReceiveInput, Response};

lee_core::actor_entrypoint!(handle_message);

fn handle_message(input: &ReceiveInput, greeting: Vec<u8>) -> Response {
    let mut bytes = input.pre_state.to_vec();
    bytes.extend(greeting);
    Response::set_state(bytes)
}
cargo run --bin run_hello_world $EXAMPLES/hello_world.bin <account> <payer>

One message in, one actor’s state in, a new state out. Covered by Accounts, actors and state.

2. hello_world_with_authorization

One line more:

fn handle_message(input: &ReceiveInput, greeting: Vec<u8>) -> Response {
    assert!(input.is_authorized(), "Missing required authorization");

    let mut bytes = input.pre_state.to_vec();
    bytes.extend(greeting);
    Response::set_state(bytes)
}
cargo run --bin run_hello_world_with_authorization \
  $EXAMPLES/hello_world_with_authorization.bin <account> <payer>

Authorization comes from a transaction signature for a public account, from its authorization secret key (ask, Keys) for a private one, or from the seed of a program-derived account (PDA) that the sending program attaches (program 5). Covered by Authorization.

Point the unauthorized runner at it:

cargo run --bin run_hello_world $EXAMPLES/hello_world_with_authorization.bin <account> <payer>

The sequencer’s terminal shows the guest’s own panic, panicked at …/hello_world_with_authorization.rs:15:5: followed by Missing required authorization, and the transaction is still included and pays its fee, with no change to the account.

3. hello_world_with_move_function

A message enum instead of raw bytes, and the first program that touches two accounts.

use lee_core::{
    account::{AccountId, Actor},
    program::{ReceiveInput, Response},
};

#[derive(borsh::BorshSerialize, borsh::BorshDeserialize)]
enum Message {
    Write(Vec<u8>),
    MoveData { data: Vec<u8>, to: AccountId },
    Append(Vec<u8>),
}

lee_core::actor_entrypoint!(handle_message);

fn handle_message(input: &ReceiveInput, message: Message) -> Response {
    match message {
        Message::Write(data) => append(input, &data),
        Message::MoveData { data, to } => {
            assert_eq!(
                input.pre_state.as_ref(),
                data.as_slice(),
                "the source account does not hold the bytes the instruction moves out of it"
            );
            Response::set_state(Vec::new()).send_sync(
                Actor::new(to, input.receiver.program_account_id),
                &Message::Append(data),
            )
        }
        Message::Append(data) => {
            assert!(
                input.from_own_program(),
                "only a move of this program appends to its destination"
            );
            append(input, &data)
        }
    }
}

fn append(input: &ReceiveInput, data: &[u8]) -> Response {
    Response::set_state([input.pre_state.as_ref(), data].concat())
}

This runner takes the payer first, then the function and its arguments. Each run without --program-id deploys a new instance of the program, with its own state (Programs, deployment and identity), so pass the id the first run prints to the two after it:

cargo run --bin run_hello_world_with_move_function $EXAMPLES/hello_world_with_move_function.bin \
  <payer> write-public <public account> mundo!
cargo run --bin run_hello_world_with_move_function $EXAMPLES/hello_world_with_move_function.bin \
  <payer> --program-id <program id> write-private <private account> Hola
wallet account sync-private
cargo run --bin run_hello_world_with_move_function $EXAMPLES/hello_world_with_move_function.bin \
  <payer> --program-id <program id> move-data-public-to-private <public account> <private account>

The sync matters, since the move builds on the private account’s local state, and must wait for the block holding write-private. A move built on the state from before it spends a nullifier write-private already spent: the sequencer drops it at settlement, when it applies the block (Transaction failed settlement, skipping it in its log), while the runner still returns, or refuses it outright with Nullifier already seen once that spend is in the head. Afterwards the public account’s state is empty and, after another sync, the private one reads Holamundo!.

The program is identical in all three runs and is not told which accounts are public: the runner decides when it builds the transaction (why this matters, Transactions, public and private).

MoveData carries the data the caller claims the source holds, and the source refuses unless its state is exactly that. The claim is pinned against the state rather than trusted, an idea that recurs throughout the pattern language.

Append guards with input.from_own_program(), so it runs only on a move from this program. Write and MoveData have no authorization check, so in this example anyone can append to or empty this program’s state on any public account; a real program would check is_authorized() there. Routing on the sender is pattern 2, Route on the sender first.

4. simple_tail_call

The first program that talks to another program.

use lee_core::{
    account::Actor,
    program::{ReceiveInput, Response},
};

lee_core::actor_entrypoint!(handle_message);

fn handle_message(_input: &ReceiveInput, callee: Actor) -> Response {
    let greeting: Vec<u8> = b"Hello from tail call".to_vec();

    Response::keep_state().send_sync(callee, &greeting)
}
cargo run --bin run_hello_world_through_tail_call \
  $EXAMPLES/simple_tail_call.bin $EXAMPLES/hello_world.bin <account> <payer>

keep_state() because it changes nothing of its own; it exists only to send. The callee arrives in the message rather than as a constant, because a program’s address is not known until it is deployed.

The private form takes the same arguments, and your machine executes and proves both programs:

cargo run --bin run_hello_world_through_tail_call_private \
  $EXAMPLES/simple_tail_call.bin $EXAMPLES/hello_world.bin <private account> <payer>

Covered by Handlers and messages.

5. tail_call_with_pda

A program authorizing an account that no key controls.

use lee_core::{
    account::{AccountId, Actor},
    program::{PdaSeed, ReceiveInput, Response, SyncMessage},
};

const PDA_SEED: PdaSeed = PdaSeed::new([37; 32]);

lee_core::actor_entrypoint!(handle_message);

fn handle_message(input: &ReceiveInput, callee_account_id: AccountId) -> Response {
    let greeting: Vec<u8> = b"Hello from tail call with Program Derived Account ID".to_vec();

    Response::keep_state().send(
        SyncMessage::new(
            Actor::new(input.receiver.account_id, callee_account_id),
            &greeting,
        )
        .with_pda_seeds(vec![PDA_SEED]),
    )
}
cargo run --bin run_hello_world_with_authorization_through_tail_call_with_pda \
  $EXAMPLES/tail_call_with_pda.bin $EXAMPLES/hello_world_with_authorization.bin <payer>

It prints the derived account id, readable like any other account.

Actor::new takes the account first and the program second, so callee_account_id is the callee program’s id. The runner sends the root message to the account derived from this program’s deployed address and PDA_SEED via AccountId::for_public_pda, and declares the callee’s actor on that same account. Attaching that seed with with_pda_seeds asks the protocol to treat the account as authorized for the outgoing message, which it does only when the account id equals for_public_pda of the sending program’s account id and that seed. The callee is hello_world_with_authorization, which refuses without authorization: the seed grant is what makes it succeed.

This is how a program controls funds: a vault is an account whose authority is a program and a seed rather than a key. Covered by Authorization.

The protocol’s own test programs

Under test_programs/guest/src/bin/, built with risc0_build::embed_methods() in a build.rs rather than the Docker builder, so they are not reproducible but need no Docker.

ProgramMechanismChapter
cooldown.rsrefuses to run until a cooldown has elapsed, by reading the clock and recognising its reply by the senderSystem programs
time_locked_transfer.rsthe deadline in the message becomes a timestamp_window on the response, so the transfer can only land in a block at or past it, with no clock messageSystem programs
live_payout.rsreads another actor’s live native balance by asking for it and handling the reply, then pays a tenth of itReplies
clock_reader.rsthe smallest clock reader: forwards whatever it is sent to the clock and stores the reply as its stateSystem programs
grant_relay.rsforwards a grant along a chain of programs, re-attaching it at each hop, and spends it only at the endAuthorization
listener.rsthe raw form of actor_entrypoint!, where the handler takes only ReceiveInput and decodes nothingHandlers and messages
scripted.rsa handler driven by a Script value, for arbitrary sequences in protocol testsHandlers and messages

For time, time_locked_transfer.rs shows a validity window (only a deadline needed) and cooldown.rs a read with a reply (the time must be stored or branched on).

For authority, read grant_relay: the guest is a one-line wrapper, and a function in test_guest_core/src/guests.rs holds the whole forwarding rule. It re-attaches every grant in input.grants on each hop, and at the last hop spends those over native balance actors.

What no example covers yet

Apart from scripted, which can send async messages in protocol tests, none of these sends an async message, collects a stored one from a mailbox, has a private actor send to a public one, or uses a group-held account. Those are the mechanisms in Handlers and messages and Private accounts with no runnable example outside protocol tests.