================================================================================ CARBONCORE DEVELOPER GUIDE #09 DEVELOPMENT RULES & BEST PRACTICES ================================================================================ CRITICAL: These rules are MANDATORY for all development work ================================================================================ PROHIBITION #1: #НикакихLocalStorage ================================================================================ RULE: ABSOLUTELY NO browser storage APIs Forbidden: ❌ localStorage.setItem() ❌ sessionStorage.setItem() ❌ IndexedDB ❌ Web Storage API ❌ Cookies for state storage Reason: - Platform runs on AWS with multiple workstations - Data must be accessible across devices - Browser storage is device-specific - Violates multi-device architecture Alternatives: ✅ Server-side storage (database) ✅ JWT tokens for authentication ✅ In-memory state (JavaScript variables) ✅ URL parameters for temporary state ✅ Smart contract storage (blockchain) Example Violation: ❌ BAD: localStorage.setItem('userToken', token); const saved = localStorage.getItem('territoryData'); Example Compliance: ✅ GOOD: // Store in memory window.userState = { token, data }; // Store on server await saveToDatabase(data); // Store on blockchain await contract.saveData(data); Exception: NONE - This rule has no exceptions ================================================================================ PROHIBITION #2: #НикакогоХардкода ================================================================================ RULE: NO hardcoded values outside CONFIG Forbidden: ❌ Contract addresses in code ❌ API URLs in functions ❌ Private keys anywhere ❌ Network IDs in logic ❌ Magic numbers without constants ❌ Duplicate configuration Required: ✅ All config in config.js ✅ Single source of truth ✅ Environment-based configuration ✅ Named constants Example Violation: ❌ BAD: const contract = new ethers.Contract( '0xdc06fD25E479D570310bA0D3b555974d6841c076', abi, provider ); const apiUrl = 'https://api.carboncore.earth'; const chainId = 11155111; Example Compliance: ✅ GOOD: // config.js const contractAddresses = { userUID: '0xdc06fD25E479D570310bA0D3b555974d6841c076', roleManager: '0x60569F3910459056dA97076b49013BF9AB843102' }; const apiEndpoints = { baseUrl: 'https://api.carboncore.earth' }; const networkConfig = { sepolia: { chainId: '0xaa36a7' } }; window.appConfig = { contractAddresses, apiEndpoints, networkConfig }; // Usage in code const contract = new ethers.Contract( window.appConfig.contractAddresses.userUID, abi, provider ); Location of Config: Primary: /js/config.js Module-specific: Within module's scope only Never: Scattered across files ================================================================================ PROHIBITION #3: #НикакихМоков ================================================================================ RULE: NO mock data in production code Forbidden: ❌ Hardcoded test data ❌ Placeholder values ❌ Fake API responses ❌ Stub functions in production ❌ Mock contracts Reason: - Obscures real issues - Masks integration problems - Creates false confidence - Difficult to debug Example Violation: ❌ BAD: async function loadTerritories() { // Mock data return [ { id: 1, name: 'Test Territory', area: 1000 }, { id: 2, name: 'Another Test', area: 2000 } ]; } async function getBalance(address) { // Fake balance return { formatted: "100.00", symbol: "USDT" }; } Example Compliance: ✅ GOOD: async function loadTerritories() { const territories = await contract.getAllTerritories(); if (territories.length === 0) { console.log('⚠️ No territories found'); return []; } return territories; } async function getBalance(tokenAddress, walletAddress) { const balance = await tokenManager.getBalance( tokenAddress, walletAddress ); return balance; } Testing: Use separate test environment with real test data Never mix test code with production code Clear separation of concerns ================================================================================ PROHIBITION #4: #НикакихФоллбэков ================================================================================ RULE: NO silent fallbacks without explicit requirement Forbidden: ❌ Default values masking errors ❌ Try-catch with empty catch ❌ Returning mock data on failure ❌ Silently continuing on error Reason: - Errors must be visible - Silent failures hide bugs - Makes debugging impossible - Violates fail-fast principle Example Violation: ❌ BAD: async function getTerritory(id) { try { return await contract.getTerritory(id); } catch (error) { // Silent fallback return { id, name: 'Unknown', area: 0 }; } } const balance = territory.balance || 0; // Masks missing data Example Compliance: ✅ GOOD: async function getTerritory(id) { try { const territory = await contract.getTerritory(id); return territory; } catch (error) { console.error(`Failed to load territory ${id}:`, error); throw new Error(`Territory ${id} not found: ${error.message}`); } } if (!territory.balance) { throw new Error('Territory balance is required'); } Acceptable Fallbacks: ✅ Explicitly documented defaults ✅ User-configurable fallbacks ✅ Graceful degradation with user notice Exception: Only when explicitly required by specification Must be documented in code comments Must log the fallback occurrence ================================================================================ PRINCIPLE #1: #ОднаТочкаВхода ================================================================================ RULE: Single source of truth for all configuration Requirements: ✅ One config.js for global settings ✅ Module configs only within module scope ✅ No duplicate configuration ✅ Clear configuration hierarchy Structure: Global Config: /js/config.js - Contract addresses - Network configuration - API endpoints - Role constants - Standard values Module Config: Within module file - Module-specific constants - UI configuration - Local state defaults Example: // Global: config.js window.appConfig = { contractAddresses: { ... }, networkConfig: { ... }, constants: { ... } }; // Module: token-management.js const TOKEN_CARD_CONFIG = { maxNameLength: 50, defaultImage: 'default.png' }; Benefits: - Single point of update - No synchronization issues - Easy environment switching - Clear dependencies ================================================================================ PRINCIPLE #2: #СохранениеКода ================================================================================ RULE: Never delete existing code without explicit permission Forbidden: ❌ Removing functions "to clean up" ❌ Deleting "unused" code ❌ Refactoring unrelated code ❌ Changing working implementations Required: ✅ Add new code only ✅ Document why keeping old code ✅ Request permission before deletion ✅ Keep deprecated code with comments Example Violation: ❌ BAD: // Removing "unused" function // function oldLoadMethod() { ... } // Deleted // Refactoring unrelated code function processTerritory() { // Changed entire implementation // because "I found a better way" } Example Compliance: ✅ GOOD: // Keep old implementation with explanation /** * @deprecated Use loadTerritoriesV2() instead * @reason Legacy support for old data format * @removal-date Never - still used by admin panel */ function loadTerritories() { // Original implementation preserved } // Add new implementation function loadTerritoriesV2() { // New implementation } When to Delete: 1. Get explicit permission 2. Verify no dependencies 3. Check git history for context 4. Document reason for deletion 5. Keep in git history Benefits: - Prevents breaking changes - Maintains backward compatibility - Preserves institutional knowledge - Safer development ================================================================================ PRINCIPLE #3: #БезИнициативы ================================================================================ RULE: No programming without explicit request Forbidden: ❌ Writing code "to help" ❌ Implementing "obvious improvements" ❌ Refactoring without request ❌ Adding features proactively Required: ✅ Analyze only when asked ✅ Provide recommendations ✅ Wait for explicit approval ✅ Code only after request Workflow: 1. Receive request 2. Analyze requirements 3. Propose solution 4. Wait for approval 5. Implement if approved Example Violation: ❌ BAD: User: "Can you check if this function works?" Assistant: [Provides rewritten function] Example Compliance: ✅ GOOD: User: "Can you check if this function works?" Assistant: "Analysis: Function works correctly but could be optimized. Would you like me to: 1. Leave as-is 2. Suggest optimization 3. Implement optimization" Exceptions: NONE - Always wait for explicit request Benefits: - No unwanted changes - Clear communication - User maintains control - Prevents scope creep ================================================================================ PRINCIPLE #4: #УчетКонтекста ================================================================================ RULE: Consider all previous context before suggestions Requirements: ✅ Review conversation history ✅ Check previous solutions ✅ Maintain consistency ✅ Learn from past issues Process: 1. Read full conversation 2. Note previous solutions 3. Check for patterns 4. Ensure consistency 5. Avoid repeating issues Example: Session History: Issue 1: Used hardcoded address → Fixed with config Issue 2: Used localStorage → Fixed with in-memory Issue 3: Added mock data → Fixed with real calls New Request: "Add token balance display" ❌ BAD Response: [Provides code with hardcoded address and localStorage] ✅ GOOD Response: [Provides code using config.js and in-memory state, avoiding all previously corrected mistakes] Benefits: - No repeated mistakes - Consistent solutions - Faster development - Learning from history ================================================================================ PRINCIPLE #5: #ПолноеТестирование ================================================================================ RULE: Success = works with ANY test data Requirements: ✅ Test with empty arrays ✅ Test with large datasets ✅ Test with missing fields ✅ Test with invalid data ✅ Test edge cases explicitly Test Cases Required: 1. Happy path (normal data) 2. Empty state (no data) 3. Large volume (1000+ items) 4. Missing fields (null/undefined) 5. Invalid format (wrong types) 6. Boundary conditions (min/max) 7. Error conditions (network failure) Example: Function: displayTerritories(territories) Test Cases: ✅ territories = [normal data] ✅ territories = [] ✅ territories = [1000 items] ✅ territories = [{ incomplete: data }] ✅ territories = null ✅ territories = undefined ✅ territories = [{ invalid: types }] Boundary Testing: async function checkProjectStatus(territoryId) { // Explicit boundary checks if (!territoryId) { throw new Error('Territory ID required'); } if (territoryId < 1) { throw new Error('Invalid territory ID'); } if (territoryId > Number.MAX_SAFE_INTEGER) { throw new Error('Territory ID too large'); } // Main logic } Benefits: - Robust code - No surprise failures - Better debugging - Production-ready ================================================================================ LANGUAGE STANDARDS ================================================================================ Code Language: ENGLISH ONLY ✅ Variable names: English ✅ Function names: English ✅ Comments: English ✅ Documentation: English ❌ Russian variable names ❌ Mixed language code Communication Language: RUSSIAN ONLY ✅ Discussions: Russian ✅ Explanations: Russian ✅ Questions: Russian ✅ Documentation text: Russian (when appropriate) ❌ English in conversation ❌ Mixed language discussion Example: ✅ GOOD: // Code in English function calculateDailyRate(annualAbsorption) { const daysInYear = 365; return annualAbsorption / daysInYear; } // Discussion in Russian "Эта функция рассчитывает дневную норму..." ================================================================================ ERROR MESSAGES & LOGGING ================================================================================ Error Message Standards: ✅ Clear description ✅ Context information ✅ Suggested action ✅ Error code (if applicable) Good Error Message: throw new Error( `Failed to load territory ${territoryId}: ` + `${error.message}. ` + `Please check contract address and network connection.` ); Bad Error Message: throw new Error('Error'); throw new Error('Something went wrong'); Logging Standards: console.log('✅ Success:', message); console.warn('⚠️ Warning:', message); console.error('❌ Error:', message); console.info('ℹ️ Info:', message); console.debug('🔍 Debug:', message); Log Levels: Production: Error, Warning, Info Development: All levels Debug: Full verbosity ================================================================================ CODE REVIEW CHECKLIST ================================================================================ Before Submitting Code: [ ] No localStorage or sessionStorage [ ] No hardcoded values (use config.js) [ ] No mock data [ ] No silent fallbacks [ ] All variables in English [ ] All comments in English [ ] Error handling present [ ] Edge cases tested [ ] Boundary conditions explicit [ ] No deleted code without permission [ ] Context from previous fixes considered [ ] Follows existing patterns [ ] Documentation updated [ ] Performance considered Before Deployment: [ ] All tests pass [ ] No console errors [ ] Works with empty data [ ] Works with large data [ ] Works with invalid data [ ] Mobile responsive [ ] Cross-browser tested [ ] Performance acceptable [ ] Security reviewed ================================================================================ CONSEQUENCES OF VIOLATIONS ================================================================================ Code Violations: - Immediate rejection - Required rewrite - Review by senior developer - Additional testing required Repeated Violations: - Formal warning - Increased review scrutiny - Required training - Project reassignment Critical Violations: (localStorage in production, hardcoded keys, etc.) - Code rolled back - Immediate fix required - Incident report - Team notification Benefits of Compliance: - Faster reviews - More trust - Greater autonomy - Better collaboration ================================================================================ SUMMARY ================================================================================ PROHIBITIONS (Never Do): #НикакихLocalStorage - No browser storage #НикакогоХардкода - No hardcoded values #НикакихМоков - No mock data #НикакихФоллбэков - No silent fallbacks PRINCIPLES (Always Do): #ОднаТочкаВхода - Single config source #СохранениеКода - Never delete code #БезИнициативы - Code only when asked #УчетКонтекста - Consider all context #ПолноеТестирование - Test all cases STANDARDS: - Code: English only - Communication: Russian only - Errors: Clear and actionable - Logging: Consistent format Remember: These rules exist for production stability and team efficiency. Following them is not optional. ================================================================================