Building Agent-402: Cryptographically-Signed AI Agents for Regulated Finance
We built infrastructure that lets AI agents work in regulated industries (finance, healthcare, legal) by adding cryptographic signatures, immutable audit trails, and deterministic replay.
🌐 Live Demo: https://agent402.ainative.studio
💻 GitHub: https://github.com/AINative-Studio/Agent-402
The Problem Nobody's Solving
AI agents are everywhere. ChatGPT, AutoGPT, autonomous trading bots—they're powerful and getting smarter every day.
But they can't work in finance. Or healthcare. Or legal. Or any regulated industry.
Why?
Because they're black boxes:
- ❌ No cryptographic verification
- ❌ No audit trails
- ❌ Can't prove what they did
- ❌ Can't replay decisions
- ❌ No compliance architecture
A financial regulator asks: "Prove your AI agent made this trade for legitimate reasons."
Current answer: "Uhh... trust us?"
That doesn't fly in regulated industries.
This blocks billions of dollars in AI value from finance, healthcare, legal, and government sectors.
What We Built
Agent-402 is infrastructure for auditable, compliant autonomous agents.
Architecture Overview
┌─────────────────────────────────────────────┐
│ CrewAI Agent System │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
│ │ Analyst │ │Compliance│ │Transaction│ │
│ │ Agent │ │ Agent │ │ Agent │ │
│ └────┬─────┘ └────┬─────┘ └────┬──────┘ │
└───────┼────────────┼────────────┼───────────┘
│ │ │
└────────────┴────────────┘
↓
┌────────────────────────┐
│ x402 Signing Layer │
│ (Cryptographic Sigs) │
└───────────┬────────────┘
↓
┌────────────────────────┐
│ Circle Programmable │
│ Wallets │
└───────────┬────────────┘
↓
┌────────────────────────┐
│ Arc Network (L1) │
│ (USDC Settlement <1s) │
└───────────┬────────────┘
↓
┌────────────────────────┐
│ ZeroDB Ledgers │
│ (Immutable Audit Trail)│
└────────────────────────┘
Core Components
- x402 Protocol - Cryptographically signed requests
- Circle Arc Network - Blockchain settlement layer
- Circle Wallets - Programmable agent treasuries
- CrewAI - Multi-agent orchestration
- ZeroDB - Persistent memory & audit ledgers
Technical Deep Dive
1. Cryptographic Signing with x402
Every agent request is cryptographically signed before execution:
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import padding
import base64
import json
def sign_request(payload: dict, private_key) -> str:
"""
Sign an agent request with private key
Returns base64-encoded signature
"""
# Serialize payload deterministically
message = json.dumps(payload, sort_keys=True).encode()
# Sign with RSA-PSS
signature = private_key.sign(
message,
padding.PSS(
mgf=padding.MGF1(hashes.SHA256()),
salt_length=padding.PSS.MAX_LENGTH
),
hashes.SHA256()
)
return base64.b64encode(signature).decode()
def verify_signature(payload: dict, signature: str, public_key) -> bool:
"""
Verify request signature
"""
try:
message = json.dumps(payload, sort_keys=True).encode()
sig_bytes = base64.b64decode(signature)
public_key.verify(
sig_bytes,
message,
padding.PSS(
mgf=padding.MGF1(hashes.SHA256()),
salt_length=padding.PSS.MAX_LENGTH
),
hashes.SHA256()
)
return True
except Exception:
return False
Why this matters:
- Every agent action has a cryptographic signature
- Can prove WHO authorized WHAT action WHEN
- Non-repudiable (agent can't deny it did something)
2. Circle Wallets Integration
Each agent gets its own programmable wallet:
import requests
import os
CIRCLE_API_KEY = os.getenv("CIRCLE_API_KEY")
CIRCLE_API_URL = "https://api.circle.com/v1"
def create_agent_wallet(agent_id: str) -> dict:
"""
Create a developer-controlled wallet for an agent
"""
response = requests.post(
f"{CIRCLE_API_URL}/wallets",
headers={
"Authorization": f"Bearer {CIRCLE_API_KEY}",
"Content-Type": "application/json"
},
json={
"idempotencyKey": f"agent-{agent_id}-{int(time.time())}",
"walletSetId": os.getenv("WALLET_SET_ID"),
"metadata": {
"agent_id": agent_id,
"created_at": datetime.utcnow().isoformat()
}
}
)
return response.json()
# Create wallets for each agent
analyst_wallet = create_agent_wallet("analyst-001")
compliance_wallet = create_agent_wallet("compliance-001")
transaction_wallet = create_agent_wallet("transaction-001")
Agent treasury management:
- Each agent has its own USDC balance
- Can track spending per agent
- Policy-governed (e.g., max $1000/day per agent)
3. Arc Network Settlement
Transactions settle on Arc blockchain in sub-second time:
from web3 import Web3
# Connect to Arc Network
ARC_RPC = "https://rpc.arc.network"
web3 = Web3(Web3.HTTPProvider(ARC_RPC))
# USDC is native gas on Arc
USDC_ADDRESS = "0x..." # Arc USDC contract
def execute_payment(from_wallet: str, to_address: str, amount_usdc: float) -> str:
"""
Execute USDC payment on Arc Network
Returns transaction hash
"""
# Convert USDC amount to smallest unit (6 decimals)
amount_wei = int(amount_usdc * 10**6)
# Build transaction
tx = {
'from': from_wallet,
'to': USDC_ADDRESS,
'value': 0,
'gas': 100000,
'gasPrice': web3.eth.gas_price,
'nonce': web3.eth.get_transaction_count(from_wallet),
'data': encode_transfer(to_address, amount_wei)
}
# Sign and send
signed_tx = web3.eth.account.sign_transaction(tx, private_key)
tx_hash = web3.eth.send_raw_transaction(signed_tx.rawTransaction)
return tx_hash.hex()
def verify_settlement(tx_hash: str) -> bool:
"""
Verify transaction was successful on Arc
"""
receipt = web3.eth.get_transaction_receipt(tx_hash)
return receipt['status'] == 1
Why Arc Network:
- USDC as native gas (no ETH needed)
- Sub-second finality
- Predictable fees
- Built for stablecoin commerce
4. Immutable Audit Trail
Every action is logged to ZeroDB:
from zerodb_client import ZeroDBClient
db = ZeroDBClient(
api_key=os.getenv("ZERODB_API_KEY"),
project_id=os.getenv("PROJECT_ID")
)
def log_agent_action(
agent_id: str,
action_type: str,
payload: dict,
result: dict,
signature: str
):
"""
Store agent action in immutable ledger
"""
entry = {
"agent_id": agent_id,
"timestamp": datetime.utcnow().isoformat(),
"action_type": action_type,
"payload": payload,
"result": result,
"signature": signature,
"tx_hash": result.get("tx_hash"),
"arc_block": result.get("block_number")
}
# Store with vector embedding for semantic search
db.store(
collection="agent_actions",
data=entry,
text=f"{action_type}: {json.dumps(payload)}"
)
return entry
# Example usage
log_agent_action(
agent_id="transaction-001",
action_type="usdc_transfer",
payload={"to": "0x...", "amount": 100.00},
result={"tx_hash": "0x...", "block_number": 12345},
signature="base64_signature_here"
)
Audit capabilities:
- Query any agent's history
- Prove what happened when
- Replay entire workflows
- Generate compliance reports
Real-World Use Cases
1. Autonomous Trading (Fintech)
from crewai import Agent, Task, Crew
# Define agents
analyst = Agent(
role="Market Analyst",
goal="Analyze market conditions and identify opportunities",
tools=[market_data_tool, sentiment_analysis_tool]
)
compliance = Agent(
role="Compliance Officer",
goal="Ensure all trades meet regulatory requirements",
tools=[kyc_check_tool, aml_screening_tool, risk_assessment_tool]
)
trader = Agent(
role="Transaction Agent",
goal="Execute approved trades with x402 signing",
tools=[x402_signing_tool, arc_settlement_tool]
)
# Orchestrate workflow
crew = Crew(
agents=[analyst, compliance, trader],
tasks=[analyze_task, compliance_task, trade_task],
process="sequential"
)
# Every step is signed and auditable
result = crew.kickoff()
Compliance benefits:
- Full audit trail of decision process
- Can prove compliance checks were performed
- Deterministic replay for investigations
- Cryptographically verifiable
2. Clinical Decision Support (Healthcare)
# AI agent analyzes patient data
clinical_agent = Agent(
role="Clinical Analyst",
goal="Analyze patient data and recommend treatments",
tools=[medical_kb_tool, drug_interaction_tool]
)
# Every recommendation is:
# 1. Cryptographically signed by agent
# 2. Stored in immutable ledger
# 3. Can be replayed to show reasoning
# 4. HIPAA-compliant audit trail
recommendation = clinical_agent.execute(patient_data)
3. Contract Analysis (Legal)
# AI agent reviews legal contracts
legal_agent = Agent(
role="Contract Analyzer",
goal="Identify risks and flag issues in contracts",
tools=[legal_kb_tool, precedent_search_tool]
)
# Benefits:
# - Provable AI analysis
# - Can demonstrate to court
# - Full audit trail
# - Deterministic results
Results & Performance
Speed
- ⚡ Transaction settlement: <1 second on Arc
- ⚡ Agent decision time: 2-5 seconds
- ⚡ Signature verification: <100ms
Security
- 🔒 RSA-2048 signatures (industry standard)
- 🔒 Immutable ledgers (can't modify history)
- 🔒 On-chain verification (trustless)
Compliance
- ✅ 100% audit coverage
- ✅ Cryptographically verifiable
- ✅ Deterministically replayable
- ✅ Non-repudiable actions
Try It Yourself
Live Demo
🌐 https://agent402.ainative.studio
Quick Start (Local)
# Clone repository
git clone https://github.com/SenayYakut/Agent-402
cd Agent-402
# Install dependencies
pip install -r requirements.txt
# Set up environment
cp .env.example .env
# Add your API keys:
# - CIRCLE_API_KEY
# - ZERODB_API_KEY
# - ARC_RPC_URL
# Run demo
python scripts/run_demo.py
Example Output
🚀 Starting Agent-402 Demo
✅ Created analyst wallet: 0x1234...
✅ Created compliance wallet: 0x5678...
✅ Created transaction wallet: 0x9abc...
📊 Analyst Agent: Analyzing market conditions...
→ Opportunity identified: BTC/USDC arbitrage
🔍 Compliance Agent: Running checks...
→ KYC: PASSED
→ AML: PASSED
→ Risk score: LOW
💰 Transaction Agent: Executing trade...
→ Signed with x402: sig_abc123...
→ Submitted to Arc: tx_0xdef456...
→ Confirmed in block: 12345
✅ Trade complete!
📝 Audit entry: https://agent402.ainative.studio/audit/xyz789
⏱️ Total time: 3.2 seconds
What's Next
Short Term
- [ ] Add multi-party signing (requires 2+ agents to approve)
- [ ] Integration with more compliance APIs
- [ ] Dashboard for monitoring agent activity
- [ ] More agent templates (DeFi, healthcare, legal)
Long Term
- [ ] Agent marketplace (deploy pre-built compliant agents)
- [ ] Cross-chain support (beyond Arc)
- [ ] Enterprise features (SSO, custom policies)
- [ ] Regulatory reporting automation
Technical Stack Summary
| Component | Technology | Purpose |
|---|---|---|
| Agent Orchestration | CrewAI | Multi-agent coordination |
| Signing | x402 Protocol | Cryptographic request signing |
| Settlement | Circle Arc Network | Blockchain + USDC |
| Wallets | Circle Programmable Wallets | Agent treasuries |
| Memory | ZeroDB | Persistent storage |
| API | FastAPI | HTTP server |
| Language | Python 3.11+ | Backend logic |
Why This Matters
Current state:
- AI agents are powerful
- But can't work in regulated industries
- Compliance is the bottleneck
With Agent-402:
- Agents can be audited
- Actions are provable
- Regulators can verify
- AI can finally work in finance, healthcare, legal
This unlocks billions in AI value that's currently blocked by compliance concerns.
Links & Resources
- 🌐 Live Demo: https://agent402.ainative.studio
- 💻 GitHub: https://github.com/SenayYakut/Agent-402
- 📚 Documentation: https://github.com/SenayYakut/Agent-402/tree/main/docs
- 🎥 Demo Video: [Coming soon]
- 🏆 Hackathon: Built for lablab.ai's Agentic Commerce on Arc
Open source (MIT License)
Contributions welcome! ⭐
Discussion
What compliance challenges are you facing with AI systems?
Drop a comment below! I'd love to hear about:
- Industries where you need auditable AI
- Specific compliance requirements
- Features that would make this more useful
- Questions about the architecture
Let's build the future of compliant AI together! 🚀
Top comments (0)