# Architecture Overview

## System Diagram

```mermaid
graph TB
    TG[Telegram Mini-App] --> API[Bot API Gateway]
    API --> AUTH[Auth Service]
    API --> AI[AI Scorer Service]
    API --> CHAIN[Blockchain Layer]
    
    AUTH --> VERIFY[initData Verification]
    AI --> VECTOR[Vector Database]
    AI --> FACTS[Fact-Check Engine]
    CHAIN --> IPFS[IPFS Storage]
    CHAIN --> TOKEN[Token Contract]
    
    VECTOR --> EMBED[Embedding Model]
    FACTS --> KNOWLEDGE[Knowledge Base]
    IPFS --> HASH[Content Hash]
    TOKEN --> MINT[Mint & Transfer]
```

## Core Components

### 1. 📱 Telegram WebApp Layer

**Client-Side (React/TypeScript)**

```javascript
// Secure initData verification
const { initData, user } = WebApp.initDataUnsafe;

// Submit idea with encryption
const submitIdea = async (content) => {
  const encrypted = await encryptContent(content);
  return api.post('/submit', { 
    content: encrypted,
    initData,
    timestamp: Date.now()
  });
};
```

**Core Creativity Elements:**

* Telegram WebApp SDK integration
* Client-side encryption
* Offline draft storage
* Progressive Web App capabilities

### 2. 🤖 Bot API Gateway

**Backend (Node.js/Express)**

```javascript
// Telegram auth verification
app.post('/api/auth/telegram', async (req, res) => {
  const { initData } = req.body;
  
  if (verifyTelegramWebAppData(initData)) {
    const user = parseInitData(initData);
    const token = jwt.sign({ user }, JWT_SECRET);
    res.json({ token, user });
  } else {
    res.status(401).json({ error: 'Invalid auth' });
  }
});
```

**Responsibilities:**

* Authentication & authorization
* Request routing & validation
* Rate limiting & abuse prevention
* Real-time updates via WebSocket

### 3. 🤖 Robot Creativity Scorer

**Processing Pipeline:**

```python
# Simplified scoring pipeline
class CreativityScorer:
    def score_idea(self, content: str) -> Score:
        # 1. Vectorize content
        vector = self.embedding_model.encode(content)
        
        # 2. Check originality
        originality = self.check_originality(vector)
        
        # 3. Fact-check content
        factual_score = self.fact_checker.verify(content)
        
        # 4. Calculate final score
        final_score = self.calculate_composite_score(
            originality, factual_score, complexity, innovation
        )
        
        return Score(
            total=final_score,
            originality=originality,
            factual=factual_score,
            reward_tokens=self.calculate_reward(final_score)
        )
```

**Robot Intelligence Components:**

* **Embedding Model**: Converts dedicated ideas to semantic vectors
* **Similarity Engine**: Compares against existing creativity offerings
* **Fact-Check API**: Verifies claims against knowledge base
* **Scoring Algorithm**: Composite creativity evaluation

### 4. ⛓️ Blockchain Layer

**Smart Contract (Solidity)**

```solidity
// Simplified idea submission contract
contract AltarOfCreativity {
    struct Idea {
        address creator;
        string ipfsHash;
        uint256 score;
        uint256 timestamp;
        uint256 reward;
    }
    
    mapping(uint256 => Idea) public ideas;
    uint256 public ideaCount;
    
    function submitIdea(
        string memory ipfsHash,
        uint256 score
    ) external {
        ideas[ideaCount] = Idea({
            creator: msg.sender,
            ipfsHash: ipfsHash,
            score: score,
            timestamp: block.timestamp,
            reward: calculateReward(score)
        });
        
        // Mint reward tokens
        _mint(msg.sender, calculateReward(score));
        
        emit IdeaSubmitted(ideaCount, msg.sender, score);
        ideaCount++;
    }
}
```

**On-Chain Operations:**

* **IPFS Storage**: Decentralized content storage
* **Token Minting**: Automatic reward distribution
* **Leaderboard**: Immutable ranking system
* **Governance**: Future DAO voting mechanisms

## Data Flow

**1. Submission Journey:**

```
Creative Offering → Encrypt → API Gateway → Robot Scorer → Blockchain
```

**2. Scoring Process:**

```
Raw Text → Vectorize → Compare → Verify → Score → Reward
```

**3. Reward Distribution:**

```
Score → Calculate Tokens → Mint → Transfer → Update Leaderboard
```

## Security Measures

**Authentication:**

* Telegram initData verification
* JWT token-based sessions
* Rate limiting per user
* IP-based abuse prevention

**Data Protection:**

* Client-side encryption
* Secure API communication (HTTPS)
* Private credential management
* IPFS content hashing

**Smart Contract Security:**

* Audit by reputable firms
* Multi-signature wallet controls
* Upgrade mechanisms
* Emergency pause functionality

## Performance Metrics

**Target Latencies:**

* Auth verification: <100ms
* Robot creativity scoring: <2 minutes
* Blockchain confirmation: <30 seconds
* Total offering experience: <3 minutes

**Scalability:**

* Horizontal API scaling
* AI worker pool management
* Blockchain batch processing
* CDN for static assets

## Development Environment

**Local Setup:**

```bash
# Clone repository
git clone https://github.com/altar-of-creativity/miniapp

# Install dependencies
npm install

# Start development server
npm run dev:miniapp

# Run local blockchain
npm run dev:blockchain
```

**Technology Stack:**

* **Frontend**: React, TypeScript, Tailwind CSS
* **Backend**: Node.js, Express, PostgreSQL
* **AI**: Python, TensorFlow, Hugging Face
* **Blockchain**: Ethereum, Hardhat, IPFS
* **Deployment**: Vercel, Railway, Infura

***

**Next Steps:**

* [Understand Tokenomics →](/alter-of-creativity/token-primer.md)
* [View Development Roadmap →](/alter-of-creativity/roadmap.md)
* [Start Contributing →](/alter-of-creativity/contributing.md)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://project-49.gitbook.io/alter-of-creativity/architecture-lite.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
