================================================================================ CARBONCORE DEVELOPER GUIDE #03 TOKEN MANAGEMENT SYSTEM ================================================================================ PRINCIPLE: Scan ALL platform tokens in user wallet, not just owned projects ================================================================================ TOKENMANAGER ARCHITECTURE ================================================================================ Class: TokenManager Location: js/token-management.js Core Properties: tokens: [] - Array of user's token holdings totalBalance: 0 - Total balance across all tokens territories: [] - Related territory data Key Methods: init() - Main initialization loadUserTokens() - Scan wallet for ALL platform tokens renderTokens() - Display token cards updateStats() - Update statistics ================================================================================ INITIALIZATION FLOW ================================================================================ Step 1: Authentication Check Check: sessionStorage.getItem('walletAddress') Check: sessionStorage.getItem('userTokenId') Result: walletConnected, hasNFT status Step 2: Wallet Connection If no wallet: Display: "Connect Wallet" message Return: Exit initialization Step 3: UID Verification If no UID: Display: "Create Profile" message Return: Exit initialization Step 4: Token Scanning Call: loadUserTokens(walletAddress) Process: Scan ALL platform projects (1-200) Result: Array of tokens with balances ================================================================================ TOKEN SCANNING ALGORITHM ================================================================================ Function: findAllPlatformTokensInWallet() Process: FOR projectId = 1 TO 200: TRY: 1. Get project from CarbonCreditFactory 2. Check project.active == true 3. Check project.tokenAddress != 0x0 4. Check user balance > 0 5. If balance > 0: Add to results CATCH: - Continue if project doesn't exist - Stop if 50+ consecutive failures Output: Array of { projectId, territoryId, vintageYear, tokenAddress, balance, dailyRate, co2AbsorptionRate } Key Feature: Finds tokens from ANY project, not just user-owned territories ================================================================================ TOKEN DATA STRUCTURE ================================================================================ Token Object: { projectId: "1", territoryId: "24", territoryName: "Amazon Conservation Alpha", territoryType: "Forest", territoryArea: 15000, tokenAddress: "0x...", tokenSymbol: "CCT24-2025", vintageYear: "2025", balance: "257534.247", totalSupply: "94000000", dailyRate: "257534.247", co2AbsorptionRate: "94000000", boundary: { /* GeoJSON */ } } ================================================================================ TOKEN CARD DISPLAY ================================================================================ Card Components: 1. Header - Territory name - Token symbol + Vintage year 2. Mini-Map - Territory boundary visualization - Leaflet.js integration 3. Details - Territory Type - Area (formatted) - Daily Rate - Total Supply 4. Balance Display - Your Balance (large) - Estimated Value ($10/token) 5. Actions - View in MetaMask - Copy Address - Territory Details - View on Etherscan ================================================================================ METAMASK INTEGRATION ================================================================================ Function: viewInMetaMask(tokenAddress) Process: 1. Call window.ethereum.request() 2. Method: 'wallet_watchAsset' 3. Parameters: type: 'ERC20' address: tokenAddress symbol: tokenSymbol decimals: 18 image: CarbonCore logo URL Result: Token appears in MetaMask wallet Function: copyTokenAddress(tokenAddress) 1. Copy to clipboard 2. Show success notification Function: viewOnExplorer(tokenAddress) URL: https://sepolia.etherscan.io/token/{tokenAddress} ================================================================================ TERRITORY DETAILS INTEGRATION ================================================================================ Function: showTerritoryDetails(territoryId) Process: 1. Find token with matching territoryId 2. Create temporary territory data if not in global state 3. Call window.TerritoryDetailsService.showDetails(territoryId) 4. Universal details modal opens with: - General Info tab - Tokens tab - Verification tab - Standards & Insurance tab ================================================================================ TOKEN BALANCE CHECKING ================================================================================ Function: checkTokenBalance(tokenAddress, walletAddress, provider) Code: const tokenABI = [ "function balanceOf(address) view returns (uint256)" ]; const token = new ethers.Contract(tokenAddress, tokenABI, provider); const balance = await token.balanceOf(walletAddress); Return: Balance in wei (BigNumber) Format for Display: const formatted = ethers.utils.formatEther(balance); const display = parseFloat(formatted).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }); ================================================================================ STATISTICS CALCULATION ================================================================================ Function: updateStats() Metrics: 1. Total Tokens Held Sum of all token balances 2. Total Projects Count of unique tokens 3. Estimated Value totalBalance * $10 per token 4. Territory Types Unique count of territory types Display: Updated in dashboard summary cards ================================================================================ ERROR HANDLING ================================================================================ No Wallet Connected: Display: "Please connect your Web3 wallet" Action: Show wallet connection button No UID Profile: Display: "Create your profile to continue" Action: Redirect to profile creation No Tokens Found: Display: "No tokens found in wallet" Suggestion: "Register territories and create projects" Action: Link to territory registration Loading Error: Display: Error message with details Action: Retry button Log: Full error trace to console ================================================================================ MINI-MAP INITIALIZATION ================================================================================ Function: initializeMiniMaps() Process: FOR each token with boundary data: 1. Create Leaflet map in container 2. Add OpenStreetMap tile layer 3. Parse GeoJSON boundary 4. Add polygon to map 5. Fit bounds to polygon 6. Disable interactions Timeout: 100ms after render (DOM ready) Map Configuration: zoom: Auto (fitBounds) scrollWheelZoom: false dragging: false zoomControl: false attributionControl: true ================================================================================ TOKEN FILTERING AND SORTING ================================================================================ Filter Options: - By Territory Type (Forest, Wetland, etc.) - By Vintage Year - By Balance (>0, >100, >1000) - By Project Status Sort Options: - By Balance (High to Low) - By Daily Rate (High to Low) - By Territory Name (A-Z) - By Vintage Year (Newest first) Implementation: Client-side JavaScript filtering ================================================================================ PERFORMANCE OPTIMIZATION ================================================================================ Caching: - Token decimals cached for 1 hour - Territory data cached in global state - Provider reused across calls Batch Loading: - Check 20 projects per batch - Max 3 concurrent batches - Adaptive delays (100-200ms) Early Termination: - Stop after 50 consecutive failed project IDs - Max 200 projects scanned Memory Management: - Clear old cache entries - Limit map instances - Dispose unused contracts ================================================================================ INTEGRATION POINTS ================================================================================ 1. Territory Management Event: "List for Sale" button Action: Navigate to OTC marketplace with pre-filled data 2. OTC Marketplace Event: Token selection for sale Data: Token address, balance, territory info 3. Dashboard Widget: Active tokens summary Metrics: Count, value, recent changes 4. Profile Page Section: Token holdings overview Link: Full token management page ================================================================================