Blockchain-powered transparent charity platform with Soulbound Tokens ensuring donations reach their intended purpose.
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.
- Problem Statement
- Solution Architecture
- Key Features
- Technology Stack
- Project Structure
- Setup Instructions
- Smart Contract Architecture
- Cryptographic Proof of Disbursement
- Assumptions and Design Decisions
- Security Considerations
- Testing Strategy
- Deployment Guide
- API Documentation
- Contributing
- Misuse of Funds: Donors cannot reliably track how their contributions are spent
- Lack of Accountability: NGOs and charities often provide limited reporting on fund utilization
- Erosion of Trust: Donors hesitate to contribute due to fears of corruption or inefficiency
- Difficulty in Verification: No simple way exists to prove whether donations reached intended beneficiaries
- 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
Instead of transferring funds directly to NGOs to spend freely, we implement a voucher-based system using Soulbound Tokens (SBTs):
- Token Issuance: Smart contracts issue non-transferable tokens to verified beneficiaries
- Entitlement Representation: Each token represents entitlement to specific funds for a specific purpose
- Redemption Mechanism: Service providers (hospitals, schools, etc.) redeem tokens on-chain to receive payment
- Enforcement: Blockchain ensures funds only go to intended causes
Donor → Smart Contract → Soulbound Token → Verified Beneficiary
↓
Service Provider Redeems Token
↓
Smart Contract Releases Funds
- Complete donation tracking from contribution to utilization
- Real-time dashboard showing fund flows
- Cryptographic proof of impact
- Tax receipt generation
- Campaign creation and management
- KYC verification system
- Campaign creation tools
- Fund request management
- Beneficiary registration
- Automated reporting
- Digital identity verification
- Entitlement tokens (SBTs)
- Service redemption tracking
- Privacy-preserving verification
- Token redemption interface
- Payment processing
- Service delivery proof submission
- Revenue tracking
- 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)
- 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)
- Runtime: Node.js 18+
- Framework: Express.js
- Database: MongoDB with Mongoose ODM
- Security: Helmet, CORS, Rate Limiting
- Blockchain Sync: Real-time event polling service
- Off-Chain Storage: IPFS (via Pinata)
- Version Control: Git/GitHub
- Deployment: Vercel (frontend), Railway/AWS (backend) - deployment-ready
- Local Development: Hardhat node for rapid iteration
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
- Node.js 18+ and npm
- Git
- MetaMask browser extension
- MongoDB (local or MongoDB Atlas - free tier works)
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 devThen 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/tofrontend/lib/abi/.
- Clone the repository
git clone https://github.com/iDheer/CharityChain.git
cd CharityChain- Install dependencies
npm install- Install smart contract dependencies
cd contracts
npm install
cd ..- Install frontend dependencies
cd frontend
npm install
cd ..- Install backend dependencies
cd backend
npm install
cd ..- 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_keyFrontend .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_idBackend .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- Start MongoDB
mongod- Compile Smart Contracts
npx hardhat compile- Run Local Blockchain (for development)
npx hardhat node- Deploy Contracts
npx hardhat run scripts/deploy.js --network localhostAlternatively you can deploy to the Sepolia testnet (useful for multi-device/manual testing with real wallets):
npm run deploy:sepolia- Start Backend
cd backend
npm run dev- Start Frontend
cd frontend
npm run devVisit http://localhost:3000 to access the application.
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:
- Create a new NGO (use the frontend or
POST /api/ngos). - Verify the NGO via an admin account (backend governance/admin routes).
- Create a new campaign (NGO account).
- Donate some amount to the campaign (through the frontend or by sending a transaction to the contract).
- Add a beneficiary (use another account). When creating the beneficiary, ensure the
serviceTypeyou supply matches theserviceTypethat will be used when registering the service provider. - Use a third account to register as a service provider (
POST /api/providersor frontend provider registration). - Verify the service provider on-chain (I provide a helper script for localhost):
npx hardhat run scripts/verifyProvider.js --network localhost- Grant the redeemer role to the service provider (helper script for localhost):
npx hardhat run scripts/grantRedeemer.js --network localhost- 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
serviceTypestrings 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.
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
localhostwhen iterating on contracts and frontend code rapidly, running unit tests, or when you need to reset chain state often. - Use
sepoliawhen 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.
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:localNotes:
npm run smoke:localwill run compilation and the deploy script and then attempt to talk to localhost endpoints; it does not start the dev servers for you. Usenpm run start:localto bring up the node + backend + frontend concurrently.- If you plan to test on Sepolia instead, run
npm run deploy:sepoliaand then update yourfrontend/.env.localandbackend/.envwith the sepolia RPC and contract addresses saved by the deploy script.
- 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
- 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
- NGO registration and KYC document submission
- Admin and governance-based verification
- Reputation scoring (0-1000 scale)
- Status management (Pending, Verified, Suspended, Blacklisted)
- Activity logging
- Decentralized NGO verification through community voting
- Challenge mechanism for verified NGOs
- Reputation-weighted voting system
- Proposal lifecycle management
- User reputation tracking
- Provider registration (hospitals, schools, etc.)
- Verification by admins
- Redemption tracking and statistics
- Service type categorization
-
Campaign Creation: NGO creates a campaign (e.g., "Eye Surgeries for 100 Patients")
-
Donation Collection: Donors contribute funds to the campaign smart contract
-
Beneficiary Verification: NGO identifies and verifies beneficiaries off-chain, submits to platform
-
Token Minting: Smart contract mints Soulbound Tokens to beneficiaries' wallets
- Token metadata: { beneficiaryId, campaignId, entitledAmount, serviceType, expiryDate }
-
Service Delivery: Beneficiary visits service provider (e.g., hospital)
-
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
-
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
- 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
-
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)
-
Testnet Development: Sepolia testnet used because:
- Active and well-maintained
- Faucets available for testing
- Similar to mainnet behavior
-
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)
-
Off-Chain Storage: IPFS for documents because:
- Decentralized and censorship-resistant
- Content-addressed (tamper-proof)
- Cost-effective for large files
- Good ecosystem support
-
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
-
NGO Participation: Assumes NGOs willing to:
- Undergo KYC verification
- Adopt new technology
- Share beneficiary data (with consent)
- Pay platform fees (if applicable)
-
Beneficiary Access: Assumes beneficiaries can:
- Access smartphones/computers
- Have internet connectivity
- Understand basic wallet operations
- Or NGOs provide assistance
-
Service Provider Integration: Assumes providers:
- Willing to accept token-based payments
- Can submit digital proofs
- Have technical capability
- Trust smart contract payments
-
Regulatory Compliance: Platform designed to:
- Support KYC/AML requirements
- Enable tax receipt generation
- Maintain audit trails
- Respect data privacy laws (GDPR, etc.)
-
Hybrid Architecture:
- On-chain: Critical trust operations (donations, disbursements)
- Off-chain: Metadata, user profiles, search/discovery
- Rationale: Balance transparency, cost, and user experience
-
Voucher Model vs Direct Transfer:
- Chose voucher/SBT model over direct transfers
- Rationale: Ensures funds reach intended purpose, not just intended organization
-
Role-Based Access:
- Four distinct roles: Donor, NGO, Beneficiary, Service Provider
- Rationale: Clear separation of concerns and permissions
-
Campaign Milestones:
- Support for milestone-based fund release
- Rationale: Allows phased funding and progress tracking
-
Refund Mechanism:
- Donors can request refunds if campaign goals not met
- Rationale: Protects donor interests and builds trust
-
Platform Fees:
- Optional small fee to sustain platform operations
- Rationale: Long-term sustainability without compromising mission
-
Privacy vs Transparency Balance:
- Public: Fund flows, campaign details, aggregate statistics
- Private: Beneficiary personal details, medical records
- Rationale: Maximum transparency without compromising privacy
- Access Control: OpenZeppelin's AccessControl for role management
- Reentrancy Protection: ReentrancyGuard on all fund transfers
- Integer Overflow: Solidity 0.8+ built-in overflow protection
- Pausability: Emergency pause mechanism
- Upgrade Strategy: Transparent proxy pattern for upgrades
- Audit: Contracts should be audited before mainnet deployment
- Authentication: Web3 signature-based authentication
- Input Validation: Zod schemas for all user inputs
- Rate Limiting: API rate limits to prevent abuse
- CORS: Proper CORS configuration
- Environment Variables: Sensitive data in env files
- SQL Injection: Using Mongoose ORM prevents SQL injection
- XSS Protection: React's built-in XSS protection + Content Security Policy
- Personal Data: Stored off-chain with encryption
- IPFS: Only non-sensitive proofs stored on IPFS
- Consent: Explicit consent for data sharing
- Right to Erasure: Off-chain data can be deleted per GDPR
npx hardhat test
npx hardhat coverageTest Coverage:
- Unit tests for each contract
- Integration tests for contract interactions
- Edge cases and failure scenarios
- Gas optimization tests
cd frontend
npm testTest Coverage:
- Component unit tests (Jest + React Testing Library)
- Integration tests for user flows
- E2E tests (Playwright)
- Wallet connection tests
cd backend
npm testTest Coverage:
- API endpoint tests (Supertest)
- Database operations tests
- Authentication/authorization tests
- External service mocking
- Testnet Deployment (Sepolia)
npx hardhat run scripts/deploy.js --network sepolia
npx hardhat verify --network sepolia <CONTRACT_ADDRESS>- Mainnet Deployment
# After thorough testing and audit
npx hardhat run scripts/deploy.js --network mainnet
npx hardhat verify --network mainnet <CONTRACT_ADDRESS>cd frontend
vercel --prodcd backend
# Configure railway.json or AWS Elastic Beanstalk
railway up # or eb deployBase URL: http://localhost:5000/api
POST /auth/login- Web3 signature loginPOST /auth/verify- Verify JWT token
GET /ngos- List all verified NGOsGET /ngos/:id- Get NGO detailsPOST /ngos- Register new NGOPUT /ngos/:id- Update NGO profilePOST /ngos/:id/verify- Submit KYC documents
GET /campaigns- List all campaignsGET /campaigns/:id- Get campaign detailsPOST /campaigns- Create campaign (NGO only)PUT /campaigns/:id- Update campaignPOST /campaigns/:id/beneficiaries- Add beneficiaries
GET /donations- User's donation historyPOST /donations- Record donation (called after blockchain tx)GET /donations/:id/receipt- Generate tax receipt
POST /beneficiaries- Register beneficiaryGET /beneficiaries/:id- Get beneficiary detailsGET /beneficiaries/:id/tokens- Get beneficiary's tokens
GET /providers- List service providersPOST /providers- Register providerPOST /providers/redeem- Process token redemption
Full API documentation available at /api-docs when backend is running.
- Fork the repository
- Create feature branch (
git checkout -b feature/AmazingFeature) - Commit changes (
git commit -m 'Add some AmazingFeature') - Push to branch (
git push origin feature/AmazingFeature) - Open a Pull Request
- 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
MIT License - see LICENSE file for details
- GitHub: @iDheer
- Project Link: https://github.com/iDheer/CharityChain
- Issues: https://github.com/iDheer/CharityChain/issues
- 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.