Function Storage API
This API is exported through the sbcore.storage
object. It provides endpoints to store and load key-value pairs. It offers a simple way to persist and retrieve data using unique keys.
public Load(namespace: string, key: string, defaultValue: object): Promise<object>;
public Store(namespace: string, key: string, value: object): Promise<object>;
The namespace string must consist of alphanumeric characters, hyphens and underscores, eg. my_namespace123
.
A namespace can be used by different functions, but only of the same user. Having said that, a namespace's data can also be shared publicly!
Store Key-Value Pair
By using the Store
method of the sbcore.storage
object you can store any type of object or primitive that can be serialized to json. The following examples show how you can use the method:
- Saving the block number (string) that triggered the current function
await sbcore.storage.Store("my_namespace", "triggeredForBlock", context.blockNumber);
-
Saving the index (number) of the transaction in the block that triggered the function:
await sbcore.storage.Store("my_namespace", "triggeredForTxIndex", context.txIndex);
-
Save both TxIndex and blockNumber as an object :
await sbcore.storage.Store("my_namespace", "context", { txIndex: context.txIndex, blockNumber: context.blockNumber, });
Load Value by key
You can use the Load
method of the sbcore.storage
object to retrieve stored values based on their keys. This method returns a promise that resolves to the loaded value or a default value that was passed if the key does not exist. Below are examples of how to use the Load method:
-
Loading the block number that triggered the current function:
const defaultBlockValue = "default"; const blockNumber = await sbcore.storage.Load("my_namespace", "triggeredForBlock", defaultBlockValue); if (blockNumber == defaultBlockValue) { console.log("First trigger of the function"); } else { console.log("Previous run of the func was for block:", blockNumber); }
-
Loading the index of the transaction in the block that triggered the function:
const txIndex = await sbcore.storage.Load("my_namespace", "triggeredForTxIndex", 1); console.log("Transaction Index:", txIndex);
-
Loading an object containing both TxIndex and blockNumber:
const contextData = await sbcore.storage.Load("my_namespace", "context", {}); console.log("Context Data:", contextData);
Updated 24 days ago