-
Notifications
You must be signed in to change notification settings - Fork 25
/
allowlist.ts
54 lines (45 loc) · 1.92 KB
/
allowlist.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import { StandardMerkleTree } from "@openzeppelin/merkle-tree";
import { getFromIPFS } from "./fetchers";
import { logger } from "./logger";
import { AllowlistEntry } from "src/types";
const parseAllowListEntriesToMerkleTree = (allowList: AllowlistEntry[]) => {
const tuples = allowList.map((p) => [p.address, p.units.toString()]);
const tree = StandardMerkleTree.of(tuples, ["address", "uint256"]);
return tree;
};
const getMerkleTreeFromIPFS = async (cidOrIpfsUri: string) => {
const data = await getFromIPFS(cidOrIpfsUri);
const allowlist = typeof data === "string" ? data : undefined;
if (!allowlist) {
throw new Error(`Invalid allowlist at ${cidOrIpfsUri}`);
}
const tree = StandardMerkleTree.load(JSON.parse(allowlist));
if (!tree) {
throw new Error(`Invalid allowlist at ${cidOrIpfsUri}`);
}
return tree;
};
/**
* This function retrieves proofs from an allowlist.
*
* It fetches a Merkle tree from IPFS using a given CID or IPFS URI, then iterates over the tree to find an account.
* When the account is found, it generates a proof for that account and logs the account, index, and proof as debug.
* It returns the proof and the root of the Merkle tree.
*
* @param cidOrIpfsUri - The CID or IPFS URI to fetch the Merkle tree from.
* @param account - The account to find in the Merkle tree.
* @returns An object containing the proof for the account and the root of the Merkle tree.
* @throws Will throw an error if the Merkle tree cannot be fetched.
* @async
*/
const getProofsFromAllowlist = async (cidOrIpfsUri: string, account: `0x${string}`) => {
const tree = await getMerkleTreeFromIPFS(cidOrIpfsUri);
for (const [i, v] of tree.entries()) {
if (v[0] === account) {
const proof = tree.getProof(i);
logger.debug(`Found ${account} at index ${i} with proof ${proof}`);
return { proof, root: tree.root };
}
}
};
export { getProofsFromAllowlist, parseAllowListEntriesToMerkleTree };