Skip to content

How CosmWasm's SnapshotMap Works

ekez edited this page Jan 24, 2023 · 3 revisions

We would like to create a map such that $map[(height, key)]$ stores the value of $key$ at $height$. Let's call this idealized map $values$.

CosmWasm's SnapshotMap is implemented as two maps. The first is called $primary$ and stores all current values.

$$ primary := primary[k] = values[(currentHeight, k)] $$

The second, called $snapshots$ stores historical values.

$$ snapshots := (h, k) \in snapshots \implies snapshots[(h, k)] = values[(h - 1, k)] $$

That is, for each height it stores the value the key contained before that height.

Our save function saves the old value to $snapshots$ and the new one to $primary$.

$$ save(h, k, v) := snapshots[(h, k)] = primary[k]; primary[k] = v $$

Our load function checks if the provided height has a snapshotted value at the provided height, and if not returns the current value.

$$ load(h, k) := \begin{cases} snapshots[(h', k)] \quad &\text{if} , (h', k) \in snapshots, h \le h' \\ primary[k] \quad &\text{else} \end{cases} $$

Locating a key that satisfies the requirement for the first branch of $load$ is gas-efficient as in CosmWasm the underlying store supports searching by prefix.

This is how CosmWasm's SnapshotMap works.