// ============================================================================ // LOCAL DEVELOPMENT ENVIRONMENT SETUP GUIDE // For Crypto Asset Management System // ============================================================================
Before starting, ensure you have installed:
- Node.js (v16 or higher) - https://nodejs.org/
- Git - https://git-scm.com/
- MySQL/PostgreSQL - https://www.mysql.com/ or https://www.postgresql.org/
- Hardhat - For Solidity smart contract development
- MetaMask - Browser extension for Ethereum interaction
# Navigate to your projects folder
cd ~/projects
# Clone your contracts repository
git clone https://github.com/HBReality/contracts.git
cd contracts
# Verify directory structure
ls -la# Initialize npm
npm init -y
# Install core dependencies
npm install express web3 ethers axios mysql2 dotenv jsonwebtoken cors nodemon
# Install development dependencies
npm install --save-dev hardhat @nomiclabs/hardhat-ethers ethers @openzeppelin/hardhat-upgrades
# Verify installations
npm list# Create necessary directories
mkdir -p backend/config
mkdir -p backend/models
mkdir -p backend/routes
mkdir -p backend/services
mkdir -p backend/middleware
mkdir -p backend/jobs
mkdir -p contracts/scripts
mkdir -p database
mkdir -p tests
# Create main backend file
touch backend/index.js
touch backend/config/database.js
touch backend/middleware/auth.js
touch backend/services/blockchainService.js
touch backend/models/wallet.js
touch backend/routes/wallets.js
touch backend/jobs/syncWallets.js
# Create environment file
touch .env
touch .env.exampleOn macOS (using Homebrew):
brew install mysql
brew services start mysqlOn Windows:
- Download from https://dev.mysql.com/downloads/mysql/
- Follow installation wizard
- Run MySQL as service
On Linux (Ubuntu/Debian):
sudo apt-get install mysql-server
sudo service mysql start# Connect to MySQL
mysql -u root -p
# In MySQL CLI, create database
CREATE DATABASE crypto_portfolio;
USE crypto_portfolio;
# Exit MySQL
EXIT;
# Import schema from file
mysql -u root -p crypto_portfolio < database/schema.sql
# Verify tables were created
mysql -u root -p crypto_portfolio -e "SHOW TABLES;"Create backend/config/database.js:
const mysql = require('mysql2/promise');
require('dotenv').config();
const pool = mysql.createPool({
host: process.env.DB_HOST || 'localhost',
user: process.env.DB_USER || 'root',
password: process.env.DB_PASSWORD || '',
database: process.env.DB_NAME || 'crypto_portfolio',
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0
});
module.exports = pool;Create .env file in project root:
# Database Configuration
DB_HOST=localhost
DB_USER=root
DB_PASSWORD=
DB_NAME=crypto_portfolio
# API Configuration
PORT=3000
NODE_ENV=development
# JWT Configuration
JWT_SECRET=your_super_secret_jwt_key_change_this_in_production
JWT_EXPIRE=24h
# Blockchain RPC URLs
ETHEREUM_RPC=https://eth-mainnet.g.alchemy.com/v2/YOUR_ALCHEMY_KEY
POLYGON_RPC=https://polygon-mainnet.g.alchemy.com/v2/YOUR_ALCHEMY_KEY
BSC_RPC=https://bsc-dataseed1.binance.org:8545
# External APIs
ETHERSCAN_API_KEY=YOUR_ETHERSCAN_API_KEY
ALCHEMY_KEY=YOUR_ALCHEMY_API_KEY
COINGECKO_API_KEY=optional_coingecko_key
# Smart Contract Deployment
PRIVATE_KEY=your_wallet_private_key_for_testnet_only
SEPOLIA_RPC=https://sepolia.infura.io/v3/YOUR_INFURA_KEY
# Sync Job Interval (in minutes)
SYNC_INTERVAL=5cp .env .env.example# Create/update .gitignore
echo ".env" >> .gitignore
echo ".env.local" >> .gitignore
echo "node_modules/" >> .gitignore
echo "dist/" >> .gitignore
echo ".DS_Store" >> .gitignore- Go to https://etherscan.io/apis
- Sign up / Login
- Create new API key
- Copy key to
.envasETHERSCAN_API_KEY
- Go to https://www.alchemy.com/
- Sign up / Login
- Create new app (select Ethereum Mainnet)
- Copy API key to
.envasALCHEMY_KEY
- Go to https://infura.io/
- Sign up / Login
- Create new project
- Copy Project ID to
.envasINFURA_KEY
- Go to https://www.coingecko.com/en/api
- Free API available, no key needed (optional)
Create backend/index.js:
const express = require('express');
const cors = require('cors');
require('dotenv').config();
const app = express();
// Middleware
app.use(cors());
app.use(express.json());
// Health check
app.get('/health', (req, res) => {
res.json({ status: 'Backend is running ✅' });
});
// Routes
app.use('/api/wallets', require('./routes/wallets'));
// Error handling
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).json({
success: false,
error: err.message
});
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`✅ Backend server running on http://localhost:${PORT}`);
});Create backend/middleware/auth.js:
const jwt = require('jsonwebtoken');
function authenticateUser(req, res, next) {
const token = req.headers.authorization?.split(' ')[1];
if (!token) {
return res.status(401).json({
success: false,
error: 'No token provided'
});
}
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET);
req.user = decoded;
next();
} catch (error) {
res.status(401).json({
success: false,
error: 'Invalid token'
});
}
}
module.exports = { authenticateUser };Create backend/routes/wallets.js:
const express = require('express');
const router = express.Router();
const { authenticateUser } = require('../middleware/auth');
// Test endpoint
router.get('/test', (req, res) => {
res.json({
success: true,
message: 'Wallets API is working ✅'
});
});
// Get all user wallets (requires auth)
router.get('/user/wallets', authenticateUser, (req, res) => {
res.json({
success: true,
message: 'User wallets endpoint',
user_id: req.user.id
});
});
module.exports = router;Update package.json:
{
"scripts": {
"start": "node backend/index.js",
"dev": "nodemon backend/index.js",
"test": "echo \"Error: no test specified\" && exit 1",
"hardhat:compile": "hardhat compile",
"hardhat:deploy": "hardhat run scripts/deploy.js --network sepolia"
},
"engines": {
"node": ">=16.0.0"
}
}# In project root
npx hardhat
# Select: Create a JavaScript project
# Choose defaults for other promptsCreate hardhat.config.js:
require("@nomicfoundation/hardhat-toolbox");
require("@nomiclabs/hardhat-ethers");
require('dotenv').config();
module.exports = {
solidity: {
version: "0.8.19",
settings: {
optimizer: {
enabled: true,
runs: 200
}
}
},
networks: {
hardhat: {},
sepolia: {
url: process.env.SEPOLIA_RPC || "",
accounts: process.env.PRIVATE_KEY ? [process.env.PRIVATE_KEY] : []
},
localhost: {
url: "http://127.0.0.1:8545"
}
},
etherscan: {
apiKey: process.env.ETHERSCAN_API_KEY || ""
}
};# Copy the contracts from INTEGRATION_GUIDE.md to:
# contracts/PortfolioManager.sol# Compile contracts
npx hardhat compile
# Expected output:
# Compiled 1 Solidity file successfullyCreate test-db.js:
require('dotenv').config();
const mysql = require('mysql2/promise');
async function testConnection() {
try {
const connection = await mysql.createConnection({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME
});
console.log('✅ Database connection successful!');
const [rows] = await connection.execute('SHOW TABLES');
console.log('📊 Tables in database:', rows.length);
rows.forEach(row => {
console.log(' -', Object.values(row)[0]);
});
await connection.end();
} catch (error) {
console.error('❌ Database connection failed:', error.message);
}
}
testConnection();Run test:
node test-db.js# Start backend in one terminal
npm run dev
# In another terminal, test the API
curl http://localhost:3000/health
# Expected response:
# {"status":"Backend is running ✅"}# First, generate a test JWT token
# Use an online JWT tool: https://jwt.io/
# Payload: { "id": 1, "email": "test@example.com" }
# Secret: your JWT_SECRET from .env
# Then test protected endpoint
curl -H "Authorization: Bearer YOUR_TEST_TOKEN" \
http://localhost:3000/api/wallets/user/walletsRun through this checklist to verify everything:
# 1. Check Node.js version
node --version
# Should be v16 or higher
# 2. Check npm version
npm --version
# 3. Verify MySQL is running
mysql -u root -p -e "SELECT 1"
# 4. Verify database exists
mysql -u root -p -e "USE crypto_portfolio; SHOW TABLES;"
# 5. Install all npm dependencies
npm install
# 6. Check .env file exists
cat .env | head -10
# 7. Compile smart contracts
npx hardhat compile
# 8. Test database connection
node test-db.js
# 9. Start backend
npm run dev
# 10. Test health endpoint (in another terminal)
curl http://localhost:3000/health# Start backend in development mode (with auto-reload)
npm run dev
# Compile Solidity contracts
npx hardhat compile
# Deploy to Sepolia testnet
npx hardhat run scripts/deploy.js --network sepolia
# Test Ethereum connection
npx hardhat run scripts/test-connection.js
# Start local Ethereum node (for testing)
npx hardhat node
# Create database backup
mysqldump -u root -p crypto_portfolio > backup.sql
# Restore database from backup
mysql -u root -p crypto_portfolio < backup.sql
# View real-time logs
tail -f logs/backend.logSolution:
npm install
npm install expressSolution: MySQL is not running
# macOS
brew services start mysql
# Linux
sudo service mysql start
# Windows: Start MySQL from ServicesSolution: Wrong MySQL password
# Update .env with correct password
# Or reset MySQL password
mysql -u root -p
# Then change password in .envSolution:
# Kill process on port 3000
lsof -i :3000
kill -9 <PID>
# Or use different port
PORT=3001 npm run devSolution:
# Create .env from .env.example
cp .env.example .env
# Edit with your values
nano .envAfter completing setup:
- ✅ Test all endpoints - Make sure API responds correctly
- ✅ Deploy contracts to Sepolia - Test on testnet first
- ✅ Add test data - Populate database with test wallets
- ✅ Connect MetaMask - Link to your local/testnet setup
- ✅ Build Frontend - Create React/Vue UI connected to API
# 1. Clone repo
git clone https://github.com/HBReality/contracts.git
cd contracts
# 2. Install dependencies
npm install
# 3. Setup database
mysql -u root -p crypto_portfolio < database/schema.sql
# 4. Create .env
cp .env.example .env
# Edit .env with your API keys
# 5. Start backend
npm run dev
# 6. In another terminal, test
curl http://localhost:3000/healthStatus: ✅ Ready to Start Development Created: July 13, 2026