Writing the Program

Since Zephyr allows for complete customizability, writing a program involves a vast number of options. The scope of the section "Learn" of the docs is in fact to cover all those different options you have. Nevertheless, there are a few things we can state at a general level.

The source file of Zephyr programs is lib.rs, so you can start from here when writing your programs.

Entry Point

As already said, a Zephyr program will run for every new ledger close if we wish. That is for sure the case when it is used to index and return data, which is Zephyr's main use case. Of course, the program can be used solely as an API that returns already indexed (public indexed data by other users) or ledger data, in which case we wouldn't need it to run for every ledger close, but only when called.

The on_close Function

If you are using Zephyr as an indexer, your starting point will be the on_close function, that the Zephyr VM will always call when executing the program for every new ledger close. This function is already defined when opening the lib.rs. Initially, it will look like this:

#[no_mangle]
pub extern "C" fn on_close() {
    let env = EnvClient::new();
    
    ...
}

Inside the function, we need to define a new EnvClient object, which will help us communicate with the VM and the host environment.

The env variable enables us to:

  • retrieve XDR data.

  • log messages and data.

  • interact with the database.

  • send web requests.

  • read from the ledger.

  • simulate and perform contract calls.

Serverless functions

Nevertheless, the entry point for a program doesn't necessarily have to be an on_close function. As already said, if we define it solely as a custom API for accessing already indexed or ledger data, the entry point is a serverless function that will be externally called. The function will hold all the logic on how to return data.

To know more about how serverless functions work, jump to the Serverless Functions page. Of course, you can define such functions and also have your program run for every ledger close while indexing data. The possibility of combining all its different features is the power of Zephyr.

Last updated