Autonomous Payments

Payments for AI Agents & Bots

Enable your AI agents and bots to pay for services automatically with zero-knowledge privacy.

Fully autonomous payments with no user interaction. Pre-fund, auto-spend, and settle in the background.

Why x402 for Agents?

Traditional payment systems require:

  • User interaction (OAuth, 2FA, confirmations)
  • Wallet signatures every time
  • Credit cards (KYC, billing addresses)
  • API keys that leak in logs

ShadowPay x402 enables:

  • Fully autonomous payments - No user interaction needed
  • Escrow authorization - Pre-fund, auto-spend
  • Zero-knowledge privacy - Agent activity is private
  • Instant authorization - 147ms response times
  • Background settlement - Non-blocking ZK proofs

Use Cases

Autonomous payments for autonomous agents

Chatbots & Virtual Assistants

Pay for premium API calls automatically

  • OpenAI/Claude API access
  • Paywalled knowledge bases
  • Real-time data feeds

Trading Bots

Subscribe to market data and execute trades

  • Real-time market data streams
  • Trade execution services
  • Premium analytics

Gaming NPCs

Autonomous in-game purchases

  • In-game item purchases
  • Premium asset access
  • Cross-game trading

Web Scrapers

Pay-per-scrape services

  • Premium proxy access
  • Anti-bot bypass
  • Data extraction APIs

Enterprise Automation

Internal resource metering

  • Micro-service billing
  • Resource allocation
  • Cost tracking

AI Model Inference

Autonomous model API payments

  • Image generation
  • Text completion
  • Code generation

Quick Start (Agent Setup)

Get your agent paying autonomously in three steps

1

Create Agent Wallet & Fund Escrow

Generate a dedicated wallet for your agent and fund its escrow account. The escrow deposit endpoint returns an unsigned transaction that you must sign and submit to Solana.

setup-agent.sh
# Step 1: Generate agent wallet
solana-keygen new -o agent-wallet.json --no-bip39-passphrase

# Step 2: Get wallet address
AGENT_WALLET=$(solana-keygen pubkey agent-wallet.json)
echo "Agent wallet: $AGENT_WALLET"

# Step 3: Get unsigned escrow deposit transaction
curl -X POST https://shadow.radr.fun/shadowpay/api/escrow/deposit \
  -H "Content-Type: application/json" \
  -d "{
    \"wallet_address\": \"$AGENT_WALLET\",
    \"amount\": 100000000
  }" > escrow_tx.json

# Response contains unsigned transaction:
# {
#   "unsigned_tx_base64": "...",
#   "recent_blockhash": "..."
# }

# Step 4: Sign and send transaction (Python example)
python3 << 'EOF'
import json
import base64
from solders.keypair import Keypair
from solders.transaction import Transaction
from solana.rpc.api import Client

# Load agent wallet
with open('agent-wallet.json', 'r') as f:
    keypair_bytes = bytes(json.load(f))
agent_keypair = Keypair.from_bytes(keypair_bytes)

# Load unsigned transaction
with open('escrow_tx.json', 'r') as f:
    tx_data = json.load(f)

# Decode and sign transaction
tx_bytes = base64.b64decode(tx_data['unsigned_tx_base64'])
tx = Transaction.deserialize(tx_bytes)
tx.sign([agent_keypair])

# Send to Solana
client = Client('https://api.mainnet-beta.solana.com')
result = client.send_transaction(tx)
print(f"✅ Escrow funded! TX: {result.value}")
EOF

# Step 5: Verify escrow balance
curl https://shadow.radr.fun/shadowpay/api/escrow/balance/$AGENT_WALLET
bash
2

Implement Autonomous Payment

Build your agent to automatically authorize payments and fetch data without any human intervention. Note: The ShadowPayClient SDK abstracts ZK proof generation but requires Node.js/snarkjs subprocess (see Step 3).

autonomous_agent.py
import requests
import time
from shadowpay import ShadowPayClient

class AutonomousAgent:
    def __init__(self, wallet_address, escrow_balance):
        self.wallet = wallet_address
        self.shadowpay = ShadowPayClient(
            base_url='https://shadow.radr.fun'
        )
        self.escrow_balance = escrow_balance
    
    def fetch_premium_data(self, endpoint, merchant_wallet, 
                          merchant_api_key, amount):
        """
        Autonomously pay for and fetch data
        """
        try:
            # Step 1: Instant authorization (147ms)
            auth = self.shadowpay.authorize_payment(
                user_wallet=self.wallet,
                merchant_wallet=merchant_wallet,
                merchant_api_key=merchant_api_key,
                amount=amount
            )
            
            print(f"✅ Authorized: {auth['access_token'][:20]}...")
            
            # Step 2: Fetch data immediately
            response = requests.get(
                endpoint,
                headers={
                    'Authorization': f"Bearer {auth['access_token']}"
                }
            )
            
            if response.status_code == 200:
                data = response.json()
                
                # Step 3: Settle in background (non-blocking)
                self.shadowpay.settle_async(
                    commitment=auth['commitment'],
                    on_complete=lambda r: print(f"✅ Settled: {r['tx_hash']}")
                )
                
                return data
            else:
                print(f"❌ Failed to fetch: {response.status_code}")
                return None
                
        except Exception as e:
            print(f"❌ Payment error: {e}")
            return None
    
    def monitor_escrow_balance(self):
        """
        Check escrow balance and auto-refill
        """
        balance = self.shadowpay.get_escrow_balance(self.wallet)
        
        if balance < 1000000:  # Less than 0.001 SOL
            print("⚠️  Low escrow balance, refilling...")
            self.refill_escrow()
    
    def refill_escrow(self):
        """
        Automatically refill escrow when low
        """
        deposit = self.shadowpay.deposit_to_escrow(
            user_wallet=self.wallet,
            amount=50000000  # 0.05 SOL
        )
        print(f"✅ Escrow refilled: {deposit['tx_hash']}")
python
3

Setup ZK Proof Generation (Required)

Python doesn't natively support snarkjs ZK proof generation or ElGamal encryption. Agents must call Node.js subprocess or use a Rust binary for proof generation.

zkp_generator.py
import subprocess
import json
import os

class ZKProofGenerator:
    def __init__(self, circuit_dir='./circuits'):
        """
        Initialize ZK proof generator with circuit artifacts
        """
        self.circuit_dir = circuit_dir
        self.ensure_circuits_downloaded()
    
    def ensure_circuits_downloaded(self):
        """
        Download circuit artifacts if not present
        """
        if not os.path.exists(self.circuit_dir):
            os.makedirs(self.circuit_dir)
        
        circuits = [
            'shadowpay_final.zkey',
            'shadowpay_js/shadowpay.wasm',
            'shadowpay-elgamal_final.zkey',
            'shadowpay-elgamal_js/shadowpay-elgamal.wasm'
        ]
        
        for circuit in circuits:
            if not os.path.exists(f"{self.circuit_dir}/{circuit}"):
                print(f"⚠️  Circuit {circuit} not found. Downloading...")
                # Download from CDN
                url = f"https://shadow.radr.fun/shadowpay/circuit/{circuit}"
                subprocess.run(['curl', '-o', f"{self.circuit_dir}/{circuit}", url])
    
    def generate_proof(self, witness_input):
        """
        Generate ZK proof by calling Node.js snarkjs subprocess
        
        NOTE: This requires Node.js and snarkjs installed:
        npm install -g snarkjs
        """
        # Write witness input to temp file
        with open('/tmp/witness_input.json', 'w') as f:
            json.dump(witness_input, f)
        
        # Call snarkjs via subprocess (blocks for ~2-5 seconds)
        proof_script = """
        const snarkjs = require('snarkjs');
        const fs = require('fs');
        
        async function generateProof() {
            const input = JSON.parse(fs.readFileSync('/tmp/witness_input.json'));
            
            const { proof, publicSignals } = await snarkjs.groth16.fullProve(
                input,
                './circuits/shadowpay_js/shadowpay.wasm',
                './circuits/shadowpay_final.zkey'
            );
            
            console.log(JSON.stringify({ proof, publicSignals }));
        }
        
        generateProof();
        """
        
        with open('/tmp/proof_gen.js', 'w') as f:
            f.write(proof_script)
        
        result = subprocess.run(
            ['node', '/tmp/proof_gen.js'],
            capture_output=True,
            text=True,
            timeout=10
        )
        
        if result.returncode == 0:
            return json.loads(result.stdout)
        else:
            raise Exception(f"Proof generation failed: {result.stderr}")

# Example usage in agent
zkp = ZKProofGenerator()

# Generate proof for payment
proof_data = zkp.generate_proof({
    'commitment': '12345678901234567890',
    'nullifier': '09876543210987654321',
    'amount': 1000000,
    'merkleRoot': '...',
    'merkleProofSiblings': [...]
})

print(f"✅ Proof generated: {proof_data['proof'][:50]}...")
python
4

Run Continuously

Deploy your agent to run continuously, automatically paying for services as needed while monitoring escrow balance.

run_agent.py
# Usage
agent = AutonomousAgent(
    wallet_address='AGENT_WALLET_ADDRESS',
    escrow_balance=100000000
)

# Agent autonomously pays for data every 5 minutes
while True:
    data = agent.fetch_premium_data(
        endpoint='https://api.example.com/market-data',
        merchant_wallet='MERCHANT_WALLET',
        merchant_api_key='MERCHANT_API_KEY',
        amount=10000  # 0.00001 SOL per request
    )
    
    if data:
        print(f"📊 Market data: {data}")
    
    agent.monitor_escrow_balance()
    time.sleep(300)
python

Flow Comparison

Traditional Payment Flow (Agent Blocked)

  1. 1.Agent needs data
  2. 2.Agent polls merchant: 'Is payment confirmed?'
  3. 3.Wait 5-10 seconds for blockchain confirmation
  4. 4.Poll again: 'Now?'
  5. 5.Finally confirmed
  6. 6.Fetch data

Total: ~10 seconds + polling overhead

ShadowPay x402 Flow (Agent Non-Blocking)

  1. 1.Agent needs data
  2. 2.Authorize payment (147ms)
  3. 3.Fetch data immediately (52ms)
  4. 4.Background ZK proof generation (agent doesn't wait)
  5. 5.Settlement completes on-chain

Total agent latency: ~200ms

50x faster. Zero polling.

Advanced: Multi-Agent Coordination

Manage a pool of agents with shared escrow and individual spending quotas.

agent_pool.py
class AgentPool:
    def __init__(self, pool_wallet, agent_wallets):
        self.pool = pool_wallet
        self.agents = agent_wallets
        self.shadowpay = ShadowPayClient()
    
    def delegate_payment(self, agent_id, endpoint, amount):
        """
        Agent requests permission to spend from pool
        """
        if self.check_agent_quota(agent_id, amount):
            # Authorize payment from pool escrow
            return self.shadowpay.authorize_payment(
                user_wallet=self.pool,
                merchant_wallet=endpoint['merchant'],
                merchant_api_key=endpoint['api_key'],
                amount=amount
            )
        else:
            raise QuotaExceeded(f"Agent {agent_id} exceeded spending limit")
    
    def check_agent_quota(self, agent_id, amount):
        """
        Check if agent is within spending limits
        """
        spent_today = self.get_agent_daily_spend(agent_id)
        daily_limit = 10000000  # 0.01 SOL per agent per day
        
        return spent_today + amount <= daily_limit
python

Privacy Benefits for Agents

Traditional Payments Leak:

  • 🔍Agent identity - Wallet address on every transaction
  • 🔍Spending patterns - When and how much agent spends
  • 🔍Service usage - What APIs the agent calls
  • 🔍Relationships - Which merchants the agent works with

ShadowPay Hides:

  • Agent identity - ZK proofs don't reveal sender
  • Payment amounts - ElGamal encryption
  • Timing analysis - Relayer batches settlements
  • Service graphs - No on-chain link between agent and merchant

Your agent's behavior stays private.

Cost Optimization for High-Volume Agents

Batch Payments

Instead of paying per-request, batch multiple requests:

# Pay once for 1000 API calls
auth = shadowpay.authorize_payment(
    amount=1000000,  # 0.001 SOL
    metadata={'requests': 1000}
)

# Use token for next 1000 calls
for i in range(1000):
    response = requests.get(
        endpoint, 
        headers={'Authorization': f'Bearer {auth["access_token"]}'}
    )
    # Process response...
python

Subscription Model

Pay monthly for unlimited access:

# Pay 1 SOL for 30 days unlimited
subscription = shadowpay.authorize_payment(
    amount=1000000000,
    metadata={
        'type': 'subscription',
        'duration_days': 30
    }
)
python

Monitoring & Alerts

Set up alerts for agent spending anomalies and unusual patterns.

agent_monitor.py
import logging

class AgentMonitor:
    def __init__(self, agent_wallet):
        self.wallet = agent_wallet
        self.logger = logging.getLogger('agent_monitor')
    
    def check_spending_anomalies(self):
        """
        Detect unusual spending patterns
        """
        recent_payments = shadowpay.get_payment_history(
            wallet=self.wallet,
            last_hours=1
        )
        
        total = sum(p['amount'] for p in recent_payments)
        
        if total > 50000000:  # More than 0.05 SOL per hour
            self.logger.warning(f"⚠️  High spending detected: {total} lamports")
            self.alert_operator()
    
    def alert_operator(self):
        """
        Send alert to human operator
        """
        # Send email, Slack notification, etc.
        pass
python

Security Considerations

✅ Best Practices:

  • Limit escrow balance - Only fund what agent needs
  • Set spending caps - Max amount per transaction
  • Whitelist merchants - Restrict who agent can pay
  • Monitor spending - Alert on anomalies
  • Rotate keys - Periodically update agent wallet
  • Isolate agents - Separate escrows for different agents

❌ Common Mistakes:

  • Storing private keys in code
  • Over-funding escrow accounts
  • No spending limits or monitoring
  • Logging payment commitments (privacy leak!)
  • Reusing nullifiers across agents

Example: OpenAI API Payment Agent

Autonomous GPT-4 access with ShadowPay - no user interaction required.

gpt_agent.py
import openai
from shadowpay import ShadowPayClient

class GPTPaymentAgent:
    def __init__(self, agent_wallet, openai_merchant):
        self.wallet = agent_wallet
        self.merchant = openai_merchant
        self.shadowpay = ShadowPayClient()
    
    def query_gpt4(self, prompt, cost_per_query=100000):
        """
        Pay for and query GPT-4 via paywalled API
        """
        # Authorize payment (147ms)
        auth = self.shadowpay.authorize_payment(
            user_wallet=self.wallet,
            merchant_wallet=self.merchant['wallet'],
            merchant_api_key=self.merchant['api_key'],
            amount=cost_per_query
        )
        
        # Query GPT-4 immediately
        response = openai.ChatCompletion.create(
            model="gpt-4",
            messages=[{"role": "user", "content": prompt}],
            headers={'Authorization': f"Bearer {auth['access_token']}"}
        )
        
        # Background settlement
        self.shadowpay.settle_async(auth['commitment'])
        
        return response['choices'][0]['message']['content']

# Usage
agent = GPTPaymentAgent(
    agent_wallet='AGENT_WALLET',
    openai_merchant={
        'wallet': 'OPENAI_MERCHANT_WALLET',
        'api_key': 'OPENAI_MERCHANT_API_KEY'
    }
)

answer = agent.query_gpt4("What is the capital of France?")
print(answer)
python

Circuit Artifacts (ZK Proof Setup)

Agents need to download ZK circuit files for autonomous proof generation. Cache these files for faster subsequent payments.

Main Circuit (Payment Proof)

GET
/shadowpay/circuit/shadowpay_final.zkey

Download proving key (main circuit)~50 MB

GET
/shadowpay/circuit/shadowpay_js/shadowpay.wasm

Download WASM (main circuit)~2 MB

ElGamal Circuit (Amount Encryption)

GET
/shadowpay/circuit-elgamal/shadowpay-elgamal_final.zkey

Download ElGamal proving key~45 MB

GET
/shadowpay/circuit-elgamal/shadowpay-elgamal_js/shadowpay-elgamal.wasm

Download ElGamal WASM~1.8 MB

Python Agent Setup

download_circuits.py
import requests
import os

# Download and cache circuit files
CIRCUIT_DIR = './circuits'
os.makedirs(CIRCUIT_DIR, exist_ok=True)

def download_circuits():
    """Download ZK circuit artifacts (one-time setup)"""
    circuits = {
        'shadowpay_final.zkey': 'https://shadow.radr.fun/shadowpay/circuit/shadowpay_final.zkey',
        'shadowpay.wasm': 'https://shadow.radr.fun/shadowpay/circuit/shadowpay_js/shadowpay.wasm',
        'shadowpay-elgamal_final.zkey': 'https://shadow.radr.fun/shadowpay/circuit-elgamal/shadowpay-elgamal_final.zkey',
        'shadowpay-elgamal.wasm': 'https://shadow.radr.fun/shadowpay/circuit-elgamal/shadowpay-elgamal_js/shadowpay-elgamal.wasm'
    }
    
    for filename, url in circuits.items():
        filepath = os.path.join(CIRCUIT_DIR, filename)
        
        if os.path.exists(filepath):
            print(f"✅ {filename} already cached")
            continue
        
        print(f"📥 Downloading {filename}...")
        response = requests.get(url, stream=True)
        
        with open(filepath, 'wb') as f:
            for chunk in response.iter_content(chunk_size=8192):
                f.write(chunk)
        
        print(f"✅ Downloaded {filename}")

# Run once on agent startup
download_circuits()

# Use with snarkjs (via subprocess or Python bindings)
class AgentPaymentProver:
    def __init__(self):
        self.circuit_wasm = os.path.join(CIRCUIT_DIR, 'shadowpay-elgamal.wasm')
        self.proving_key = os.path.join(CIRCUIT_DIR, 'shadowpay-elgamal_final.zkey')
    
    def generate_proof(self, witness_input):
        # Generate proof using cached circuits
        # Implementation depends on your ZK library
        pass
python

💡 Cache these files on agent startup. Download once, use for all subsequent payments.

Rate Limits & Quotas

Default Limits:

  • 50 RPS - 50 authorizations per second
  • 10,000 commits/day - 10k payments per day

Enterprise Limits:

  • 500 RPS
  • 100,000 commits/day
  • Dedicated infrastructure

For high-volume agents, contact us for enterprise limits

Traditional vs ShadowPay for Agents

FeatureTraditional x402ShadowPay x402
User InteractionRequiredNone
Authorization Speed5-10 seconds147ms
Polling Required
PrivacyPublic activityZero-knowledge
Escrow Pre-funding
Auto-refill

Frequently Asked Questions

Common questions about autonomous agent payments

Stay off the RADR.

Join the next generation of private payment infrastructure.

99.9%
Uptime
<200ms
Auth Speed
0
Fraud Cases