A comprehensive educational project demonstrating how to build a complete decentralized application (dApp) on the Hedera blockchain. This project includes a smart contract, modern web frontend, and extensive documentation for blockchain beginners.
This project demonstrates:
- Smart Contract Development: A feature-rich counter contract written in Solidity
- Frontend Integration: Modern React/Next.js application with TypeScript
- Wallet Integration: HashPack wallet connection and transaction signing
- Real-time Updates: Live contract state monitoring and transaction tracking
- Educational Content: Comprehensive tutorials and explanations
The Hedera Counter DApp interface showing the counter value, transaction controls, contract verification links, and real-time transaction history.
- β Increment/Decrement counter by 1 or custom amounts
- β Owner-only reset functionality
- β Pause/unpause contract operations
- β Comprehensive error handling and validation
- β Event emission for all operations
- β Gas-optimized design
- β Modern, responsive UI with Tailwind CSS
- β Real-time counter value display with progress visualization
- β Multi-wallet support via Hedera WalletConnect (HashPack, Blade, Kabila, etc.)
- β Transaction history and status tracking
- β Error handling and user feedback
- β Mobile-friendly design
-
Visit the Official MetaMask Website
- Go to https://metamask.io/
- Click "Download" button
-
Install Browser Extension
- Choose your browser (Chrome, Firefox, Edge, or Brave)
- Click "Install MetaMask for [Your Browser]"
- Add the extension to your browser
- Pin the MetaMask extension to your browser toolbar for easy access
-
Initial Setup
- Click the MetaMask fox icon in your browser
- Choose "Create a new wallet" (for new users) or "Import an existing wallet"
- Create a strong password (at least 8 characters)
β οΈ IMPORTANT: Write down your Secret Recovery Phrase and store it safely!
MetaMask doesn't include Hedera networks by default, so we need to add them manually:
-
Open MetaMask Settings
- Click the MetaMask icon
- Click your account avatar (top right)
- Select "Settings" β "Networks" β "Add Network"
-
Add Hedera Testnet Network
Network Name: Hedera Testnet New RPC URL: https://testnet.hashio.io/api Chain ID: 296 Currency Symbol: HBAR Block Explorer URL: https://hashscan.io/testnet -
Add Hedera Mainnet Network (Optional - for production use)
Network Name: Hedera Mainnet New RPC URL: https://mainnet.hashio.io/api Chain ID: 295 Currency Symbol: HBAR Block Explorer URL: https://hashscan.io/mainnet -
Save and Switch Networks
- Click "Save" to add the network
- Switch to "Hedera Testnet" from the network dropdown
If you already have a Hedera account, you can import it into MetaMask:
-
Get Your Private Key
- From Hedera Portal or your existing wallet
β οΈ WARNING: Never share your private key with anyone!
-
Import Account in MetaMask
- Click your account avatar β "Import Account"
- Select "Private Key" as import type
- Paste your Hedera private key (with or without 0x prefix)
- Click "Import"
-
Verify Import
- Your account should appear with your HBAR balance
- Account ID format: 0.0.xxxxxx
-
Visit Hedera Portal
- Go to https://portal.hedera.com/
- Click "Create Account" or "Get Started"
-
Choose Account Type
- Select "Testnet" for development and testing
- Click "Create Testnet Account"
-
Account Creation
- The portal will generate a new account automatically
- You'll receive:
- Account ID (format: 0.0.xxxxxx)
- Public Key (starts with 302a300506...)
- Private Key (starts with 302e020100... or hex format)
-
Save Your Credentials
Account ID: 0.0.1234567 Private Key: 302e020100300506032b657004220420... Public Key: 302a300506032b6570032100...β οΈ CRITICAL: Save these credentials securely!- Store them in a password manager or secure note-taking app
-
Automatic Funding
- New testnet accounts usually receive 1000 HBAR automatically
- Wait 1-2 minutes for the funding to appear
-
Manual Faucet (if needed)
- Visit https://portal.hedera.com/
- Log in with your account credentials
- Look for "Testnet Faucet" or "Get HBAR" button
- Request additional HBAR (usually 1000 HBAR per request)
-
Alternative Faucet Sources
- Hedera Faucet (Official)
- Community faucets (check Hedera Discord for links)
-
Check Balance on HashScan
- Visit https://hashscan.io/testnet
- Search for your Account ID (0.0.xxxxxx)
- Verify your HBAR balance appears
-
Import to MetaMask
- Follow the MetaMask setup guide above
- Import your account using the private key
- Verify the balance shows in MetaMask
Before starting, ensure you have these installed:
- β Node.js (v18.0.0 or higher) - Download here
- β npm (comes with Node.js) or yarn
- β Git - Download here
- β MetaMask Browser Extension (see guide above)
- β Hedera Testnet Account with HBAR (see guide above)
- β Code Editor (VS Code recommended)
Check Your Versions:
node --version # Should be v18.0.0 or higher
npm --version # Should be 8.0.0 or higher
git --version # Any recent version-
Open Terminal/Command Prompt
- Windows: Press
Win + R, typecmd, press Enter - Mac: Press
Cmd + Space, type "Terminal", press Enter - Linux: Press
Ctrl + Alt + T
- Windows: Press
-
Navigate to Your Desired Directory
# Example: Navigate to Desktop cd Desktop # Or create a new projects folder mkdir blockchain-projects cd blockchain-projects
-
Clone the Repository
git clone https://github.com/walterthesmart/Hedera-Counter-Dapp.git cd Hedera-Counter-Dapp
-
Install Root Dependencies
npm install
Expected Output:
added 245 packages, and audited 246 packages in 15s -
Install Smart Contract Dependencies
cd smart-contract npm install cd ..
-
Install Frontend Dependencies
cd frontend npm install cd ..
- If you get permission errors, try:
npm install --no-optional - For Windows users with Python errors:
npm install --ignore-scripts - If installation fails, delete
node_modulesand try again
-
Create Environment Files
# Copy the example environment file cp .env.example .env # For Windows users: copy .env.example .env
-
Configure Main Environment File (.env)
Open
.envin your code editor and update with your Hedera account details:# Hedera Network Configuration HEDERA_NETWORK=testnet # Your Hedera Account Details (from portal.hedera.com) HEDERA_ACCOUNT_ID=0.0.1234567 HEDERA_PRIVATE_KEY=302e020100300506032b657004220420abcd1234... # These will be auto-populated after contract deployment CONTRACT_ID= CONTRACT_ADDRESS= NEXT_PUBLIC_CONTRACT_ID=
-
Configure Frontend Environment
cd frontend cp .env.local.example .env.localEdit
frontend/.env.local:# Hedera Network NEXT_PUBLIC_HEDERA_NETWORK=testnet # App Configuration NEXT_PUBLIC_APP_NAME=Hedera Counter DApp NEXT_PUBLIC_APP_DESCRIPTION=A simple counter DApp on Hedera # Contract ID (will be populated after deployment) NEXT_PUBLIC_CONTRACT_ID=
-
Compile the Smart Contract
cd smart-contract npm run compileExpected Output:
Compiled 1 Solidity file successfully -
Deploy to Hedera Testnet
npm run deploy
Expected Output:
π Starting Hedera Counter Contract Deployment... π Connected to Hedera Testnet π Contract bytecode loaded successfully β³ Deploying Counter contract... β Contract deployed successfully! π Contract ID: 0.0.6285476 π Contract Address: 0x00000000000000000000000000000000005fd844 -
Verify Deployment
- The script automatically updates your
.envfiles - Check that
CONTRACT_IDandNEXT_PUBLIC_CONTRACT_IDare now populated - Visit the HashScan link provided to see your contract
- The script automatically updates your
-
Navigate to Frontend Directory
cd ../frontend -
Start Development Server
npm run dev
Expected Output:
ready - started server on 0.0.0.0:3000, url: http://localhost:3000 -
Open Your DApp
- Visit
http://localhost:3000in your browser - You should see the Hedera Counter DApp interface
- Visit
-
Connect MetaMask
- Click "Connect MetaMask" button in the top-right
- Approve the connection in MetaMask
- Ensure you're on Hedera Testnet network
-
Test Contract Functions
- Try incrementing the counter
- Try decrementing the counter
- Check transaction history
- Verify transactions on HashScan
β Installation Complete When:
- All dependencies installed without errors
- Environment files configured with your account details
- Smart contract compiled successfully
- Contract deployed to Hedera testnet
- Frontend starts on
http://localhost:3000 - MetaMask connects successfully
- Counter increment/decrement works
- Transactions appear in history
Solution:
# Update Node.js to latest LTS version
# Visit https://nodejs.org/ and download latest versionSolution:
- Double-check your
.envfile has the correct private key - Ensure no extra spaces or quotes around the key
- Verify the key starts with
302e020100...or is in hex format
Solution:
- Get more testnet HBAR from portal.hedera.com
- Wait a few minutes for funding to appear
- Check your balance on hashscan.io/testnet
Solution:
- Ensure MetaMask is installed and unlocked
- Verify Hedera Testnet network is added to MetaMask
- Check that you're on the correct network (Chain ID: 296)
Solution:
- Verify your account has sufficient HBAR (need ~5 HBAR for deployment)
- Check your private key is correct in
.env - Ensure you're connected to testnet, not mainnet
Hedera is a public distributed ledger that offers:
- High Performance: 10,000+ transactions per second
- Low Fees: Predictable, low-cost transactions
- Energy Efficient: Proof-of-Stake consensus
- Enterprise Grade: Built for real-world applications
- Every user has a unique Account ID (format:
0.0.xxxxx) - Accounts hold HBAR (Hedera's native cryptocurrency)
- Required for all blockchain interactions
- Self-executing contracts with terms directly written into code
- Deployed to the blockchain with a unique Contract ID
- Can hold and transfer HBAR, store data, and execute logic
- All blockchain interactions are transactions
- Require HBAR to pay for network fees
- Provide cryptographic proof of execution
- Hedera uses Hashgraph consensus algorithm
- Provides fast finality and high throughput
- More energy-efficient than traditional blockchains
hedera-counter-dapp/
βββ smart-contract/ # Smart contract code
β βββ contracts/ # Solidity contracts
β βββ scripts/ # Deployment scripts
β βββ test/ # Contract tests
β βββ config/ # Configuration files
βββ frontend/ # Next.js frontend application
β βββ src/
β β βββ components/ # React components
β β βββ hooks/ # Custom React hooks
β β βββ pages/ # Next.js pages
β β βββ styles/ # CSS styles
β β βββ types/ # TypeScript types
β β βββ utils/ # Utility functions
β βββ public/ # Static assets
βββ docs/ # Additional documentation
βββ .env.example # Environment variables template
βββ README.md # This file
Our smart contract includes several key components:
uint256 private _count; // Current counter value
address private _owner; // Contract owner
bool private _paused; // Pause state- increment() - Increases counter by 1
- decrement() - Decreases counter by 1
- incrementBy(uint256) - Increases by custom amount
- decrementBy(uint256) - Decreases by custom amount
- getCount() - Returns current value (view function)
- reset() - Resets to 0 (owner only)
- Access Control: Owner-only functions
- Pause Mechanism: Emergency stop functionality
- Input Validation: Boundary checks and error handling
- Event Logging: All operations emit events
The contract is optimized for gas efficiency:
- Uses
privatevariables with public getters - Efficient storage layout
- Minimal external calls
- Batch operations support
- Next.js 14: React framework with SSR/SSG
- TypeScript: Type-safe JavaScript
- Tailwind CSS: Utility-first CSS framework
- Hedera SDK: Official Hedera JavaScript SDK
- React Hooks: State management and side effects
Handles wallet connection and displays connection status.
Shows current counter value with visual progress indicators.
Provides buttons for all contract interactions.
Displays recent transactions with status tracking.
Manages wallet connection state and operations.
Handles all smart contract interactions.
Tracks transaction history and status.
- Reentrancy Protection: Functions use proper state updates
- Access Control: Owner-only functions properly protected
- Input Validation: All inputs validated before processing
- Pause Mechanism: Emergency stop functionality
- Environment Variables: Sensitive data properly managed
- Input Sanitization: User inputs validated and sanitized
- Error Handling: Graceful error handling and user feedback
- HTTPS Only: Production deployment uses HTTPS
Run the comprehensive test suite:
npm run test-contractTests cover:
- Basic functionality (increment/decrement)
- Access control (owner-only functions)
- Boundary conditions (min/max values)
- Error conditions (paused state, invalid inputs)
- Event emission verification
After deployment, verify your contract works:
cd smart-contract
npm run verify-
Prepare Environment
# Ensure you have testnet HBAR # Update .env with your credentials
-
Compile Contract
npm run compile-contract
-
Deploy to Testnet
npm run deploy-contract
-
Verify Deployment
cd smart-contract node scripts/verify.js
-
Connect Repository
- Import your GitHub repository to Vercel
- Configure build settings
-
Environment Variables
NEXT_PUBLIC_HEDERA_NETWORK=testnet NEXT_PUBLIC_CONTRACT_ID=0.0.YOUR_CONTRACT_ID NEXT_PUBLIC_APP_NAME=Hedera Counter DApp -
Deploy
- Vercel will automatically deploy on push to main branch
cd frontend
npm run build
npm run startThe project supports multiple Hedera networks:
- Testnet: For development and testing
- Mainnet: For production deployment
- Previewnet: For preview features
Configure in .env:
HEDERA_NETWORK=testnet # or mainnet, previewnetCustomize contract behavior in smart-contract/contracts/Counter.sol:
uint256 public constant MAX_COUNT = 1000000; // Maximum counter value
uint256 public constant MIN_COUNT = 0; // Minimum counter value- Cause: Not enough HBAR for transaction fees
- Solution: Get testnet HBAR from Hedera Portal
- Cause: Contract not deployed or wrong Contract ID
- Solution: Redeploy contract and update environment variables
- Cause: HashPack not installed or network mismatch
- Solution: Install HashPack and ensure correct network
- Cause: Network congestion or insufficient gas
- Solution: Retry transaction or increase gas limit
Enable debug logging:
NODE_ENV=development
DEBUG=trueWe welcome contributions! Please see our Contributing Guide for details.
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests if applicable
- Submit a pull request
This project is licensed under the MIT License - see the LICENSE file for details.
- Hedera Team for the excellent blockchain platform
- HashPack Team for the wallet integration
- OpenZeppelin for smart contract security patterns
- Next.js Team for the amazing React framework
- GitHub Issues: Report bugs or request features
- Discord: Join the Hedera Discord
- Documentation: Check our detailed docs
Happy Building! π
This project is for educational purposes and demonstrates best practices for Hedera dApp development.
