aelf 백서

bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 41쪽 중 17쪽

x has a MainChain height greater than validateTokenInfoExist's let heightDone = false ; while ( ! heightDone ) { // get latest index Hight const sideIndexMainHeight = await GetParentChainHeight ( ) ; if ( // check the latest index Hight is grater than or equal sideIndexMainHeight >= VALIDATE_TXRESULT . Transaction . RefBlockNumber ) { VALIDATE_TXRESULT = await aelf . chain . getTxResult ( VALIDATE_TXID ) ; heightDone = true ; } } console . log ( VALIDATE_TXRESULT , "VALIDATE_TXRESULT=====2" ) ; const merklePath = await getMerklePathByTxId ( aelf , VALIDATE_TXID ) ; toast . update ( validateNFTLoadingId , { render : "Validating NFT Successfully Executed" , type : "success" , isLoading : false , } ) ; removeNotification ( validateNFTLoadingId ) ; // return necessary values return { parentChainHeight : VALIDATE_TXRESULT . BlockNumber , signedTx : signedTx , merklePath : merklePath , } ; } catch ( error ) { toast . update ( validateNFTLoadingId , { render : error . message , type : "error" , isLoading : false , } ) ; removeNotification ( validateLoadingId ) ; return "error" ; } } ; Here's what the function does: ​ Displays Loading Toast: Shows a notification indicating that the NFT validation is in progress on the blockchain. Prepares Validation Input: Constructs the input parameters needed for validating the NFT token. Gets Token Contract: Retrieves the token contract instance from the MainChain. Signs and Sends Transaction: Signs the transaction to validate the token info and sends it to the blockchain. Polls for Transaction Result: Waits for the transaction result and ensures the transaction has reached the required block height. Fetches Merkle Path: Retrieves the Merkle path for the validated transaction. Handles Success: Updates the notification to show successful validation and returns necessary values. Handles Errors: Logs errors and returns "error" if something goes wrong. Step 3: Write a Function for Create NFT on dAppChain Now, let's write the Create NFT on dAppChain function. Scroll down to find the comment // step 8 - Create a NFT on dAppChain . Replace the existing createNftTokenOnSideChain function with this code snippet: create-nft/index.tsx // step 8 - Create a NFT on dAppChain. const createNftTokenOnSideChain = async ( values : INftValidateResult ) => { let createSideChainNFTLoadingId ; try { createSideChainNFTLoadingId = toast . loading ( "Creating NFT on SideChain..." ) ; const CROSS_CHAIN_CREATE_TOKEN_PARAMS = { fromChainId : mainchain_from_chain_id , parentChainHeight : values . parentChainHeight , transactionBytes : Buffer . from ( values . signedTx , "hex" ) . toString ( "base64" ) , merklePath : values . merklePath , } ; await sideChainSmartContract ?. callSendMethod ( "CrossChainCreateToken" , currentWalletAddress , CROSS_CHAIN_CREATE_TOKEN_PARAMS ) ; toast . update ( createSideChainNFTLoadingId , { render : "NFT Created Successfully On SideChain" , type : "success" , isLoading : false , } ) ; removeNotification ( createSideChainNFTLoadingId ) ; return "success" ; } catch ( error ) { toast . update ( createSideChainNFTLoadingId , { render : error . message , type : "error" , isLoading : false , } ) ; removeNotification ( createSideChainNFTLoadingId ) ; return "error" ; } } ; Here's what the function does: ​ Displays Loading Toast: Shows a notification indicating that the NFT is being created on the dAppChain. Prepares Cross-Chain Transaction Parameters: Constructs the parameters needed for creating the NFT on the dAppChain, including chain IDs, block height, transaction data, and Merkle path. Calls Smart Contract Method: Sends the transaction to the dAppChain smart contract to create the NFT. Handles Success: Updates the notification to show successful NFT creation on the dAppChain. Handles Errors: Logs errors and returns "error" if something goes wrong. Step 4: Write a Function for Issue NFT Token which has been Created on dAppChain. Now, let's write the Issue NFT Function. Scroll down to find the comment // step 9 - Issue a NFT Function which has been Created on dAppChain . Replace the existing issueNftOnSideChain function with this code snippet: create-nft/index.tsx // step 9 - Issue a NFT Function which has been Created on dAppChain const issueNftOnSideChain = async ( values : { symbol : string ; amount : string ; memo : string ; } ) => { let issuingNFTLoadingId try { issuingNFTLoadingId = toast . loading ( "Issuing NFT on SideChain..." ) ; const issueNftInput = { symbol : values . symbol , amount : values . amount , memo : values . memo , to : currentWalletAddress , } ; const result = await sideChainSmartContract ?. callSendMethod ( "Issue" , currentWalletAddress , issueNftInput ) ; console . log ( "========= result of createNewNft =========" , result ) ; toast . update ( issuingNFTLoadingId , { render : "NFT Issue Successfully Executed" , type : "success" , isLoading : false , } ) ; removeNotification ( issuingNFTLoadingId ) ; toast . success ( "You will get NFT on your Wallet! It can take sometimes to get into your wallet" ) ; handleReturnClick ( ) ; return "success" ; } catch ( error : any ) { toast . update ( issuingNFTLoadingId , { render : error . message , type : "error" , isLoading : false , } ) ; removeNotification ( issuingNFTLoadingId ) ; setTransactionStatus ( false ) ; return "error" ; } } ; Here's what the function does: ​ Displays Loading Toast: Shows a notification indicating that the NFT is being issued on the dAppChain. Prepares Issuance Input: Constructs the input parameters for issuing the NFT, including symbol, amount, memo, and recipient address. Calls Smart Contract Method: Sends the transaction to the dAppChain smart contract to issue the NFT. Handles Success: Updates the notification to show successful issuance and notifies the user that the NFT will appear in their wallet. Handles Errors: Logs and displays any error messages, updates the transaction status, and returns "error" . Step 5: Create a Function to Call Necessary Functions for NFT Creation Now, let's write the createNftToken Function. Scroll down to find the comment // step 10 - Call Necessary Function for Create NFT . Replace the existing createNftToken function with this code snippet: create-nft/index.tsx // step 10 - Call Necessary Function for Create NFT const createNftToken = async ( values : INftParams ) => { try { const mainChainResult = await createNFTOnMainChain ( values ) ; if ( mainChainResult === "error" ) { setTransactionStatus ( false ) ; return ; } await delay ( 3000 ) ; const validateNFTData : INftValidateResult | "error" = await validateNftToken ( values ) ; if ( validateNFTData === "error" ) { setTransactionStatus ( false ) ; return ; } const sideChainResult = await createNftTokenOnSideChain ( validateNFTData ) ; if ( sideChainResult === "error" ) { setTransactionStatus ( false ) ; return ; } await issueNftOnSideChain ( { symbol : values . symbol , amount : values . totalSupply , memo : "We are issuing nftToken" , } ) ; setTransactionStatus ( false ) ; } catch ( error : any ) { console . error ( error , "=====error" ) ; setTransactionStatus ( false ) ; toast . error ( error ) ; return "error" ; } } ; Here's what the function does: ​ Creates NFT on MainChain: Calls createNFTOnMainChain to create the NFT on the MainChain. If it fails, it updates the transaction status and exits. Validates NFT Token: Waits for 3 seconds, then calls validateNftToken to validate the NFT. If validation fails, it updates the transaction status and exits. Creates NFT on dAppChain: Calls createNftTokenOnSideChain to create the NFT on the dAppChain using the validated data. If it fails, it updates the transaction status and exits. Issues NFT on dAppChain: Calls issueNftOnSideChain to issue the NFT. Updates the transaction status to false after completion. Handles Errors: Catches and logs any errors, updates the transaction status, and displays an error notification. Configure Submit Form ​ Now, let's Write a Function to Call Necessary Functions for NFT Creation. Scroll down to find the comment // Step 11 - Handle Submit Form . Replace the existing onSubmit function with this code snippet: create-nft/index.tsx //Step 11 - Handle Submit Form const onSubmit = async ( values : z . infer < typeof formSchema > ) => { setTransactionStatus ( true ) ; if ( isNftCollectionCreated ) { // Already Collection Created // create NFT Token await createNftToken ( values ) ; } else { // create NFT Collection on MainChain const createResult = await createNftCollectionOnMainChain ( values ) ; if ( createResult === "error" ) { setTransactionStatus ( false ) ; return ; } // Validate NFT Collection const validateCollectionResult = await validateNftCollectionInfo ( createResult ) ; if ( validateCollectionResult === "error" ) { setTransactionStatus ( false ) ; return ; } // create NFT Collection on dAppChain await createCollectionOnSideChain ( validateCollectionResult . transactionId , validateCollectionResult . signedTx , validateCollectionResult . BlockNumber ) ; } } ; Here's what the function does: ​ Starts Transaction: Sets the transaction status to true. Checks NFT Collection Status: If the NFT collection is already created, calls createNftToken to create the NFT token. Creates and Validates NFT Collection: If the collection isn’t created, calls createNftCollectionOnMainChain to create it. If successful, validates the NFT collection with validateNftCollectionInfo . Creates Collection on dAppChain: If validation is successful, calls createCollectionOnSideChain to create the collection on the dAppChain. Handles Errors: Updates the transaction status to false and exits if any step fails. Fetch NFT Data ​ Let's write the Function for the fetch NFT data from user's Wallet using API. Step 1: Locate the File go to the src/lib/commonFunctions.ts file. Step 2: Write the Helper Functions for fetch the NFT data The commonFunctions.ts file is contains the helpers function for fetch NFT and etc. Find the comment // Function to get the balance of a specific NFT . Replace the existing getBalanceOfNft function with this code snippet: commonFunctions.ts // Function to get the balance of a specific NFT const getBalanceOfNft = async ( values : { symbol : string , owner : string , } , sideChainSmartContract : any ) : Promise < number > => { // @ts-ignore const { data } : { data : { balance : number } } = await sideChainSmartContract ?. callViewMethod ( "getBalance" , values ) ; return data . balance ; } ; Here's what the function does: ​ Retrieves NFT Balance: The function getBalanceOfNft fetches the balance of a specific NFT for a given owner. Parameters: It takes two parameters: values : An object containing the symbol of the NFT and the owner address. sideChainSmartContract : An instance of the side chain smart contract. Calls View Method: It calls the getBalance view method on the side chain smart contract with the provided values . Returns Balance: It extracts the balance from the response and returns it as a number. Find the comment // Function to fetch balance information for an array of NFTs . Replace the existing fetchNftBalances function with this code snippet: commonFunctions.ts // Function to fetch balance information for an array of NFTs const fetchNftBalances = async ( nfts : Nft [ ] , ownerAddress : string , sideChainSmartContract : any ) : Promise < Nft [ ] > => { const nftDataWithBalances = await Promise . all ( nfts . map ( async ( nft ) => { const balance = await getBalanceOfNft ( { symbol : nft . nftSymbol , owner : ownerAddress , } , sideChainSmartContract ) ; return { ... nft , balance } ; } ) ) ; return nftDataWithBalances ; } ; Here's what the function does: ​ Fetches Balances for Multiple NFTs: The function fetchNftBalances retrieves balance information for an array of NFTs for a specific owner. Parameters: It takes three parameters: nfts : An array of Nft objects, each representing an NFT. ownerAddress : A string representing the address of the owner. sideChainSmartContract : An instance of the side chain smart contract. Maps NFTs to Balances: It uses Promise.all to concurrently fetch the balance for each NFT by calling the getBalanceOfNft function. Combines NFT Data with Balances: For each NFT, it combines the existing NFT data with the fetched balance. Returns Updated NFT Array: It returns a new array of Nft objects, each including its respective balance. Find the comment // fetch NFT Data from eforest API . Replace the existing fetchUserNftData function with this code snippet: commonFunctions.ts // fetch NFT Data from eforest API export const fetchUserNftData = async ( currentWalletAddress : string , sideChainSmartContract : any ) => { try { const response = await fetch ( "https://test.eforest.finance/api/app/nft/nft-infos-user-profile/myhold" , { method : "POST" , headers : { "Content-Type" : "application/json" , } , body : JSON . stringify ( { ChainList : [ "tDVV" ] , hasListingFlag : false , hasAuctionFlag : false , hasOfferFlag : false , collectionIds : [ ] , address : currentWalletAddress , sorting : "ListingTime DESC" , } ) , } ) ; if ( ! response . ok ) { throw new Error ( "Network response was not ok" ) ; } const responseData = await response . json ( ) ; const newNftData = await fetchNftBalances ( responseData . data . items , currentWalletAddress as string , sideChainSmartContract ) ; return newNftData ; } catch ( error ) { console . log ( error ) ; return "error" } } ; Here's what the function does: ​ Fetches User NFT Data: The function fetchUserNftData retrieves NFT data for a specific user from the eforest API and fetches balance information for each NFT. Parameters: It takes two parameters: currentWalletAddress : A string representing the wallet address of the user. sideChainSmartContract : An instance of the side chain smart contract. API Request: It makes a POST request to the eforest API endpoint https://test.eforest.finance/api/app/nft/nft-infos-user-profile/myhold with the user's wallet address and some other parameters. Checks Response: It checks if the response from the API is okay. If not, it throws an error. Parses Response: It parses the JSON response from the API. Fetches NFT Balances: It calls fetchNftBalances to get the balance for each NFT in the response data. Returns Updated NFT Data: It returns the updated NFT data, each including its respective balance. Handles Errors: If any error occurs during the process, it logs the error and returns the string "error". We have Prepared all necessary function for fetch NFT Data from User's Wallet. Now, Let's call fetchUserNftData on necessary page. Step 3: Call fetchUserNftData Functions on Home Page go to the src/pages/home/index.tsx file. The home/index.tsx file contains the Home Page of NFT dApp Find the comment // get NFT Data from User's wallet . Replace the existing getNFTData function with this code snippet: home/index.tsx // get NFT Data from User's wallet const getNFTData = async ( ) => { const result = await fetchUserNftData ( currentWalletAddress as string , sideChainSmartContract ) ; if ( result !== "error" ) { setUserNfts ( result ) ; } setLoading ( false ) ; } ; Here's what the function does: ​ Fetches NFT Data: The function getNFTData retrieves NFT data from the user's wallet. Calls Fetch Function: It calls the fetchUserNftData function with the currentWalletAddress and sideChainSmartContract parameters. Handles Result: It checks the result: If the result is not "error", it updates the state with the fetched NFT data by calling setUserNfts(result) . Updates Loading State: Regardless of the result, it sets the loading state to false by calling setLoading(false) . Step 4: Call fetchUserNftData Functions on Profile Page go to the src/pages/profile/index.tsx file. The profile/index.tsx file contains the Home Page of NFT dApp Find the comment // get NFT Data from User's wallet . Replace the existing getNFTData function with this code snippet: profile/index.tsx // get NFT Data from User's wallet const getNFTData = async ( ) => { const result = await fetchUserNftData ( currentWalletAddress as string , sideChainSmartContract ) ; if ( result !== "error" ) { setUserNfts ( result ) ; } setLoading ( false ) ; } ; Here's what the function does: ​ Fetches NFT Data: The function getNFTData retrieves NFT data from the user's wallet. Calls Fetch Function: It calls the fetchUserNftData function with currentWalletAddress and sideChainSmartContract as arguments. Handles Successful Result: If the result from fetchUserNftData is not "error": It updates the user's NFTs by calling setUserNfts(result) . Updates Loading State: It sets the loading state to false by calling setLoading(false) , regardless of whether the fetch was successful or not. Transfer NFT Token ​ As we have completed Create and Fetch NFT so now it's time to Transfer NFT . So now let's Transfer NFT to other wallet now. Step 1: Locate the File go to the src/pages/transfer-nft/index.tsx file. This file is the Transfer NFT page where users can enter details like the address , amount and memo . Step 2: Prepare Form for Transfer NFT Find the comment // Configure NFT Transfer Form . Replace the form variable with this code snippet: transfer-nft/index.tsx // Configure NFT Transfer Form const form = useForm < z . infer < typeof formSchema >> ( { resolver : zodResolver ( formSchema ) , defaultValues : { address : "" , amount : 0 , memo : "" , } , } ) ; Here's what the function does: ​ Initializes a new form variable with default values needed to transfer a nft. Fields include: address , amount , and memo . Now your form is ready for users to fill in the necessary details for their NFTs Transfer function Interaction. Step 3: Create NFT Transfer Function Find the comment // Transfer NFT to Other Wallet . Replace the form variable with this code snippet: transfer-nft/index.tsx // Transfer NFT to Other Wallet const transferNftToOtherAccount = async ( values : { address : string ; amount : string ; memo : string ; } ) => { if ( Number ( values . amount ) > Number ( nftBalance ) ) { toast . error ( "Amount must be Less than or Equal to Supply Balance" ) ; return ; } const transferNFTLoadingId = toast . loading ( "Transfer Transaction Executing" ) ; try { const transferNtfInput = { to : values . address , symbol : nftSymbol , amount : + values . amount , memo : values . memo , } ; await sideChainSmartContract ?. callSendMethod ( "Transfer" , currentWalletAddress , transferNtfInput ) ; toast . update ( transferNFTLoadingId , { render : "NFT Transferred Successfully!" , type : "success" , isLoading : false , } ) ; removeNotification ( transferNFTLoadingId ) ; await delay ( 3000 ) ; handleReturnClick ( ) ; } catch ( error : any ) { console . error ( error . message , "=====error" ) ; toast . error ( error . message ) ; } } ; Here's what the function does: ​ Transfers NFT to Another Wallet: The function transferNftToOtherAccount transfers a specified amount of an NFT to another wallet. Parameters: It takes a values object containing: address : The destination wall
프로젝트로 돌아가기