Publish events from a Rust contract
An event can contain up to 4 topics, alongside the data it is publishing. The data
can be any value or type you want. However, the topics must not contain:
Vec
Map
Bytes
orBytesN
longer than 32 bytescontracttype
// This function does nothing beside publishing events. Topics we are using are
// some `u32` integers for the sake of simplicity here.
pub fn events_function(env: Env) {
// A symbol will be our `data` we want published
my_data = Symbol::new(&env, "data_to_publish");
// an event with 0 topics
env.events().publish((), my_data.clone());
// an event with 1 topic (Notice the extra comma after the topic in the
// tuple? That comma is required in Rust to make a one-element tuple)
env.events().publish((1u32,), my_data.clone());
// an event with 2 topics
env.events().publish((1u32, 2u32), my_data.clone());
// an event with 3 topics
env.events().publish((1u32, 2u32, 3u32), my_data.clone());
// an event with 4 topics
env.events().publish((1u32, 2u32, 3u32, 4u32), my_data.clone());
}
A more realistic example can be found in the way the token interface works. For example, the interface requires an event to be published every time the transfer
function is invoked, with the following information:
pub fn transfer(env: Env, from: Address, to: Address, amount: i128) {
// transfer logic omitted here
env.events().publish(
(symbol_short!("transfer"), from, to),
amount
);
}
Guides in this category:
📄️ Ingest events published from a contract
Soroban RPC provides a getEvents method which allows you to query events from a smart contract. However, the data retention window for these events is roughly 24 hours. If you need access to a longer-lived record of these events you'll want to "ingest" the events as they are published, maintaining your own record or database as events are ingested.
📄️ Publish events from a Rust contract
An event can contain up to 4 topics, alongside the data it is publishing. The data can be any value or type you want. However, the topics must not contain: