DEV Community

ASHDEEP SINGH
ASHDEEP SINGH

Posted on

Dapp final iv

This week of learning blockchain , we completed the blockchain project we were doing. Almost all the functionalities were done but we just needed to integrate the token market place in our project. This is how we do it.

Github

First we introduce Token market place page to do the following :

1. Initialization of Contracts
We're initializing the ERC-20 token contract (erc20ContractInstance) and Token Marketplace contract (tokenMarketplaceInstance) inside useEffect hooks.

2. Handling Asynchronous Initialization
While contract instantiations usually execute synchronously, it's often a good idea to treat these operations as asynchronous functions.

Further We'll use some different components :



return (
    <>
     <TokenBalance erc20ContractInstance={erc20ContractInstance}/>
     <br/>
     <TokenPrice contractInstance ={tokenMarketplaceInstance}/>
     <br/>
     <BuyToken contractInstance ={tokenMarketplaceInstance}/>
     <br/>
     <SellToken erc20ContractInstance={erc20ContractInstance} contractInstance ={tokenMarketplaceInstance}/>

    </>);


Enter fullscreen mode Exit fullscreen mode

BuyToken
The BuyToken component is a React component that allows users to purchase tokens using the connected contract instance. It takes contractInstance as a prop, which is the initialized smart contract that includes the method for purchasing tokens. Inside the component, useRef is used to reference the token amount input field. The buyToken function is called when the form is submitted, preventing the default form submission behavior with e.preventDefault(). It then retrieves the token amount entered by the user, converts it from ETH to Wei using ethers.parseEther(), and calls the buyGLDToken method on the contract with the converted value and a gas limit of 300,000. If the transaction is successful, the receipt is logged to the console, and in case of an error, it is caught in a try-catch block, displaying an error message via toast for user feedback. The form captures user input and has a submit button to trigger the purchase.

SellToken
The SellToken component enables users to sell tokens and approve a token marketplace to spend tokens on their behalf, both utilizing smart contract functions. It takes two contract instances as props: contractInstance (representing the marketplace contract) and erc20ContractInstance (for interacting with the ERC-20 token contract). The component uses useRef to track user input for both selling and approving tokens. The sellToken function is triggered when the user submits the form, converting the entered token amount from ETH to Wei using ethers.parseEther(), and then calls the marketplace's sellGLDToken method to sell the tokens. It awaits the transaction and logs the receipt if successful, handling errors with toast for user feedback. Similarly, the approveToken function handles approval, allowing the marketplace contract to spend the user's tokens. It also converts the input from ETH to Wei and calls the approve method on the ERC-20 contract with the marketplace's address and the specified token amount. Both functions use async/await to handle asynchronous blockchain transactions, providing a smooth interaction experience for the user.

TokenBalance
The TokenBalance component retrieves and displays the user's token balance using the provided ERC-20 contract instance. It relies on the useWeb3Context hook to access the current Web3 state, specifically the selectedAccount, which holds the user's Ethereum account address. The balance is fetched by calling the balanceOf method on the erc20ContractInstance, which returns the user's token balance in Wei (the smallest unit of Ether). This balance is then converted from Wei to Ether using ethers.formatEther(). The balance is stored in the userTokenBalance state variable using useState, which initially starts at "0". The useEffect hook triggers the fetchTokenBalance function whenever the erc20ContractInstance or selectedAccount changes. If the balance fetch fails, an error is caught and logged, and a toast.error message is displayed to inform the user. The balance is rendered in the component, providing a seamless experience for users to see their token holdings.

TokenPrice
The TokenPrice component fetches and displays the price of a token by interacting with the provided contract instance. The component uses useState to store the token price in the tokenPrice state variable, which is initially set to null. The useEffect hook triggers whenever the contractInstance is available, calling the fetchTokenPrice function to retrieve the token price from the smart contract. This price is fetched in Wei using the tokenPrice() method on the contract, then converted to Ether using ethers.formatEther() before being stored in the state variable. If an error occurs during this process, a toast.error message is displayed to notify the user, and the error is logged to the console for debugging. The token price is rendered within the component, giving users real-time access to the current price in Ether.

That's all for this week folks.

Stay tuned for more.

Top comments (0)