A production-ready Cloudflare Worker API that generates cryptographically secure, verifiable random numbers using Harmony ONE blockchain's native VRF (Verifiable Random Function). This project provides a simple REST API for generating random numbers with blockchain-backed proof of randomness.
Created by EasyNodePro - Making blockchain infrastructure accessible.
- 🎲 Cryptographically Secure Randomness - Uses Harmony ONE's native VRF precompiled contract
- ✅ Verifiable Proofs - Each random number includes blockchain proof for verification
- 🚀 Fast & Scalable - Runs on Cloudflare's global edge network
- 🔒 Built-in Rate Limiting - Configurable per-IP rate limits
- 🌐 CORS Enabled - Ready for cross-origin requests
- 💰 Cost Effective - Leverages Harmony's free native VRF (no gas fees for VRF calls)
- 📝 Full TypeScript - Type-safe codebase with comprehensive validation
This API leverages Harmony ONE's unique native VRF feature, which is built into every block via a precompiled contract at address 0xff. Unlike traditional VRF solutions that require paying gas fees and waiting for multiple transactions, Harmony's native VRF:
- Provides instant randomness from the current block
- Requires no transaction fees
- Is cryptographically secure and verifiable on-chain
- Mixes block VRF with timestamps for uniqueness per request
- Node.js (v18 or higher)
- A Cloudflare account (free tier works)
- Wrangler CLI (installed via npm)
- Clone or download this repository:
git clone https://github.com/patrickmogul/harmony-vrf-site.git
cd harmony-vrf-site- Install dependencies:
npm install- Test locally:
npm run devThe API will be available at http://localhost:8787
- Test the endpoint:
curl -X POST http://localhost:8787 \
-H "Content-Type: application/json" \
-d '{"min": 1, "max": 100}'To customize this API for your own domain, you'll need to update a few configuration files:
Replace yourdomain.com with your actual domain:
name = "harmony-vrf-worker"
main = "src/index.ts"
compatibility_date = "2023-12-01"
[vars]
RATE_LIMIT_PER_MINUTE = "60"
# Replace yourdomain.com with your actual domain
routes = [
{ pattern = "yourdomain.com", custom_domain = true }
]
[env.production]
name = "harmony-vrf-api"
routes = [
{ pattern = "yourdomain.com", custom_domain = true }
]
[env.production.vars]
RATE_LIMIT_PER_MINUTE = "100"Example: If your domain is api.example.com, change both route patterns to "api.example.com".
Edit src/index.ts around line 99-107 to customize the HTML landing page that appears when someone visits your API root URL in a browser:
<h1>🎲 Your Custom Title</h1>
<p>Your custom description</p>
<a href="https://yourdomain.com">Your Link</a>If you want to use a custom Harmony RPC endpoint:
# Copy the example file
cp .dev.vars.example .dev.vars
# Edit .dev.vars and uncomment/set:
HARMONY_RPC=https://api.harmony.one
RATE_LIMIT_PER_MINUTE=60Note: The .dev.vars file is gitignored and only used for local development.
Edit package.json to reflect your project details:
{
"name": "your-project-name",
"description": "Your description",
"author": "Your Name"
}npx wrangler loginThis opens a browser window to authorize Wrangler with your Cloudflare account.
Important: Before deploying, ensure your domain is added to Cloudflare:
- Go to your Cloudflare Dashboard
- Add your domain to Cloudflare (if not already added)
- Update your domain's nameservers to point to Cloudflare
- Wait for DNS propagation (usually a few minutes)
npm run deployCloudflare will automatically:
- Build and upload your Worker
- Provision an SSL certificate for your domain
- Configure DNS records
- Deploy to Cloudflare's global edge network
Test your deployed API:
curl -X POST https://yourdomain.com \
-H "Content-Type: application/json" \
-d '{"min": 1, "max": 100}'Expected response:
{
"randomNumber": 42,
"proof": "{\"method\":\"harmony-native-vrf\",\"blockNumber\":12345,...}",
"requestId": "0x...",
"min": 1,
"max": 100,
"timestamp": 1234567890
}POST / - Generate a verifiable random number
{
"min": 1,
"max": 100
}Parameters:
min(number, required): Minimum value (inclusive, must be a positive integer)max(number, required): Maximum value (inclusive, must be a positive integer greater than min)
{
"randomNumber": 42,
"proof": "{...}",
"requestId": "0x...",
"min": 1,
"max": 100,
"timestamp": 1234567890
}Fields:
randomNumber: The generated random number within your specified rangeproof: JSON string containing cryptographic proof and verification detailsrequestId: Unique identifier for this requestmin: Echo of the minimum value requestedmax: Echo of the maximum value requestedtimestamp: Unix timestamp when the number was generated
The proof field contains a JSON string with verification details:
{
"method": "harmony-native-vrf",
"blockNumber": 12345,
"vrfData": "0x...",
"vrfRandomness": "123456789...",
"uniqueSeed": "0x...",
"timestamp": 1234567890,
"chain": "harmony-one",
"verifiable": true,
"verifyUrl": "https://explorer.harmony.one/block/12345",
"description": "Uses Harmony's native VRF..."
}You can verify the randomness by checking the block on Harmony Explorer.
{
"error": "Error message description"
}Common Errors:
400- Validation errors (invalid min/max values)405- Method not allowed (only POST is accepted)429- Rate limit exceeded500- Internal server error
See EXAMPLES.md for code examples in multiple languages.
Configure rate limits in wrangler.toml:
[vars]
RATE_LIMIT_PER_MINUTE = "60" # Development: 60 requests/minute
[env.production.vars]
RATE_LIMIT_PER_MINUTE = "100" # Production: 100 requests/minuteRate limits are per-IP address and reset every minute.
To use a custom Harmony RPC endpoint:
For local development:
echo 'HARMONY_RPC=https://your-custom-rpc.com' > .dev.varsFor production (via Cloudflare dashboard):
- Go to Workers & Pages → Your Worker → Settings → Variables
- Add environment variable:
HARMONY_RPC=https://your-custom-rpc.com - Or use Wrangler:
npx wrangler secret put HARMONY_RPC
# Enter your RPC URL when promptednpm run devStarts local development server at http://localhost:8787
npm run buildCompiles TypeScript to check for errors.
npm testRuns the validation test suite with Vitest.
harmony-vrf-site/
├── src/
│ └── index.ts # Main Worker code
├── test/
│ └── api.test.ts # Validation tests
├── wrangler.toml # Cloudflare Worker configuration
├── package.json # Dependencies and scripts
├── tsconfig.json # TypeScript configuration
├── vitest.config.ts # Test configuration
├── EXAMPLES.md # Code examples in multiple languages
├── .env.example # Example environment variables
├── .dev.vars.example # Example local dev variables
└── README.md # This file
npx wrangler tailShows real-time logs from your deployed Worker.
View usage analytics in your Cloudflare Dashboard:
- Go to Workers & Pages
- Select your Worker
- View the Analytics tab for:
- Request counts
- Error rates
- CPU usage
- Response times
After making changes to your code:
npm run deployChanges are deployed instantly to all edge locations.
Free Tier:
- 100,000 requests per day
- 10ms CPU time per request
- Unlimited bandwidth
Paid Tier ($5/month):
- 10 million requests per month (additional requests $0.50/million)
- 50ms CPU time per request
- No daily limits
For most use cases, the free tier is sufficient. Learn more about pricing.
Ensure your domain is added to Cloudflare and DNS is active:
- Check your Cloudflare dashboard
- Verify nameservers are pointed to Cloudflare
- Wait a few minutes for DNS propagation
Edit .dev.vars to increase the development rate limit:
RATE_LIMIT_PER_MINUTE=1000
Check your Harmony RPC endpoint:
- Default:
https://api.harmony.one - Try an alternative RPC if needed
- Verify network connectivity
npm install
npm run buildEdit src/index.ts function handleCORS() to restrict origins:
function handleCORS(): Response {
return new Response(null, {
headers: {
'Access-Control-Allow-Origin': 'https://yourdomain.com', // Restrict to your domain
'Access-Control-Allow-Methods': 'POST, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type',
},
});
}Add authentication by checking for an API key header:
const apiKey = request.headers.get('X-API-Key');
if (apiKey !== env.API_KEY) {
return jsonResponse({ error: 'Unauthorized' }, 401);
}Then set API_KEY as a secret:
npx wrangler secret put API_KEYCloudflare Workers can integrate with:
- Cloudflare D1 (SQLite)
- Cloudflare KV (Key-Value store)
- Cloudflare Durable Objects
- External databases via HTTP APIs
- Harmony ONE Documentation
- Harmony VRF Specification
- Cloudflare Workers Documentation
- Wrangler CLI Documentation
- Code Examples - Multi-language integration examples
Contributions are welcome! Feel free to:
- Open issues for bugs or feature requests
- Submit pull requests with improvements
- Share your use cases and feedback
MIT License - see LICENSE file for details.
Created and maintained by EasyNodePro - Your trusted partner for blockchain infrastructure.
Built with ❤️ using Harmony ONE blockchain and Cloudflare Workers.
Need help? Open an issue on GitHub or visit easynodepro.com for professional blockchain infrastructure support.