Filebase
HomepageFilebase DashboardDiscordBlog
  • 👋Welcome to Filebase!
  • Getting Started
    • FAQ
    • Service Limits
    • Getting Started Guides
      • Pin Your First File To IPFS
      • Developer Quick Start Guide
  • IPFS Concepts
    • What is IPFS?
    • What is an IPFS CID?
    • What is IPFS Pinning?
    • What is an IPFS Gateway?
  • IPFS Pinning
    • Pinning Files
    • Listing Files
    • Deleting Files
    • Event Notifications
  • IPNS Names
    • Managing Names
  • Dedicated IPFS Gateways
    • Managing Dedicated Gateways
    • Access Controls
    • Image Optimizations
    • Adding a Custom Domain
  • API Documentation
    • S3-Compatible API
      • Cross Origin Resource Sharing (CORS)
        • Create and Apply a CORS Rule to a Filebase Bucket
        • Deep Dive: Cross Origin Resource Sharing (CORS)
      • Pre-Signed URLs
    • Filebase Platform APIs
    • IPFS Pinning Service API
  • Code Development + SDKs
    • Code Development
      • Apache Libcloud - Python
      • Apostrophe CMS
      • AWS Lambda - NodeJS
      • AWS Lambda - Python
      • AWS SDK - Go (Golang)
      • AWS SDK - Java
      • AWS SDK - JavaScript
      • AWS SDK - .NET
      • AWS SDK - PHP
      • AWS SDK - Python
      • AWS SDK - Ruby
      • Code Examples
        • How To Utilize Filebase with NodeJS
      • DataCamp
      • Dart / Flutter
      • Django
      • Docker
        • Docker Volume Backup
      • Elixir Phoenix
      • Filebase NPM Package
      • Fog.io - Ruby
      • Google App Scripts
      • Integrated Haskell Platform
      • Laravel
      • Nuxt
      • Paperspace
      • Postman
      • Reading a JSON File
      • UNA
      • Unity
      • Uppy AWS S3 Plugin
      • Vue
      • Watcher for NodeJS
      • Webpack S3 Plugin
      • Xamarin
    • SDK Examples: Pinning Files and Folders to IPFS
      • AWS SDK for .NET
      • AWS SDK for Go
      • AWS SDK for JavaScript
      • AWS SDK for PHP
      • AWS SDK for Python
      • AWS SDK for Ruby
  • Archive
    • Content Archive
      • IPFS Getting Started Guide
      • Web Console Getting Started Guide
      • IPFS Tools
        • IPFS CLI
        • IPFS Desktop
        • IPFS Pin Sync
        • IPFS Pinning Service API
        • IPFS3up
      • Third Party Tools and Clients
        • Backup Client Configurations
          • AhsayCBS
          • BackupAssist Classic
          • BackupAssist ER
          • BackupNinja
          • BackupSheep
          • Bacula Enterprise Edition
          • CloudBacko
          • CloudBerry Backup
          • Cloudron
          • cPanel
          • Comet
          • Commvault
          • Duplicacy
          • Ghost IPFS Storage Adapter
          • IPFS Pinning GitHub Action
          • JetBackup
          • Kopia
          • MoveBot
          • MSP360 Online Backup
          • oDrive
          • Photos+ Cloud Library
          • qBackup
          • S3 Uploader for GitHub Actions
          • SimpleBackups
          • SnapShooter
          • Strapi Provider Plugin
          • Veeam
          • Wordpress
            • Media Cloud
            • XCloner
          • Zerto
        • CLI Tools
          • Ansible
          • Apache Pulsar
          • AWS CLI
            • How To Delete Data with AWS CLI
            • What is Multipart Upload?
          • Bash
            • Backup Files to IPFS with Bash
            • Laravel Backup with Bash
            • MongoDB Backup with Bash
            • PostgreSQL Backup with Bash
            • Wordpress Backup with Bash
          • cURL
          • Elasticsearch
          • IPFS-CAR
          • IPFScrape
          • IPGet
          • Jenkins
          • JFrog Artifactory
          • Kubernetes
            • Backup and Restore InFluxDB to Filebase with TrilioVault
            • CSI-S3
            • Kasten K10
            • Kerberos Vault
            • Longhorn.io
            • Stash for Kubernetes
            • Velero
          • Litestream
          • Minty
          • MongoDB
          • MoSMB
          • MySQL
          • Next.js .CAR File Upload
          • NFT Image Generator
          • NGINX S3 Gateway
          • Pinning Docker Images to IPFS
          • Pinning Encrypted Files to IPFS
          • PowerShell
            • Calculate the Size of Filebase Buckets using PowerShell
          • Rclone
            • Backing Up DigitalOcean Spaces to Filebase using Rclone
          • Restic
          • S3cmd
          • S3Express
          • S3FS-FUSE
          • S3QL
          • S3Surfer
          • S4cmd
          • SeaweedFS
          • Tableland
        • Content Delivery Networks
          • Bunny CDN
          • CloudFront CDN
          • Fastly CDN
        • File Management Client Configurations
          • Airbyte
          • Arq
          • Astiga
          • AWS Rekognition
          • AWS S3 Manager - iOS App
          • BucketAnywhere for S3 - Android App
          • CentreStack
          • CloudFlyer
          • Cloudfser
          • Couchdrop
          • CrossFTP
          • CyberDuck
            • How To Delete Data with CyberDuck
          • Dropshare
          • Duplicati
          • FileBrowserGO
          • Flexify.IO
          • ForkLift
          • Goofys
          • Joplin
          • LucidLink
          • MASV
          • Matrix Synapse
          • MinIO Gateway for S3
          • Mountain Duck
          • NetDrive
          • Nexfs
          • NextCloud
          • Nodeum
          • ownCloud
          • Plesk
          • Pure Storage FlashBlade
          • RaiDrive
          • S3 Browser
          • ShareX
          • SmartFTP
          • StableBit Cloud Drive
          • Storage Made Easy Enterprise File Fabric
          • WinSCP
        • NAS Device Configurations
          • Buffalo TeraStation
          • Datadobi DobiProtect
          • Netapp ONTAP Select
          • OpenDrives Atlas
          • Synology Hyper Backup
          • TrueNAS CORE
      • Knowledge Base
        • Deep Dives
          • Deep Dive: Blockchains
          • Deep Dive: Decentralized Compute
          • Deep Dive: Decentralized Digital Identity
          • Deep Dive: Decentralized Storage
          • Deep Dive: Erasure Coding
          • Deep Dive: Geo-Redundancy
          • Deep Dive: Metadata
          • Deep Dive: Metaverse
          • Deep Dive: NFTs
          • Deep Dive: Web3
        • Filebase eBooks
        • Filebase One-Pagers
        • Filebase Whitepapers
        • Web3 Tutorials
          • Alchemy
            • Alchemy: Build a dApp That Provides Real-Time Ethereum Transaction Notifications
            • Alchemy: Create a Full-Stack dApp
            • Alchemy: Create a Hello World Smart Contract
            • Alchemy: Create Your Own ERC20 Cryptocurrency
            • Alchemy: Decentralized Youtube
            • Alchemy: How to Create and Mint an NFT using Filebase
            • Alchemy: How to Mint an NFT Using Web3.js
            • Alchemy: Using The Alchemy SDK with NFTs Minted Through thirdweb
          • Agoric
            • Agoric: Create a DeFi dApp Using Agoric That’s Stored on Filebase
          • AirSwap
            • AirSwap: Track NFT Contract Addresses with AirSwap CLI
          • ArcBlock
            • ArcBlock: Running an ArcBlock Blocket Server on IPFS
          • Ankr
            • Ankr: Create a Truffle Project with Ankr and Filebase
            • Ankr: Deploy a Smart Contract on Polygon using Ankr that is backed up to Filebase
          • Avalanche
            • Avalanche: How To Launch a Generative NFT Collection With Avalanche and IPFS
          • Backing Up NFTs
          • Brownie
            • Brownie: Create and Mint an NFT Using Brownie
          • Bueno
            • Bueno: How to Create a Generative NFT Collection with Bueno
          • Cardano
            • Cardano: Submit Cardano Blockchain Transactions with Embedded Metadata Stored on Filebase
          • Ceramic
            • Ceramic: How to Host a Ceramic Node Using Decentralized Storage
          • Create-IPFS-app
          • Cosmos
            • Cosmos: Storing Cosmos Chain Governance Metadata on IPFS
          • DeCommerce
          • Ethereum Name Service
            • ENS: Configure an ENS Domain to use a Filebase IPFS Dedicated Gateway
          • Figment Datahub
            • Figment Datahub and Avalanche: Make an e-Voting dApp Using Figment Datahub, Avalanche, and Filebase
            • Figment Datahub and Celo Network: Create an ERC1155 NFT on the Celo Network using Figment Datahub and Objects Stored on Filebase
          • Flow
            • Flow: How to Create an NFT Marketplace with Filebase + Flow
          • Fauna
            • Fauna: Host an Application on IPFS with IPFS Dedicated Gateways
          • Ganache
            • Ganache: Create a dApp Hosted on IPFS
          • GUN
            • GUN: Create a Decentralized Chat App with GUN and IPFS
          • Hardhat
            • Hardhat: Creating an NFT Contract using Hardhat and Setting NFT Metadata using IPFS on Filebase
          • Harmony
            • Harmony: Deploy an HRC721 NFT on Harmony with IPFS
          • Hosting a Form on IPFS
          • iExec
            • iExec: Using iExec and Tee Worker to Create Apps that Use Datasets Stored on Filebase
          • Infura
            • Infura: Build dApp Frontends with Infura, React, and IPFS
            • Infura: Create an NFT Contract Factory with Metadata stored on IPFS
          • Lens Protocol
            • Lens Protocol: Build a Decentralized Social Media Network Stored on IPFS
          • LIT Protocol
            • LIT Protocol: Create a MintLIT NFT with LIT Protocol and IPFS
          • LivePeer
            • LivePeer: Mint a Video NFT with LivePeer
          • Macrometa
            • Macrometa: Track IPFS Files with Macrometa
          • Mina Protocol
            • Mina Protocol: Create a Simple zkApp with Mina Protocol and IPFS
          • NEAR Protocol
            • NEAR Protocol: Storing Off-Chain Data on IPFS using Filebase
          • NFTPort
            • NFTPort: Create an NFT Collection with NFTPort
          • Ocean Protocol
            • Ocean Protocol: Publish Data NFTs Stored on IPFS using Ocean Protocol
          • Pin Tezos Tokens Tool
          • Polkadot
            • Polkadot: Deploy a Polkadot dApp on Decentralized Storage
          • Polygon
            • Polygon: Building an App NFT With Polygon
            • Polygon: Make a Donation App with IPFS and Polygon
          • Python
            • Generating NFT Metadata with Python
          • QuickNode
            • QuickNode: Create a Token dApp using QuickNode
          • Remix
            • Remix: Create a Web App with Remix to Upload to Decentralized Storage
          • Remix IDE
            • Remix IDE: Creating Interactive NFTs with IPFS and Remix IDE
          • Secret Network
            • Secret Network: Create an NFT on Secret Network with Data Stored on IPFS
          • Stargaze
            • Stargaze: Create an NFT Collection Using IPFS and Stargaze
          • Starknet
            • Starknet: Create a HardHat Project Using A Starknet Plugin Hosted On IPFS
          • Studio 721
            • Studio 721: Create an NFT Collection with Studio 721 and IPFS
          • Solana
            • Solana: Minting an NFT Using Sugar, Candy Machine, and Filebase
          • Subsquid
            • Subsquid: Querying NFT Data using Subsquid and a Filebase IPFS Dedicated Gateway
          • Tailwind CSS
            • Tailwind CSS: Build an Image Gallery App with IPFS and Tailwind CSS
          • Tatum
            • Tatum: How To Mint NFTs on Solana with Tatum
          • Tezos
            • Tezos: Create an NFT on the Tezos Network using IPFS on Filebase
          • thirdweb
            • thirdweb: Build an NFT Loot Box with thirdweb and IPFS
            • thirdweb: Build an NFT Minting Page with thirdweb, IPFS, RainbowKit, and WAGMI
            • thirdweb: Create a Discord Bot That Gives Roles to NFT Holders
            • thirdweb: Create a Gated Website Using NFTs and IPFS
            • thirdweb: Create an NFT Marketplace with thirdweb and IPFS
            • thirdweb: Release an NFT Drop Using thirdweb and IPFS
          • useDApp
            • useDApp: Create a dApp using useDApp and IPFS
          • Unstoppable Domains
            • Unstoppable Domains: Create a Decentralized Website Using Unstoppable Domains and IPFS Folders
            • Unstoppable Domains: Deploy a Decentralized Blog Using Unstoppable Domains, Akash, and IPFS
            • Unstoppable Domains: IPFS Configuration
          • Vultr
            • Vultr: Store Bedrock Minecraft Worlds on Decentralized Storage
            • Vultr: Store Forge Minecraft Worlds on Decentralized Storage
            • Vultr: Store PaperSpigot Minecraft Worlds on Decentralized Storage
            • Vultr: Store Vanilla Minecraft Worlds on Decentralized Storage
          • Waffle
            • Waffle: Deploy a Smart Contract with Waffle That’s Stored on IPFS
          • Walt.id
            • Walt.id: Mint an NFT with Walt.id and Filebase
          • Web3 Toolbox
            • Web3 Toolbox: Building an NFT Drop With Web3 Toolbox
Powered by GitBook
On this page
  • What is Polygon?
  • 1. Begin by installing the Truffle NPM package with the following command:
  • 2. Then, create a NextJS app with the commands:
  • 3. Navigate into the newly created application directory and initialize the project:
  • 4. Navigate into the contracts directory and create a new file called DonationContract.sol.
  • 5. Navigate to the migrations directory, then create a new file called 1_initial_migration.js.
  • 6. Save this file. Then, navigate back to the contracts directory and create a new file called Migrations.sol.
  • 7. In the migrations directory, create another new file called 2_donation_contract_migration.js.
  • 8. Next, install Ganache.
  • 9. Then select ‘Save’ to start your Ganache development blockchain environment.
  • 10. Next, open the truffle-config.js file and replace its existing contents with the following:
  • 11. Now it’s time to deploy our Truffle configuration to the Ganache development network with the command:
  • 12. Before moving on with our app, we’ll run a few test scripts. In the tests directory, create a new file called donation-contract-tests.js that contains the following code:
  • 13. Next, install the chai package, which is Truffle’s test script package used in the script above:
  • 14. Then, run the test script with the command:
  • 15. In the root directory of your project, create a new directory called contexts, then create a new file called DataContext.tsx.
  • 16. Next, open the pages/_app.tsx file and insert the following code:
  • 17. For our app’s user interface, we’ll be using the TailwindCSS package. Install it, along with HeadlessUI, with the command:
  • 18. Open the pages/index.tsx file and replace the existing code with the following content:
  • 19. There are three components referenced in this code that don’t exist yet - Body.tsx, UploadImage.tsx, and Header.tsx.
  • 20. Now, to use the IPFS client, let’s install the IPFS HTTP client package:
  • 21. Lastly, before we can publish this contract, we need to set up authentication through our cryptowallet.
  • 22. Next, create a new file called .secret in the root of your project.
  • 23. For submitted transactions, you will need some testnet MATIC, which you can get from the Polygon Matic faucet.
  • 24. To cover gas fees, we’ll use the hdwallet-provider package, which can be installed with the command:
  • 25. Now that we have these configuration details, update your truffle-config.js file with the following:
  • 26. Now it’s time to deploy your donation app’s smart contract to the Polygon Mumbai network with the command:
  • 27. Then, start the web app with the command:
  • 28. The app will be running at localhost:3000. It will look something like this:
  • 29. Select ‘Upload Image’ to upload an image to the application.
  • 30. Select a file from your local computer, provide an optional description, then select ‘Upload’.

Was this helpful?

  1. Archive
  2. Content Archive
  3. Knowledge Base
  4. Web3 Tutorials
  5. Polygon

Polygon: Make a Donation App with IPFS and Polygon

Learn how to create a Web3 donation app using IPFS and Polygon.

PreviousPolygon: Building an App NFT With PolygonNextPython

Last updated 9 months ago

Was this helpful?

What is Polygon?

Polygon is a layer two blockchain network that is designed as a sidechain solution for scaling alongside the Ethereum blockchain network.

Read below to learn how to create a Web3 donation app using IPFS and Polygon.

Prerequisites:

1. Begin by installing the Truffle NPM package with the following command:

npm install -g truffle

2. Then, create a NextJS app with the commands:

npm install next

npx create-next-app --typescript

When prompted, provide a name for your app. This tutorial uses the name ‘polygon-dapp’.

3. Navigate into the newly created application directory and initialize the project:

cd polygon-dapp

truffle init

The ‘init’ command will create the following files and directories:

  • contracts/: Used to store the project’s smart contracts.

  • migrations/: Used to store the Truffle scripts for deploying the smart contracts.

  • test/: Used to store the project’s test scripts for validating the smart contracts.

  • truffle-config.js: The Truffle configuration setting file.

4. Navigate into the contracts directory and create a new file called DonationContract.sol.

In the file, insert the following code:

// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.5.16;

contract DonationContract {
  // Keep track of total number of images in contract
  uint256 public imageCount =  0;

  // Data structure to store images data
  struct Image {
    uint256 id;
    string hash;
    string description;
    uint256 donationAmount;
    address payable author;
  }

  mapping(uint256 => Image) public images;

  // Event emitted when image is created
  event ImageCreated(
    uint256 id,
    string hash,
    string description,
    uint256 donationAmount,
    address payable author
  );

  // Event emitted when an there is a donation
  event DonateImage(
    uint256 id,
    string hash,
    string description,
    uint256 donationAmount,
    address payable author
  );

// Create an Image
function uploadImage(string memory _imgHash, string memory _description) public {
  require(bytes(_imgHash).length > 0);
  require(bytes(_description).length > 0);
  require(msg.sender != address(0x0));
  imageCount++;
  images[imageCount] = Image(
    imageCount,
    _imgHash,
    _description,
    0,
    msg.sender
  );
  emit ImageCreated(imageCount, _imgHash, _description, 0, msg.sender);
}

function donateImageOwner(uint256 _id) public payable {
  require(_id > 0 && _id <= imageCount);

  Image memory _image = images[_id];
  address payable _author = _image.author;
  address(_author).transfer(msg.value);
  _image.donationAmount = _image.donationAmount + msg.value;
  images[_id] = _image;

  emit DonateImage(
    _id,
    _image.hash,
    _image.description,
    _image.donationAmount,
    _author
  );
}
}

This smart contract handles the donation process when users interact with our application. Save this file, then compile it with the command:

truffle compile

You should receive output that resembles the following:

5. Navigate to the migrations directory, then create a new file called 1_initial_migration.js.

In this file, insert the following code:

const Migrations = artifacts.require("Migrations");

module.exports = function(deployer) {
  deployer.deploy(Migrations);
};

6. Save this file. Then, navigate back to the contracts directory and create a new file called Migrations.sol.

Insert the following code into this file:

pragma solidity >=0.4.22 <0.7.0;

contract Migrations {
  address public owner;
  uint256 public last_completed_migration;

  modifier restricted() {
    if (msg.sender == owner) _;
  }

  constructor() public {
    owner = msg.sender;
  }

  function setCompleted(uint completed) public restricted {
    last_completed_migration = completed;
  }

  function upgrade(address new_address) public restricted {
    Migrations upgraded = Migrations(new_address);
    upgraded.setCompleted(last_completed_migration);
  }
}

7. In the migrations directory, create another new file called 2_donation_contract_migration.js.

In this file, insert the following code:

const DonationContract = artifacts.require("DonationContract");
module.exports = function (deployer) {
deployer.deploy(DonationContract);
};

9. Then select ‘Save’ to start your Ganache development blockchain environment.

10. Next, open the truffle-config.js file and replace its existing contents with the following:

module.exports = {
  networks: {
    development: {
      host: "localhost",
      port: 7545,
      network_id: "*",
    },
  },
  contracts_directory: "./contracts",
  contracts_build_directory: "./abis",
  compilers: {
    solc: {
      optimizer: {
        enabled: true,
        runs: 200,
      },
    },
  },

  db: {
    enabled: false,
  },
};

11. Now it’s time to deploy our Truffle configuration to the Ganache development network with the command:

truffle migrate

The output should resemble the following:

12. Before moving on with our app, we’ll run a few test scripts. In the tests directory, create a new file called donation-contract-tests.js that contains the following code:

const { assert } = require("chai");
const DonationContract = artifacts.require("./DonationContract.sol");
require("chai").use(require("chai-as-promised")).should();

contract("DonationContract", ([deployer, author, donator]) => {
  let donationContract;
  before(async () => {
    donationContract = await DonationContract.deployed();
  });

  describe("deployment", () => {
    it("should be an instance of DonationContract", async () => {
      const address = await donationContract.address;
      assert.notEqual(address, null);
      assert.notEqual(address, 0x0);
      assert.notEqual(address, "");
      assert.notEqual(address, undefined);
    });
  });

  describe("Images", () => {
    let result;
    const hash = "abcd1234";
    const description = "This is a test image";
    let imageCount;
    before(async () => {
      result = await donationContract.uploadImage(hash, description, {
        from: author,
      });
      imageCount = await donationContract.imageCount();
    });

    it("Check Image", async () => {
      let image = await donationContract.images(1);
      assert.equal(imageCount, 1);
      const event = result.logs[0].args;
      assert.equal(event.hash, hash);
      assert.equal(event.description, description);
    });

    it("Allow users to donate", async () => {
      let oldAuthorBalance;
      oldAuthorBalance = await web3.eth.getBalance(author);
      oldAuthorBalance = new web3.utils.BN(oldAuthorBalance);
      result = await donationContract.donateImageOwner(imageCount, {
        from: donator,
        value: web3.utils.toWei("1", "Ether"),
      });

      const event = result.logs[0].args;
      let newAuthorBalance;
      newAuthorBalance = await web3.eth.getBalance(author);
      newAuthorBalance = new web3.utils.BN(newAuthorBalance);

      let donateImageOwner;
      donateImageOwner = web3.utils.toWei("1", "Ether");
      donateImageOwner = new web3.utils.BN(donateImageOwner);

      const expectedBalance = oldAuthorBalance.add(donateImageOwner);
      assert.equal(newAuthorBalance.toString(), expectedBalance.toString());
    });
  });
});

13. Next, install the chai package, which is Truffle’s test script package used in the script above:

npm install chai chai-as-promised

14. Then, run the test script with the command:

truffle test

Your output should look like this:

15. In the root directory of your project, create a new directory called contexts, then create a new file called DataContext.tsx.

In this file, insert the following content:

declare let window: any;
import { createContext, useContext, useEffect, useState } from "react";
import Web3 from "web3";
import DonationContract from "../abis/DonationContract.json";

interface DataContextProps {
  account: string;
  contract: any;
  loading: boolean;
  images: any[];
  imageCount: number;
  updateImages: () => Promise<void>;
  donateImageOwner: (id: string, donateAmout: any) => Promise<void>;
}

const DataContext = createContext<DataContextProps | null>(null);

export const DataProvider: React.FC = ({ children }) => {
  const data = useProviderData();
  return <DataContext.Provider value={data}>{children}</DataContext.Provider>;
};

export const useData = () => useContext<DataContextProps | null>(DataContext);

This script uses the package web3, so let’s install it with the command:

npm install web3

16. Next, open the pages/_app.tsx file and insert the following code:

import "tailwindcss/tailwind.css";
import { DataProvider } from "../contexts/DataContext";

function MyApp({ Component, pageProps }) {
  return (
    <>
      <DataProvider>
        <Component {...pageProps} />
      </DataProvider>
    </>
  );
}

export default MyApp;

17. For our app’s user interface, we’ll be using the TailwindCSS package. Install it, along with HeadlessUI, with the command:

npm install tailwindcss @headlessui/react

18. Open the pages/index.tsx file and replace the existing code with the following content:

import Head from "next/head";
import { useState } from "react";
import Body from "../components/Body";
import Header from "../components/Layout/Header";
import { UploadImage } from "../components/UploadImage";
import { useData } from "../contexts/DataContext";

export default function Home() {
  let [isOpen, setIsOpen] = useState(false);
  const { loading } = useData();

  function closeModal() {
    setIsOpen(false);
  }

  function openModal() {
    setIsOpen(true);
  }

  return (
    <div className="flex flex-col items-center justify-start min-h-screen py-2">
      <Head>
        <title>Decentragram</title>
        <link rel="icon" href="/favicon.ico" />
      </Head>
      <UploadImage isOpen={isOpen} closeModal={closeModal} />
      <Header />
      <div
        className="max-w-2xl w-full bg-blue-100 rounded-xl flex justify-center items-center py-2 mt-3 hover:bg-blue-200 cursor-pointer"
        onClick={openModal}
      >
        <span className="text-blue-500 font-bold text-lg">Upload Image</span>
      </div>
      {loading ? (
        <div className="font-bold text-gray-400 mt-36 text-4xl">Loading...</div>
      ) : (
        <Body />
      )}
    </div>
  );
}

19. There are three components referenced in this code that don’t exist yet - Body.tsx, UploadImage.tsx, and Header.tsx.

Create a new directory called components, then create a new file for each of these in the components directory. Then, insert the following code into each:

Body.tsx:

declare let window: any;
import Identicon from "identicon.js";
import React from "react";
import { useData } from "../contexts/DataContext";

const Body = () => {
  const { images } = useData();
  return (
    <>
      {images.length > 0 &&
        images.map((image, index) => (
          <BodyItem
            key={index}
            totalDonationss={image.donationAmount}
            address={image.author}
            description={image.description}
            hash={image.hash}
            id={image.id}
          />
        ))}
    </>
  );
};

export default Body;

const BodyItem = ({ address, description, totalDonationss, hash, id }) => {
  const { donateImageOwner, updateImages } = useData();
  var data = new Identicon(address, 200).toString();
  return (
    <div className="w-full md:mx-0 md:max-w-2xl mt-5 p-3 border rounded-xl flex flex-col">
      <div className="flex flex-row space-x-5 bg-gray-100 rounded-t-xl py-3 px-4 border-t border-l border-r font-mono items-center">
        <img width={35} height={35} src={`data:image/png;base64, ${data}`} />
        <div className="overflow-ellipsis w-52 overflow-hidden">{address}</div>
      </div>
      <img src={`https://ipfs.filebase.io/ipfs/${hash}`} />
      <div className="py-3 px-4 flex flex-col border-l border-r">
        <span className="font-sans font-bold">Description</span>
        <span className="font-sans pt-2">{description}</span>
      </div>
      <div className="bg-gray-100 rounded-b-xl py-3 px-4 border-b border-l border-r font-mono flex flex-row justify-between">
        <span>
          Total DONATIONS: {window.web3.utils.fromWei(totalDonations, "Ether")}{" "}
          MATIC
        </span>
        <div
          onClick={async () => {
            let donationAmount = window.web3.utils.toWei("0.1", "Ether");
            await donationImageOwner(id, donationAmount);
            await updateImages();
          }}
        >
          <span className="cursor-pointer font-bold text-blue-400">
            DONATE: 0.1 MATIC
          </span>
        </div>
      </div>
    </div>
  );
};

Header.tsx:

import Identicon from "identicon.js";
import React, { useEffect } from "react";
import { useData } from "../../contexts/DataContext";

function Header() {
  const { account } = useData();
  const [data, setData] = React.useState();
  useEffect(() => {
    if (account !== "0x0") {
      setData(new Identicon(account, 200).toString());
    }
  }, [account]);
  return (
    <div className="container items-center">
      <div className="flex flex-col md:flex-row items-center md:justify-between border py-3 px-5 rounded-xl">
        <span className="font-mono">Polygon MATIC</span>
        <div className="flex flex-row space-x-2 items-center">
          <div className="h-5 w-5 rounded-full bg-blue-500"></div>
          <span className="font-mono text-xl font-bold">Decentagram</span>
        </div>
        <div className="flex flex-row space-x-2 items-center">
          <span className="font-mono overflow-ellipsis w-52 overflow-hidden">
            {account}
          </span>
          {account && data && (
            <img
              width={35}
              height={35}
              src={`data:image/png;base64, ${data}`}
            />
          )}
        </div>
      </div>
    </div>
  );
}

export default Header;

UploadImage.tsx:

import { Dialog, Transition } from "@headlessui/react";
import { create } from "ipfs-http-client";
import { Fragment, useState } from "react";
import { useData } from "../contexts/DataContext";

interface Props {
  isOpen: boolean;
  closeModal: () => void;
}

export const UploadImage: React.FC<Props> = ({ isOpen, closeModal }) => {
  const [buttonTxt, setButtonTxt] = useState<string>("Upload");
  const [file, setFile] = useState<File | null>(null);
  const { contract, account, updateImages } = useData();
  const client = create({ url: "https://api.filebase.io/v1/ipfs/" });
  const [description, setDescription] = useState<string>("");

  const uploadImage = async () => {
    setButtonTxt("Uploading to IPFS...");
    const added = await client.add(file);
    setButtonTxt("Creating smart contract...");
    contract.methods
      .uploadImage(added.path, description)
      .send({ from: account })
      .then(async () => {
        await updateImages();
        setFile(null);
        setDescription("");
        setButtonTxt("Upload");
        closeModal();
      })
      .catch(() => {
        closeModal();
      });
  };

  return (
    <>
      <Transition appear show={isOpen} as={Fragment}>
        <Dialog
          as="div"
          className="fixed inset-0 z-10 overflow-y-auto"
          onClose={closeModal}
        >
          <Dialog.Overlay className="fixed inset-0 bg-black opacity-40" />

          <div className="min-h-screen px-4 text-center ">
            <Transition.Child
              as={Fragment}
              enter="ease-out duration-300"
              enterFrom="opacity-0"
              enterTo="opacity-100"
              leave="ease-in duration-200"
              leaveFrom="opacity-100"
              leaveTo="opacity-0"
            >
              <Dialog.Overlay className="fixed inset-0" />
            </Transition.Child>

            {/* This element is to trick the browser into centering the modal contents. */}
            <span
              className="inline-block h-screen align-middle"
              aria-hidden="true"
            >
              &#8203;
            </span>
            <Transition.Child
              as={Fragment}
              enter="ease-out duration-300"
              enterFrom="opacity-0 scale-95"
              enterTo="opacity-100 scale-100"
              leave="ease-in duration-200"
              leaveFrom="opacity-100 scale-100"
              leaveTo="opacity-0 scale-95"
            >
              <div className="inline-block w-full p-6 my-8 overflow-hidden text-left align-middle transition-all transform bg-white shadow-xl rounded-2xl max-w-xl">
                <Dialog.Title
                  as="h3"
                  className="text-lg font-medium leading-6 text-gray-900"
                >
                  Upload Image to IPFS
                </Dialog.Title>
                <div className="mt-2">
                  <input
                    onChange={(e) => setFile(e.target.files[0])}
                    className="my-3"
                    type="file"
                  />
                </div>

                {file && (
                  <div className="mt-2">
                    <img src={URL.createObjectURL(file)} />
                  </div>
                )}

                <div className="mt-4">
                  <textarea
                    onChange={(e) => {
                      setDescription(e.target.value);
                    }}
                    value={description}
                    placeholder="Description"
                    className="px-3 py-1 font-sourceSansPro text-lg bg-gray-100 hover:bg-white focus:bg-white rounded-lg border-4 hover:border-4 border-transparent hover:border-green-200 focus:border-green-200 outline-none focus:outline-none focus:ring w-full pr-10 transition-all duration-500 ring-transparent"
                  />
                </div>
                <div className="mt-4">
                  <button
                    type="button"
                    disabled={buttonTxt !== "Upload"}
                    className="inline-flex justify-center px-4 py-2 text-sm font-medium text-blue-900 bg-blue-100 border border-transparent rounded-md hover:bg-blue-200 focus:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:ring-blue-500"
                    onClick={() => {
                      if (file) uploadImage();
                    }}
                  >
                    {buttonTxt}
                  </button>
                </div>
              </div>
            </Transition.Child>
          </div>
        </Dialog>
      </Transition>
    </>
  );
};

20. Now, to use the IPFS client, let’s install the IPFS HTTP client package:

npm install ipfs-http-client

21. Lastly, before we can publish this contract, we need to set up authentication through our cryptowallet.

22. Next, create a new file called .secret in the root of your project.

24. To cover gas fees, we’ll use the hdwallet-provider package, which can be installed with the command:

npm install @truffle/hdwallet-provider

25. Now that we have these configuration details, update your truffle-config.js file with the following:

const HDWalletProvider = require("@truffle/hdwallet-provider");
const fs = require("fs");
const mnemonic = fs.readFileSync(".secret").toString().trim();

module.exports = {
  networks: {
    development: {
      host: "localhost",
      port: 7545,
      network_id: "*",
    },
    matic: {
      provider: () =>
        new HDWalletProvider({
          mnemonic: {
            phrase: mnemonic,
          },
          providerOrUrl: `https://matic-mumbai.chainstacklabs.com/`,
          chainId: 80001,
        }),
      network_id: 80001,
      confirmations: 2,
      timeoutBlocks: 200,
      skipDryRun: true,
      chainId: 80001,
    },
  },
  contracts_directory: "./contracts",
  contracts_build_directory: "./abis",
  compilers: {
    solc: {
      optimizer: {
        enabled: true,
        runs: 200,
      },
    },
  },
  db: {
    enabled: false,
  },
};

26. Now it’s time to deploy your donation app’s smart contract to the Polygon Mumbai network with the command:

truffle migrate --network matic

A successful deployment will produce the following output:

27. Then, start the web app with the command:

npm run build

npm start

28. The app will be running at localhost:3000. It will look something like this:

29. Select ‘Upload Image’ to upload an image to the application.

30. Select a file from your local computer, provide an optional description, then select ‘Upload’.

8. Next, install .

You can install either the GUI application or the . We’ll be using the GUI application. Once downloaded, launch the GUI app, then select ‘Quickstart Ethereum’ when prompted to create a workspace.

First, make sure that your wallet is connected to the Polygon Mumtai testnet. For instructions on how to do this, check out this guide

In this file, insert your cryptowallet’s Mnemonic phrase or Please note that this phrase should NEVER be shared with anyone, and should be placed in your .gitignore file if you plan to publish this project to GitHub.

23. For submitted transactions, you will need some testnet MATIC, which you can get from the

MetaMask
Polygon Mumbai network
Install Node.js and npm
VSCode
Sign up
here
here
Ganache
CLI tool
here.
Secret Recovery Phrase.
Polygon Matic faucet.