merkletreejs icon indicating copy to clipboard operation
merkletreejs copied to clipboard

MerkleTree always returns []

Open damianlluch opened this issue 3 years ago • 2 comments

Hi, I am trying to use this library to manage a whiteList of Ethereum address.

Question, I have tried many ways, and I can not get it to work.

I had to modify a little bit the leafNodes part, because when using Typescript it was giving me problems.

I'm using MongoDB. I clarify. The merkleRoot generation function seems to work correctly like this:

const arrayUsers = [];
    users.map(function (element) {
      arrayUsers.push(element.address);
    });
    const leafNodes = arrayUsers.map(x => keccak256(Buffer.from(x)));
    const tree = new MerkleTree(leafNodes, keccak256, { sortPairs: true });
    const root = '0x' + tree.getRoot().toString('hex');
    whiteList.merkleRoot = root;

Now for the merkleProff, I'm running it like this (based on examples I saw in the tests section).

    const leafNodes = whiteList.addresses.map(x => keccak256(Buffer.from(x)));
    const tree = new MerkleTree(leafNodes, keccak256, { sortPairs: true });
    const eligibleProof = tree.getHexProof(Buffer.from(leafNodes[0]));

In my code, I create the list, add an address to the whitelist, close the list (I create merkleRoot) and then use a function for the merkleProff to check if the user is in the whitelist.

damianlluch avatar Jul 12 '22 15:07 damianlluch

I have also tried the following way, and I get the message:


Error: leaf is required

private async generateHexProof(_AddressSentToEndpoint, _whiteListAddresses) {
    const index = _whiteListAddresses.findIndex(element => {
      element == _AddressSentToEndpoint;
    });

    console.log(_whiteListAddresses, 'address');
    const leaves = _whiteListAddresses.map(v => keccak256(Buffer.from(v)))


    const merkleTree = new MerkleTree(leaves, keccak256, {
      sortPairs: true,
    });

    const claimingAddress = leaves[index]
    return merkleTree.getProof(claimingAddress);
  }

```



```
private async generateRootHashNormalized(_whiteListAddresses) {
    const leafNodes = _whiteListAddresses.map(addr =>
      keccak256(Buffer.from(addr)),
    );

    const merkleTree = new MerkleTree(leafNodes, keccak256, {
      sortPairs: true,
    });
    const rootHash = merkleTree.getRoot(); //buffer
    let rootHashNormalized = '0x';

    // @ts-ignore
    rootHash.map(element => {
      if (element.toString(16).length < 2) {
        rootHashNormalized += '0';
      }
      rootHashNormalized += element.toString(16);
    });

    return rootHashNormalized;
  }
```

damianlluch avatar Jul 12 '22 18:07 damianlluch

On my side to make it work I have to add an empty entry in the original array:

[
    "",
    "0xAddress1",
    "0xAddress2"
]

gaetan-hexadog avatar Sep 27 '22 18:09 gaetan-hexadog