DEV Community

Senay Yakut
Senay Yakut

Posted on

Agent-402

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)β”‚
        β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
Enter fullscreen mode Exit fullscreen mode

Core Components

  1. x402 Protocol - Cryptographically signed requests
  2. Circle Arc Network - Blockchain settlement layer
  3. Circle Wallets - Programmable agent treasuries
  4. CrewAI - Multi-agent orchestration
  5. 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
Enter fullscreen mode Exit fullscreen mode

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")
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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"
)
Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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

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! πŸš€


Tags

ai #fintech #blockchain #compliance #python #opensource #agents #cryptocurrency #machinelearning #automation

Top comments (0)