Paygent is a production-ready AI agent payment orchestrator that enables autonomous micropayments for AI services on the Stacks blockchain. It implements the x402 payment protocol to facilitate machine-to-machine transactions, allowing AI agents to discover, evaluate, and pay for services without human intervention.
In the emerging agentic economy, AI agents need to:
- Access paid APIs and services autonomously
- Make micropayments without pre-configured credentials
- Orchestrate multi-step workflows across different services
- Maintain spending controls and audit trails
Paygent provides a complete infrastructure for autonomous agent payments:
User: "Research Bitcoin and publish findings"
Paygent:
├─ Step 1: Fetch news (0.001 STX) ──────► NewsAPI
├─ Step 2: Summarize content (0.002 STX) ► Groq AI
├─ Step 3: Analyze sentiment (0.0015 STX) ► Sentiment API
└─ Step 4: Generate tweet (0.001 STX) ───► Content Generator
Total: 0.0055 STX | 4 blockchain transactions | ~30 seconds
| Feature | Description |
|---|---|
| Multi-Step Pipelines | Orchestrate complex workflows with data flowing between steps |
| Real-Time Execution | WebSocket-powered live updates with step-by-step progress |
| Autonomous Payments | x402 protocol handles 402 Payment Required responses automatically |
| Spending Controls | Per-task and daily limits with real-time tracking |
| Service Discovery | Automatic discovery of x402-enabled services |
| Multiple Interfaces | Modern React UI, REST API, CLI, and programmatic SDK |
| Blockchain Verified | Every payment creates an auditable on-chain transaction |
┌─────────────────────────────────────────────────────────────────────────────────┐
│ PAYGENT │
├─────────────────────────────────────────────────────────────────────────────────┤
│ │
│ ┌──────────────┐ ┌──────────────────────────────────────────────────────┐ │
│ │ Frontend │ │ Backend │ │
│ │ (React 18) │────▶│ ┌─────────────────────────────────────────────────┐ │ │
│ │ Port 8080 │ WS │ │ Orchestration Server │ │ │
│ └──────────────┘ │ │ Port 3402 │ │ │
│ │ │ ┌───────────┐ ┌───────────┐ ┌───────────────┐ │ │ │
│ │ │ │ Pipeline │ │ Context │ │ x402 │ │ │ │
│ │ │ │ Engine │ │ Manager │ │ Payment │ │ │ │
│ │ │ └─────┬─────┘ └─────┬─────┘ └───────┬───────┘ │ │ │
│ │ └────────┼─────────────┼───────────────┼──────────┘ │ │
│ │ │ │ │ │ │
│ │ ┌────────▼─────────────▼───────────────▼──────────┐ │ │
│ │ │ Service Layer │ │ │
│ │ │ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌────────┐ │ │ │
│ │ │ │Discovery│ │ Wallet │ │ Payment │ │Spending│ │ │ │
│ │ │ └────┬────┘ └────┬────┘ └────┬────┘ └───┬────┘ │ │ │
│ │ └───────┼───────────┼───────────┼──────────┼──────┘ │ │
│ └──────────┼───────────┼───────────┼──────────┼────────┘ │
│ │ │ │ │ │
│ ┌───────────────────────────────┼───────────┼───────────┼──────────┼────────┐ │
│ │ External Services │ │ │ │ │
│ │ ┌────────────┐ ┌────────────┐ ┌───────▼────┐ ┌───▼────┐ │ │
│ │ │ CoinGecko │ │ NewsAPI │ │ Groq AI │ │ Stacks │ │ │
│ │ │ (Prices) │ │ (News) │ │ (LLM) │ │Testnet │ │ │
│ │ └────────────┘ └────────────┘ └────────────┘ └────────┘ │ │
│ └────────────────────────────────────────────────────────────────────────┘ │
│ │
└──────────────────────────────────────────────────────────────────────────────┘
| Component | Technology | Description |
|---|---|---|
| Frontend | React 18, Vite, TailwindCSS, shadcn/ui | Modern UI with real-time pipeline visualization |
| Orchestrator | Express.js, WebSocket | Pipeline execution, context management, service coordination |
| Demo Server | Express.js | x402-enabled API endpoints for testing |
| Payment Layer | x402-stacks v2.0.0 | HTTP 402 payment handling with Stacks transactions |
- Node.js >= 18.0.0
- npm >= 9.0.0
- Stacks Testnet Wallet with STX tokens
# Clone the repository
git clone https://github.com/emmanuelist/paygent.git
cd paygent
# Install backend dependencies
npm install
# Install frontend dependencies
cd frontend && npm install && cd ..- Create environment file:
cp .env.example .env- Configure environment variables:
# Wallet Configuration
PAYGENT_PRIVATE_KEY=your_stacks_private_key
# API Keys
GROQ_API_KEY=your_groq_api_key # AI processing
NEWS_API_KEY=your_newsapi_key # News headlines
COINGECKO_API_KEY=your_coingecko_key # Price data (optional)
# Network Configuration
NETWORK=testnet
FACILITATOR_URL=https://x402.org/facilitator
# Server Configuration
PORT=3402
DEMO_SERVER_PORT=3403- Get Testnet STX:
Visit Stacks Testnet Faucet and request tokens.
# Terminal 1: Start the demo server (x402-enabled APIs)
npm run demo-server
# Terminal 2: Start the orchestration server
npm run server
# Terminal 3: Start the frontend
cd frontend && npm run devAccess the application at http://localhost:8080
The web interface provides a visual way to execute agent pipelines:
- Enter a query in the search bar (e.g., "Research Bitcoin and publish findings")
- Watch real-time progress as each step executes
- View results including news, summaries, sentiment, and generated content
- Track transactions with clickable Stacks Explorer links
| Query | Steps | Est. Cost | Description |
|---|---|---|---|
Get current Bitcoin price |
1 | ~0.001 STX | Simple price lookup |
Get Bitcoin news |
1 | ~0.001 STX | Fetch latest headlines |
Summarize Bitcoin news |
2 | ~0.003 STX | News + AI summary |
Research Bitcoin and publish findings |
4 | ~0.01 STX | News → Summary → Sentiment → Tweet |
Full market intelligence analysis |
5 | ~0.0125 STX | Price → News → Sentiment → Summary → Report |
# Execute a pipeline
curl -X POST http://localhost:3402/task \
-H "Content-Type: application/json" \
-d '{"query": "Get Bitcoin price"}'
# Preview pipeline (no payment)
curl -X POST http://localhost:3402/preview \
-H "Content-Type: application/json" \
-d '{"query": "Research Bitcoin"}'
# List available services
curl http://localhost:3402/services
# Check wallet balance
curl http://localhost:3402/wallet
# Get spending summary
curl http://localhost:3402/spendingimport { Paygent, loadConfig } from 'paygent';
const config = loadConfig();
const agent = new Paygent(config);
// Execute a task
const result = await agent.executeTask('Get latest Bitcoin news');
if (result.success) {
console.log('Data:', result.data);
console.log('Cost:', result.payment?.amount, 'microSTX');
console.log('TxID:', result.payment?.txId);
}
// With spending limits
const limitedResult = await agent.executeTask('Market analysis', {
maxBudget: 10000, // 0.01 STX max
timeout: 60000, // 60 second timeout
});Connect to ws://localhost:3402 for real-time updates:
// Client → Server
{
type: 'execute',
payload: {
query: 'Research Bitcoin',
maxBudget: 100000 // Optional: max microSTX
}
}
// Server → Client: Pipeline start
{
type: 'pipeline_start',
payload: {
id: 'pipeline-uuid',
description: 'Research and publish workflow',
steps: [...],
estimatedCost: '0.01 STX'
}
}
// Server → Client: Step progress
{
type: 'step_start' | 'step_complete' | 'step_error',
payload: {
stepId: 'step-0',
stepName: 'Fetch News',
result?: { ... },
error?: string,
txId?: 'transaction-hash'
}
}
// Server → Client: Pipeline complete
{
type: 'pipeline_complete',
payload: {
success: true,
totalCost: '0.01 STX',
duration: 45000,
results: [...]
}
}| Method | Endpoint | Description |
|---|---|---|
POST |
/task |
Execute a pipeline |
POST |
/preview |
Preview pipeline without payment |
GET |
/services |
List available services |
GET |
/wallet |
Get wallet balance and address |
GET |
/spending |
Get spending summary |
GET |
/health |
Health check |
| Variable | Required | Default | Description |
|---|---|---|---|
PAYGENT_PRIVATE_KEY |
Yes | - | Stacks wallet private key (hex) |
GROQ_API_KEY |
Yes | - | Groq API key for AI processing |
NEWS_API_KEY |
Yes | - | NewsAPI key for news headlines |
COINGECKO_API_KEY |
No | - | CoinGecko API key (optional, has free tier) |
NETWORK |
No | testnet |
mainnet or testnet |
FACILITATOR_URL |
No | https://x402.org/facilitator |
x402 facilitator endpoint |
MAX_SPEND_PER_TASK |
No | 100000 |
Max microSTX per task (0.1 STX) |
MAX_SPEND_PER_DAY |
No | 1000000 |
Max microSTX per day (1 STX) |
PORT |
No | 3402 |
Orchestration server port |
DEMO_SERVER_PORT |
No | 3403 |
Demo API server port |
Configure spending limits to prevent runaway costs:
// Per-task limit
const result = await agent.executeTask('Query', {
maxBudget: 50000, // 0.05 STX maximum
});
// Daily limit (environment variable)
MAX_SPEND_PER_DAY=1000000 // 1 STX per day
// Per-task default (environment variable)
MAX_SPEND_PER_TASK=100000 // 0.1 STX per taskpaygent/
├── src/
│ ├── agent/ # Core Paygent agent
│ │ └── index.ts # Agent orchestration logic
│ ├── config/ # Configuration management
│ │ └── index.ts # Config loader and validator
│ ├── services/ # Service modules
│ │ ├── discovery.ts # x402 service discovery
│ │ ├── selector.ts # AI-powered service selection
│ │ ├── wallet.ts # Stacks wallet management
│ │ ├── payment.ts # x402 payment execution
│ │ └── spending.ts # Spending tracker
│ ├── types/ # TypeScript definitions
│ │ └── index.ts
│ ├── utils/ # Utility functions
│ │ ├── formatting.ts # Output formatting
│ │ ├── keygen.ts # Wallet key generation
│ │ └── logger.ts # Winston logger setup
│ ├── cli.ts # Command-line interface
│ ├── server.ts # WebSocket orchestration server
│ ├── demo-server.ts # x402-enabled demo APIs
│ └── index.ts # Main exports
├── frontend/
│ ├── src/
│ │ ├── components/ # React components
│ │ │ ├── HeroSection.tsx
│ │ │ ├── PipelineView.tsx
│ │ │ └── ui/ # shadcn/ui components
│ │ ├── hooks/ # Custom React hooks
│ │ │ └── usePipelineWebSocket.ts
│ │ ├── pages/ # Page components
│ │ │ └── Index.tsx
│ │ └── App.tsx
│ ├── public/ # Static assets
│ ├── package.json
│ └── vite.config.ts
├── docs/ # Documentation
├── .env.example # Environment template
├── package.json
├── tsconfig.json
└── README.md
# Dockerfile
FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY dist ./dist
COPY .env.example .env
EXPOSE 3402 3403
CMD ["node", "dist/server.js"]# Build and run
docker build -t paygent .
docker run -p 3402:3402 -p 3403:3403 --env-file .env paygent- Connect your GitHub repository
- Set environment variables in the dashboard
- Configure build command:
npm run build - Configure start command:
npm run server
cd frontend
vercel --prodConfigure VITE_WS_URL to point to your deployed backend.
- Never commit
.envfiles containing private keys - Use environment variables in production
- Consider hardware wallets for mainnet deployments
- Rotate keys periodically
- Set conservative limits initially
- Monitor daily spending via the
/spendingendpoint - Implement alerts for unusual activity
- Use HTTPS in production
- Implement rate limiting on public endpoints
- Validate all user inputs
- Use CORS restrictions
# Install all dependencies
npm install && cd frontend && npm install && cd ..
# Start in development mode with hot reload
npm run dev # Backend
cd frontend && npm run dev # Frontend# Run backend tests
npm test
# Run frontend tests
cd frontend && npm test
# Run with coverage
npm test -- --coverage# Build backend
npm run build
# Build frontend
cd frontend && npm run build# Lint
npm run lint
# Format (if prettier configured)
npm run formatWe welcome contributions! Please see our Contributing Guide for details.
- Fork the repository
- Create a feature branch:
git checkout -b feature/amazing-feature - Make your changes
- Run tests:
npm test - Commit:
git commit -m 'Add amazing feature' - Push:
git push origin feature/amazing-feature - Open a Pull Request
This project adheres to the Contributor Covenant Code of Conduct.
WebSocket connection failed
Error: WebSocket connection to 'ws://localhost:3402' failed
Solution: Ensure the orchestration server is running on port 3402.
Insufficient balance
Error: Insufficient STX balance for transaction
Solution: Request tokens from the Stacks Testnet Faucet.
API rate limit
Error: 429 Too Many Requests
Solution: Add API keys to .env or wait for rate limit reset.
- Multi-chain Support - Extend to other x402-compatible chains
- Plugin System - Custom service integrations
- Agent Memory - Persistent context across sessions
- Batch Operations - Execute multiple queries efficiently
- Advanced Analytics - Spending insights and optimization
- Mobile App - React Native companion app
This project is licensed under the MIT License - see the LICENSE file for details.
- x402 Protocol - HTTP 402 payment standard
- x402-stacks - Stacks implementation
- Stacks Foundation - Blockchain infrastructure
- Groq - AI inference
- CoinGecko - Cryptocurrency data
- NewsAPI - News aggregation
