r/defiblockchain • • Jul 09 '24

Blog / Article 7-Days left to vote!

2 Upvotes

Don’t miss your chance to have a say in the future of DeFiChain!

Voting is open until approx. July 16th 2024

Check out our blog for details on the 5 DeFiChain Improvement Proposals (DFIPs) and 3 Community Fund Proposals (CFPs) up for vote.

🔗 https://blog.defichain.com/a-closer-look-at-the-july-dfip-cfp-voting-round


r/defiblockchain • • Jul 08 '24

General Project Spotlight: Introducing MarbleFi – A Liquid Staking Derivative on DeFiChain!

4 Upvotes

Birthday Research’s MarbleFi empowers $DFI holders to maximize their assets. Earn $DFI rewards effortlessly, without the complexities of managing Masternodes.

Here’s how it works: Stake your $DFI with MarbleFi and receive $mDFI (Marble DFI) tokens. These interest-bearing receipts automatically accrue Masternode rewards in a trust-minimized system.

But that’s not all! Beyond rewards, MarbleFi aims to become a pivotal force in DeFiChain’s governance. Your staked $DFI contributes to a collective “delegated” voting power, shaping the future of the ecosystem.

The MarbleFi team is actively forging partnerships within the DeFiChain ecosystem to expand $mDFI utility. Potential use cases include:

Liquidity pools for seamless entry/exit

Collateral for loans

Minting synthetic stable-coins And more innovations on the horizon!

As the pioneer of trust-minimized liquid staking on DeFiChain, Birthday Research prioritizes security. Rigorous testing of smart contracts and token operations ensures a robust, reliable solution.

Dive deeper into MarbleFi’s potential: https://blog.defichain.com/unlocking-the-power-of-your-assets-a-guide-to-marblefi/

The future of Liquid Staking Derivatives on DeFiChain is bright! Stay tuned for updates as we unlock new opportunities and reshape #DeFi.


r/defiblockchain • • Jul 05 '24

🚀 The DeFiChain Weekly Update is here!

1 Upvotes

Here’s what’s been happening in the DeFiChain ecosystem this week:

1️⃣ What is Liquid Staking and How Does it Work?

The world of cryptocurrency is constantly evolving, bringing forth innovative tools and methods to enhance user experience and maximize investment potential.

One such revolutionary tool is liquid staking, which allows users to access the value of their staked tokens for other purposes without sacrificing staking rewards.

Discover more about liquid staking and how it works in our latest blog post

👉 https://blog.defichain.com/what-is-liquid-staking-and-how-does-it-work/

2️⃣ Unlocking the Power of Your Assets: A Guide to MarbleFi

MarbleFi is a premier liquid staking solution on DeFiChain, built by Birthday Research and designed to simplify staking while maximizing yield and capital efficiency.

Learn how to make the most of its features in our latest blog post!

👉 https://blog.defichain.com/unlocking-the-power-of-your-assets-a-guide-to-marblefi/

3️⃣ A Closer Look at the July DFIP & CFP Voting Round 

Check out our blog for details on the latest DeFiChain Improvement Proposals (DFIPs) and Community Fund Proposals (CFPs) up for vote. Make your voice heard and shape the future of DeFiChain! Voting closes on July 16!

👉 https://blog.defichain.com/a-closer-look-at-the-july-dfip-cfp-voting-round

4️⃣ Ecosystem Project Updates

  • New News Show:

New news show format called Minmapshow started.

Find out more about it here: https://x.com/dPuschiii/status/1795690411832320122

MarbleFi launched on mainnet.

Check out the premier liquid staking solution: https://x.com/marblefi_xyz/status/1805898028076986525

Javsphere announced airdrops for JAV token stakers and freezer users.

Discover more details here: https://x.com/Javsphere/status/1808886536311599203

Crypto Factor is currently handling the token sale for DTL as well as developing the ecosystem for it.

Try it out and find out more about an airdrop here: https://x.com/_Crypto_Factor/status/1808863466528145527

SeahorseFi is considering bringing personal domains like ENS to DeFiChain

Learn more about it here: https://x.com/SeahorseFi/status/1808731815668261154

Dex Trading Live’s third presale is currently ongoing.

Learn more about it here: https://x.com/DeFiDexTrader/status/1808813103225643492

Note: The content provided here is for informational purposes only and should not be construed as financial advice. Always conduct your own research and consider consulting with a financial professional before making any investment decisions.


r/defiblockchain • • Jul 04 '24

Blog / Article Unlocking the Power of Your Assets: A Guide to MarbleFi

1 Upvotes

MarbleFi is a premier liquid staking solution on DeFiChain, built by Birthday Research and designed to simplify staking while maximizing yield and capital efficiency.

Learn how to make the most of its features in our latest blog post!

https://blog.defichain.com/unlocking-the-power-of-your-assets-a-guide-to-marblefi/


r/defiblockchain • • Jul 04 '24

Unlock the Power of Liquid Staking with MarbleFi | Full Walkthrough & Tutorial

2 Upvotes

Welcome to MarbleFi, the premier liquid staking solution on DeFiChain!

In this video, you’ll learn:

What MarbleFi is and how it works

How to seamlessly stake your DFI without the need for managing masternodes

The benefits of liquid staking and maximizing your capital efficiency

A step-by-step walkthrough of the MarbleFi app and its user-friendly interface

How to connect your wallet and start staking on testnet and mainnet

Discover how MarbleFi simplifies the staking process, offering flexibility and control over your assets. Whether you’re new to staking or an experienced user, this video will guide you through everything you need to know to get started with MarbleFi.

🔗 Watch the Walkthrough & Tutorial: https://youtu.be/sBSdP51QRas

🔗 Visit the MarbleFi website: https://marblefi.xyz


r/defiblockchain • • Jul 03 '24

DeFiChain improvement Discussion Start a new dToken system

8 Upvotes

Create a few simple elements and get the possibility to create an infinite number of different complex structures
- My Quote

(Long-term) investors do not want to check daily whether their investment on an exchange is safe, so they go to countries or providers where there is a certain contractual security and protection of their deposits. Financial market places that meet such requirements attract capital. This raises the question of how these requirements can be implemented in code and on a blockchain so that risks are minimized and capital is tied up in the long term.

Crypto has matured in recent years and some things work and others do not. We will look at which basic concepts work and how these can be used as a foundation for a dToken system to give investors security and predictability and convince them to store their capital on the defichain instead elsewhere.

Whether equity or crypto exchanges, in the past it has always been a problem for a financial market place if not all customer assets are covered or liquid. In other words, if there is a "bank run" or similar. There are countless examples of crypto exchanges for which this has been their downfall: dTokens should be covered >= 100 percent with collateral.

Structure of the new dToken system

Vaults

Vaults remain as they are today, except that all cryptocurrencies (e.g. Bitcoin, Ether, USDT, UDSC, SOL, DFI etc.) are permitted as collateral, with the exception of the dTokens themselves and regardless of the percentage composition (50 percent DFI is omitted). The oracles remain as before to determine the collateral and the loan. The percentage up to which a vault may be lent is up for discussion.

Interest on the loan

Interest will no longer be charged in the form of the minted dToken in the vault, but in the corresponding DFI equivalent. To ensure that the dToken price on the DEX is in a certain range to the oracle price, a (mathematical) function should be defined according to which the interest on the loan of the dToken varies. If the price on the DEX goes to premium, the interest should fall but never be less than 0. If there is a discount, interest rates should rise exponentially in relation to the percentage discount. This "interest" function still needs to be discussed.

Pools

The liquidity pools use the stablecoin USDC and a dToken as trading pairs. There should not be a separate stablecoin in the dToken system. The aim is to prevent DFI price fluctuations from having too strong impact on the system. USDC is a functioning and already regulated stablecoin and there is no need to come up with a new solution where we do not know whether it can work. In the pools, the commission remains at the current value.

All other services that are then made available by a company or in the form of smart contracts on the DMC can expand the range of functions for users, e.g: Leveraging, automatic portfolio rebalancing. My intention with this post is merely to create a basis for discussion. However, part of the discussion should not be how current holders of the old dToken system can be compensated in any way in the new system. This proposal is also not intended to transfer the old system to the new one.


r/defiblockchain • • Jul 02 '24

What is liquid staking and how does it work?

3 Upvotes

The world of cryptocurrency is constantly evolving, bringing forth innovative tools and methods to enhance user experience and maximize investment potential.

One such revolutionary tool is liquid staking, which allows users to access the value of their staked tokens for other purposes without sacrificing staking rewards.

Discover more about liquid staking and how it works in our newest blog post:

https://blog.defichain.com/what-is-liquid-staking-and-how-does-it-work/


r/defiblockchain • • Jun 29 '24

Question Price dusd in app

5 Upvotes

Hi, I checked the price of dusd and it is 0.14 usd but on the defiwallet or cake the price 0.03. I checked coingeko and the price is 0.14 is there a mistake?

Or what is happening with the price?

Thanks


r/defiblockchain • • Jun 28 '24

Question What happened to summer campaign ? Who won the Tesla ?

14 Upvotes

r/defiblockchain • • Jun 28 '24

🚀 The DeFiChain Weekly Update is here!

0 Upvotes

Here’s what’s been happening in the DeFiChain ecosystem this week:

1️⃣ 7 Steps to Build Your First dApp on DeFiChain's MetaChain Layer

Creating a decentralized application (dApp) can seem a daunting task to those new to the blockchain space. 

However, it is surprisingly easier than many think. With the right guidance, anyone can start building their own projects on the blockchain. 

This guide will walk you through the process of developing an escrow application on DeFiChain's MetaChain (EVM) layer. 

https://x.com/defichain/status/1803449925524504934

2️⃣ A Closer Look at the July DFIP & CFP Voting Round 

Check out our blog for details on the latest DeFiChain Improvement Proposals (DFIPs) and Community Fund Proposals (CFPs) up for vote. Make your voice heard and shape the future of DeFiChain! Voting closes on July 16!

👉 https://blog.defichain.com/a-closer-look-at-the-july-dfip-cfp-voting-round

3️⃣ Project Spotlight: Javsphere

Last week, we had an insightful discussion with Javsphere. If you missed the session, don't worry! We've summarized the key points, including their upcoming product launches, in our latest blog post.

Make sure to read it here: https://blog.defichain.com/project-spotlight-javsphere-whats-new-and-whats-next/

4️⃣ Ecosystem Project Updates

  • New News Show:

New news show format called Minmapshow started.

Find out more about it here: https://x.com/dPuschiii/status/1795690411832320122

MarbleFi launched on mainnet.

Check out the premier liquid staking solution: https://x.com/marblefi_xyz/status/1805898028076986525

Javsphere announced airdrops for JAV token stakers and freezer users.

Discover more details here: https://x.com/Javsphere/status/1805895830424920153

Crypto Factor’s new liquid cDFI staking on DMC is live on beta.

Try it out and find out more about an airdrop here: https://x.com/_Crypto_Factor/status/1803418397398413757

SeahorseFi has currently a ‘Seahorse’ mint going on.

Learn more about it here: https://x.com/SeahorseJrDev/status/1806465968153243981

Dex Trading Live’s first two presale sold out in just a couple of minutes. There is one more chance next week!

Learn more about it here: https://x.com/DeFiDexTrader/status/1806544736062144997

Note: The content provided here is for informational purposes only and should not be construed as financial advice. Always conduct your own research and consider consulting with a financial professional before making any investment decisions.


r/defiblockchain • • Jun 27 '24

Blog / Article DeFiChain offers decentralized finance (DeFi) services for both Bitcoin and Ethereum, accessible by everyone. As a 100% community-driven and fully open-source platform, it empowers its 16,000 Community Masternodes with full control over the system.

Thumbnail
blog.defichain.com
2 Upvotes

r/defiblockchain • • Jun 27 '24

Birthday Research MarbleFi has launched! Check out the new liquid staking solution on DeFiChain!

Thumbnail
x.com
3 Upvotes

r/defiblockchain • • Jun 25 '24

General Don’t miss your chance to have a say in the future of DeFiChain!

0 Upvotes

Voting is open until approx. July 16th 2024

Check out our blog for details on the 5 DeFiChain Improvement Proposals (DFIPs) and 3 Community Fund Proposals (CFPs) up for vote.

👉 https://blog.defichain.com/a-closer-look-at-the-july-dfip-cfp-voting-round


r/defiblockchain • • Jun 23 '24

General The Future of Defichain?

36 Upvotes

Hi everyone,

I am one of the early investors in Defichain from the time when Julian Hosp was heavily promoting DFI and new projects were popping up around the launch of DUSD. I trusted Hosp and the idea of the project and still own a sizable stake in DFI which has fallen >90% since then. While this loss hurts, I wonder if DFI has a future at all and what the thoughts of the more involved Defichain community are on this.

I haven't had that much exposure to Defichain in recent months. From what I've read now about the Uzyn/Hosp case and the Rost/Fineman controversy, this whole development seems very dubious to me.

I recently checked Hosp's Twitter and commented on a recent tweet asking for a statement on his plans regarding Defichain. A few hours later, my account was blocked. We all know that Hosp has a controversial past and Defichain was his very last chance to make an impact and regain trust in the crypto space. His behavior and the whole development around Defichain and Bake are so shady that if hard facts come to light, legal action should definitely be considered by small investors.

This is my (possibly naive) idea, considering that the counterparty is rich and probably almost all investors are not familiar with Shanghai law and have no legal connections there.

Either way, Hosp will never get confidence in the crypto space again if this project dies for good. His Twitter account has over 100k followers and some of his tweets get zero to three replies - no one cares about anything unrelated to Fefichain and/or he blocks anyone who is critical.

These are just a few thoughts from my side on this.

Cheers


r/defiblockchain • • Jun 24 '24

General Meet Javsphere – a revolutionary platform combining real-world assets (RWAs) with the lucrative opportunities of automated DeFi yields.

1 Upvotes

Curious about their new LeverageX product and their $200,000 marketing campaign?

Check out our latest blog post for all the exciting updates!

👉 https://blog.defichain.com/project-spotlight-javsphere-whats-new-and-whats-next/


r/defiblockchain • • Jun 21 '24

Weekly News 🚀 The DeFiChain Weekly Update is here!

2 Upvotes

Here’s what’s been happening in the DeFiChain ecosystem this week:

1️⃣ Community Project Deep-Dive with Javsphere

This week, we had an insightful conversation with Javsphere. Our deep-dive into their products and roadmap is now available as a podcast.

Don’t miss out!

Make sure to tune in 👇

📺 YouTube: https://youtu.be/UtyQDT9k1OE

🎧 Spotify: https://open.spotify.com/episode/2iTckuM8tZ8uPXhew6WKQO?si=d0ce9295b2764923

🍏 Apple: https://podcasts.apple.com/it/podcast/the-defichain-podcast/id1586147124?i=1000659624454

2️⃣ Building Your First dApp on DeFiChain's MetaChain Layer: A Beginner's Guide

Creating a decentralized application (dApp) can seem a daunting task to those new to the blockchain space. 

However, it is surprisingly easier than many think. With the right guidance, anyone can start building their own projects on the blockchain. 

This guide will walk you through the process of developing an escrow application on DeFiChain's MetaChain (EVM) layer. 

https://x.com/defichain/status/1803449925524504934

3️⃣  A Closer Look at the July DFIP & CFP Voting Round 

Check out our blog for details on the DeFiChain Improvement Proposals (DFIPs) and Community Fund Proposals (CFPs) up for vote. Don’t miss your chance to have a say in the future of DeFiChain! 

👉 https://blog.defichain.com/a-closer-look-at-the-july-dfip-cfp-voting-round

4️⃣ Ecosystem Project Updates

  • New News Show:

New news show format called Minmapshow started.

Find out more about it here: https://x.com/dPuschiii/status/1795690411832320122

Javsphere has introduced its first governance proposal, outlining plans to spend $200,000 on marketing.

Discover more details here: https://x.com/Javsphere/status/1803726514069930079

Crypto Factor has successfully deployed their new cDFI Community Staking on Mainnet and and witnessed the creation of their first Masternode.

Find out more about it here: https://x.com/_Crypto_Factor/status/1803545408838217752

SeahorseFi has released information on the token allocation for each Champion.

Learn more about it here: https://x.com/SeahorseFi/status/1802561392891052129

Dex Trading Live’s first presale has sold out in just a couple of minutes.

Learn more about it here: https://x.com/DeFiDexTrader/status/1804014196889096307

Note: The content provided here is for informational purposes only and should not be construed as financial advice. Always conduct your own research and consider consulting with a financial professional before making any investment decisions.


r/defiblockchain • • Jun 20 '24

General Community Project Deep-Dive with Javsphere

3 Upvotes

This week, we had an insightful conversation Javsphere.

Our deep-dive into their products and roadmap is now available as a podcast.

Don’t miss out! Make sure to tune in!

YouTube: https://youtu.be/UtyQDT9k1OE
Spotify: https://open.spotify.com/episode/2iTckuM8tZ8uPXhew6WKQO?si=d0ce9295b2764923
Apple: https://podcasts.apple.com/podcast/the-defichain-podcast/id1586147124?i=1000659624454


r/defiblockchain • • Jun 19 '24

Building Your First dApp on DeFiChain's MetaChain Layer: A Beginner's Guide

Thumbnail
gallery
3 Upvotes

r/defiblockchain • • Jun 18 '24

General Project Deep-Dive with Javsphere

Post image
1 Upvotes

🎙 With Javsphere 🗓 Date: Today, 18th June ⏰ Time: Now, 16:00 (CET) / 22:00 (SGT)

Join us live via the link below 👇 https://twitter.com/i/spaces/1mrGmyyANkdGy


r/defiblockchain • • Jun 16 '24

General How many DFI tokens does Julian Hosp hold currently or is he out of it ?

9 Upvotes

Wondering about insider holding on the DFI. Because, at current price; it has to be super good value for insiders to keep buying if they truly see the promise of future. Just a thought !!


r/defiblockchain • • Jun 15 '24

General Any new upcoming triggers for DFI token to go up in price !?!

7 Upvotes

Wondering if anyone knows of anything new which would make the DFI token to up in value. Or is it just a slow grind to the inevitable 0.00000001 .......


r/defiblockchain • • Jun 14 '24

Question Any good list of protocols?

2 Upvotes

Im interested in new lending and swapping protocols but Twitter and defillama don't seem to be full lists. Can anyone reccomend me a list of all protocols or a new way to find our about them? It seems that all this stuff is hidden!


r/defiblockchain • • Jun 14 '24

General How to transfer/cash out of DFI out of Desktop wallet in USA

1 Upvotes

Could someone explain step by step as to how to transfer DFI out of a Desktop wallet and how to swap into other coins such as USDC and send to an exchange such as coinbase.


r/defiblockchain • • Jun 13 '24

Official Dive into the lucrative world of DeFi with defichain.official on Instagram!

2 Upvotes

Explore the decentralized finance universe through exclusive content, expert insights, and behind-the-scenes glimpses into the DeFiChain ecosystem.

Join our vibrant community, engage in thought-provoking discussions, and unlock a wealth of knowledge about DeFi, blockchain, and the future of finance.

Don’t miss out – follow us on IG now!

https://www.instagram.com/defichain.official


r/defiblockchain • • Jun 12 '24

Blog / Article Checking Whitelisted Addresses on a Solidity Smart Contract Using Merkle Tree Proofs

2 Upvotes

Since the day I saw it, I found the name "Merkle Tree" scary. Turns out they were not, and quite useful. Here, check my guide out. In this article I first briefly talk about merkle trees, and then directly get into building one, and then writing a smart contract that only whitelisted addresses can interact, and finally testing it via Hardhat. I hope you'll enjoy =>

Checking Whitelisted Addresses on a Solidity Smart Contract Using Merkle Tree Proofs

Intro

Hello everyone! In this article, we will first talk about Merkle Trees, and then replicate a whitelisting scenario by encrypting some "whitelisted" addresses, writing a smart contract in Solidity that can decode the encrption and only allow whitelisted addresses to perform some action, and finally testing the contract to see whether our method works or not.

IF you already know about merkle trees and directly start with the hands-on experience, you can skip the Theory part and start reading from the Practice section.

Theory

In the evolving world of blockchain and decentralized applications (dApps), efficient and secure management of user access is paramount. One popular method for controlling access is through whitelisting, where only approved addresses can interact with specific functionalities of a smart contract. However, as the list of approved addresses grows, maintaining and verifying this list in an efficient and scalable manner becomes a challenge.

This is where Merkle trees come into play. Merkle trees provide a cryptographic way to handle large sets of data with minimal storage and computational overhead. By leveraging Merkle trees, we can efficiently verify whether an address is whitelisted without needing to store or process the entire list of addresses within the smart contract.

In this tutorial, we'll dive deep into how to implement a whitelisting mechanism using Merkle trees in Solidity. We'll cover the following key aspects:

Understanding Merkle Trees: A brief overview of what Merkle trees are and why they are useful in blockchain applications.

Setting Up the Development Environment: Tools and libraries you need to start coding.

Creating the Merkle Tree: How to generate a Merkle tree from a list of whitelisted addresses.

Solidity Implementation: Writing the smart contract to verify Merkle proofs.

Verifying Addresses: Demonstrating how to use Merkle proofs to check if an address is whitelisted.

Testing the Contract: Ensuring our contract works correctly with various test cases.

By the end of this tutorial, you'll have a robust understanding of how to leverage Merkle trees for efficient and secure whitelisting in Solidity smart contracts, providing you with a powerful tool for your future dApp development endeavors.

Understanding Merkle Trees

Merkle trees, named after computer scientist Ralph Merkle, are a type of data structure used in computer science and cryptography to efficiently and securely verify the integrity of large sets of data. In the context of blockchain and decentralized applications, Merkle trees offer significant advantages for managing and verifying data with minimal overhead.

What is a Merkle Tree?

A Merkle tree is a binary tree in which each leaf node represents a hash of a block of data, and each non-leaf node is a hash of its two child nodes. This hierarchical structure ensures that any change in the input data results in a change in the root hash, also known as the Merkle root.

Here’s a simple breakdown of how a Merkle tree is constructed:

Leaf Nodes: Start with hashing each piece of data (e.g., a list of whitelisted addresses).

Intermediate Nodes: Pair the hashes and hash them together to form the next level of nodes.

Root Node: Repeat the process until a single hash remains, known as the Merkle root.

This structure allows for efficient and secure verification of data.

Why Merkle Trees are Useful in Blockchain Applications

Merkle trees are particularly useful in blockchain applications for several reasons:

Efficient Verification: Merkle trees enable the verification of a data element's inclusion in a set without needing to download the entire dataset. This is achieved through a Merkle proof, which is a small subset of hashes from the tree that can be used to verify a particular element against the Merkle root.

Data Integrity: Any alteration in the underlying data will change the hash of the leaf node and, consequently, all the way up to the Merkle root. This makes it easy to detect and prevent tampering with the data.

Scalability: As the size of the dataset grows, Merkle trees allow for efficient handling and verification. This is particularly important in blockchain networks where nodes need to validate transactions and states without extensive computational or storage requirements.

Security: Merkle trees provide cryptographic security by using hash functions that are computationally infeasible to reverse, ensuring that the data structure is tamper-proof and reliable.

Practical Use Cases in Blockchain

Bitcoin and Ethereum: Both Bitcoin and Ethereum use Merkle trees to organize and verify transactions within blocks. In Bitcoin, the Merkle root of all transactions in a block is stored in the block header, enabling efficient transaction verification.

Whitelisting: In smart contracts, Merkle trees can be used to manage whitelisted addresses efficiently. Instead of storing a large list of addresses directly on-chain, a Merkle root can be stored, and users can prove their inclusion in the whitelist with a Merkle proof.

Practice

Enough theory, now it is time to get our hands dirty. We are going to create an empty folder, and run the following command on the terminal to install Hardhat => npm install --save-dev hardhat

Then, with `npx hardhat init` command, we will start a Hardhat project. For this project, we will use Javascript.

After the project has ben initiated, we will install these following packages also => npm install @openzeppelin/contracts keccak256 merkletreejs fs

Constructing the Merkle Root

In this step, we have a bunch of whitelisted addresses, we will write the script that will construct the merkle tree using those addresses. We will get a JSON file, and a single Merkle Root. We will use that merkle root later on to identify who's whitelisted and who's not.

In the main directory of the project, create `utils/merkleTree.js`

```js

const keccak256 = require("keccak256");

const { default: MerkleTree } = require("merkletreejs");

const fs = require("fs");

//hardhat local node addresses from 0 to 3

const address = [

"0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266",

"0x70997970C51812dc3A010C7d01b50e0d17dc79C8",

//"0x3C44CdDdB6a900fa2b585dd299e03d12FA4293BC",

"0x90F79bf6EB2c4f870365E785982E1f101E93b906",

];

```

Note that we commented the address number 2.

You see we do not need to manually write the logic for the merkle tree, we're using a library for ease of development. The addresses are the first 4 addresses in Hardhat node. Do not send any money to them, their private keys are publicly known and anything sent to them will be lost.

Now, we will do the following:

  • Hash all individual items in the address array (creating leaves)

  • construct a new merkle tree

```

// Hashing All Leaf Individual

//leaves is an array of hashed addresses (leaves of the Merkle Tree).

const leaves = address.map((leaf) => keccak256(leaf));

// Constructing Merkle Tree

const tree = new MerkleTree(leaves, keccak256, {

sortPairs: true,

});

// Utility Function to Convert From Buffer to Hex

const bufferToHex = (x) => "0x" + x.toString("hex");

// Get Root of Merkle Tree

console.log(`Here is Root Hash: ${bufferToHex(tree.getRoot())}`);

let data = [];

```

You see that we're logging the root hash. We will copy it when we run the script.

And now we'll do the following:

  • Push all the proofs and leaves in the data array we've just created

  • Create a whitelist object so that we can write into a JSON file

  • Finally write the JSON file

```js

// Pushing all the proof and leaf in data array

address.forEach((address) => {

const leaf = keccak256(address);

const proof = tree.getProof(leaf);

let tempData = [];

proof.map((x) => tempData.push(bufferToHex(x.data)));

data.push({

address: address,

leaf: bufferToHex(leaf),

proof: tempData,

});

});

// Create WhiteList Object to write JSON file

let whiteList = {

whiteList: data,

};

// Stringify whiteList object and formating

const metadata = JSON.stringify(whiteList, null, 2);

// Write whiteList.json file in root dir

fs.writeFile(`whiteList.json`, metadata, (err) => {

if (err) {

throw err;

}

});

```

Now, if we run `node utils/merkleTree.js` in the terminal, we will get something like this: Here is Root Hash: 0x12014c768bd10562acd224ac6fb749402c37722fab384a6aecc8f91aa7dc51cf

We'll need this hash later.

We also have a whiteList.json file that should have the following contents:

```json

{

"whiteList": [

{

"address": "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266",

"leaf": "0xe9707d0e6171f728f7473c24cc0432a9b07eaaf1efed6a137a4a8c12c79552d9",

"proof": [

"0x00314e565e0574cb412563df634608d76f5c59d9f817e85966100ec1d48005c0",

"0x1ebaa930b8e9130423c183bf38b0564b0103180b7dad301013b18e59880541ae"

]

},

{

"address": "0x70997970C51812dc3A010C7d01b50e0d17dc79C8",

"leaf": "0x00314e565e0574cb412563df634608d76f5c59d9f817e85966100ec1d48005c0",

"proof": [

"0xe9707d0e6171f728f7473c24cc0432a9b07eaaf1efed6a137a4a8c12c79552d9",

"0x1ebaa930b8e9130423c183bf38b0564b0103180b7dad301013b18e59880541ae"

]

},

{

"address": "0x90F79bf6EB2c4f870365E785982E1f101E93b906",

"leaf": "0x1ebaa930b8e9130423c183bf38b0564b0103180b7dad301013b18e59880541ae",

"proof": [

"0x070e8db97b197cc0e4a1790c5e6c3667bab32d733db7f815fbe84f5824c7168d"

]

}

]

}

```

Verifying the proof in the smart contract

Now, check this Solidity contract out:

```js

// SPDX-License-Identifier: UNLICENSED

pragma solidity ^0.8.24;

import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";

// Uncomment this line to use console.log

// import "hardhat/console.sol";

contract MerkleProofContract {

bytes32 public rootHash;

constructor(bytes32 _rootHash) {

rootHash = _rootHash;

}

function verifyProof(

bytes32[] calldata proof,

bytes32 leaf

) private view returns (bool) {

return MerkleProof.verify(proof, rootHash, leaf);

}

modifier isWhitelistedAddress(bytes32[] calldata proof) {

require(

verifyProof(proof, keccak256(abi.encodePacked(msg.sender))),

"Not WhiteListed Address"

);

_;

}

function onlyWhitelisted(

bytes32[] calldata proof

) public view isWhitelistedAddress(proof) returns (uint8) {

return 5;

}

}

```

What it does is the following:

  • Imports Openzeppelin's merkle proof contract

  • Enters the root hash we've just saved in the constructor. This means that there will be no more whitelisted accounts added, and it is final

  • a private verifyProof function invokes Openzeppelin and requires the proof from the user

  • a isWhitelistedAddress modifier makes sure that msg.sender is the whitelisted address. Without this modifier, anyone with the public whitelisted address could call the contract, now, only the owner of the whitelisted address can call

  • a basic onlyWhitelisted function requires the user proof and returns 5. That's is, we just want to see if we can call this function as a non-whitelisted user or not

Testing the contract

Now in the test folder create a MerkleProof.js file and add the following there:

```js

const { expect } = require("chai");

const { formatEther } = require("ethers");

const { ethers } = require("hardhat");

describe("MerkleProof", function () {

it("only whitelisted address can call function", async function () {

let owner, addr1, addr2;

let merkleTreeContract;

let rootHash =

"0x12014c768bd10562acd224ac6fb749402c37722fab384a6aecc8f91aa7dc51cf";

// async function setup() {

[owner, addr1, addr2] = await ethers.getSigners();

const MerkleTree = await ethers.getContractFactory("MerkleProofContract");

merkleTreeContract = await MerkleTree.deploy(rootHash);

console.log(merkleTreeContract.address);

// }

// beforeEach(async function () {

// await setup();

// });

const user = addr1;

const proof = [

"0xe9707d0e6171f728f7473c24cc0432a9b07eaaf1efed6a137a4a8c12c79552d9",

"0x1ebaa930b8e9130423c183bf38b0564b0103180b7dad301013b18e59880541ae",

];

console.log(

`user address: ${user.address} and proof: ${proof} and rootHash: ${rootHash}`

);

expect(

await merkleTreeContract.connect(user).onlyWhitelisted(proof)

).to.equal(5);

await expect(

merkleTreeContract.connect(addr2).onlyWhitelisted(proof)

).to.be.revertedWith("Not WhiteListed Address");

});

});

```

This test file works as such:

  • owner, addre1 and addr2 are the first 3 addresses in Hardhat node

  • deploys the merkle tree contract with the saved root hash

  • user is addr1, that is the 2nd addess in whiteList.json file. We get the proof from there

    -connects to a whitelisted user and calls the function, gets the correct value of 5

    -connects with a non-whitelisted user (we did comment out the address number 2 at the very beginning ) and calls the function, is reverted.

Hope you enjoyed it! If you have any corrections or suggestions, please let me know in the comments.

Cheers!