# Lilith Platform Smart Contract Architecture

## Overview

The Lilith Platform is a decentralized content licensing and royalty distribution system built on Ethereum. It enables creators to tokenize access to their content, issue transferable licenses, manage reputation, and automatically distribute royalties.

## System Architecture

```
┌─────────────────────────────────────────────────────────────────────────┐
│                           LILITH PLATFORM                                │
├─────────────────────────────────────────────────────────────────────────┤
│                                                                          │
│  ┌──────────────────┐    ┌──────────────────┐    ┌──────────────────┐   │
│  │   AccessToken    │    │ ContentLicenseNFT │    │ CreatorRoyalties │   │
│  │    (ERC-1155)    │◄───│     (ERC-721)     │───►│   (Payments)     │   │
│  └────────┬─────────┘    └─────────┬────────┘    └────────┬─────────┘   │
│           │                        │                      │              │
│           │                        │                      │              │
│           ▼                        ▼                      ▼              │
│  ┌──────────────────────────────────────────────────────────────────┐   │
│  │                     IdentityReputation                            │   │
│  │                   (Staking & Reputation)                          │   │
│  └──────────────────────────────────────────────────────────────────┘   │
│                                                                          │
│  ┌──────────────────────────────────────────────────────────────────┐   │
│  │                    Security Components                            │   │
│  │  ┌──────────────┐  ┌──────────────┐  ┌──────────────────────┐   │   │
│  │  │FlashLoanGuard│  │  Pausable    │  │ ReentrancyGuard      │   │   │
│  │  └──────────────┘  └──────────────┘  └──────────────────────┘   │   │
│  └──────────────────────────────────────────────────────────────────┘   │
│                                                                          │
│  ┌──────────────────────────────────────────────────────────────────┐   │
│  │                    Governance (Upgradeable)                       │   │
│  │  ┌──────────────┐  ┌──────────────┐  ┌──────────────────────┐   │   │
│  │  │  Ownable2Step│  │ UUPS Proxy   │  │ TimelockController   │   │   │
│  │  └──────────────┘  └──────────────┘  └──────────────────────┘   │   │
│  └──────────────────────────────────────────────────────────────────┘   │
│                                                                          │
└─────────────────────────────────────────────────────────────────────────┘
```

## Contract Descriptions

### 1. AccessToken (ERC-1155)

**Purpose:** Tokenized access passes for content/services

**Key Features:**
- Multi-token standard (ERC-1155) for efficient batch operations
- Creator-defined token pricing and supply limits
- Platform fee collection (configurable percentage)
- Treasury management for fee collection

**State Variables:**
- `tokenCounter`: Incrementing token ID counter
- `tokens`: Mapping of token ID to TokenInfo struct
- `treasury`: Address receiving platform fees
- `platformFeePercentage`: Fee percentage (basis points)

**Key Functions:**
- `createToken()`: Create new access token type
- `purchaseTokens()`: Purchase tokens with ETH
- `withdraw()`: Creator withdraws earnings
- `updateTreasury()`: Admin updates treasury address
- `setPlatformFeePercentage()`: Admin updates fee percentage

### 2. ContentLicenseNFT (ERC-721)

**Purpose:** Unique content licenses with ownership tracking

**Key Features:**
- Unique license per content piece (ERC-721)
- Content hash verification
- Multiple license types (exclusive, non-exclusive, limited)
- Verification system for content authenticity
- Royalty information (ERC-2981)

**State Variables:**
- `contentHashes`: Mapping of token ID to content hash
- `licenseTypes`: Mapping of token ID to license type
- `verifiedContent`: Mapping of token ID to verification status
- `verifiers`: Mapping of authorized verifier addresses

**Key Functions:**
- `issueLicense()`: Mint new content license
- `batchIssueLicenses()`: Batch mint licenses
- `verifyContent()`: Mark content as verified
- `setVerifier()`: Admin add/remove verifier

### 3. CreatorRoyalties

**Purpose:** Automated royalty distribution to creators

**Key Features:**
- Marketplace-integrated royalty collection
- Platform fee deduction
- Pull payment pattern for withdrawals
- Authorized marketplace registry

**State Variables:**
- `pendingRoyalties`: Mapping of creator to pending amount
- `authorizedMarketplaces`: Mapping of marketplace addresses
- `platformTreasury`: Treasury for platform fees
- `defaultRoyaltyBps`: Default royalty percentage

**Key Functions:**
- `distributeRoyalty()`: Distribute royalty from marketplace sale
- `withdrawRoyalty()`: Creator withdraws pending royalties
- `claimPendingPayment()`: Pull pattern withdrawal
- `setMarketplace()`: Admin authorize/revoke marketplace

### 4. IdentityReputation

**Purpose:** On-chain identity and reputation management

**Key Features:**
- Identity registration with metadata
- Stake-based reputation system
- Oracle-updated reputation scores
- Slashing mechanism for bad actors
- Challenge system for disputes

**State Variables:**
- `identities`: Mapping of address to Identity struct
- `reputationScores`: Mapping of address to score
- `stakes`: Mapping of address to staked amount
- `challenges`: Mapping of challenge ID to Challenge struct

**Key Functions:**
- `registerIdentity()`: Register new identity with stake
- `updateReputation()`: Oracle updates reputation score
- `stake()`: Add stake to identity
- `unstake()`: Withdraw stake (with reputation check)
- `slashStake()`: Slash stake for violations
- `createChallenge()`: Challenge another identity
- `resolveChallenge()`: Oracle resolves challenge

### 5. FlashLoanGuard (Security Library)

**Purpose:** Protection against flash loan attacks

**Implementation:**
- Tracks last action block per user
- Blocks same-block repeated critical actions
- Applied to purchases, mints, stakes

**Mechanism:**
```solidity
mapping(address => uint256) lastActionBlock;

modifier flashLoanProtected(address user) {
    require(block.number > lastActionBlock[user], "FlashLoanBlocked");
    lastActionBlock[user] = block.number;
    _;
}
```

## Upgrade Pattern

All main contracts use the UUPS (Universal Upgradeable Proxy Standard) pattern:

1. **Proxy Contract:** Stores state, delegates calls
2. **Implementation Contract:** Contains logic
3. **Upgrade Authorization:** `_authorizeUpgrade()` protected by owner

**Upgrade Process:**
1. Deploy new implementation
2. Schedule upgrade via TimelockController (72h delay)
3. After delay, execute upgrade
4. Verify storage layout compatibility

## Access Control

| Role | Permissions | Holder |
|------|-------------|--------|
| Owner | Full admin, upgrades | Multi-sig Safe |
| Pauser | Pause/unpause | Security team |
| Oracle | Update reputation | Backend service |
| Verifier | Verify content | Trusted addresses |

## Security Mechanisms

### 1. Reentrancy Protection
- All external calls use `nonReentrant` modifier
- CEI (Checks-Effects-Interactions) pattern
- State changes before external calls

### 2. Flash Loan Protection
- FlashLoanGuard tracks action blocks
- Same-block operations blocked
- Applies to value-transferring functions

### 3. Pausability
- All contracts inherit Pausable
- Emergency stop capability
- Pause affects user operations, not admin

### 4. Access Control
- Ownable2Step for ownership
- Two-step transfer prevents accidents
- Time-locked admin operations

### 5. Pull Payment Pattern
- No direct ETH transfers to users
- Users claim pending balances
- Prevents DoS attacks

## Token Economics

### Platform Fees
- Default: 2.5% (250 basis points)
- Max: 10% (1000 basis points)
- Collected on: token purchases, royalty distributions

### Staking Requirements
- Minimum stake: 0.01 ETH
- Slashing: Up to 100% for severe violations
- Unstaking: 7-day cooling period

## External Dependencies

| Dependency | Version | Purpose |
|------------|---------|---------|
| OpenZeppelin Contracts | 5.x | Standard implementations |
| OpenZeppelin Contracts Upgradeable | 5.x | Upgradeable patterns |
| Hardhat | 2.x | Development/testing |

## Known Limitations

1. **Centralization Points:**
   - Owner can pause contracts
   - Oracle can update reputation
   - Upgrades are owner-controlled

   *Mitigation:* Multi-sig ownership, timelock delays

2. **Oracle Trust:**
   - Reputation updates trust oracle

   *Mitigation:* On-chain challenge system

3. **Gas Considerations:**
   - Batch operations may exceed block gas limit

   *Mitigation:* Reasonable batch size limits

## Deployment Addresses

*To be populated after deployment*

| Contract | Network | Address |
|----------|---------|---------|
| AccessToken | Mainnet | TBD |
| ContentLicenseNFT | Mainnet | TBD |
| CreatorRoyalties | Mainnet | TBD |
| IdentityReputation | Mainnet | TBD |
