Account management, authentication, and payment system for SyftBox services
Access the accounting client for payment management and authentication with SyftBox services.
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.
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")
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.
UserAccount - Account object with email, password, and initial balance
# 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.
configure(accounting_url: str, email: str, password: str) -> None
Connect to the accounting system using existing credentials.
# 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(accounting_url: str, email: str, password: str) -> None
Convenient alias for the configure() method that provides the same functionality with a more descriptive name.
show() -> None
Display an interactive status widget, showing account details, balance, service URL, and common operations.
# 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() -> str
Retrieve the email address currently configured for this accounting client, which serves as your unique identifier across the payment system.
get_account_info() -> Dict[str, Any]
Retrieve comprehensive account information including current balance, account ID, usage statistics, and billing history through an asynchronous operation.
Dict - Account information including balance and account ID
# 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']}")
get_account_balance() -> float
Retrieve your current account balance synchronously, blocking until the balance is fetched from the accounting service.
float - Current account balance in USD
# Get current balance (synchronous)
balance = client.accounting_client.get_account_balance()
print(f"Available Balance: ${balance}")
_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.
# Get current balance (asynchronous)
balance = await client.accounting_client._get_account_balance_async()
print(f"Available Balance: ${balance}")
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.
str - Transaction token for payment authorization
# 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}")
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.
bool - True if credentials are valid, False otherwise
# 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")
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.
~/.syftbox/accounting.json# 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.
@classmethodload_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.
~/.syftbox/accounting.json# 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)
@classmethodfrom_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.
# 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)
@classmethodsetup_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.
Tuple[AccountingClient, bool] - Accounting client and configuration status
# 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")
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.
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
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.
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
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.
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")