SAM Framework implements a defense-in-depth security approach with multiple layers of protection for handling sensitive blockchain operations and AI interactions.
Key Management
Fernet encryption with OS keyring integration
Transaction Safety
Pre-execution checks and slippage protection
Privacy First
Local operation with minimal external dependencies
Secure Memory
Encrypted conversation context and session data
SAM uses military-grade encryption for all sensitive data:
# sam/utils/crypto.py from cryptography.fernet import Fernet def encrypt_private_key(private_key: str, fernet_key: str) -> str: f = Fernet(fernet_key) encrypted = f.encrypt(private_key.encode()) return encrypted.decode() def decrypt_private_key(encrypted_key: str, fernet_key: str) -> str: f = Fernet(fernet_key) decrypted = f.decrypt(encrypted_key.encode()) return decrypted.decode()
Security Properties:
Comprehensive pre-execution checks prevent unauthorized or dangerous transactions:
# sam/utils/transaction_validator.py async def validate_pump_buy(args: Dict[str, Any]) -> bool: """Validate Pump.fun buy transaction parameters.""" # Amount validation if args.get('amount', 0) <= 0: raise ValueError("Amount must be positive") # Slippage limits slippage = args.get('slippage', 5) if slippage < 1 or slippage > 50: raise ValueError("Slippage must be between 1% and 50%") # Maximum transaction limits max_sol = float(os.getenv('MAX_TRANSACTION_SOL', '1000')) if args['amount'] > max_sol: raise ValueError(f"Transaction exceeds maximum SOL limit: {max_sol}") return True
Validation Layers:
Built-in protection against excessive API usage:
# sam/utils/rate_limiter.py class RateLimiter: def __init__(self, requests_per_minute: int = 60): self.requests_per_minute = requests_per_minute self.requests = [] async def check_limit(self, key: str) -> bool: """Check if request is within rate limits.""" now = time.time() # Remove old requests self.requests = [req for req in self.requests if now - req < 60] if len(self.requests) >= self.requests_per_minute: return False self.requests.append(now) return True
Rate Limiting Features:
Secure conversation context management:
# sam/core/memory.py class MemoryManager: async def save_session(self, session_id: str, messages: List[Dict]): """Securely store conversation context.""" # Sanitize sensitive data before storage sanitized_messages = [] for msg in messages: if msg.get('role') == 'tool' and 'private_key' in str(msg.get('content', '')): # Remove sensitive data from context msg = msg.copy() msg['content'] = '[SENSITIVE_DATA_REMOVED]' sanitized_messages.append(msg) # Store sanitized context await self._store_messages(session_id, sanitized_messages)
Memory Security:
Critical: Never store private keys in plain text files or environment variables. Always use the secure import feature.
# β Good: Use secure import uv run sam key import # β Bad: Store in environment SAM_WALLET_PRIVATE_KEY=your_private_key_here # β Bad: Store in .env file echo "SAM_WALLET_PRIVATE_KEY=your_key" >> .env
# Regularly rotate your Fernet encryption key uv run sam key generate # Update SAM_FERNET_KEY in your .env file # Re-import your private key with the new encryption key
# Set reasonable slippage limits export DEFAULT_SLIPPAGE=5 # 5% for volatile tokens export MAX_TRANSACTION_SOL=10.0 # Maximum 10 SOL per transaction
# Always test with small amounts first "buy 0.001 SOL worth of TEST_TOKEN" # Verify transaction details before large trades "get swap quote for 1 SOL to USDC"
# Use production settings export RATE_LIMITING_ENABLED=true export LOG_LEVEL=WARNING export MAX_TRANSACTION_SOL=5.0
# Use secure file permissions chmod 600 .env # Never commit sensitive files echo ".env" >> .gitignore echo ".sam/" >> .gitignore
# Run security health check uv run sam health # Validate configuration security uv run sam setup # Check for exposed sensitive data grep -r "private_key\|api_key" . --exclude-dir=.git
# Monitor for suspicious activity tail -f sam.log | grep -E "(ERROR|WARNING|private_key)" # Check rate limiting effectiveness grep "rate_limit" sam.log
# Verify key access patterns uv run sam health # Check key retrieval status # Monitor for unusual transaction patterns # Review transaction history for anomalies
| Risk | Mitigation | |------|------------| | Private Key Exposure | Encrypted storage + OS keyring | | API Key Leakage | Environment variables + secure storage | | Transaction Manipulation | Pre-validation + slippage protection | | Rate Limit Bypass | Multi-layer rate limiting | | Memory Dumping | Sensitive data sanitization | | Log Exposure | No sensitive data in logs |
# sam/integrations/solana/solana_tools.py async def _sign_transaction(self, transaction_hex: str) -> str: """Secure transaction signing with validation.""" # Validate transaction before signing if not self._validate_transaction_format(transaction_hex): raise ValueError("Invalid transaction format") # Sign with keypair signed_tx = self.keypair.sign_message(transaction_hex) # Clear sensitive data from memory del transaction_hex return signed_tx
sam key import
Security is not a featureβit's a fundamental requirement. SAM Framework is designed with security-first principles to protect your assets and data.