Key-Value Storage (KVS)

Learn how to use the KVS

About

An alternative method for storing function state is through a Key-Value storage system. This approach enables storing and retrieving specific portions of the state during any interaction, eliminating the need to process the entire JSON object while reading state.

API reference

  • SmartWeave.kv.put(key, value) - insert a new key-value pair or update an existing key's value

  • SmartWeave.kv.get(key) - return the value of a given key, readable via response.data.result

  • SmartWeave.kv.del(key) - delete a key-value pair (it will still be accessible on-chain from the previous state reference)

  • SmartWeave.kv.keys(options: QueryOptions) - fetch a key based on a custom range

  • SmartWeave.kv.kvMap(options: QueryOptions) - Fetch a pair based on custom range

QueryOptions interface for .keys and .kvMap

interface QueryOptions {
  // Greater than or equal to (default: 0)
  gte?: number;
  // Less than (default: Object.keys(this.kv).length)
  lt?: number;
  // Reverse the order (default: false)
  reverse?: boolean;
  // Limit the result length (no default)
  limit: number;
}

Function example

After writing to the Key-Value storage (KVS), data can be retrieved by external actors/applications through the following flow:

  1. Retrieve the value associated with the key using SmartWeave.kv.get().

  2. The result, which is the value of the key, is then returned alongside the response transaction as a result.

function.js
export async function handle(state, action) {
  const input = action.input;

  if (input.function === "put") {
    const { key, value } = input;
    
    state.puts.push({ key, value }); // write to state
    SmartWeave.kv.put(key, value); // write to KVS
    return { state };
  }
  if (input.function === "get") {
    const { key } = input;
    
    const res = SmartWeave.kv.get(key);
    state.gets.push(res)
    return { state };
  }

  if (input.function === "del") {
    const { key } = input;
    SmartWeave.kv.del(key);
    return { state };
  }
}
state.json
{
  "puts": [],
  "gets": [],
  "publicFunctions": { "put": ["key", "value"], "get": ["key"], "del": ["key"] }
}

Contribution History

The MEM features introduced to the 3EM repository codebase (OSS) have started by this PR: https://github.com/three-em/3em/pull/234

Last updated

mem.tech © 2023