Install the @semaphore-research/merkle-tree package with npm:
npm i @semaphore-research/merkle-tree --saveor yarn:
yarn add @semaphore-research/merkle-tree# new IncrementalMerkleTree(hash: HashFunction, leaves?: Node[]): IncrementalMerkleTree
import { IncrementalMerkleTree } from "@semaphore-research/merkle-tree"
import { poseidon2 } from "poseidon-lite/poseidon2"
const hash = (a: Node, b: Node): Node => poseidon2([a, b])
const tree = new IncrementalMerkleTree(hash, [1, 2, 3])# insert(leaf: Node)
tree.insert(1)# update(index: number, newLeaf: Node)
tree.update(0, 2)# delete(index: number)
tree.delete(0)# indexOf(leaf: Node): number
tree.insert(2)
const index = tree.indexOf(BigInt(2))
console.log(index) // 1# has(leaf: Node): boolean
console.log(tree.has(2)) // true# generateProof(index: number): MerkleProof
const proof = tree.generateProof(1)# verifyProof(proof: MerkleProof): boolean
console.log(tree.verifyProof(proof)) // trueBenchmarks were run on a Intel Core i7-1165G7, 16 GB RAM machine.
| Init (256) | Insert (1) | Insert (256)* | InsertMany (256) | Update (1) | |
|---|---|---|---|---|---|
| Old Mekrle tree | 57ms |
3.6ms |
956ms |
Not implemented | 4ms |
| New Merkle tree | 54ms |
1ms |
348ms |
46ms |
3ms |
If you want to run the benchmarks yourself install the dependencies with yarn in the javascript folder and then run yarn benchmarks.
For more information about gas savings and Solidity benchmarks read the solidity README.md file.
*The insert function has been executed 256 times as it only takes 1 leaf as a parameter, whereas the insertMany function supports batch insertions and takes a list of leaves as a parameter.