cirtusai-sdk 0.2.2
A Python SDK for the CirtusAI backend: agent, wallet, credential management, and advanced compliance features.
Requires Python: >=3.8

# CirtusAI Python SDK - Complete Developer Guide (Updated July 2025)

v0.2.2 (beta)

## CirtusAI — Autonomy Verified

_The Trust Layer for the Agent Economy_

The most comprehensive SDK for autonomous AI agent management with blockchain-level security

The CirtusAI Python SDK provides everything developers need to build powerful, secure, and compliant AI agent applications. From basic wallet management to advanced smart contract automation, from governance participation to real-world asset tokenization - this SDK unlocks the complete power of the CirtusAI platform.

## What Makes CirtusAI Unique

- **Enterprise-Grade 2FA Security**: Mandatory TOTP authentication with time-sync tolerance
- **Smart Contract Agent Wallets**: On-chain spending limits, whitelists, and automated rule enforcement  
- **Multi-Chain Support**: Ethereum, Polygon, Arbitrum, and more
- **Email Integration**: IMAP/SMTP and OAuth for seamless communication
- **DAO Governance**: Participate in on-chain voting and proposal management
- **DeFi Integration**: Swaps, yield farming, cross-chain bridges, and gas abstraction
- **Real-World Assets (RWA)**: Tokenize and manage physical assets on-chain
- **Advanced Compliance (NEW v0.3.0)**: KYC/AML verification, document processing, audit trails, webhook management
- **Asynchronous Processing**: Celery-based background task processing for enterprise scalability
- **Tamper-Evident Audit Logging**: Hash chain-secured audit trails with cryptographic integrity
- **Rate Limiting & Permissions**: Advanced API protection with user-based rate limiting
- **Production Ready**: Sync/async support, comprehensive error handling, and extensive testing

---

## Installation

Install the latest stable SDK:

```bash
pip install cirtusai-sdk
```

Install the beta/pre-release version:

```bash
pip install --pre cirtusai-sdk
```

---

## Command Line Interface

The SDK includes a powerful CLI for common tasks. After installing:

```bash
pip install cirtusai-sdk
```

Use the `cirtusai` command:

```bash
cirtusai --help
```

Available commands:

```bash
cirtusai auth           Authentication (login, register, refresh, verify-2fa)
cirtusai agents         Agent management (list, get, create-child, delete, children, provision-email, provision-wallet, update-permissions, unlink)
cirtusai wallets        Wallet & email account management (list-assets, list-email, create-email, get-email, update-email, delete-email, refresh-email-token, add-crypto)
cirtusai identity       DID & credential management (get-did, issue-credential, verify-credential)
cirtusai governance     Governance (create-proposal, cast-vote, get-proposal-state)
cirtusai reputation     Soulbound token commands (issue-sbt, get-sbt-owner)
cirtusai bridge         Cross-chain bridge (get-quote, transfer)
cirtusai assets         Asset view (view, refresh)
cirtusai marketplace    Marketplace (create-listing, list-listings, get-listing, update-listing, cancel-listing, place-bid, list-bids, accept-bid)
cirtusai swap           Token swap (get-quote, execute, cancel)
cirtusai nfts           NFT management (list, get-metadata, mint, batch-transfer, burn)
cirtusai child-assets   Child asset management (list, get, create, update, delete)
cirtusai child-services Child service management (list)
cirtusai compliance     🆕 Compliance & monitoring (kyc-check, process-document, audit-trail, webhook-status, retry-webhook, rate-limit-status)
cirtusai compliance advanced  🆕 Enterprise compliance features (bulk-process, compliance-dashboard, risk-assessment)
```
```bash

---

## Quick Start Guide

### 1. Authentication with 2FA (Required)

Every CirtusAI application starts with secure authentication. First, import the client and error classes, then initialize the client with your backend URL:

```python
from cirtusai import CirtusAIClient
from cirtusai.auth import TwoFactorAuthenticationError

client = CirtusAIClient(base_url="http://localhost:8000")
```

Register a new user (automatic 2FA setup):

```python
setup_info = client.auth.register(
    username="mycompany_agent",
    email="admin@mycompany.com",
    password="SuperSecure123!",
    preferred_2fa_method="totp"
)
```

Save the QR code, secret, and backup codes provided for your authenticator app:

```python
print(f"Scan QR: data:image/png;base64,{setup_info.qr_code_image}")
print(f"Secret: {setup_info.secret}")
print(f"Backup codes: {setup_info.backup_codes}")
```

Login with 2FA using a current TOTP code:

```python
try:
    token = client.auth.login_with_2fa(
        "mycompany_agent",
        "SuperSecure123!",
        "123456"
    )
    client.set_token(token.access_token)
    print("Authenticated successfully!")
except TwoFactorAuthenticationError as e:
    print(f"2FA failed: {e}")
```

### 2. Create Your First Wallet

Create a new HD wallet
```python
wallet = client.wallets.create_wallet(chain="ethereum")
print(f"New wallet: {wallet['wallet_address']}")

```
Import an existing wallet
```python
imported = client.wallets.import_wallet(
    chain="ethereum",
    private_key="0x1234567890abcdef..."  # Your private key
)
print(f"Imported wallet: {imported['wallet_address']}")

```
List all your wallets
```python
wallets = client.wallets.list_wallets()
for w in wallets:
    print(f"  {w['name']}: {w['wallet_address']} ({w['chain']})")
```

### 3. Deploy Your First Agent Wallet

Agent wallets are smart contracts with programmable rules:

Deploy a smart contract agent wallet
```python
agent_wallet = client.wallets.deploy_agent_wallet()
print(f"Agent wallet deployed: {agent_wallet['wallet_address']}")

```
Set spending limits (daily ETH limit)
```python
tx_hash = client.wallets.set_spending_limit(
    address=agent_wallet['wallet_address'],
    token="0x0",  # ETH
    amount=1000000000000000000,  # 1 ETH in wei
    period=86400  # 24 hours
)
print(f"Spending limit set: {tx_hash}")

```
Add trusted addresses to whitelist
```python
whitelist_tx = client.wallets.update_whitelist(
    address=agent_wallet['wallet_address'],
    target="0x742d35Cc6634C0532925a3b8D0715a99C7DCF",
    allowed=True
)
print(f"Address whitelisted: {whitelist_tx}")
```

### 4. Manage Child Agents

List master agents
```python
agents = client.agents.list_agents()
print(f"Master agents: {agents}")

```
Create a child agent under a master agent
```python
child = client.agents.create_child_agent("my_master_id", "assistant_bot")
print(f"Created child agent: {child['id']}")

```
List all child agents
```python
children = client.agents.get_children()
print(f"Child agents: {children}")
```

---

## Complete Feature Guide

## 1.  Advanced Authentication & Security

### 1.1 Complete 2FA Management

Check current 2FA status
```python
status = client.auth.get_2fa_status()
print(f"2FA enabled: {status.is_2fa_enabled}")

```
Setup 2FA for existing users
```python
setup = client.auth.setup_2fa()
print(f"New secret: {setup.secret}")

```
Get QR code as image bytes
```python
qr_bytes = client.auth.get_qr_code()
with open("qr_code.png", "wb") as f:
    f.write(qr_bytes)

```
Debug time synchronization issues
```python
debug_info = client.auth.debug_2fa()
print("Valid codes right now:")
for step, code in debug_info["valid_codes"].items():
    print(f"  {step}: {code}")

```
Disable 2FA (requires password + TOTP)
```python
result = client.auth.disable_2fa(
    totp_code="123456",
    password="SuperSecure123!"
)
print(f"2FA disabled: {result['enabled']}")
```

### 1.2 Session Management

Get current user information  
```python
user_info = client.auth.get_user_info()
print(f"User: {user_info['username']} ({user_info['email']})")

```
Refresh expired tokens
```python
new_token = client.auth.refresh(refresh_token="your_refresh_token")
client.set_token(new_token.access_token)

```
Logout and clear session
```python
client.auth.logout()
```

---

## 2.  Comprehensive Wallet Management

### 2.1 Multi-Chain Wallet Operations

Create wallets on different chains
```python
eth_wallet = client.wallets.create_wallet(chain="ethereum")
poly_wallet = client.wallets.create_wallet(chain="polygon") 
arb_wallet = client.wallets.create_wallet(chain="arbitrum")

```
Get wallet balances
```python
balance = client.wallets.get_balance(
    chain="ethereum",
    address=eth_wallet['wallet_address']
)
print(f"ETH Balance: {balance}")

```
Get consolidated asset view across all chains
```python
assets = client.assets.get_multi_chain_asset_view()
print(f"Total portfolio value: ${assets['total_value_usd']}")
for chain, data in assets['chains'].items():
    print(f"  {chain}: {data['native_balance']} native + {len(data['tokens'])} tokens")
```

### 2.2 ERC-20 Token Management

Get token balance
```python
usdc_balance = client.wallets.get_token_balance(
    wallet_id=eth_wallet['id'],
    token_address="0xA0b86a33E6D1cc22c435370bA9e4240EE8D5fE5"  # USDC
)
print(f"USDC: {usdc_balance['balance']} {usdc_balance['symbol']}")

```
Transfer tokens
```python
transfer_tx = client.wallets.transfer_tokens(
    wallet_id=eth_wallet['id'],
    token_address="0xA0b86a33E6D1cc22c435370bA9e4240EE8D5fE5",
    to_address="0x742d35Cc6634C0532925a3b8D0715a99C7DCF",
    amount=100.0
)
print(f"Transfer completed: {transfer_tx['tx_hash']}")

```
Approve token spending
```python
approve_tx = client.wallets.approve_tokens(
    wallet_id=eth_wallet['id'], 
    token_address="0xA0b86a33E6D1cc22c435370bA9e4240EE8D5fE5",
    spender_address="0x1234567890abcdef...",
    amount=500.0
)
print(f"Approval set: {approve_tx['tx_hash']}")
```

---

## 3.  Agent Wallet Smart Contracts

### 3.1 Agent Wallet Deployment & Management

Deploy multiple agent wallets for different purposes
```python
marketing_agent = client.wallets.deploy_agent_wallet()
finance_agent = client.wallets.deploy_agent_wallet()
ops_agent = client.wallets.deploy_agent_wallet()

```
List all agent wallets
```python
agent_wallets = client.wallets.list_agent_wallets()
for wallet in agent_wallets:
    print(f"Agent: {wallet['wallet_address']} (deployed: {wallet['created_at']})")

```
Get detailed wallet information
```python
wallet_details = client.wallets.get_agent_wallet(
    address=marketing_agent['wallet_address']
)
print(f"Wallet details: {wallet_details}")
```

### 3.2 On-Chain Rule Management

Set daily spending limits for different tokens
```python
agent_addr = marketing_agent['wallet_address']

```
ETH spending limit: 0.5 ETH per day
```python
eth_limit = client.wallets.set_spending_limit(
    address=agent_addr,
    token="0x0",  # ETH
    amount=500000000000000000,  # 0.5 ETH in wei
    period=86400  # 24 hours
)

```
USDC spending limit: $1000 per day  
```python
usdc_limit = client.wallets.set_spending_limit(
    address=agent_addr,
    token="0xA0b86a33E6D1cc22c435370bA9e4240EE8D5fE5",  # USDC
    amount=1000000000,  # $1000 (6 decimals)
    period=86400
)

```
Build a whitelist of approved addresses
```python
approved_vendors = [
    "0x742d35Cc6634C0532925a3b8D0715a99C7DCF",  # OpenAI API payments
    "0x8b3a92Ef6F66F79A7B7C4D8f9E2A1B5C3D7E9F",   # AWS payments  
    "0x1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a"    # Partner agent
]

for vendor in approved_vendors:
    whitelist_tx = client.wallets.update_whitelist(
        address=agent_addr,
        target=vendor,
        allowed=True
    )
    print(f" Whitelisted {vendor}: {whitelist_tx}")

```
Set transaction threshold requiring manual approval
```python
threshold_tx = client.wallets.set_threshold(
    address=agent_addr,
    new_threshold=500  # Require approval for transactions > $500
)
print(f"Threshold set: {threshold_tx}")
```

### 3.3 Audit Trail & Event Monitoring

Get complete transaction history for an agent wallet
```python
transactions = client.wallets.list_wallet_transactions(
    address=agent_addr
)

print(f"Found {len(transactions)} events:")
for tx in transactions:
    print(f"  {tx['timestamp']}: {tx['event_name']}")
    print(f"    TX: {tx['tx_hash']}")
    print(f"    Details: {tx['details']}")
    print(f"    Block: {tx['block_number']}")
    print()

```
Monitor for specific event types
```python
spending_events = [tx for tx in transactions if tx['event_name'] == 'SpendingLimitSet']
whitelist_events = [tx for tx in transactions if tx['event_name'] == 'WhitelistUpdated']

print(f"Spending limit changes: {len(spending_events)}")
print(f"Whitelist updates: {len(whitelist_events)}")
```

---

## 4.  Master/Child Agent Management

### 4.1 Agent Hierarchy Creation

Create a master agent for your organization
```python
master_agent = client.agents.create_agent(
    name="Marketing Master Agent",
    description="Handles all marketing automation",
    agent_type="master",
    capabilities=["content_creation", "social_media", "email_marketing"]
)
print(f"Master agent created: {master_agent['id']}")

```
Create specialized child agents
```python
social_media_agent = client.agents.create_agent(
    name="Social Media Specialist",
    description="Automated social media posting and engagement",
    agent_type="child",
    parent_id=master_agent['id'],
    capabilities=["social_media", "content_scheduling"]
)

email_agent = client.agents.create_agent(
    name="Email Campaign Manager", 
    description="Automated email marketing campaigns",
    agent_type="child",
    parent_id=master_agent['id'],
    capabilities=["email_marketing", "newsletter_automation"]
)

print(f"Child agents created:")
print(f"  Social Media: {social_media_agent['id']}")
print(f"  Email: {email_agent['id']}")
```

### 4.2 Agent Rule Inheritance

Child agents inherit rules from their master
```python
inherited_rules = client.agents.get_inherited_rules(
    child_id=social_media_agent['id']
)

print(f"Inherited rules from master:")
print(f"  Spending limits: {inherited_rules['spending_limits']}")
print(f"  Whitelists: {inherited_rules['whitelists']}")
print(f"  Policies: {inherited_rules['policies']}")
```

### 4.3 Task Delegation

Delegate specific tasks to child agents
```python
social_campaign = client.agents.delegate_task(
    master_id=master_agent['id'],
    child_agent_id=social_media_agent['id'],
    task_type="social_media_campaign",
    budget_allocation={
        "token": "0x0",  # ETH
        "amount": "50000000000000000"  # 0.05 ETH
    },
    deadline="2025-07-24T1200Z",
    parameters={
        "platform": "twitter",
        "campaign_theme": "product_launch",
        "post_frequency": "3_per_day"
    }
)
print(f"Task delegated: {social_campaign['id']}")

```
Monitor delegation status
```python
delegations = client.agents.list_delegations(master_agent['id'])
for delegation in delegations:
    print(f"Task: {delegation['task_type']} → {delegation['status']}")
```

---

## 5.  Email Integration & Communication

### 5.1 Email Account Linking

Link IMAP/SMTP email account
```python
email_account = client.wallets.create_email_account(
    provider="imap",
    email_address="marketing@mycompany.com",
    config={
        "host": "imap.gmail.com",
        "port": 993,
        "username": "marketing@mycompany.com", 
        "password": "app_password_here",  # Use app password for Gmail
        "use_ssl": True,
        "smtp_host": "smtp.gmail.com",
        "smtp_port": 587
    }
)
print(f"Email account linked: {email_account['id']}")

```
OAuth integration for Google/Outlook (redirect-based)
```python
google_oauth_url = client.wallets.get_google_oauth_url()
print(f"Google OAuth: {google_oauth_url}")

```
List all linked email accounts
```python
email_accounts = client.wallets.list_email_accounts()
for account in email_accounts:
    print(f"  {account['email_address']} ({account['provider']})")
```

### 5.2 Email Management & Access

Test email connection
```python
test_result = client.wallets.test_email_connection(email_account['id'])
print(f"Connection test: {test_result['status']}")

```
Access inbox (with proper permissions)
```python
inbox = client.wallets.get_inbox(
    account_id=email_account['id'],
    limit=10,
    unread_only=True
)
print(f"Unread emails: {inbox['unread_count']}")
for msg in inbox['messages']:
    print(f"  From: {msg['from']}")
    print(f"  Subject: {msg['subject']}")
    print(f"  Date: {msg['date']}")
```

---

## 6.  Cross-Chain Bridge & DeFi

### 6.1 Cross-Chain Transfers

Get bridge quote for cross-chain transfer
```python
quote = client.bridge.get_quote(
    from_chain="ethereum", 
    to_chain="polygon",
    from_token="0xA0b86a33E6D1cc22c435370bA9e4240EE8D5fE5",  # USDC
    to_token="0x2791bca1f2de4661ed88a30c99a7a9449aa84174",   # USDC on Polygon
    amount=1000000000  # $1000 USDC
)
print(f"Bridge quote:")
print(f"  Fee: ${quote['fee_usd']}")
print(f"  Time: {quote['estimated_time']}")
print(f"  You'll receive: {quote['to_amount']} USDC on Polygon")

```
Execute the bridge transfer
```python
if quote['fee_usd'] < 10:  # Acceptable fee
    bridge_tx = client.bridge.bridge_transfer(
        provider=quote['provider'],
        from_chain="ethereum",
        to_chain="polygon", 
        from_token="0xA0b86a33E6D1cc22c435370bA9e4240EE8D5fE5",
        to_token="0x2791bca1f2de4661ed88a30c99a7a9449aa84174",
        amount=1000000000,
        recipient_address=poly_wallet['wallet_address']
    )
    print(f"Bridge transfer initiated: {bridge_tx['tx_hash']}")
```

### 6.2 DeFi Integration

Swap tokens using integrated DEX
```python
swap_tx = client.wallets.swap_tokens(
    wallet_id=eth_wallet['id'],
    from_token="0x0",  # ETH
    to_token="0xA0b86a33E6D1cc22c435370bA9e4240EE8D5fE5",  # USDC
    amount=1.0,  # 1 ETH
    slippage_tolerance=0.5  # 0.5%
)
print(f"Swap completed: {swap_tx['tx_hash']}")

```
Deposit into yield farming vault
```python
yield_deposit = client.wallets.deposit_yield_vault(
    wallet_id=eth_wallet['id'],
    vault_address="0x1234567890abcdef...",  # Aave USDC vault
    token_address="0xA0b86a33E6D1cc22c435370bA9e4240EE8D5fE5",
    amount=500.0
)
print(f"Yield farming deposit: {yield_deposit['tx_hash']}")

```
Check yield farming positions
```python
positions = client.wallets.get_yield_positions(eth_wallet['id'])
for position in positions:
    print(f"Vault: {position['vault_name']}")
    print(f"  Deposited: {position['deposited_amount']}")
    print(f"  Current value: {position['current_value']}")
    print(f"  APY: {position['apy']}%")
```

### 6.3 On-Chain Swap Services

Get swap quote for token pair
```python
swap_quote = client.swap.get_quote(
    from_token="0x0",  # ETH
    to_token="0xA0b86a33E6D1cc22c435370bA9e4240EE8D5fE5",  # USDC
    amount=1.0
)
print(f"Swap quote: {swap_quote}")

```
Execute the swap
```python
swap_tx = client.swap.execute_swap(
    from_token="0x0",
    to_token="0xA0b86a33E6D1cc22c435370bA9e4240EE8D5fE5",
    amount=1.0,
    slippage_tolerance=0.5
)
print(f"Swap executed: {swap_tx['tx_hash']}")

```
Cancel a pending swap quote
```python
cancel = client.swap.cancel_swap(quote_id=swap_quote['quote_id'])
print(f"Swap quote cancelled: {cancel['status']}")
```

### 6.4 Marketplace Operations

List marketplace listings
```python
listings = client.marketplace.list_listings(limit=20)
for l in listings:
    print(f"Listing: {l['id']} - {l['asset_name']} at {l['price']}")

```
Create a new listing
```python
new_listing = client.marketplace.create_listing(
    asset_id="asset123",
    price="0.5 ETH",
    quantity=1
)
print(f"Created listing: {new_listing['id']}")

```
Place a bid on a listing
```python
bid = client.marketplace.place_bid(
    listing_id=new_listing['id'],
    bid_amount="0.45 ETH"
)
print(f"Bid placed: {bid['bid_id']}")

```
Cancel a listing
```python
client.marketplace.cancel_listing(listing_id=new_listing['id'])
print("Listing cancelled")
```

---

## 7. ️ Governance & DAO Participation

### 7.1 Proposal Management

Create a governance proposal
```python
proposal = client.governance.create_proposal(
    targets=["0x1234567890abcdef..."],  # Contract to call
    values=[0],  # ETH to send (0 for parameter change)
    calldatas=["0xabcdef..."],  # Encoded function call
    description="Increase agent spending limits to $2000/day"
)
print(f"Proposal created: {proposal['proposal_id']}")

```
Get proposal details
```python
proposal_info = client.governance.get_proposal_state(proposal['proposal_id'])
print(f"Proposal status: {proposal_info['status']}")
print(f"Votes for: {proposal_info['votes_for']}")
print(f"Votes against: {proposal_info['votes_against']}")
print(f"Voting deadline: {proposal_info['voting_deadline']}")
```

### 7.2 Voting

Cast vote on proposal (1 = for, 0 = against)
```python
vote = client.governance.cast_vote(
    proposal_id=proposal['proposal_id'],
    support=1  # Vote in favor
)
print(f"Vote cast: {vote['tx_hash']}")

```
Check your voting history
```python
voting_history = client.governance.get_user_votes()
for vote_record in voting_history:
    print(f"Proposal {vote_record['proposal_id']}: {'FOR' if vote_record['support'] else 'AGAINST'}")
```

---

## 8.  Real-World Assets (RWA)

### 8.1 Asset Tokenization

Register a real-world asset token
```python
rwa_asset = client.wallets.register_rwa_asset(
    token_address="0x9876543210fedcba...",  # RWA token contract
    token_id="1",  # Specific asset ID
    metadata_uri="https://metadata.example.com/asset/1"
)
print(f"RWA asset registered: {rwa_asset['id']}")

```
List your RWA holdings
```python
rwa_holdings = client.wallets.list_rwa_assets()
for asset in rwa_holdings:
    print(f"Asset: {asset['name']}")
    print(f"  Type: {asset['asset_type']}")
    print(f"  Value: ${asset['estimated_value']}")
    print(f"  Yield: {asset['annual_yield']}%")
```

### 8.2 Asset Management

Transfer RWA tokens
```python
rwa_transfer = client.wallets.transfer_rwa(
    wallet_id=eth_wallet['id'],
    token_address="0x9876543210fedcba...",
    token_id="1",
    to_address="0x742d35Cc6634C0532925a3b8D0715a99C7DCF",
    amount=1
)
print(f"RWA transfer: {rwa_transfer['tx_hash']}")
```

---

## 9.  Child Asset Provisioning

### 9.1 Email Asset Provisioning

Provision email access to child agents
```python
email_provision = client.agents.provision_email_asset(
    child_id=email_agent['id'],
    email_account_id=email_account['id'],
    permissions=["read", "send"],
    quota={
        "daily_emails": 100,
        "monthly_emails": 2000
    }
)
print(f"Email access provisioned: {email_provision['email_address']}")

```
Check email quota usage
```python
email_usage = client.agents.get_email_usage(email_agent['id'])
print(f"Email usage: {email_usage['used_today']}/{email_usage['daily_limit']}")
```

### 9.2 Wallet Asset Provisioning

Provision dedicated wallets for child agents
```python
child_eth_wallet = client.agents.provision_wallet_asset(
    child_id=social_media_agent['id'],
    chain="ethereum"
)
print(f"Child wallet created: {child_eth_wallet['wallet_address']}")

child_poly_wallet = client.agents.provision_wallet_asset(
    child_id=social_media_agent['id'],
    chain="polygon"
)
print(f"Child Polygon wallet: {child_poly_wallet['wallet_address']}")

```
Transfer budget to child wallets
```python
budget_transfer = client.agents.transfer_assets_to_child(
    child_id=social_media_agent['id'],
    from_wallet=eth_wallet['wallet_address'],
    to_wallet=child_eth_wallet['wallet_address'],
    asset_type="eth",
    amount="100000000000000000",  # 0.1 ETH
    note="Monthly social media budget"
)
print(f"Budget transferred: {budget_transfer['transfer_id']}")
```

---

## 10.  Fiat On/Off Ramps

### 10.1 Fiat Onboarding

Create fiat on-ramp session
```python
onramp_session = client.wallets.create_onramp_session(
    currency="USD",
    amount=1000.0  # $1000
)
print(f"On-ramp session: {onramp_session['session_id']}")
print(f"Widget URL: {onramp_session['widget_url']}")

```
Check on-ramp status
```python
onramp_status = client.wallets.get_onramp_status(
    session_id=onramp_session['session_id']
)
print(f"Status: {onramp_status['status']}")
if onramp_status['status'] == 'completed':
    print(f"Received: {onramp_status['crypto_amount']} {onramp_status['crypto_currency']}")
```

---

## 11.  Gas Management & Abstraction

### 11.1 Gas Sponsorship

Deposit tokens for gas sponsorship
```python
gas_deposit = client.wallets.sponsor_gas(
    token_address="0xA0b86a33E6D1cc22c435370bA9e4240EE8D5fE5",  # USDC
    amount=100.0  # $100 worth of gas
)
print(f"Gas sponsorship: {gas_deposit}")

```
Check gas balance
```python
gas_balance = client.wallets.get_gas_sponsorship_balance()
print(f"Gas balance: {gas_balance} USDC")

```
Send gasless transaction using ERC-4337
```python
user_op = client.wallets.send_user_operation(
    user_op={
        "sender": agent_addr,
        "nonce": "0x0",
        "initCode": "0x",
        "callData": "0x...",  # Your transaction data
        "callGasLimit": "0x5208",
        "verificationGasLimit": "0x5208", 
        "preVerificationGas": "0x5208",
        "maxFeePerGas": "0x3b9aca00",
        "maxPriorityFeePerGas": "0x3b9aca00",
        "paymasterAndData": "0x",
        "signature": "0x"
    },
    entry_point_address="0x5FF137D4b0FDCD49DcA30c7CF57E578a026d2789"
)
print(f"Gasless transaction: {user_op['user_op_hash']}")
```

---

## 12. 🆕 Advanced Compliance & Monitoring 

### 12.1 KYC/AML Verification

Perform comprehensive KYC verification
```python
kyc_result = client.compliance.kyc_verification(
    user_id="user123",
    identity_check=True,
    document_scan=True
)
print(f"KYC Status: {kyc_result['status']}")
print(f"Risk Score: {kyc_result['risk_score']}")
print(f"Verification Level: {kyc_result['verification_level']}")
```

Check current KYC status
```python
status = client.compliance.get_kyc_status(user_id="user123")
print(f"Current status: {status['status']}")
print(f"Last updated: {status['last_updated']}")
```

### 12.2 Document Processing & Validation

Process compliance documents with AI validation
```python
with open("passport.pdf", "rb") as document:
    result = client.compliance.process_document(
        document=document,
        document_type="passport",
        user_id="user123"
    )
    
print(f"Document processed: {result['document_id']}")
print(f"Validation status: {result['validation_status']}")
print(f"Extracted data: {result['extracted_data']}")
print(f"Confidence score: {result['confidence_score']}")
```

Supported document types:
- `passport` - International passports
- `driver_license` - Government-issued driver's licenses  
- `utility_bill` - Proof of address documents
- `bank_statement` - Financial institution statements
- `tax_document` - Tax returns and related documents

### 12.3 Tamper-Evident Audit Trails

Retrieve audit trail with cryptographic verification
```python
audit_trail = client.compliance.get_audit_trail(
    user_id="user123",
    action_type="document_upload",
    start_date="2025-07-01",
    end_date="2025-07-17",
    limit=50
)

for entry in audit_trail['entries']:
    print(f"Timestamp: {entry['timestamp']}")
    print(f"Action: {entry['action_type']}")
    print(f"User: {entry['user_id']}")
    print(f"Hash: {entry['hash_value']}")
    print(f"Previous Hash: {entry['previous_hash']}")
    print(f"Verification: {'✓ Valid' if entry['hash_verified'] else '✗ Invalid'}")
    print("---")
```

Verify audit trail integrity
```python
verification = client.compliance.verify_audit_integrity(
    start_date="2025-07-01",
    end_date="2025-07-17"
)
print(f"Audit trail verified: {verification['is_valid']}")
print(f"Total entries checked: {verification['entries_checked']}")
print(f"Hash chain intact: {verification['hash_chain_valid']}")
```

### 12.4 Webhook Management & Persistence

Get webhook delivery status
```python
webhook_status = client.compliance.get_webhook_status(webhook_id="webhook_123")
print(f"Delivery status: {webhook_status['status']}")
print(f"Attempts: {webhook_status['attempts']}")
print(f"Last attempt: {webhook_status['last_attempt_time']}")
print(f"Next retry: {webhook_status['next_retry_time']}")
```

List all webhook deliveries
```python
deliveries = client.compliance.list_webhook_deliveries(
    status="failed",  # Options: pending, delivered, failed, retrying
    limit=20
)
for delivery in deliveries:
    print(f"Webhook {delivery['webhook_id']}: {delivery['status']}")
```

Manually retry a failed webhook
```python
retry_result = client.compliance.retry_webhook(webhook_id="webhook_123")
print(f"Retry initiated: {retry_result['retry_scheduled']}")
print(f"Retry time: {retry_result['retry_time']}")
```

### 12.5 Rate Limiting & API Protection

Check rate limit status
```python
rate_status = client.compliance.get_rate_limit_status(user_id="user123")
print(f"Requests remaining: {rate_status['requests_remaining']}")
print(f"Reset time: {rate_status['reset_time']}")
print(f"Rate limit: {rate_status['rate_limit']}")
```

Check global rate limit status
```python
global_status = client.compliance.get_rate_limit_status()
print(f"Global requests remaining: {global_status['global_requests_remaining']}")
print(f"Per-user limits active: {global_status['per_user_limits_active']}")
```

### 12.6 Enterprise Compliance Features

For enterprise users with advanced compliance plans:

```python
# Bulk document processing
if hasattr(client, 'compliance_advanced'):
    bulk_result = client.compliance_advanced.bulk_process_documents(
        directory_path="/path/to/documents",
        document_type="bank_statement",
        batch_size=10
    )
    print(f"Processed {bulk_result['total_processed']} documents")
    print(f"Success rate: {bulk_result['success_rate']}%")
```

Get compliance dashboard data
```python
if hasattr(client, 'compliance_advanced'):
    dashboard = client.compliance_advanced.get_dashboard_data()
    print(f"Total KYC completions: {dashboard['metrics']['kyc_completions']}")
    print(f"Document processing rate: {dashboard['metrics']['document_success_rate']}%")
    print(f"Compliance score: {dashboard['metrics']['overall_compliance_score']}")
```

Perform comprehensive risk assessment
```python
if hasattr(client, 'compliance_advanced'):
    risk_assessment = client.compliance_advanced.perform_risk_assessment(
        user_id="user123"
    )
    print(f"Risk level: {risk_assessment['risk_level']}")
    print(f"Risk factors: {risk_assessment['risk_factors']}")
    print(f"Recommended actions: {risk_assessment['recommendations']}")
```

### 12.7 Asynchronous Task Processing

Monitor background compliance tasks
```python
# Check status of document processing job
task_status = client.compliance.get_task_status(task_id="task_123")
print(f"Task status: {task_status['status']}")
print(f"Progress: {task_status['progress']}%")
print(f"ETA: {task_status['estimated_completion']}")
```

List all active compliance tasks
```python
active_tasks = client.compliance.list_active_tasks()
for task in active_tasks:
    print(f"Task {task['task_id']}: {task['task_type']} - {task['status']}")
```

---

## 13.  Advanced Features

### 13.1 NFT Management

List NFTs in wallet
```python
nfts = client.wallets.list_nfts(wallet_id=eth_wallet['id'])
for nft in nfts:
    print(f"{nft['name']} #{nft['token_id']}")
    print(f"  Collection: {nft['collection_name']}")
    print(f"  Value: ${nft['estimated_value']}")

```
Transfer NFT
```python
nft_transfer = client.wallets.transfer_nft(
    wallet_id=eth_wallet['id'],
    contract_address="0x1234567890abcdef...",
    token_id="123", 
    to_address="0x742d35Cc6634C0532925a3b8D0715a99C7DCF"
)
print(f"NFT transferred: {nft_transfer['tx_hash']}")

```
Get metadata for a specific NFT
```python
metadata = client.nfts.get_nft_metadata(
    contract_address="0x1234567890abcdef...",
    token_id="123"
)
print(f"NFT Metadata: {metadata}")

```
Mint a new NFT
```python
minted = client.nfts.mint_nft(
    contract_address="0xNFTContract...",
    to_address="0x742d35Cc6634C0532925a3b8D0715a99C7DCF",
    metadata_uri="https://metadata.example.com/nft/1"
)
print(f"NFT minted: {minted['token_id']}")

```
Batch transfer multiple NFTs
```python
batch = client.nfts.batch_transfer(
    contract_address="0x1234567890abcdef...",
    transfers=[
        {"token_id": "123", "to_address": "0xabc..."},
        {"token_id": "124", "to_address": "0xdef..."}
    ]
)
print("Batch transfer complete")

```
Burn an NFT
```python
burn = client.nfts.burn_nft(
    contract_address="0x1234567890abcdef...",
    token_id="123"
)
print(f"NFT burned: {burn['status']}")
```

### 13.2 Event Subscriptions

Subscribe to wallet events
```python
subscription = client.wallets.subscribe_to_events(
    wallet_address=eth_wallet['wallet_address'],
    event_types=["transfer", "approval", "swap"]
)
print(f"Event subscription: {subscription['subscription_id']}")

```
Get recent events
```python
events = client.wallets.get_wallet_events(
    wallet_address=eth_wallet['wallet_address'],
    limit=50
)
for event in events:
    print(f"{event['event_type']}: {event['details']}")
```

##  Complete API Reference

### AuthClient

- `register(username, email, password, preferred_2fa_method="totp")` → `TwoFactorSetupResponse`
- `login(username, password)` → `Token | TwoFactorRequiredResponse`
- `login_with_2fa(username, password, totp_code)` → `Token`
- `verify_2fa(temporary_token, totp_code)` → `Token`
- `get_2fa_status()` → `TwoFactorStatusResponse`
- `setup_2fa()` → `TwoFactorSetupResponse`
- `confirm_2fa(totp_code)` → `dict`
- `disable_2fa(totp_code, password)` → `dict`
- `get_qr_code()` → `bytes`
- `debug_2fa()` → `dict`
- `refresh(refresh_token)` → `Token`
- `logout()` → `dict`

### WalletsClient

**Basic Wallet Operations:**

- `create_wallet(chain)` → `dict`
- `import_wallet(chain, private_key)` → `dict`
- `list_wallets()` → `List[dict]`
- `delete_wallet(wallet_id)` → `None`
- `get_balance(chain, address)` → `Decimal`

**Token Management:**

- `get_token_balance(wallet_id, token_address)` → `dict`
- `transfer_tokens(wallet_id, token_address, to_address, amount)` → `dict`
- `approve_tokens(wallet_id, token_address, spender_address, amount)` → `dict`

**Agent Wallets:**

- `deploy_agent_wallet()` → `dict`
- `list_agent_wallets()` → `List[dict]`
- `get_agent_wallet(address)` → `dict`
- `set_spending_limit(address, token, amount, period)` → `str`
- `update_whitelist(address, target, allowed)` → `str`
- `set_threshold(address, new_threshold)` → `str`
- `list_wallet_transactions(address)` → `List[dict]`

**DeFi Integration:**

- `swap_tokens(wallet_id, from_token, to_token, amount, slippage_tolerance)` → `dict`
- `deposit_yield_vault(wallet_id, vault_address, token_address, amount)` → `dict`
- `withdraw_yield_vault(wallet_id, vault_address, amount)` → `dict`
- `get_yield_positions(wallet_id)` → `List[dict]`

**Email Integration:**

- `list_email_accounts()` → `List[dict]`
- `create_email_account(provider, email_address, config)` → `dict`
- `test_email_connection(account_id)` → `dict`
- `get_inbox(account_id, limit=10, unread_only=False)` → `dict`

**Gas & Fees:**

- `sponsor_gas(token_address, amount)` → `str`
- `get_gas_sponsorship_balance()` → `Decimal`
- `send_user_operation(user_op, entry_point_address)` → `dict`

**Events & Monitoring:**

- `subscribe_to_events(wallet_address, event_types)` → `dict`
- `get_wallet_events(wallet_address, limit=50)` → `List[dict]`
- `unsubscribe_event(subscription_id)` → `None`

**RWA & NFTs:**

- `register_rwa_asset(token_address, token_id, metadata_uri)` → `dict`
- `list_rwa_assets()` → `List[dict]`
- `transfer_rwa(wallet_id, token_address, token_id, to_address, amount)` → `dict`
- `list_nfts(wallet_id)` → `List[dict]`
- `transfer_nft(wallet_id, contract_address, token_id, to_address)` → `dict`

**Fiat Integration:**

- `create_onramp_session(currency, amount)` → `dict`
- `get_onramp_status(session_id)` → `dict`

### AgentsClient

- `list_agents()` → `List[dict]`
- `create_agent(name, description, agent_type, parent_id=None, capabilities=[])` → `dict`
- `get_agent(agent_id)` → `dict`
- `update_agent(agent_id, **kwargs)` → `dict`
- `delete_agent(agent_id)` → `None`
- `get_inherited_rules(child_id)` → `dict`
- `delegate_task(master_id, child_agent_id, task_type, budget_allocation, deadline, parameters)` → `dict`
- `list_delegations(agent_id)` → `List[dict]`
- `provision_email_asset(child_id, email_account_id, permissions, quota)` → `dict`
- `provision_wallet_asset(child_id, chain)` → `dict`
- `transfer_assets_to_child(child_id, from_wallet, to_wallet, asset_type, amount, note)` → `dict`
- `get_email_usage(child_id)` → `dict`

### BridgeClient

- `get_quote(from_chain, to_chain, from_token, to_token, amount)` → `dict`
- `bridge_transfer(provider, from_chain, to_chain, from_token, to_token, amount, recipient_address)` → `dict`

### AssetsClient

- `get_multi_chain_asset_view()` → `dict`

### GovernanceClient

- `create_proposal(targets, values, calldatas, description)` → `dict`
- `cast_vote(proposal_id, support)` → `dict`
- `get_proposal_state(proposal_id)` → `dict`
- `get_user_votes()` → `List[dict]`

### ReputationClient

- `issue_sbt(to_address, metadata_uri)` → `dict`
- `get_sbt_owner(token_id)` → `dict`
- `get_user_reputation(user_id)` → `dict`
- `stake_reputation(amount)` → `dict`

### MonitoringClient

- `watch_address(address, alert_conditions)` → `dict`
- `get_transaction_status(tx_hash)` → `dict`
- `list_watches()` → `List[dict]`
- `get_alerts()` → `List[dict]`

### ComplianceClient

- `get_kyc_status()` → `dict`
- `initiate_kyc()` → `dict`
- `generate_report(start_date, end_date, report_type)` → `dict`
- `get_audit_trail(entity_id, entity_type)` → `List[dict]`

### SwapClient

- `get_quote(from_token, to_token, amount)` → `dict`
- `execute_swap(from_token, to_token, amount, slippage_tolerance)` → `dict`
- `cancel_swap(quote_id)` → `dict`

### MarketplaceClient

- `list_listings(limit=None)` → `List[dict]`
- `get_listing(listing_id)` → `dict`
- `create_listing(asset_id, price, quantity)` → `dict`
- `place_bid(listing_id, bid_amount)` → `dict`
- `cancel_listing(listing_id)` → `None`

### Contributing

We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details on:

- Setting up the development environment
- Running tests and linting
- Submitting pull requests
- Code style guidelines

---

##  Requirements

- **Python 3.8+**
- **requests** or **httpx** (for async support)
- **pydantic** for data validation
- **Authenticator app** (Google Authenticator, Authy, Microsoft Authenticator, etc.)

---

##  What's New in July 2025

###  Latest Features

-  **Complete Two-Factor Authentication** with TOTP and SMS support
-  **Agent Smart Contract Wallets** with prog