π A decentralized application (DApp) for managing university elections and professor enrollment built on Ethereum blockchain. This system enables universities to participate in transparent, secure elections while managing professor enrollments with smart contract-enforced rules.
β‘ Built on Scaffold-ETH 2 framework using Next.js, RainbowKit, Hardhat, Wagmi, Viem, and TypeScript.
π Features
ποΈ University Management
- Dynamic University Registration: President can add/remove universities (not hardcoded)
- Professor Enrollment: Universities can enroll professors with a 10 wei fee
- Capacity Management: Maximum 30 professors per university
- Fee Distribution: Enrollment fees are automatically transferred to universities
π³οΈ Election System
- Election Lifecycle: Universities can start elections with a 100 wei fee
- Voting Mechanism: Encrypted voting system with JSON-based vote structure
- Election Status: Three states - NO_ELECTION, IN_PROGRESS, CLOSED
- Time-based Elections: Elections run for 1000 blocks (configurable)
- Quorum Requirements: Requires majority participation for valid elections
π Security & Transparency
- Smart Contract Enforcement: All rules enforced at blockchain level
- Transparent Voting: Immutable vote records on blockchain
- Access Control: Only registered universities can participate
- Fee Management: Automatic fee handling and refunds
π οΈ Development Tools
- Contract Hot Reload: Frontend auto-adapts to smart contract changes
- Custom Hooks: TypeScript-enabled React hooks for contract interactions
- Debug Interface: Built-in contract debugging and testing tools
- Block Explorer: Integrated blockchain explorer for transaction tracking
ποΈ Architecture
Smart Contract Structure
YourContract.sol
βββ University Management
β βββ universityProfessors (mapping)
β βββ isUniversity (mapping)
β βββ universityNames (mapping)
β βββ professorToUniversity (mapping)
βββ Election System
β βββ votesMap (mapping)
β βββ hasVoted (mapping)
β βββ VOTE_STATUS (enum)
β βββ electionEndBlock
βββ Fee Management
β βββ ENROLLMENT_FEE (10 wei)
β βββ ELECTION_START_FEE (100 wei)
β βββ feeHoldingAddress
β βββ heldFee
βββ Governance
βββ currentPresident
βββ President-only functions
Frontend Architecture
packages/nextjs/
βββ app/
β βββ page.tsx (Main voting interface)
β βββ debug/ (Contract debugging tools)
β βββ blockexplorer/ (Blockchain explorer)
βββ components/scaffold-eth/ (Reusable Web3 components)
βββ hooks/scaffold-eth/ (Custom contract interaction hooks)
βββ contracts/ (Auto-generated contract interfaces)
π Getting Started
Prerequisites
- Node.js (>= v20.18.3)
- Yarn (v1 or v2+)
- Git
- MetaMask or compatible Web3 wallet
Installation
Clone the repository
git clone https://github.com/your-username/university-election-dapp.git cd university-election-dapp
Install dependencies
yarn install
Start local blockchain
yarn chain
This starts a local Hardhat network with pre-configured accounts.
Deploy smart contracts
yarn deploy
Deploys the YourContract.sol to the local network. Universities need to be added by the president after deployment.
Launch the application
yarn start
Access the DApp at
http://localhost:3000
Initial Setup
After deployment, the contract deployer becomes the initial president. Universities must be added manually by the president.
π Usage
For the President
Managing Universities
- Add University: Call
addUniversity(address, name)
when no election is active - Remove University: Call
removeUniversity(address)
when no election is active - View All Universities: Use
getAllUniversitiesWithNames()
to see registered universities
For Universities
Starting an Election
- Connect wallet using a registered university address
- Ensure election status is βNO_ELECTIONβ
- Call
startVotation()
function - Pay 100 wei election fee
- Election runs for 1000 blocks
Voting Process
- During election (IN_PROGRESS status)
- Enter vote data in JSON format:
{"candidate_name": vote_count}
- Example:
{"Alice": 50, "Bob": 30, "scheda bianca": 0}
- Call
vote(voteData)
function (one vote per university)
Professor Management
- Enrollment: Call
enrollProfessor(universityAddress)
and pay 10 wei - Capacity: Maximum 30 professors per university
- Unenrollment: Call
removeProfessor()
when no election is active
For Professors
Checking Status
- Use
getProfessorInfo(address)
to check enrollment status - Professors can only be enrolled in one university at a time
For Developers
Testing Contracts
yarn hardhat:test
Contract Debugging
- Navigate to
/debug
page - Interact with contract functions directly
- View contract state and events
- Test different scenarios
Linting & Type Checking
yarn hardhat:lint
yarn next:lint
yarn next:check-types
π§ Configuration
Network Configuration
Edit packages/hardhat/hardhat.config.ts
to modify network settings.
Frontend Configuration
Customize packages/nextjs/scaffold.config.ts
for:
- Target networks
- Polling intervals
- API keys
- Wallet configurations
Contract Parameters
These constants are defined in the contract:
CAP
: Maximum professors per university (30)ENROLLMENT_FEE
: Professor enrollment fee (10 wei)ELECTION_START_FEE
: Election start fee (100 wei)ELECTION_DURATION_BLOCKS
: Election duration (1000 blocks)QUORUM_PERCENTAGE
: Quorum requirement (50%)
π Security Features
Access Control
- President-Only Functions: Adding/removing universities, closing elections
- University Verification: Only registered universities can participate
- Election State Checks: Actions restricted based on election status
- Professor Association: Professors can only be enrolled in one university
Fee Management
- Automatic Transfers: Fees automatically sent to universities
- Fee Holding: Election fees held during voting process
- Refund Mechanism: Unused fees can be returned
- Value Validation: Minimum fee requirements enforced
Vote Integrity
- One Vote Per University: Universities cannot vote multiple times
- Vote Encryption: Vote data stored as encrypted JSON strings
- Immutable Records: Votes stored permanently on blockchain
- Election Lifecycle: Proper state transitions enforced
π οΈ Development
Project Structure
βββ packages/
β βββ hardhat/ # Smart contract development
β β βββ contracts/ # Solidity contracts
β β βββ deploy/ # Deployment scripts
β β βββ scripts/ # Utility scripts
β β βββ test/ # Contract tests
β βββ nextjs/ # Frontend application
β βββ app/ # Next.js app router
β βββ components/ # React components
β βββ hooks/ # Custom React hooks
β βββ contracts/ # Contract interfaces
β βββ utils/ # Utility functions
Smart Contract Events
The contract emits several events for frontend integration:
ElectionStarted
: When an election beginsElectionClosed
: When an election endsUniversityVoted
: When a university submits a voteUniversityAdded
: When a university is registeredUniversityRemoved
: When a university is removedProfessorEnrolled
: When a professor enrollsProfessorRemoved
: When a professor is removedPresidentChanged
: When presidency changesStatusChanged
: When election status changesFeeReceived
: When fees are paidFeeReturned
: When fees are refunded
Custom Hooks
useScaffoldReadContract
: Read contract stateuseScaffoldWriteContract
: Execute contract functionsuseScaffoldEventHistory
: Listen to contract eventsuseDeployedContractInfo
: Get contract deployment infouseTargetNetwork
: Manage network connections
Key Contract Functions
View Functions
getAllUniversities()
: Get all university addressesgetAllUniversitiesWithNames()
: Get universities with namesgetElectionInfo()
: Get current election status and infogetUniversityInfo(address)
: Get university detailsgetProfessorInfo(address)
: Check professor enrollmentisCurrentPresident(address)
: Check if address is presidentgetHeldFeeInfo()
: Get fee holding informationgetCurrentBlock()
: Get current block number
State-Changing Functions
addUniversity(address, name)
: Add new university (president only)removeUniversity(address)
: Remove university (president only)startVotation()
: Start new election (payable, 100 wei)vote(string)
: Submit vote during electionclose(string)
: Close election and set winner (president only)enrollProfessor(address)
: Enroll professor (payable, 10 wei)removeProfessor()
: Remove professor from universitycheckStatus()
: Update election status if time expired
π Election Workflow
graph TD
A[No Election] --> B[University Pays 100 wei]
B --> C[Election Started]
C --> D[Universities Vote]
D --> E{All Voted or Time Up?}
E -->|No| D
E -->|Yes| F[President Closes Election]
F --> G[New President Set]
G --> H[Fees Distributed/Refunded]
H --> A
π§ͺ Testing
The project includes comprehensive tests covering:
- University management
- Election lifecycle
- Professor enrollment
- Fee handling
- Access control
- Edge cases and error conditions
Run tests with:
yarn hardhat:test
π Deployment
Local Development
yarn chain # Start local blockchain
yarn deploy # Deploy contracts
yarn start # Start frontend
Live Networks
- Configure network in
hardhat.config.ts
- Set deployer private key in
.env
- Deploy:
yarn deploy --network <network_name>
- Verify contracts:
yarn verify --network <network_name>
Frontend Deployment
yarn build # Build for production
yarn vercel # Deploy to Vercel
# or
yarn ipfs # Deploy to IPFS
π€ Contributing
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests for new functionality
- Ensure all tests pass
- Submit a pull request
Please read CONTRIBUTING.md for detailed guidelines.
π License
This project is licensed under the MIT License.
β οΈ Important Notes
- Not Production Ready: This is a demo/educational project
- Fee Amounts: Using wei amounts for testing (very small values)
- Security: Implement additional security measures for production use
- Governance: The presidency transfer mechanism is simplified for demonstration
- Scalability: Consider gas costs and limits for large-scale deployments