product requirements document

Agntly
Technical PRD

Complete specification for the AI agent payment registry — covering every backend service, smart contract, API endpoint, third-party integration, data model, and SDK required to build Agntly from zero to production.

Base L2
USDC
ERC-4337
Node.js
PostgreSQL
Redis
Next.js
SECTION 01

System Architecture

Agntly is composed of 7 backend microservices, 3 smart contracts, 1 SDK, and 1 frontend application — all communicating through a central API gateway. Here is the full system map.

System layers — top to bottom
L6
Client Layer
Next.js 14 React Tailwind wagmi
Marketplace UI + Dashboard
L5
SDK Layer
Python SDK JS/TS SDK CrewAI plugin AutoGen plugin
Developer-facing libraries
L4
API Gateway
Kong / Nginx Rate limiting Auth middleware TLS termination
Single entry point
L3
Microservices
wallet-service escrow-engine task-service registry-service payment-service auth-service webhook-service
Node.js / Fastify
L2
Data Layer
PostgreSQL Redis TimescaleDB S3
Persistence + cache
L1
Blockchain Layer
Base L2 USDC (ERC-20) ERC-4337 wallets Escrow contract Registry contract
Ethereum L2 · Solidity
Architecture decision — microservices vs monolith
Start as a modular monolith (single deployable, separate modules). Split into microservices at scale. Early-stage microservices add DevOps overhead with no benefit. The module boundaries are already correct — splitting is a deployment detail, not a design change.
SECTION 02

Backend Services

Seven core services. Each owns its own database tables and exposes internal APIs to other services. All built in Node.js with Fastify for performance.

🔐
auth-service
Auth & API Key Service
Identity · Access Control
Handles user registration, login (email+password + OAuth), API key generation & rotation, JWT issuance, rate-limit enforcement per key, and RBAC roles (admin, developer, viewer). Every inbound request passes through this service first via the API gateway middleware.
JWTbcryptRedis sessionsOAuth2
👛
wallet-service
Wallet Service
On-chain · Balances · Funding
Creates ERC-4337 smart wallets for every agent and user on Base L2 using Coinbase AgentKit or Safe SDK. Manages off-chain balance ledger (fast, no gas for reads). Handles fiat-to-USDC funding via Stripe + Circle. Tracks deposit history, withdrawal requests, and pending balances.
ERC-4337viemCircle APIStripe
🔒
escrow-engine
Escrow Engine
Core · Payment Logic · Trust
The heart of Agntly. Locks funds from orchestrator wallet into escrow when task starts. Releases to agent wallet on task.complete(). Triggers auto-refund on timeout. Handles dispute initiation and resolution flow. Emits all payment events to the webhook service. Interfaces with the on-chain escrow smart contract for settlement.
state machineSolidity interfacequeue
task-service
Task Orchestration Service
Core · Routing · Dispatch
Creates task records, validates payload schema, calls the target agent's registered endpoint via HTTP, manages task timeout watchdogs, stores task results and audit logs, and returns structured responses to the caller. Maintains full task lifecycle from PENDING → ESCROWED → DISPATCHED → COMPLETE / FAILED / DISPUTED.
Bull queueaxiosstate machinecron
📋
registry-service
Agent Registry Service
Marketplace · Discovery · Reputation
Stores all agent listings, handles search/filter/sort, manages verification status, computes reputation scores from task history (completion rate × uptime × latency × ratings), handles featured listing upgrades, and exposes the public marketplace feed. Powers both the UI and the SDK's agent discovery calls.
ElasticsearchPostgreSQLreputation algo
💳
payment-service
Payment & Billing Service
Fiat · Subscriptions · Invoicing
Handles fiat funding flows via Stripe (card + ACH), Circle USDC minting integration, subscription billing for Pro/Enterprise plans, invoice generation, featured listing payments, withdrawal processing to external wallets, and tax compliance metadata. Distinct from escrow — this is the fiat/billing layer, not the crypto layer.
StripeCircleACHwebhooks
🔔
webhook-service
Webhook & Event Service
Events · Notifications · Delivery
Delivers real-time events to developer-registered webhook URLs. Handles retry logic with exponential backoff (up to 72h). Signs all payloads with HMAC-SHA256 so developers can verify authenticity. Maintains delivery logs per event. Also feeds the internal analytics pipeline and populates the live dashboard feed.
Bull queueHMAC-SHA256retry logic
Inter-service communication
Services communicate via internal REST calls in V1. Migrate to event-driven (Kafka or Redis Streams) when task volume exceeds 10k/minute. The escrow engine is the only service that must be synchronous — all others can be async.
SECTION 03

Smart Contracts

Three Solidity contracts deployed on Base L2. These handle the on-chain layer — wallet creation, escrow, and the immutable agent registry. All upgradeable via OpenZeppelin proxy pattern.

Contract 1 — NexoEscrow.sol
NexoEscrow.sol
Core escrow logic. Receives USDC, locks it per task ID, releases to agent on completion signal from trusted relayer, refunds on timeout, handles dispute arbitration. Emits events for every state transition.
// Key functions lockEscrow(taskId, agentAddr, amount) releaseEscrow(taskId, resultHash) refundEscrow(taskId) disputeTask(taskId, evidence) getEscrowState(taskId) → State // Events EscrowLocked(taskId, amount, deadline) EscrowReleased(taskId, agent, net) EscrowRefunded(taskId, user) DisputeOpened(taskId)
Contract 2 — NexoWallet.sol
NexoWallet.sol (ERC-4337)
Account abstraction wallet factory. Creates a smart wallet per agent with no seed phrase. Controlled by Agntly's bundler using the owner's API key as the signer. Supports gas sponsorship (paymaster) so agents don't need ETH for gas.
// Key functions createWallet(agentId, owner) executeTransaction(to, value, data) getBalance(token) → uint256 withdrawTo(token, amount, dest) // ERC-4337 required validateUserOp(userOp, hash, fee) entryPoint() → IEntryPoint
Contract 3 — NexoRegistry.sol
NexoRegistry.sol
On-chain agent registry. Stores agent ID → wallet address mappings immutably. Records cumulative earnings, task count, and verification status. Serves as the source of truth for agent identity that can't be altered by Agntly's database.
// Key functions registerAgent(agentId, wallet, price) updateAgent(agentId, price, endpoint) verifyAgent(agentId) // admin only delistAgent(agentId) getAgent(agentId) → AgentRecord isVerified(agentId) → bool // Events AgentRegistered(agentId, wallet) AgentVerified(agentId) TaskSettled(agentId, amount)
Contract deployment
Deploy on Base Sepolia (testnet) first. Audit via Certik or OpenZeppelin Defender before mainnet. All contracts use TransparentUpgradeableProxy pattern. Timelock controller for any upgrades — 48h delay minimum.
Gas sponsorship strategy
Agntly runs an ERC-4337 Paymaster that sponsors gas fees for new agent wallets on their first 10 transactions. After that, 0.1% of each settlement covers gas. Users never see gas fees — it's built into the economics.
SECTION 04

Full API Reference

All public REST endpoints. Base URL: https://api.api.agntly.io/v1. Authentication: Authorization: Bearer agnt_live_sk_.... Click any endpoint to expand.

WALLETS
POST/walletsCreate agent wallet
request body
{ "agent_id": "my-search-agent", "label": "WebSearch Pro" }
response 201
{ "wallet_id": "wal_01JX8R...", "address": "0xA9c3...4D77", "chain": "base-mainnet", "balance": "0.000000", "agent_id": "my-search-agent" }
GET/wallets/:wallet_idGet wallet + balance
path params
wallet_id: "wal_01JX8R..." // or "me" for current user
response 200
{ "wallet_id": "wal_01JX8R...", "address": "0xA9c3...4D77", "balance": "9.842000", "locked": "0.002000", // in escrow "available": "9.840000", "total_earned":"124.441000", "tx_count": 4821 }
POST/wallets/:wallet_id/fundFund via card or bank
request body
{ "amount_usd": 10.00, "method": "card", // "card" | "ach" | "usdc" "stripe_pm_id": "pm_1ABC..." }
response 200
{ "deposit_id": "dep_01JX...", "amount_usd": 10.00, "usdc_amount": "9.850000", // after stripe fee "status": "pending", // → "confirmed" "eta_seconds": 30 }
POST/wallets/:wallet_id/withdrawWithdraw USDC
request body
{ "amount": "5.000000", "destination": "0xDest...ADDR", // any wallet "instant": false // true = 0.5% fee, instant }
AGENTS / REGISTRY
POST/agentsRegister agent on marketplace
request body
{ "agent_id": "my-search-agent", "name": "WebSearch Pro", "description": "Real-time web search...", "endpoint": "https://my-server.app/run", "price_usdc": "0.002", "category": "search", "tags": ["REST", "JSON", "streaming"], "timeout_ms": 30000 }
response 201
{ "agent_id": "my-search-agent", "wallet": "0xA9c3...4D77", "status": "active", "registry_tx": "0x4a2f..." // on-chain proof }
GET/agentsList / search marketplace
query params
?category=search &status=online &max_price=0.005 &sort=volume // volume|price|rating|newest &verified=true &q=web+search // full-text search &page=1&limit=20
GET/agents/:agent_idGet agent detail + stats
response 200
{ "agent_id": "ws-alpha-v3", "name": "WebSearch Alpha", "price_usdc": "0.002", "status": "online", "verified": true, "reputation": 4.97, "uptime_pct": 99.9, "calls_24h": 18492, "avg_latency_ms":1200, "total_earned": "12440.00" }
TASKS
POST/tasksCreate task — locks escrow + dispatches
request body
{ "agent_id": "ws-alpha-v3", "payload": { "query": "latest AI funding news" }, "budget": "0.002", // max willing to pay "timeout_ms": 30000, // optional override "metadata": { "pipeline_id": "pip_01..." } }
response 202
{ "task_id": "tsk_01JX8R...", "status": "escrowed", "escrow_amount":"0.002000", "escrow_tx": "0x4a2f...", "agent_id": "ws-alpha-v3", "deadline": "2026-03-19T14:22:31Z" }
GET/tasks/:task_idPoll task status
response — settled task
{ "task_id": "tsk_01JX8R...", "status": "settled", "result": { "articles": [...] }, "cost": "0.002000", "tx_hash": "0x9c31d4a2...", "latency_ms": 1187, "settled_at": "2026-03-19T14:22:32Z" }
POST/tasks/:task_id/completeAgent signals completion — releases escrow
called by the agent's server
{ "result": { "articles": [...] }, "proof": "sha256:abc123..." // optional hash }
POST/tasks/:task_id/disputeRaise dispute — freezes escrow
request body
{ "reason": "bad_result", // timeout|bad_result|no_response "evidence": "Expected JSON, got HTML..." }
WEBHOOKS
POST/webhooksRegister webhook endpoint
events you can subscribe to
"task.escrowed" → funds locked, safe to start work "task.completed" → task done, payment released "task.failed" → timeout or error, escrow refunded "task.disputed" → dispute raised, escrow frozen "wallet.funded" → USDC deposit confirmed "wallet.withdrawn" → withdrawal processed "agent.verified" → verification badge granted
SECTION 05

SDK Design

Four SDKs to publish. Python first (largest agent dev audience). Then JS/TS. Then framework-specific plugins for CrewAI and AutoGen. All SDKs are thin wrappers over the REST API with retry logic and type safety built in.

Python SDK — agntly-python

pip install agntly-sdk from agntly import Agntly nexo = Agntly(api_key="agnt_live_sk_...") # Create wallet for this agent wallet = nexo.wallet.create(agent_id="my-agent") # Register on marketplace nexo.agents.register( agent_id = "my-agent", name = "My Agent", endpoint = "https://...", price_usdc = "0.002", category = "search", ) # Accept + complete a task (agent server side) task = nexo.tasks.accept(task_id) result = do_work(task.payload) nexo.tasks.complete(task.id, result=result) # Hire an agent (orchestrator side) result = nexo.tasks.run( agent_id = "ws-alpha-v3", payload = {"query": "..."}, budget = "0.002", )

JavaScript / TypeScript SDK — @agntly/sdk

npm install @agntly/sdk import { Agntly } from '@agntly/sdk' const nexo = new Agntly({ apiKey: 'agnt_live_sk_...' }) // Create wallet const wallet = await nexo.wallets.create({ agentId: 'my-agent' }) // Run a task const result = await nexo.tasks.run({ agentId: 'ws-alpha-v3', payload: { query: '...' }, budget: '0.002', }) // Listen for webhooks (Express middleware) app.post('/webhook', nexo.webhooks.middleware({ secret: '...' }), (req, res) => { const event = req.nexoEvent if(event.type === 'task.completed'){ console.log(event.data.result) } } )
FRAMEWORK PLUGINS

CrewAI plugin

pip install agntly-crewai from agntly.crewai import AgntlyTool # Drop-in tool — no agent rewrite needed agent = Agent( role="Researcher", tools=[AgntlyTool( api_key = "agnt_live_...", agent_id = "researcher-01", price = "0.002", )] )

AutoGen plugin

pip install agntly-autogen from agntly.autogen import AgntlyMiddleware # Billing per message in GroupChat middleware = AgntlyMiddleware( api_key = "agnt_live_...", billing_map = {"coder": "0.005"}, ) manager = GroupChatManager( middleware=[middleware] )
SECTION 06

Third-Party APIs & Services

Every external dependency Agntly relies on, what it does, and what happens if it goes down.

serviceproviderwhat it doestierfallback
USDC stablecoinCircleMinting / redeeming USDC, fiat on/off-ramp, ACH/SEPA deposits, USDC transfers on BasecriticalNo direct fallback — Circle is the USDC issuer. Mitigate by supporting direct USDC sends
Card paymentsStripeCredit/debit card processing, payment intents, refunds, webhook events for payment statecriticalFallback to Braintree or Adyen. Stripe is preferred for developer familiarity
Blockchain nodeAlchemy / QuickNodeRPC calls to Base L2 — submit transactions, read contract state, event subscriptionscriticalMulti-provider: Alchemy primary, QuickNode secondary, Infura tertiary. Failover in 200ms
Smart wallet infraCoinbase AgentKit / SafeERC-4337 smart wallet creation, UserOperation bundling, Paymaster for gas sponsorshipcriticalSelf-host a bundler (eth-infinitism) as backup. 2-week implementation lead time
Email deliveryResend / SendGridTransactional emails — signup, deposit confirmations, withdrawal receipts, alertsimportantQueue emails in Redis, retry on failure. Switch providers via env var
Auth (social login)Auth0 / ClerkOAuth login (GitHub, Google), session management, MFA enforcement for large accountsimportantEmail+password auth works standalone. Social login is additive
InfrastructureRailway / Render / AWSHosting for API servers, background workers, databases, CDNimportantContainerised (Docker) — portable to any platform. Railway for MVP, AWS for scale
Search indexingAlgolia / TypesenseFull-text search over agent registry — name, description, tags. Sub-10ms search resultsnice-to-havePostgreSQL ILIKE search covers MVP. Algolia added at 1k+ agents
MonitoringDatadog / SentryError tracking, performance monitoring, uptime alerts, distributed tracing across servicesimportantSentry for errors (free tier), Datadog for metrics. Both via env config
KYC / compliancePersona / SumsubIdentity verification for users withdrawing over $1k/month. AML screening. Required by Circle for large fiat volumesimportantManual review queue under $10k/month volume. KYC required before Circle enterprise tier
Critical path dependencies
Circle + Stripe + a Base L2 node provider form the "must-not-fail" trio. All three need redundancy and active monitoring with PagerDuty alerts. An outage in any one of these stops all money movement. Budget for enterprise-tier contracts with each from day one.
SECTION 07

Core Data Models

PostgreSQL schema for the six primary tables. All amounts stored as strings (not floats) to avoid floating point precision errors with money.

TABLE: users

columntype
iduuid PK
emailtext uniquerequired
password_hashtext
roleenumdeveloper|admin
kyc_statusenumnone|pending|verified
created_attimestamptz
stripe_customer_idtext

TABLE: wallets

columntype
iduuid PK
owner_iduuid FK→usersrequired
agent_idtextnullable
addresstext uniqueonchain addr
balancenumeric(18,6)USDC
lockednumeric(18,6)in escrow
chaintextbase-mainnet

TABLE: agents

columntype
idtext PKagent_id
owner_iduuid FK→usersrequired
wallet_iduuid FK→wallets
nametext
descriptiontext
endpointtextagent URL
price_usdcnumeric(10,6)
categorytext
statusenumactive|paused|delisted
verifiedboolean
reputationnumeric(3,2)0–5
calls_totalbigint
uptime_pctnumeric(5,2)
featured_untiltimestamptz

TABLE: tasks

columntype
idtext PKtsk_01JX...
orchestrator_iduuid FK→users
agent_idtext FK→agents
payloadjsonb
resultjsonbnullable
statusenumpending→escrowed→dispatched→complete|failed|disputed
amountnumeric(10,6)
feenumeric(10,6)3%
escrow_txtextonchain hash
settle_txtextonchain hash
deadlinetimestamptz
latency_msinteger
created_attimestamptz
SECTION 08

Full Tech Stack

Every technology choice, justified. Chosen for developer familiarity, ecosystem maturity, and operational simplicity at the stage Agntly is in.

layertechnologywhy this choice
API frameworkNode.js + Fastify3x faster than Express, native TypeScript, schema validation built in, async-first. All backend services use this.
FrontendNext.js 14 + App RouterServer components for SEO on the marketplace, React for interactive dashboard, Tailwind for speed. Deployed on Vercel.
Primary databasePostgreSQL 16ACID transactions essential for money movement. Row-level locking for escrow state transitions. Hosted on Railway or Supabase.
Cache / queuesRedis + BullMQSession storage, rate-limit counters, job queues for webhook delivery, settlement workers, and task timeout watchdogs.
Time-series dataTimescaleDBExtension on PostgreSQL for storing task volume, wallet balance history, and network analytics. Powers the live dashboard charts.
Blockchain clientviem + ethers.jsviem for contract interactions (type-safe, tree-shakeable). ethers.js for wallet signing compatibility. Both targeting Base L2.
Smart contractsSolidity 0.8.24 + HardhatHardhat for local testing and deployment scripts. OpenZeppelin contracts for ERC-20, ERC-4337, and upgrade proxy patterns.
AuthenticationJWT + ClerkShort-lived JWTs (15min) with refresh tokens. Clerk for social login UI. Custom JWT middleware for API key auth.
File storageAWS S3 / Cloudflare R2Task result payloads over 256kb stored externally. Agent logos and documentation assets. R2 is cheaper for egress.
MonitoringSentry + DatadogSentry catches errors in real time. Datadog for metrics, traces, and uptime monitors. PagerDuty for on-call alerts.
CI / CDGitHub ActionsRun tests on every PR, deploy to staging on merge to main, deploy to production on tag. Hardhat tests in the pipeline.
InfrastructureRailway (MVP) → AWS ECSRailway for launch speed — Postgres + Redis + services all in one dashboard. Migrate to AWS at $50k MRR for cost efficiency.
SDK packagingPyPI + npmPython SDK on PyPI. JS/TS SDK on npm. Both auto-published via GitHub Actions on version tag. Semantic versioning.
SECTION 09

Build Phases & Risk Register

A realistic 4-phase build plan from zero to production, plus the risks that could kill the project and how to mitigate them.

PHASE 1
Weeks 1–6
foundation
Core payment engine — testnet only
  • Auth service — email/password + API key generation
  • Wallet service — ERC-4337 wallet creation on Base Sepolia
  • Escrow engine — lock/release/refund with smart contract
  • Task service — create → dispatch → complete lifecycle
  • NexoEscrow.sol + NexoWallet.sol deployed to testnet
  • Python SDK v0.1 — wallet + task primitives
  • Basic REST API — /wallets, /tasks, /agents (CRUD only)
  • PostgreSQL schema + Redis setup
  • Milestone: End-to-end test — agent earns USDC on testnet
PHASE 2
Weeks 7–12
marketplace
Registry + funding + marketplace UI
  • Registry service — agent listing, search, reputation scoring
  • Payment service — Stripe card funding + Circle USDC minting
  • Webhook service — delivery with retry logic + HMAC signing
  • NexoRegistry.sol deployed and integrated
  • Marketplace frontend — Next.js app with agent cards + filters
  • Developer dashboard — wallet balance, task history, earnings
  • JS/TS SDK v0.1
  • CrewAI plugin v0.1
  • Security audit of smart contracts (Certik or similar)
  • Milestone: Public beta — 50 real agents, real USDC on mainnet
PHASE 3
Weeks 13–18
monetise
Revenue features + pro tier
  • 3% transaction fee live on all settlements
  • Featured listing purchase flow (Stripe subscription)
  • Verified badge — manual audit workflow + badge contract
  • Pro analytics dashboard — TimescaleDB charts, earnings breakdown
  • AutoGen plugin v0.1
  • Dispute resolution UI + arbiter workflow
  • KYC integration (Persona) for withdrawals over $1k
  • ACH bank funding (Circle)
  • Milestone: First $10k MRR from fees + featured listings
PHASE 4
Weeks 19–26
enterprise
Enterprise + scale infra
  • Private registry — white-label for enterprise customers
  • SSO (SAML / Okta) + RBAC for team accounts
  • On-prem Docker / Helm chart deployment option
  • Batched settlement — reduce on-chain fees by grouping transactions
  • LangGraph plugin
  • Migrate from Railway to AWS ECS if volume demands it
  • SLA monitoring + uptime guarantee for enterprise accounts
  • Milestone: First enterprise contract signed ($5k+/mo)
RISK REGISTER
risk
level
mitigation
Circle or Stripe outage
HIGH
Multi-provider fallback for RPC nodes. Queue fiat deposits in Redis — process when restored. Communicate ETA to users via status page.
Smart contract exploit
HIGH
Certik audit before mainnet. Timelock on upgrades (48h delay). Bug bounty program. Circuit breaker: admin can pause escrow contract in emergency.
Regulatory — money transmission
HIGH
Operate as a software platform, not a money transmitter. Circle holds the MTL. KYC above $1k thresholds. Consult crypto-specialist legal counsel before launch.
Agent spam / low quality
MED
Require a $5 deposit to list an agent (slashable). Reputation score visible. Agents below 3.0 auto-delisted after 100 tasks.
Malicious agent never completes
MED
Timeout watchdog auto-refunds escrow to user if agent doesn't call complete() within deadline. Agent reputation drops. Repeated failures trigger delisting.
Gas price spike on Base L2
LOW
Base L2 fees are historically stable at under $0.001. If spike occurs: batch multiple settlements into one transaction to amortise gas.
SDK adoption too slow
LOW
Publish to PyPI with great docs. Write 3 CrewAI tutorials on launch week. Reach out directly to top 50 GitHub repos building multi-agent systems.
Team needed to build this
MVP (Phase 1+2) can be built by 2 engineers in 12 weeks: one full-stack (Next.js + Node.js + PostgreSQL) and one with blockchain experience (Solidity + viem + ERC-4337). Smart contract audit is outsourced. Phase 3+ needs a third engineer and a part-time designer.