syft-hub SDK is in beta. Payments are disabled during beta; enjoy $20 in free credits.

Authentication API

Account management, authentication, and payment system for SyftBox services

client.accounting_client

Access the accounting client for payment management and authentication with SyftBox services.

Quick Start

Is Configured


client.accounting_client.is_configured() -> bool

Check if accounting credentials are properly configured and the client is ready to handle payments and authentication. This method validates that all necessary configuration is in place without making network requests.

Example

from syftbox import Client

# Initialize client - automatically discovers saved credentials
client = Client()

# Check if accounting is configured
if client.accounting_client.is_configured():
    print("✓ Accounting configured")
    client.accounting_client.show()  # Display status widget
else:
    print("❌ No accounting configuration found")

Account Registration

Register Accounting


register_accounting(email: str, password: str = None, organization: str = None) -> UserAccount

Create a new accounting account that enables access to paid AI services and provides usage tracking across the network. The account includes initial credits and allows you to monitor costs across all your service interactions.

Parameters

email str required
Email address for the new account
password str optional
Account password. Auto-generated if not provided
organization str optional
Organization name for the account

Returns

UserAccount - Account object with email, password, and initial balance

Example

# Register with email - password will be generated if not provided
user_account = client.accounting_client.register_accounting(
    email="your.email@example.com",
    password="secure_password",  # Optional - auto-generated if not provided
    organization="YourOrganization"  # Optional
)

print(f"Account created: {user_account.email}")
print(f"Password: {user_account.password}")  # Save this securely!
print(f"Balance: ${user_account.balance}")


Important: Save the generated password securely - it cannot be recovered. If you lose it, contact support@openmined.org.

Account Connection

Configure


configure(accounting_url: str, email: str, password: str) -> None

Connect to the accounting system using existing credentials.

Parameters

email str required
Account email address
password str required
Account password

Example

# Method 1: Configure directly
client.accounting_client.configure(
    email="your.email@example.com",
    password="your_password"
)

# Method 2: Use connect_accounting alias
client.accounting_client.connect_accounting(
    email="your.email@example.com",
    password="your_password"
)

# Display connection status
client.accounting_client.show()

Connect Accounting


connect_accounting(accounting_url: str, email: str, password: str) -> None

Convenient alias for the configure() method that provides the same functionality with a more descriptive name.

Account Status

Show


show() -> None

Display an interactive status widget, showing account details, balance, service URL, and common operations.

Example

# Display interactive status widget (Jupyter environments)
client.accounting_client.show()

# Get basic configuration info
print(f"Configured: {client.accounting_client.is_configured()}")
print(f"Email: {client.accounting_client.get_email()}")
print(f"Service URL: {client.accounting_client.accounting_url}")

Get Email


get_email() -> str

Retrieve the email address currently configured for this accounting client, which serves as your unique identifier across the payment system.

Get Account Info


get_account_info() -> Dict[str, Any]

Retrieve comprehensive account information including current balance, account ID, usage statistics, and billing history through an asynchronous operation.

Returns

Dict - Account information including balance and account ID

Example

# Get detailed account information (async)
import asyncio
info = await client.accounting_client.get_account_info()
print(f"Balance: ${info['balance']}")
print(f"Account ID: {info['account_id']}")

Balance and Payments

Get Account Balance


get_account_balance() -> float

Retrieve your current account balance synchronously, blocking until the balance is fetched from the accounting service.

Returns

float - Current account balance in USD

Example

# Get current balance (synchronous)
balance = client.accounting_client.get_account_balance()
print(f"Available Balance: ${balance}")

Get Account Balance Async


_get_account_balance_async() -> float

Retrieve your current account balance asynchronously, allowing your application to continue processing while the balance is fetched in the background. This approach is better for applications that need to check balances frequently or handle multiple concurrent operations without blocking the main thread.

Example

# Get current balance (asynchronous)
balance = await client.accounting_client._get_account_balance_async()
print(f"Available Balance: ${balance}")

Create Transaction Token


create_transaction_token(recipient_email: str) -> str

Generate a secure transaction token that authorizes payment to a specific service provider, enabling you to pay for AI model usage or data access in a controlled manner. This token-based approach ensures secure, traceable payments while maintaining privacy and preventing unauthorized charges.

Parameters

recipient_email str required
Email of the service provider to pay

Returns

str - Transaction token for payment authorization

Example

# Create transaction token for payments
token = await client.accounting_client.create_transaction_token(
    recipient_email="service@example.com"
)
print(f"Transaction token: {token}")

# Complete transaction workflow
# Check balance before operation
initial_balance = client.accounting_client.get_account_balance()
print(f"Current Balance: ${initial_balance}")

# Create transaction token for service payment
service_email = "ai-service@example.com"
transaction_token = await client.accounting_client.create_transaction_token(
    recipient_email=service_email
)

# Use the token in your service requests
response = await some_ai_service.query(
    message="Your query here",
    payment_token=transaction_token
)

# Check remaining balance
final_balance = client.accounting_client.get_account_balance()
print(f"Remaining Balance: ${final_balance}")
print(f"Transaction Cost: ${initial_balance - final_balance}")

Credential Validation

Validate Credentials


validate_credentials() -> bool

Verify that your stored credentials are still valid and that you can successfully authenticate with the accounting service. This asynchronous operation checks credential freshness, account status, and service connectivity, helping you detect and resolve authentication issues before they impact your workflow.

Returns

bool - True if credentials are valid, False otherwise

Example

# Test if credentials are valid
is_valid = await client.accounting_client.validate_credentials()
if is_valid:
    print("✓ Credentials are valid")
else:
    print("❌ Invalid credentials")

# Check if client is configured
if client.accounting_client.is_configured():
    email = client.accounting_client.get_email()
    print(f"Configured for: {email}")
else:
    print("No configuration found")

Configuration Management

Save Credentials


save_credentials(filepath: str = None) -> None

Securely save your authentication credentials to a local configuration file with strict permissions, enabling automatic authentication in future sessions. This method requires explicit user consent and encrypts sensitive data before storage, providing a balance between convenience and security for development workflows.

Parameters

filepath str optional
Custom path for config file. Defaults to ~/.syftbox/accounting.json

Example

# Save credentials to config file (requires user consent)
client.accounting_client.save_credentials()  # Saves to ~/.syftbox/accounting.json
# Or specify custom path
client.accounting_client.save_credentials("/path/to/config.json")

Security Note: Config files are saved with restrictive permissions (0o600) and contain sensitive data. Only save credentials with explicit user consent.

Load From Config


@classmethod
load_from_config(filepath: str = None) -> AccountingClient

Load previously saved credentials from the local configuration file, automatically establishing authentication without requiring manual credential entry. This class method creates a new AccountingClient instance with stored credentials, streamlining the setup process for recurring use of the same account.

Parameters

filepath str optional
Path to config file. Defaults to ~/.syftbox/accounting.json

Example

# Load from saved config
accounting_client = AccountingClient.load_from_config()
# Or from custom path
accounting_client = AccountingClient.load_from_config("/path/to/config.json")

client = Client(accounting_client=accounting_client)

From Environment


@classmethod
from_environment() -> AccountingClient

Create an AccountingClient instance using credentials stored in environment variables, enabling secure credential management in production environments and CI/CD pipelines. This method follows standard practices for secret management by keeping sensitive data out of code repositories.

Environment Variables

# Set environment variables in your shell or .env file
export SYFTBOX_ACCOUNTING_EMAIL=your.email@example.com
export SYFTBOX_ACCOUNTING_PASSWORD=your_secure_password
export SYFTBOX_ACCOUNTING_URL=https://your-accounting-service.com
from syftbox import Client
from syftbox.accounting import AccountingClient

# Method 1: Load via AccountingClient class method
accounting_client = AccountingClient.from_environment()
client = Client(accounting_client=accounting_client)

# Method 2: Auto-discovery during client setup
client = Client()  # Automatically tries environment variables
accounting_client, is_configured = AccountingClient.setup_accounting_discovery()

# Verify authentication
print(accounting_client)

Setup Accounting Discovery


@classmethod
setup_accounting_discovery() -> Tuple[AccountingClient, bool]

Automatically discover and load credentials using a fallback strategy that first tries saved configuration files, then environment variables, providing the most convenient authentication setup.

Returns

Tuple[AccountingClient, bool] - Accounting client and configuration status

Example

# Auto-discovery: tries config file, then environment variables
accounting_client, is_configured = AccountingClient.setup_accounting_discovery()
if is_configured:
    print("✓ Credentials loaded automatically")
else:
    print("❌ No saved credentials found")

Error Handling

Authentication Error


AuthenticationError

Handle authentication failures, invalid credentials, and connection issues with the accounting service, providing specific error messages to help diagnose and resolve authentication problems. This exception type helps distinguish authentication issues from other types of errors in your application logic.

Example

from syftbox.core.exceptions import AuthenticationError, PaymentError

try:
    client.accounting_client.configure(
        accounting_url="https://service.com",
        email="user@example.com",
        password="password"
    )
except AuthenticationError as e:
    print(f"Authentication failed: {e}")
    # Check credentials or register new account

Payment Error


PaymentError

Handle payment-related errors such as insufficient funds, failed transactions, or payment service unavailability, allowing your application to gracefully respond to billing issues. This exception type provides detailed error information to help users understand and resolve payment problems.

Example

try:
    balance = client.accounting_client.get_account_balance()
    if balance < 5.0:
        print("Warning: Low balance")
    
    token = await client.accounting_client.create_transaction_token(
        recipient_email="service@example.com"
    )
except PaymentError as e:
    print(f"Payment error: {e}")
    # Handle insufficient balance or service unavailability

Service Exception


ServiceException

Handle situations where the accounting service is temporarily unavailable, experiencing outages, or unreachable due to network issues. This exception allows your application to implement retry logic, fallback behavior, or graceful degradation when payment services are disrupted.

Example

try:
    from syft_accounting_sdk import ServiceException
except ImportError:
    print("syft-accounting-sdk not installed")
    print("Install with: pip install syft-accounting-sdk")

# Check if accounting features are available
if hasattr(client, 'accounting_client') and client.accounting_client:
    is_valid = await client.accounting_client.validate_credentials()
    if not is_valid:
        print("Invalid credentials or service unavailable")
else:
    print("Accounting client not available")