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

Handlers and messages: SyncMessage and AsyncMessage

A program is one function

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)
}

The whole hello-world program (examples/program_deployment/methods/guest/src/bin/hello_world.rs) appends the message to its own state.

actor_entrypoint! only expands to the guest’s main: it reads the input, decodes the message with Borsh into the handler’s second parameter, calls the handler, and commits the result. The form actor_entrypoint!(raw handler) skips the decoding and gives the handler only the input, for programs that decode differently depending on the sender.

What the handler receives

pub struct ReceiveInput {
    pub receiver: Actor,          // the actor this run is for
    pub from: Option<Actor>,      // the sending actor; None when the transaction's author sent it
    pub grants: BTreeSet<Actor>,  // see the Authorization chapter
    pub pre_state: ActorState,    // this actor's state before the message
    pub message: MessageData,     // the message bytes
}
  • receiver tells the handler which actor it is. One program serves many accounts, and some behave differently per account (the clock refuses every message outside its one fixed account).
  • from is filled in by the system; a program cannot forge it. A stored message keeps its original sender when it is collected.
  • pre_state is empty for an actor that has never been written.

What the handler returns

pub struct Response {
    pub post_state: Option<ActorState>,
    pub sync_messages: Vec<SyncMessage>,
    pub async_messages: Vec<AsyncMessage>,
    pub events: Vec<ProgramEvent>,
    pub validity: ValidityWindows,
}

Build it with chained methods:

Response::set_state(new_bytes)      // or Response::keep_state()
    .send_sync(other_actor, &message)    // deliver now
    .send_async(some_actor, &message)     // deliver now if possible, otherwise store
    .event(event)
    .block_window(100..)            // only valid from block 100 on

To refuse a message, the handler panics. A panic fails the whole transaction: when a public handler panics, the state changes are dropped but the payer is still charged (in a private transaction, only when the proof carries a fee fallback or a signer declares the fee; otherwise the transaction is dropped unpaid); when a private handler panics, no proof can be made, so there is no transaction to submit.

SyncMessage

A SyncMessage is delivered inside the transaction it was emitted in, or the transaction fails.

  • The receiver’s handler runs before the transaction ends.
  • If it fails, everything fails, including the sender’s state change.
  • A SyncMessage can carry PDA seeds, which authorize the receiver, and grants its sender holds (see Authorization).

A SyncMessage returns no value. For an answer, the receiver sends a second message back and the sender’s handler runs again to receive it (Replies).

Who can be reached by a SyncMessage:

  • any public actor the transaction declares, that is, lists among the actors it may reach (Declaring actors); a public account that does not exist yet must also be admitted (Admission);
  • a private actor whose owner is building this transaction.

A SyncMessage to anyone else’s private actor fails the transaction: only the owner can run a private handler, and they are not here.

AsyncMessage

An AsyncMessage is a message that is allowed to wait.

DestinationWhat happens
a public actor the transaction declaresdelivered in this transaction
one of the submitter’s own private actors, when the submitter promotes it (asks for it to run now)delivered in this transaction
any other private addressstored on chain for its owner to collect later

An AsyncMessage delivered in this transaction fails like a SyncMessage: if its handler fails, the whole transaction fails, the sender’s state change included. It differs in two ways: it carries no PDA seeds and no grants, and it runs after the SyncMessages of the same response and everything they trigger. Only a stored message leaves its sender unaffected: the sender’s transaction completes whatever later happens to the message.

By default the reference wallet promotes every async message to a private account the transaction includes, so wallet auth-transfer send to your own private account credits it at once. wallet pending receive can also promote chosen ones by index (--promote-public, --promote-private): the engine numbers, from 0, the async messages the transaction’s handlers send to undeclared destinations, counting those from public and from private senders separately. wallet program call builds only public transactions, so delivering a program’s message to your private actor at once needs the wallet library, with that account mentioned (it need not be authorized).

For a stored message, the sender’s transaction completes and the message waits in a global mailbox until the destination’s owner builds a transaction whose root is that stored message; their handler runs then.

Rules for stored messages:

  • A public sender’s stored message is published in the clear with a recovery note, so the destination needs a recovery binding (an encrypted note on chain that tells the owner which of their accounts the address belongs to): one already on chain, or one a privacy-preserving transaction introduces. A private sender seals it (encrypts it to the recipient’s keys) and needs no binding, unless it chooses to publish in the clear. See Recovery bindings.
  • Only private addresses can hold stored messages. An AsyncMessage to a public account that the transaction did not declare cannot be stored and fails the transaction: in the clear it fails with UnboundAsyncDestination, and a seal cannot be addressed to it.
  • The sender cannot be told about failure, and nothing returns to it (A stored message is never returned). Design receiving handlers so that a legitimate message always succeeds.

Choosing between them

You wantUse
all-or-nothing with the other actorSyncMessage
to grant a PDA seedSyncMessage
to reach a stranger’s private accountAsyncMessage
the same code to work whether the receiver is public or privateAsyncMessage
the receiver to be free to act later, or neverAsyncMessage

The native token shows this. Transfer debits the sender and sends Credit to the recipient as an async message (lee/state_machine/core/src/native_token.rs). For a declared public recipient the credit lands in the same transaction; for a private recipient it waits in their mailbox. The transfer code does not know which.

Order of execution

A transaction’s messages form a tree. The root is the message the transaction is built to deliver: a SyncMessage from its author (with from set to None), or a stored message being collected (TransactionEntry, lee/state_machine/core/src/execution_state.rs). Each message a handler sends and the transaction delivers is a child of the message that ran it. A stored message ends its branch; the transaction that collects it delivers it as its root or as a claim (a further stored message swept into the same transaction, as Pending messages describes for native credits). Claims run before the root, each as its own entry, and a proven fee’s transfer runs after the root’s subtree.

Messages are processed depth first: of several messages a handler returns, the first and everything it triggers complete before the second is delivered. Within one response, SyncMessages run before any AsyncMessages delivered in the same transaction.

A handler can therefore be entered more than once in a transaction; the second time, pre_state is the state its first run wrote.

Replies

There is no read access to another actor’s state, so reading takes two messages. The native token shows the shape:

Message::ReadState => {
    let reader = input
        .from
        .ok_or(TransferError::UnroutableRead { account_id })?;
    // The reply returns the grant the reader lent, so its handler can act on it.
    Response::keep_state()
        .send(SyncMessage::new(reader, &StateReply::from(input)).with_lent_grant(input))
}

The asking actor sends ReadState and the balance actor answers with its state. The asking program must handle the reply and check who sent it. The fee program does it this way (lez/programs/fee/src/main.rs):

if input
    .from
    .is_some_and(|from| from.program_account_id == NATIVE_TOKEN_PROGRAM_ID)
{
    let reply: StateReply =
        borsh::from_slice(&input.message).expect("a native state reply must decode");
    return pay_out(input, &reply);
}

It decodes a StateReply only from the native token program; without that check anyone could forge a reply.

A message submitted by the transaction’s author has no sender, so nothing can reply to it: ReadState sent that way fails.

Message types

Messages are bytes in a format the receiver’s program defines and the sender must use. A program therefore needs a handler for every message it can receive, not for those it sends.

A layout that keeps handlers honest:

/// Anyone may send these.
enum Message { Transfer { .. }, ReadState }

/// Only actors of this same program may send these.
enum Internal { Credit(u128) }

/// Sent to other programs; never received.
enum Outbound { StateReply(..) }

The handler looks at input.from first, then decodes with the type that sender is allowed to use. The fee program does this (the reply check above); the native token instead uses one enum and checks the sender inside the match arm.

Validity windows

A handler can limit when its transaction is valid:

Response::keep_state().timestamp_window(deadline..)

An open-ended range (from.. or ..to) goes to block_window or timestamp_window. A closed range can be empty, so it goes to try_block_window or try_timestamp_window, which return an error for an empty one.

The windows of all handlers in a transaction are intersected, and the sequencer checks the result against the block being built. A lower bound is inclusive and an upper bound is exclusive. An empty intersection fails the transaction.

Events

A handler can emit events: an 8-byte selector and data. Events from public handlers are attached to the transaction for indexers; those from private handlers are dropped.

Small helpers

  • input.from_own_program(): true when the sender is an actor of the receiver’s own program.
  • write_once(pre_state, data): returns data, and panics if the state already holds something different, for values that must be set once.