Alchemy: Create a Full-Stack dApp

Learn how to create a full-stack dApp for minting NFTs using Alchemy and Filebase.

What is a dApp?

Decentralized applications, known as dApps, are open-source applications developed using cryptocurrency and smart contracts, then deployed on a blockchain network.

In this tutorial, we’ll launch an example dApp built with Alchemy and React on the Ethereum Testnet Ropsten. Then, we’ll create a series of functions that allow us to mint an NFT that uses an image asset stored on the IPFS network through Filebase.

Read below to learn how to create a full-stack dApp for minting NFTs using Alchemy and Filebase.

Prerequisites:

This tutorial assumes you know what NFTs are and how the NFT minting process works. For more information on NFTs and how they’re minted, check out our deep dive on NFTs here.

1. Start by cloning the Github repository for this project:

git clone https://github.com/alchemyplatform/nft-minter-tutorial

This repo contains two directories, minter-starter-files and nft-minter. We’ll be using the nft-minter tutorial directory, so navigate inside of that:

cd nft-minter-tutorial

2. Next, install the alchemy-web3 package:

npm install @alch/alchemy-web3

3. Navigate to the minter-starter-files directory:

cd minter-starter-files

4. Next, install the required dependencies of the project:

npm install

Then start the app with the command:

npm start

5. Your default app will be launched at http://localhost:3000. It should look like this:

6. Now let’s edit this app. Open the file located in the src directory called Minter.js and open this file in your code editor of choice.

This file has 3 main sections:

  • State Variables: This section contains variables such as walletAddress, status, name, description, and URL. These variables will be used to store information about our NFT and its status inside the dApp.

  • Functions: These functions are unimplemented as the code currently stands, and are used to run functions in the dApp like connecting your wallet to the app, and minting the NFT when a button is clicked.

  • User Interface: The user interface used to interact with the dApp’s functions and variables.

7. Next, head over to the Göerli Faucet and send your wallet some fake ETH to use with our dApp:

8. Next, create a new directory called utils in the src directory.

Then create a new file called interact.js inside the new utils directory.

mkdir src/utils

touch src/utils/interact.js

9. Open this interact.js file in your code editor. Input the following code into this file:

export const connectWallet = async () => {
  if (window.ethereum) {
    try {
      const addressArray = await window.ethereum.request({
        method: "eth_requestAccounts",
      });
      const obj = {
        status: "👆🏽 Write a message in the text-field above.",
        address: addressArray[0],
      };
      return obj;
    } catch (err) {
      return {
        address: "",
        status: "😥 " + err.message,
      };
    }
  } else {
    return {
      address: "",
      status: (
        <span>
          <p>
            {" "}
            🦊{" "}
            <a target="_blank" href={`https://metamask.io/download.html`}>
              You must install Metamask, a virtual Ethereum wallet, in your
              browser.
            </a>
          </p>
        </span>
      ),
    };
  }
};

export const getCurrentWalletConnected = async () => {
  if (window.ethereum) {
    try {
      const addressArray = await window.ethereum.request({
        method: "eth_accounts",
      });
      if (addressArray.length > 0) {
        return {
          address: addressArray[0],
          status: "👆🏽 Write a message in the text-field above.",
        };
      } else {
        return {
          address: "",
          status: "🦊 Connect to Metamask using the top right button.",
        };
      }
    } catch (err) {
      return {
        address: "",
        status: "😥 " + err.message,
      };
    }
  } else {
    return {
      address: "",
      status: (
        <span>
          <p>
            {" "}
            🦊{" "}
            <a target="_blank" href={`https://metamask.io/download.html`}>
              You must install Metamask, a virtual Ethereum wallet, in your
              browser.
            </a>
          </p>
        </span>
      ),
    };
  }
};

10. Head back to the Minter.js file. Add the following line to the top of the file:

import { connectWallet, getCurrentWalletConnected } from "./utils/interact.js";

11. Then, in the functions section in the connectWalletPressed function, add the following code to call the connectWallet function:

const connectWalletPressed = async () => {
    const walletResponse = await connectWallet();
    setStatus(walletResponse.status);
    setWallet(walletResponse.address);
  };

12. Then in the useEffect function, add the following code to call the get CurrentWalletConnected function:

useEffect(async () => {
    const {address, status} = await getCurrentWalletConnected();
    setWallet(address)
    setStatus(status); 
}, []);

13. Save your files.

Your react app running at localhost:3000 will update automatically. You will now be able to click the ‘Connect Wallet’ button and will be prompted to connect your Metamask wallet to the website. Once connected, your dApp will reflect your wallet’s address:

14. Next, in your Minter.js file, we need to add the function addWalletListener.

This function tracks the wallet’s state, such as if it disconnects or if the user switches accounts. In the Minter.js file, add the following function:

function addWalletListener() {
  if (window.ethereum) {
    window.ethereum.on("accountsChanged", (accounts) => {
      if (accounts.length > 0) {
        setWallet(accounts[0]);
        setStatus("👆🏽 Write a message in the text-field above.");
      } else {
        setWallet("");
        setStatus("🦊 Connect to Metamask using the top right button.");
      }
    });
  } else {
    setStatus(
      <p>
        {" "}
        🦊{" "}
        <a target="_blank" href={`https://metamask.io/download.html`}>
          You must install Metamask, a virtual Ethereum wallet, in your
          browser.
        </a>
      </p>
    );
  }
}

Then, edit the useEffect function to reflect the following code:

useEffect(async () => {
    const {address, status} = await getCurrentWalletConnected();
    setWallet(address)
    setStatus(status);

    addWalletListener(); 
}, []);

15. Now we need an image to use as an NFT. We’ll start by uploading an image to Filebase for us to use.

To do this, navigate to console.filebase.com. If you don’t have an account already, sign up, then log in.

16. Select ‘Buckets’ from the left side bar menu, or navigate to console.filebase.com/buckets.

Select ‘Create Bucket’ in the top right corner to create a new bucket for your NFTs.

17. Enter a bucket name and choose the IPFS storage network to create the bucket.

Bucket names must be unique across all Filebase users, be between 3 and 63 characters long, and can contain only lowercase characters, numbers, and dashes.

18. Next, select the bucket from your list of buckets, then select ‘Upload’ in the top right corner to upload an image file.

19. Select your images to be uploaded.

Once uploaded, they will be listed in the bucket.

20. You can view the object’s IPFS CID in the CID column, or you can click on your uploaded object to display the metadata for the object, which includes the IPFS CID.

Choose the method you prefer, and take note of the IPFS CID. We will reference this later.

21. Now, let’s head over to Alchemy and either sign up for an account or login.

22. From the Alchemy dashboard, we need to create an app.

Select the ‘Create App’ button to get started.

23. Create a new app. For our example, we called our app NFTs.

Set the environment to ‘Staging’, the chain to ‘Ethereum’, and the network to ‘Göerli’.

24. Then, from our App’s page, select ‘View Key’:

25. Copy your app’s HTTP Key:

26. Then in your interact.js file, insert the following lines at the top of the file:

const alchemyKey = "ALCHEMY_API_KEY";
const { createAlchemyWeb3 } = require("@alch/alchemy-web3");
const web3 = createAlchemyWeb3(alchemyKey);
const contractABI = require('../contract-abi.json')
const contractAddress = "0x4C4a07F737Bf57F6632B6CAB089B78f62385aCaE";

Replace ALCHEMY_APY_KEY with your Alchemy HTTP key.

27. Then at the bottom of the file, insert the following code:

export const mintNFT = async(url, name, description) => {

 
    if (url.trim() == "" || (name.trim() == "" || description.trim() == "")) { 
        return {
            success: false,
            status: "❗Please make sure all fields are completed before minting.",
        }
    }

    const metadata = new Object();
    metadata.name = name;
    metadata.image = url;
    metadata.description = description;

    const tokenURI = url;  

    window.contract = await new web3.eth.Contract(contractABI, contractAddress);//loadContract();

    const transactionParameters = {
        to: contractAddress, // Required except during contract publications.
        from: window.ethereum.selectedAddress, 
        'data': window.contract.methods.mintNFT(window.ethereum.selectedAddress, tokenURI).encodeABI() //make call to NFT smart contract 
    };

    try {
        const txHash = await window.ethereum
            .request({
                method: 'eth_sendTransaction',
                params: [transactionParameters],
            });
        return {
            success: true,
            status: "✅ Check out your transaction on Etherscan: <https://ropsten.etherscan.io/tx/>" + txHash
        }
    } catch (error) {
        return {
            success: false,
            status: "😥 Something went wrong: " + error.message
        }
    }
}

28. Head back to your Minter.js file.

Edit the import statement to include your newly exported mintNFT function from the interact.js file:

import { connectWallet, getCurrentWalletConnected, mintNFT } from "./utils/interact.js";

29. Then, still within the Minter.js file, edit the onMintPressed function to resemble the following:

const onMintPressed = async () => {
    const { status } = await mintNFT(url, name, description);
    setStatus(status);
};

30. Now, head over to your dApp running at localhost:3000.

In the ‘Link to asset’ field, enter https://ipfs.filebase.io/ipfs/IPFS_CID replacing IPFS_CID with the CID from one of your files uploaded to Filebase earlier in the tutorial. Then give your NFT a name and a description.

31. It’s time to mint!

Click the ‘Mint NFT’ button. You’ll be prompted to sign the transaction with your connected Metamask wallet.

32. Your transaction will be returned in your dApp for you to view on Etherscan:

Congrats! You’ve deployed your own full-stack dApp that can be used to mint your own NFTs!

Last updated