@laborx/merkletree
v0.2.1
Published
Provides implementation for building and managing Merkle tree structure.
Downloads
14
Keywords
Readme
Merkle tree
Provides implementation for building and managing Merkle tree structure.
Usage
Install package with:
npm install @laborx/merkletree
or
yarn add @laborx/merkletree
Main classes
There are two main classes:
- MerkleTree
- AirdropMerkleProofBuilder
MerkleTree class provides functionality to initialize, build, construct merkle proof for provided element and verify passed proof.
AirdropMerkleProofBuilder class provided wrapper around MerkleTree and allowes to speak on a business language rather than low-level instructions. This class uses AirdropNode interface to set up bounds around entity that is supposed to be used throughout class's lifecycle. It will be helpful to coordinate with @laborx/airdrop-contracts
smart contracts.
Use cases
MerkleTree class
Creation of MerkleTree
import { MerkleTree, HashFunction } from "@laborx/merkletree";
// ...
const leaves: Buffer[];
const hashAlgorithm: HashAlgorithm;
const merkleTree = new MerkleTree(leaves, hashAlgorithm)
Then merkle tree is ready to go.
Generate proof for one of your leaf
const leaf: Buffer;
const merkleProof: MerkleProofItem[] = merkleTree.getProof(leaf);
Verify provided proof for validity:
const merkleRoot: Buffer = merkleTree.getRoot();
const leaf: Buffer;
const merkleProof: MerkleProofItem[];
merkleTree.verify(proof, leaf, merkleRoot);
AirdropMerkleProofBuilder class
This class allows easiest acceess and communication with MerkleTree class through lenses of airdrop functionality.
Creation of AirdropMerkleProofBuilder
import { AirdropMerkleProofBuilder, AirdropNode, AirdropProof, makeTreeLeafString } from "@laborx/merkletree";
const elements: AirdropNode[];
const airdropProofBuilder = new AirdropMerkleProofBuilder(elements);
Get a merkle proof
const element: AirdropNode;
const proof: AirdropProof[] = airdropProofBuilder.getProofForNode(element);
Verify your node of merkle tree entrance
const proof: AirdropProof[];
const element: AirdropNode;
const isValidElement: boolean = airdropProofBuilder.verifyProofForNode(proof, element);
Compile updated version of elements
When existed elements are updated and initial merkle tree have to be updated too just do
const updatedElement: AirdropNode[];
airdropProofBuilder.compileNewMerkleTree(updatedElement);