# Lilith Smart Contracts

This directory contains the smart contracts for the Lilith platform, providing Web3 payment processing, access control, and content licensing functionality.

## 🏗️ Architecture

### Core Contracts

#### AccessToken.sol
- **Type**: ERC-1155 Multi-Token Standard
- **Purpose**: Subscription and access control tokens
- **Features**:
  - Multiple token types (Basic, Premium, Lifetime subscriptions)
  - Time-based expiration
  - Content/feature-specific access control
  - Non-transferable subscription tokens
  - Payment distribution with platform fees

#### ContentLicenseNFT.sol
- **Type**: ERC-721 NFT Standard
- **Purpose**: Content licensing and attribution NFTs
- **Features**:
  - Flexible license types (Personal, Commercial, Derivative, etc.)
  - License scope control (Single-use, Time-limited, etc.)
  - Royalty distribution to creators and collaborators
  - Content verification + manifest metadata anchoring
  - Usage tracking, limits, and batch issuance helpers

#### CreatorRoyalties.sol
- **Type**: Royalty + Licensing Registry
- **Purpose**: Creator registration, licensing agreements, royalty splits
- **Features**:
  - Creator onboarding, verification, and reputation tracking
  - Content license registration with collaborator splits
  - Marketplace delegation via `purchaseLicenseFor`
  - Automatic royalty distribution and analytics reporting

#### RoyaltyLicenseManager.sol
- **Type**: Marketplace Hub
- **Purpose**: One-click license purchase + NFT issuance flow
- **Features**:
  - Calls `CreatorRoyalties.purchaseLicenseFor` on behalf of buyers
  - Mints matching `ContentLicenseNFT` licenses with a single transaction
  - Refunds excess payment and emits purchase analytics events
  - Admin setters for swapping royalties/NFT contract addresses

## 🚀 Deployment

### Local Development

```bash
# Start local hardhat node
npm run node

# Deploy contracts to localhost
npm run deploy:localhost

# Check contract status
COMMAND=status npx hardhat run scripts/manage.js --network localhost
```

### Multi-Chain Deployment

```bash
# Deploy to Sepolia testnet
npm run deploy:sepolia

# Deploy to Polygon
npm run deploy:polygon

# Dry run deployment (no actual deployment)
npm run deploy:dry-run
```

### Supported Networks

- **Mainnet**: Ethereum mainnet (Chain ID: 1)
- **Sepolia**: Ethereum testnet (Chain ID: 11155111)
- **Polygon**: Polygon mainnet (Chain ID: 137)
- **Mumbai**: Polygon testnet (Chain ID: 80001)
- **Arbitrum**: Arbitrum One (Chain ID: 42161)
- **Optimism**: Optimism mainnet (Chain ID: 10)
- **Base**: Base mainnet (Chain ID: 8453)

## 🛠️ Management

### Contract Management Commands

```bash
# View contract status
COMMAND=status npx hardhat run scripts/manage.js --network localhost

# Create new token type
COMMAND=create-token ARGS="Course Access,Course description,0.002,course-123" npx hardhat run scripts/manage.js --network localhost

# Purchase tokens
COMMAND=purchase ARGS="1,1" npx hardhat run scripts/manage.js --network localhost

# Check user access
COMMAND=check-access ARGS="0xUserAddress,content-123" npx hardhat run scripts/manage.js --network localhost

# Mint content license NFT
COMMAND=mint-license ARGS="0xRecipient,zen-meditation-1,0.01" npx hardhat run scripts/manage.js --network localhost
```

### Emergency Actions

```bash
# View available emergency actions
COMMAND=emergency npx hardhat run scripts/manage.js --network localhost
```

## 🌐 IPFS Metadata Pipeline

- `src/ipfs/index.ts` implements the reusable `IpfsUploader` helper and the `buildLicenseMetadata` factory for richly structured NFT metadata.
- Provide the IPFS environment variables (see below) to pin license metadata during management flows; CIDs become the on-chain `tokenURI`.
- `npm run manage mint-license` now generates metadata, uploads it, and logs both the `ipfs://` URI and the public gateway link.
- Set `IPFS_DISABLED=true` to bypass uploads globally; the underlying `ContractManager#mintLicense` helper also exposes a `skipIpfs` flag for programmatic use cases.
- Dedicated tests live in `test/IpfsUploader.test.ts` to ensure metadata shape and upload behaviour remain deterministic.

## 🔧 Configuration

### Environment Variables

Create a `.env` file in the contracts directory:

```env
# RPC URLs
MAINNET_RPC_URL=https://eth-mainnet.alchemyapi.io/v2/YOUR_KEY
SEPOLIA_RPC_URL=https://eth-sepolia.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
OPTIMISM_RPC_URL=https://opt-mainnet.alchemyapi.io/v2/YOUR_KEY
BASE_RPC_URL=https://base-mainnet.alchemyapi.io/v2/YOUR_KEY

# Deployment key
PRIVATE_KEY=your_private_key_here

# Verification
ETHERSCAN_API_KEY=your_etherscan_api_key

# IPFS configuration (optional)
IPFS_API_ENDPOINT=https://ipfs.infura.io:5001/api/v0
IPFS_PROJECT_ID=your_project_id
IPFS_PROJECT_SECRET=your_project_secret
# Alternatively provide a pre-built auth token
IPFS_AUTH_TOKEN=Basic your_base64_token
IPFS_GATEWAY_URL=https://ipfs.io/ipfs/
IPFS_DEFAULT_PIN=true
IPFS_DEFAULT_TIMEOUT_MS=60000
IPFS_DISABLED=false
LILITH_METADATA_BASE_URL=https://app.lilith.ai/nft/metadata
LILITH_CONTENT_BASE_URL=https://app.lilith.ai/content
```

### Treasury Configuration

By default, the deployer address is used as the treasury. To specify a different treasury:

```bash
npm run deploy:sepolia -- --treasury=0xYourTreasuryAddress
```

## 📋 Default Token Types

The AccessToken contract comes with three pre-configured token types:

### Token ID 1: Basic Monthly Subscription
- **Price**: 0.005 ETH
- **Duration**: 30 days
- **Permissions**: Course access, community access
- **Transferable**: No

### Token ID 2: Premium Monthly Subscription
- **Price**: 0.01 ETH
- **Duration**: 30 days
- **Permissions**: All content, features, courses, community
- **Transferable**: No

### Token ID 3: Lifetime Premium Access
- **Price**: 0.1 ETH
- **Duration**: Permanent
- **Permissions**: All current and future content
- **Transferable**: Yes
- **Max Supply**: 1,000 tokens

## 🧪 Testing

```bash
# Run all tests
npm test

# Run with coverage
npm run coverage

# Compile contracts
npm run compile
```
TypeScript support is enabled via Hardhat + ts-node. Test files live under `test/*.ts` and leverage the generated TypeChain typings. Run `npx hardhat test` to automatically compile Solidity, emit TypeChain definitions, and execute the TypeScript suites.


## 🔍 Verification

After deployment to public networks, verify contracts on Etherscan:

```bash
npx hardhat verify --network sepolia CONTRACT_ADDRESS "constructor_arg1" "constructor_arg2"
```

Verification commands are automatically generated and displayed after deployment.

## 📁 Project Structure

```
contracts/
├── contracts/
│   ├── AccessToken.sol          # ERC-1155 subscription tokens
│   └── ContentLicenseNFT.sol    # ERC-721 content licenses
├── scripts/
│   ├── deploy.js                # Basic deployment script
│   ├── deploy-multichain.js     # Multi-network deployment
│   └── manage.js                # Contract management utilities
├── test/
│   ├── AccessToken.test.js      # AccessToken tests
│   └── ContentLicenseNFT.test.js # ContentLicenseNFT tests
├── deployments/                 # Deployment artifacts
├── hardhat.config.js           # Hardhat configuration
└── package.json                # Scripts and dependencies
```

## 🔗 Integration

These contracts integrate with the Lilith platform services:

- **Token Verification Service**: Validates user access tokens
- **Payment Orchestrator**: Handles token purchases and payments
- **Content Service**: Manages content access permissions
- **User Service**: Tracks user subscriptions and licenses

## 🛡️ Security Features

### AccessToken
- Reentrancy protection on all payment functions
- Pausable in emergency situations
- Ownership controls for administrative functions
- Transfer restrictions on subscription tokens
- Usage tracking and expiration management

### ContentLicenseNFT
- Comprehensive license term enforcement
- Royalty distribution to creators
- Content verification system
- Platform fee management
- Emergency withdrawal capabilities

## 📊 Gas Optimization

Both contracts are optimized for gas efficiency:
- Batch operations support
- Efficient storage patterns
- Minimal external calls
- Optimized loops and iterations

## 🤝 Contributing

When modifying contracts:
1. Ensure all tests pass
2. Update relevant documentation
3. Test deployment on testnets
4. Verify gas costs are reasonable
5. Update integration services if needed

## 📄 License

MIT License - see LICENSE file for details.
