🚀 o1js reference documentation is now available at the new o1Labs docs site.
Indexed Merkle Map
Similar to a Merkle Tree, a Merkle Map allows referencing off-chain data by storing a single hash, also known as the root.
A Merkle Map is a wrapper around a Merkle Tree. Both data structures are analogous, but instead of using an index to set a leaf in a tree, a Merkle Map uses a key in a map.
Design​
The Indexed Merkle Map is an improved version of the MerkleMap, offering enhanced efficiency and usability:
- Reduced Constraints: In o1js 3.0.0, an
insertinto anIndexedMerkleMap(33)takes 2,621 rows and anupdatetakes 1,613 rows. An update of aMerkleMapvalue takes 10,591 rows. These are the numbers thatanalyzeMethods()reports for the contracts of Tutorial 5. - Provable Code Integration: Unlike
MerkleTreeandMerkleMap, the high-level API ofIndexedMerkleMapis usable within provable code. - Proof of absence: The map can prove that a key is not in the map.
insert()fails for a key that is already in the map, andupdate()fails for a key that is not in the map.
The Indexed Merkle Map can have a height of at most 52, whereas the Merkle Map has a larger height fixed at 256.
Utilizing Indexed Merkle Map​
Prerequisites​
In o1js 3.0.0, IndexedMerkleMap is a top-level export of o1js. It is not in the Experimental namespace: Experimental.IndexedMerkleMap is undefined.
import { IndexedMerkleMap } from 'o1js';
Instantiating an Indexed Merkle Map​
Given a height, you can instantiate an Indexed Merkle Map by extending the base class. The height determines the capacity of the map; the maximum number of leaf nodes it can contain.
const height = 31;
class IndexedMerkleMap31 extends IndexedMerkleMap(height) {}
In this example, IndexedMerkleMap31 is a Merkle map capable of holding up to 2(31−1) leaves; approximately 1 billion entries. A new map already contains the key 0 with the value 0, and that entry uses one leaf.
Use it in a smart contract​
Tutorial 5: Indexed Merkle Map has a tested smart contract that stores only the root of the map on chain and inserts and updates keys. It also shows why the contract method must change a clone() of the map argument.
Indexed Merkle Map - API reference​
For an example, see the IndexedMerkleMap API reference in o1js.
Additional Resources​
For more details and examples, please refer to the following GitHub resources: