Spaces:
Runtime error
Runtime error
| import asyncio | |
| import json | |
| import random | |
| from typing import Dict, List, Any, Optional | |
| from datetime import datetime | |
| import logging | |
| class BarouiaTokenEconomy: | |
| """ | |
| Système économique tokenisé Barouia | |
| Gestion des tokens, récompenses et échanges internes | |
| """ | |
| def __init__(self): | |
| self.logger = logging.getLogger("token_economy") | |
| self.total_supply = 1000000 | |
| self.circulating_supply = 500000 | |
| self.token_holders = {} | |
| self.transaction_history = [] | |
| self.token_value = 0.01 | |
| self.market_cap = self.circulating_supply * self.token_value | |
| async def initialize(self): | |
| """Initialise l'économie tokenisée""" | |
| self.logger.info("💰 Initialisation de l'économie tokenisée...") | |
| try: | |
| await self._load_token_data() | |
| await self._setup_initial_distribution() | |
| await self._start_market_simulation() | |
| self.logger.info("✅ Économie tokenisée initialisée") | |
| self.logger.info(f"📊 Market Cap: ${self.market_cap:,.2f}") | |
| return True | |
| except Exception as e: | |
| self.logger.error(f"❌ Erreur d'initialisation économique: {e}") | |
| return False | |
| async def reward_user(self, user_id: str, action: str, value: float) -> Dict[str, Any]: | |
| """Récompense un utilisateur avec des tokens""" | |
| reward_amount = await self._calculate_reward(action, value) | |
| if user_id not in self.token_holders: | |
| self.token_holders[user_id] = { | |
| "balance": 0, | |
| "first_interaction": datetime.now().isoformat(), | |
| "total_earned": 0 | |
| } | |
| # Distribution de la récompense | |
| self.token_holders[user_id]["balance"] += reward_amount | |
| self.token_holders[user_id]["total_earned"] += reward_amount | |
| transaction = { | |
| "type": "reward", | |
| "user_id": user_id, | |
| "amount": reward_amount, | |
| "action": action, | |
| "timestamp": datetime.now().isoformat(), | |
| "token_value": self.token_value | |
| } | |
| self.transaction_history.append(transaction) | |
| return { | |
| "user_id": user_id, | |
| "reward_amount": reward_amount, | |
| "new_balance": self.token_holders[user_id]["balance"], | |
| "transaction_hash": f"TX{len(self.transaction_history):08d}", | |
| "usd_value": reward_amount * self.token_value | |
| } | |
| async def transfer_tokens(self, from_user: str, to_user: str, amount: float) -> Dict[str, Any]: | |
| """Transfère des tokens entre utilisateurs""" | |
| # Vérification du solde | |
| if from_user not in self.token_holders or self.token_holders[from_user]["balance"] < amount: | |
| return {"error": "Solde insuffisant"} | |
| # Initialisation du destinataire si nécessaire | |
| if to_user not in self.token_holders: | |
| self.token_holders[to_user] = { | |
| "balance": 0, | |
| "first_interaction": datetime.now().isoformat(), | |
| "total_earned": 0 | |
| } | |
| # Exécution du transfert | |
| self.token_holders[from_user]["balance"] -= amount | |
| self.token_holders[to_user]["balance"] += amount | |
| transaction = { | |
| "type": "transfer", | |
| "from": from_user, | |
| "to": to_user, | |
| "amount": amount, | |
| "timestamp": datetime.now().isoformat(), | |
| "token_value": self.token_value | |
| } | |
| self.transaction_history.append(transaction) | |
| return { | |
| "success": True, | |
| "from_balance": self.token_holders[from_user]["balance"], | |
| "to_balance": self.token_holders[to_user]["balance"], | |
| "transaction_hash": f"TX{len(self.transaction_history):08d}" | |
| } | |
| async def get_token_metrics(self) -> Dict[str, Any]: | |
| """Retourne les métriques du token""" | |
| total_holders = len(self.token_holders) | |
| active_holders = len([h for h in self.token_holders.values() if h["balance"] > 0]) | |
| return { | |
| "token_name": "BAROUIA", | |
| "total_supply": self.total_supply, | |
| "circulating_supply": self.circulating_supply, | |
| "token_value": self.token_value, | |
| "market_cap": self.market_cap, | |
| "total_holders": total_holders, | |
| "active_holders": active_holders, | |
| "transactions_count": len(self.transaction_history), | |
| "daily_volume": await self._calculate_daily_volume() | |
| } | |
| async def stake_tokens(self, user_id: str, amount: float, duration_days: int) -> Dict[str, Any]: | |
| """Stake des tokens pour obtenir des récompenses""" | |
| if user_id not in self.token_holders or self.token_holders[user_id]["balance"] < amount: | |
| return {"error": "Solde insuffisant"} | |
| # Calcul des récompenses de staking | |
| apy = await self._calculate_apy(duration_days) | |
| expected_reward = amount * (apy / 100) * (duration_days / 365) | |
| stake_record = { | |
| "user_id": user_id, | |
| "amount": amount, | |
| "duration_days": duration_days, | |
| "start_date": datetime.now().isoformat(), | |
| "expected_reward": expected_reward, | |
| "apy": apy, | |
| "status": "active" | |
| } | |
| return { | |
| "stake_record": stake_record, | |
| "estimated_reward": expected_reward, | |
| "completion_date": await self._calculate_end_date(duration_days) | |
| } | |
| async def _calculate_reward(self, action: str, value: float) -> float: | |
| """Calcule la récompense basée sur l'action et la valeur""" | |
| reward_weights = { | |
| "quantum_thought": 10.0, | |
| "world_generation": 25.0, | |
| "temporal_prediction": 15.0, | |
| "code_evolution": 20.0, | |
| "system_interaction": 5.0, | |
| "content_creation": 8.0 | |
| } | |
| base_reward = reward_weights.get(action, 5.0) | |
| value_multiplier = min(2.0, 1.0 + (value / 100)) | |
| return base_reward * value_multiplier * random.uniform(0.8, 1.2) | |
| async def _calculate_apy(self, duration_days: int) -> float: | |
| """Calcule le APY pour le staking""" | |
| base_apy = 5.0 # 5% de base | |
| duration_bonus = min(10.0, duration_days / 36.5) # Max 10% bonus | |
| return base_apy + duration_bonus | |
| async def _calculate_daily_volume(self) -> float: | |
| """Calcule le volume quotidien des transactions""" | |
| today = datetime.now().date() | |
| today_transactions = [ | |
| t for t in self.transaction_history | |
| if datetime.fromisoformat(t["timestamp |