0% found this document useful (0 votes)
11 views16 pages

Building a Blockchain Donation App

The document describes how to build a donation blockchain app from scratch using Rinkeby test network, Solidity, and Web3.js. It involves creating an ERC20 token contract, deploying it to Rinkeby, creating a donation smart contract that handles donations of the token, deploying this contract, and building a frontend to allow users to donate tokens and view balances.

Uploaded by

frgegtbg
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views16 pages

Building a Blockchain Donation App

The document describes how to build a donation blockchain app from scratch using Rinkeby test network, Solidity, and Web3.js. It involves creating an ERC20 token contract, deploying it to Rinkeby, creating a donation smart contract that handles donations of the token, deploying this contract, and building a frontend to allow users to donate tokens and view balances.

Uploaded by

frgegtbg
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Blockchain technology has revolutionized the way we handle financial transactions.

With the
advent of decentralized applications (dApps), it is now possible to build a secure and transparent
donation platform using an ERC20 token. In this tutorial, we will go through the process of
building a donation blockchain app from scratch using Rinkeby, VS Code, Solidity, and [Link].

Prerequisites

To follow this tutorial, you will need the following:

● A basic understanding of Solidity programming language


● An Ethereum wallet (e.g., MetaMask)
● Infura API key
● VS Code
● [Link] and NPM installed on your computer

Step 1: Creating the ERC20 Token Contract

The first step is to create the ERC20 token contract. Open VS Code and create a new file named
"[Link]". Copy and paste the following code into the file:

pragma solidity ^0.8.0;

contract MyToken {
string public name = "My Token";
string public symbol = "MTK";
uint256 public totalSupply = 1000000;
mapping(address => uint256) public balanceOf;

constructor() {
balanceOf[[Link]] = totalSupply;
}

function transfer(address to, uint256 value) public returns (bool) {


require(balanceOf[[Link]] >= value);
balanceOf[[Link]] -= value;
balanceOf[to] += value;
return true;
}
}

This contract defines a basic ERC20 token with a name, symbol, and total supply. It also
includes a "transfer" function to transfer tokens between addresses.

Step 2: Compiling the Contract

Next, we need to compile the contract. Open the terminal and navigate to the folder where the
"[Link]" file is located. Run the following command to install the Solidity compiler:

npm install -g solc

Once the compiler is installed, run the following command to compile the contract:

solc [Link] --bin --abi --optimize -o ./build

This command will create two files in the "build" folder: "[Link]" and "[Link]".
The "[Link]" file contains the bytecode of the contract, and the "[Link]" file
contains the Application Binary Interface (ABI).

Step 3: Deploying the Contract on Rinkeby

Now we are ready to deploy the contract on Rinkeby. Follow these steps to deploy the contract:

1. Open MetaMask and select "Rinkeby Test Network" as the network.


2. Click on the three dots in the top right corner and select "Copy Address to clipboard".
This is the address of your MetaMask account.
3. Go to Infura ([Link] and sign up for an account.
4. Create a new project and copy the project ID.
5. In VS Code, create a new file named "[Link]" and copy and paste the following code:

const Web3 = require('web3');


const fs = require('fs');
const web3 = new Web3('[Link]
const bytecode = [Link]('./build/[Link]').toString();
const abi = [Link]([Link]('./build/[Link]').toString());
const myToken = new [Link](abi);
[Link]({
data: '0x' + bytecode,
arguments: []
}).send({
from: 'YOUR-METAMASK-ADDRESS',
gas: 1500000,
gasPrice: [Link]('0.00003', 'ether')
}).

This code uses the [Link] library to interact with the Ethereum network. We first create an
instance of the Web3 object with the Infura endpoint for the Rinkeby test network. We then read
in the bytecode and ABI files that we compiled earlier. Finally, we create a new instance of the
contract using the ABI, and deploy it to the network using the bytecode.

Replace the "YOUR-PROJECT-ID" and "YOUR-METAMASK-ADDRESS" placeholders with


your Infura project ID and MetaMask account address, respectively.

6. Save the "[Link]" file and run the following command in the terminal:

node [Link]

This will deploy the contract on the Rinkeby test network. You should see the contract address
printed in the terminal.

Step 4: Creating the Donation Smart Contract

Now that we have deployed the ERC20 token contract, we need to create a smart contract to
handle the donation process. Open VS Code and create a new file named "[Link]". Copy
and paste the following code into the file:

pragma solidity ^0.8.0;

import "./[Link]";

contract Donation {
MyToken public token;
address public owner;
constructor(address _token) {
token = MyToken(_token);
owner = [Link];
}

function donate(uint256 _amount) public {


require(_amount > 0);
require([Link]([Link]) >= _amount);
[Link]([Link], owner, _amount);
}
}

This contract imports the previously deployed "MyToken" contract and creates a new "Donation"
contract. The constructor takes the address of the "MyToken" contract as a parameter and
initializes the "token" and "owner" variables. The "donate" function allows users to donate
tokens to the "owner" address.

Step 5: Compiling and Deploying the Donation Smart Contract

We now need to compile and deploy the "Donation" contract. Follow these steps:

1. In the terminal, run the following command to compile the contract:

solc [Link] --bin --abi --optimize -o ./build

2. In the "[Link]" file, add the following code below the previous code:

const donationBytecode = [Link]('./build/[Link]').toString();

const donationAbi = [Link]([Link]('./build/[Link]').toString());

const donation = new [Link](donationAbi);


[Link]({

data: '0x' + donationBytecode,

arguments: [[Link]]

}).send({

from: 'YOUR-METAMASK-ADDRESS',

gas: 1500000,

gasPrice: [Link]('0.00003', 'ether')

}).then((instance) => {

[Link]('Donation contract deployed at address: ' + [Link]);

});

This code reads in the bytecode and ABI of the "Donation" contract and creates a new
instance of the contract. It then deploys the contract to the network using the address of
the "MyToken" contract as a parameter.

3. Save the "[Link]" file and run the following command in the terminal:

node [Link]
This will deploy the "Donation" contract on the Rinkeby test network. You should see the
contract address printed in the terminal.

Step 6: Building the Frontend

The final step is to build the frontend of the donation app. This requires knowledge of web
development and the [Link] library. Here is a basic outline of what the frontend should do:

1. Connect to the Ethereum network


2. Instantiate the "MyToken" and "Donation" contracts using their respective ABI files and
addresses on the Rinkeby test network.
3. Allow the user to input the amount of tokens they want to donate and call the "donate"
function of the "Donation" contract with that amount.
4. Display the user's token balance, the balance of the "MyToken" contract, and the balance
of the "Donation" contract.
5. Update the display in real-time when a donation is made or when the balances change.

Here is some sample code for the frontend:

<!DOCTYPE html>

<html>

<head>

<title>Donation App</title>

<script src="[Link]

<script src="./[Link]"></script>

<script src="./[Link]"></script>
<script>

let web3;

let myToken;

let donation;

let accounts;

async function init() {

// Connect to the Ethereum network

if (typeof [Link] !== 'undefined') {

web3 = new Web3([Link]);

await [Link]();

accounts = await [Link]();

} else {

alert("Please install MetaMask to use this app!");

}
// Instantiate the contracts

const myTokenAddress = 'MYTOKEN-ADDRESS';

const donationAddress = 'DONATION-ADDRESS';

myToken = new [Link](myTokenAbi, myTokenAddress);

donation = new [Link](donationAbi, donationAddress);

// Display the user's token balance

const userBalance = await [Link](accounts[0]).call();

[Link]("user-balance").innerHTML = "Your token balance: "


+ userBalance;

// Display the balance of the MyToken contract

const myTokenBalance = await


[Link](myTokenAddress).call();
[Link]("mytoken-balance").innerHTML = "MyToken
balance: " + myTokenBalance;

// Display the balance of the Donation contract

const donationBalance = await


[Link](donationAddress).call();

[Link]("donation-balance").innerHTML = "Donation
balance: " + donationBalance;

async function donate() {

const amount = [Link]("donation-amount").value;

// Call the donate function of the Donation contract

await [Link](amount).send({from: accounts[0]});

// Update the display


const userBalance = await [Link](accounts[0]).call();

[Link]("user-balance").innerHTML = "Your token balance: "


+ userBalance;

const donationBalance = await


[Link](donationAddress).call();

[Link]("donation-balance").innerHTML = "Donation
balance: " + donationBalance;

</script>

</head>

<body onload="init()">

<h1>Donation App</h1>

<label for="donation-amount">Amount to donate:</label>

<input type="number" id="donation-amount"><br><br>

<button onclick="donate()">Donate</button><br><br>

<div id="user-balance"></div>
<div id="mytoken-balance"></div>

<div id="donation-balance"></div>

</body>

</html>

This code uses the [Link] library to connect to the Ethereum network and instantiate the

"MyToken

and "Donation" contracts. The init() function is called when the page loads and displays the
user's token balance, the balance of the "MyToken" contract, and the balance of the "Donation"
contract. The donate() function is called when the user clicks the "Donate" button and calls the
"donate" function of the "Donation" contract with the amount of tokens the user wants to donate.
It then updates the display with the new balances.

Here is the code for the "MyToken" contract:

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "@openzeppelin/contracts/token/ERC20/[Link]";

contract MyToken is ERC20 {


constructor() ERC20("MyToken", "MTK") {

_mint([Link], 1000000000000000000000000); // Mint 1,000,000 tokens to the


contract creator

This contract extends the ERC20 standard and mints 1,000,000 tokens to the contract creator
upon deployment.

Here is the code for the "Donation" contract:

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "./[Link]";

contract Donation {

MyToken public myToken;

address public owner;


constructor(address _myToken) {

myToken = MyToken(_myToken);

owner = [Link];

function donate(uint256 _amount) public {

require([Link]([Link], address(this), _amount), "Transfer


failed"); // Transfer tokens to the contract

function withdraw() public {

require([Link] == owner, "Only the contract owner can withdraw"); // Ensure


only the owner can withdraw

uint256 balance = [Link](address(this));

[Link](owner, balance); // Transfer all tokens in the contract to the owner


}

This contract accepts donations of "MyToken" tokens by calling the "donate" function, which

transfers the tokens to the contract. The contract owner can then withdraw the tokens by calling

the "withdraw" function.

To deploy these contracts on the Rinkeby test network, you can use Remix IDE or the Truffle

suite. Here are the steps to deploy with Remix IDE:

1. Copy the "MyToken" and "Donation" contract code into separate files in Remix IDE.
2. Select the "Solidity Compiler" plugin and set the compiler version to 0.8.0.
3. Compile the contracts by clicking the "Compile" button.
4. Select the "Deploy & run transactions" plugin and set the environment to "Injected
Web3" (which uses MetaMask).
5. Deploy the "MyToken" contract by clicking the "Deploy" button and confirming the
transaction in MetaMask.
6. Copy the deployed "MyToken" contract address and use it to instantiate the "Donation"
contract in the same way.
7. Deploy the "Donation" contract by clicking the "Deploy" button and confirming the
transaction in MetaMask.
8. Copy the deployed "Donation" contract address and use it in your frontend code.

To deploy with the Truffle suite, you can create a Truffle project and add the "MyToken" and

"Donation" contracts to the "contracts" directory. You will also need to create a deployment

script for each contract in the "migrations" directory. Here is an example deployment script for

the "MyToken" contract:


// SPDX-License-Identifier: MIT
const MyToken = [Link]("MyToken");

[Link] = async function (deployer) {


await [Link](MyToken

);
};

And here is an example deployment script for the "Donation" contract:


// SPDX-License-Identifier: MIT
const MyToken = [Link]("MyToken");

const Donation = [Link]("Donation");

[Link] = async function (deployer) {


const myToken = await [Link]();
await [Link](Donation, [Link]);

};

To deploy to the Rinkeby test network with Truffle, you will need to set up a Rinkeby network
configuration in the "[Link]" file and create a Rinkeby account in MetaMask to use as
your deployment account.

Once you have deployed the contracts, you can use [Link] to interact with them in your
frontend code. Here is an example "[Link]" file that initializes the "MyToken" and "Donation"
contracts and allows the user to donate tokens:

const Web3 = require("web3");


const MyToken = require("./build/contracts/[Link]");

const Donation = require("./build/contracts/[Link]");

const web3 = new Web3("[Link]


const myToken = new [Link]([Link], "MY_TOKEN_ADDRESS");
const donation = new [Link]([Link], "DONATION_ADDRESS");

async function init() {


const accounts = await [Link]();
const myBalance = await [Link](accounts[0]).call();
const donationBalance = await [Link]([Link]).call();
[Link]("my-balance").textContent = myBalance;
[Link]("donation-balance").textContent = donationBalance;

async function donate() {


const amount = [Link]("donate-amount").value;
await [Link]([Link], amount).send({ from: accounts[0]
});
await [Link](amount).send({ from: accounts[0] });
const myBalance = await [Link](accounts[0]).call();
const donationBalance = await [Link]([Link]).call();
[Link]("my-balance").textContent = myBalance;
[Link]("donation-balance").textContent = donationBalance;

[Link]("DOMContentLoaded", init);

[Link]("donate-btn").addEventListener("click", donate);

This code initializes the "MyToken" and "Donation" contracts, displays the user's token balance
and the balance of the "Donation" contract on the page load, and allows the user to donate tokens
by clicking the "Donate" button. It also updates the display with the new balances after each
donation.

In summary, building a donation blockchain app using an ERC20 token involves creating and
deploying the "MyToken" and "Donation" contracts, and using [Link] to interact with them in a
frontend application. By following the steps outlined in this article, you should be able to create a
functional donation app that allows users to donate tokens to a specific cause or organization.

You might also like