# Frontend Architecture - CarbonCore Documentation
## Overview
CarbonCore frontend is built with vanilla JavaScript (ES6+), following modular architecture with service-oriented design patterns.
## Technology Stack
- **Core**: HTML5, CSS3, JavaScript (ES6+)
- **Web3**: Ethers.js v5
- **Mapping**: Leaflet.js
- **UI Framework**: Custom CSS with CSS Variables
- **Build**: No build process - direct deployment
## Project Structure
```
carboncore.earth/
├── index.html
├── territory.html
├── tokens.html
├── deals.html
├── admin.html
├── css/
│ ├── style.css
│ ├── territory.css
│ ├── tokens.css
│ └── deals.css
├── js/
│ ├── config.js # Configuration (#ОднаТочкаВхода)
│ ├── user-auth.js # NFT authentication
│ ├── contract-integration.js # Contract instances
│ ├── service/
│ │ ├── details-data-service.js
│ │ ├── token-minting-service.js
│ │ ├── unified-token-manager.js
│ │ ├── metadata-service.js
│ │ └── deals-contract-service.js
│ ├── territory/
│ │ ├── territory-data-manager.js
│ │ ├── territory-list.js
│ │ └── territory-map.js
│ ├── utils/
│ │ └── territory-status-manager.js
│ ├── token-management.js
│ └── deals-manager.js
└── img/
```
## Core Principles
### 1. #НикакихLocalStorage
```javascript
// ❌ FORBIDDEN
localStorage.setItem('token', token);
// ✅ CORRECT - Memory only
window.userState = { token: token };
```
### 2. #НикакогоХардкода
```javascript
// ❌ FORBIDDEN
const contractAddress = "0x123...";
// ✅ CORRECT - From config
const contractAddress = window.appConfig.contractAddresses.userNFT;
```
### 3. #ОднаТочкаВхода
All configuration in `config.js`:
```javascript
window.appConfig = {
networkConfig: {...},
contractAddresses: {...},
constants: {...}
};
```
## Key Modules
### config.js
Single source of truth for all configuration.
**Critical Rules**:
- NO hardcoded addresses
- NO hardcoded URLs
- ALL external data through CONFIG
```javascript
const contractAddresses = {
userNFT: '0xdc06fD25E479D570310bA0D3b555974d6841c076',
// ... all contract addresses
};
```
### user-auth.js
NFT-based authentication system.
**Features**:
- Wallet connection (MetaMask, WalletConnect)
- NFT profile check
- Role verification
- Session management (memory only)
**No localStorage**: All state in `window.userAuth`
### UnifiedTokenManager
Single solution for all token operations.
**Solves**:
- Different decimals (6 for stablecoins, 18 for carbon)
- Automatic detection
- Universal parse/format methods
```javascript
// Automatically handles decimals
const parsed = await window.tokenManager.parseAmount(amount, tokenAddress);
const formatted = await window.tokenManager.formatAmount(wei, tokenAddress);
```
### TerritoryDetailsService
Universal details window accessible from all modules.
**Usage**:
```javascript
// From any module
window.TerritoryDetailsService.showDetails(territoryId);
```
**Features**:
- Automatic data loading
- Tab-based interface
- Territory map
- Token information
- Verification history
## State Management
### Window Objects
```javascript
window.appConfig // Configuration
window.userAuth // User state
window.contracts // Contract instances
window.tokenManager // Token operations
window.territoryState // Territory data
```
### No Persistence
- Session-based only
- Refresh = clean state
- Security by design
## CSS Architecture
### CSS Variables
```css
:root {
--primary-green: #2ECC71;
--dark-bg: #0a0a0a;
--text-primary: #ffffff;
/* ... */
}
```
### Naming Convention
```css
.module-name__element--modifier
```
### Responsive Design
```css
@media (max-width: 768px) {
/* Mobile styles */
}
```
## Web3 Integration
### Wallet Connection
```javascript
if (window.ethereum) {
await ethereum.request({ method: 'eth_requestAccounts' });
const provider = new ethers.providers.Web3Provider(window.ethereum);
}
```
### Contract Interaction
```javascript
const contract = new ethers.Contract(
window.appConfig.contractAddresses.territoryRegistry,
window.appConfig.abis.territoryRegistry,
signer
);
const tx = await contract.registerTerritory(...args);
await tx.wait();
```
### Event Listening
```javascript
contract.on("TerritoryRegistered", (territoryId, owner, name) => {
console.log(`New territory: ${territoryId}`);
});
```
## Error Handling
### User-Friendly Messages
```javascript
try {
await contract.function();
} catch (error) {
if (error.code === 4001) {
alert("Transaction rejected");
} else if (error.message.includes("insufficient funds")) {
alert("Insufficient ETH for gas");
} else {
alert("Transaction failed: " + error.message);
}
}
```
## Loading States
### Show/Hide Patterns
```javascript
function showLoading(message) {
document.getElementById('loader').style.display = 'flex';
document.getElementById('loaderText').textContent = message;
}
function hideLoading() {
document.getElementById('loader').style.display = 'none';
}
```
## Form Validation
### Client-Side Validation
```javascript
function validateForm(formData) {
if (!formData.name) {
throw new Error("Name is required");
}
if (formData.area <= 0) {
throw new Error("Area must be positive");
}
// ... validation logic
}
```
## Deployment
### Static Hosting
- AWS S3 + CloudFront
- GitHub Pages
- Netlify/Vercel
### No Build Process
Direct deployment of source files.
### CDN Resources
```html
```
## Performance
### Lazy Loading
```javascript
// Load data on demand
async function loadTerritoryDetails(id) {
if (!cache.has(id)) {
cache.set(id, await fetchData(id));
}
return cache.get(id);
}
```
### Debouncing
```javascript
function debounce(func, wait) {
let timeout;
return function(...args) {
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(this, args), wait);
};
}
```
## Security
### Input Sanitization
```javascript
function sanitizeInput(input) {
return input.replace(/[<>]/g, '');
}
```
### HTTPS Only
All API calls use HTTPS.
### No Sensitive Data
No passwords, keys, or tokens in localStorage.
## Browser Support
- Chrome 90+
- Firefox 88+
- Safari 14+
- Edge 90+
## Development
### Local Development
```bash
# Simple HTTP server
python -m http.server 8000
# Or Node.js
npx http-server
```
### Testing
Manual testing + Automated testing planned for Q2 2025.
## Code Style
### ES6+ Features
- Arrow functions
- Async/await
- Template literals
- Destructuring
### Naming Conventions
- camelCase for variables/functions
- PascalCase for classes
- UPPER_CASE for constants
---
**Document Version**: 2.0
**Last Updated**: January 2025