Full documentation on the OutLayer dashboard.
A complete example demonstrating how to use NEAR OutLayer for CAPTCHA verification in token sales, preventing bot purchases while maintaining decentralized execution.
Token sales on blockchain face a major challenge: bots can instantly buy all tokens, leaving real users empty-handed. Traditional CAPTCHA solutions require centralized servers and break the decentralized model.
OutLayer + CAPTCHA provides the best of both worlds:
- β User solves CAPTCHA in their browser (familiar UX)
- β Verification happens off-chain (fast, no gas costs)
- β Final settlement on NEAR Layer 1 (secure, immutable)
- β Worker validates via launchpad API (no centralized trust)
User Browser β Token Sale Contract β OutLayer β CAPTCHA Worker
β β
βββββββββ Launchpad API (WebSocket) βββββββββ
- User visits launchpad website, gets
session_id - User calls
buy_tokens(session_id)on smart contract with NEAR - Contract calls OutLayer with session_id
- OutLayer Worker (captcha-example):
- Makes HTTP POST to launchpad
/api/captcha/challenge - Launchpad sends CAPTCHA to user's browser via WebSocket
- Worker polls
/api/captcha/verify/{id}every 500ms
- Makes HTTP POST to launchpad
- User sees modal with CAPTCHA, solves it
- Launchpad receives solution, validates, marks challenge as "solved"
- Worker gets verification result, returns to contract
- Contract completes purchase or refunds based on result
WASM module that verifies CAPTCHA by communicating with launchpad API.
Location: /src/main.rs
Input:
{
"session_id": "abc123",
"buyer": "alice.testnet",
"amount": "1000000000000000000000000",
"launchpad_url": "http://localhost:3001"
}Output (Success):
{
"verified": true,
"session_id": "abc123",
"error": null,
"error_type": null
}Output (Failure):
{
"verified": false,
"session_id": "abc123",
"error": "CAPTCHA verification failed",
"error_type": "wrong_answer" // or "timeout", "network_error", "system_error"
}Error handling: Worker immediately returns on wrong answer or timeout. Contract automatically refunds buyer on any failure. See ERROR_HANDLING.md for details.
Smart contract that integrates OutLayer for CAPTCHA verification.
Location: /token-sale-contract/src/lib.rs
Key methods:
buy_tokens(session_id: String)- Buy tokens with CAPTCHA verificationon_captcha_verified()- Callback to complete/refund purchaseget_stats()- View sale statistics
Node.js API server that manages CAPTCHA challenges and WebSocket connections.
Location: /launchpad-backend/server.js
CAPTCHA Provider: hCaptcha - Free, privacy-focused CAPTCHA service
Endpoints:
GET /api/session- Get session ID + hCaptcha site keyPOST /api/captcha/challenge- Create CAPTCHA challengeGET /api/captcha/verify/:id- Check challenge status (polled by worker)POST /api/captcha/solve/:id- Submit hCaptcha token for verificationWebSocket /ws?session_id=X- Real-time communication with browser
Environment Variables:
HCAPTCHA_SITE_KEY- Your hCaptcha site key (optional, uses test key by default)HCAPTCHA_SECRET- Your hCaptcha secret key (optional, uses test key by default)PORT- Server port (default: 3001)
Test Mode: By default, uses hCaptcha test keys that always pass verification. Perfect for development!
Single-page application with NEAR Wallet integration and hCaptcha.
Location: /launchpad-frontend/index.html
Features:
- NEAR Wallet Selector - MyNearWallet integration via CDN
- Session management - Backend session tracking
- WebSocket connection - Real-time CAPTCHA delivery
- hCaptcha widget - Privacy-focused CAPTCHA in modal
- Smart contract calls - Direct transaction signing via wallet
- Auto-configuration - Gets contract ID from backend API
- Network detection - Works on testnet/mainnet
- Rust toolchain with
wasm32-wasip2target - Node.js 18+
- NEAR CLI
- hCaptcha account (free at hcaptcha.com)
- Web server with SSL (for production)
- Running OutLayer coordinator
- Build & Publish WASI Worker - WASM for off-chain CAPTCHA verification, deployed as an OutLayer project
- Deploy Smart Contract - Token sale logic on NEAR blockchain
- Start Backend Server - Handles CAPTCHA challenges and WebSocket
- Build & Deploy Frontend - User interface for token purchase
- Configure Networking - Set up domains and SSL certificates
See CONFIGURATION.md for detailed setup instructions.
cd captcha-example
# Add WASM target
rustup target add wasm32-wasip2
# Build
cargo build --target wasm32-wasip2 --release
# Output: target/wasm32-wasip2/release/captcha-example.wasm (~459KB)
# Publish it and deploy as a project
outlayer upload target/wasm32-wasip2/release/captcha-example.wasm
# prints SHA256 and: FastFS URL: https://test.fastfs.io/<you>/outlayer.testnet/<sha256>.wasm
outlayer deploy captcha-example <FastFS URL>cd token-sale-contract
# Build contract
cargo near build
# Deploy to testnet with your launchpad backend URL
near contract deploy tokensale.testnet \
use-file target/near/token_sale_contract/token_sale_contract.wasm \
with-init-call new \
json-args '{
"owner": "your-account.testnet",
"total_supply": "10000",
"launchpad_url": "https://api-launchpad.your domain.com"
}' \
prepaid-gas '100.0 Tgas' \
attached-deposit '0 NEAR' \
network-config testnet \
sign-with-keychain \
sendcd launchpad-backend
# Install dependencies (including dotenv)
npm install dotenv
# Create .env file with your hCaptcha keys
cat > .env <<EOF
PORT=3181
HCAPTCHA_SITE_KEY=your_site_key_from_hcaptcha
HCAPTCHA_SECRET=your_secret_from_hcaptcha
ALLOWED_ORIGINS=https://launchpad.yourdomain.com
SESSION_SECRET=$(openssl rand -base64 32)
EOF
# Start server
npm start
# Server runs on http://localhost:3181
# WebSocket available at ws://localhost:3181/wsImportant: Backend requires dotenv package and import 'dotenv/config'; at the top of server.js.
cd launchpad-app
# Install dependencies
npm install
# Create .env file
cat > .env <<EOF
REACT_APP_CONTRACT_ID=tokensale.testnet
REACT_APP_NEAR_NETWORK=testnet
REACT_APP_HCAPTCHA_SITE_KEY=your_site_key_from_hcaptcha
EOF
# Build production app
npm run build
# Deploy build/ folder to your web server
# Frontend should be accessible at: https://launchpad.yourdomain.comFor production deployment, you need:
-
Two domains with SSL:
launchpad.yourdomain.com- Frontend (serves React app)api-launchpad.yourdomain.com- Backend (Node.js server + WebSocket)
-
Web server configuration (nginx/Apache):
- Frontend: Serve static files from
launchpad-app/build/ - Backend: Reverse proxy to Node.js on port 3181
- WebSocket: Proxy
/wspath with Upgrade headers
- Frontend: Serve static files from
-
hCaptcha dashboard:
- Add both domains to allowed domains list
- Copy Site Key and Secret to
.envfiles
See CONFIGURATION.md for complete production setup guide.
- Visit
http://localhost:8000 - Click "Connect Wallet" button
- Select MyNearWallet (or other wallet)
- Sign in with your NEAR account:
alice.testnet - Approve connection
- See your account displayed in the button
- Enter amount:
1NEAR - Click "Buy Tokens" button
- Wallet popup appears - review transaction:
- Method:
buy_tokens - Deposit: 1.1 NEAR (1 for tokens + 0.1 for OutLayer)
- Gas: 300 TGas
- Method:
- Click "Approve" in wallet
- Transaction is sent to blockchain
- CAPTCHA modal appears automatically in browser
- Complete the hCaptcha challenge (checkbox or image selection)
- Click "Submit Verification"
- Worker verifies CAPTCHA with backend
- Result sent back to contract
# View transaction result
near tx-status TRANSACTION_HASH --accountId alice.testnet
# Check contract stats
near view tokensale.testnet get_statsUser: alice.testnet
Action: buy_tokens("abc123")
Deposit: 1.1 NEAR
β
OutLayer Worker (captcha-example):
1. POST /api/captcha/challenge
{session_id: "abc123", buyer: "alice.testnet", amount: "1000..."}
2. Poll GET /api/captcha/verify/challenge_xyz
3. User solves CAPTCHA in browser
4. Return: {verified: true, session_id: "abc123"}
β
Contract Callback:
- CAPTCHA verified β
- Issue 100 tokens to alice.testnet
- Log success
Result: alice.testnet receives 100 tokens
Edit token-sale-contract/src/lib.rs:
const OUTLAYER_CONTRACT_ID: &str = "outlayer.testnet"; // or "outlayer.near"
const MIN_PURCHASE: u128 = 1_000_000_000_000_000_000_000_000; // 1 NEAR
const TOKENS_PER_NEAR: u128 = 100;Point source in the contract at your project:
let source = near_sdk::serde_json::json!({
"Project": {
"project_id": "YOUR_ACCOUNT/captcha-example",
"version_key": null
}
});Create .env file in launchpad-backend/:
# Optional: Use real hCaptcha keys for production
# Get keys at: https://www.hcaptcha.com/
HCAPTCHA_SITE_KEY=your_site_key_here
HCAPTCHA_SECRET=your_secret_key_here
# Server port
PORT=3001Test Mode: If no environment variables are set, the backend uses hCaptcha test keys:
- Site key:
10000000-ffff-ffff-ffff-000000000001(always shows simple checkbox) - Secret:
0x0000000000000000000000000000000000000000(always passes verification)
For production, set secure: true in session config (requires HTTPS).
near call tokensale.testnet buy_tokens \
'{"session_id":"YOUR_SESSION_ID"}' \
--accountId buyer.testnet \
--deposit 1.1 \
--gas 300000000000000near view tokensale.testnet get_stats
# Returns: ["0", "10000"] (tokens_sold, total_supply)near view tokensale.testnet get_price
# Returns: "100 tokens per 1 NEAR"- Sign up at https://www.hcaptcha.com/
- Create a new site and get your Site Key and Secret Key
- Set environment variables in
launchpad-backend/.env:HCAPTCHA_SITE_KEY=your_actual_site_key HCAPTCHA_SECRET=your_actual_secret_key
- Restart backend - now uses real hCaptcha with image challenges
To use reCAPTCHA or other providers, modify:
Backend (launchpad-backend/server.js):
// Replace hCaptcha verification with your provider's API
async function verifyHCaptchaToken(token, remoteip) {
// Your CAPTCHA provider verification logic
}Frontend (launchpad-frontend/index.html):
<!-- Replace hCaptcha script with your provider -->
<script src="https://www.google.com/recaptcha/api.js"></script>Edit token-sale-contract/src/lib.rs β on_captcha_verified():
// Current: Simple token counter
self.tokens_sold += tokens_amount;
// Add: Token transfer, NFT minting, etc.
// Promise::new(buyer).transfer(tokens);Launchpad backend should validate session IDs properly:
// TODO: Add proper session validation
const session = await validateSession(session_id);
if (!session || session.account_id !== buyer) {
return res.status(401).json({ error: 'Invalid session' });
}CRITICAL: Backend must verify that CAPTCHA challenge requests come from authorized OutLayer workers only. Without this, attackers can spam your backend with fake challenge requests.
// Example: API key authentication
const WORKER_API_KEY = process.env.WORKER_API_KEY; // Store securely
app.post('/api/captcha/challenge', (req, res) => {
const apiKey = req.headers['x-api-key'];
if (!apiKey || apiKey !== WORKER_API_KEY) {
return res.status(401).json({ error: 'Unauthorized' });
}
// Continue with challenge creation...
});Options for worker authentication:
- API Key: Shared secret between worker and backend (simplest for MVP)
- JWT tokens: Backend issues short-lived tokens to verified workers
- IP Whitelist: Allow requests only from known worker IPs
- Request signing: Worker signs requests with private key, backend verifies with public key
Add rate limiting to prevent abuse:
// TODO: Add rate limiter
const rateLimit = require('express-rate-limit');
app.use('/api/captcha/', rateLimit({
windowMs: 60000,
max: 10
}));Worker times out after 40 seconds. Backend cleans up after 60 seconds:
// Cleanup interval in server.js
setInterval(() => {
for (const [id, challenge] of pendingChallenges.entries()) {
if (now - challenge.created_at > 60000) {
pendingChallenges.delete(id);
}
}
}, 60000);Use HTTPS for all communication in production:
// Update CORS origin
app.use(cors({
origin: 'https://yourdomain.com',
credentials: true
}));
// Update WebSocket URL in frontend
ws = new WebSocket(`wss://yourdomain.com/ws?session_id=${sessionId}`);Solution: Make sure backend is running on port 3001:
cd launchpad-backend
npm startProblem: Challenge expired (>40 seconds)
Solution: Worker polls for 40s. User must solve CAPTCHA within this time.
Problem: Worker couldn't reach launchpad API
Solution: Check launchpad_url in contract init:
near view tokensale.testnet get_launchpad_urlProblem: Built for wrong target
Solution: Must use wasm32-wasip2:
cargo build --target wasm32-wasip2 --releaseMIT OR Apache-2.0, at your option β see LICENSE-MIT and LICENSE-APACHE.
This is a demo example. Feel free to fork and customize for your use case!
Built with β€οΈ using NEAR OutLayer