A lightweight Node.js Express middleware for implementing prepaid credit monetization with BSV (Bitcoin SV) payments. Users deposit BSV once, receive credits, and pay per API callβno per-request payment friction.
β
ON/OFF Monetization Switch - Enable/disable monetization globally
β
Prepaid Credit System - Users deposit BSV, receive credits instantly
β
Automatic Credit Deduction - 1 API call = X credits (configurable)
β
Payment Verification - Validates BSV transactions on blockchain
β
Credit Management - Track balances, deposits, and consumption per user
β
Comprehensive Logging - Audit trail of all transactions
β
Admin Dashboard - View users, transactions, and logs
β
Docker Ready - Full Docker & Docker Compose support
β
Protected Endpoints - Enforce credit requirements per route
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β API Server (Express) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Free Endpoints: Protected Endpoints: β
β β’ GET /health β’ GET /paid (1 credit) β
β β’ GET /free β’ GET /premium (5 credits) β
β β’ GET /config β’ POST /api/data (1 credit) β
β β
β Payment Flow: Admin Endpoints: β
β β’ POST /deposit β’ GET /admin/users β
β β’ POST /verify-payment β’ GET /admin/transactions β
β β’ POST /simulate-payment β’ GET /admin/logs β
β β’ GET /balance β’ GET /admin/config β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Credit Manager (In-Memory) β
β β’ User balances β’ Transaction history β
β β’ Deposit tracking β’ Usage analytics β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Payment Verifier (BSV Blockchain) β
β β’ Transaction verification (simulated + real) β
β β’ Credit calculation (BSV β Credits) β
β β’ Double-spend prevention β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Install dependencies
npm install
# Start server
npm start
# In another terminal, run tests
npm testServer runs on: http://localhost:3000
# Build image
npm run docker:build
# Run with Docker Compose
npm run docker:runExposed on: http://localhost:3000
Edit config/monetization.json:
{
"monetization": "ON",
"price_per_call": 0.001,
"currency": "BSV",
"payout_address": "REPLACE_WITH_YOUR_BSV_ADDRESS",
"payment_mode": "prepaid",
"credits_per_call": 1
}Or use environment variables:
MONETIZATION=ON
PRICE_PER_CALL=0.001
CURRENCY=BSV
PAYOUT_ADDRESS=YOUR_BSV_WALLET
PAYMENT_MODE=prepaid
CREDITS_PER_CALL=1
ADMIN_TOKEN=admin_secretCheck server status
curl http://localhost:3000/healthFree endpoint example
curl http://localhost:3000/freeGet monetization configuration
curl http://localhost:3000/configRequest deposit instructions
curl -X POST http://localhost:3000/deposit \
-H "Content-Type: application/json" \
-H "x-api-key: your-api-key" \
-d '{"amount": 0.01}'Response:
{
"status": "DEPOSIT_INITIATED",
"depositInstructions": {
"payTo": "your_payout_address",
"amount": 0.01,
"currency": "BSV"
},
"estimatedCredits": 10,
"yourApiKey": "your-api-key"
}Verify payment and add credits
curl -X POST http://localhost:3000/verify-payment \
-H "Content-Type: application/json" \
-H "x-api-key: your-api-key" \
-d '{"txid": "abc123...", "amount": 0.01}'Simulate a payment in test mode
curl -X POST http://localhost:3000/simulate-payment \
-H "Content-Type: application/json" \
-H "x-api-key: test-user" \
-d '{"amount": 0.01}'Check credit balance
curl http://localhost:3000/balance \
-H "x-api-key: your-api-key"Response:
{
"apiKey": "your-api-key",
"credits": 42,
"transactions": [...]
}Get transaction history
curl http://localhost:3000/transactions \
-H "x-api-key: your-api-key"Protected endpoint (costs 1 credit)
curl http://localhost:3000/paid \
-H "x-api-key: your-api-key"Response headers:
X-Credits-Remaining: 41
X-Credits-Deducted: 1
Premium endpoint (costs 5 credits)
curl http://localhost:3000/premium \
-H "x-api-key: your-api-key"Data API endpoint (costs 1 credit)
curl -X POST http://localhost:3000/api/data \
-H "Content-Type: application/json" \
-H "x-api-key: your-api-key" \
-d '{"query": "data"}'View all users
curl "http://localhost:3000/admin/users?token=admin_secret"View all transactions
curl "http://localhost:3000/admin/transactions?token=admin_secret"View all logs
curl "http://localhost:3000/admin/logs?token=admin_secret"Get full configuration
curl "http://localhost:3000/admin/config?token=admin_secret"Run the test suite to verify everything works:
# Terminal 1: Start server
npm start
# Terminal 2: Run tests
npm testWhat the tests verify:
- β Server health check
- β Configuration loaded correctly
- β Protected endpoint rejects requests without credits
- β Payment simulation works
- β Credits are added correctly
- β Protected endpoint accepts requests with credits
- β Multiple requests consume credits correctly
- β Premium endpoint enforces 5-credit requirement
- β Admin endpoints work
- β Full audit trail is logged
Logs are stored in the logs/ directory:
- deposits.log - All deposit transactions
- credits.log - Credit additions and deductions
- payments.log - Payment verification events
- access-denied.log - Failed access attempts
- api-calls.log - All API requests
- errors.log - System errors
Example log entry:
[2026-04-22T10:30:45.123Z] CREDITS_DEDUCTED: apiKey=user123, credits=1, endpoint=/paid, balanceAfter=41
ββββββββββββββββββββββββββββββββββββ
β 1. User requests deposit β
β POST /deposit β
ββββββββββββββββ¬ββββββββββββββββββββ
β
ββββββββββββββββββββββββββββββββββββ
β 2. Server returns: β
β β’ Payout address β
β β’ Amount required β
β β’ Estimated credits β
β β’ API key (auto-generated) β
ββββββββββββββββ¬ββββββββββββββββββββ
β
ββββββββββββββββββββββββββββββββββββ
β 3. User sends BSV to payout_addr β
β (BSV blockchain) β
ββββββββββββββββ¬ββββββββββββββββββββ
β
ββββββββββββββββββββββββββββββββββββ
β 4. User verifies payment β
β POST /verify-payment β
β + txid + amount β
ββββββββββββββββ¬ββββββββββββββββββββ
β
ββββββββββββββββββββββββββββββββββββ
β 5. Server verifies on BSV β
β blockchain (or simulation) β
ββββββββββββββββ¬ββββββββββββββββββββ
β
ββββββββββββββββββββββββββββββββββββ
β 6. Credits added: β
β credits = amount / price β
β Example: 0.01 / 0.001 = 10 β
ββββββββββββββββ¬ββββββββββββββββββββ
β
ββββββββββββββββββββββββββββββββββββ
β 7. User can now call /paid β
β 1 credit deducted per call β
ββββββββββββββββββββββββββββββββββββ
# 1. Simulate a payment (get 10 credits for 0.01 BSV)
API_KEY=$(curl -s -X POST http://localhost:3000/simulate-payment \
-H "Content-Type: application/json" \
-H "x-api-key: new-user" \
-d '{"amount": 0.01}' | jq -r '.apiKey')
# 2. Check balance
curl http://localhost:3000/balance \
-H "x-api-key: $API_KEY" | jq '.credits'
# Output: 10
# 3. Call protected endpoint 3 times
for i in {1..3}; do
curl http://localhost:3000/paid \
-H "x-api-key: $API_KEY" | jq '.creditsRemaining'
done
# Outputs: 9, 8, 7
# 4. Check transaction history
curl http://localhost:3000/transactions \
-H "x-api-key: $API_KEY" | jq '.transactions'# Set monetization to OFF in config/monetization.json
{
"monetization": "OFF", # β Change this
...
}
# Now all protected endpoints work without credits
curl http://localhost:3000/paid
# Response: "Protected endpoint accessed successfully"{
"monetization": "ON",
"price_per_call": 0.002, # More expensive
"credits_per_call": 1,
...
}
// Now: 0.01 BSV = 5 credits (0.01 / 0.002 = 5)
// Instead of: 0.01 BSV = 10 credits- Change admin token: Set
ADMIN_TOKENto a strong random value - Use real BSV address: Replace
payout_addresswith your wallet - Enable HTTPS: Deploy behind nginx/apache with SSL
- Validate txid: Connect to real BSV blockchain API (not simulation)
- Use database: Replace in-memory storage with PostgreSQL/MongoDB
- Rate limiting: Add rate limiting middleware
- API key validation: Use JWT or similar for API key generation
βββ src/
β βββ index.js # Main Express app & endpoints
β βββ creditManager.js # Credit balance tracking
β βββ monetizationMiddleware.js # Credit enforcement middleware
β βββ paymentVerifier.js # Transaction verification
β βββ config.js # Configuration manager
β βββ logger.js # Event logging
βββ config/
β βββ monetization.json # Configuration file
βββ tests/
β βββ test-scenario.js # Complete test suite
βββ docker-compose.yml # Docker Compose setup
βββ Dockerfile # Docker image definition
βββ package.json # Dependencies
βββ README.md # This file
# Install dependencies
npm install
# Start server (development with nodemon)
npm run dev
# Start server (production)
npm start
# Run tests
npm test
# Build Docker image
npm run docker:build
# Run with Docker
npm run docker:run
# View logs (after running app)
tail -f logs/*.log| Variable | Default | Purpose |
|---|---|---|
PORT |
3000 | Server port |
NODE_ENV |
development | Environment mode |
MONETIZATION |
ON | Enable/disable monetization |
PRICE_PER_CALL |
0.001 | BSV per API call |
CURRENCY |
BSV | Payment currency |
PAYOUT_ADDRESS |
REPLACE_... | BSV wallet address |
PAYMENT_MODE |
prepaid | Payment model |
CREDITS_PER_CALL |
1 | Credits per endpoint call |
ADMIN_TOKEN |
admin_secret | Admin authentication |
# SSH into instance
ssh ec2-user@your-instance.compute.amazonaws.com
# Clone repo
git clone <repo> && cd monetization-switch
# Install Node.js
curl -fsSL https://rpm.nodesource.com/setup_18.x | sudo bash
sudo yum install -y nodejs
# Install dependencies & run with PM2
npm install
sudo npm install -g pm2
pm2 start npm --name "monetization" -- start
pm2 startup
pm2 save# Build and tag
docker build -t your-username/bsv-monetization:latest .
# Push to Docker Hub
docker push your-username/bsv-monetization:latest
# Pull and run anywhere
docker pull your-username/bsv-monetization
docker run -p 3000:3000 your-username/bsv-monetizationTo use real BSV payments instead of simulation:
- Configure BSV API endpoint in
paymentVerifier.js:
async verifyTransaction(txid, expectedAmount, payoutAddress) {
// Instead of simulation:
const response = await axios.get(
`https://api.whiteonion.io/v3/tx/${txid}`
);
// Parse and validate response
const tx = response.data;
const verified = tx.outputs.some(output =>
output.address === payoutAddress &&
output.amount === expectedAmount
);
return { verified, ...tx };
}- Test with testnet BSV first
- Switch to mainnet when ready
- π Documentation: See README.md
- π§ͺ Examples: Run
npm test - π Issues: Check logs in
logs/directory - π¬ Questions: Review comments in source code
MIT License - Free to use and modify
β
Complete Node.js Express server
β
Pre-built middleware for credit enforcement
β
In-memory credit manager (ready for database upgrade)
β
Payment verification layer (simulation + BSV ready)
β
Comprehensive logging system
β
Docker & Docker Compose setup
β
Full test suite
β
Admin dashboard endpoints
β
Configuration management
β
Error handling & validation
Ready to monetize? Deploy with npm run docker:run π