Building a Blockchain-based Banking Management System using React.js and Web3

Building a Blockchain-based Banking Management System using React.js and Web3

Blockchain technology is revolutionizing various industries, including finance. By combining blockchain’s decentralized architecture with modern web development frameworks like React.js and Web3, we can build secure, transparent, and efficient financial applications. In this blog, we will walk through the process of building a banking management system using React.js, Web3, and Ethereum smart contracts.

1. Introduction to Blockchain and Web3

Blockchain is a decentralized ledger that records transactions across many computers, making it secure and tamper-proof. In a blockchain-based banking system, transactions like deposits, withdrawals, and transfers can be conducted transparently and efficiently, reducing the need for intermediaries.

Web3 is a collection of libraries that allow us to interact with a blockchain, such as Ethereum, from a web application. By using Web3, we can create smart contracts and interact with the Ethereum blockchain directly through our React.js application.

2. Setting Up the Development Environment

Before we start building the banking management system, we need to set up the necessary tools and libraries.

Prerequisites

  • Node.js and npm: These are required to manage our project dependencies. Install them from Node.js official website.
  • MetaMask: A browser extension that acts as an Ethereum wallet, enabling interactions with the blockchain. Download MetaMask from here.
  • Ganache: A local blockchain environment that helps in developing and testing Ethereum smart contracts.

Install Dependencies

  1. Install Create React App to start a new React project:
npx create-react-app blockchain-banking
cd blockchain-banking

Install Web3 and Solidity dependencies:

npm install web3
npm install -g truffle

Web3 will allow us to interact with the blockchain, and Truffle will help in writing and deploying smart contracts.

3. Writing Smart Contracts in Solidity

The backbone of our blockchain banking system will be a smart contract written in Solidity. This smart contract will handle operations such as account creation, deposits, withdrawals, and balance checks.

Create a contracts directory and a file called Bank.sol inside it:

// contracts/Bank.sol
pragma solidity ^0.8.0;

contract Bank {
    mapping(address => uint256) public balances;

    function deposit() public payable {
        balances[msg.sender] += msg.value;
    }

    function withdraw(uint256 amount) public {
        require(balances[msg.sender] >= amount, "Insufficient balance");
        balances[msg.sender] -= amount;
        payable(msg.sender).transfer(amount);
    }

    function checkBalance() public view returns (uint256) {
        return balances[msg.sender];
    }
}

This contract contains:

  • deposit(): Allows users to deposit Ether into their account.
  • withdraw(): Allows users to withdraw funds from their account.
  • checkBalance(): Lets users check their account balance.

Compile and Deploy the Contract

  1. Create a migration file in the migrations folder:
const Bank = artifacts.require("Bank");

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

Start Ganache and connect it to your local development environment:

ganache-cli

Compile and migrate the contract to the blockchain:

truffle compile
truffle migrate

Now, our smart contract is deployed on the local blockchain.

4. Integrating React.js with Web3

Next, we’ll create a React.js frontend that interacts with the deployed smart contract using Web3.

Setting up Web3 in React

Install Web3 in your React project:

npm install web3

Then, set up a connection to the Ethereum blockchain using Web3 in your App.js file:

import React, { useEffect, useState } from 'react';
import Web3 from 'web3';
import Bank from './contracts/Bank.json';

function App() {
  const [account, setAccount] = useState('');
  const [contract, setContract] = useState(null);
  const [balance, setBalance] = useState(0);
  const [inputAmount, setInputAmount] = useState('');

  useEffect(() => {
    const loadBlockchainData = async () => {
      const web3 = new Web3(Web3.givenProvider || 'http://localhost:7545');
      const accounts = await web3.eth.getAccounts();
      setAccount(accounts[0]);

      const networkId = await web3.eth.net.getId();
      const networkData = Bank.networks[networkId];
      if (networkData) {
        const contractInstance = new web3.eth.Contract(Bank.abi, networkData.address);
        setContract(contractInstance);
      } else {
        alert('Smart contract not deployed to the current network');
      }
    };

    loadBlockchainData();
  }, []);

  const deposit = async () => {
    await contract.methods.deposit().send({
      from: account,
      value: Web3.utils.toWei(inputAmount, 'ether'),
    });
    loadBalance();
  };

  const withdraw = async () => {
    await contract.methods.withdraw(Web3.utils.toWei(inputAmount, 'ether')).send({
      from: account,
    });
    loadBalance();
  };

  const loadBalance = async () => {
    const balance = await contract.methods.checkBalance().call({ from: account });
    setBalance(Web3.utils.fromWei(balance, 'ether'));
  };

  return (
    <div>
      <h1>Blockchain Banking System</h1>
      <p>Account: {account}</p>
      <p>Balance: {balance} ETH</p>

      <input
        type="number"
        value={inputAmount}
        onChange={(e) => setInputAmount(e.target.value)}
        placeholder="Enter amount in Ether"
      />
      <button onClick={deposit}>Deposit</button>
      <button onClick={withdraw}>Withdraw</button>
    </div>
  );
}

export default App;

Explaining the Code

  1. Web3 Setup: We initialize a Web3 instance and connect it to the Ethereum network via Web3.givenProvider. This enables the interaction between the React app and MetaMask.
  2. Smart Contract Integration: We retrieve the deployed smart contract from the blockchain and interact with its functions like deposit(), withdraw(), and checkBalance().
  3. User Interactions: The app allows users to deposit and withdraw Ether, and the balance is fetched from the smart contract.

MetaMask and Testing

Ensure you have MetaMask installed and set to the appropriate local network (Ganache). Once set, MetaMask will prompt you to approve transactions when interacting with the app.

5. Testing the System

To test the banking system:

  1. Start the local blockchain (Ganache) and make sure the contract is deployed.
  2. Open your React app, which should automatically connect to MetaMask.
  3. Deposit Ether using the deposit button and withdraw using the withdraw button. The balance will be updated automatically.

6. Enhancing the Banking Management System

Here are some additional features you can add to improve your blockchain banking system:

  • Transaction History: Store and display a list of user transactions.
  • Multiple Accounts: Allow users to create and manage multiple accounts.
  • Interest Calculation: Implement an interest-earning mechanism for deposited funds.
  • Two-factor Authentication: Increase security by integrating 2FA.
  • Real-world Deployment: Deploy the system on a live Ethereum network using platforms like Infura or Alchemy.

7. Deploying the Application

Once you’ve built your app, you can deploy it on services like Netlify or Vercel. You can also deploy the smart contract to the Ropsten Testnet or Ethereum Mainnet using Infura or Alchemy.

Conclusion

Building a blockchain-based banking management system using React.js, Web3, and Ethereum smart contracts provides a great opportunity to explore decentralized finance. By leveraging the power of blockchain, this system offers transparency, security, and efficiency, eliminating the need for intermediaries like traditional banks. You can further expand this project with more advanced features and real-world applications.

Happy coding!