Skip to content

iDheer/CharityChain

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

21 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

CharityChain 🔗💚

Blockchain-powered transparent charity platform with Soulbound Tokens ensuring donations reach their intended purpose.

License: MIT Solidity Next.js

Project Overview

CharityChain is a decentralized charity platform that ensures complete transparency in donation tracking and fund disbursement using blockchain technology, smart contracts, and cryptographic proof of disbursement.

Table of Contents

Problem Statement

Issues Addressed

  1. Misuse of Funds: Donors cannot reliably track how their contributions are spent
  2. Lack of Accountability: NGOs and charities often provide limited reporting on fund utilization
  3. Erosion of Trust: Donors hesitate to contribute due to fears of corruption or inefficiency
  4. Difficulty in Verification: No simple way exists to prove whether donations reached intended beneficiaries

Importance

  • Donor Confidence: Transparency encourages more contributions
  • Better Impact: Funds reach intended causes effectively, maximizing social benefit
  • Fraud Prevention: Immutable records reduce corruption and financial mismanagement
  • Scalability: Applicable globally across disaster relief, education, healthcare, and community development

Solution Architecture

Core Innovation: Cryptographic Proof of Disbursement

Instead of transferring funds directly to NGOs to spend freely, we implement a voucher-based system using Soulbound Tokens (SBTs):

  1. Token Issuance: Smart contracts issue non-transferable tokens to verified beneficiaries
  2. Entitlement Representation: Each token represents entitlement to specific funds for a specific purpose
  3. Redemption Mechanism: Service providers (hospitals, schools, etc.) redeem tokens on-chain to receive payment
  4. Enforcement: Blockchain ensures funds only go to intended causes

Example Flow

Donor → Smart Contract → Soulbound Token → Verified Beneficiary
                              ↓
                    Service Provider Redeems Token
                              ↓
                    Smart Contract Releases Funds

Key Features

For Donors

  • Complete donation tracking from contribution to utilization
  • Real-time dashboard showing fund flows
  • Cryptographic proof of impact
  • Tax receipt generation
  • Campaign creation and management

For NGOs

  • KYC verification system
  • Campaign creation tools
  • Fund request management
  • Beneficiary registration
  • Automated reporting

For Beneficiaries

  • Digital identity verification
  • Entitlement tokens (SBTs)
  • Service redemption tracking
  • Privacy-preserving verification

For Service Providers

  • Token redemption interface
  • Payment processing
  • Service delivery proof submission
  • Revenue tracking

Technology Stack

Blockchain Layer

  • Platform: Ethereum (Sepolia testnet for development)
  • Smart Contracts: Solidity 0.8.20+
  • Development Framework: Hardhat
  • Testing: Hardhat, Chai, Ethers.js
  • Token Standards: ERC-721 (for Soulbound Tokens)

Frontend

  • Framework: Next.js 14 (App Router)
  • Blockchain Integration: wagmi + viem (ethers.js compatible)
  • Wallet Connection: RainbowKit (MetaMask, Coinbase Wallet)
  • UI Library: Tailwind CSS
  • State Management: React Query (@tanstack/react-query)

Backend

  • Runtime: Node.js 18+
  • Framework: Express.js
  • Database: MongoDB with Mongoose ODM
  • Security: Helmet, CORS, Rate Limiting
  • Blockchain Sync: Real-time event polling service

Storage

  • Off-Chain Storage: IPFS (via Pinata)

DevOps

  • Version Control: Git/GitHub
  • Deployment: Vercel (frontend), Railway/AWS (backend) - deployment-ready
  • Local Development: Hardhat node for rapid iteration

Project Structure

blockchain-charity-platform/
├── contracts/                    # Smart contracts (Solidity 0.8.20+)
│   ├── CampaignFactory.sol      # Campaign creation & fund management
│   ├── SoulboundToken.sol       # Non-transferable beneficiary tokens (ERC-721)
│   ├── NGORegistry.sol          # NGO verification & management
│   ├── NGOGovernance.sol        # Decentralized governance & voting
│   └── ServiceProviderRegistry.sol # Service provider management
├── test/                        # Smart contract tests (Hardhat + Chai)
├── scripts/                     # Deployment & utility scripts
│   ├── deploy.js                # Main deployment script
│   ├── verifyProvider.js        # Helper to verify service providers
│   ├── grantRedeemer.js         # Helper to grant redeemer role
│   └── healthCheck.js           # Environment health check
├── frontend/                    # Next.js 14 frontend (App Router)
│   ├── app/                     # App router pages
│   ├── components/              # React components
│   ├── lib/                     # Utilities, contracts, API client
│   └── types/                   # TypeScript types
├── backend/                     # Node.js/Express backend
│   ├── src/
│   │   ├── routes/              # API routes (RESTful)
│   │   ├── models/              # MongoDB/Mongoose models
│   │   ├── services/            # Blockchain sync & IPFS services
│   │   └── utils/               # Logger & utilities
├── deployments/                 # Deployment artifacts (auto-generated)
├── docs/                        # Documentation
├── hardhat.config.js            # Hardhat configuration
├── package.json                 # Root package.json
└── README.md                    # This file

Setup Instructions

Prerequisites

  • Node.js 18+ and npm
  • Git
  • MetaMask browser extension
  • MongoDB (local or MongoDB Atlas - free tier works)

🚀 Quick Start (Recommended)

The fastest way to get CharityChain running locally:

# 1. Clone and install all dependencies
git clone https://github.com/iDheer/CharityChain.git
cd CharityChain
npm install
cd backend && npm install && cd ..
cd frontend && npm install && cd ..

# 2. Start local blockchain
npx hardhat node

# 3. Deploy contracts (in a new terminal)
npm run deploy:local

# 4. Start backend (in a new terminal)
cd backend && npm run dev

# 5. Start frontend (in a new terminal)
cd frontend && npm run dev

Then open http://localhost:3000 and connect MetaMask to localhost:8545 (Chain ID: 31337).

Note: If you modify any smart contract, redeploy and copy the new ABI files from artifacts/contracts/ to frontend/lib/abi/.

Detailed Installation

  1. Clone the repository
git clone https://github.com/iDheer/CharityChain.git
cd CharityChain
  1. Install dependencies
npm install
  1. Install smart contract dependencies
cd contracts
npm install
cd ..
  1. Install frontend dependencies
cd frontend
npm install
cd ..
  1. Install backend dependencies
cd backend
npm install
cd ..
  1. Environment Configuration

Create .env files in root, frontend, and backend directories:

Root .env (for Hardhat)

PRIVATE_KEY=your_private_key_here
SEPOLIA_RPC_URL=https://sepolia.infura.io/v3/your_infura_key
ETHERSCAN_API_KEY=your_etherscan_api_key

Frontend .env.local

NEXT_PUBLIC_CHAIN_ID=11155111
NEXT_PUBLIC_RPC_URL=https://sepolia.infura.io/v3/your_infura_key
NEXT_PUBLIC_CONTRACT_ADDRESS=deployed_contract_address
NEXT_PUBLIC_API_URL=http://localhost:5000/api
NEXT_PUBLIC_WALLETCONNECT_PROJECT_ID=your_walletconnect_id

Backend .env

PORT=5000
MONGODB_URI=mongodb://localhost:27017/charity_platform
JWT_SECRET=your_jwt_secret
PINATA_API_KEY=your_pinata_api_key
PINATA_SECRET_KEY=your_pinata_secret
ETHEREUM_RPC_URL=https://sepolia.infura.io/v3/your_infura_key
CONTRACT_ADDRESS=deployed_contract_address

Running the Application

  1. Start MongoDB
mongod
  1. Compile Smart Contracts
npx hardhat compile
  1. Run Local Blockchain (for development)
npx hardhat node
  1. Deploy Contracts
npx hardhat run scripts/deploy.js --network localhost

Alternatively you can deploy to the Sepolia testnet (useful for multi-device/manual testing with real wallets):

npm run deploy:sepolia
  1. Start Backend
cd backend
npm run dev
  1. Start Frontend
cd frontend
npm run dev

Visit http://localhost:3000 to access the application.

Main Flow (local / developer sequence)

Follow this sequence to exercise the main end-to-end flow on a local Hardhat node. This reflects the current implemented flow in the repo:

  1. Create a new NGO (use the frontend or POST /api/ngos).
  2. Verify the NGO via an admin account (backend governance/admin routes).
  3. Create a new campaign (NGO account).
  4. Donate some amount to the campaign (through the frontend or by sending a transaction to the contract).
  5. Add a beneficiary (use another account). When creating the beneficiary, ensure the serviceType you supply matches the serviceType that will be used when registering the service provider.
  6. Use a third account to register as a service provider (POST /api/providers or frontend provider registration).
  7. Verify the service provider on-chain (I provide a helper script for localhost):
npx hardhat run scripts/verifyProvider.js --network localhost
  1. Grant the redeemer role to the service provider (helper script for localhost):
npx hardhat run scripts/grantRedeemer.js --network localhost
  1. Redeem the token from the service provider account (on-chain redeem call / frontend redemption flow). After successful redemption the token is marked redeemed and funds are released to the provider.

Notes:

  • Make sure the serviceType strings match exactly between beneficiary creation and provider registration; mismatches will prevent redemption.
  • The scripts above are written to work against a local Hardhat network and assume the contract addresses from a local deployment.

Local vs Testnet (Sepolia) — which should you use?

Short answer:

  • For fast iterative development, unit tests, and debugging, use the local Hardhat node (localhost). It's quick to reset and gives you deterministic accounts with large balances.
  • For multi-device manual testing, wallet UX validation, and closer-to-production behavior, deploy to Sepolia. Sepolia uses live Ethereum clients and real wallets, so it surfaces issues that only appear off a single local node (for example MetaMask network settings, CORS, provider timeouts, and 3rd-party RPC behavior).

What Sepolia gives you:

  • A public testnet with real network propagation and peers (not a single local process). This more closely matches mainnet behaviour for wallets and relays.
  • The ability to use standard RPC providers (Infura/Alchemy), so you can test how the app behaves with provider rate limits and real HTTP RPC semantics.
  • Easier manual testing with separate devices/browsers because the chain is globally accessible.

When to use each:

  • Use localhost when iterating on contracts and frontend code rapidly, running unit tests, or when you need to reset chain state often.
  • Use sepolia when you want to validate cross-device flows (e.g., a donor on a phone using MetaMask Mobile), test contract verification on block explorers, or validate integration with public RPC providers.

Security and cost notes:

  • Sepolia uses test ETH you get from faucets; there are no real-money costs, but requests to public RPCs may be rate-limited.
  • Never use mainnet keys or secrets when deploying to Sepolia; keep your private keys safe.

Quick smoke tests and health checks

I added a small health-check script to help confirm your local dev environment is working. It checks the Hardhat RPC, backend /health endpoint, and the frontend server.

  • Run the quick health check (assumes you already started Hardhat node, backend, and frontend):
npm run health:check
  • Run an automated local smoke sequence (compile → deploy to localhost → health checks):
npm run smoke:local

Notes:

  • npm run smoke:local will run compilation and the deploy script and then attempt to talk to localhost endpoints; it does not start the dev servers for you. Use npm run start:local to bring up the node + backend + frontend concurrently.
  • If you plan to test on Sepolia instead, run npm run deploy:sepolia and then update your frontend/.env.local and backend/.env with the sepolia RPC and contract addresses saved by the deploy script.

Smart Contract Architecture

1. CampaignFactory.sol

  • Campaign creation and management by verified NGOs
  • Milestone tracking with proof submission
  • Donation collection and fund management
  • Beneficiary token issuance (SBTs)
  • Platform fee handling (configurable, default 2.5%)
  • Pause/unpause functionality for emergencies

2. SoulboundToken.sol (Key Innovation)

  • Non-transferable ERC-721 tokens for beneficiaries
  • Entitlement representation (funds for specific services)
  • Redemption logic by authorized service providers
  • Expiry management and token revocation
  • Full audit trail on-chain

Key Properties:

  • Non-transferable: Cannot be sold or transferred (soulbound)
  • Verifiable: Linked to beneficiary identity
  • Redeemable: Service providers can redeem for payment
  • Traceable: Full on-chain history

3. NGORegistry.sol

  • NGO registration and KYC document submission
  • Admin and governance-based verification
  • Reputation scoring (0-1000 scale)
  • Status management (Pending, Verified, Suspended, Blacklisted)
  • Activity logging

4. NGOGovernance.sol

  • Decentralized NGO verification through community voting
  • Challenge mechanism for verified NGOs
  • Reputation-weighted voting system
  • Proposal lifecycle management
  • User reputation tracking

5. ServiceProviderRegistry.sol

  • Provider registration (hospitals, schools, etc.)
  • Verification by admins
  • Redemption tracking and statistics
  • Service type categorization

Cryptographic Proof of Disbursement

How It Works

  1. Campaign Creation: NGO creates a campaign (e.g., "Eye Surgeries for 100 Patients")

  2. Donation Collection: Donors contribute funds to the campaign smart contract

  3. Beneficiary Verification: NGO identifies and verifies beneficiaries off-chain, submits to platform

  4. Token Minting: Smart contract mints Soulbound Tokens to beneficiaries' wallets

    • Token metadata: { beneficiaryId, campaignId, entitledAmount, serviceType, expiryDate }
  5. Service Delivery: Beneficiary visits service provider (e.g., hospital)

  6. Token Redemption:

    • Service provider verifies beneficiary identity
    • Provider submits proof of service delivery to IPFS
    • Provider calls redeemToken() with token ID and IPFS hash
    • Smart contract verifies token validity
    • Funds are released to service provider
    • Token is marked as redeemed
  7. Verification: All stakeholders can verify:

    • Donor: Their funds went to specific beneficiary
    • NGO: Service was delivered
    • Beneficiary: They received the service
    • Public: Full transparency of fund flow

Security Features

  • Soulbound Nature: Tokens cannot be traded or sold
  • Time-Limited: Tokens expire if not redeemed
  • Proof Required: Service delivery proof must be submitted
  • Multi-Signature: High-value redemptions require multiple approvals
  • Audit Trail: Immutable on-chain record of entire process

Assumptions and Design Decisions

Technical Assumptions

  1. Blockchain Selection: Ethereum chosen for:

    • Mature ecosystem and tooling
    • Strong security track record
    • Wide adoption and developer community
    • ERC standards support
    • Alternative: Polygon for lower gas costs (deployment option)
  2. Testnet Development: Sepolia testnet used because:

    • Active and well-maintained
    • Faucets available for testing
    • Similar to mainnet behavior
  3. Token Standard: ERC-721 adapted for Soulbound Tokens because:

    • NFT standard widely understood
    • Easy to modify transfer restrictions
    • Rich metadata support
    • Marketplace infrastructure available (even if not used)
  4. Off-Chain Storage: IPFS for documents because:

    • Decentralized and censorship-resistant
    • Content-addressed (tamper-proof)
    • Cost-effective for large files
    • Good ecosystem support
  5. Database: MongoDB for off-chain data because:

    • Flexible schema for diverse NGO/campaign types
    • Good performance for read-heavy operations
    • Easy integration with Node.js
    • Suitable for user profiles and metadata

Business Assumptions

  1. NGO Participation: Assumes NGOs willing to:

    • Undergo KYC verification
    • Adopt new technology
    • Share beneficiary data (with consent)
    • Pay platform fees (if applicable)
  2. Beneficiary Access: Assumes beneficiaries can:

    • Access smartphones/computers
    • Have internet connectivity
    • Understand basic wallet operations
    • Or NGOs provide assistance
  3. Service Provider Integration: Assumes providers:

    • Willing to accept token-based payments
    • Can submit digital proofs
    • Have technical capability
    • Trust smart contract payments
  4. Regulatory Compliance: Platform designed to:

    • Support KYC/AML requirements
    • Enable tax receipt generation
    • Maintain audit trails
    • Respect data privacy laws (GDPR, etc.)

Design Decisions

  1. Hybrid Architecture:

    • On-chain: Critical trust operations (donations, disbursements)
    • Off-chain: Metadata, user profiles, search/discovery
    • Rationale: Balance transparency, cost, and user experience
  2. Voucher Model vs Direct Transfer:

    • Chose voucher/SBT model over direct transfers
    • Rationale: Ensures funds reach intended purpose, not just intended organization
  3. Role-Based Access:

    • Four distinct roles: Donor, NGO, Beneficiary, Service Provider
    • Rationale: Clear separation of concerns and permissions
  4. Campaign Milestones:

    • Support for milestone-based fund release
    • Rationale: Allows phased funding and progress tracking
  5. Refund Mechanism:

    • Donors can request refunds if campaign goals not met
    • Rationale: Protects donor interests and builds trust
  6. Platform Fees:

    • Optional small fee to sustain platform operations
    • Rationale: Long-term sustainability without compromising mission
  7. Privacy vs Transparency Balance:

    • Public: Fund flows, campaign details, aggregate statistics
    • Private: Beneficiary personal details, medical records
    • Rationale: Maximum transparency without compromising privacy

Security Considerations

Smart Contract Security

  1. Access Control: OpenZeppelin's AccessControl for role management
  2. Reentrancy Protection: ReentrancyGuard on all fund transfers
  3. Integer Overflow: Solidity 0.8+ built-in overflow protection
  4. Pausability: Emergency pause mechanism
  5. Upgrade Strategy: Transparent proxy pattern for upgrades
  6. Audit: Contracts should be audited before mainnet deployment

Application Security

  1. Authentication: Web3 signature-based authentication
  2. Input Validation: Zod schemas for all user inputs
  3. Rate Limiting: API rate limits to prevent abuse
  4. CORS: Proper CORS configuration
  5. Environment Variables: Sensitive data in env files
  6. SQL Injection: Using Mongoose ORM prevents SQL injection
  7. XSS Protection: React's built-in XSS protection + Content Security Policy

Data Privacy

  1. Personal Data: Stored off-chain with encryption
  2. IPFS: Only non-sensitive proofs stored on IPFS
  3. Consent: Explicit consent for data sharing
  4. Right to Erasure: Off-chain data can be deleted per GDPR

Testing Strategy

Smart Contract Testing

npx hardhat test
npx hardhat coverage

Test Coverage:

  • Unit tests for each contract
  • Integration tests for contract interactions
  • Edge cases and failure scenarios
  • Gas optimization tests

Frontend Testing

cd frontend
npm test

Test Coverage:

  • Component unit tests (Jest + React Testing Library)
  • Integration tests for user flows
  • E2E tests (Playwright)
  • Wallet connection tests

Backend Testing

cd backend
npm test

Test Coverage:

  • API endpoint tests (Supertest)
  • Database operations tests
  • Authentication/authorization tests
  • External service mocking

Deployment Guide

Smart Contracts

  1. Testnet Deployment (Sepolia)
npx hardhat run scripts/deploy.js --network sepolia
npx hardhat verify --network sepolia <CONTRACT_ADDRESS>
  1. Mainnet Deployment
# After thorough testing and audit
npx hardhat run scripts/deploy.js --network mainnet
npx hardhat verify --network mainnet <CONTRACT_ADDRESS>

Frontend Deployment (Vercel)

cd frontend
vercel --prod

Backend Deployment (Railway/AWS)

cd backend
# Configure railway.json or AWS Elastic Beanstalk
railway up  # or eb deploy

API Documentation

Backend API Endpoints

Base URL: http://localhost:5000/api

Authentication

  • POST /auth/login - Web3 signature login
  • POST /auth/verify - Verify JWT token

NGOs

  • GET /ngos - List all verified NGOs
  • GET /ngos/:id - Get NGO details
  • POST /ngos - Register new NGO
  • PUT /ngos/:id - Update NGO profile
  • POST /ngos/:id/verify - Submit KYC documents

Campaigns

  • GET /campaigns - List all campaigns
  • GET /campaigns/:id - Get campaign details
  • POST /campaigns - Create campaign (NGO only)
  • PUT /campaigns/:id - Update campaign
  • POST /campaigns/:id/beneficiaries - Add beneficiaries

Donations

  • GET /donations - User's donation history
  • POST /donations - Record donation (called after blockchain tx)
  • GET /donations/:id/receipt - Generate tax receipt

Beneficiaries

  • POST /beneficiaries - Register beneficiary
  • GET /beneficiaries/:id - Get beneficiary details
  • GET /beneficiaries/:id/tokens - Get beneficiary's tokens

Service Providers

  • GET /providers - List service providers
  • POST /providers - Register provider
  • POST /providers/redeem - Process token redemption

Full API documentation available at /api-docs when backend is running.

Contributing

  1. Fork the repository
  2. Create feature branch (git checkout -b feature/AmazingFeature)
  3. Commit changes (git commit -m 'Add some AmazingFeature')
  4. Push to branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

Development Guidelines

  • Follow Solidity style guide for smart contracts
  • Use ESLint configuration for JavaScript/TypeScript
  • Write tests for all new features
  • Update documentation
  • Keep commits atomic and well-described

License

MIT License - see LICENSE file for details

Contact & Support

Acknowledgments

  • OpenZeppelin for secure smart contract libraries
  • Ethereum Foundation for blockchain infrastructure
  • RainbowKit for wallet connection
  • Next.js team for excellent framework
  • The open source community
  • Open source community

Note: This is a complex project requiring significant development time. Prioritize MVP features first, then iterate with additional functionality.

About

Blockchain-powered transparent charity platform with Soulbound Tokens ensuring donations reach their intended purpose.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors