npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@dilukangelo/merklelib

v1.0.12

Published

A TypeScript library for generating Merkle trees and proofs with Solidity data types

Downloads

806

Readme

MerkleLib

A TypeScript library for generating Merkle trees and proofs with Solidity data types support. This library makes it easy to create Merkle trees with various Solidity data types and generate proofs for verification.

Installation

npm install @dilukangelo/merklelib

Usage

import { MerkleTree, LeafNode } from '@dilukangelo/merklelib';

// Example with different Solidity types
const data: LeafNode[] = [
  { value: '0x1234567890123456789012345678901234567890', type: 'address' },
  { value: '1000000000000000000', type: 'uint256' },
  { value: true, type: 'bool' },
  { value: 'Hello World', type: 'string' }
];

// Create a new Merkle Tree
const merkleTree = new MerkleTree(data);

// Get the Merkle root
const root = merkleTree.getRoot();
console.log('Merkle Root:', root);

// Method 1: Get proof using index
const proofByIndex = merkleTree.getProof(0);
console.log('Proof by index:', proofByIndex);

// Method 2: Get proof using value (new!)
const proofByValue = merkleTree.getProofByValue('0x1234567890123456789012345678901234567890', 'address');
console.log('Proof by value:', proofByValue);

// Verify the proof (works the same for both methods)
const isValid = merkleTree.verify(proofByValue);
console.log('Proof is valid:', isValid);

NFT Whitelist Example

Here's a complete example of implementing an NFT whitelist using MerkleLib:

TypeScript Setup (Frontend/Scripts)

import { MerkleTree, LeafNode } from '@dilukangelo/merklelib';

// Whitelist addresses
const whitelistAddresses = [
  "0x1234567890123456789012345678901234567890",
  "0x2345678901234567890123456789012345678901",
  "0x3456789012345678901234567890123456789012",
  // ... more addresses
];

// Convert addresses to LeafNode format
const leaves: LeafNode[] = whitelistAddresses.map(address => ({
  value: address,
  type: 'address'
}));

// Create Merkle Tree
const merkleTree = new MerkleTree(leaves);

// Get root for contract deployment
const root = merkleTree.getRoot();
console.log('Merkle Root:', root);

// Generate proof for a specific address
// You can now directly use the address value instead of finding its index!
const addressToProve = "0x1234567890123456789012345678901234567890";
const proof = merkleTree.getProofByValue(addressToProve, 'address');
console.log('Proof for address:', proof);

// Verify the proof
const isValid = merkleTree.verify(proof);
console.log('Proof is valid:', isValid);

Solidity Smart Contract

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;

import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/access/Ownable.sol";

contract WhitelistNFT is ERC721, Ownable {
    bytes32 public merkleRoot;
    uint256 public maxSupply = 1000;
    uint256 public currentTokenId;
    mapping(address => bool) public claimed;

    constructor(bytes32 _merkleRoot) ERC721("WhitelistNFT", "WNFT") {
        merkleRoot = _merkleRoot;
    }

    function mint(bytes32[] calldata proof) external {
        require(!claimed[msg.sender], "Already claimed");
        require(currentTokenId < maxSupply, "Max supply reached");
        require(
            verifyProof(proof, keccak256(abi.encodePacked(msg.sender))),
            "Invalid proof"
        );

        claimed[msg.sender] = true;
        _safeMint(msg.sender, currentTokenId);
        currentTokenId++;
    }

    function verifyProof(
        bytes32[] calldata proof,
        bytes32 leaf
    ) public view returns (bool) {
        bytes32 computedHash = leaf;

        for (uint256 i = 0; i < proof.length; i++) {
            bytes32 proofElement = proof[i];

            if (computedHash <= proofElement) {
                computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
            } else {
                computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
            }
        }

        return computedHash == merkleRoot;
    }

    function setMerkleRoot(bytes32 _merkleRoot) external onlyOwner {
        merkleRoot = _merkleRoot;
    }
}

Using the Whitelist (Frontend Example)

// Example using ethers.js
import { ethers } from 'ethers';
import { MerkleTree, LeafNode } from '@dilukangelo/merklelib';

async function mintNFT(
    contractAddress: string,
    userAddress: string,
    whitelistAddresses: string[]
) {
    // Create Merkle Tree
    const leaves: LeafNode[] = whitelistAddresses.map(addr => ({
        value: addr,
        type: 'address'
    }));
    const merkleTree = new MerkleTree(leaves);

    // Get proof directly using the user's address
    const proof = merkleTree.getProofByValue(userAddress, 'address');

    // Connect to contract
    const provider = new ethers.providers.Web3Provider(window.ethereum);
    const signer = provider.getSigner();
    const contract = new ethers.Contract(contractAddress, ABI, signer);

    // Mint NFT
    const tx = await contract.mint(proof.proof);
    await tx.wait();

    console.log('NFT minted successfully!');
}

Supported Solidity Types

  • address
  • uint256
  • uint128
  • uint64
  • uint32
  • uint16
  • uint8
  • string
  • bytes32
  • bool

API Reference

MerkleTree Class

Constructor

constructor(data: LeafNode[], options?: MerkleTreeOptions)
  • data: Array of leaf nodes with values and their Solidity types
  • options: Optional configuration
    • sortPairs: Boolean to determine if pairs should be sorted before hashing (default: true)

Methods

getRoot(): string

Returns the Merkle root as a hex string.

getProof(index: number): MerkleProof

Generates a Merkle proof for the leaf at the specified index.

  • Returns: MerkleProof object containing:
    • leaf: The leaf value
    • proof: Array of proof elements
    • root: The Merkle root
getProofByValue(value: any, type: SolidityType): MerkleProof

Generates a Merkle proof for a leaf with the specified value and type. This is a more convenient way to get proofs when you know the value but not its index.

  • Parameters:
    • value: The value to generate proof for (must match exactly with a value in the tree)
    • type: The Solidity type of the value
  • Returns: MerkleProof object containing:
    • leaf: The leaf value
    • proof: Array of proof elements
    • root: The Merkle root
  • Throws: Error if the value is not found in the tree
verify(proof: MerkleProof): boolean

Verifies a Merkle proof.

  • Returns: Boolean indicating if the proof is valid

License

MIT