Skip to content

Deploy A ERC20 Token Faucet dApp

Published: at 08:40 PM

๐Ÿ’“ If you enjoyed the information and the web site, please donate.

ERC20 Token Faucet dApp


You are going to be creating a simple single page application that allows a user to receive 100 faucet token (FCT) that you create. Faucets are used to get fake testnet ether for your wallet that use in the development of your dApp. You will create a faucet for your own token and use the ERC20 token standard for your token. You will add a function to the smart contract called faucet() that will allow a user to receive 100 FCT.


The user will be able to:

๐Ÿ’ด At Paxful trade virtually anything you own, from cars and gold to groceries and appliances, for Bitcoin


๐Ÿ“ฒ Technologies Used

๐Ÿ’น Join Robinhood with my link and we will both pick a free stock.


๐Ÿ’ฅ What Do These Technologies Do?

โ›” Join Raisin using the referral code elyser010443 when you register for a high-yield savings product on raisin.com to earn up to a $125 bonus.


๐Ÿ†• Set Up The Project

npx create-react-app faucet
npm install ethers hardhat @nomiclabs/hardhat-waffle ethereum-waffle chai @nomiclabs/hardhat-ethers
npm install react-bootstrap bootstrap@4.6.0
npm install @openzeppelin/contracts
{
  "name": "react-token-faucet",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@nomiclabs/hardhat-ethers": "^2.0.2",
    "@nomiclabs/hardhat-waffle": "^2.0.1",
    "@openzeppelin/contracts": "^4.1.0",
    "@testing-library/jest-dom": "^5.12.0",
    "@testing-library/react": "^11.2.7",
    "@testing-library/user-event": "^12.8.3",
    "bootstrap": "^4.6.0",
    "chai": "^4.3.4",
    "ethereum-waffle": "^3.3.0",
    "ethers": "^5.2.0",
    "hardhat": "^2.3.0",
    "react": "^17.0.2",
    "react-bootstrap": "^1.6.0",
    "react-dom": "^17.0.2",
    "react-scripts": "4.0.3",
    "web-vitals": "^1.1.2"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}
npx hardhat run

๐Ÿ’ต Buy and sell bitcoins with Localbitcoins by finding cash and online exchanges

# misc
.env
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
require("@nomiclabs/hardhat-waffle");
require('dotenv').config({ path: 'variables.env' });

// This is a sample Hardhat task. To learn how to create your own go to
// https://hardhat.org/guides/create-task.html
task("accounts", "Prints the list of accounts", async () => {
  const accounts = await ethers.getSigners();

  for (const account of accounts) {
    console.log(account.address);
  }
});

// You need to export an object to set up your config
// Go to https://hardhat.org/config/ to learn more

/**
 * @type import('hardhat/config').HardhatUserConfig
 */
 module.exports = {
  paths: {
    artifacts: './src/artifacts',
  },

  networks: {
    hardhat: {
      chainId: 1337
    },
  },
  solidity: "0.8.4"
};

๐Ÿง  Never forget any of your passwords with Roboform

๐Ÿ“ Code The Smart Contract

It is time to program the smart contract that you will deploy to the blockchain and interact with using your React front end.

Remix IDE: Remix is an in-browser solidity development environment. It is a good way to write smart contracts and test them before deploying them into your projects. Your project is set up, so you will use Remix to test your smart contract.

pragma solidity ^0.8.0;

import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/ERC20.sol";

contract FCTToken is ERC20 {

    constructor(string memory name, string memory symbol) ERC20(name, symbol) {
        _mint(msg.sender, 10000 * (10 ** 18));
    }

    function faucet (address recipient , uint amount) external {
      _mint(recipient, amount);
    }
}

This is the code for your smart contact. You are importing the Open Zeppelin library into your Remix IDE. When you create your contract with contract FCTToken is ERC20 your contract will have all the functions from the open zeppelin ERC20 token.

These functions are:

function name() public view returns (string)
function symbol() public view returns (string)
function decimals() public view returns (uint8)
function totalSupply() public view returns (uint256)
function balanceOf(address _owner) public view returns (uint256 balance)
function transfer(address _to, uint256 _value) public returns (bool success)
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success)
function approve(address _spender, uint256 _value) public returns (bool success)
function allowance(address _owner, address _spender) public view returns (uint256 remaining)

๐Ÿ’ก From marketing to design use Fiverr for all your needs

The constructor part of the code will initialize the smart contract parameters name and symbol with values that you will pass to it when it is deployed. These will be the name of your token and its symbol: โ€œFaucetโ€, โ€œFCTโ€.

_mint is an inherited function so you can mint 10,000 tokens. The math used when you call _mint has to be implemented because of token base units.

You added your new function to this smart contract faucet which takes two arguments address recipient and uint amount.

You can see your contract waiting to be deployed. Click Deploy. Remix

If everything is working, you will see a green check mark in the Remix console. Remix

You should see your smart contract under Deployed Contracts. Click the arrow icon to expand it. Remix

You will now see a list of all the available functions you can use in your smart contract. This includes all the functions you received from the Open Zeppelin contracts import. Remix

Open up the faucet function. Remix

You will see the inputs for each argument: recipient and amount. Remix

You will see a drop down menu under Account. This allows you to switch simulated user accounts. Each account is loaded up with test ether. Copy the address of the current account by clicking the copy icon. Remix

Paste that address into the faucet box for recipient and 100 for amount then click transact. Remix

You deployed a smart contract function. To check to see if it worked, open your smart contract functions and call balanceOf with your address as the argument. You should see a balance of 100. Remix

Remix

There is a difference between the functions with orange buttons and the functions with blue buttons. The orange functions write data to the blockchain, this counts as a transaction which costs gas. This action is immutable. The blue functions read data which counts as a call, this is free and does not change any data on the blockchain.

Your smart contract is working, you can safely use it in your project.

In your project in the /contracts folder delete any contracts and create a new contract called FCTToken.sol with the code you just tested:

pragma solidity ^0.8.3;

import "@openzeppelin/contracts/token/ERC20/ERC20.sol";

contract FCTToken is ERC20 {

    constructor(string memory name, string memory symbol) ERC20(name, symbol) {
        _mint(msg.sender, 100000 * (10 ** 18));
    }

    function faucet (address recipient , uint amount) external {
      _mint(recipient, amount);
    }
}

๐Ÿ’ฐ Sign up and get $10 of bitcoin free from Coinbase.


๐Ÿ“ˆ Deploy A Smart Contract On Your Local Blockchain

In your terminal and inside your projectโ€™s root directory run:

npx hardhat node

You will see hardhart start running a local blockchain. It will give you a list of addresses with test eth. Leave this terminal window running and open a new one.

Open your scripts/deploy.js and update it to:

const hre = require("hardhat");

async function main() {
  const [deployer] = await hre.ethers.getSigners();

  console.log(
    "Deploying contracts with the account:",
    deployer.address
  );

  const FCTToken = await hre.ethers.getContractFactory("FCTToken");
  const fctToken = await FCTToken.deploy("FCTToken", "TKN");

  await fctToken.deployed();

  console.log("Token deployed to:", fctToken.address);
}

main()
  .then(() => process.exit(0))
  .catch(error => {
    console.error(error);
    process.exit(1);
  });

Compile and deploy the FCTtoken.sol:

npx hardhat compile

Then run this command:

npx hardhat run scripts/deploy.js --network localhost

Terminal should print out something similar to: Run Hardhat

Save the address of Token Deployed To* you will be using it later.

You have deployed your FCTtoken.sol contract to your local hardhat blockchain.

๐Ÿ’ณ Here is $10 off your first purchase with Afterpay. Shop now and pay later in 4 interest-free payments.


๐Ÿ“ Design The Front End

You will build a web page with a few buttons. These buttons will call your smart contract functions. You need:

In your /src/app.css file delete all the code and replace it with:

.App {
  text-align: center;
  background-color: #34a3a3;
  height: 100%;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
}

.App-header {
  background-color: rgb(253, 204, 251);
  padding: 20px;
  color: white;
}

.App-intro {
  font-size: large;
}

In your App.js file delete all the code and replace it with:

import './App.css';
import FCTToken from './artifacts/contracts/FCTToken.sol/FCTToken.json'

function App() {

  const Token = FCTToken;

  return (
    <div className="App">
    </div>
  );
}

export default App;

In your terminal run this code to start your localhost:

npm run start

This code will load up at localhost:3000 and show a blank page with a blue colored page. Background Color

import './App.css';
import FCTToken from './artifacts/contracts/FCTToken.sol/FCTToken.json'
import 'bootstrap/dist/css/bootstrap.min.css'
import { Container, Row, Col } from 'react-bootstrap'

function App() {

  const Token = FCTToken;

  return (
    <div className="App">
    <Container>
    <Row className="justify-content-md-center">
      <Col>
      <div>Faucet</div>
      </Col>
      <Col>
      <div>Send Area</div>
      </Col>
    </Row>
    </Container>
    </div>
  );
}

export default App;

You imported some bootstrap-react components and sketched out where you need the main UI components to be on the page.

You should see the page reload every time you save a change to your react code.

Create your Faucet component by adding this snippet at line 22:

 <Faucet tokenContract={Token}/>

This creates a react component and sends it the prop Token. This variable contains the ABI which you are importing at line 5.

Code the Faucet component by creating a folder and file src/components/Faucet.js. The code for your Faucet.js react component:

import { useState } from 'react';
import { ethers } from 'ethers'
import Card from 'react-bootstrap/Card'
import Button from 'react-bootstrap/Button'

const tokenAddress = "{YOUR DEPLOYED TOKEN ADDRESS}"

const Faucet = (props) => {

  const [balance, setBalance] = useState()
  const [showBalance, setShowBalance] = useState(false)


  async function getBalance() {
    if (typeof window.ethereum !== 'undefined') {
      const [account] = await window.ethereum.request({ method: 'eth_requestAccounts' })
      const provider = new ethers.providers.Web3Provider(window.ethereum);
      const contract = new ethers.Contract(tokenAddress, props.tokenContract.abi, provider)
      const balance = await contract.balanceOf(account);
      console.log("Balance: ", balance.toString());
      setBalance(balance.toString());
      setShowBalance(true);
    }
  }

  async function faucet() {
    if (typeof window.ethereum !== 'undefined') {
      const account = await window.ethereum.request({ method: 'eth_requestAccounts' });
      const provider = new ethers.providers.Web3Provider(window.ethereum);
      const signer = provider.getSigner();
      const contract = new ethers.Contract(tokenAddress, props.tokenContract.abi, signer);
      contract.faucet(account[0], 100);
    }
  }
    return (
        <div>
        <Card style={{background: "rgba(227, 104, 222, 0.71)"}}>
        <Card.Body>
        <Card.Subtitle>receive faucet ERC20 to your wallet
        </Card.Subtitle><br></br>
        <div className="d-grid gap-2">
        <Button onClick={faucet}>get faucet token</Button>
        <Button onClick={getBalance} variant="warning">check my balance</Button>   
        </div>
        </Card.Body>
        </Card>
        </div>
    )
}

export default Faucet

On line 7, replace the tokenAddress value with the Token Deployed To address you got from your contract being deployed.

You have declared two async functions getBalance() and faucet(). These need to be asynchronous functions as you are calling the smart contract which lives in the block chain so you need JavaScript to work well with ethereum.

In the function you check to see if the user has MetaMask running, then get the data needed using the ethers.js library and assign that data to local variables. This data is made accessible via the ABI, which you imported into App.js and passed as a property to Faucet.js.

Now you need to import that component in to your App.js at the top of the file:

import Faucet from './components/Faucet.js'

Back on your localhost:3000 you should see something like this: Faucet

The blue background around your Faucet component is because it is wrapped in a react-bootstrap component and was customized inline with CSS styling. The different color buttons are set using the variant property.

๐Ÿ’น Join Robinhood with my link and we will both pick a free stock.


๐Ÿ“ Test The Faucet

Set up your MetaMask wallet so that it connects to your hardhat blockchain node. You get a list of addresses and private keys for testing. Your node should still be running: Faucet

import Alert from 'react-bootstrap/Alert'

const Message = ({ balance }) => {
    return (
      <div>
      <Alert variant="info"> balance : {balance}</Alert>
      </div>
  )
}

export default Message
{ showBalance ? <Message balance={balance}/> : null }
import Message from './Message'
<TokenSend tokenContract={Token}/>
import { useState } from 'react';
import { ethers } from 'ethers'
import Card from 'react-bootstrap/Card'
import Button from 'react-bootstrap/Button'

const tokenAddress = "{YOUR DEPLOYED TOKEN ADDRESS}"

const TokenSend = (props) => {

  const [userAccount, setUserAccount] = useState()
  const [amount, setAmount] = useState()

  // request access to the user's MetaMask account
  async function requestAccount() {
    await window.ethereum.request({ method: 'eth_requestAccounts' });
  }

  async function sendCoins() {
  if (typeof window.ethereum !== 'undefined') {
    await requestAccount()
    const provider = new ethers.providers.Web3Provider(window.ethereum);
    const signer = provider.getSigner();
    const contract = new ethers.Contract(tokenAddress, props.tokenContract.abi, signer);
    const transation = await contract.transfer(userAccount, amount);
    await transation.wait();
    console.log(`${amount} Coins successfully sent to ${userAccount}`);
  }
}
    return (
        <Card style={{background: "rgba(227, 104, 222, 0.71)"}}>
        <Card.Body>
        <Card.Subtitle> send faucet to an address
        </Card.Subtitle>
        <br></br>
        <div className="d-grid gap-2">
        <input onChange={e => setUserAccount(e.target.value)} placeholder="Payee 0x address" />
        <input onChange={e => setAmount(e.target.value)} placeholder="Amount" />
        <Button onClick={sendCoins} variant="success">send </Button>
        </div>
        </Card.Body>
        </Card>
    )
}

export default TokenSend
import TokenSend from './components/TokenSend.js'

๐Ÿ’ฐ Sign up and get $10 of bitcoin free from Coinbase.


๐Ÿ’ฒ Launch On the Goreli Testnet

require("@nomiclabs/hardhat-waffle");
require('dotenv').config({ path: 'variables.env' })

// This is a sample Hardhat task. To learn how to create your own go to
// https://hardhat.org/guides/create-task.html
task("accounts", "Prints the list of accounts", async () => {
  const accounts = await ethers.getSigners();

  for (const account of accounts) {
    console.log(account.address);
  }
});

// You need to export an object to set up your config
// Go to https://hardhat.org/config/ to learn more

/**
 * @type import('hardhat/config').HardhatUserConfig
 */
 module.exports = {
  paths: {
    artifacts: './src/artifacts',
  },
  networks: {
    hardhat: {
      chainId: 1337
    },
    goreli: {
      url: "{YOUR END POINT URL}",
      accounts: [`0x${process.env.PRIVATE_KEY}`]

    }
  },
  solidity: "0.8.3"
};
PRIVATE_KEY="{YOUR-PRIVATE-KEY}"

๐Ÿ•‹ Deploy Your dApp

npx hardhat run scripts/deploy.js --network goreli

Once your contract is deployed you will see this: Deployed Contract

const tokenAddress = "{YOUR-DEPLOYED-TOKEN-ADDRESS}"

๐Ÿ”ผ Upload To A Hosting Service

๐Ÿ’ถ Earn Bitcoin by viewing ads at CoinPayU


๐Ÿ”ถ Summary

You learned how to build a simple single page application that allows a user to receive 100 faucet token (FCT) that you created.

Here is the fully built dApp.

๐Ÿ’“ If you enjoyed the information and the web site, please donate.


Elyse Y. Robinson Elyse Y. Robinson, an enterprising entrepreneur, is the mastermind behind Taxes and Services, a multifaceted holding company that doubles as her accounting firm. Her ventures encompass an array of innovative projects. One of her key initiatives is Switch Into Tech, a dynamic weekly newsletter that doubles as a platform for advertising monthly career seminars, offering weekly tech-related freebies, and promoting her latest podcast episodes of Nobody Wants To Work Tho. Additionally, Elyse shares her insights through her blog at Data.gal, where she delves into various data-related topics. Elyseโ€™s passions extend beyond her businesses; she is deeply enamored with Mexico, has an insatiable appetite for research, and is dedicated to assisting others in transitioning into technology careers.


Subscribe to the Newsletter