SDK & API

Built for Developers

Integrate ShadowPay in minutes with our SDKs, comprehensive API, and sandbox environment.

Production-ready SDKs for TypeScript, Python, and Rust. Extensive documentation, example apps, and testing tools.

SDKs & Tools

Everything you need to integrate ShadowPay into your stack

TypeScript/JavaScript

Full-featured SDK for Node.js and browser

  • npm install @shadowpay/sdk
  • React/Next.js components
  • Express middleware

Python

Clean, Pythonic API for backends and agents

  • pip install shadowpay
  • Django/Flask integration
  • Async support

Rust

High-performance SDK for Solana programs

  • cargo add shadowpay
  • On-chain integration
  • Zero-copy parsing

Sandbox Environment

Test without spending real SOL

  • Devnet support
  • Mock data generators
  • Test wallets included

API Reference

Complete REST API documentation

  • OpenAPI spec
  • Postman collection
  • Interactive examples

Example Apps

Production-ready starter templates

  • Paywalled blog
  • Premium API gateway
  • Trading bot skeleton

Quick Start

Get up and running in minutes with our production-ready SDKs

1

Install SDK

Choose your language and install the ShadowPay SDK. All SDKs provide the same core functionality with idiomatic APIs.

install.sh
# TypeScript/JavaScript
npm install @shadowpay/sdk

# Python
pip install shadowpay

# Rust
cargo add shadowpay
bash
2

Initialize Client

Create a ShadowPay client instance with your configuration. For merchants, you'll need your API key. For users, just a wallet address.

client.ts
// TypeScript
import { ShadowPayClient } from '@shadowpay/sdk';

const client = new ShadowPayClient({
  baseUrl: 'https://shadow.radr.fun',
  network: 'mainnet', // or 'devnet' for testing
});

await client.init();
typescript
3

Make Your First Payment

Authorize a payment as a user. The SDK handles ZK proof generation, escrow management, and background settlement automatically.

payment.ts
// User pays for premium content
const payment = await client.pay({
  userWallet: 'USER_WALLET_ADDRESS',
  merchantWallet: 'MERCHANT_WALLET_ADDRESS',
  merchantApiKey: 'MERCHANT_API_KEY',
  amount: 1000000, // 0.001 SOL in lamports
  
  // Optional: callback when settlement completes
  onProofComplete: (result) => {
    console.log('✅ Payment settled on-chain:', result.txHash);
  }
});

// Use access token to fetch premium content
const response = await fetch('/api/premium-data', {
  headers: { 
    'Authorization': `Bearer ${payment.accessToken}` 
  }
});
typescript

Merchant Integration

Protect your endpoints with ShadowPay verification

middleware.ts
// Express middleware
import { verifyShadowPayToken } from '@shadowpay/sdk';

app.use('/api/premium/*', async (req, res, next) => {
  const token = req.headers.authorization?.replace('Bearer ', '');
  
  if (!token) {
    return res.status(402).json({
      x402Version: 1,
      accepts: [{
        scheme: 'zkproof',
        network: 'solana-mainnet',
        maxAmountRequired: '1000000',
        resource: req.path,
        payTo: process.env.MERCHANT_WALLET
      }]
    });
  }
  
  try {
    const payment = await verifyShadowPayToken(token, {
      apiKey: process.env.SHADOWPAY_API_KEY
    });
    
    if (payment.valid) {
      req.payment = payment;
      next();
    } else {
      res.status(402).json({ error: 'Invalid payment' });
    }
  } catch (error) {
    res.status(500).json({ error: 'Verification failed' });
  }
});
typescript

Python SDK Example

Perfect for data APIs and AI agent backends

app.py
from shadowpay import ShadowPayClient

# Initialize client
client = ShadowPayClient(
    base_url='https://shadow.radr.fun',
    network='mainnet'
)

# Verify payment (merchant side)
@app.route('/api/premium-data')
def premium_data():
    token = request.headers.get('Authorization', '').replace('Bearer ', '')
    
    if not token:
        return jsonify({
            'x402Version': 1,
            'accepts': [{
                'scheme': 'zkproof',
                'network': 'solana-mainnet',
                'maxAmountRequired': '1000000',
                'resource': '/api/premium-data',
                'payTo': os.environ['MERCHANT_WALLET']
            }]
        }), 402
    
    payment = client.verify_token(
        token=token,
        api_key=os.environ['SHADOWPAY_API_KEY']
    )
    
    if payment['valid']:
        return jsonify({'data': 'Premium content here!'})
    else:
        return jsonify({'error': 'Invalid payment'}), 402
python

Rust SDK Example

High-performance on-chain integration

main.rs
use shadowpay::{ShadowPayClient, PaymentRequest};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Initialize client
    let client = ShadowPayClient::new(
        "https://shadow.radr.fun",
        Network::Mainnet
    ).await?;
    
    // Create payment request
    let payment = PaymentRequest::new()
        .user_wallet("USER_WALLET_ADDRESS")
        .merchant_wallet("MERCHANT_WALLET_ADDRESS")
        .amount(1_000_000) // 0.001 SOL
        .build()?;
    
    // Authorize and pay
    let result = client.pay(payment).await?;
    
    println!("✅ Payment authorized: {}", result.access_token);
    println!("⏳ Settlement in progress...");
    
    // Wait for settlement (optional)
    let settlement = result.wait_for_settlement().await?;
    println!("✅ Settled: {}", settlement.tx_hash);
    
    Ok(())
}
rust

API Reference

Complete REST API with OpenAPI spec and Postman collection

API Keys

POST
/shadowpay/v1/keys/new

Generate merchant API key

GET
/shadowpay/v1/keys/by-wallet/{wallet}

Get API key by wallet

POST
/shadowpay/v1/keys/rotate

Rotate API key (requires X-API-Key)

Pool Management

GET
/shadowpay/api/pool/balance/{wallet}

Check pool balance

POST
/shadowpay/api/pool/deposit

Deposit to pool

POST
/shadowpay/api/pool/withdraw

Withdraw SOL from pool

ShadowID (Anonymous Identity)

POST
/shadowpay/api/shadowid/register

Register commitment

POST
/shadowpay/api/shadowid/proof

Get Merkle proof

GET
/shadowpay/api/shadowid/root

Get Merkle root

ZK Payments

POST
/shadowpay/v1/payment/prepare

Prepare ZK payment (requires X-API-Key)

POST
/shadowpay/verify

Verify ZK proof (instant)

POST
/shadowpay/settle

Settle payment on-chain

GET
/shadowpay/premium

x402 demo resource

Payment Intents (Traditional Flow)

POST
/shadowpay/v1/pay/intent

Create payment intent (requires X-API-Key)

POST
/shadowpay/v1/pay/verify

Verify payment (requires X-API-Key)

GET
/shadowpay/v1/pay/pubkey

Get merchant public key (requires X-API-Key)

Automated Payments (Spending Authorizations)

POST
/shadowpay/api/authorize-spending

Register spending authorization

POST
/shadowpay/api/revoke-authorization

Revoke authorization

GET
/shadowpay/api/my-authorizations/{wallet}

List authorizations

Circuit Artifacts (ZK Proof Generation)

GET
/shadowpay/circuit/shadowpay_final.zkey

Download proving key (main circuit)

GET
/shadowpay/circuit/shadowpay_js/shadowpay.wasm

Download WASM (main circuit)

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

Download ElGamal proving key

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

Download ElGamal WASM

Marketplace (Service Registry)

GET
/shadowpay/api/marketplace/discover

Discover services (query params: capability, max_price_sol)

POST
/shadowpay/api/marketplace/register

Register service

POST
/shadowpay/api/marketplace/call

Agent calls service

Agent Registry

GET
/shadowpay/api/agents/discover

Discover agents (query params: capability, pricing_model)

POST
/shadowpay/api/agents/register

Register agent

POST
/shadowpay/api/agents/hire

Hire agent

GET
/shadowpay/api/agents/{agent_id}/tasks

Get agent tasks

Merchant Analytics

GET
/shadowpay/v1/merchant/revenue

Get revenue stats (requires X-API-Key)

Testing & Sandbox

Test your integration safely before going to production

1. Use Devnet

Test without spending real SOL

const client = new ShadowPayClient({
  network: 'devnet' // Use Solana devnet
});
typescript

2. Get Test Wallets

Generate funded test wallets

// Generate test wallet
const testWallet = await client.createTestWallet();

// Request devnet SOL airdrop
await client.airdrop(testWallet.address, 1_000_000_000); // 1 SOL
typescript

3. Mock Proofs (Development Only)

Skip ZK proof generation for faster testing

const client = new ShadowPayClient({
  network: 'devnet',
  mockProofs: true // Skip proof generation
});
typescript

Webhook Configuration

Get real-time notifications when payments settle

webhooks.ts
// Configure webhook
await client.merchant.setWebhook({
  url: 'https://your-app.com/webhooks/shadowpay',
  events: ['payment.settled', 'payment.failed'],
  secret: 'your-webhook-secret'
});

// Handle webhook in your app
app.post('/webhooks/shadowpay', (req, res) => {
  // Verify signature
  const signature = req.headers['x-shadowpay-signature'];
  const isValid = client.verifyWebhookSignature(
    req.body,
    signature,
    'your-webhook-secret'
  );
  
  if (!isValid) {
    return res.status(401).send('Invalid signature');
  }
  
  const { event, data } = req.body;
  
  switch (event) {
    case 'payment.settled':
      console.log(`✅ Payment settled: ${data.amount} lamports`);
      console.log(`TX: ${data.txHash}`);
      // Update database, grant access, etc.
      break;
      
    case 'payment.failed':
      console.log(`❌ Payment failed: ${data.reason}`);
      // Handle failure, notify user, etc.
      break;
  }
  
  res.sendStatus(200);
});
typescript

Error Handling

Gracefully handle payment failures

error-handling.ts
try {
  const payment = await client.pay({
    userWallet: 'USER_WALLET',
    merchantWallet: 'MERCHANT_WALLET',
    amount: 1_000_000
  });
} catch (error) {
  if (error.code === 'INSUFFICIENT_ESCROW') {
    console.error('❌ User needs to deposit more SOL to escrow');
    // Prompt user to fund escrow
  } else if (error.code === 'PROOF_GENERATION_FAILED') {
    console.error('❌ ZK proof generation failed, retrying...');
    // Retry payment
  } else if (error.code === 'MERCHANT_NOT_FOUND') {
    console.error('❌ Invalid merchant wallet or API key');
    // Check configuration
  } else {
    console.error('❌ Payment failed:', error.message);
    // Generic error handling
  }
}
typescript

Example Applications

Production-ready starter templates to kickstart your integration

Paywalled Blog

Next.js blog with premium articles

Next.js, Prisma, ShadowPay

Premium API Gateway

Express API with per-request payments

Express, Redis, ShadowPay

Trading Bot

Autonomous trading bot with ShadowPay

Python, FastAPI, ShadowPay

NFT Marketplace

Decentralized marketplace with private bids

React, Anchor, ShadowPay

Integration Patterns

Common payment models and how to implement them

Per-Request Payments

Charge for each API call

Use case: High-value endpoints, AI inference, data queries

app.get('/api/analyze', verifyShadowPay, (req, res) => {
  const result = runExpensiveAnalysis();
  res.json(result);
});
typescript

Subscription Model

Monthly or time-based access

Use case: SaaS apps, premium content, recurring services

const subscription = await client.pay({
  amount: 100_000_000, // 0.1 SOL
  metadata: { 
    type: 'subscription',
    duration: 30 * 24 * 60 * 60 // 30 days
  }
});
typescript

Metered Billing

Pay per resource unit consumed

Use case: Cloud services, bandwidth, compute time

// Track usage
const usage = trackUserUsage(userId);

// Charge at end of period
await client.pay({
  amount: usage.units * PRICE_PER_UNIT,
  metadata: { usage }
});
typescript

Batch Payments

Single payment for multiple operations

Use case: Bulk data downloads, batch processing

const batch = await client.pay({
  amount: 10_000_000, // 0.01 SOL
  metadata: { 
    type: 'batch',
    operations: 100 
  }
});
typescript

Developer FAQ

Common questions about integrating ShadowPay

Stay off the RADR.

Join the next generation of private payment infrastructure.

99.9%
Uptime
<200ms
Auth Speed
0
Fraud Cases