(Fraud Detection & Reputation System for x402)
TrustScore is the trust layer for the x402 autonomous AI agent payments ecosystem. It provides real-time fraud detection, comprehensive reputation scoring, and analytics to prevent scams, ensure trust, and enable safe transactions between AI agents and services.
- Real-Time Fraud Detection - Monitors all x402 transactions on Base, detecting 7 types of fraud patterns
- Two-Sided Reputation System - Scores both services (0-100) and agents (0-100) based on on-chain behavior
- Trust Compatibility Checker - Analyzes service-agent pairs for transaction safety
- Webhook Alerts - Instant notifications when fraud is detected
- x402 Payment Integration - Monetized API with free tier (10 checks/month) and one-time payment options
- Background Jobs - Automated fraud scanning and reputation score updates with configurable intervals
- SQLite Database - Lightweight, serverless database with optional PostgreSQL support
- Web Dashboard - Modern, responsive interface with animations and visual analytics
- Transaction History API - Complete transaction analytics with pagination and detailed breakdowns
- Reputation Breakdown Visualization - Visual representation of reputation score components
- Velocity Abuse - Services receiving >50 transactions/hour
- New Wallet Risk - Wallets <7 days old with >$100 volume
- Low Payer Diversity - Very few unique addresses accounting for most volume
- Identical Amounts - All transactions have exactly the same amounts
- Volume Spikes - 10x+ sudden increase in daily transaction volume
- Wash Trading - Coordinated transactions to inflate activity metrics
- Time Clustering - Suspiciously regular transaction timing indicating automation
TrustScore/
├── src/ # Core application code
│ ├── api/ # Express.js API routes and middleware
│ │ ├── middleware/ # Rate limiting, error handling, x402 payments
│ │ ├── routes/ # API endpoints (reputation, fraud, transactions)
│ │ ├── validators/ # Input validation schemas
│ │ └── server.js # Main Express server
│ ├── db/ # Database layer
│ │ ├── database.js # Database connection management
│ │ ├── queries.js # SQL query functions
│ │ └── schema.js # Database schema definitions
│ ├── fraud/ # Fraud detection engine
│ │ ├── detector.js # Fraud pattern analysis
│ │ └── rules.js # Fraud detection rules
│ ├── indexer/ # Blockchain indexing
│ │ ├── x402-indexer.js # Base network transaction indexer
│ │ └── facilitator-discovery.js # Facilitator address discovery
│ ├── jobs/ # Background tasks
│ │ ├── scheduler.js # Cron job manager
│ │ ├── fraud-scanner.js # Automated fraud detection
│ │ └── score-updater.js # Reputation score updates
│ ├── notifications/ # Alert system
│ │ └── webhook.js # Webhook notification service
│ ├── reputation/ # Reputation scoring system
│ │ ├── agent-scorer.js # Agent reputation calculation
│ │ ├── service-scorer.js # Service reputation calculation
│ │ └── trust-matcher.js # Compatibility analysis
│ ├── utils/ # Utility functions
│ │ ├── constants.js # Application constants
│ │ ├── helpers.js # Helper functions
│ │ └── logger.js # Logging system
│ └── config/ # Configuration
│ └── config.js # Main configuration file
├── public/ # Frontend assets
│ ├── index.html # Web dashboard
│ └── js/
│ └── dashboard.js # Frontend JavaScript
├── scripts/ # Utility scripts
│ ├── setup-db.js # Database initialization
│ └── seed-diverse-data.js # Comprehensive test data seeding
├── tests/ # Test suite
│ ├── integration/ # Integration tests
│ ├── unit/ # Unit tests
│ └── setup.js # Test configuration
├── examples/ # Usage examples
│ ├── agent-integration.js # Agent integration example
│ └── service-integration.js # Service integration example
├── trustscore-SDK/ # Node.js SDK
│ ├── index.js # SDK entry point
│ ├── package.json # SDK dependencies
│ └── README.md # SDK documentation
├── index.js # Main application entry point
├── package.json # Dependencies and scripts
├── jest.config.js # Test configuration
├── .env.example # Environment template
├── .gitignore # Git ignore rules
└── README.md # This file
The system uses SQLite by default with 8 main tables:
- transactions - All x402 USDC transfers with facilitator data
- fraud_flags - Detected fraudulent activities and resolutions
- service_reputation - Reputation scores and metrics for services
- agent_reputation - Reputation scores and metrics for AI agents
- webhooks - Registered webhook URLs for fraud alerts
- payments - x402 payment tracking for API usage
- used_nonces - Prevents replay attacks on x402 payments
- user_usage - Free tier usage tracking
- Node.js 18+ with npm
- SQLite 3+ (included with Node.js) or PostgreSQL 13+ (optional)
- Alchemy or Infura RPC endpoint for Base network
- Ethereum Wallet with USDC for x402 payments
git clone https://github.com/yourusername/trustscore.git
cd trustscore
npm installCreate .env file from example:
cp .env.example .envEdit .env with your configuration:
# Database (SQLite by default)
DB_TYPE=sqlite
DB_PATH=./trustscore.db
# For PostgreSQL (alternative)
# DB_HOST=localhost
# DB_PORT=5432
# DB_NAME=trustscore
# DB_USER=trustscore_user
# DB_PASSWORD=your_password
# Blockchain
BASE_RPC_URL=https://mainnet.base.org
USDC_CONTRACT=0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913
# Server
PORT=3000
NODE_ENV=development
# x402 Payments
TRUSTSCORE_WALLET_ADDRESS=0x_your_wallet_address
TRUSTSCORE_PRIVATE_KEY=your_private_key
# API Pricing (in USDC)
PRICE_REPUTATION_CHECK=0.01
PRICE_FRAUD_CHECK=0.02
PRICE_TRUST_CHECK=0.05
PRICE_WEBHOOK_REGISTRATION=1.00
# Free Tier
FREE_TIER_MONTHLY_LIMIT=10
# API Security
API_SECRET=your-secret-key-change-this-in-productionnpm run setup# Seed with diverse test scenarios for development
npm run seedThis creates test addresses with different fraud patterns:
0x1111...1111- Legitimate Service (Score: ~85)0x2222...2222- Wash Trading (Score: ~30)0x6666...6666- New Risky (Score: ~45)0x7777...7777- Volume Spike (Score: ~65)0x8888...8888- Retry Spam (Score: ~60)0xAAAA...AAAA- Excellent (Score: ~95)
npm startFor development with auto-reload:
npm run devThe system will be available at:
- API: http://localhost:3000
- Dashboard: http://localhost:3000
Important: Addresses must be indexed before reputation data is available:
- New Addresses: When you first query a service/agent address, you may see "address not found"
- Indexing Process: The system continuously scans Base blockchain for x402 transactions
- Data Population: Once an address participates in x402 transactions, it gets automatically indexed
- Reputation Calculation: Scores are calculated based on on-chain transaction history
Monitor indexing progress:
# Check API stats for indexed addresses
curl http://localhost:3000/api/statsnpm install trustscore-sdkconst TrustScore = require('trustscore-sdk');
const { ethers } = require('ethers');
// Initialize with wallet for x402 payments
const wallet = new ethers.Wallet('your-private-key');
const ts = new TrustScore({
wallet: wallet,
useFreeTier: true // 10 free checks/month
});
// Check service reputation
const serviceRep = await ts.checkService('0xServiceAddress');
console.log(`Score: ${serviceRep.reputation.score}/100`);
// Check agent reputation
const agentRep = await ts.checkAgent('0xAgentAddress');
console.log(`Trust Level: ${agentRep.reputation.trustLevel}`);
// Check fraud status
const fraudStatus = await ts.checkFraud('0xServiceAddress');
console.log(`Active fraud flags: ${fraudStatus.activeFlags.length}`);
// Register for fraud alerts
await ts.registerWebhook('0xYourService', 'https://your-api.com/webhooks/fraud');Run the complete test suite:
# Run all tests
npm test
# Run tests in watch mode
npm run test:watch
# Generate coverage report
npm run test:coverage
# Run specific test suites
npm run test:unit
npm run test:integrationThe TrustScore dashboard provides a comprehensive web interface for analyzing x402 addresses and monitoring platform health.
- Auto-detection - Automatically identifies whether an address is an x402 agent or service
- Real-time Scoring - Instant reputation scoring with detailed breakdowns
- Visual Analytics - Interactive charts and graphs for data visualization
- Transaction History - Complete transaction timeline with pagination
- Animated Progress Bars - Smooth score displays with color-coded trust levels
- Pattern Cards - Hover effects and detailed fraud pattern explanations
- Severity Indicators - Color-coded fraud flag severity levels (Critical, High, Medium, Low)
- Reputation Breakdown - Visual representation of score components
- Keyboard Shortcuts - Ctrl+K to focus search, Escape to clear results
- Responsive Design - Mobile-friendly interface with Tailwind CSS
- Loading Animations - Smooth transitions and loading states
- Tooltips - Contextual help for user guidance
- Trust Compatibility Checker - Analyze service-agent pair compatibility
- Fraud Pattern Detection - Detailed explanations of detected fraud patterns
- Platform Statistics - Real-time platform-wide metrics and health indicators
- Performance Monitoring - Page load time tracking and optimization alerts
- Access the Dashboard: Navigate to
http://localhost:3000after starting the system - Enter Address: Input any x402 agent or service address
- View Analysis: Get instant reputation scores, fraud flags, and transaction history
- Check Compatibility: Use the trust compatibility checker for pair analysis
- Monitor Stats: View platform-wide statistics and system health
The dashboard uses the following key API endpoints:
GET /api/reputation/service/:address- Service reputation dataGET /api/reputation/agent/:address- Agent reputation dataGET /api/fraud/analyze/:address- Fraud pattern analysisGET /api/transactions/:address- Transaction historyGET /api/stats- Platform statistics
Get service reputation score and detailed metrics.
Response:
{
"address": "0x...",
"reputationScore": 85,
"trustLevel": "high",
"totalTransactions": 100,
"totalVolume": "5000.00",
"uniquePayers": 50,
"accountAgeDays": 30,
"activeFraudFlags": 0,
"badges": ["VERIFIED", "TRUSTED"]
}Get agent reputation score and metrics.
Check compatibility between service and agent.
Get comprehensive fraud pattern analysis with detailed explanations.
Get basic fraud status without payment.
Get detailed fraud flag history.
Get educational information about fraud patterns.
Get transaction history with pagination and detailed analytics.
Get summary statistics without full transaction list.
Get platform-wide statistics and health metrics.
Register webhook for fraud alerts.
// src/config/config.js
blockchain: {
rpcUrl: process.env.BASE_RPC_URL,
usdcContract: process.env.USDC_CONTRACT || '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',
chainId: 8453, // Base Mainnet
blockConfirmations: 1,
backfillBlocks: 1000,
batchSize: parseInt(process.env.INDEXER_BATCH_SIZE) || 50,
maxBatchSize: parseInt(process.env.INDEXER_MAX_BATCH_SIZE) || 500,
pollingInterval: parseInt(process.env.INDEXER_POLLING_INTERVAL) || 10000
}// src/config/config.js
fraud: {
velocityLimit: 50, // Max transactions per hour
newWalletAgeDays: 7, // Days to consider "new"
newWalletVolumeThreshold: 100, // USDC volume threshold
volumeSpikeMultiplier: 10, // Spike detection multiplier
retrySpamLimit: 10, // Max retries in 5 minutes
circularFlowMinCount: 10, // Min identical payments for wash trading
lowDiversityRatio: 0.1, // Minimum payer diversity ratio
timeClusteringVariance: 0.2 // Maximum variance for timing patterns
}// src/config/config.js
reputation: {
defaultScore: 50,
minScore: 0,
maxScore: 100,
decayDays: 30,
minTransactionsForScore: 5
}// src/config/config.js
payment: {
walletAddress: process.env.TRUSTSCORE_WALLET_ADDRESS,
privateKey: process.env.TRUSTSCORE_PRIVATE_KEY,
pricing: {
reputationCheck: parseFloat(process.env.PRICE_REPUTATION_CHECK || '0.01'),
fraudCheck: parseFloat(process.env.PRICE_FRAUD_CHECK || '0.02'),
trustCheck: parseFloat(process.env.PRICE_TRUST_CHECK || '0.05'),
webhookRegistration: parseFloat(process.env.PRICE_WEBHOOK_REGISTRATION || '1.00'),
oneTimePayment: parseFloat(process.env.PRICE_ONE_TIME_PAYMENT || '0.10')
},
freeTier: {
monthlyLimit: parseInt(process.env.FREE_TIER_MONTHLY_LIMIT || '10')
}
}// src/config/config.js
jobs: {
fraudScanInterval: '*/5 * * * *', // Every 5 minutes
scoreUpdateInterval: '0 * * * *', // Every hour
cleanupInterval: '0 0 * * *' // Daily at midnight
}- Connect GitHub repository to Railway
- Add PostgreSQL database addon
- Set all environment variables
- Deploy and monitor
FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
EXPOSE 3000
CMD ["npm", "start"]# Production settings
NODE_ENV=production
DB_SSL=true
API_SECRET=strong-random-secret
BASE_RPC_URL=https://your-alchemy-url- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Add comprehensive tests for new functionality
- Ensure all tests pass and coverage stays above 80%
- Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
- Code Style: ESLint and Prettier configuration included
- Testing: 80%+ code coverage required for new features
- Documentation: JSDoc comments for all public APIs
- Security: Input validation and SQL injection protection mandatory
- API Subscriptions - $10/month per service for premium features
- Pay-per-Check - $0.01-$0.05 per reputation/fraud check
- Enterprise - Custom integrations and white-label solutions
- 10 API calls per month
- Basic reputation scores
- No advanced fraud pattern analysis
- Input Validation: All inputs validated with Joi schemas
- Rate Limiting: 100 requests per 15 minutes per IP
- SQL Injection Protection: Parameterized queries only
- Replay Attack Prevention: Nonce tracking for x402 payments
- HTTPS Only: All production traffic encrypted
- API Keys: Secure authentication for premium features
MIT License - see LICENSE file for details.
- Issues: GitHub Issues
- Discussions: GitHub Discussions
- SDK Docs: trustscore-SDK/README.md
- x402 Protocol team for the payment standard
- Base network for fast, low-cost transactions
- Alchemy for reliable RPC infrastructure
- Open source community for fraud detection research
TrustScore - Making AI agent payments safe and trustworthy.