From b8e6b548d16f210be816b9b48d972f4fba37ca88 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Wed, 22 Oct 2025 10:20:42 +0000 Subject: [PATCH 1/4] Initial plan From eae4634321da385cc9328352313aebc32d9af043 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Wed, 22 Oct 2025 10:27:13 +0000 Subject: [PATCH 2/4] Add Hedera EVM configuration files and documentation Co-authored-by: AbhishekSatpathy4848 <108116233+AbhishekSatpathy4848@users.noreply.github.com> --- README.md | 68 +++++++++++++++++ frontend/.env.example | 22 ++++++ frontend/README.env.md | 77 +++++++++++++++++++ reputation_layer/.env.example | 34 +++++++++ reputation_layer/README.env.md | 132 +++++++++++++++++++++++++++++++++ 5 files changed, 333 insertions(+) create mode 100644 frontend/.env.example create mode 100644 frontend/README.env.md create mode 100644 reputation_layer/.env.example create mode 100644 reputation_layer/README.env.md diff --git a/README.md b/README.md index 5e9fe0c..35b9c1a 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,70 @@ # Sentinel-Protocol This project is being built for ETHOnline 2025 + +## Overview + +Sentinel Protocol is an intelligent asset protection system that leverages AI-powered risk management to protect cryptocurrency portfolios on the Hedera EVM network. + +## Quick Start + +### Prerequisites + +- Node.js 18+ (for frontend) +- Python 3.8+ (for reputation engine) +- A Hedera wallet (testnet or mainnet) + +### Setup + +1. **Clone the repository** + ```bash + git clone https://github.com/csking101/Sentinel-Protocol.git + cd Sentinel-Protocol + ``` + +2. **Frontend Setup** + ```bash + cd frontend + npm install + cp .env.example .env.local + # Edit .env.local with your Hedera configuration + npm run dev + ``` + + See [frontend/README.env.md](frontend/README.env.md) for detailed environment variable documentation. + +3. **Reputation Engine Setup** + ```bash + cd reputation_layer + pip install -r requirements.txt # Create this if needed + cp .env.example .env + # Edit .env with your API keys and Hedera wallet credentials + python engine.py + ``` + + See [reputation_layer/README.env.md](reputation_layer/README.env.md) for detailed environment variable documentation. + +## Environment Configuration + +This project uses the Hedera EVM-compatible network. You'll need to configure: + +- **Hedera Network**: Testnet (Chain ID: 296) or Mainnet (Chain ID: 295) +- **RPC Endpoint**: HashIO JSON-RPC Relay (https://testnet.hashio.io/api) +- **Smart Contract Addresses**: Deploy and configure your TokenReputation contract +- **API Keys**: CoinGecko, Covalent for reputation data +- **Wallet**: Hedera-compatible wallet with HBAR for gas fees + +Detailed setup instructions are available in: +- [frontend/README.env.md](frontend/README.env.md) +- [reputation_layer/README.env.md](reputation_layer/README.env.md) + +## Architecture + +- **Frontend**: Next.js application with MetaMask integration for Hedera EVM +- **Reputation Layer**: Python engine for calculating token reputation scores +- **Smart Contracts**: Solidity contracts deployed on Hedera EVM + +## Resources + +- [Hedera Documentation](https://docs.hedera.com/) +- [Hedera EVM Guide](https://docs.hedera.com/hedera/core-concepts/smart-contracts) +- [HashIO JSON-RPC Relay](https://docs.hedera.com/hedera/core-concepts/smart-contracts/json-rpc-relay) diff --git a/frontend/.env.example b/frontend/.env.example new file mode 100644 index 0000000..1f4f9cd --- /dev/null +++ b/frontend/.env.example @@ -0,0 +1,22 @@ +# Hedera EVM Network Configuration +# Use Hedera Testnet for development, Mainnet for production + +# Hedera Testnet +NEXT_PUBLIC_HEDERA_NETWORK=testnet +NEXT_PUBLIC_HEDERA_CHAIN_ID=296 +NEXT_PUBLIC_HEDERA_RPC_URL=https://testnet.hashio.io/api + +# Hedera Mainnet (uncomment for production) +# NEXT_PUBLIC_HEDERA_NETWORK=mainnet +# NEXT_PUBLIC_HEDERA_CHAIN_ID=295 +# NEXT_PUBLIC_HEDERA_RPC_URL=https://mainnet.hashio.io/api + +# Smart Contract Addresses (deploy your contracts and add addresses here) +NEXT_PUBLIC_TOKEN_REPUTATION_CONTRACT_ADDRESS= + +# Optional: WalletConnect Project ID (for WalletConnect integration) +# Get one at https://cloud.walletconnect.com +NEXT_PUBLIC_WALLETCONNECT_PROJECT_ID= + +# API Endpoints (if backend is separate) +NEXT_PUBLIC_API_URL=http://localhost:8000 diff --git a/frontend/README.env.md b/frontend/README.env.md new file mode 100644 index 0000000..fd75c9f --- /dev/null +++ b/frontend/README.env.md @@ -0,0 +1,77 @@ +# Environment Variables Setup + +This document explains how to set up environment variables for the Sentinel Protocol frontend. + +## Quick Start + +1. Copy the example environment file: + ```bash + cp .env.example .env.local + ``` + +2. Edit `.env.local` with your specific configuration values. + +## Configuration Variables + +### Hedera Network Configuration + +The frontend connects to the Hedera EVM-compatible network. You can use either testnet or mainnet: + +#### Testnet (Recommended for Development) +```env +NEXT_PUBLIC_HEDERA_NETWORK=testnet +NEXT_PUBLIC_HEDERA_CHAIN_ID=296 +NEXT_PUBLIC_HEDERA_RPC_URL=https://testnet.hashio.io/api +``` + +#### Mainnet (Production Only) +```env +NEXT_PUBLIC_HEDERA_NETWORK=mainnet +NEXT_PUBLIC_HEDERA_CHAIN_ID=295 +NEXT_PUBLIC_HEDERA_RPC_URL=https://mainnet.hashio.io/api +``` + +### Smart Contract Configuration + +After deploying your smart contracts, add the contract addresses: + +```env +NEXT_PUBLIC_TOKEN_REPUTATION_CONTRACT_ADDRESS=0x... +``` + +### Optional Configuration + +#### WalletConnect +If you want to support WalletConnect in addition to MetaMask: + +```env +NEXT_PUBLIC_WALLETCONNECT_PROJECT_ID=your_project_id_here +``` + +Get a free Project ID at: https://cloud.walletconnect.com + +#### API Backend +If running a separate backend API: + +```env +NEXT_PUBLIC_API_URL=http://localhost:8000 +``` + +## Important Notes + +- **Never commit `.env.local` or `.env` files to version control** - they contain sensitive information +- All `NEXT_PUBLIC_*` variables are exposed to the browser +- Do not store private keys or secrets in variables starting with `NEXT_PUBLIC_` +- The `.env.local` file takes precedence over `.env` in Next.js + +## Getting Hedera Testnet Tokens + +1. Visit the [Hedera Portal](https://portal.hedera.com/) +2. Create a testnet account +3. Fund your account with test HBAR using the testnet faucet + +## Resources + +- [Hedera EVM Documentation](https://docs.hedera.com/hedera/core-concepts/smart-contracts) +- [Next.js Environment Variables](https://nextjs.org/docs/app/building-your-application/configuring/environment-variables) +- [HashIO JSON-RPC Relay](https://docs.hedera.com/hedera/core-concepts/smart-contracts/json-rpc-relay) diff --git a/reputation_layer/.env.example b/reputation_layer/.env.example new file mode 100644 index 0000000..ffed03c --- /dev/null +++ b/reputation_layer/.env.example @@ -0,0 +1,34 @@ +# Hedera EVM Network Configuration +# Use Hedera Testnet for development, Mainnet for production + +# Hedera Testnet +RPC_URL=https://testnet.hashio.io/api +CHAIN_ID=296 + +# Hedera Mainnet (uncomment for production) +# RPC_URL=https://mainnet.hashio.io/api +# CHAIN_ID=295 + +# Smart Contract Configuration +CONTRACT_ADDRESS= +ABI_PATH=TokenReputationABI.json + +# Wallet Configuration (KEEP PRIVATE - DO NOT COMMIT) +# Generate a new wallet for testnet at: https://portal.hedera.com/ +PRIVATE_KEY= +OWNER_ADDRESS= + +# API Keys for Data Sources +# CoinGecko API (https://www.coingecko.com/en/api) +COINGECKO_API_KEY= + +# Etherscan API (not needed for Hedera, but kept for compatibility) +ETHERSCAN_API_KEY= + +# Covalent API (https://www.covalenthq.com/) +COVALENT_API_KEY= + +# Rate Limiting Configuration +API_DELAY=1.0 +MAX_RETRIES=3 +RETRY_DELAY=2.0 diff --git a/reputation_layer/README.env.md b/reputation_layer/README.env.md new file mode 100644 index 0000000..798b55b --- /dev/null +++ b/reputation_layer/README.env.md @@ -0,0 +1,132 @@ +# Environment Variables Setup + +This document explains how to set up environment variables for the Sentinel Protocol reputation engine. + +## Quick Start + +1. Copy the example environment file: + ```bash + cp .env.example .env + ``` + +2. Edit `.env` with your specific configuration values. + +## Required Configuration + +### Hedera Network Configuration + +Configure the connection to Hedera's EVM-compatible network: + +#### Testnet (Recommended for Development) +```env +RPC_URL=https://testnet.hashio.io/api +CHAIN_ID=296 +``` + +#### Mainnet (Production Only) +```env +RPC_URL=https://mainnet.hashio.io/api +CHAIN_ID=295 +``` + +### Smart Contract Configuration + +```env +CONTRACT_ADDRESS=0x... # Your deployed TokenReputation contract address +ABI_PATH=TokenReputationABI.json # Path to the contract ABI file +``` + +### Wallet Configuration + +⚠️ **CRITICAL**: Never commit these values or share them publicly! + +```env +PRIVATE_KEY=0x... # Your wallet's private key (with 0x prefix) +OWNER_ADDRESS=0x... # Your wallet's public address +``` + +**Getting a Hedera Wallet:** +1. Visit [Hedera Portal](https://portal.hedera.com/) +2. Create a testnet account +3. Get test HBAR from the faucet +4. Export your private key (keep it secure!) + +### API Keys for Data Sources + +The reputation engine fetches data from multiple sources: + +#### CoinGecko API +```env +COINGECKO_API_KEY=your_api_key_here +``` +Get a free API key at: https://www.coingecko.com/en/api + +#### Covalent API +```env +COVALENT_API_KEY=your_api_key_here +``` +Get a free API key at: https://www.covalenthq.com/ + +#### Etherscan API (Optional) +```env +ETHERSCAN_API_KEY=your_api_key_here +``` +Currently not required for Hedera network operations. + +### Rate Limiting Configuration + +Control API request behavior: + +```env +API_DELAY=1.0 # Delay between API requests in seconds +MAX_RETRIES=3 # Maximum number of retry attempts +RETRY_DELAY=2.0 # Delay between retries in seconds +``` + +## Running the Scripts + +### Calculate Reputation Scores +```bash +python engine.py +``` + +### Sync Scores to Blockchain +```bash +python sync_reputation_to_chain.py +``` + +## Security Best Practices + +1. **Never commit `.env` files** - they are already in `.gitignore` +2. **Use environment-specific .env files**: + - `.env.development` for local development + - `.env.production` for production +3. **Use separate wallets**: + - Testnet wallet for development + - Mainnet wallet with minimal funds for production +4. **Rotate API keys regularly** +5. **Use read-only keys where possible** + +## Troubleshooting + +### Connection Issues +- Verify RPC_URL is correct and accessible +- Check that CHAIN_ID matches the network (296 for testnet, 295 for mainnet) +- Ensure your wallet has sufficient HBAR for gas fees + +### Transaction Failures +- Check that PRIVATE_KEY and OWNER_ADDRESS match +- Verify contract address is correct +- Ensure wallet has sufficient HBAR balance +- Check that the ABI file exists and is valid JSON + +### API Rate Limiting +- Increase API_DELAY if you're hitting rate limits +- Consider upgrading to paid API tiers for higher limits + +## Resources + +- [Hedera EVM Documentation](https://docs.hedera.com/hedera/core-concepts/smart-contracts) +- [HashIO JSON-RPC Relay](https://docs.hedera.com/hedera/core-concepts/smart-contracts/json-rpc-relay) +- [Python-dotenv Documentation](https://pypi.org/project/python-dotenv/) +- [Web3.py Documentation](https://web3py.readthedocs.io/) From 3a3e3f8f6007011ade3b3a97298042411c505386 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Wed, 22 Oct 2025 10:33:46 +0000 Subject: [PATCH 3/4] Add Hedera utilities and validation tools Co-authored-by: AbhishekSatpathy4848 <108116233+AbhishekSatpathy4848@users.noreply.github.com> --- frontend/README.env.md | 22 +++ frontend/src/lib/hedera.js | 209 +++++++++++++++++++++++ reputation_layer/README.env.md | 14 ++ reputation_layer/requirements.txt | 10 ++ reputation_layer/validate_config.py | 249 ++++++++++++++++++++++++++++ 5 files changed, 504 insertions(+) create mode 100644 frontend/src/lib/hedera.js create mode 100644 reputation_layer/requirements.txt create mode 100644 reputation_layer/validate_config.py diff --git a/frontend/README.env.md b/frontend/README.env.md index fd75c9f..c4addcc 100644 --- a/frontend/README.env.md +++ b/frontend/README.env.md @@ -70,6 +70,28 @@ NEXT_PUBLIC_API_URL=http://localhost:8000 2. Create a testnet account 3. Fund your account with test HBAR using the testnet faucet +## Using the Hedera Utilities + +The project includes a utility library at `src/lib/hedera.js` that provides: + +- Network configuration (testnet/mainnet) +- Automatic network switching in MetaMask +- Wallet connection helpers +- Event listeners for account/network changes + +Example usage: + +```javascript +import { connectWallet, switchToHederaNetwork } from '@/lib/hedera'; + +// Connect wallet and ensure correct network +const { address, isCorrectNetwork } = await connectWallet(); + +if (!isCorrectNetwork) { + alert('Please switch to Hedera network'); +} +``` + ## Resources - [Hedera EVM Documentation](https://docs.hedera.com/hedera/core-concepts/smart-contracts) diff --git a/frontend/src/lib/hedera.js b/frontend/src/lib/hedera.js new file mode 100644 index 0000000..62dfc13 --- /dev/null +++ b/frontend/src/lib/hedera.js @@ -0,0 +1,209 @@ +/** + * Hedera EVM Network Configuration + * + * This module provides configuration and utilities for connecting to + * the Hedera EVM-compatible network. + */ + +// Network configurations +export const HEDERA_NETWORKS = { + testnet: { + chainId: '0x128', // 296 in hex + chainIdDecimal: 296, + chainName: 'Hedera Testnet', + nativeCurrency: { + name: 'HBAR', + symbol: 'HBAR', + decimals: 18, + }, + rpcUrls: [process.env.NEXT_PUBLIC_HEDERA_RPC_URL || 'https://testnet.hashio.io/api'], + blockExplorerUrls: ['https://hashscan.io/testnet'], + }, + mainnet: { + chainId: '0x127', // 295 in hex + chainIdDecimal: 295, + chainName: 'Hedera Mainnet', + nativeCurrency: { + name: 'HBAR', + symbol: 'HBAR', + decimals: 18, + }, + rpcUrls: [process.env.NEXT_PUBLIC_HEDERA_RPC_URL || 'https://mainnet.hashio.io/api'], + blockExplorerUrls: ['https://hashscan.io/mainnet'], + }, +}; + +// Get current network from environment +export const getCurrentNetwork = () => { + const network = process.env.NEXT_PUBLIC_HEDERA_NETWORK || 'testnet'; + return HEDERA_NETWORKS[network]; +}; + +// Get chain ID from environment +export const getChainId = () => { + return process.env.NEXT_PUBLIC_HEDERA_CHAIN_ID || '296'; +}; + +// Get RPC URL from environment +export const getRpcUrl = () => { + return process.env.NEXT_PUBLIC_HEDERA_RPC_URL || 'https://testnet.hashio.io/api'; +}; + +// Get contract addresses +export const getContractAddress = (contractName) => { + const addresses = { + tokenReputation: process.env.NEXT_PUBLIC_TOKEN_REPUTATION_CONTRACT_ADDRESS, + }; + return addresses[contractName]; +}; + +/** + * Switch to Hedera network in MetaMask + * @returns {Promise} true if successful, false otherwise + */ +export const switchToHederaNetwork = async () => { + if (typeof window.ethereum === 'undefined') { + console.error('MetaMask is not installed'); + return false; + } + + const network = getCurrentNetwork(); + + try { + // Try to switch to the network + await window.ethereum.request({ + method: 'wallet_switchEthereumChain', + params: [{ chainId: network.chainId }], + }); + return true; + } catch (switchError) { + // This error code indicates that the chain has not been added to MetaMask + if (switchError.code === 4902) { + try { + // Add the network to MetaMask + await window.ethereum.request({ + method: 'wallet_addEthereumChain', + params: [network], + }); + return true; + } catch (addError) { + console.error('Failed to add Hedera network:', addError); + return false; + } + } + console.error('Failed to switch to Hedera network:', switchError); + return false; + } +}; + +/** + * Check if user is on the correct Hedera network + * @returns {Promise} + */ +export const isOnHederaNetwork = async () => { + if (typeof window.ethereum === 'undefined') { + return false; + } + + try { + const chainId = await window.ethereum.request({ method: 'eth_chainId' }); + const expectedChainId = getCurrentNetwork().chainId; + return chainId === expectedChainId; + } catch (error) { + console.error('Error checking network:', error); + return false; + } +}; + +/** + * Connect wallet and ensure it's on the correct network + * @returns {Promise<{address: string, isCorrectNetwork: boolean}>} + */ +export const connectWallet = async () => { + if (typeof window.ethereum === 'undefined') { + throw new Error('Please install MetaMask to use this application'); + } + + try { + // Request account access + const accounts = await window.ethereum.request({ + method: 'eth_requestAccounts', + }); + + // Check if on correct network + const correctNetwork = await isOnHederaNetwork(); + + if (!correctNetwork) { + // Try to switch to correct network + const switched = await switchToHederaNetwork(); + return { + address: accounts[0], + isCorrectNetwork: switched, + }; + } + + return { + address: accounts[0], + isCorrectNetwork: true, + }; + } catch (error) { + console.error('Error connecting wallet:', error); + throw error; + } +}; + +/** + * Format address for display (0x1234...5678) + * @param {string} address + * @param {number} startChars + * @param {number} endChars + * @returns {string} + */ +export const formatAddress = (address, startChars = 6, endChars = 4) => { + if (!address) return ''; + return `${address.slice(0, startChars)}...${address.slice(-endChars)}`; +}; + +/** + * Listen for network changes + * @param {Function} callback - Called when network changes + * @returns {Function} - Cleanup function + */ +export const onNetworkChange = (callback) => { + if (typeof window.ethereum === 'undefined') { + return () => {}; + } + + const handleChainChanged = (chainId) => { + callback(chainId); + }; + + window.ethereum.on('chainChanged', handleChainChanged); + + // Return cleanup function + return () => { + window.ethereum.removeListener('chainChanged', handleChainChanged); + }; +}; + +/** + * Listen for account changes + * @param {Function} callback - Called when accounts change + * @returns {Function} - Cleanup function + */ +export const onAccountChange = (callback) => { + if (typeof window.ethereum === 'undefined') { + return () => {}; + } + + const handleAccountsChanged = (accounts) => { + callback(accounts[0] || null); + }; + + window.ethereum.on('accountsChanged', handleAccountsChanged); + + // Return cleanup function + return () => { + window.ethereum.removeListener('accountsChanged', handleAccountsChanged); + }; +}; diff --git a/reputation_layer/README.env.md b/reputation_layer/README.env.md index 798b55b..c51872c 100644 --- a/reputation_layer/README.env.md +++ b/reputation_layer/README.env.md @@ -83,6 +83,20 @@ MAX_RETRIES=3 # Maximum number of retry attempts RETRY_DELAY=2.0 # Delay between retries in seconds ``` +## Validating Your Configuration + +Before running the main scripts, validate your configuration: + +```bash +python validate_config.py +``` + +This script will: +- ✓ Check that all required environment variables are set +- ✓ Test connection to the Hedera network +- ✓ Verify your contract configuration +- ✓ Validate your wallet setup (if configured) + ## Running the Scripts ### Calculate Reputation Scores diff --git a/reputation_layer/requirements.txt b/reputation_layer/requirements.txt new file mode 100644 index 0000000..f11aa49 --- /dev/null +++ b/reputation_layer/requirements.txt @@ -0,0 +1,10 @@ +# Core dependencies +web3>=6.0.0 +pandas>=2.0.0 +numpy>=1.24.0 +requests>=2.31.0 +python-dotenv>=1.0.0 + +# Optional: For enhanced functionality +# eth-account>=0.9.0 # Included with web3 +# eth-typing>=3.0.0 # Included with web3 diff --git a/reputation_layer/validate_config.py b/reputation_layer/validate_config.py new file mode 100644 index 0000000..abd4e7b --- /dev/null +++ b/reputation_layer/validate_config.py @@ -0,0 +1,249 @@ +#!/usr/bin/env python3 +""" +Configuration Validation Script for Sentinel Protocol + +This script validates that all required environment variables are set +and that the Hedera network connection is working properly. +""" + +import os +import sys +from dotenv import load_dotenv +from web3 import Web3 +import json + +def validate_env_vars(): + """Validate that all required environment variables are set.""" + print("=" * 60) + print("Environment Variables Validation") + print("=" * 60) + + required_vars = { + "RPC_URL": "Hedera RPC endpoint URL", + "CONTRACT_ADDRESS": "TokenReputation contract address", + "ABI_PATH": "Path to contract ABI file", + } + + optional_vars = { + "PRIVATE_KEY": "Wallet private key (needed for transactions)", + "OWNER_ADDRESS": "Wallet public address (needed for transactions)", + "COINGECKO_API_KEY": "CoinGecko API key", + "COVALENT_API_KEY": "Covalent API key", + "ETHERSCAN_API_KEY": "Etherscan API key", + "API_DELAY": "API request delay", + "MAX_RETRIES": "Maximum retry attempts", + "RETRY_DELAY": "Delay between retries", + } + + all_good = True + + print("\n✓ Required Variables:") + for var, description in required_vars.items(): + value = os.getenv(var) + if value: + # Mask sensitive values + display_value = value if len(value) < 20 else f"{value[:10]}...{value[-4:]}" + print(f" ✓ {var}: {display_value}") + else: + print(f" ✗ {var}: NOT SET - {description}") + all_good = False + + print("\n⚠ Optional Variables:") + for var, description in optional_vars.items(): + value = os.getenv(var) + if value: + display_value = value if len(value) < 20 or var in ["API_DELAY", "MAX_RETRIES", "RETRY_DELAY"] else f"{value[:10]}...{value[-4:]}" + print(f" ✓ {var}: {display_value}") + else: + print(f" - {var}: Not set - {description}") + + return all_good + +def validate_network_connection(): + """Validate connection to Hedera network.""" + print("\n" + "=" * 60) + print("Network Connection Validation") + print("=" * 60) + + rpc_url = os.getenv("RPC_URL") + if not rpc_url: + print("✗ Cannot test network connection: RPC_URL not set") + return False + + try: + print(f"\nConnecting to: {rpc_url}") + w3 = Web3(Web3.HTTPProvider(rpc_url)) + + if not w3.is_connected(): + print("✗ Failed to connect to network") + return False + + print("✓ Successfully connected to network") + + # Get network information + chain_id = w3.eth.chain_id + print(f"✓ Chain ID: {chain_id}") + + if chain_id == 296: + print("✓ Network: Hedera Testnet") + elif chain_id == 295: + print("✓ Network: Hedera Mainnet") + else: + print(f"⚠ Warning: Unknown Chain ID {chain_id}") + + # Get latest block + try: + latest_block = w3.eth.block_number + print(f"✓ Latest block: {latest_block}") + except Exception as e: + print(f"⚠ Could not fetch latest block: {e}") + + return True + + except Exception as e: + print(f"✗ Connection error: {e}") + return False + +def validate_contract(): + """Validate contract configuration.""" + print("\n" + "=" * 60) + print("Contract Configuration Validation") + print("=" * 60) + + contract_address = os.getenv("CONTRACT_ADDRESS") + abi_path = os.getenv("ABI_PATH") + rpc_url = os.getenv("RPC_URL") + + if not all([contract_address, abi_path, rpc_url]): + print("✗ Missing required configuration") + return False + + try: + # Check if ABI file exists + if not os.path.exists(abi_path): + print(f"✗ ABI file not found: {abi_path}") + return False + + print(f"✓ ABI file found: {abi_path}") + + # Load ABI + with open(abi_path, 'r') as f: + abi = json.load(f) + + print(f"✓ ABI file is valid JSON with {len(abi)} entries") + + # Connect to contract + w3 = Web3(Web3.HTTPProvider(rpc_url)) + if not w3.is_connected(): + print("✗ Cannot connect to network") + return False + + checksum_address = Web3.to_checksum_address(contract_address) + print(f"✓ Contract address (checksum): {checksum_address}") + + contract = w3.eth.contract(address=checksum_address, abi=abi) + print("✓ Contract instance created successfully") + + # Try to get code at address + code = w3.eth.get_code(checksum_address) + if code == b'' or code == '0x': + print("⚠ Warning: No code found at contract address (contract may not be deployed)") + else: + print(f"✓ Contract code found (size: {len(code)} bytes)") + + return True + + except Exception as e: + print(f"✗ Contract validation error: {e}") + return False + +def validate_wallet(): + """Validate wallet configuration (if provided).""" + print("\n" + "=" * 60) + print("Wallet Configuration Validation") + print("=" * 60) + + private_key = os.getenv("PRIVATE_KEY") + owner_address = os.getenv("OWNER_ADDRESS") + rpc_url = os.getenv("RPC_URL") + + if not private_key or not owner_address: + print("⚠ Wallet credentials not set (required for transactions)") + return True # Not an error, just a warning + + try: + w3 = Web3(Web3.HTTPProvider(rpc_url)) + if not w3.is_connected(): + print("✗ Cannot connect to network") + return False + + # Validate address format + checksum_address = Web3.to_checksum_address(owner_address) + print(f"✓ Wallet address (checksum): {checksum_address}") + + # Check wallet balance + balance = w3.eth.get_balance(checksum_address) + balance_hbar = w3.from_wei(balance, 'ether') # HBAR uses same decimals as ETH + print(f"✓ Wallet balance: {balance_hbar} HBAR") + + if balance == 0: + print("⚠ Warning: Wallet has zero balance (cannot send transactions)") + + # Validate private key matches address (without exposing the key) + try: + account = w3.eth.account.from_key(private_key) + if account.address.lower() == owner_address.lower(): + print("✓ Private key matches owner address") + else: + print("✗ Private key does NOT match owner address") + return False + except Exception as e: + print(f"✗ Invalid private key format: {e}") + return False + + return True + + except Exception as e: + print(f"✗ Wallet validation error: {e}") + return False + +def main(): + """Main validation function.""" + print("\n" + "=" * 60) + print("Sentinel Protocol Configuration Validator") + print("=" * 60) + + # Load environment variables + load_dotenv() + + # Run validations + results = { + "Environment Variables": validate_env_vars(), + "Network Connection": validate_network_connection(), + "Contract Configuration": validate_contract(), + "Wallet Configuration": validate_wallet(), + } + + # Summary + print("\n" + "=" * 60) + print("Validation Summary") + print("=" * 60) + + all_passed = True + for test, passed in results.items(): + status = "✓ PASSED" if passed else "✗ FAILED" + print(f"{test}: {status}") + if not passed: + all_passed = False + + print("=" * 60) + + if all_passed: + print("\n✓ All validations passed! Your configuration is ready.") + return 0 + else: + print("\n✗ Some validations failed. Please check the output above and fix the issues.") + return 1 + +if __name__ == "__main__": + sys.exit(main()) From 33c740540091c1cf20e267cdeaaa25e86408639d Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Wed, 22 Oct 2025 10:36:59 +0000 Subject: [PATCH 4/4] Add comprehensive Hedera EVM setup guide Co-authored-by: AbhishekSatpathy4848 <108116233+AbhishekSatpathy4848@users.noreply.github.com> --- HEDERA_SETUP.md | 325 ++++++++++++++++++++++++++++++++++++++++++++++++ README.md | 8 +- 2 files changed, 330 insertions(+), 3 deletions(-) create mode 100644 HEDERA_SETUP.md diff --git a/HEDERA_SETUP.md b/HEDERA_SETUP.md new file mode 100644 index 0000000..2c86978 --- /dev/null +++ b/HEDERA_SETUP.md @@ -0,0 +1,325 @@ +# Hedera EVM Setup Guide for Sentinel Protocol + +This guide walks you through setting up the Sentinel Protocol to work with Hedera's EVM-compatible network. + +## What is Hedera EVM? + +Hedera is a public distributed ledger that supports EVM-compatible smart contracts through its JSON-RPC relay service. This allows you to use familiar Ethereum tools (MetaMask, Web3.js, Ethers.js) while benefiting from Hedera's: + +- ⚡ High throughput (10,000+ TPS) +- 💰 Low, predictable fees +- 🔒 Enterprise-grade security +- 🌍 Carbon-negative network + +## Quick Start + +### 1. Get a Hedera Wallet + +**For Testnet (Development):** +1. Visit [Hedera Portal](https://portal.hedera.com/) +2. Create a testnet account +3. Fund your account with test HBAR from the faucet +4. Export your private key (keep it secure!) + +**For Mainnet (Production):** +1. Use a compatible wallet like MetaMask +2. Purchase HBAR from an exchange +3. Transfer HBAR to your wallet + +### 2. Configure Frontend + +```bash +cd frontend +cp .env.example .env.local +``` + +Edit `.env.local`: +```env +# For Testnet +NEXT_PUBLIC_HEDERA_NETWORK=testnet +NEXT_PUBLIC_HEDERA_CHAIN_ID=296 +NEXT_PUBLIC_HEDERA_RPC_URL=https://testnet.hashio.io/api + +# Add your contract address after deployment +NEXT_PUBLIC_TOKEN_REPUTATION_CONTRACT_ADDRESS=0x... +``` + +### 3. Configure Backend (Reputation Layer) + +```bash +cd reputation_layer +cp .env.example .env +``` + +Edit `.env`: +```env +# Network +RPC_URL=https://testnet.hashio.io/api +CHAIN_ID=296 + +# Contract +CONTRACT_ADDRESS=0x... +ABI_PATH=TokenReputationABI.json + +# Your wallet (KEEP PRIVATE!) +PRIVATE_KEY=0x... +OWNER_ADDRESS=0x... + +# API Keys +COINGECKO_API_KEY=your_key +COVALENT_API_KEY=your_key +``` + +### 4. Install Dependencies + +**Frontend:** +```bash +cd frontend +npm install +``` + +**Backend:** +```bash +cd reputation_layer +pip install -r requirements.txt +``` + +### 5. Validate Configuration + +```bash +cd reputation_layer +python validate_config.py +``` + +This will check: +- ✓ All environment variables are set +- ✓ Network connection is working +- ✓ Contract is accessible +- ✓ Wallet is configured correctly + +## Network Information + +### Hedera Testnet +- **Chain ID**: 296 (0x128) +- **RPC URL**: https://testnet.hashio.io/api +- **Explorer**: https://hashscan.io/testnet +- **Faucet**: Available at Hedera Portal +- **Currency**: HBAR (test) + +### Hedera Mainnet +- **Chain ID**: 295 (0x127) +- **RPC URL**: https://mainnet.hashio.io/api +- **Explorer**: https://hashscan.io/mainnet +- **Currency**: HBAR + +## Adding Hedera to MetaMask + +The frontend automatically prompts users to add the Hedera network, but you can also add it manually: + +1. Open MetaMask +2. Click on the network dropdown +3. Click "Add Network" +4. Enter the following details: + +**For Testnet:** +- Network Name: `Hedera Testnet` +- RPC URL: `https://testnet.hashio.io/api` +- Chain ID: `296` +- Currency Symbol: `HBAR` +- Block Explorer: `https://hashscan.io/testnet` + +**For Mainnet:** +- Network Name: `Hedera Mainnet` +- RPC URL: `https://mainnet.hashio.io/api` +- Chain ID: `295` +- Currency Symbol: `HBAR` +- Block Explorer: `https://hashscan.io/mainnet` + +## Deploying Smart Contracts + +### Prerequisites +- Solidity compiler (solc) +- Hardhat or Foundry (optional, for easier deployment) +- HBAR in your wallet for gas fees + +### Using Remix IDE + +1. Go to [Remix IDE](https://remix.ethereum.org/) +2. Load your contract (`TokenReputationContract.sol`) +3. Compile the contract +4. Go to "Deploy & Run Transactions" +5. Select "Injected Provider - MetaMask" +6. Ensure MetaMask is on Hedera network +7. Deploy the contract +8. Copy the contract address +9. Update your `.env` files with the contract address + +### Using Hardhat + +```javascript +// hardhat.config.js +module.exports = { + networks: { + hederaTestnet: { + url: "https://testnet.hashio.io/api", + chainId: 296, + accounts: [process.env.PRIVATE_KEY] + } + } +}; +``` + +Deploy: +```bash +npx hardhat run scripts/deploy.js --network hederaTestnet +``` + +## Frontend Integration + +The frontend includes a Hedera utility library at `src/lib/hedera.js`: + +```javascript +import { + connectWallet, + switchToHederaNetwork, + getCurrentNetwork, + formatAddress +} from '@/lib/hedera'; + +// Connect wallet +const { address, isCorrectNetwork } = await connectWallet(); + +// Switch network if needed +if (!isCorrectNetwork) { + await switchToHederaNetwork(); +} +``` + +## Backend Usage + +### Calculate Reputation Scores + +```bash +cd reputation_layer +python engine.py +``` + +This will: +1. Fetch token data from CoinGecko, Covalent +2. Calculate reputation scores +3. Save results to `reputation_scores.csv` + +### Sync to Blockchain + +```bash +python sync_reputation_to_chain.py +``` + +This will: +1. Read reputation scores from CSV +2. Connect to Hedera network +3. Submit transactions to update the smart contract +4. Display transaction results + +## Troubleshooting + +### Connection Issues + +**Problem**: Cannot connect to Hedera network + +**Solutions**: +- Check RPC URL is correct +- Verify internet connection +- Try alternative RPC endpoints if available +- Check if Hedera network is operational at [status.hedera.com](https://status.hedera.com/) + +### Transaction Failures + +**Problem**: Transactions fail or revert + +**Solutions**: +- Ensure wallet has sufficient HBAR for gas +- Check that contract address is correct +- Verify private key matches owner address +- Check gas limit is sufficient +- Review contract function parameters + +### Wrong Network + +**Problem**: MetaMask is on wrong network + +**Solutions**: +- Use the frontend's automatic network switching +- Manually switch in MetaMask +- Check NEXT_PUBLIC_HEDERA_CHAIN_ID matches network + +### API Rate Limiting + +**Problem**: API requests being rate limited + +**Solutions**: +- Increase API_DELAY in `.env` +- Upgrade to paid API tier +- Implement caching for repeated requests + +## Cost Estimation + +### Testnet +- **All operations are FREE** - use test HBAR from faucet + +### Mainnet +- **Transactions**: ~$0.01-0.05 per transaction +- **Contract Deployment**: ~$1-5 depending on contract size +- **Contract Interactions**: ~$0.01-0.10 per function call + +Note: Hedera fees are significantly lower than Ethereum mainnet! + +## Security Best Practices + +1. **Never commit `.env` files** - they contain sensitive data +2. **Use different wallets for testnet and mainnet** +3. **Keep minimal funds in hot wallets** +4. **Regularly rotate API keys** +5. **Use environment-specific configuration files** +6. **Validate all inputs before sending transactions** +7. **Test thoroughly on testnet before mainnet deployment** + +## Resources + +### Official Documentation +- [Hedera Documentation](https://docs.hedera.com/) +- [Smart Contracts on Hedera](https://docs.hedera.com/hedera/core-concepts/smart-contracts) +- [JSON-RPC Relay](https://docs.hedera.com/hedera/core-concepts/smart-contracts/json-rpc-relay) +- [Hedera Portal](https://portal.hedera.com/) + +### Developer Tools +- [HashScan Explorer](https://hashscan.io/) +- [Hedera SDK for JavaScript](https://github.com/hashgraph/hedera-sdk-js) +- [Remix IDE](https://remix.ethereum.org/) + +### Community +- [Hedera Discord](https://hedera.com/discord) +- [Hedera GitHub](https://github.com/hashgraph) +- [Developer Forum](https://hedera.com/discord) + +## Support + +If you encounter issues: +1. Check this guide and the READMEs +2. Run `validate_config.py` to diagnose configuration issues +3. Check the [Hedera documentation](https://docs.hedera.com/) +4. Ask in the [Hedera Discord](https://hedera.com/discord) +5. Open an issue on this repository + +## Next Steps + +1. ✓ Complete environment setup +2. ✓ Validate configuration +3. Deploy smart contracts to testnet +4. Test frontend wallet connection +5. Run reputation engine +6. Sync data to blockchain +7. Test end-to-end flow +8. Deploy to mainnet (when ready) + +Happy building on Hedera! 🚀 diff --git a/README.md b/README.md index 35b9c1a..4f6a5fd 100644 --- a/README.md +++ b/README.md @@ -53,9 +53,11 @@ This project uses the Hedera EVM-compatible network. You'll need to configure: - **API Keys**: CoinGecko, Covalent for reputation data - **Wallet**: Hedera-compatible wallet with HBAR for gas fees -Detailed setup instructions are available in: -- [frontend/README.env.md](frontend/README.env.md) -- [reputation_layer/README.env.md](reputation_layer/README.env.md) +📚 **Complete Setup Guide**: See [HEDERA_SETUP.md](HEDERA_SETUP.md) for a comprehensive guide to getting started with Hedera EVM. + +Detailed configuration documentation: +- [frontend/README.env.md](frontend/README.env.md) - Frontend environment variables +- [reputation_layer/README.env.md](reputation_layer/README.env.md) - Backend environment variables ## Architecture