States

States are where you can store information when a usecase is run so that it can be used again in another usecase execution.

A simple example of state is to create an alert when there is a price change:

export async function process({ event, state }) {
    const currentPrice = event.data.price;
    
    // Retrieve data from project state
    const previousPrice = await state.get("priceFeed");
    
    // Set state to a new value so when next price update arrives,
    // it could be compared to current data
    await state.set("priceFeed", currentPrice);
    
    if (!previousPrice) {
        return { isAlert: false, message: "" };
    }
    if (Math.abs(currentPrice - previousPrice)/currentPrice >= 0.01) {
        return {
            isAlert: true,
            message: "Price changed more than 1%"
        }
    }
    return {
        isAlert: false,
        message: "Price changed less than 1%"
    }
}

The above usecase stores the latest price in a state called priceFeed, which is used when the next usecase execution is run. The rule compares that current price with priceFeed (which is now the previous price) and if the change exceeds 1%, it creates an alert.

Usecase states have enabled more complex logic such as:

  • Alerts with historical data, such as price change or contract parameter change

  • Alerts that requires chain of multiple events

  • Alerts related to blockchain state changes

Accessing states

States are project-scoped, meaning all states are shared inside a project, but cannot be accessible outside one. Project members with role of Editor and above can manage usecase states.

States can be accessed directly in usecase rule, utilizing injected state parameter in process() function. In addition, states can be viewed in State menu in project edit page as well.

Currently, each state has a maximum size of 1kB.

Data Types

While storing states during usecase execution (i.e. via state.set() in usecase rule), the engine will automatically determine the data type supplied. Retrieved data through state.get() will retain its data type.

Supported data types are:

  • Object (as JSON)

  • Boolean

  • Number

  • BigInt

  • String

  • Symbol

Last updated