# Lilith Smart Contracts Guide

Complete guide for deploying, integrating, and interacting with Lilith's smart contract ecosystem.

---

## Overview

Lilith's blockchain layer provides:
- **Access Tokens (ERC-1155)**: Subscription and course access management
- **Content License NFTs (ERC-721)**: Content licensing with royalty distribution
- **Creator Royalties**: Creator registration and royalty tracking
- **Identity & Reputation**: Decentralized identity verification and reputation scores
- **Security**: Flash loan guards and reentrancy protection

---

## Contract Architecture

```
┌─────────────────────────────────────────────────────────────┐
│                    User/Marketplace                          │
└────────────────────────┬────────────────────────────────────┘
                         │
         ┌───────────────┴───────────────┐
         │                               │
         ▼                               ▼
┌─────────────────┐           ┌─────────────────────┐
│  AccessToken    │           │ RoyaltyLicenseManager│
│   (ERC-1155)    │           │    (Orchestrator)    │
└─────────────────┘           └──────────┬──────────┘
                                         │
                    ┌────────────────────┴────────────────────┐
                    │                                         │
                    ▼                                         ▼
         ┌─────────────────┐                      ┌─────────────────┐
         │ CreatorRoyalties │                      │ ContentLicenseNFT│
         │   (Registry)     │                      │    (ERC-721)     │
         └─────────────────┘                      └─────────────────┘
                    │
                    ▼
         ┌─────────────────┐
         │ IdentityReputation│
         │   (Verification)  │
         └─────────────────┘
```

---

## AccessToken (ERC-1155)

Multi-token standard for managing subscriptions, course access, and feature unlocks.

### Token Types

| Type | ID | Description |
|------|------|-------------|
| Basic Subscription | 1 | Monthly basic access |
| Premium Subscription | 2 | Monthly premium access |
| Lifetime Premium | 3 | One-time premium purchase |
| Course Access | 4 | Individual course access |
| Feature Access | 5 | Specific feature unlock |
| Content Access | 6 | Individual content access |
| Creator Token | 7 | Creator-specific benefits |
| Community Access | 8 | Community membership |

### Key Functions

```solidity
// Purchase a token
function purchaseToken(
    uint256 tokenId,
    uint256 durationDays
) external payable;

// Check if user has premium access
function hasPremiumAccess(address user) external view returns (bool);

// Check if token is active for user
function isTokenActive(
    address user,
    uint256 tokenId
) external view returns (bool);

// Get user's active tokens (paginated)
function getUserActiveTokensPaginated(
    address user,
    uint256 offset,
    uint256 limit
) external view returns (uint256[] memory tokenIds, uint256[] memory expirations);
```

### Creating Token Types (Admin)

```solidity
function createTokenType(
    uint256 tokenId,
    string memory name,
    uint256 price,
    uint256 maxSupply,
    bool transferable,
    bool isPremium
) external onlyOwner;
```

### Integration Example

```typescript
import { ethers } from 'ethers';
import { AccessToken__factory } from '@lilith/contracts';

const provider = new ethers.JsonRpcProvider(RPC_URL);
const signer = new ethers.Wallet(PRIVATE_KEY, provider);
const accessToken = AccessToken__factory.connect(CONTRACT_ADDRESS, signer);

// Purchase monthly subscription
const price = await accessToken.getTokenPrice(2); // Premium subscription
await accessToken.purchaseToken(2, 30, { value: price });

// Check access
const hasPremium = await accessToken.hasPremiumAccess(userAddress);
```

---

## ContentLicenseNFT (ERC-721)

NFT-based content licensing with royalty distribution following EIP-2981.

### License Types

| Type | Description |
|------|-------------|
| Personal | Personal use only |
| Commercial | Commercial use allowed |
| Derivative | Create derivative works |
| Redistribution | Redistribute content |
| Exclusive | Exclusive rights |
| Creator Rights | Full creator rights |
| Attribution Only | Free with attribution |

### License Scopes

| Scope | Description |
|-------|-------------|
| Single Use | One-time use |
| Time Limited | Limited duration |
| Perpetual | Forever |
| Usage Limited | Limited uses |
| Territory Limited | Geographic restriction |
| Platform Limited | Platform-specific |

### Key Functions

```solidity
// Issue a license NFT
function issueLicense(
    address to,
    string memory contentId,
    LicenseType licenseType,
    LicenseScope scope,
    uint256 price,
    address creator,
    uint96 royaltyPercentage
) external payable returns (uint256 tokenId);

// Batch issue licenses
function batchIssueLicenses(
    address[] memory recipients,
    string[] memory contentIds,
    LicenseType[] memory licenseTypes,
    LicenseScope[] memory scopes,
    uint256[] memory prices,
    address creator,
    uint96 royaltyPercentage
) external payable returns (uint256[] memory tokenIds);

// Get royalty info (EIP-2981)
function royaltyInfo(
    uint256 tokenId,
    uint256 salePrice
) external view returns (address receiver, uint256 royaltyAmount);

// Claim pending royalties (pull-payment pattern)
function claimPendingRoyalties() external;
```

### Royalty Distribution

Royalties are distributed automatically on secondary sales (marketplaces supporting EIP-2981):

```solidity
// Default: 10% royalty to creator
// Max: 50% royalty cap
// Pull-payment for failed transfers
```

### Integration Example

```typescript
// Issue a commercial license
const tx = await contentLicenseNFT.issueLicense(
  buyerAddress,
  "content_abc123",
  1, // Commercial
  2, // Perpetual
  ethers.parseEther("0.1"),
  creatorAddress,
  1000 // 10% royalty
);

// Check license ownership
const owner = await contentLicenseNFT.ownerOf(tokenId);
const licenseInfo = await contentLicenseNFT.getLicense(tokenId);
```

---

## CreatorRoyalties

Registry for creator profiles, content licensing, and royalty distribution.

### Creator Registration

```solidity
// Register as a creator
function registerCreator(
    string memory name,
    string memory bio,
    string[] memory specializations,
    string[] memory socialLinks
) external;

// Verify creator (admin only)
function verifyCreator(address creator) external onlyVerifier;
```

### Content Registration

```solidity
// Register content for licensing
function registerContent(
    string memory contentId,
    string memory title,
    string memory description,
    uint256 basePrice,
    address[] memory collaborators,
    uint256[] memory collaboratorShares
) external;
```

### License Purchasing

```solidity
// Purchase a license
function purchaseLicense(
    string memory contentId,
    LicenseType licenseType,
    uint256 durationMonths
) external payable;

// Marketplace-delegated purchase
function purchaseLicenseFor(
    address buyer,
    string memory contentId,
    LicenseType licenseType,
    uint256 durationMonths
) external payable onlyAuthorizedMarketplace;
```

### Pricing Tiers

| License Type | Multiplier |
|--------------|------------|
| Standard | 1x |
| Commercial | 3x |
| Exclusive | 10x |
| Educational | 0.5x |
| Open Source | Free |

| Duration | Discount |
|----------|----------|
| Monthly | 0% |
| Yearly | 20% |

### Integration Example

```typescript
// Register as creator
await creatorRoyalties.registerCreator(
  "Artist Name",
  "Digital artist specializing in sacred geometry",
  ["meditation", "sacred_geometry"],
  ["https://twitter.com/artist"]
);

// Register content
await creatorRoyalties.registerContent(
  "artwork_001",
  "Sacred Mandala",
  "AI-generated sacred geometry artwork",
  ethers.parseEther("0.05"),
  [collaboratorAddress],
  [2000] // 20% to collaborator
);

// Purchase license
const price = await creatorRoyalties.calculateLicensePrice(
  "artwork_001",
  1, // Commercial
  12 // 12 months
);
await creatorRoyalties.purchaseLicense("artwork_001", 1, 12, { value: price });
```

---

## IdentityReputation

Decentralized identity verification and reputation scoring.

### Identity Types

| Type | Description |
|------|-------------|
| Individual | Personal user |
| Organization | Company/team |
| Institution | Educational/religious |
| Validator | Verification service |
| Oracle | Data provider |
| Community | Community group |

### Verification Types

| Type | Stake | Reward |
|------|-------|--------|
| Email | 0.01 ETH | 0.005 ETH |
| Phone | 0.05 ETH | 0.025 ETH |
| Government ID | 1 ETH | 0.5 ETH |
| Educational Credential | 0.5 ETH | 0.25 ETH |
| Professional License | 0.8 ETH | 0.4 ETH |
| Social Media | 0.02 ETH | 0.01 ETH |
| Domain Ownership | 0.1 ETH | 0.05 ETH |
| Biometric | 0.5 ETH | 0.25 ETH |
| Community Vouching | 0.05 ETH | 0.025 ETH |
| Expert Endorsement | 0.2 ETH | 0.1 ETH |

### Reputation Components

```solidity
struct ReputationScore {
    uint256 contentQuality;      // 0-2500
    uint256 communityEngagement; // 0-2500
    uint256 trustworthiness;     // 0-2500
    uint256 expertise;           // 0-2500
}
// Total max: 10,000 points
```

### Reputation Tiers

| Tier | Score Range |
|------|-------------|
| Bronze | 0 - 2,499 |
| Silver | 2,500 - 4,999 |
| Gold | 5,000 - 7,499 |
| Platinum | 7,500+ |

### Key Functions

```solidity
// Register identity
function registerIdentity(
    IdentityType identityType,
    string memory did,
    string memory publicKey,
    string memory metadata
) external;

// Stake and claim verification
function stakeAndClaimVerification(
    address subject,
    VerificationType verificationType,
    bytes memory proof
) external payable;

// Challenge a verification (dispute)
function challengeVerification(
    uint256 claimId,
    string memory reason,
    bytes memory evidence
) external payable;

// Resolve challenge (authorized resolvers)
function resolveChallenge(
    uint256 challengeId,
    bool challengerWins,
    string memory resolution
) external onlyAuthorizedResolver;

// Update reputation
function updateReputation(
    address subject,
    ReputationAction action,
    int256 change
) external onlyAuthorizedUpdater;
```

### Challenge System

- **30-day challenge window** from claim issuance
- **7-day resolution period** for disputes
- **Stake matching** - challenger must stake equal amount
- **Slashing** - 50% penalty for false claims/challenges

### Integration Example

```typescript
// Register identity
await identityReputation.registerIdentity(
  0, // Individual
  "did:lilith:user123",
  publicKeyBytes,
  JSON.stringify({ name: "User", country: "US" })
);

// Claim email verification
await identityReputation.stakeAndClaimVerification(
  userAddress,
  0, // Email
  emailProof,
  { value: ethers.parseEther("0.01") }
);

// Get reputation
const rep = await identityReputation.getReputationScore(userAddress);
const tier = await identityReputation.getReputationTier(userAddress);
```

---

## RoyaltyLicenseManager

Orchestrator that combines license purchase with NFT minting in a single transaction.

### Key Functions

```solidity
// Purchase license and mint NFT in one transaction
function purchaseAndMintLicense(
    string memory contentId,
    LicenseType licenseType,
    uint256 durationMonths
) external payable returns (uint256 nftTokenId);

// Claim refunds (pull-payment)
function claimRefund() external;
```

### Integration Example

```typescript
// Single transaction: purchase + mint
const tx = await royaltyLicenseManager.purchaseAndMintLicense(
  "content_abc",
  1, // Commercial
  12, // 12 months
  { value: ethers.parseEther("0.15") }
);

const receipt = await tx.wait();
const tokenId = receipt.logs[0].args.tokenId;
```

---

## FlashLoanGuard

Security module preventing same-block multi-action attacks.

### Usage

```solidity
import "./security/FlashLoanGuard.sol";

contract MyContract is FlashLoanGuard {
    function sensitiveAction() external flashLoanGuarded {
        // Protected from same-block repeated calls
    }
}
```

### How It Works

1. Tracks `_lastActionBlock[address]` per user
2. Prevents calling protected functions twice in same block
3. Complements ReentrancyGuard (same-transaction protection)

---

## Deployment

### Prerequisites

```bash
# Install dependencies
cd contracts
npm install

# Set environment variables
cp .env.example .env
# Edit .env with your values
```

### Environment Variables

```env
# RPC Endpoints
ETHEREUM_RPC_URL=https://eth-mainnet.alchemyapi.io/v2/YOUR_KEY
POLYGON_RPC_URL=https://polygon-mainnet.alchemyapi.io/v2/YOUR_KEY
ARBITRUM_RPC_URL=https://arb-mainnet.alchemyapi.io/v2/YOUR_KEY

# Private Keys (NEVER COMMIT)
DEPLOYER_PRIVATE_KEY=your_private_key

# Verification
ETHERSCAN_API_KEY=your_etherscan_key
POLYGONSCAN_API_KEY=your_polygonscan_key

# Contract Configuration
TREASURY_ADDRESS=0x...
PLATFORM_FEE_PERCENTAGE=250
```

### Deploy to Testnet

```bash
# Compile
npx hardhat compile

# Deploy to Sepolia
npx hardhat run scripts/deploy-testnet.ts --network sepolia

# Verify contracts
npx hardhat verify --network sepolia DEPLOYED_ADDRESS
```

### Deploy to Mainnet

```bash
# Run pre-mainnet checks
npx hardhat run scripts/pre-mainnet-check.ts

# Deploy (UUPS upgradeable)
npx hardhat run scripts/deploy-upgradeable.ts --network mainnet

# Verify
npx hardhat verify --network mainnet PROXY_ADDRESS
```

### Multi-Chain Deployment

```bash
# Deploy to multiple chains
npx hardhat run scripts/deploy-multichain.ts

# Supported networks:
# - Ethereum Mainnet (1)
# - Polygon (137)
# - Arbitrum One (42161)
# - Optimism (10)
# - Base (8453)
```

---

## Upgrading Contracts

All core contracts use the UUPS proxy pattern for upgradability.

### Upgrade Process

```bash
# 1. Deploy new implementation
npx hardhat run scripts/upgrade.ts --network mainnet

# 2. Verify new implementation
npx hardhat verify --network mainnet NEW_IMPL_ADDRESS

# 3. Test upgrade (dry run)
npx hardhat run scripts/upgrade.ts --network mainnet --dry-run
```

### Upgrade Safety

```typescript
// Upgrade safety test
const upgraded = await upgrades.upgradeProxy(
  proxyAddress,
  NewImplementation,
  { call: { fn: 'reinitialize', args: [newVersion] } }
);
```

---

## Security Considerations

### Access Control

- `Ownable2Step`: Two-step ownership transfer prevents accidental transfers
- Role-based: `onlyOwner`, `onlyVerifier`, `onlyAuthorizedMarketplace`
- Admin functions protected with access control

### Reentrancy Protection

- `ReentrancyGuard` on all payment functions
- `FlashLoanGuard` for same-block attack prevention
- Checks-Effects-Interactions pattern

### DoS Prevention

- Paginated queries with `MAX_ENUMERATION_LIMIT = 100`
- O(1) counters instead of array iteration
- `MAX_TOKEN_TYPES = 1000` limit

### Payment Safety

- Pull-payment pattern for failed transfers
- `pendingRoyalties` mapping for claim later
- Low-level call for ETH transfers (supports smart contract wallets)

### Emergency Controls

- `Pausable` modifier on critical functions
- `emergencyWithdraw()` for fund extraction
- Owner-controlled pause/unpause

---

## Testing

### Run Tests

```bash
# All tests
npx hardhat test

# Specific contract
npx hardhat test test/AccessToken.test.ts

# With coverage
npx hardhat coverage
```

### Fuzz Testing (Foundry)

```bash
# Install Foundry
curl -L https://foundry.paradigm.xyz | bash
foundryup

# Run fuzz tests
forge test --fuzz-runs 100000
```

---

## Gas Optimization

| Operation | Gas Cost |
|-----------|----------|
| purchaseToken | ~85,000 |
| issueLicense | ~120,000 |
| registerCreator | ~150,000 |
| purchaseLicense | ~180,000 |
| stakeAndClaimVerification | ~200,000 |

### Optimization Tips

1. Batch operations when possible
2. Use `calldata` for read-only arrays
3. Pack storage variables
4. Use custom errors (22% gas savings)

---

## Contract Addresses

### Testnet (Sepolia)

| Contract | Address |
|----------|---------|
| AccessToken | See `/deployments/sepolia.json` |
| ContentLicenseNFT | See `/deployments/sepolia.json` |
| CreatorRoyalties | See `/deployments/sepolia.json` |
| IdentityReputation | See `/deployments/sepolia.json` |
| RoyaltyLicenseManager | See `/deployments/sepolia.json` |

### Mainnet

Pending deployment. Check `/deployments/mainnet.json` after launch.

---

## Related Documentation

- [Contract Security Audit](/contracts/reports/audit.md)
- [Upgrade Safety Tests](/contracts/test/UpgradeSafety.test.ts)
- [Gas Benchmark Report](/contracts/reports/gas-benchmark.md)
- [TypeScript SDK](/sdk/typescript/README.md)
