cdp-agent/database.py

210 lines
8.2 KiB
Python
Raw Permalink Normal View History

2024-12-11 00:38:47 +03:00
import sqlite3
import json
from datetime import datetime
from typing import Dict, Any, List, Optional
from contextlib import contextmanager
class Database:
"""
Manages database operations for the CDP agent system.
"""
def __init__(self, db_path: str = 'cdp_agent.db'):
self.db_path = db_path
self.initialize_database()
2024-12-11 20:29:09 +03:00
@contextmanager
2024-12-11 00:38:47 +03:00
def get_connection(self):
2024-12-11 20:29:09 +03:00
"""
Context manager for database connections.
"""
2024-12-11 00:38:47 +03:00
conn = sqlite3.connect(self.db_path)
2024-12-11 20:29:09 +03:00
conn.row_factory = sqlite3.Row
try:
yield conn
conn.commit()
except Exception as e:
conn.rollback()
raise DatabaseError(f"Database operation failed: {str(e)}")
finally:
conn.close()
2024-12-11 00:38:47 +03:00
def initialize_database(self) -> None:
"""
2024-12-11 20:29:09 +03:00
Initializes the database with required tables.
2024-12-11 00:38:47 +03:00
"""
with self.get_connection() as conn:
2024-12-11 20:29:09 +03:00
# Transactions table
2024-12-11 00:38:47 +03:00
conn.execute("""
CREATE TABLE IF NOT EXISTS transactions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
2024-12-11 20:29:09 +03:00
wallet_address TEXT,
operation_type TEXT,
network TEXT,
status TEXT,
2024-12-11 00:38:47 +03:00
tx_hash TEXT,
block_number INTEGER,
gas_used REAL,
amount REAL,
token_address TEXT,
recipient_address TEXT,
details TEXT,
error_message TEXT
)
""")
2024-12-11 20:29:09 +03:00
# Wallets table
2024-12-11 00:38:47 +03:00
conn.execute("""
CREATE TABLE IF NOT EXISTS wallets (
address TEXT PRIMARY KEY,
2024-12-11 20:29:09 +03:00
network TEXT,
2024-12-11 00:38:47 +03:00
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
last_active DATETIME,
balance TEXT,
tokens TEXT,
metadata TEXT
)
""")
2024-12-11 20:29:09 +03:00
# Metrics table
2024-12-11 00:38:47 +03:00
conn.execute("""
CREATE TABLE IF NOT EXISTS performance_metrics (
id INTEGER PRIMARY KEY AUTOINCREMENT,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
2024-12-11 20:29:09 +03:00
operation_type TEXT,
2024-12-11 00:38:47 +03:00
duration_ms INTEGER,
success BOOLEAN,
error_type TEXT,
details TEXT
)
""")
def record_transaction(self, transaction_data: Dict[str, Any]) -> int:
2024-12-11 20:29:09 +03:00
"""Records a blockchain transaction."""
2024-12-11 00:38:47 +03:00
with self.get_connection() as conn:
cursor = conn.execute("""
INSERT INTO transactions (
wallet_address, operation_type, network, status,
tx_hash, block_number, gas_used, amount,
token_address, recipient_address, details, error_message
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""", (
2024-12-11 20:29:09 +03:00
str(transaction_data.get('wallet_address', '')),
str(transaction_data.get('operation_type', '')),
str(transaction_data.get('network', '')),
str(transaction_data.get('status', '')),
str(transaction_data.get('tx_hash', '')),
2024-12-11 00:38:47 +03:00
transaction_data.get('block_number'),
transaction_data.get('gas_used'),
transaction_data.get('amount'),
transaction_data.get('token_address'),
transaction_data.get('recipient_address'),
json.dumps(transaction_data.get('details', {})),
transaction_data.get('error_message')
))
return cursor.lastrowid
def update_wallet(self, wallet_data: Dict[str, Any]) -> None:
2024-12-11 20:29:09 +03:00
"""Updates wallet information."""
2024-12-11 00:38:47 +03:00
with self.get_connection() as conn:
conn.execute("""
INSERT OR REPLACE INTO wallets (
address, network, last_active, balance, tokens, metadata
) VALUES (?, ?, ?, ?, ?, ?)
""", (
2024-12-11 20:29:09 +03:00
str(wallet_data.get('address', '')),
str(wallet_data.get('network', '')),
2024-12-11 00:38:47 +03:00
datetime.now().isoformat(),
json.dumps(wallet_data.get('balance', {})),
json.dumps(wallet_data.get('tokens', [])),
json.dumps(wallet_data.get('metadata', {}))
))
def record_metric(self, metric_data: Dict[str, Any]) -> None:
2024-12-11 20:29:09 +03:00
"""Records performance metrics."""
2024-12-11 00:38:47 +03:00
with self.get_connection() as conn:
conn.execute("""
INSERT INTO performance_metrics (
operation_type, duration_ms, success, error_type, details
) VALUES (?, ?, ?, ?, ?)
""", (
2024-12-11 20:29:09 +03:00
str(metric_data.get('operation_type', '')),
metric_data.get('duration_ms', 0),
bool(metric_data.get('success', False)),
str(metric_data.get('error_type', '')),
2024-12-11 00:38:47 +03:00
json.dumps(metric_data.get('details', {}))
))
def get_transaction_history(
self,
wallet_address: Optional[str] = None,
limit: int = 50
) -> List[Dict[str, Any]]:
2024-12-11 20:29:09 +03:00
"""Gets transaction history."""
2024-12-11 00:38:47 +03:00
with self.get_connection() as conn:
query = "SELECT * FROM transactions"
params = []
if wallet_address:
query += " WHERE wallet_address = ?"
params.append(wallet_address)
query += " ORDER BY timestamp DESC LIMIT ?"
params.append(limit)
cursor = conn.execute(query, params)
2024-12-11 20:29:09 +03:00
return [dict(zip([column[0] for column in cursor.description], row))
for row in cursor.fetchall()]
2024-12-11 00:38:47 +03:00
def get_wallet_details(self, address: str) -> Optional[Dict[str, Any]]:
2024-12-11 20:29:09 +03:00
"""Gets wallet details."""
2024-12-11 00:38:47 +03:00
with self.get_connection() as conn:
cursor = conn.execute(
"SELECT * FROM wallets WHERE address = ?",
(address,)
)
row = cursor.fetchone()
if row:
2024-12-11 20:29:09 +03:00
column_names = [column[0] for column in cursor.description]
result = dict(zip(column_names, row))
result['balance'] = json.loads(result.get('balance', '{}'))
result['tokens'] = json.loads(result.get('tokens', '[]'))
result['metadata'] = json.loads(result.get('metadata', '{}'))
return result
2024-12-11 00:38:47 +03:00
return None
2024-12-11 20:29:09 +03:00
def save_wallet_data(self, wallet_data: Dict[str, Any]) -> None:
"""Saves wallet data to the database."""
try:
# If parsing JSON string
if isinstance(wallet_data, str):
try:
wallet_json = json.loads(wallet_data)
except json.JSONDecodeError:
raise DatabaseError("Invalid JSON in wallet data")
else:
wallet_json = wallet_data
2024-12-11 00:38:47 +03:00
2024-12-11 20:29:09 +03:00
# Extract address or use default_address_id
address = wallet_json.get('address') or wallet_json.get('default_address_id')
if not address:
raise DatabaseError("No valid address found in wallet data")
with self.get_connection() as conn:
conn.execute("""
INSERT OR REPLACE INTO wallets
(address, network, created_at, balance, tokens, metadata)
VALUES (?, ?, ?, ?, ?, ?)
""", (
address, # Address
wallet_json.get('network', 'base-sepolia'), # Network
datetime.now().isoformat(), # Created at
json.dumps(wallet_json.get('balance', {})), # Balance
json.dumps(wallet_json.get('tokens', [])), # Tokens
json.dumps(wallet_json) # Full metadata
))
except Exception as e:
raise DatabaseError(f"Failed to save wallet data: {str(e)}")
2024-12-11 00:38:47 +03:00
class DatabaseError(Exception):
"""Custom exception for database-related errors."""
pass