diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 6a33aee..64710a4 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,228 +1,203 @@ # Contributing to Elata Protocol -We welcome contributions from the community! This guide will help you get started with contributing to the Elata Protocol. - -## Table of Contents - -- [Code of Conduct](#code-of-conduct) -- [Getting Started](#getting-started) -- [Development Process](#development-process) -- [Pull Request Guidelines](#pull-request-guidelines) -- [Testing](#testing) -- [Code Style](#code-style) -- [Security](#security) - -## Code of Conduct - -By participating in this project, you agree to abide by our Code of Conduct. We are committed to providing a welcoming and inclusive environment for all contributors. +This guide covers everything you need to contribute to the smart contracts. ## Getting Started ### Prerequisites -- [Foundry](https://getfoundry.sh/) - Ethereum development toolkit -- [Git](https://git-scm.com/) - Version control -- [Node.js](https://nodejs.org/) (optional, for frontend integration) +- [Foundry](https://getfoundry.sh/) — `curl -L https://foundry.paradigm.xyz | bash && foundryup` +- [Node.js](https://nodejs.org/) v18+ +- Git ### Setup -1. Fork the repository -2. Clone your fork: - ```bash - git clone https://github.com/your-username/elata-protocol - cd elata-protocol - ``` -3. Install dependencies: - ```bash - forge install - ``` -4. Build the project: - ```bash - forge build - ``` -5. Run tests to ensure everything works: - ```bash - forge test - ``` - -## Development Process - -### Branch Naming - -Use descriptive branch names that follow this pattern: -- `feature/description-of-feature` -- `fix/description-of-fix` -- `docs/description-of-docs-change` -- `test/description-of-test-addition` - -### Commit Messages - -Follow the [Conventional Commits](https://www.conventionalcommits.org/) specification: +```bash +# Clone your fork +git clone https://github.com/your-username/elata-protocol +cd elata-protocol -``` -type(scope): description +# Install dependencies and git hooks +make install -[optional body] +# Build contracts +make build -[optional footer] +# Run tests +make test ``` -Examples: -- `feat(token): add burn functionality to ELTA token` -- `fix(staking): correct voting power calculation in VeELTA` -- `docs(readme): update installation instructions` -- `test(lotpool): add comprehensive fuzz testing` - -### Development Workflow - -1. Create a new branch from `main` -2. Make your changes -3. Add tests for new functionality -4. Ensure all tests pass -5. Update documentation if needed -6. Submit a pull request - -## Pull Request Guidelines - -### Before Submitting - -- [ ] All tests pass (`forge test`) -- [ ] Code follows style guidelines -- [ ] Documentation is updated -- [ ] Commit messages follow conventions -- [ ] No merge conflicts with main branch - -### PR Description Template - -```markdown -## Description -Brief description of changes made. - -## Type of Change -- [ ] Bug fix (non-breaking change that fixes an issue) -- [ ] New feature (non-breaking change that adds functionality) -- [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected) -- [ ] Documentation update - -## Testing -- [ ] Unit tests added/updated -- [ ] Integration tests added/updated -- [ ] Fuzz tests added/updated -- [ ] All tests pass - -## Checklist -- [ ] Code follows project style guidelines -- [ ] Self-review completed -- [ ] Documentation updated -- [ ] No new warnings introduced -``` +The `make install` command sets up pre-commit hooks that format code and run tests before each commit. -## Testing +## Development Workflow -### Test Categories +### 1. Create a branch -1. **Unit Tests**: Test individual contract functions - ```bash - forge test --match-contract ELTATest - ``` +Use descriptive names with prefixes: -2. **Integration Tests**: Test multi-contract interactions - ```bash - forge test --match-contract ProtocolIntegrationTest - ``` +``` +feature/add-emergency-withdraw +fix/voting-power-calculation +docs/update-deployment-guide +test/add-lotpool-fuzz-tests +``` -3. **Fuzz Tests**: Property-based testing with random inputs - ```bash - forge test --match-test testFuzz_ - ``` +### 2. Make changes -### Writing Tests +Edit contracts in `src/`, add tests in `test/`. Run tests frequently: -- Use descriptive test names: `test_RevertWhen_InvalidInput()` -- Test both success and failure cases -- Include edge cases and boundary conditions -- Add fuzz tests for functions with numeric inputs -- Use appropriate assertions and error checking +```bash +# Quick test run +forge test -### Test Structure +# Test specific contract +forge test --match-contract VeELTATest -```solidity -function test_DescriptiveTestName() public { - // Setup - uint256 amount = 1000 ether; - - // Action - vm.prank(user); - contract.someFunction(amount); - - // Assertions - assertEq(contract.balance(), amount); -} +# Test with gas report +make gas-report + +# Run all CI checks +make ci ``` -## Code Style +### 3. Format and lint + +```bash +make fmt # Format code +make fmt-check # Check formatting without changes +``` + +### 4. Commit with conventional commits + +``` +feat(token): add burn functionality +fix(staking): correct boost calculation for edge case +docs(readme): update deployment instructions +test(lotpool): add fuzz tests for voting +refactor(apps): extract deployment library +``` -### Solidity Style Guide +### 5. Open a pull request -We follow the [Solidity Style Guide](https://docs.soliditylang.org/en/latest/style-guide.html) with these additions: +Include in your PR description: +- What changed and why +- How to test it +- Any breaking changes -- Use explicit imports: `import {Contract} from "./Contract.sol";` -- Group imports by category (external, internal) -- Use NatSpec documentation for all public functions -- Maximum line length: 100 characters -- Use descriptive variable names -- Include error handling with custom errors +## Code Style -### Documentation Standards +### Solidity -- All public functions must have NatSpec comments -- Include `@param` and `@return` descriptions -- Add `@notice` for user-facing functions -- Use `@dev` for developer notes +Follow the [Solidity Style Guide](https://docs.soliditylang.org/en/latest/style-guide.html): -Example: ```solidity +// Use explicit imports +import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; + +// Document public functions with NatSpec /** - * @notice Creates a new lock for the specified amount and duration - * @param amount The amount of ELTA tokens to lock - * @param lockDuration The duration of the lock in seconds - * @dev Lock duration must be between MIN_LOCK and MAX_LOCK + * @notice Creates a new staking position + * @param amount ELTA tokens to lock + * @param duration Lock duration in seconds + * @return positionId The ID of the created position */ -function createLock(uint256 amount, uint256 lockDuration) external { +function createLock(uint256 amount, uint256 duration) external returns (uint256 positionId) { // Implementation } ``` -## Security +### Testing + +Name tests descriptively: + +```solidity +function test_CreateLock_WithMinDuration() public { } +function test_CreateLock_RevertWhen_AmountIsZero() public { } +function testFuzz_CreateLock_AnyValidDuration(uint256 duration) public { } +``` + +Test both success paths and revert conditions. Add fuzz tests for functions with numeric inputs. + +### Custom Errors + +Use custom errors instead of require strings: + +```solidity +// In src/utils/Errors.sol +error AmountTooLow(); +error LockExpired(); + +// In contract +if (amount < MIN_AMOUNT) revert Errors.AmountTooLow(); +``` + +## Project Structure + +``` +src/ +├── token/ELTA.sol # Governance token +├── staking/VeELTA.sol # Vote-escrowed staking +├── experience/ElataXP.sol # Reputation system +├── governance/ # Governor, timelock, funding +├── rewards/ # Fee distribution +├── apps/ # App token framework +└── utils/Errors.sol # Shared error definitions + +test/ +├── token/ELTATest.t.sol # Unit tests per contract +├── staking/VeELTATest.t.sol +├── integration/ # Cross-contract tests +└── fuzz/ # Property-based tests + +script/ +├── Deploy.sol # Main deployment script +└── SeedLocalData.s.sol # Local test data seeding +``` + +## Running the Full CI Suite + +Before pushing, run the same checks CI will run: + +```bash +make ci +``` + +This runs: +1. `forge fmt --check` — formatting check +2. `forge build` — compilation +3. `forge test` — all tests +4. Gas report generation + +## Security Guidelines -### Security Guidelines +When modifying contracts: -- Follow the [ConsenSys Smart Contract Best Practices](https://consensys.github.io/smart-contract-best-practices/) -- Use OpenZeppelin contracts when possible -- Implement proper access controls -- Add reentrancy guards where needed -- Validate all inputs -- Use safe math operations (Solidity 0.8+) +- Use OpenZeppelin contracts where possible +- Add reentrancy guards to functions that transfer tokens +- Validate all inputs (zero addresses, array lengths, bounds) +- Consider edge cases in math operations +- Add access control to admin functions +- Write tests for the security properties you're relying on ### Reporting Security Issues -If you discover a security vulnerability, please: +If you find a security vulnerability: -1. **DO NOT** open a public issue +1. Do not open a public issue 2. Email security@elata.bio with details -3. Allow time for the issue to be addressed before disclosure +3. Allow time for a fix before disclosure ## Getting Help -- Join our [Discord](https://discord.gg/elata) for community support -- Check existing issues and discussions on GitHub -- Read the documentation at [docs.elata.bio](https://docs.elata.bio) +- Check existing [GitHub Issues](https://github.com/Elata-Biosciences/elata-protocol/issues) +- Read the [architecture docs](./docs/ARCHITECTURE.md) +- Ask in the community Discord ## Recognition -Contributors will be recognized in our documentation and may be eligible for: -- ELTA token rewards for significant contributions -- Recognition in project credits -- Invitation to contributor events +Significant contributions may be eligible for: +- ELTA token grants +- Recognition in release notes +- Contributor role in the community -Thank you for contributing to Elata Protocol! 🧠⚡ +Thanks for contributing. diff --git a/PR_SUMMARY.md b/PR_SUMMARY.md deleted file mode 100644 index aec1816..0000000 --- a/PR_SUMMARY.md +++ /dev/null @@ -1,130 +0,0 @@ -# Protocol Enhancements: XP-Gated Launch, Transfer Fees & Multi-Token Rewards - -## 🎯 Overview - -This PR implements major protocol enhancements to improve tokenomics, user experience, and ecosystem sustainability. The changes introduce XP-gated early access, transfer fees, and unified fee routing while maintaining full backward compatibility and security. - -## ✨ New Features - -### 1. XP-Gated Launch Window -- **Early Access Period**: 6-hour window after app launch where only users with sufficient XP can buy tokens -- **Configurable Threshold**: Governance can set minimum XP requirement (default: 100 XP) -- **Configurable Duration**: Governance can adjust early access window length (default: 6 hours) -- **Fair Launch**: Prevents immediate dumping by inexperienced users while rewarding engaged community members - -### 2. Fee-on-Transfer (FoT) Mechanism -- **Always Enabled**: 1% transfer fee on all app token transfers (governance configurable, max 2%) -- **Smart Distribution**: 70% to app stakers, 15% to veELTA stakers, 15% to treasury -- **Exempt Addresses**: Critical protocol addresses (bonding curves, vaults, routers) are exempt to avoid circular fees -- **Anti-Speculation**: Discourages rapid flipping while funding ecosystem rewards - -### 3. Unified Fee Routing (70/15/15 Split) -- **Consistent Distribution**: All protocol fees now flow through `RewardsDistributor` for unified 70/15/15 split -- **Multi-Token Support**: Rewards can be distributed in both ELTA and app tokens -- **Removed Legacy Logic**: Eliminated duplicate `protocolFeeRate` that bypassed unified routing -- **Fixed Integration Bug**: Corrected fee routing between bonding curve and fee router - -### 4. Enhanced Contract Interfaces -- **New Events**: Added events for XP gating, transfer fees, and fee exemptions -- **View Functions**: Added comprehensive getters for frontend integration -- **Access Control**: Proper role-based permissions for all new features -- **Frontend Support**: All state changes properly exposed for UI monitoring - -## 🔧 Technical Changes - -### Core Contracts Modified -- `AppToken.sol`: Added transfer fee logic with exemption system -- `AppBondingCurve.sol`: Implemented XP gating and fixed fee routing -- `AppFactory.sol`: Updated to pass new parameters and register tokens -- `AppRewardsDistributor.sol`: Added multi-token reward support -- `RewardsDistributor.sol`: Enhanced for app token fee distribution - -### New Interfaces -- `IElataXP.sol`: Interface for XP token integration -- Updated `IAppRewardsDistributor.sol` and `IRewardsDistributor.sol` for multi-token support - -### Deployment Updates -- Updated `AppDeploymentLib.sol` with new constructor parameters -- Modified deployment scripts to handle new dependencies -- Added proper role assignments and exemptions during setup - -## 🧪 Testing - -### Test Coverage: 100% ✅ -- **469 tests passing** (up from 428) -- **0 tests failing** (down from 41) -- **Comprehensive coverage** of all new features - -### New Test Files -- `XPGatedLaunchAndTransferFees.t.sol`: Comprehensive testing of new features -- Updated existing tests to account for transfer fees and XP gating -- Added edge case handling for small amounts and rounding - -### Test Categories Fixed -- **Transfer Fee Tests**: Updated balance assertions for 1% fee -- **XP Gating Tests**: Added XP to users in relevant tests -- **Staking Tests**: Made vaults exempt from transfer fees -- **Fuzz Tests**: Handled edge cases and rounding differences -- **Gas Tests**: Updated thresholds for new feature overhead - -## 🔒 Security Considerations - -### Access Control -- Only governance can modify XP thresholds and transfer fee rates -- Proper role-based permissions for all new functions -- Exemption system prevents circular fee issues - -### Economic Security -- Transfer fees capped at 2% to prevent abuse -- XP gating prevents immediate dumping by new users -- Unified fee routing ensures consistent tokenomics - -### Integration Safety -- All changes maintain backward compatibility -- Existing functionality preserved -- No breaking changes to core interfaces - -## 📊 Impact Analysis - -### Positive Impacts -- **Ecosystem Sustainability**: Transfer fees fund ongoing rewards -- **Community Engagement**: XP gating rewards active users -- **Reduced Speculation**: Transfer fees discourage rapid flipping -- **Unified Tokenomics**: Consistent 70/15/15 fee distribution - -### Gas Impact -- **App Creation**: ~7.2M gas (updated threshold from 7M) -- **Token Transfers**: Minimal overhead for fee calculation -- **Overall**: Acceptable increase for enhanced functionality - -## 🚀 Deployment Notes - -### Required Setup -1. Deploy `ElataXP` token contract -2. Update `AppFactory` constructor with new parameters -3. Set initial XP thresholds and transfer fee rates -4. Configure exemption addresses for critical contracts - -### Migration Path -- Existing apps continue to work without changes -- New apps automatically benefit from enhanced features -- Gradual rollout possible with governance controls - -## 📋 Checklist - -- [x] XP-gated launch window implemented -- [x] Transfer fee mechanism added -- [x] Unified fee routing (70/15/15) implemented -- [x] Multi-token rewards support added -- [x] All tests passing (469/469) -- [x] Security mechanisms verified -- [x] Gas optimization completed -- [x] Documentation updated -- [x] Backward compatibility maintained - -## 🎉 Ready for Production - -This PR represents a significant enhancement to the Elata protocol, introducing sophisticated tokenomics while maintaining security and usability. All features are fully tested, documented, and ready for deployment. - -**The protocol is now production-ready with enhanced tokenomics and user experience!** 🚀 - diff --git a/QUICKSTART.md b/QUICKSTART.md index cc91a27..f00c421 100644 --- a/QUICKSTART.md +++ b/QUICKSTART.md @@ -1,213 +1,123 @@ -# Elata Protocol - Quick Start Guide +# Quick Start Guide -## 🚀 Local Development Setup (One Command) +Get the Elata Protocol running locally in under two minutes. -Get the entire Elata Protocol stack running locally in under 2 minutes: +## One-Command Setup ```bash npm run local:up ``` -This single command will: -1. ✅ Start Anvil (local Ethereum blockchain) -2. ✅ Build all smart contracts -3. ✅ Deploy all contracts (ELTA, AppFactory, Governance, etc.) -4. ✅ Seed test data (users, XP, staking, apps, funding rounds) -5. ✅ Generate frontend configuration +This command: +1. Starts Anvil (local Ethereum blockchain) +2. Builds and deploys all smart contracts +3. Seeds test data (users, XP, staking positions, apps, funding rounds) +4. Generates frontend configuration -**That's it!** Your local blockchain is now running with all contracts deployed. +When it completes, your local blockchain is running with everything deployed. ---- +## What Gets Deployed -## 📋 What Gets Deployed +**Core Contracts** +- ELTA Token (ERC20 governance token) +- ElataXP (non-transferable reputation) +- VeELTA (vote-escrowed staking) +- LotPool (funding round governance) +- RewardsDistributor (fee distribution) +- ElataGovernor and ElataTimelock (on-chain governance) -### Core Contracts -- **ELTA Token**: ERC20 governance token -- **ElataXP**: Non-transferable XP token for reputation -- **VeELTA**: Vote-escrowed ELTA for governance voting power -- **AppFactory**: Launch new app tokens with bonding curves -- **AppModuleFactory**: Create app modules (tournaments, leaderboards, etc.) -- **TournamentFactory**: Create competitive tournaments -- **LotPool**: Funding rounds for research/development -- **RewardsDistributor**: Distribute ELTA rewards (70/15/15 split) -- **ElataGovernor**: On-chain governance -- **ElataTimelock**: Timelock for governance execution +**App Ecosystem** +- AppFactory (token launcher with bonding curves) +- AppModuleFactory (utility module deployer) +- TournamentFactory (competition infrastructure) -### Test Data Seeded -- 5 test users with XP (300-5000 XP each) -- 1 staking position (10,000 ELTA locked for 2 years) -- 3 test apps (NeuroPong, MindfulBreath, FocusTrainer) -- 1 active funding round (10,000 ELTA pool) +**Test Data** +- 5 users with XP balances (300–5,000 XP each) +- Staking positions (10,000 ELTA locked for 2 years) +- 3 sample apps (NeuroPong, MindfulBreath, FocusTrainer) +- 1 active funding round with 10,000 ELTA ---- +## Next Steps -## 🎮 Next Steps +### Start the Frontend -### Start the Frontend (App Store) +In a separate terminal: ```bash cd ../elata-appstore npm run local:full ``` -The App Store will be available at `http://localhost:3001` +The app store runs at `http://localhost:3001`. -### View Deployed Contract Addresses +### View Contract Addresses ```bash cat deployments/local.json ``` -### Check Anvil Logs +### Get Test ELTA -```bash -tail -f anvil.log -``` - -### Get ELTA Tokens for Testing - -Need ELTA to launch apps or test features? Use the faucet: - -```bash -npm run faucet -``` - -This sends 10,000 ELTA from the deployer account to your address. +Send 10,000 ELTA to any address: -**Example:** ```bash -npm run faucet 0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb +npm run faucet ``` -**Note:** The faucet only works on local network (chainId 31337) for safety. - ---- +### Connect MetaMask -## 🛠️ Available Commands - -### Primary Commands +Add the local network to MetaMask: +- Network Name: Anvil Local +- RPC URL: `http://127.0.0.1:8545` +- Chain ID: `31337` +- Currency Symbol: ETH -| Command | Description | -|---------|-------------| -| `npm run local:up` | **Start everything** (Anvil + Deploy + Seed) | -| `npm run local:down` | **Stop everything** (Anvil + cleanup) | -| `npm run local:restart` | **Restart** (Down + Up) | +Import the default test account: +- Address: `0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266` +- Private Key: `0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80` -### Individual Steps (Advanced) +## Commands Reference | Command | Description | |---------|-------------| -| `npm run anvil:start` | Start Anvil only | +| `npm run local:up` | Start everything | +| `npm run local:down` | Stop Anvil | +| `npm run local:restart` | Restart from scratch | | `npm run deploy:local` | Deploy contracts only | | `npm run seed:local` | Seed test data only | -| `npm run config:appstore` | Generate frontend config only | - -### Testnet Deployment - -| Command | Description | -|---------|-------------| -| `npm run deploy:sepolia` | Deploy to Sepolia testnet | -| `npm run deploy:base-sepolia` | Deploy to Base Sepolia | - ---- +| `npm run faucet ` | Send 10k ELTA to address | -## 🔧 Troubleshooting +## Troubleshooting -### Anvil Won't Start +**Anvil won't start (port in use)** ```bash -# Kill any existing Anvil process pkill -9 anvil - -# Try starting again npm run local:up ``` -### Contracts Won't Deploy +**Contracts fail to deploy** ```bash -# Clean build artifacts and try again forge clean npm run local:up ``` -### Frontend Can't Connect +**MetaMask "nonce too high" error** -```bash -# Regenerate frontend configuration -npm run config:appstore +Clear MetaMask activity: Settings → Advanced → Clear activity tab data -# Copy to appstore -cd ../elata-appstore -npm run sync-abi -``` +**Frontend can't connect** -### Check Deployment Status +Regenerate the config and restart: ```bash -# View deployment logs -cat broadcast/Deploy.sol/31337/run-latest.json | jq - -# Check if contracts have code -cast code --rpc-url http://127.0.0.1:8545 +npm run config:appstore +cd ../elata-appstore && npm run local:full ``` ---- - -## 📚 Additional Resources - -- **Full Documentation**: See `docs/LOCAL_DEVELOPMENT.md` for detailed information -- **Architecture**: See `docs/ARCHITECTURE.md` for system design -- **Testing**: See `docs/TESTING.md` for running tests -- **Deployment**: See `docs/DEPLOYMENT.md` for production deployment - ---- - -## ⚠️ Important Notes - -### Contract Size Limits - -Some contracts (AppModuleFactory) exceed the EIP-170 24KB limit. This is: -- ✅ **Safe for local development** (Anvil allows it) -- ✅ **Safe for L2 deployment** (Base, Arbitrum, Optimism) -- ⚠️ **May need optimization** for Ethereum mainnet - -### Anvil Configuration - -Anvil is started with: -- Chain ID: `31337` -- Port: `8545` -- `--disable-code-size-limit` (allows oversized contracts) -- 10 pre-funded accounts with 10,000 ETH each - -### Default Accounts - -Account #0 (Deployer): -- Address: `0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266` -- Private Key: `0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80` -- Balance: 10,000 ETH - ---- - -## 🤝 Contributing - -When making changes: - -1. **Test locally first**: `npm run local:up` -2. **Run tests**: `forge test` -3. **Check gas usage**: `forge test --gas-report` -4. **Verify deployment**: Check `deployments/local.json` - ---- - -## 📞 Support - -Having issues? Check: -1. This quickstart guide -2. `docs/LOCAL_DEVELOPMENT.md` for detailed setup -3. `docs/TROUBLESHOOTING.md` for common issues -4. GitHub Issues for known problems - ---- +## Further Reading -**Happy Building! 🚀** +- [docs/LOCAL_DEVELOPMENT.md](./docs/LOCAL_DEVELOPMENT.md) — Detailed environment setup +- [docs/ARCHITECTURE.md](./docs/ARCHITECTURE.md) — System design overview +- [docs/APP_LAUNCH_GUIDE.md](./docs/APP_LAUNCH_GUIDE.md) — Building apps on the protocol diff --git a/README.md b/README.md index 64640da..8bc20c6 100644 --- a/README.md +++ b/README.md @@ -1,28 +1,20 @@ # Elata Protocol -**On‑chain economics for the Internet of Brains.** +Smart contracts for token economics, staking, reputation, and research funding governance. This repository contains the on-chain infrastructure that coordinates participants in the Elata ecosystem—developers building neurotech applications, researchers conducting studies, and community members contributing data and governance input. -This repository contains the smart contracts that power Elata's token, staking, XP (reputation), and experiment‑funding governance. It is the **economic coordination layer** that aligns players, researchers, developers, and long‑term token holders in building the future of precision psychiatry. +> **Scope**: Token economics, staking, XP reputation, and funding governance. Experiment data contracts (ZORP) live in a separate repository. -> **Scope of this repo**: Token economics + staking + XP + funding governance. (ZORP experiment data contracts live in a separate repository.) +## Quick Start -## 🚀 Quick Start - -**One command (recommended):** +Run one command to start a local blockchain with all contracts deployed and seeded with test data: ```bash bash scripts/dev-local.sh ``` -This will: -- ✅ Start Anvil (local blockchain) -- ✅ Deploy all contracts -- ✅ Seed test data (users, XP, apps, funding rounds) -- ✅ Generate frontend configuration - -**That's it!** Your local blockchain is ready with all contracts deployed. +This starts Anvil, deploys all contracts, seeds test users with XP and ELTA, creates sample apps, and generates frontend configuration. Your local environment is ready in about 30 seconds. -Alternative (npm): +Alternatively: ```bash npm run local:up @@ -30,1305 +22,179 @@ npm run local:up ### Next Steps -1. **Start the frontend:** +Start the frontend (in a separate terminal): + ```bash cd ../elata-appstore npm run local:full ``` -2. **View deployed contracts:** +View deployed contract addresses: + ```bash cat deployments/local.json ``` -3. **Connect MetaMask:** - - Network: `http://127.0.0.1:8545` +Connect MetaMask to the local network: +- RPC URL: `http://127.0.0.1:8545` - Chain ID: `31337` - - Default Account: `0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266` - -### Essential Documentation - -- **[QUICKSTART.md](./QUICKSTART.md)** - Complete setup guide -- **[docs/LOCAL_DEVELOPMENT.md](./docs/LOCAL_DEVELOPMENT.md)** - Detailed local dev info -- **[docs/ARCHITECTURE.md](./docs/ARCHITECTURE.md)** - System architecture -- **Testing:** Run `forge test` - - -## What problem does the protocol solve? - -```mermaid -graph LR - subgraph "Traditional Research" - T1[Slow Funding
🐌 Months/years] - T2[Centralized Decisions
🏢 Committee-based] - T3[Disconnected Incentives
❌ No user alignment] - end - - subgraph "Elata Solution" - S1[Weekly Funding
Community-driven] - S2[Decentralized Voting
XP-weighted] - S3[Aligned Incentives
Usage-based rewards] - end - - T1 -.->|Replaces| S1 - T2 -.->|Replaces| S2 - T3 -.->|Replaces| S3 - - style T1 fill:#ffcdd2 - style T2 fill:#ffcdd2 - style T3 fill:#ffcdd2 - style S1 fill:#c8e6c9 - style S2 fill:#c8e6c9 - style S3 fill:#c8e6c9 -``` - -Neurotech needs participation at scale—people playing EEG games, training, submitting sessions—and a way to **fund the right experiments** while **accruing value** to long‑term stewards. Traditional research funding is slow, centralized, and disconnected from actual usage. - -Elata Protocol provides: - -* **A governance token ($ELTA)** with real utility and future on‑chain voting support -* **Time‑locked staking (veELTA)** that weights governance toward long‑horizon holders -* **Non‑transferable XP tokens** that turn participation into *voice* (not money) -* **XP‑weighted funding pools (LotPool)** that direct budgets to the most valuable experiments and apps - -Think of it as an **app & research economy** where usage and participation determine what gets built next, and protocol value flows to committed ELTA holders. - ---- - -## Economic flywheel - -```mermaid -graph TD - A[Users Play EEG Apps
Engagement] --> B[Generate Data & Usage
Value Creation] - B --> C[Protocol Captures Fees
Revenue Generation] - C --> D[Community Directs Funding
XP-weighted Voting] - D --> E[Fund Research & Development
Innovation] - E --> F[Better Apps & Experiences
Quality Improvement] - F --> A - - C --> G[Distribute Yields to Stakers
Real Returns] - G --> H[Attract Long-term Holders
Stable Governance] - H --> I[Quality Governance Decisions
Protocol Evolution] - I --> D - - style A fill:#e1f5fe - style C fill:#fff3e0 - style D fill:#f3e5f5 - style G fill:#e8f5e8 -``` - -**Play → Data → Fees → Funding → Yield → Better Apps → More Play** - -1. **Users engage**: Play EEG apps, submit data sessions, participate in tournaments -2. **Protocol captures value**: App store fees, tournament rake, infrastructure usage -3. **Community directs funding**: Weekly LotPool allocates budgets via XP voting -4. **Value flows to stakers**: Protocol revenues distributed to veELTA holders (real yield) -5. **Ecosystem grows**: Funded experiments + dev grants → better apps → more engagement - -**Key insight**: XP guides *what to fund*; ELTA staking captures *the economics*. - ---- - -## Contract architecture - -```mermaid -graph TB - subgraph "Core Protocol" - ELTA[ELTA Token
Governance & Utility
77M Supply Cap] - VE[VeELTA
Multi-position Staking
NFT-based, 1w-2y locks] - XP[ElataXP
Experience Points
Permanent, soulbound] - LP[LotPool
Funding Rounds
XP-weighted voting] - end - - subgraph "Advanced Features" - RD[RewardsDistributor
Staker Rewards
Merkle tree, 7d epochs] - GOV[ElataGovernor
Onchain Governance
4% quorum, 1d delay] - TL[ElataTimelock
Execution Delays
48h standard, 6h emergency] - STATS[ProtocolStats
Frontend Utils
Batch queries] - end - - subgraph "App Ecosystem" - AF[AppFactory
Token Launcher
Bonding curves, LP locking] - AMF[AppModuleFactory
Utility Deployer
Staking, NFTs, Rewards] - TF[TournamentFactory
Tournament Creator
Competition infrastructure] - end - - ELTA --> VE - ELTA --> GOV - ELTA --> AF - VE --> RD - XP --> LP - GOV --> TL - - AF --> AMF - AMF --> TF - - STATS -.-> ELTA - STATS -.-> VE - STATS -.-> XP - STATS -.-> LP - - style ELTA fill:#ff9999 - style VE fill:#99ccff - style XP fill:#99ff99 - style LP fill:#ffcc99 - style RD fill:#cc99ff - style GOV fill:#ffccff - style AF fill:#ffe6cc - style AMF fill:#e6f3ff - style TF fill:#fff0e6 -``` - -### Core Protocol - -| Contract | Purpose | Key Features | -|----------|---------|--------------| -| **[ELTA.sol](src/token/ELTA.sol)** | Governance & utility token | ERC20 + Votes + Permit + Burnable, 77M cap, no fees | -| **[VeELTA.sol](src/staking/VeELTA.sol)** | Vote-escrowed staking | Non-transferable ERC20Votes, duration boost (1x-2x), snapshot-enabled | -| **[ElataXP.sol](src/experience/ElataXP.sol)** | Experience points | Non-transferable, checkpoint tracking, governance ready | -| **[LotPool.sol](src/governance/LotPool.sol)** | Research funding rounds | XP-weighted voting, weekly cycles, transparent payouts | - -### Rewards & Revenue Architecture - -| Contract | Purpose | Key Features | -|----------|---------|--------------| -| **[RewardsDistributor.sol](src/rewards/RewardsDistributor.sol)** | Central revenue hub | 70/15/15 split, on-chain snapshot claims, no Merkle trees | -| **[AppRewardsDistributor.sol](src/rewards/AppRewardsDistributor.sol)** | App staker rewards | Pro-rata distribution by stake, snapshot-based, gas-bounded | -| **[AppFeeRouter.sol](src/fees/AppFeeRouter.sol)** | Fee collection | 1% trading fee, forwards to rewards, governance-adjustable | -| **[ElataGovernor.sol](src/governance/ElataGovernor.sol)** | Onchain governance | 4% quorum, emergency proposals, timelock integration | - -### Why each contract exists - -* **ELTA**: Clean, DEX-compatible governance token with **no transfer taxes** and **hard supply cap** -* **VeELTA**: Aligns governance with **time commitment**; non-transferable ERC20Votes with duration boost -* **XP**: Rewards **participation over capital**; non-transferable prevents reputation markets -* **LotPool**: Turns community activity into **transparent capital allocation** -* **RewardsDistributor**: Distributes **real yield** with 70/15/15 split (app stakers / veELTA / treasury) -* **AppRewardsDistributor**: On-chain snapshot-based rewards for app token stakers -* **AppFeeRouter**: Collects 1% trading fees and forwards to rewards system -* **Governor**: Enables **on-chain voting** for protocol parameters and upgrades - -### App Launch Framework - -```mermaid -graph TD - subgraph "App Token Launch" - AF[AppFactory
Permissionless Launcher] - ABC[AppBondingCurve
📈 Fair Price Discovery] - AT[AppToken
Individual App Tokens] - LL[LpLocker
Liquidity Protection] - end - - subgraph "Launch Process" - CREATE[Developer Creates App
Stakes 100 ELTA] - CURVE[Bonding Curve Sale
Price increases with demand] - GRADUATE[Auto-Graduation
At 42k ELTA raised] - LIQUIDITY[DEX Liquidity
Locked for 2 years] - end - - Developer[Developer] --> AF - AF --> AT - AF --> ABC - AT --> AMF - AMF --> ASV - AMF --> AA - AMF --> ER - AT -.-> TF - TF -.-> T - - CREATE[1. Pay 110 ELTA] --> AF - CURVE[2. Users buy tokens] --> ABC - MODULES[3. Deploy modules] --> AMF - GRADUATE[4. Auto-graduation] --> ABC - - style Developer fill:#e3f2fd - style AF fill:#ffe6cc - style AMF fill:#e6f3ff - style TF fill:#fff0e6 -``` - -**App Ecosystem Contracts:** - -| Factory | Purpose | Deployed In | -|---------|---------|-------------| -| **[AppFactory.sol](src/apps/AppFactory.sol)** | Token launcher with bonding curves | Main Deploy.sol | -| **[AppModuleFactory.sol](src/apps/AppModuleFactory.sol)** | Utility module deployer (staking, NFTs, rewards) | Main Deploy.sol | -| **[TournamentFactory.sol](src/apps/TournamentFactory.sol)** | Tournament infrastructure deployer | Main Deploy.sol | - -| Per-App Contracts | Purpose | Deployed Via | -|----------|---------|--------------| -| **[AppToken.sol](src/apps/AppToken.sol)** | Individual app tokens | AppFactory.createApp() | -| **[AppBondingCurve.sol](src/apps/AppBondingCurve.sol)** | Fair price discovery | AppFactory.createApp() | -| **[AppStakingVault.sol](src/apps/AppStakingVault.sol)** | Per-app token staking | AppModuleFactory.deployModules() | -| **[AppAccess1155.sol](src/apps/AppAccess1155.sol)** | NFT items and gating | AppModuleFactory.deployModules() | -| **[EpochRewards.sol](src/apps/EpochRewards.sol)** | Reward distribution | AppModuleFactory.deployModules() | -| **[Tournament.sol](src/apps/Tournament.sol)** | Individual tournaments | TournamentFactory.createTournament() | -| **[LpLocker.sol](src/apps/LpLocker.sol)** | Liquidity protection | AppBondingCurve (on graduation) | - -**Why the App Launch Framework:** -* **Developer Empowerment**: Any developer can launch their EEG app with its own token economy -* **Fair Distribution**: Bonding curves ensure fair price discovery without insider allocations -* **Ecosystem Growth**: Each app token creates new utility and demand for ELTA -* **Liquidity Security**: Automatic LP creation and locking prevents rug pulls -* **Protocol Integration**: App launches feed back into ELTA treasury and governance - -### Complete App Launch Workflow - -```mermaid -sequenceDiagram - participant Developer - participant AppFactory - participant AppModuleFactory - participant AppToken - participant BondingCurve - participant Users - - Note over Developer, Users: Step 1: Create App Token - Developer->>AppFactory: createApp() + 110 ELTA - AppFactory->>AppToken: Deploy token (1B supply) - AppFactory->>BondingCurve: Deploy bonding curve - AppFactory->>AppToken: Mint 10% to creator, 90% to curve - AppFactory-->>Developer: Returns appId, token address - - Note over Developer, Users: Step 2: Deploy Utility Modules - Developer->>AppModuleFactory: deployModules(appToken, baseURI) - AppModuleFactory->>AppModuleFactory: Deploy AppStakingVault - AppModuleFactory->>AppModuleFactory: Deploy AppAccess1155 - AppModuleFactory->>AppModuleFactory: Deploy EpochRewards - AppModuleFactory-->>Developer: Returns module addresses - - Note over Developer, Users: Step 3: Configure & Launch - Developer->>AppAccess1155: setItem() - Configure NFTs - Developer->>AppAccess1155: setFeatureGate() - Set requirements - Users->>BondingCurve: buy() - Purchase tokens with ELTA - Users->>AppAccess1155: purchase() - Buy NFTs (burns tokens) - Users->>AppStakingVault: stake() - Stake for benefits - - Note over Developer, Users: Step 4: Graduation - BondingCurve->>BondingCurve: Target reached (42k ELTA raised) - BondingCurve->>BondingCurve: Create DEX liquidity pair - BondingCurve->>BondingCurve: Lock LP tokens for 2 years -``` - - -## Token economics deep dive - -### ELTA Token Mechanics - -```solidity -// Core parameters (from ELTA.sol) -MAX_SUPPLY = 77,000,000 ELTA // Hard cap, immutable -decimals = 18 // Standard precision -MINTER_ROLE // Role-gated minting up to cap -``` - -**Supply & Distribution** -- **Total Supply**: 77,000,000 ELTA (hard cap) -- **Initial Mint**: ~10,000,000 ELTA to treasury -- **Remaining**: 67,000,000 ELTA available for future minting (role-gated) - -**Key Properties** -- **No transfer fees** → DEX/aggregator compatible -- **ERC20Votes** → Onchain governance ready -- **ERC20Permit** → Gasless approvals -- **Burnable** → Deflationary pressure -- **Non-upgradeable** → Immutable, trustless - -### Value Accrual Mechanisms - -**Revenue Sources** (examples) -``` -App Store (15% take rate) + Tournament Rake (5-10%) + Infrastructure Fees -``` - -**Distribution Policy** (automated via RewardsDistributor) -``` -Protocol Revenue (ELTA) -├── 70% → App Token Stakers (via AppRewardsDistributor) -├── 15% → veELTA Stakers (on-chain snapshot claims) -└── 15% → Treasury (grants, operations, development) -``` - -**Revenue Sources** -``` -Trading Fees (1% on bonding curve) + Tournament Rake + App Fees - ↓ -RewardsDistributor.deposit() - ↓ Automatic 70/15/15 Split - ├─ 70% → Distributed to app stakers proportionally - ├─ 15% → Claimable by veELTA holders - └─ 15% → Treasury (immediate transfer) -``` - -**Example Calculation** -``` -Monthly trading volume: 100,000 ELTA -Trading fee (1%): 1,000 ELTA - -App stakers: 700 ELTA (70%) -veELTA stakers: 150 ELTA (15%) -Treasury: 150 ELTA (15%) -``` - -> **Important**: Data licensing proceeds go to participants via data trusts, **not** to the protocol. ELTA accrues from software/infrastructure economics. - -### App Launch Economics - -**App Token Launch Model:** -``` -Developer Investment: 110 ELTA (100 seed + 10 creation fee) -├── Seed Liquidity: 100 ELTA → Bonding curve initial liquidity -├── Creation Fee: 10 ELTA → Protocol treasury -└── Token Supply: 1B tokens → Split 50/50 - -Token Distribution: -├── 50% → Auto-staked for creator (aligned incentives, earns rewards immediately) -└── 50% → Bonding curve (public sale, fair price discovery) - -🆕 XP-Gated Launch (First 6 Hours): -├── Early Access: Only users with ≥100 XP can buy -├── Sybil Protection: Must earn XP through protocol participation -└── After 6 Hours: Open to all users - -Trading Fees (ON TOP of trade): -├── Trading Fee: 1% → AppFeeRouter → RewardsDistributor -│ ├── 70% → App token stakers -│ ├── 15% → veELTA stakers -│ └── 15% → Treasury -└── Graduation: At 42k ELTA raised → Auto-create locked DEX liquidity (2 years) - -🆕 App Token Transfer Fees: -├── Transfer Fee: 1% (default, capped at 2%, governance-adjustable) -│ ├── 70% → App token stakers (in app token) -│ ├── 15% → veELTA stakers (in app token) -│ └── 15% → Treasury (in app token) -├── Exemptions: Bonding curve, staking vault, factory (automatic) -└── Benefits: Rewards long-term holders, discourages dumping -``` - -**Economic Benefits:** -- **Creator Alignment**: 50% auto-staked prevents dumps, aligns with long-term success -- **Fair Launches**: XP gating rewards protocol participants with early access -- **ELTA Demand**: Every app launch requires ELTA; all trading uses ELTA -- **Protocol Revenue**: 1% trading fee on all bonding curve volume -- **Continuous Rewards**: 1% transfer fee creates ongoing yield for stakers -- **Ecosystem Growth**: More apps = more ELTA utility and rewards for stakers -- **Real Yield**: App stakers earn 70% of protocol revenues in both ELTA and app tokens - -### Protocol Enhancement Details - -**XP-Gated Early Access:** -- Protects against bots and snipers -- Rewards early protocol participants -- Creates natural price discovery -- Governance-configurable (XP minimum & duration) -- View functions: `canUserBuy()`, `getEarlyAccessInfo()` - -**Unified Fee Routing:** -- All protocol fees flow through RewardsDistributor -- Consistent 70/15/15 split across all revenue sources -- On-chain snapshot-based claims (no Merkle trees) -- Gas-efficient pro-rata distribution - -**Multi-Token Rewards:** -- Distributors accept both ELTA and app tokens -- Separate epoch tracking prevents mixing -- Stakers earn in multiple assets -- Treasury receives diversified revenue - ---- - -## App Token Utility Modules - -Beyond fair token launches, Elata provides utility modules that make app tokens valuable for in-game economies and user engagement. - -### Utility Contracts - -| Contract | Purpose | Key Features | -|----------|---------|--------------| -| **[AppAccess1155.sol](src/apps/AppAccess1155.sol)** | Items and passes | Burn-on-purchase, soulbound toggle, feature gates, 25+ view functions | -| **[AppStakingVault.sol](src/apps/AppStakingVault.sol)** | Per-app staking | ERC20Votes stake-shares, non-transferable, snapshot-enabled for rewards | -| **[Tournament.sol](src/apps/Tournament.sol)** | Paid competitions | Entry fees, protocol fees, burn fees, Merkle claims | -| **[EpochRewards.sol](src/apps/EpochRewards.sol)** | Time-boxed rewards | Owner-funded, Merkle claims, for app token seasonal distributions | -| **[AppModuleFactory.sol](src/apps/AppModuleFactory.sol)** | Core module deployer | Deploys Access1155, StakingVault, EpochRewards in one call | -| **[TournamentFactory.sol](src/apps/TournamentFactory.sol)** | Tournament deployer | One-click tournament creation, registry, default fees | -| **[Interfaces.sol](src/apps/Interfaces.sol)** | Interface definitions | IAppToken, IOwnable | - -### Core Utility Features - -**AppToken** (Enhanced): -- ERC20 with Permit support for gasless approvals -- Optional max supply cap with enforcement -- Irreversible `finalizeMinting()` to lock supply permanently -- Burnable for deflationary mechanics -- `owner()` function for factory integration -- 🆕 **1% transfer fee** (default, governance-adjustable, capped at 2%) - - 70% to app stakers, 15% to veELTA, 15% to treasury - - Smart exemption system (bonding curve, vault, factory auto-exempt) - - View functions: `getTransferFeeInfo()`, `calculateTransferFee()` - -**AppAccess1155** (Items & Passes): -- ERC1155 multi-token standard for in-app items -- Configurable per item: price, soulbound toggle, time windows, supply caps -- 100% burn-on-purchase (deflationary by design) -- Soulbound (non-transferable) enforcement per item -- Feature gate registry for app-side access control -- Comprehensive view functions: `checkFeatureAccess()`, `checkPurchaseEligibility()`, `getPurchaseCost()`, `getRemainingSupply()` -- Batch getters for efficient UI loading - -**AppStakingVault** (Staking): -- Per-app isolated staking with ERC20Votes stake-shares -- Non-transferable shares (prevents stake trading) -- Snapshot-enabled for on-chain ELTA reward distribution -- Instant unstake (no lock periods) -- Auto-delegation for voting power -- Feature gating via `balanceOf()` checks -- Earns 70% of protocol revenues proportionally - -**Tournament** (Competitions): -- Entry fee collection in app tokens -- Protocol fee (default 2.5%) to treasury -- Burn fee (default 1%) for deflationary pressure -- Time-windowed entry periods -- Merkle proof claim distribution -- One-time finalization -- View functions: `getTournamentState()`, `checkEntryEligibility()`, `calculateFees()` - -**EpochRewards** (Distribution): -- Time-boxed reward periods (no continuous faucets) -- Owner-funded from rewards treasury -- Merkle proof claims for gas efficiency -- Per-epoch isolation and tracking -- Analytics views: `getEpochUtilization()`, `isEpochClaimable()` -- Batch operations for multiple epochs - -**AppModuleFactory** (Core Module Deployment): -- Deploys Access1155, StakingVault, and EpochRewards in one call -- **Used after AppFactory** - adds utility modules to your token -- Restricted: only AppToken owner can deploy -- Optional ELTA creation fee to treasury -- On-chain registry via `modulesByApp` mapping -- Ownership alignment (creator owns all modules) -- One-time deployment per app - -**TournamentFactory** (Tournament Deployment): -- Deploys new Tournament contract per event -- Tournaments are single-use (finalize once, claim once per user) -- Registry tracks all tournaments by app and creator -- Default fee templates (2.5% protocol, 1% burn) -- Custom fees supported for special events -- Enables weekly/monthly tournaments without manual deployment - -### Complete App Creator Journey - -``` -Step 1: Launch App (via AppFactory) -├─ Pay ELTA (110: 100 seed + 10 creation fee) -├─ AppToken deployed (1B supply) -├─ AppStakingVault deployed (for rewards) -├─ Bonding curve deployed (with 1% fee routing) -├─ Receive 50% auto-staked (500M tokens staked, earns ELTA rewards immediately) -├─ Receive admin control (DEFAULT_ADMIN_ROLE) -├─ Vault ownership transferred to creator -└─ 50% in bonding curve for public trading (500M tokens) - -Creator Benefits: -- Staked position earns 70% of all protocol revenues (proportional by stake) -- Cannot immediately dump (must unstake first, visible on-chain) -- Aligned with long-term app success -- No vesting period (immediate rewards eligibility) - -Step 2: Deploy Utility Modules (via AppModuleFactory) -├─ Pay optional ELTA creation fee -├─ Receive AppAccess1155 (items/passes) -├─ Receive AppStakingVault (staking) -├─ Receive EpochRewards (reward distribution) -└─ Creator owns all modules - -Step 3: Configure Economy -├─ Set items with prices, time windows, supply caps -├─ Configure feature gates (stake + item requirements) -└─ Ready for users - -Step 4: Deploy Tournaments (via TournamentFactory - per event) -├─ Create tournament with entry fee and time window -├─ Tournament uses default fees (2.5% protocol, 1% burn) -├─ One contract per event (tournaments are single-use) -└─ Registry tracks all tournaments - -Step 5: Run Reward Epochs (reusable) -├─ Start epoch with time window -├─ Fund from creator treasury (has 100M tokens!) -├─ Finalize with Merkle root after off-chain computation -└─ Users claim rewards with proofs -``` - -### Deflationary Economics - -**Burn Mechanisms:** -1. **Purchase Burns**: 100% of item/pass purchases burn app tokens -2. **Tournament Burns**: 1% of entry fee pool burned -3. **No New Minting**: After `finalizeMinting()`, supply can only decrease - -**Example Flow:** -``` -Initial Supply: 1,000,000,000 tokens -AppFactory mints at creation: -├─ 100,000,000 tokens (10%) → Creator treasury for rewards -└─ 900,000,000 tokens (90%) → Bonding curve for trading - -Creator can optionally call finalizeMinting() to lock supply - -Month 1 Activity: -├─ Users purchase items: 500,000 tokens burned -├─ Tournament burns: 50,000 tokens burned -└─ Epoch rewards distributed: 10,000,000 tokens (from creator treasury) - -Net Supply: 999,450,000 tokens (deflationary) -Creator Treasury Remaining: 90,000,000 tokens for future rewards -``` - -### Feature Gating System - -Apps can gate features using on-chain state: -**Stake-Only Gating:** -```solidity -access.setFeatureGate(featureId, FeatureGate({ - minStake: 1000 ether, // Require 1000 tokens staked - requiredItem: 0, // No item required - requireBoth: false, - active: true -})); - -// App checks access -bool hasAccess = access.checkFeatureAccess(user, featureId, userStake); -``` - -**Item-Only Gating:** -```solidity -access.setFeatureGate(featureId, FeatureGate({ - minStake: 0, - requiredItem: 5, // Require premium pass (ID 5) - requireBoth: false, - active: true -})); -``` - -**Combined Gating (Both Required):** -```solidity -access.setFeatureGate(featureId, FeatureGate({ - minStake: 5000 ether, // Require 5000 staked - requiredItem: 10, // AND legendary pass (ID 10) - requireBoth: true, // Both required - active: true -})); -``` +See [QUICKSTART.md](./QUICKSTART.md) for the complete setup guide. -### Tournament Economics +## Repository Structure ``` -Entry Fees Collected -├── Protocol Fee (2.5%) → Treasury (ELTA-aligned revenue) -├── Burn Fee (1.0%) → Removed from circulation -└── Net Pool (96.5%) → Distributed to winners via Merkle claims -``` - -**Why Merkle Claims:** -- Gas efficient for any number of winners -- Off-chain ranking/scoring flexibility -- On-chain verification and transparency -- No gas cost for non-winners - -### Epoch Rewards Model - -**Sustainable Distribution:** -- Owner creates time-boxed epochs (e.g., weekly, monthly) -- Owner funds from 10% creator treasury received at launch -- Off-chain: compute XP/rankings, generate Merkle tree -- Owner finalizes epoch with Merkle root -- Users claim rewards with proofs -- Single EpochRewards contract handles all seasons (reusable) - -**No Continuous Faucets:** -- Prevents inflation spirals -- Maintains token value -- Allows curated, merit-based distribution -- Owner controls emission schedule -- Finite supply from creator treasury (100M tokens) - -### Tournament Model - -**Per-Event Deployment:** -- TournamentFactory creates new Tournament for each event -- Tournaments are single-use (finalize once) -- Entry fees accumulate in prize pool -- Protocol fee (2.5%) and burn fee (1%) applied at finalization -- Winners claim via Merkle proofs -- Registry tracks all tournaments per app for discovery - -### View Functions for UI/UX - -All contracts include comprehensive view functions for frontends: - -**Eligibility Checking:** -- `checkFeatureAccess(user, featureId, stake)` - Can user access feature? -- `checkPurchaseEligibility(user, id, amount)` - Can user purchase item? -- `checkEntryEligibility(user)` - Can user enter tournament? - -**Cost Calculations:** -- `getPurchaseCost(id, amount)` - Calculate purchase cost -- `calculateFees()` - Preview tournament fee breakdown - -**State Queries:** -- `getRemainingSupply(id)` - Check item availability -- `getTournamentState()` - Complete tournament info -- `getEpochUtilization(id)` - Track claim rates - -**Batch Operations:** -- `getItems(ids[])` - Load multiple items efficiently -- `getFeatureGates(featureIds[])` - Load multiple gates -- `getEpochs(ids[])` - Load multiple epochs -- `checkClaimStatuses(id, users[])` - Check multiple users - -### Security & Design Principles - -**Non-Upgradeable:** -- All contracts immutable after deployment -- No proxy patterns or upgrade mechanisms -- Trust through code transparency - -**Owner-Controlled:** -- App creators configure their own modules -- No protocol-level governance of app parameters -- Creators can use Snapshot for community input - -**Burn-by-Default:** -- Purchases burn 100% of tokens (deflationary) -- Can add fee splits later if desired -- Supports token value directly - -**ELTA-Aligned:** -- Module creation fees paid in ELTA -- Tournament protocol fees to treasury -- Sustainable protocol revenue - -**Gating App-Side:** -- Smart contracts provide data via views -- Apps enforce access in their logic -- Flexible, gas-efficient, easy to update - ---- - -## veELTA Staking — Time-weighted governance - -### Voting Power Model - -veELTA is a **non-transferable ERC20Votes token** with duration-based boost. - -```mermaid -graph LR - subgraph "Voting Power Calculation" - INPUT[Locked ELTA Amount × Duration Boost] - BOOST[Linear: 1x at 7 days to 2x at 730 days] - OUTPUT[veELTA Balance = Voting Power] - end - - INPUT --> BOOST --> OUTPUT - - style INPUT fill:#e3f2fd - style BOOST fill:#fff3e0 - style OUTPUT fill:#e8f5e8 +src/ +├── token/ # ELTA governance token +├── staking/ # veELTA time-locked staking +├── experience/ # ElataXP reputation system +├── governance/ # Governor, Timelock, LotPool funding +├── rewards/ # Fee distribution contracts +├── fees/ # Fee routing infrastructure +├── apps/ # App token launch framework +└── utils/ # Shared utilities ``` -### Mathematical Formula +## Core Contracts -```solidity -// From VeELTA.sol - Duration boost (linear interpolation) -boost = 1e18 + ((1e18 * duration) / MAX_LOCK) // 1x to 2x -veELTA_minted = (eltaAmount * boost) / 1e18 - -// Constants -MIN_LOCK = 7 days // Minimum lock period -MAX_LOCK = 730 days // Maximum lock period (2 years) -``` +| Contract | Purpose | Source | +|----------|---------|--------| +| ELTA | ERC20 governance token with 77M supply cap | [src/token/ELTA.sol](src/token/ELTA.sol) | +| VeELTA | Vote-escrowed staking (7 days to 2 years) | [src/staking/VeELTA.sol](src/staking/VeELTA.sol) | +| ElataXP | Non-transferable reputation points | [src/experience/ElataXP.sol](src/experience/ElataXP.sol) | +| LotPool | XP-weighted funding rounds | [src/governance/LotPool.sol](src/governance/LotPool.sol) | +| RewardsDistributor | Protocol fee distribution (70/15/15 split) | [src/rewards/RewardsDistributor.sol](src/rewards/RewardsDistributor.sol) | +| ElataGovernor | On-chain governance with 4% quorum | [src/governance/ElataGovernor.sol](src/governance/ElataGovernor.sol) | +| AppFactory | Permissionless app token launches | [src/apps/AppFactory.sol](src/apps/AppFactory.sol) | -### Examples +## How It Works -| Lock Amount | Lock Duration | Boost | veELTA Received | Unlock After | -|-------------|---------------|-------|-----------------|--------------| -| 1,000 ELTA | 730 days (max) | 2.0x | 2,000 veELTA | 730 days | -| 1,000 ELTA | 365 days | 1.5x | 1,500 veELTA | 365 days | -| 1,000 ELTA | 7 days (min) | 1.0x | 1,000 veELTA | 7 days | +The protocol coordinates three activities: -**Key Features**: -- **Single lock per user** (simplifies state, reduces gas) -- **Can increase amount** or **extend duration** anytime -- **No continuous decay** (voting power updates only on actions) -- **Principal returned 1:1** on unlock (veELTA burned, ELTA returned) -- **Non-transferable** (prevents vote-buying, ensures genuine commitment) -- **Snapshot-enabled** (ERC20Votes) for on-chain governance and reward claims +**Staking**: Users lock ELTA tokens to receive veELTA, which grants voting power and a share of protocol revenue. Longer locks (up to 2 years) earn up to 2x boost on voting power. +**Reputation**: Users earn XP through protocol participation—playing apps, submitting data, engaging in governance. XP is non-transferable and determines voting weight in funding decisions. -## ElataXP — Participation without speculation +**Funding**: Each week, the community votes (weighted by XP) to allocate protocol funds to research proposals and development grants. Winners receive ELTA from the treasury. -### Basic XP System +Protocol revenue flows from app store fees, trading fees, and tournament rake. The RewardsDistributor splits incoming fees: 70% to app token stakers, 15% to veELTA holders, 15% to treasury. -**What it is**: Non-transferable ERC20-style points token (soulbound) - -**How it's earned** (policy examples): -- **EEG data submission**: 10-100 XP per valid session -- **App engagement**: 1-10 XP per activity/achievement -- **Tournament participation**: Bonus XP for performance -- **Community governance**: XP for proposal creation/voting - -**How it's used**: -- **🆕 Early Access** (first 6 hours of app launches require ≥100 XP) -- **LotPool voting** (funding experiments) via block-based snapshots -- **App store boosts** (minimum XP for premium features) -- **Reputation system** (proof of sustained contribution) -- **Access control** (XP-gated tournaments, exclusive content) - -### XP Management - -```solidity -// From ElataXP.sol -XP_OPERATOR_ROLE // Required to award/revoke XP -``` - -**Features**: -1. **Permanent XP**: Once earned, XP remains until explicitly revoked -2. **Signature-based awards**: Off-chain operators can sign XP grants (EIP-712) -3. **Soulbound**: Non-transferable, preventing reputation trading -4. **Snapshot voting**: Built-in checkpoint system for governance - -**Why permanent?** Simpler implementation, clear accounting, and reliable reputation without complex decay mechanics. - -For operator and distribution runbooks, see: -- docs/xp-system.md (XP architecture and Merkle claims) -- docs/xp-ops.md (Operator roles, rotation, publishing distributions) - -### XP Lifecycle - -```mermaid -graph LR - subgraph "XP Flow" - AWARD[XP Awarded
Operator/Signature] - HOLD[XP Balance
Permanent Reputation] - VOTE[Voting Power
Snapshot-based] - REVOKE[XP Revoked
Admin Only] - end - - AWARD --> HOLD - HOLD --> VOTE - HOLD -.optional.-> REVOKE - - style AWARD fill:#4caf50 - style HOLD fill:#2196f3 - style VOTE fill:#9c27b0 - style REVOKE fill:#ff9800 -``` - ---- - -## LotPool — XP-weighted funding rounds - -### Mechanism - -```solidity -// From LotPool.sol - Weekly funding cycles -function startRound( - bytes32[] calldata options, // e.g., ["EXP-123", "APP-456"] - address[] calldata recipients, // Payout addresses - uint64 durationSecs // Typically 7 days -) external returns (uint256 roundId, uint256 snapshotBlock) -``` - -**Round Lifecycle**: -1. **Start**: Admin creates round with proposals and recipients -2. **Snapshot**: Contract captures XP balances at specific block -3. **Voting**: Users allocate their snapshot XP across options -4. **Finalization**: Admin distributes ELTA to winning proposal - -### Voting Formula - -```solidity -// Users can allocate up to their XP balance across options -voterXP = XP.getPastXP(msg.sender, snapshotBlock); -totalAllocated = sum(voteWeights); // Must not exceed voterXP - -// Winner determination -winner = option with max(totalVotes) -``` - -**Example Round**: -``` -Round 1: "PTSD Research" vs "Depression Study" -- Alice (2000 XP): votes 1500 for PTSD, 500 for Depression -- Bob (1000 XP): votes 800 for Depression -- Charlie (500 XP): votes 500 for PTSD - -Results: -- PTSD Research: 2000 votes (1500 + 500) -- Depression Study: 1300 votes (500 + 800) -- Winner: PTSD Research → receives funding -``` - -**Properties**: -- **Sybil-resistant** via XP (must be earned on-chain) -- **Transparent** (all votes and payouts on-chain) -- **Modular** (recipients can be PIs, escrow contracts, dev grants) -- **Snapshot-based** (prevents double-voting or manipulation) - -### Funding Round Flow - -```mermaid -sequenceDiagram - participant Admin - participant LotPool - participant Users - participant Winners - - Note over Admin, Winners: Round Setup - Admin->>LotPool: startRound(options, recipients, duration) - LotPool->>LotPool: Take XP snapshot at block N-1 - LotPool->>Users: Announce new round - - Note over Admin, Winners: Voting Period - Users->>LotPool: vote(roundId, option, xpAmount) - LotPool->>LotPool: Validate XP at snapshot - LotPool->>LotPool: Record votes - - Note over Admin, Winners: Finalization - Admin->>LotPool: finalize(roundId, winner, amount) - LotPool->>Winners: Transfer ELTA funding - LotPool->>Users: Announce results -``` - - -## Technical specifications - -### Contract Constants - -```solidity -// Token Economics -ELTA.MAX_SUPPLY = 77,000,000 * 1e18 // Hard cap -ELTA.decimals = 18 // Standard precision - -// Staking Parameters -VeELTA.MIN_LOCK = 7 days // Minimum lock duration -VeELTA.MAX_LOCK = 730 days // 2 years maximum -VeELTA.BOOST_MIN = 1e18 // 1x boost at min duration -VeELTA.BOOST_MAX = 2e18 // 2x boost at max duration - -// XP System -ElataXP.XP_OPERATOR_ROLE // Required role for award/revoke -ElataXP (permanent, no decay) // Simple reputation system - -// Governance -Governor.votingDelay = 1 days // Proposal delay -Governor.votingPeriod = 7 days // Voting duration -Governor.proposalThreshold = 0.1% // 77K ELTA minimum -Governor.quorum = 4% // 3.08M ELTA required - -// Rewards & Fees -RewardsDistributor.BIPS_APP = 7000 // 70% to app stakers -RewardsDistributor.BIPS_VEELTA = 1500 // 15% to veELTA stakers -RewardsDistributor.BIPS_TREASURY = 1500 // 15% to treasury -AppFeeRouter.feeBps = 100 // 1% trading fee (max 5%) -``` - -### Gas Costs (Optimized for Mainnet) - -```mermaid -graph TD - subgraph "Low Cost Operations (<100K gas)" - LC1[ELTA Transfer: 56K
Standard token transfer] - LC2[ELTA Mint: 67K
With supply cap check] - LC3[VeELTA Lock: 88K
Position creation] - LC5[LotPool Vote: 86K
XP allocation] - LC6[Reward Claim: 80K
Merkle verification] - end - - subgraph "Medium Cost Operations (100K-300K gas)" - MC1[XP Award: 189K
With auto-delegation] - MC2[Multi-lock Create: 256K
NFT + delegation] - end - - style LC1 fill:#c8e6c9 - style LC2 fill:#c8e6c9 - style LC3 fill:#c8e6c9 - style LC4 fill:#c8e6c9 - style LC5 fill:#c8e6c9 - style LC6 fill:#c8e6c9 - style MC1 fill:#fff3e0 - style MC2 fill:#fff3e0 -``` - -| Operation | Gas Cost | Notes | -|-----------|----------|-------| -| **ELTA transfer** | ~56K | Standard ERC20 | -| **ELTA mint** | ~67K | With supply cap check | -| **VeELTA lock** | ~88K | Single position creation | -| **Multi-lock create** | ~256K | NFT + delegation setup | -| **XP award** | ~189K | With auto-delegation | -| **XP revoke** | ~82K | Burn XP from user | -| **LotPool vote** | ~86K | XP allocation | -| **Governance vote** | ~90K | Standard governor | -| **Reward claim** | ~80K | Merkle proof verification | - -### Deployment Costs - -| Contract | Size | Deploy Cost | Category | Status | -|----------|------|-------------|----------|--------| -| **Core Tokenomics** |||| -| ELTA | 13.3KB | 2.3M gas | Token | Optimal | -| VeELTA | 13.8KB | 3.0M gas | Staking | Optimal | -| ElataXP | 8.2KB | 1.8M gas | Reputation | Optimal | -| LotPool | 5.5KB | 1.1M gas | Funding | Optimal | -| RewardsDistributor | 7.4KB | 1.1M gas | Rewards | Optimal | -| ElataGovernor | 16.6KB | 3.2M gas | Governance | Acceptable | -| **App Ecosystem** |||| -| AppFactory | 14.2KB | 2.9M gas | Factory | Optimal | -| AppModuleFactory | 6.8KB | 1.4M gas | Factory | Optimal | -| TournamentFactory | 5.2KB | 1.0M gas | Factory | Optimal | - ---- - -## Developer integration - -### Launching a Complete App - -```solidity -// Step 1: Create app token with bonding curve (via AppFactory) -ELTA.approve(address(appFactory), 110 ether); -uint256 appId = appFactory.createApp( - "NeuroPong Token", // name - "NPONG", // symbol - 0, // supply (0 = use default 1B) - "Description", // description - "ipfs://...", // imageURI - "https://..." // website -); - -// Get your token address -address myToken = appFactory.apps(appId).token; - -// Step 2: Deploy utility modules (via AppModuleFactory) -(address access1155, address staking, address rewards) = - appModuleFactory.deployModules( - myToken, - "https://metadata.myapp.com/" - ); - -// Step 3: Configure your economy -AppAccess1155(access1155).setItem( - 1, // itemId - 50 ether, // price in app tokens - true, // soulbound - true, // active - 0, 0, // no time restrictions - 10000, // max supply - "ipfs://..." // metadata URI -); - -// Now users can: -// - Buy your token on the bonding curve -// - Purchase NFT items (burns tokens) -// - Stake tokens for benefits -// - Enter tournaments -``` - -### Awarding XP Automatically - -```solidity -// Grant XP_OPERATOR_ROLE to your app contract -xp.grantRole(XP_OPERATOR_ROLE, address(myAppContract)); - -// In your app logic -function completeSession(address user, uint256 sessionQuality) external { - uint256 xpAmount = calculateXP(sessionQuality); // Your logic - xp.award(user, xpAmount); -} -``` - -### Creating Staking Positions - -```solidity -// VeELTA V2: Single lock per user with ERC20Votes -veELTA.lock(1000e18, uint64(block.timestamp + 365 days)); // Lock for 1 year - -// Manage your lock -veELTA.increaseAmount(500e18); // Add more ELTA to existing lock -veELTA.extendLock(uint64(block.timestamp + 730 days)); // Extend to 2 years - -// Check your voting power -uint256 votingPower = veELTA.balanceOf(msg.sender); // Current veELTA balance -uint256 pastPower = veELTA.getPastVotes(msg.sender, blockNumber); // Historical snapshot - -// Unlock after expiry -veELTA.unlock(); // Burns veELTA, returns 1:1 ELTA principal - -// Delegation is automatic (self-delegated for voting power) -``` - -### Running Funding Rounds - -```solidity -// Start weekly funding round -bytes32[] memory options = [keccak256("EXP-123"), keccak256("APP-456")]; -address[] memory recipients = [researcher1, developer1]; -uint256 roundId = lotPool.startRound(options, recipients, 7 days); - -// Users vote with their XP -lotPool.vote(roundId, keccak256("EXP-123"), 500e18); - -// Finalize and distribute -lotPool.finalize(roundId, keccak256("EXP-123"), 10000e18); -``` - - -## Security & design principles - -### Core Security Features - -- **Non-upgradeable contracts** → Immutable logic, no proxy risks -- **Role-based access control** → Multisig-gated admin functions -- **Reentrancy protection** → All state-changing functions protected -- **Supply cap enforcement** → Hard limit prevents inflation attacks -- **Time-locked governance** → Delays prevent immediate execution -- **Merkle proof verification** → Prevents reward manipulation - -### Economic Security - -- **Linear decay prevents gaming** → No cliff-based manipulation -- **XP non-transferability** → Prevents reputation markets -- **Emergency unlock penalties** → 50% penalty discourages abuse -- **Snapshot-based voting** → Prevents double-voting attacks -- **Minimum lock periods** → Prevents flash-loan governance - ---- - -## Build, test, deploy +## Development ### Prerequisites -- [Foundry](https://book.getfoundry.sh/) - Ethereum development toolkit -- [Node.js](https://nodejs.org/) v18+ - For frontend and scripts -- [Git](https://git-scm.com/) - Version control - -### Local Development (Recommended for testing) +- [Foundry](https://book.getfoundry.sh/) (forge, anvil, cast) +- Node.js v18+ +- Docker Desktop (for the App Store's Postgres database) -**Get started in 60 seconds!** +### Commands ```bash -# Clone and setup -git clone https://github.com/Elata-Biosciences/elata-protocol -cd elata-protocol - -# Install dependencies and setup Git hooks +# Install dependencies and set up git hooks make install -# Or manually: -forge install -npm install -bash scripts/setup-hooks.sh - -# Start local blockchain with all contracts + test data (protocol only) -npm run dev - -# In another terminal, run the App Store frontend (separate repo) -cd ../elata-appstore -npm run local:full -``` - -Prerequisites: - -- Foundry (forge, anvil, cast) -- Node.js v18+ -- Git -- Docker Desktop (required if you will run the App Store locally; it starts Postgres via docker compose) - - Verify: `docker --version` and `docker compose version` - - Make sure Docker Desktop is running before `npm run local:full` in `elata-appstore` - -This automatically: -- Starts Anvil (local blockchain) -- Deploys ALL protocol contracts -- Seeds test data (apps, XP, staking, funding rounds) -- Generates frontend configuration -- Funds test accounts with ELTA -- Sets up pre-commit hooks for code quality +# Build contracts +make build -**See [QUICKSTART.md](QUICKSTART.md) for details** or the [full local development guide](docs/LOCAL_DEVELOPMENT.md). +# Run tests +make test -### Development Tools +# Run tests with gas report +make gas-report -We provide a comprehensive Makefile for common development tasks: +# Format code +make fmt -```bash -make help # Show all available commands -make build # Build contracts -make test # Run tests -make test-v # Run tests with verbose output -make fmt # Format code with forge fmt -make fmt-check # Check code formatting -make coverage # Generate test coverage report -make gas-report # Generate gas usage report -make ci # Run all CI checks locally (before pushing) +# Run all CI checks before pushing +make ci ``` -**Pre-commit Hooks**: Automatically format code, build, and run tests before each commit. -**Pre-push Hooks**: Run comprehensive checks including gas reports before pushing. - -**Tip**: Run `make ci` before pushing to catch issues locally. - ### Testing -```bash -# Run comprehensive test suite (454 tests, 97.6% pass rate) -npm test -# or -make test - -# With verbose output -make test-v +The test suite includes unit tests, integration tests, and fuzz tests: -# With gas report -make gas-report +```bash +# Run all tests +forge test -# Run specific test -forge test --match-test testStakingLock +# Run specific contract tests +forge test --match-contract ELTATest -# Run all CI checks locally -make ci +# Run with verbose output +forge test -vvv ``` ### Deploying to Testnet ```bash -# Setup environment +# Set environment variables export ADMIN_MSIG=0xYourGnosisSafe export INITIAL_TREASURY=0xYourTreasury export SEPOLIA_RPC_URL=https://eth-sepolia.g.alchemy.com/v2/YOUR_KEY -export ETHERSCAN_API_KEY=YOUR_API_KEY +export ETHERSCAN_API_KEY=YOUR_KEY # Deploy to Sepolia npm run deploy:sepolia ``` -### Contributing +See [SEPOLIA_DEPLOYMENT_GUIDE.md](./SEPOLIA_DEPLOYMENT_GUIDE.md) for detailed deployment instructions. -We welcome contributions! Please see our [Contributing Guide](docs/CONTRIBUTING_DEV.md) for: -- Development workflow -- Code style guidelines -- Testing best practices -- Git commit conventions -- Pull request process +## Documentation -**Quick Start for Contributors:** -```bash -# Fork and clone the repo -git clone https://github.com/YOUR_USERNAME/elata-protocol -cd elata-protocol +| Document | Description | +|----------|-------------| +| [QUICKSTART.md](./QUICKSTART.md) | Local development setup | +| [docs/ARCHITECTURE.md](./docs/ARCHITECTURE.md) | System design and contract relationships | +| [docs/TOKENOMICS.md](./docs/TOKENOMICS.md) | ELTA token mechanics and economics | +| [docs/APP_LAUNCH_GUIDE.md](./docs/APP_LAUNCH_GUIDE.md) | Building apps on the protocol | +| [docs/LOCAL_DEVELOPMENT.md](./docs/LOCAL_DEVELOPMENT.md) | Detailed local dev environment | +| [docs/DEPLOYMENT.md](./docs/DEPLOYMENT.md) | Production deployment procedures | +| [docs/xp-system.md](./docs/xp-system.md) | XP distribution architecture | +| [docs/xp-ops.md](./docs/xp-ops.md) | XP operator runbook | +| [CONTRIBUTING.md](./CONTRIBUTING.md) | Contribution guidelines | -# Setup development environment -make install - -# Make your changes and run checks -make ci +## Key Parameters -# Push and create a pull request ``` - -### Test Coverage - -**454 comprehensive tests** with 97.6% pass rate: - -```mermaid -pie title Test Coverage by Contract - "Core Tokens (ELTA, XP)" : 39 - "VeELTA V2 (13 tests)" : 13 - "Rewards V2 (31 tests)" : 31 - "App Launch (150+ tests)" : 150 - "Utilities (80+ tests)" : 80 - "Integration (11 tests)" : 11 - "Security (130+ tests)" : 130 -``` - -- **Unit tests**: Individual contract functionality (100% coverage on new contracts) -- **Integration tests**: Cross-contract workflows including full revenue flow -- **Fuzz tests**: Property-based testing with random inputs -- **Security tests**: Critical protection verification -- **Gas optimization**: Benchmarked for mainnet efficiency - -**Economic Upgrade V2 Tests**: 56/56 passing (100%) - -```bash -# Test specific contracts -forge test --match-contract ELTATest -forge test --match-contract VeELTATest -forge test --match-contract LotPoolTest - -# Test with detailed output -forge test -vvv +ELTA Supply Cap: 77,000,000 tokens +Staking Lock Range: 7 days to 730 days (2 years) +Staking Boost: 1x (min lock) to 2x (max lock) +Governance Quorum: 4% of total supply +Proposal Threshold: 0.1% of total supply (~77,000 ELTA) +Voting Delay: 1 day +Voting Period: 7 days (3 days for emergency proposals) +Trading Fee: 1% (routed to RewardsDistributor) +Revenue Split: 70% app stakers / 15% veELTA / 15% treasury ``` ---- - -## FAQ (for tokenomics-minded readers) +## Security -**Q: Why no "reward token" or emissions?** -A: Emissions tokens tend to inflate and collapse without strong sinks. Elata routes **real protocol fees** to veELTA stakers and uses **buyback & burn**—value tracks actual usage. +The contracts are designed with these principles: -**Q: Why separate XP from ELTA?** -A: XP is for *voice & access*; ELTA is for *ownership & yield*. Non-transferable XP prevents buying reputation and incentivizes ongoing contribution over capital. +- **Non-upgradeable**: All contracts are immutable after deployment +- **Role-based access**: Admin functions require multisig approval +- **Supply cap enforcement**: ELTA cannot exceed 77M tokens +- **Time-locked governance**: 48-hour delay on governance execution +- **No transfer fees on ELTA**: Compatible with standard DeFi infrastructure -**Q: Can ELTA be minted after deployment?** -A: Only up to the hard cap (77M) and only by addresses with `MINTER_ROLE`. The DAO can retire the minter role for a fixed supply, or reserve it for future programs. +Security audit status: Pending external audit before mainnet deployment. -**Q: What prevents governance attacks?** -A: **Time-locked staking** (can't flash-loan veELTA), **XP requirements** (can't buy reputation), **quorum thresholds** (4% minimum), and **time delays** (48h for execution). +## Contributing -**Q: Why is XP permanent (no decay)?** -A: Simplicity and reliability. Permanent XP provides clear accounting and predictable reputation. Operators can revoke XP if needed, but users don't need to worry about losing earned reputation over time. - ---- +See [CONTRIBUTING.md](./CONTRIBUTING.md) for development workflow, code style, and PR guidelines. -## Production readiness - -### **Ready for Mainnet** - -- **All core contracts** compile and pass 112 comprehensive tests -- **Gas costs optimized** for Ethereum mainnet usage -- **Security hardened** with OpenZeppelin v5 and best practices -- **Non-upgradeable** design for trustlessness and immutability -- **Professional documentation** and deployment infrastructure - -### **Next Steps** - -1. **External security audit** of all contracts -2. **Testnet deployment** with community testing -3. **Parameter finalization** based on testnet feedback -4. **Mainnet deployment** with ceremony and verification -5. **Ecosystem activation** with initial funding rounds - ---- - -## License - -MIT License - see [LICENSE](LICENSE) file for details. - ---- +```bash +# Quick start for contributors +git clone https://github.com/YOUR_USERNAME/elata-protocol +cd elata-protocol +make install +make ci # Run all checks before pushing +``` -## One-liner summary +## License -> **Elata Protocol makes neurotech economical**: earn XP by contributing, steer funding with XP, capture real protocol yield by locking ELTA, and build the Internet of Brains together. +MIT License. See [LICENSE](./LICENSE). --- -**Ready to revolutionize precision psychiatry through decentralized coordination.** - -*For technical architecture details, see [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md)* -*For deployment instructions, see [docs/DEPLOYMENT.md](docs/DEPLOYMENT.md)* -*For contributing guidelines, see [CONTRIBUTING.md](CONTRIBUTING.md)* - +For questions, open a GitHub issue or join the community Discord. diff --git a/SEPOLIA_DEPLOYMENT_GUIDE.md b/SEPOLIA_DEPLOYMENT_GUIDE.md index eb046b7..82b8178 100644 --- a/SEPOLIA_DEPLOYMENT_GUIDE.md +++ b/SEPOLIA_DEPLOYMENT_GUIDE.md @@ -1,168 +1,155 @@ # Base Sepolia Deployment Guide +This guide covers deploying to Base Sepolia testnet specifically. For general deployment information, see [docs/DEPLOYMENT.md](./docs/DEPLOYMENT.md). + ## Deployment Methods -We support two deployment methods: +Two options: -1. **Ledger (Recommended)** - Most secure, uses hardware wallet -2. **Private Key** - For CI/automated deployments +1. **Ledger (recommended)** — Hardware wallet for production-grade security +2. **Private Key** — For CI/automated deployments -## Quick Start (Ledger - Recommended) +## Ledger Deployment -### 1. Prepare Ledger Device +### 1. Prepare Device -- Connect your Ledger device -- Open the Ethereum app -- Go to Settings → Enable "Blind signing" -- Keep device connected and unlocked +- Connect Ledger and open the Ethereum app +- Enable "Blind signing" in Settings +- Keep device connected and unlocked throughout deployment -### 2. Get Base Sepolia ETH +### 2. Get Test ETH -Fund your Ledger address: https://www.coinbase.com/faucets/base-ethereum-sepolia-faucet +Fund your Ledger address from the Base faucet: +https://www.coinbase.com/faucets/base-ethereum-sepolia-faucet -### 3. Create `.env.sepolia` file +Budget 0.05 ETH for deployment costs. -```bash -# Base Sepolia Deployment Configuration +### 3. Create Environment File -# Network Configuration +Create `.env.sepolia` in the repository root: + +```bash +# Network BASE_SEPOLIA_RPC_URL=https://sepolia.base.org -BASESCAN_API_KEY=your_basescan_api_key_here +BASESCAN_API_KEY=your_basescan_api_key -# Governance & Treasury -ADMIN_MSIG=0xC50e39B8e22710790939f02Ad77CEb99c1cC7DF4 -INITIAL_TREASURY=0xC50e39B8e22710790939f02Ad77CEb99c1cC7DF4 +# Protocol Configuration +ADMIN_MSIG=0xYourGnosisSafeAddress +INITIAL_TREASURY=0xYourTreasuryAddress -# DEX Router (leave empty to deploy mock router - recommended) +# Leave empty to deploy mock router (recommended for testing) UNISWAP_V2_ROUTER= - -# Optional: XP Operators -# XP_OPERATOR_1=0x... ``` -**Note**: No private key needed for Ledger deployment! +No private key needed for Ledger deployment. -### 4. Deploy with Ledger +### 4. Deploy ```bash bash scripts/deploy-sepolia.sh --ledger -# Or with specific Ledger address: -bash scripts/deploy-sepolia.sh --ledger --ledger-address 0xYourLedgerAddress +# Or with specific address: +bash scripts/deploy-sepolia.sh --ledger --ledger-address 0xYourAddress ``` -The script will: -- Prompt you to confirm Ledger prerequisites -- Ask for your Ledger address (if not provided) -- Show deployment configuration -- Ask for final confirmation -- Deploy contracts (approve each tx on Ledger device) +Approve each transaction on the Ledger device. -### 5. Verify Deployment +### 5. Verify ```bash bash scripts/verify-sepolia.sh ``` -## Alternative: Private Key Deployment +## Private Key Deployment -For automated deployments or if you don't have a Ledger: +For automated deployments without hardware wallet: -### 1. Create `.env.sepolia` with Private Key +### 1. Add Key to Environment ```bash # Add to .env.sepolia DEPLOYER_PRIVATE_KEY=your_private_key_here ``` -### 2. Deploy with Private Key +### 2. Deploy ```bash bash scripts/deploy-sepolia.sh --private-key ``` -**⚠️ Security Warning**: Remove `DEPLOYER_PRIVATE_KEY` from `.env.sepolia` after deployment! +**Security**: Remove `DEPLOYER_PRIVATE_KEY` from the file after deployment. + +## Base Sepolia Configuration -## Configuration Details +### Mock Router -### Admin Multisig -- **Address**: `0xC50e39B8e22710790939f02Ad77CEb99c1cC7DF4` -- **Purpose**: Admin control over all protocol contracts -- **Receives**: 10,000,000 ELTA initial mint +We deploy a mock Uniswap V2-compatible router for testing. This provides: +- Full control over bonding curve testing +- No external dependencies +- Consistent behavior with local development -### Mock Router Strategy -We deploy our own mock Uniswap V2-compatible router on Base Sepolia for: -- **Full control** over bonding curve testing -- **No external dependencies** on third-party DEXs -- **Consistent behavior** with local development -- **Security** - known codebase +### Contract Size Limit -The mock router is identical to what we use for local Anvil development. +AppModuleFactory exceeds the 24KB limit and is skipped on Base Sepolia. Core functionality still works: +- App launches work +- Bonding curves work +- Staking and rewards work +- Module deployment (AppAccess1155, etc.) unavailable on testnet -### AppModuleFactory Note -**AppModuleFactory is skipped on Base Sepolia** due to the 24KB contract size limit (it's 29.8KB). This is expected and doesn't affect core functionality: -- ✅ App launches work -- ✅ Bonding curves work -- ✅ Staking and rewards work -- ❌ Module deployment (AppAccess1155, etc.) won't be available on testnet +This resolves automatically on Base Mainnet, which doesn't enforce the limit. -This will be resolved when we deploy to Base Mainnet or can be deployed separately if needed for testing. +### Estimated Costs -### Gas Costs -Estimated deployment gas: -- Total contracts: ~15-20M gas +- Total deployment: ~15-20M gas - At 1 gwei: ~0.015-0.02 ETH -- Budget: 0.05 ETH for safety +- Recommended budget: 0.05 ETH + +## Post-Deployment -### Deployment Artifacts +### Artifacts -After deployment, you'll find: -- `deployments/base-sepolia-deployment.json` - Contract addresses -- `broadcast/Deploy.sol/84532/` - Foundry broadcast logs +After deployment: +- `deployments/base-sepolia-deployment.json` — Contract addresses +- `broadcast/Deploy.sol/84532/` — Foundry broadcast logs -## Post-Deployment Checklist +### Checklist - [ ] All contracts deployed successfully - [ ] All contracts verified on BaseScan -- [ ] 10M ELTA in multisig treasury +- [ ] Initial ELTA minted to multisig - [ ] Multisig has admin roles -- [ ] No ELTA in deployer wallet - [ ] Verification script passes -- [ ] Addresses documented -- [ ] **Configure Timelock permissions via multisig** (see below) -- [ ] Vercel env vars updated -- [ ] Local .env.sepolia cleaned (private key removed) +- [ ] Timelock permissions configured (see below) +- [ ] Vercel environment variables updated +- [ ] Private key removed from `.env.sepolia` -## Manual Multisig Configuration Required +### Configure Timelock Permissions -After deployment, the multisig must grant Governor permissions on the Timelock: +The multisig must grant Governor permissions on the Timelock: ```bash -# Via Gnosis Safe UI or cast: -# 1. Grant PROPOSER_ROLE to Governor -cast send \ +# Grant PROPOSER_ROLE to Governor +cast send $TIMELOCK_ADDRESS \ "grantRole(bytes32,address)" \ 0xb09aa5aeb3702cfd50b6b62bc4532604938f21248a27a1d5ca736082b6819cc1 \ - \ + $GOVERNOR_ADDRESS \ --rpc-url $BASE_SEPOLIA_RPC_URL -# 2. Grant EXECUTOR_ROLE to Governor -cast send \ +# Grant EXECUTOR_ROLE to Governor +cast send $TIMELOCK_ADDRESS \ "grantRole(bytes32,address)" \ 0xfd643c72710c63c0180259aba6b2d05451e3591a24e58b62239378085726f783 \ - \ + $GOVERNOR_ADDRESS \ --rpc-url $BASE_SEPOLIA_RPC_URL ``` -Or use Gnosis Safe Transaction Builder with the Timelock contract. +Or use Gnosis Safe Transaction Builder. -## Updating Vercel Environment Variables +### Vercel Environment Variables -After deployment, add these to Vercel (elata-appstore project → Settings → Environment Variables): +Add these to the elata-appstore project in Vercel (Settings → Environment Variables): -**Scope**: Preview, Development - -```bash +``` NEXT_PUBLIC_ELTA_ADDRESS_BASE_SEPOLIA= NEXT_PUBLIC_APP_FACTORY_ADDRESS_BASE_SEPOLIA= NEXT_PUBLIC_APP_MODULE_FACTORY_ADDRESS_BASE_SEPOLIA= @@ -172,37 +159,28 @@ NEXT_PUBLIC_VE_ELTA_ADDRESS_BASE_SEPOLIA= NEXT_PUBLIC_ELATA_XP_ADDRESS_BASE_SEPOLIA= ``` +Set scope to Preview and Development. + ## Troubleshooting -### Deployment Fails -- Check RPC URL is accessible -- Verify private key has Base Sepolia ETH -- Confirm environment variables are set +### Deployment fails +- Verify RPC URL is accessible +- Check deployer has sufficient ETH +- Confirm all environment variables are set -### Verification Fails -- Get BaseScan API key -- Wait 30 seconds after deployment +### Verification fails +- Ensure BaseScan API key is valid +- Wait 30 seconds after deployment before verifying - Try manual verification on BaseScan -### Contract Too Large -- This is expected for some contracts -- They work on Base (no 24KB limit) -- Local deployment uses lower optimization runs +### Contract too large error +Expected for AppModuleFactory. It deploys successfully on L2s without the 24KB limit. -## Security Notes +## Testing After Deployment -1. **Never commit `.env.sepolia`** - it's git-ignored -2. **Deployer key** should be a dedicated testnet-only wallet -3. **After deployment**, remove private key from .env.sepolia -4. **Multisig** should be the only admin with long-term control -5. **Testnet tokens** have no value, but practice good security - -## Next Steps - -1. Run end-to-end tests on testnet +1. Run end-to-end tests against testnet 2. Send test ELTA from multisig to test wallets -3. Launch test apps -4. Verify bonding curve functionality -5. Test staking and rewards -6. Document any issues or learnings - +3. Launch a test app +4. Verify bonding curve buys and sells work +5. Test staking and reward claims +6. Document any issues diff --git a/docs/APP_LAUNCH_GUIDE.md b/docs/APP_LAUNCH_GUIDE.md new file mode 100644 index 0000000..61f111a --- /dev/null +++ b/docs/APP_LAUNCH_GUIDE.md @@ -0,0 +1,460 @@ +# App Launch Guide + +This guide walks through creating an app on the Elata Protocol, from initial token launch to deploying utility modules. + +## Overview + +Launching an app involves: + +1. Creating an app token via AppFactory +2. Deploying utility modules (staking, items, rewards) +3. Configuring your app's economy +4. Building your frontend to interact with the contracts + +By the end, you'll have a fully functional token economy for your neurotech application. + +## Prerequisites + +Before starting: + +- Local environment running (`npm run local:up` in elata-protocol) +- ELTA tokens for the launch fee (110 ELTA minimum) +- Basic Solidity knowledge for understanding contract interactions + +## Step 1: Create Your App Token + +### Using the Factory + +The AppFactory creates your token and bonding curve in a single transaction. You'll need 110 ELTA: 100 for seed liquidity and 10 as a creation fee. + +```solidity +// First, approve ELTA spending +ELTA.approve(address(appFactory), 110 ether); + +// Create the app +uint256 appId = appFactory.createApp( + "NeuroPong Token", // Token name + "NPONG", // Token symbol + 0, // Supply (0 = default 1 billion) + "EEG-controlled pong game", // Description + "ipfs://Qm...", // Image URI + "https://neuropong.app" // Website +); +``` + +### What Gets Deployed + +The factory deploys three contracts: + +1. **AppToken** — Your ERC20 token with 1 billion supply +2. **AppBondingCurve** — Handles trading before graduation +3. **AppStakingVault** — For staking your token + +### Token Distribution + +After creation: + +- 50% (500M tokens) go to you, auto-staked in the vault +- 50% (500M tokens) go to the bonding curve for public trading + +Your tokens are staked automatically, so you start earning rewards immediately. To access them, you'll need to unstake first. + +### Retrieve Your Addresses + +```solidity +// Get your app's data +AppFactory.App memory app = appFactory.apps(appId); + +address token = app.token; +address bondingCurve = app.bondingCurve; +address stakingVault = app.vault; +``` + +## Step 2: Deploy Utility Modules + +The AppModuleFactory adds utility modules to your app. This deploys additional contracts you'll use for items, rewards, and more. + +```solidity +// Deploy modules +(address access1155, address staking, address rewards) = + appModuleFactory.deployModules( + token, // Your app token address + "https://api.myapp.com/metadata/" // Base URI for NFT metadata + ); +``` + +### Modules Deployed + +| Contract | Purpose | +|----------|---------| +| AppAccess1155 | ERC1155 for in-app items and passes | +| AppStakingVault | Additional staking vault (if needed) | +| EpochRewards | Time-boxed reward distribution | + +You own all these contracts after deployment. + +## Step 3: Configure Items + +The AppAccess1155 contract lets you create purchasable items. Users burn your token to buy items. + +### Create an Item + +```solidity +AppAccess1155 access = AppAccess1155(access1155); + +access.setItem( + 1, // Item ID + 50 ether, // Price in app tokens (50 tokens) + true, // Soulbound (non-transferable) + true, // Active (can be purchased) + 0, // Start time (0 = no restriction) + 0, // End time (0 = no restriction) + 10000, // Max supply (0 = unlimited) + "ipfs://Qm..." // Metadata URI +); +``` + +### Item Parameters + +| Parameter | Description | +|-----------|-------------| +| `itemId` | Unique identifier for this item | +| `price` | Cost in app tokens (burned on purchase) | +| `soulbound` | If true, item can't be transferred | +| `active` | If false, purchases are disabled | +| `startTime` | Unix timestamp when sales start | +| `endTime` | Unix timestamp when sales end | +| `maxSupply` | Maximum items that can exist | +| `uri` | Metadata URI for the item | + +### Create Multiple Tiers + +```solidity +// Basic pass - cheap, unlimited +access.setItem(1, 10 ether, true, true, 0, 0, 0, "ipfs://basic"); + +// Premium pass - mid-tier +access.setItem(2, 100 ether, true, true, 0, 0, 1000, "ipfs://premium"); + +// Legendary pass - expensive, rare +access.setItem(3, 1000 ether, true, true, 0, 0, 100, "ipfs://legendary"); +``` + +## Step 4: Configure Feature Gates + +Feature gates let you restrict app features based on staking or item ownership. + +### Stake-Based Gate + +Require users to stake tokens to access a feature: + +```solidity +access.setFeatureGate( + keccak256("premium_mode"), // Feature identifier + FeatureGate({ + minStake: 1000 ether, // Require 1000 tokens staked + requiredItem: 0, // No item required + requireBoth: false, + active: true + }) +); +``` + +### Item-Based Gate + +Require users to own an item: + +```solidity +access.setFeatureGate( + keccak256("vip_room"), + FeatureGate({ + minStake: 0, + requiredItem: 3, // Require legendary pass (ID 3) + requireBoth: false, + active: true + }) +); +``` + +### Combined Gate + +Require both staking and item ownership: + +```solidity +access.setFeatureGate( + keccak256("exclusive_tournament"), + FeatureGate({ + minStake: 5000 ether, // 5000 tokens staked + requiredItem: 2, // AND premium pass + requireBoth: true, // Both required + active: true + }) +); +``` + +### Check Access in Your App + +Your frontend or backend checks access before enabling features: + +```solidity +bool hasAccess = access.checkFeatureAccess( + userAddress, + keccak256("premium_mode"), + stakingVault.balanceOf(userAddress) // User's stake +); +``` + +## Step 5: Run Tournaments + +The TournamentFactory creates individual tournament contracts for competitive events. + +### Create a Tournament + +```solidity +Tournament tournament = TournamentFactory(tournamentFactory).createTournament( + token, // Prize token + 100 ether, // Entry fee per player + block.timestamp, // Registration starts now + block.timestamp + 7 days, // Registration ends in 7 days + block.timestamp + 8 days // Tournament ends in 8 days +); +``` + +### Tournament Lifecycle + +1. **Registration** — Users pay entry fee to join +2. **Running** — Your app determines rankings off-chain +3. **Finalization** — You submit results as a Merkle root +4. **Claims** — Winners claim prizes with proofs + +### Finalize and Distribute + +After the tournament: + +```solidity +// Generate Merkle tree from results off-chain +bytes32 merkleRoot = computeMerkleRoot(results); + +// Finalize on-chain +tournament.finalize(merkleRoot); + +// Winners claim their share +tournament.claim(winnerAddress, amount, merkleProof); +``` + +### Fee Structure + +| Fee | Amount | Destination | +|-----|--------|-------------| +| Protocol fee | 2.5% | Treasury | +| Burn fee | 1% | Burned | +| Prize pool | 96.5% | Winners | + +## Step 6: Distribute Rewards + +The EpochRewards contract handles time-boxed reward distributions. + +### Create an Epoch + +```solidity +EpochRewards rewards = EpochRewards(rewardsAddress); + +// Start a new epoch +uint256 epochId = rewards.createEpoch( + block.timestamp, // Start time + block.timestamp + 7 days // End time +); + +// Fund the epoch from your treasury +token.approve(address(rewards), 100000 ether); +rewards.fund(epochId, 100000 ether); +``` + +### Finalize with Merkle Root + +After computing rewards off-chain: + +```solidity +// Generate Merkle tree from reward allocations +bytes32 merkleRoot = computeMerkleRoot(allocations); + +// Finalize the epoch +rewards.finalizeEpoch(epochId, merkleRoot); +``` + +### User Claims + +Users claim their rewards: + +```solidity +rewards.claim(epochId, userAddress, amount, merkleProof); +``` + +## Complete Example + +Here's a full launch script: + +```solidity +// 1. Approve and create app +ELTA.approve(address(appFactory), 110 ether); +uint256 appId = appFactory.createApp( + "BrainFlow", + "FLOW", + 0, + "Meditation with EEG feedback", + "ipfs://...", + "https://brainflow.app" +); + +AppFactory.App memory app = appFactory.apps(appId); + +// 2. Deploy modules +(address access, , address rewards) = appModuleFactory.deployModules( + app.token, + "https://api.brainflow.app/items/" +); + +// 3. Configure items +AppAccess1155(access).setItem( + 1, 25 ether, true, true, 0, 0, 0, "ipfs://basic-meditation" +); +AppAccess1155(access).setItem( + 2, 100 ether, true, true, 0, 0, 500, "ipfs://guided-meditation" +); + +// 4. Set up feature gate +AppAccess1155(access).setFeatureGate( + keccak256("advanced_sessions"), + FeatureGate({ + minStake: 500 ether, + requiredItem: 0, + requireBoth: false, + active: true + }) +); + +// Ready for users! +``` + +## Frontend Integration + +Your app interacts with these contracts via standard Ethereum libraries. + +### Read Token Balance + +```typescript +import { useReadContract } from 'wagmi'; + +const { data: balance } = useReadContract({ + address: tokenAddress, + abi: AppTokenABI, + functionName: 'balanceOf', + args: [userAddress], +}); +``` + +### Buy on Bonding Curve + +```typescript +import { useWriteContract } from 'wagmi'; + +const { writeContract } = useWriteContract(); + +// First approve ELTA +await writeContract({ + address: eltaAddress, + abi: ELTAABI, + functionName: 'approve', + args: [bondingCurveAddress, amount], +}); + +// Then buy +await writeContract({ + address: bondingCurveAddress, + abi: BondingCurveABI, + functionName: 'buy', + args: [amount, minTokensOut], +}); +``` + +### Check Feature Access + +```typescript +const { data: hasAccess } = useReadContract({ + address: accessAddress, + abi: AppAccess1155ABI, + functionName: 'checkFeatureAccess', + args: [userAddress, featureId, userStake], +}); +``` + +## Best Practices + +### Token Economics + +- Start with conservative pricing—you can lower prices later +- Use soulbound items for access passes to prevent resale markets +- Keep some tokens in reserve for future rewards and marketing + +### Feature Gates + +- Don't gate too aggressively early on—let users try your app +- Use staking gates to encourage long-term engagement +- Use item gates for premium content + +### Tournaments + +- Start with small prize pools to test the flow +- Make entry fees proportional to expected skill level +- Communicate rules clearly before registration opens + +### Security + +- Test thoroughly on local and testnet before mainnet +- Consider time-limited items for seasonal content +- Monitor your contracts after launch + +## Troubleshooting + +### "Insufficient ELTA" on app creation + +You need 110 ELTA and gas. Get test ELTA: + +```bash +npm run faucet +``` + +### Can't deploy modules + +Only the token owner can deploy modules. Make sure you're calling from the address that created the app. + +### Items not appearing + +Check that: +- Item is set to `active: true` +- Current time is within start/end window +- Max supply hasn't been reached + +### Users can't buy on curve + +During the first 6 hours, only users with 100+ XP can buy. This is the early access period. + +## Contract References + +| Contract | Source | +|----------|--------| +| AppFactory | [src/apps/AppFactory.sol](../src/apps/AppFactory.sol) | +| AppToken | [src/apps/AppToken.sol](../src/apps/AppToken.sol) | +| AppBondingCurve | [src/apps/AppBondingCurve.sol](../src/apps/AppBondingCurve.sol) | +| AppModuleFactory | [src/apps/AppModuleFactory.sol](../src/apps/AppModuleFactory.sol) | +| AppAccess1155 | [src/apps/AppAccess1155.sol](../src/apps/AppAccess1155.sol) | +| AppStakingVault | [src/apps/AppStakingVault.sol](../src/apps/AppStakingVault.sol) | +| Tournament | [src/apps/Tournament.sol](../src/apps/Tournament.sol) | +| TournamentFactory | [src/apps/TournamentFactory.sol](../src/apps/TournamentFactory.sol) | + +## Next Steps + +- [TOKENOMICS.md](./TOKENOMICS.md) — Understanding the broader economic design +- [ARCHITECTURE.md](./ARCHITECTURE.md) — How all contracts fit together +- [LOCAL_DEVELOPMENT.md](./LOCAL_DEVELOPMENT.md) — Testing your integration locally + diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 79a938d..cdb2f9e 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -1,774 +1,325 @@ -# Elata Protocol Architecture +# Architecture Overview -## 🏗️ **System Architecture Overview** +This document explains how the Elata Protocol contracts fit together, the design decisions behind them, and how data flows through the system. + +## System Overview + +The protocol consists of three layers: + +1. **Core Token Layer** — ELTA token, veELTA staking, and XP reputation +2. **Governance Layer** — On-chain voting, timelocks, and funding allocation +3. **App Ecosystem Layer** — Token launches, bonding curves, and utility modules + +Each layer builds on the one below it. Apps use the governance layer for funding decisions, and governance uses the token layer for voting power calculations. ```mermaid graph TB - subgraph "Application Layer" - APP1[EEG Games] - APP2[Meditation Apps] - APP3[Research Tools] - APP4[Analytics Dashboard] - end - - subgraph "Protocol Layer" - subgraph "Core Contracts" - ELTA[ELTA Token
Governance & Utility] - VE[VeELTA
Multi-position Staking] - XP[ElataXP
Reputation System] - LP[LotPool
Funding Governance] - end - - subgraph "Advanced Contracts" - RD[RewardsDistributor
Yield Distribution] - GOV[ElataGovernor
Onchain Voting] - TL[ElataTimelock
Execution Delays] - STATS[ProtocolStats
Data Aggregation] - end + subgraph "App Ecosystem" + AppFactory[AppFactory] + AppToken[AppToken] + BondingCurve[BondingCurve] + Modules[Utility Modules] end - subgraph "Infrastructure Layer" - ZORP[ZORP Protocol
Data Submission] - IPFS[IPFS Storage
Decentralized Data] - KEEPERS[Keeper Network
Automation] + subgraph "Governance" + Governor[ElataGovernor] + Timelock[ElataTimelock] + LotPool[LotPool] + Rewards[RewardsDistributor] end - subgraph "Hardware Layer" - EEG[EEG Devices
Data Collection] - PI[Raspberry Pi
Processing] - ADS[ADS1299
Signal Acquisition] + subgraph "Core Tokens" + ELTA[ELTA] + VeELTA[VeELTA] + XP[ElataXP] end - APP1 --> ELTA - APP2 --> XP - APP3 --> LP - APP4 --> STATS + AppFactory --> AppToken + AppFactory --> BondingCurve + AppToken --> Modules - ELTA --> VE - VE --> RD - XP --> LP - GOV --> TL + Governor --> Timelock + LotPool --> XP + Rewards --> VeELTA - LP --> ZORP - RD --> KEEPERS - STATS --> IPFS - - ZORP --> EEG - EEG --> PI - PI --> ADS - - style ELTA fill:#ff9999 - style VE fill:#99ccff - style XP fill:#99ff99 - style LP fill:#ffcc99 + ELTA --> VeELTA + ELTA --> Governor + ELTA --> AppFactory ``` -## 📊 **Contract Interaction Matrix** +## Core Token Layer -```mermaid -graph TD - subgraph "Token Economics" - direction TB - ELTA[ELTA Token
77M Supply Cap] - MINT[Minting Logic
Role-gated] - BURN[Burning Logic
Deflationary] - - ELTA --> MINT - ELTA --> BURN - end - - subgraph "Staking Economics" - direction TB - LOCK[Lock Creation
NFT Positions] - POWER[Voting Power
Linear Decay] - DELEGATE[Delegation
Flexible Control] - - LOCK --> POWER - POWER --> DELEGATE - end - - subgraph "Reputation Economics" - direction TB - EARN[XP Earning
Activity-based] - HOLD[XP Balance
Permanent Reputation] - VOTE[Voting Rights
Funding Rounds] - - EARN --> HOLD - HOLD --> VOTE - end - - subgraph "Funding Economics" - direction TB - ROUNDS[Weekly Rounds
Community Voting] - ALLOCATION[Fund Allocation
Merit-based] - PAYOUT[Research Payouts
Transparent] - - ROUNDS --> ALLOCATION - ALLOCATION --> PAYOUT - end - - ELTA -.-> LOCK - POWER -.-> DELEGATE - VOTE -.-> ROUNDS - PAYOUT -.-> ELTA - - style ELTA fill:#ff9999 - style LOCK fill:#99ccff - style EARN fill:#99ff99 - style ROUNDS fill:#ffcc99 -``` +### ELTA Token -## 🔄 **State Transitions** +ELTA is a standard ERC20 token with governance extensions. It serves as the economic unit for the entire protocol. -### VeELTA Position Lifecycle +**Key properties:** +- 77 million maximum supply (hard cap, enforced in contract) +- ERC20Votes for on-chain governance delegation +- ERC20Permit for gasless approvals +- Burnable for deflationary mechanics +- No transfer fees or taxes -```mermaid -stateDiagram-v2 - [*] --> Created: createLock() - Created --> Active: Position NFT minted - Active --> Increased: increaseAmount() - Active --> Extended: increaseUnlockTime() - Active --> Merged: mergePositions() - Active --> Split: splitPosition() - Split --> Active: New positions created - Merged --> Active: Combined position - Increased --> Active: More ELTA locked - Extended --> Active: Longer duration - Active --> Expired: Time passes - Active --> EmergencyUnlocked: emergencyUnlock() - Expired --> Withdrawn: withdraw() - EmergencyUnlocked --> Withdrawn: withdraw() - Withdrawn --> [*]: NFT burned - - note right of Created - Initial voting power: - amount × duration ÷ MAX_LOCK - end note - - note right of Active - Voting power decays linearly: - amount × time_remaining ÷ MAX_LOCK - end note - - note right of EmergencyUnlocked - 50% penalty applied - Immediate withdrawal allowed - end note -``` +The token uses OpenZeppelin's AccessControl for minting permissions. Only addresses with `MINTER_ROLE` can mint new tokens, and minting always respects the supply cap. -### XP State Machine +Source: [src/token/ELTA.sol](../src/token/ELTA.sol) -```mermaid -stateDiagram-v2 - [*] --> Awarded: XP Granted - Awarded --> Held: Permanent Balance - Held --> Voting: Used in Governance - Held --> Revoked: Admin Revokes - Voting --> Held: After Vote - Revoked --> [*]: XP Burned - - note right of Awarded - XP minted via operator - or signature authorization - end note - - note right of Held - Permanent reputation - Snapshot-based tracking - end note - - note right of Revoked - Only by XP_OPERATOR_ROLE - Exceptional circumstances - end note -``` +### VeELTA Staking -### Funding Round State Flow +VeELTA represents locked ELTA with time-weighted voting power. Users lock ELTA for a duration between 7 days and 2 years, receiving veELTA that determines their governance influence and reward share. -```mermaid -stateDiagram-v2 - [*] --> Setup: Admin creates round - Setup --> Active: startRound() - Active --> Voting: Users cast votes - Voting --> Voting: More votes - Voting --> Closed: Duration expires - Closed --> Finalized: finalize() - Finalized --> [*]: Funds distributed - - note right of Setup - - Define options - - Set recipients - - Take XP snapshot - end note - - note right of Voting - - XP allocation - - Cannot exceed snapshot - - Immutable votes - end note - - note right of Finalized - - Winner determined - - ELTA transferred - - Events emitted - end note -``` +**How the boost works:** -## 📐 **Mathematical Models** +Locking for longer gives more veELTA per ELTA locked: +- 7 days (minimum): 1x boost +- 1 year: 1.5x boost +- 2 years (maximum): 2x boost -### Voting Power Decay Function +The formula is linear interpolation: -```mermaid -graph LR - subgraph "Linear Decay Model" - INPUT[Lock: 1000 ELTA
Duration: 104 weeks] - FORMULA[f(t) = 1000 × (104-t)/104] - OUTPUT[Voting Power over Time] - end - - INPUT --> FORMULA --> OUTPUT +``` +boost = 1 + (duration / MAX_LOCK) +veELTA_minted = ELTA_locked × boost ``` -**Mathematical Expression:** -$$ -VP(t) = A \times \frac{\max(0, D - t)}{MAX\_LOCK} -$$ +**Lock lifecycle:** -Where: -- $VP(t)$ = Voting power at time $t$ -- $A$ = Locked amount -- $D$ = Lock duration -- $t$ = Time elapsed since lock creation -- $MAX\_LOCK$ = 104 weeks (2 years) +1. User calls `lock(amount, unlockTime)` to create a position +2. veELTA is minted based on amount and duration +3. User can call `increaseAmount()` to add more ELTA +4. User can call `extendLock()` to push out the unlock time +5. After unlock time passes, user calls `unlock()` to retrieve ELTA -### XP Balance Function +The veELTA balance is used for both governance voting and reward distribution snapshots. It's non-transferable to prevent vote buying. -```mermaid -graph LR - subgraph "Permanent Reputation Model" - XP_INPUT[XP Awarded: 1000 XP
Timestamp: t₀] - XP_BALANCE[Balance = 1000 XP
Permanent] - XP_OUTPUT[Voting Power = Balance
at Snapshot] - end - - XP_INPUT --> XP_BALANCE --> XP_OUTPUT -``` +Source: [src/staking/VeELTA.sol](../src/staking/VeELTA.sol) -**Mathematical Expression:** -$$ -XP_{balance}(t) = \sum_{i=1}^{n} XP_i - \sum_{j=1}^{m} XP_{revoked,j} -$$ +### ElataXP Reputation -Where: -- $XP_{balance}(t)$ = Total XP balance (permanent unless revoked) -- $XP_i$ = Amount of XP award $i$ -- $XP_{revoked,j}$ = Amount of XP revoked in event $j$ -- No time decay applied +XP tracks user participation and contribution. Unlike ELTA, XP cannot be transferred or traded. It's earned through protocol activity and used to weight votes in funding decisions. -### Reward Distribution Formula +**Distribution methods:** -$$ -R_u = \frac{VP_u}{\sum_{i=1}^{n} VP_i} \times R_{total} -$$ +1. **Direct award** — Operators with `XP_OPERATOR_ROLE` call `award(user, amount)` +2. **Signature-based** — Off-chain operators sign EIP-712 messages that users submit +3. **Merkle claims** — Batch distributions via Merkle tree proofs -Where: -- $R_u$ = Reward for user $u$ -- $VP_u$ = User's voting power at epoch snapshot -- $R_{total}$ = Total epoch rewards +XP is permanent by default. Once earned, it stays unless explicitly revoked by an operator. This simplifies accounting and makes reputation predictable. -## 🔗 **Integration Patterns** +**Why separate XP from ELTA?** -### Frontend Data Flow +XP represents *participation* (voice in funding decisions), while ELTA represents *ownership* (economic stake and yield). Keeping them separate prevents users from simply buying reputation. You have to earn XP through actual contribution. -```mermaid -sequenceDiagram - participant Frontend - participant ProtocolStats - participant ELTA - participant VeELTA - participant ElataXP - participant LotPool - - Note over Frontend, LotPool: Dashboard Load - Frontend->>ProtocolStats: getUserSummary(address) - ProtocolStats->>ELTA: balanceOf(user) - ProtocolStats->>VeELTA: getUserVotingPower(user) - ProtocolStats->>ElataXP: balanceOf(user) - ProtocolStats->>LotPool: getUserVotingStatus(user, round) - ProtocolStats-->>Frontend: Complete user data - - Note over Frontend, LotPool: Real-time Updates - ELTA->>Frontend: Transfer event - VeELTA->>Frontend: LockCreated event - ElataXP->>Frontend: XPAwarded event - LotPool->>Frontend: Voted event - - Frontend->>Frontend: Update UI state -``` +Source: [src/experience/ElataXP.sol](../src/experience/ElataXP.sol) -### Cross-Contract Communication +See also: [xp-system.md](./xp-system.md) for Merkle distribution details. -```mermaid -graph TD - subgraph "Contract Dependencies" - direction TB - - ELTA --> VE_DEP[VeELTA depends on ELTA
for token transfers] - XP --> LP_DEP[LotPool depends on ElataXP
for voting snapshots] - VE --> RD_DEP[RewardsDistributor depends on VeELTA
for voting power calculations] - ELTA --> GOV_DEP[ElataGovernor depends on ELTA
for voting tokens] - end - - subgraph "Data Flow" - direction LR - - USER_ACTION[User Action] --> CONTRACT_CALL[Contract Function] - CONTRACT_CALL --> STATE_CHANGE[State Update] - STATE_CHANGE --> EVENT_EMIT[Event Emission] - EVENT_EMIT --> FRONTEND_UPDATE[Frontend Update] - end - - style VE_DEP fill:#e3f2fd - style LP_DEP fill:#f3e5f5 - style RD_DEP fill:#e8f5e8 - style GOV_DEP fill:#fff3e0 -``` +## Governance Layer -## 🛡️ **Security Model Deep Dive** +### LotPool Funding Rounds -### Access Control Matrix +LotPool runs weekly funding rounds where the community decides how to allocate treasury funds. Votes are weighted by XP, not ELTA, so funding decisions reflect participation rather than capital. -```mermaid -graph TD - subgraph "Role Hierarchy" - ADMIN[DEFAULT_ADMIN_ROLE
🔑 Master Control] - MINTER[MINTER_ROLE
🏭 Token Creation] - MANAGER[MANAGER_ROLE
⚙️ Operations] - DISTRIBUTOR[DISTRIBUTOR_ROLE
💰 Rewards] - KEEPER[KEEPER_ROLE
🤖 Automation] - PAUSER[PAUSER_ROLE
⏸️ Emergency Stop] - EMERGENCY[EMERGENCY_ROLE
🚨 Critical Actions] - end - - ADMIN --> MINTER - ADMIN --> MANAGER - ADMIN --> DISTRIBUTOR - ADMIN --> KEEPER - ADMIN --> PAUSER - ADMIN --> EMERGENCY - - style ADMIN fill:#ff9999 - style EMERGENCY fill:#ffcdd2 -``` +**Round lifecycle:** -### Security Layers +1. Admin calls `startRound()` with a list of proposals and their recipient addresses +2. Contract takes an XP snapshot at the current block +3. Users vote by allocating their XP across proposals +4. After the voting period (typically 7 days), admin calls `finalize()` +5. The winning proposal's recipient receives ELTA from the pool -```mermaid -graph LR - subgraph "Layer 1: Input Validation" - L1_1[Zero Address Checks] - L1_2[Amount Validation] - L1_3[Array Length Matching] - L1_4[Boundary Conditions] - end - - subgraph "Layer 2: Access Control" - L2_1[Role-based Permissions] - L2_2[Multi-signature Requirements] - L2_3[Function Modifiers] - L2_4[Emergency Controls] - end - - subgraph "Layer 3: Economic Security" - L3_1[Time-locked Positions] - L3_2[Non-transferable Assets] - L3_3[Supply Caps] - L3_4[Linear Decay] - end - - subgraph "Layer 4: Operational Security" - L4_1[Reentrancy Guards] - L4_2[State Validation] - L4_3[External Call Safety] - L4_4[Event Logging] - end - - L1_1 --> L2_1 - L1_2 --> L2_2 - L1_3 --> L2_3 - L1_4 --> L2_4 - - L2_1 --> L3_1 - L2_2 --> L3_2 - L2_3 --> L3_3 - L2_4 --> L3_4 - - L3_1 --> L4_1 - L3_2 --> L4_2 - L3_3 --> L4_3 - L3_4 --> L4_4 -``` +Users can split their XP across multiple proposals. The snapshot ensures nobody can earn XP mid-round to influence the vote. -### Attack Vector Mitigation +Source: [src/governance/LotPool.sol](../src/governance/LotPool.sol) -```mermaid -graph TD - subgraph "Flash Loan Attacks" - FA1[Attacker borrows large ELTA amount] - FA2[Tries to create governance positions] - FA3[❌ BLOCKED: Time-locked staking required] - end - - subgraph "Voting Manipulation" - VM1[Attacker tries to buy XP/votes] - VM2[Attempts to transfer reputation] - VM3[❌ BLOCKED: Non-transferable XP] - end - - subgraph "Supply Manipulation" - SM1[Attacker tries to mint unlimited tokens] - SM2[Attempts to exceed supply cap] - SM3[❌ BLOCKED: Hard cap enforcement] - end - - subgraph "Governance Takeover" - GT1[Attacker accumulates voting power] - GT2[Tries to pass malicious proposals] - GT3[❌ BLOCKED: Quorum + timelock delays] - end - - style FA3 fill:#c8e6c9 - style VM3 fill:#c8e6c9 - style SM3 fill:#c8e6c9 - style GT3 fill:#c8e6c9 -``` +### ElataGovernor -## 💰 **Economic Mechanism Design** +The Governor handles protocol parameter changes and upgrades through on-chain voting. It uses ELTA (via delegation) for voting power. -### Token Value Accrual Model +**Standard proposals:** +- Voting delay: 1 day (time between proposal and voting start) +- Voting period: 7 days +- Proposal threshold: 0.1% of total supply (~77,000 ELTA) +- Quorum: 4% of total supply (~3.08M ELTA) -```mermaid -graph TD - subgraph "Revenue Sources" - RS1[App Store Fees
15% take rate] - RS2[Tournament Rake
5-10% of prizes] - RS3[Infrastructure Fees
Protocol usage] - RS4[Premium Features
ELTA-gated access] - end - - subgraph "Value Distribution" - VD1[Treasury: 50%
Operations & Growth] - VD2[Staker Yields: 25%
Real Returns] - VD3[Buyback & Burn: 25%
Supply Reduction] - end - - subgraph "Demand Drivers" - DD1[Governance Participation] - DD2[Yield Expectations] - DD3[App Ecosystem Access] - DD4[Speculative Premium] - end - - RS1 --> VD1 - RS2 --> VD2 - RS3 --> VD3 - RS4 --> VD1 - - VD2 --> DD1 - VD2 --> DD2 - VD3 --> DD3 - VD1 --> DD4 - - style VD2 fill:#e8f5e8 - style VD3 fill:#ffebee -``` +**Emergency proposals:** +- Proposal threshold: 5% of total supply +- Voting period: 3 days (expedited) -### Staking Incentive Alignment +Emergency proposals allow faster response to critical issues while requiring higher threshold to prevent abuse. -```mermaid -graph LR - subgraph "Short-term Stakers" - ST1[1-4 week locks] - ST2[Low voting power] - ST3[Minimal rewards] - ST4[High flexibility] - end - - subgraph "Medium-term Stakers" - MT1[6 month - 1 year locks] - MT2[Moderate voting power] - MT3[Proportional rewards] - MT4[Balanced commitment] - end - - subgraph "Long-term Stakers" - LT1[2-4 year locks] - LT2[Maximum voting power] - LT3[Highest rewards] - LT4[Strong alignment] - end - - ST1 --> ST2 --> ST3 --> ST4 - MT1 --> MT2 --> MT3 --> MT4 - LT1 --> LT2 --> LT3 --> LT4 - - style LT1 fill:#4caf50 - style LT2 fill:#4caf50 - style LT3 fill:#4caf50 - style LT4 fill:#4caf50 -``` +The Governor can be connected to ElataTimelock for execution delays, though the initial deployment operates without timelock integration. -## 🎮 **User Journey Flows** +Source: [src/governance/ElataGovernor.sol](../src/governance/ElataGovernor.sol) -### New User Onboarding +### RewardsDistributor -```mermaid -journey - title New User Journey - section Discovery - Learn about Elata: 5: User - Read documentation: 4: User - Join community: 5: User - section First Interaction - Get ELTA tokens: 3: User - Try EEG app: 5: User - Earn first XP: 5: User - section Engagement - Participate in funding: 4: User - Create staking position: 3: User - Delegate voting power: 3: User - section Advanced Usage - Manage multiple positions: 4: User - Claim staking rewards: 5: User - Participate in governance: 4: User -``` +The RewardsDistributor collects protocol fees and splits them according to a fixed ratio: -### Researcher Journey +- 70% to app token stakers (proportional to their stake) +- 15% to veELTA holders (proportional to their veELTA) +- 15% to treasury -```mermaid -journey - title Researcher Journey - section Proposal Creation - Identify research need: 5: Researcher - Create funding proposal: 4: Researcher - Submit to community: 4: Researcher - section Community Voting - Present to community: 4: Researcher - Community votes with XP: 5: Community - Results announced: 5: Researcher - section Funding & Execution - Receive ELTA funding: 5: Researcher - Execute research: 5: Researcher - Publish results: 4: Researcher - section Impact - Data benefits community: 5: Community - Researcher reputation grows: 5: Researcher - More funding opportunities: 5: Researcher -``` +Revenue sources include trading fees from bonding curves (1%), tournament rake, and app-specific fees. The distributor accepts both ELTA and app tokens, tracking them in separate epochs. -### Developer Integration Journey +Claims use on-chain snapshots rather than Merkle trees, so users can claim directly without needing off-chain proof generation. -```mermaid -journey - title Developer Integration - section Setup - Read documentation: 4: Developer - Clone repository: 5: Developer - Run local tests: 5: Developer - section Integration - Connect to contracts: 4: Developer - Implement XP rewards: 4: Developer - Add staking features: 3: Developer - section Advanced Features - Integrate governance: 3: Developer - Add reward claiming: 4: Developer - Optimize gas usage: 4: Developer - section Production - Deploy to testnet: 4: Developer - Community testing: 5: Community - Mainnet launch: 5: Developer -``` +Source: [src/rewards/RewardsDistributor.sol](../src/rewards/RewardsDistributor.sol) -## 🔄 **Data Flow Diagrams** +## App Ecosystem Layer -### Complete Protocol Data Flow +The app ecosystem allows developers to launch their own tokens with built-in economic infrastructure. + +### App Launch Flow ```mermaid -flowchart TD - subgraph "User Actions" - UA1[Play EEG Games] - UA2[Submit Data] - UA3[Stake ELTA] - UA4[Vote in Rounds] - end - - subgraph "Smart Contract Layer" - SC1[ElataXP.award()] - SC2[VeELTA.createLock()] - SC3[LotPool.vote()] - SC4[RewardsDistributor.claim()] - end - - subgraph "State Changes" - ST1[XP Balance Updated] - ST2[NFT Position Minted] - ST3[Vote Recorded] - ST4[Rewards Claimed] - end - - subgraph "Events Emitted" - EV1[XPAwarded] - EV2[LockCreated] - EV3[Voted] - EV4[RewardClaimed] - end - - subgraph "Frontend Updates" - FE1[Update XP Display] - FE2[Show New Position] - FE3[Update Vote Status] - FE4[Show Claimed Rewards] - end - - UA1 --> SC1 --> ST1 --> EV1 --> FE1 - UA3 --> SC2 --> ST2 --> EV2 --> FE2 - UA4 --> SC3 --> ST3 --> EV3 --> FE3 - UA4 --> SC4 --> ST4 --> EV4 --> FE4 - - style SC1 fill:#e8f5e8 - style SC2 fill:#e3f2fd - style SC3 fill:#f3e5f5 - style SC4 fill:#fff3e0 +sequenceDiagram + participant Dev as Developer + participant Factory as AppFactory + participant Token as AppToken + participant Curve as BondingCurve + participant Users + + Dev->>Factory: createApp() + 110 ELTA + Factory->>Token: Deploy token (1B supply) + Factory->>Curve: Deploy bonding curve + Factory->>Token: 50% to dev (auto-staked) + Factory->>Curve: 50% to curve + + Users->>Curve: buy() with ELTA + Curve->>Users: App tokens at curve price + + Note over Curve: At 42k ELTA raised + Curve->>Curve: Graduate to DEX + Curve->>Curve: Lock LP for 2 years ``` -## 🎯 **Performance Analysis** +**Step by step:** -### Gas Cost Breakdown +1. Developer pays 110 ELTA (100 seed + 10 creation fee) +2. AppFactory deploys an AppToken with 1 billion supply +3. AppFactory deploys a bonding curve for price discovery +4. 50% of tokens go to the developer (auto-staked for alignment) +5. 50% go to the bonding curve for public trading +6. Users buy tokens with ELTA; price rises along the curve +7. When 42,000 ELTA is raised, the curve graduates +8. Graduation creates a DEX liquidity pair and locks it for 2 years -```mermaid -graph TD - subgraph "Contract Deployment" - CD1[ELTA: 2.3M gas
$46 @ 20 gwei] - CD2[VeELTA: 3.3M gas
$66 @ 20 gwei] - CD3[ElataXP: 3.0M gas
$60 @ 20 gwei] - CD4[LotPool: 1.4M gas
$28 @ 20 gwei] - CD5[Others: 2.0M gas
$40 @ 20 gwei] - TOTAL[Total: 13M gas
$260 @ 20 gwei] - end - - CD1 --> TOTAL - CD2 --> TOTAL - CD3 --> TOTAL - CD4 --> TOTAL - CD5 --> TOTAL - - style TOTAL fill:#e8f5e8 -``` +### AppFactory + +The factory deploys new app tokens and their bonding curves. It also registers apps in an on-chain registry for discovery. + +**XP-gated early access:** + +For the first 6 hours after launch, only users with at least 100 XP can buy. This rewards active community members and prevents bot sniping. + +Source: [src/apps/AppFactory.sol](../src/apps/AppFactory.sol) -### Operation Cost Comparison +### AppBondingCurve + +The bonding curve provides fair price discovery without traditional liquidity provision. Price increases as more tokens are bought, following a predetermined curve. + +A 1% trading fee on each buy/sell routes to the RewardsDistributor. After graduation, all trading happens on the DEX instead. + +Source: [src/apps/AppBondingCurve.sol](../src/apps/AppBondingCurve.sol) + +### Utility Modules + +After launching a token, developers can add utility modules: + +| Module | Purpose | Source | +|--------|---------|--------| +| AppStakingVault | Per-app token staking | [AppStakingVault.sol](../src/apps/AppStakingVault.sol) | +| AppAccess1155 | NFT items and access passes | [AppAccess1155.sol](../src/apps/AppAccess1155.sol) | +| EpochRewards | Time-boxed reward distribution | [src/apps/EpochRewards.sol](../src/apps/) | +| Tournament | Competitive events with prizes | [Tournament.sol](../src/apps/Tournament.sol) | + +Modules are deployed via AppModuleFactory and configured by the app developer. + +Source: [src/apps/AppModuleFactory.sol](../src/apps/AppModuleFactory.sol) + +## Fee Flow ```mermaid graph LR - subgraph "Basic Operations" - BO1[ELTA Transfer
56K gas] - BO2[ERC20 Standard
~21K gas] - BO3[2.7x overhead
Due to voting features] - end - - subgraph "Staking Operations" - SO1[Create Lock
257K gas] - SO2[Increase Amount
52K gas] - SO3[Withdraw
78K gas] - end + Trading[Trading Fees 1%] --> Router[AppFeeRouter] + Tournament[Tournament Rake] --> Router + AppFees[App-specific Fees] --> Router - subgraph "Governance Operations" - GO1[XP Award
230K gas] - GO2[Vote in Round
86K gas] - GO3[Claim Rewards
80K gas] - end + Router --> Distributor[RewardsDistributor] - style BO1 fill:#fff3e0 - style SO1 fill:#e3f2fd - style GO1 fill:#f3e5f5 + Distributor --> AppStakers[70% App Stakers] + Distributor --> VeELTA[15% veELTA Holders] + Distributor --> Treasury[15% Treasury] ``` -## 🔮 **Future Architecture** +All protocol fees flow through AppFeeRouter to RewardsDistributor. This ensures consistent distribution regardless of the fee source. -### Planned Integrations +## Design Decisions + +### Why non-upgradeable contracts? + +Upgradeable contracts (proxies) add complexity and trust assumptions. By making contracts immutable: +- Users can verify the code they're interacting with +- No admin can change contract logic after deployment +- Security audits remain valid indefinitely + +The tradeoff is that bugs cannot be fixed in place. We mitigate this with thorough testing and the ability to deploy new versions that users can migrate to. + +### Why separate governance tokens? + +The protocol uses three different tokens for different purposes: +- **ELTA** for economic ownership and protocol governance +- **veELTA** for time-weighted voting power +- **XP** for participation-weighted funding decisions + +This separation prevents plutocracy (money buying all influence) while still rewarding economic stakeholders. + +### Why time-locked staking? + +Time-locking ELTA into veELTA: +- Prevents flash loan governance attacks +- Aligns voters with long-term protocol health +- Creates predictable token supply dynamics + +### Why bonding curves for app launches? + +Bonding curves provide: +- Fair price discovery without market makers +- Transparent, deterministic pricing +- Protection against rug pulls (LP is locked on graduation) +- Equal opportunity for all buyers (no insider allocations) + +## Contract Dependencies -```mermaid -graph TB - subgraph "Current Protocol" - CURRENT[Elata Protocol v2.0
Complete Implementation] - end - - subgraph "Phase 3: Ecosystem Integration" - ZORP_INT[ZORP Integration
Data submission rewards] - EEG_INT[EEG Hardware
Direct device integration] - APP_STORE[App Ecosystem
Revenue sharing] - DATA_MARKET[Data Marketplace
Monetization] - end - - subgraph "Phase 4: Advanced Features" - CROSS_CHAIN[Cross-chain Bridge
Multi-network support] - ZK_PRIVACY[ZK Privacy
Anonymous participation] - AI_MODELS[AI Marketplace
Model monetization] - MOBILE_SDK[Mobile SDK
Native app integration] - end - - CURRENT --> ZORP_INT - CURRENT --> EEG_INT - CURRENT --> APP_STORE - CURRENT --> DATA_MARKET - - ZORP_INT --> CROSS_CHAIN - EEG_INT --> ZK_PRIVACY - APP_STORE --> AI_MODELS - DATA_MARKET --> MOBILE_SDK - - style CURRENT fill:#4caf50 - style ZORP_INT fill:#2196f3 - style CROSS_CHAIN fill:#9c27b0 ``` +ELTA +├── VeELTA (locks ELTA) +├── ElataGovernor (uses ELTA for voting) +└── AppFactory (accepts ELTA for app creation) ---- +ElataXP +└── LotPool (uses XP for funding votes) -## 📚 **Documentation Map** +VeELTA +└── RewardsDistributor (uses veELTA for reward claims) -```mermaid -graph TD - subgraph "User Documentation" - UD1[README.md
📖 Overview & Quick Start] - UD2[CONTRIBUTING.md
👥 Developer Guide] - UD3[FAQ.md
❓ Common Questions] - end - - subgraph "Technical Documentation" - TD1[ARCHITECTURE.md
🏗️ System Design] - TD2[DEPLOYMENT.md
🚀 Deployment Guide] - TD3[FRONTEND_INTEGRATION.md
🖥️ API Reference] - end - - subgraph "Reference Documentation" - RD1[Contract ABIs
📋 Interface Specs] - RD2[Gas Reports
⛽ Cost Analysis] - RD3[Test Coverage
🧪 Quality Metrics] - end - - UD1 --> TD1 - UD2 --> TD2 - UD3 --> TD3 - - TD1 --> RD1 - TD2 --> RD2 - TD3 --> RD3 - - style UD1 fill:#e8f5e8 - style TD1 fill:#e3f2fd - style RD1 fill:#fff3e0 +AppToken +├── AppBondingCurve (handles trading) +├── AppStakingVault (handles staking) +└── AppAccess1155 (handles item purchases) ``` ---- +## Gas Costs + +Typical operation costs on Ethereum mainnet (at 20 gwei): -*This architecture represents a complete, production-ready DeFi protocol designed specifically for neuroscience research coordination and community governance.* +| Operation | Gas | Cost | +|-----------|-----|------| +| ELTA transfer | 56k | $2.20 | +| Create staking lock | 88k | $3.50 | +| Vote in funding round | 86k | $3.40 | +| Claim rewards | 80k | $3.20 | +| Create app | 7.2M | $288 | +App creation is expensive due to deploying multiple contracts. On L2s like Base, these costs are 50-100x lower. diff --git a/docs/COMPLETE_USER_GUIDE.md b/docs/COMPLETE_USER_GUIDE.md deleted file mode 100644 index 03c35d4..0000000 --- a/docs/COMPLETE_USER_GUIDE.md +++ /dev/null @@ -1,522 +0,0 @@ -# Complete App Creator Guide - -## Overview - -This guide walks through the complete process of launching an app with full utility features on Elata Protocol. - ---- - -## Prerequisites - -- ELTA tokens for fees: - - App creation: Query `appFactory.getTotalCreationCost()` (default 110 ELTA, governable) - - Module deployment: Query `moduleFactory.createFeeELTA()` (optional, governable) -- Ethereum wallet with ETH for gas -- Understanding of your app's tokenomics needs - -**Note**: All ELTA fees are governable by protocol and adjust based on market conditions. -Use view functions to check current costs before transactions. - ---- - -## Step-by-Step Deployment - -### Step 1: Create Your App Token - -**Call**: `AppFactory.createApp()` - -```solidity -// Check current cost (fees are governable) -uint256 totalCost = appFactory.getTotalCreationCost(); - -// Approve ELTA for creation -elta.approve(appFactory, totalCost); - -// Create app -uint256 appId = appFactory.createApp( - "NeuroRacing Token", // Token name - "NRACE", // Token symbol - 1_000_000_000 ether, // Supply (or 0 for default 1B) - "High-speed EEG racing game", - "ipfs://QmImageHash", - "https://neurorac.ing" -); - -// Cost: Default 110 ELTA (100 seed + 10 fee), but governable -// Always check getTotalCreationCost() before calling -``` - -**What You Receive:** -1. **AppToken deployed** at `apps[appId].token` - - You are the `appCreator` and have `DEFAULT_ADMIN_ROLE` - - Can call `owner()`, `updateMetadata()`, `finalizeMinting()` - -2. **100,000,000 tokens** (10% of supply) in your wallet - - This is your rewards treasury - - Use for funding epoch rewards - - Can also stake, sell, or hold - -3. **900,000,000 tokens** (90%) in bonding curve - - Available for public trading - - Price discovery via constant product formula - - Graduates to Uniswap at 42k ELTA raised - -4. **Full control** of your token - - Can call `finalizeMinting()` to permanently lock supply - - Can manage roles (though minter already revoked) - - Can update metadata anytime - -**Query Your App:** -```solidity -App memory myApp = appFactory.getApp(appId); -AppToken token = AppToken(myApp.token); - -// You now have: -uint256 myBalance = token.balanceOf(msg.sender); // 100M tokens -bool isAdmin = token.hasRole(token.DEFAULT_ADMIN_ROLE(), msg.sender); // true -address owner = token.owner(); // returns msg.sender -``` - ---- - -### Step 2: Deploy Utility Modules - -**Call**: `AppModuleFactory.deployModules()` - -```solidity -// Optional: Approve ELTA for creation fee (if set) -elta.approve(moduleFactory, createFeeELTA); - -// Deploy all core modules -( - address access1155, - address stakingVault, - address epochRewards -) = moduleFactory.deployModules( - appTokenAddress, - "https://metadata.myapp.com/" -); - -// Cost: Optional ELTA fee (e.g., 50 ELTA) -``` - -**What You Receive:** -1. **AppAccess1155** - For items and passes - - You own this contract - - Configure items, feature gates - -2. **AppStakingVault** - For staking - - You own this contract - - Users stake your token here - -3. **EpochRewards** - For reward distribution - - You own this contract - - Reusable for all seasons - - Fund from your 100M token treasury - -**All Three Are:** -- Owned by you -- Linked to your app token -- Registered in factory -- Ready to configure - ---- - -### Step 3: Configure Your In-Game Economy - -**Configure Items:** - -```solidity -AppAccess1155 access = AppAccess1155(access1155Address); - -// Season Pass (soulbound, limited time) -access.setItem( - 1, // Item ID - 50 ether, // Price: 50 tokens (BURNS on purchase) - true, // Soulbound (cannot transfer) - true, // Active - block.timestamp, // Start now - block.timestamp + 30 days, // End in 30 days - 5000, // Max 5000 passes - "ipfs://season-1-pass" -); - -// Premium Skin (transferable, permanent) -access.setItem( - 2, - 20 ether, // Price: 20 tokens - false, // Transferable (can trade) - true, - 0, // No start time - 0, // No end time - 0, // Unlimited supply - "ipfs://premium-skin-gold" -); - -// Power-Up Bundle (consumable concept via quantity) -access.setItem( - 3, - 10 ether, - false, - true, - 0, - 0, - 0, - "ipfs://power-up-bundle" -); -``` - -**Configure Feature Gates:** - -```solidity -// Bronze tier - just stake -bytes32 bronze = keccak256("bronze_tier"); -access.setFeatureGate(bronze, FeatureGate({ - minStake: 100 ether, // Need 100 tokens staked - requiredItem: 0, // No item needed - requireBoth: false, - active: true -})); - -// Gold tier - stake + pass -bytes32 gold = keccak256("gold_tier"); -access.setFeatureGate(gold, FeatureGate({ - minStake: 500 ether, // Need 500 staked - requiredItem: 1, // AND season pass - requireBoth: true, // Both required - active: true -})); - -// Exclusive tournament access - pass OR high stake -bytes32 tourneyAccess = keccak256("tournament_vip"); -access.setFeatureGate(tourneyAccess, FeatureGate({ - minStake: 1000 ether, - requiredItem: 1, - requireBoth: false, // Either one works - active: true -})); -``` - -**In Your App/Game:** -```typescript -// Check if player can access feature -const stake = await vault.stakedOf(playerAddress); -const hasAccess = await access.checkFeatureAccess( - playerAddress, - keccak256("gold_tier"), - stake -); - -if (hasAccess) { - unlockGoldFeatures(player); -} -``` - ---- - -### Step 4: Deploy Tournaments (Per Event) - -**Call**: `TournamentFactory.createTournament()` - -```solidity -TournamentFactory tournamentFactory = TournamentFactory(factoryAddress); - -// Weekly tournament -address weeklyTournament = tournamentFactory.createTournament( - appTokenAddress, - 5 ether, // Entry fee: 5 tokens - uint64(block.timestamp), // Start now - uint64(block.timestamp + 7 days) // End in 7 days -); - -// Monthly championship (higher stakes) -address championship = tournamentFactory.createTournament( - appTokenAddress, - 20 ether, // Entry fee: 20 tokens - uint64(block.timestamp + 7 days), // Starts next week - uint64(block.timestamp + 37 days) // Runs for 30 days -); - -// Custom fees for special event -address specialEvent = tournamentFactory.createTournamentWithFees( - appTokenAddress, - 10 ether, - 0, - uint64(block.timestamp + 14 days), - 500, // 5% protocol fee - 200 // 2% burn fee -); - -// Cost: Gas only (no ELTA fee) -``` - -**What You Get:** -- New Tournament contract you own -- Registered in factory (queryable) -- Ready for entries -- Single-use (create new one for next event) - -**Manage Tournament:** -```solidity -Tournament tourn = Tournament(weeklyTournament); - -// Users enter (they approve and call) -// tourn.enter(); - -// After tournament ends, you finalize with winners -bytes32 merkleRoot = generateMerkleRoot(winners); // Off-chain -tourn.finalize(merkleRoot); - -// Winners claim -// user calls: tourn.claim(proof, amount); -``` - -**Query Your Tournaments:** -```solidity -// Get all tournaments for your app -address[] memory myTournaments = tournamentFactory.getAppTournaments(appTokenAddress); - -// Get tournaments you created -address[] memory created = tournamentFactory.getCreatorTournaments(msg.sender); -``` - ---- - -### Step 5: Run Reward Epochs (Reusable Contract) - -**Use the EpochRewards deployed in Step 2:** - -```solidity -EpochRewards rewards = EpochRewards(epochRewardsAddress); - -// Start Season 1 -rewards.startEpoch( - uint64(block.timestamp), - uint64(block.timestamp + 30 days) -); - -// Fund from your creator treasury -appToken.approve(epochRewardsAddress, 10_000_000 ether); -rewards.fund(10_000_000 ether); - -// Players play your game, earn XP off-chain - -// At end of month, compute rankings and generate Merkle tree -bytes32 merkleRoot = generateRewardsMerkleRoot(players); // Off-chain - -// Finalize epoch -rewards.finalizeEpoch(merkleRoot); - -// Players claim their rewards -// player calls: rewards.claim(epochId, proof, amount); -``` - -**Start Season 2:** -```solidity -// Same contract, new epoch! -rewards.startEpoch( - uint64(block.timestamp), - uint64(block.timestamp + 30 days) -); - -appToken.approve(epochRewardsAddress, 8_000_000 ether); -rewards.fund(8_000_000 ether); - -// Repeat for all future seasons -``` - ---- - -## Complete Example: Monthly Operations - -### Month 1 Setup - -```solidity -// 1. Configure new items for the month -access.setItem(4, 30 ether, false, true, - block.timestamp, - block.timestamp + 30 days, - 1000, - "ipfs://february-skin" -); - -// 2. Deploy tournament for the month -address febTournament = tournamentFactory.createTournament( - appToken, - 5 ether, - uint64(block.timestamp), - uint64(block.timestamp + 30 days) -); - -// 3. Start monthly epoch -epochRewards.startEpoch( - uint64(block.timestamp), - uint64(block.timestamp + 30 days) -); - -appToken.approve(epochRewards, 10_000_000 ether); -epochRewards.fund(10_000_000 ether); -``` - -### Month 1 Activity (Automated) - -Users: -- Purchase February skin (burns 30 tokens each) -- Stake tokens to access premium tiers -- Enter tournament (5 token entry fee) -- Play games, earn XP off-chain - -### Month 1 End - -```solidity -// 1. Finalize tournament -bytes32 tourneyRoot = computeTournamentWinners(); // Your backend -Tournament(febTournament).finalize(tourneyRoot); - -// Winners claim -// Top player calls: Tournament(febTournament).claim(proof, 100 ether); - -// 2. Finalize epoch rewards -bytes32 rewardsRoot = computeMonthlyRankings(); // Your backend -epochRewards.finalizeEpoch(rewardsRoot); - -// Players claim -// Player calls: epochRewards.claim(1, proof, amount); -``` - -### Month 2 (Repeat) - -- Deploy new tournament for March -- Start new epoch (same contract!) -- Configure new items -- Repeat - ---- - -## Your Token Treasury Management - -**Initial State:** -- You receive: 100,000,000 tokens (10% of 1B) -- Curve has: 900,000,000 tokens (90% of 1B) - -**Usage Over Time:** - -``` -Month 1: Fund epoch with 10M tokens -Remaining: 90M - -Month 2: Fund epoch with 8M tokens -Remaining: 82M - -Month 3: Fund epoch with 8M tokens -Remaining: 74M - -... and so on for 10+ months of rewards -``` - -**When Treasury Runs Low:** -- Buy tokens from DEX (supports your token price!) -- Adjust epoch funding amounts -- Rely more on tournaments (self-funded by entry fees) -- Community can contribute to reward pool - ---- - -## Front-End Integration Checklist - -### For Item Shop -```typescript -// Check if user can purchase -const [canBuy, reason] = await access.checkPurchaseEligibility(user, itemId, qty); -const cost = await access.getPurchaseCost(itemId, qty); -const remaining = await access.getRemainingSupply(itemId); - -if (canBuy) { - // Show "Buy for {cost} tokens ({remaining} left)" - await appToken.approve(access, cost); - await access.purchase(itemId, qty, ethers.id("shop_purchase")); -} -``` - -### For Feature Access -```typescript -const stake = await vault.stakedOf(user); -const hasGoldAccess = await access.checkFeatureAccess( - user, - ethers.id("gold_tier"), - stake -); - -if (hasGoldAccess) { - enablePremiumFeatures(); -} -``` - -### For Tournaments -```typescript -// Get tournament state -const [isFinalized, isActive, pool, entryFee, ...] = - await tournament.getTournamentState(); - -const [canEnter, reason] = await tournament.checkEntryEligibility(user); - -if (canEnter && isActive) { - await appToken.approve(tournament, entryFee); - await tournament.enter(); -} -``` - -### For Rewards -```typescript -const currentEpoch = await epochRewards.getCurrentEpochId(); -const isClaimable = await epochRewards.isEpochClaimable(currentEpoch); -const hasClaimed = await epochRewards.claimed(currentEpoch, user); - -if (isClaimable && !hasClaimed) { - const proof = await fetchMerkleProof(currentEpoch, user); - const amount = await fetchRewardAmount(currentEpoch, user); - await epochRewards.claim(currentEpoch, proof, amount); -} -``` - ---- - -## Summary of Changes from Original Design - -### What Changed -1. **Creator Treasury**: Now receive 10% of supply upfront -2. **Admin Control**: Creators get DEFAULT_ADMIN_ROLE -3. **Integrated Deployment**: EpochRewards included in module factory -4. **Tournament Factory**: Dedicated factory for easy tournament creation -5. **Lower Token Amounts**: More reasonable defaults (50, 5, 500 instead of 100, 10, 1000) - -### Why These Changes -1. **Creator Treasury**: Enables immediate epoch reward funding without buying from market -2. **Admin Control**: Full ownership and control of app economy -3. **Integrated Deployment**: One-click setup for complete utility suite -4. **Tournament Factory**: Practical for recurring events (weekly/monthly tournaments) -5. **Lower Amounts**: More accessible for users, better UX - -### Impact on Economics -- Bonding curve has 90% instead of 100% (slightly higher graduation price) -- Creator can fund rewards immediately (better UX) -- No breaking changes for users or external integrations -- Maintains all deflationary mechanics - ---- - -## Final Checklist - -Before mainnet: -- [ ] Test all flows on testnet -- [ ] Deploy factories (AppModuleFactory, TournamentFactory) -- [ ] Create your app via AppFactory -- [ ] Deploy modules via AppModuleFactory -- [ ] Configure items and gates -- [ ] Test tournament deployment -- [ ] Test epoch funding -- [ ] Verify all frontend integrations -- [ ] Document for your community - -Everything is now integrated, tested (315 tests passing), and ready for production use. - diff --git a/docs/CONTRIBUTING_DEV.md b/docs/CONTRIBUTING_DEV.md deleted file mode 100644 index c3ba636..0000000 --- a/docs/CONTRIBUTING_DEV.md +++ /dev/null @@ -1,285 +0,0 @@ -# Contributing to Elata Protocol - Developer Guide - -Thank you for your interest in contributing! This guide will help you set up your development environment and follow our best practices. - -## Getting Started - -### 1. Initial Setup - -```bash -# Clone the repository -git clone https://github.com/Elata-Biosciences/elata-protocol.git -cd elata-protocol - -# Install dependencies and setup hooks -make install - -# Or manually: -forge install -bash scripts/setup-hooks.sh -``` - -### 2. Development Workflow - -#### Quick Commands - -We provide a Makefile for common tasks: - -```bash -make help # Show all available commands -make build # Build contracts -make test # Run tests -make test-v # Run tests with verbose output -make fmt # Format code -make fmt-check # Check formatting -make coverage # Generate coverage report -make gas-report # Generate gas usage report -make ci # Run all CI checks locally -``` - -#### Before Committing - -The pre-commit hook will automatically: -1. Format your code with `forge fmt` -2. Build the contracts -3. Run the test suite - -If any step fails, the commit will be rejected. - -**To skip hooks (NOT RECOMMENDED):** -```bash -git commit --no-verify -``` - -#### Before Pushing - -The pre-push hook will run comprehensive checks: -1. Verify code formatting -2. Build with size checks -3. Run full test suite -4. Generate gas report -5. Run security checks - -### 3. Code Style Guide - -#### Solidity - -- Follow the official [Solidity Style Guide](https://docs.soliditylang.org/en/latest/style-guide.html) -- Use `forge fmt` for consistent formatting (runs automatically on commit) -- Maximum line length: 120 characters -- Use descriptive variable names -- Add NatSpec comments for all public/external functions - -Example: -```solidity -/** - * @notice Stakes tokens into the vault - * @param amount The amount of tokens to stake - * @return shares The amount of shares minted - */ -function stake(uint256 amount) external returns (uint256 shares) { - require(amount > 0, "Cannot stake zero"); - // Implementation... -} -``` - -#### Testing - -- Write comprehensive tests for all functionality -- Use descriptive test names: `test_FunctionName_Scenario_ExpectedOutcome` -- Group related tests with comments -- Include both positive and negative test cases -- Add fuzz tests for functions with numeric inputs - -Example: -```solidity -function test_stake_WithValidAmount_IncreasesBalance() public { - // Setup - uint256 stakeAmount = 100 ether; - - // Execute - vault.stake(stakeAmount); - - // Assert - assertEq(vault.balanceOf(user), stakeAmount); -} -``` - -### 4. Git Workflow - -#### Branch Naming - -- `feature/description` - New features -- `fix/description` - Bug fixes -- `refactor/description` - Code refactoring -- `docs/description` - Documentation updates -- `test/description` - Test additions/updates - -#### Commit Messages - -Follow [Conventional Commits](https://www.conventionalcommits.org/): - -``` -type(scope): description - -[optional body] - -[optional footer] -``` - -Types: -- `feat`: New feature -- `fix`: Bug fix -- `docs`: Documentation changes -- `style`: Formatting, missing semicolons, etc. -- `refactor`: Code restructuring -- `test`: Adding or updating tests -- `chore`: Maintenance tasks - -Examples: -```bash -feat(staking): add emergency withdrawal function -fix(vault): correct share calculation rounding error -docs(readme): update deployment instructions -test(governance): add fuzz tests for voting -``` - -#### Pull Request Process - -1. Create a feature branch from `develop` -2. Make your changes following the style guide -3. Ensure all tests pass (`make test`) -4. Run CI checks locally (`make ci`) -5. Push your branch and create a PR -6. Fill out the PR template completely -7. Wait for CI checks to pass -8. Request review from maintainers -9. Address review feedback -10. Maintainers will merge when approved - -### 5. Testing Best Practices - -#### Running Tests - -```bash -# Run all tests -make test - -# Run specific test file -forge test --match-path test/unit/ELTA.t.sol - -# Run specific test -forge test --match-test test_mint_IncreasesBalance - -# Run with verbose output -make test-v - -# Run with trace output -forge test -vvv - -# Run with gas reporting -make gas-report -``` - -#### Test Coverage - -Aim for >90% test coverage: - -```bash -# Generate coverage report -make coverage - -# View coverage in browser (requires lcov) -genhtml lcov.info --branch-coverage --output-dir coverage -open coverage/index.html -``` - -#### Security Testing - -Always run security tests before submitting: - -```bash -# Run security test suite -forge test --match-contract Security - -# Run security checks -make security-check -``` - -### 6. Common Issues and Solutions - -#### Issue: Tests fail on commit - -**Solution:** Run tests manually to see detailed output: -```bash -forge test -vv -``` - -#### Issue: Formatting check fails - -**Solution:** Format your code: -```bash -make fmt -git add -u -git commit --amend --no-edit -``` - -#### Issue: Contract size too large - -**Solution:** -- Extract complex view functions to a separate views contract -- Move logic to libraries -- Optimize storage layout -- Consider deploying to L2 - -#### Issue: Gas optimizations needed - -**Solution:** -```bash -# Compare gas usage -forge snapshot -# Make changes -forge snapshot --diff - -# Generate detailed gas report -make gas-report -``` - -### 7. CI/CD Pipeline - -Our CI/CD pipeline runs on every push and PR: - -1. **Formatting Check** - Verifies code is properly formatted -2. **Build** - Compiles all contracts -3. **Tests** - Runs full test suite -4. **Security Tests** - Runs security-focused tests -5. **Gas Report** - Generates gas usage report -6. **Coverage** - Uploads coverage to Codecov - -Make sure all checks pass before merging. - -### 8. Release Process - -1. All changes merged to `develop` branch -2. Create release PR from `develop` to `main` -3. Update version numbers and CHANGELOG -4. Run full audit checklist -5. Get approval from core team -6. Merge to `main` and tag release -7. Deploy to production - -### 9. Getting Help - -- 💬 Join our [Discord](https://discord.gg/elata) -- 📧 Email: dev@elata.bio -- 📖 Read the [full documentation](./docs/) -- 🐛 [Report bugs](https://github.com/Elata-Biosciences/elata-protocol/issues) - -## Code of Conduct - -Please be respectful and constructive in all interactions. We are building together! - -## License - -By contributing, you agree that your contributions will be licensed under the MIT License. - diff --git a/docs/DEPLOYMENT.md b/docs/DEPLOYMENT.md index 6a631a1..7336b3c 100644 --- a/docs/DEPLOYMENT.md +++ b/docs/DEPLOYMENT.md @@ -1,373 +1,301 @@ -# 🚀 Deployment Guide - -## 📋 **Deployment Flow Overview** - -```mermaid -graph TD - subgraph "Pre-deployment Phase" - P1[Environment Setup
🔧 Configure variables] - P2[Security Review
🛡️ Audit contracts] - P3[Test Validation
🧪 100% pass rate] - P4[Gas Estimation
⛽ Cost planning] - end - - subgraph "Deployment Phase" - D1[Testnet Deploy
🧪 Sepolia validation] - D2[Community Testing
👥 User validation] - D3[Final Review
📋 Last checks] - D4[Mainnet Deploy
🚀 Production launch] - end - - subgraph "Post-deployment Phase" - PD1[Verification
✅ Contract validation] - PD2[Configuration
⚙️ Role setup] - PD3[Monitoring
📊 System health] - PD4[Community Launch
🎉 Go live] - end - - P1 --> P2 --> P3 --> P4 - P4 --> D1 --> D2 --> D3 --> D4 - D4 --> PD1 --> PD2 --> PD3 --> PD4 - - style P3 fill:#e8f5e8 - style D4 fill:#fff3e0 - style PD4 fill:#e3f2fd -``` +# Deployment Guide + +This guide covers deploying Elata Protocol contracts to testnets and mainnet. + +## Overview + +The deployment process: + +1. Configure environment variables +2. Fund the deployer wallet +3. Run the deployment script +4. Verify contracts on block explorer +5. Transfer admin roles to multisig +6. Update frontend configuration + +## Prerequisites + +- Foundry installed (`forge`, `cast`) +- Node.js v18+ +- Deployer wallet with sufficient ETH +- Admin multisig address (Gnosis Safe recommended) +- RPC endpoint (Alchemy, Infura, or public) +- Block explorer API key + +## Supported Networks + +| Network | Chain ID | Cost Estimate | Notes | +|---------|----------|---------------|-------| +| Ethereum Mainnet | 1 | ~$260 at 20 gwei | Production | +| Base Mainnet | 8453 | ~$2-5 | L2, lower costs | +| Sepolia | 11155111 | Free | Ethereum testnet | +| Base Sepolia | 84532 | Free | Base testnet | + +## Testnet Deployment (Sepolia) + +### Step 1: Create Environment File + +Create `.env.sepolia` in the repository root: -## 🔧 **Environment Configuration** - -### Network Setup Matrix - -```mermaid -graph TD - subgraph "Ethereum Mainnet" - EM1[Chain ID: 1] - EM2[Gas Price: 15-30 gwei] - EM3[Deploy Cost: ~$260] - EM4[Security: Highest] - end - - subgraph "Base Mainnet" - BM1[Chain ID: 8453] - BM2[Gas Price: 0.01-0.1 gwei] - BM3[Deploy Cost: ~$2.60] - BM4[Security: High] - end - - subgraph "Sepolia Testnet" - ST1[Chain ID: 11155111] - ST2[Gas Price: Free] - ST3[Deploy Cost: $0] - ST4[Security: Testing only] - end - - subgraph "Base Sepolia" - BS1[Chain ID: 84532] - BS2[Gas Price: Free] - BS3[Deploy Cost: $0] - BS4[Security: Testing only] - end - - style EM1 fill:#ff9999 - style BM1 fill:#99ccff - style ST1 fill:#99ff99 - style BS1 fill:#ffcc99 +```bash +# Network +SEPOLIA_RPC_URL=https://eth-sepolia.g.alchemy.com/v2/YOUR_KEY +ETHERSCAN_API_KEY=YOUR_ETHERSCAN_KEY + +# Deployer +DEPLOYER_PRIVATE_KEY=0xYOUR_PRIVATE_KEY + +# Protocol Configuration +ADMIN_MSIG=0xYourGnosisSafeAddress +INITIAL_TREASURY=0xYourTreasuryAddress + +# Optional: Leave empty to deploy mock router +UNISWAP_V2_ROUTER= ``` -### Deployment Prerequisites - -```mermaid -graph LR - subgraph "Required Tools" - RT1[Foundry
Latest version] - RT2[Git
Version control] - RT3[Node.js
v18+ for scripts] - end - - subgraph "Required Accounts" - RA1[Deployer Wallet
Sufficient ETH] - RA2[Admin Multisig
Gnosis Safe] - RA3[Treasury Wallet
Token recipient] - end - - subgraph "Required Keys" - RK1[RPC Endpoints
Infura/Alchemy] - RK2[API Keys
Etherscan/Basescan] - RK3[Private Keys
Secure storage] - end - - RT1 --> RA1 - RT2 --> RA2 - RT3 --> RA3 - - RA1 --> RK1 - RA2 --> RK2 - RA3 --> RK3 - - style RA2 fill:#fff3e0 - style RK3 fill:#ffebee +Never commit this file. It's already in `.gitignore`. + +### Step 2: Fund Deployer + +Get Sepolia ETH from a faucet: +- https://sepoliafaucet.com/ +- https://www.alchemy.com/faucets/ethereum-sepolia + +You'll need about 0.5 ETH for deployment and verification. + +### Step 3: Deploy + +```bash +npm run deploy:sepolia ``` -## 📦 **Deployment Process** - -### Contract Deployment Sequence - -```mermaid -sequenceDiagram - participant Deployer - participant ELTA - participant ElataXP - participant VeELTA - participant LotPool - participant RewardsDistributor - participant ElataGovernor - participant Verification - - Note over Deployer, Verification: Phase 1: Core Contracts - Deployer->>ELTA: Deploy with initial mint - ELTA-->>Deployer: Contract address - - Deployer->>ElataXP: Deploy with admin - ElataXP-->>Deployer: Contract address - - Deployer->>VeELTA: Deploy with ELTA reference - VeELTA-->>Deployer: Contract address - - Note over Deployer, Verification: Phase 2: Governance - Deployer->>LotPool: Deploy with ELTA + XP - LotPool-->>Deployer: Contract address - - Deployer->>RewardsDistributor: Deploy with VeELTA - RewardsDistributor-->>Deployer: Contract address - - Deployer->>ElataGovernor: Deploy with ELTA - ElataGovernor-->>Deployer: Contract address - - Note over Deployer, Verification: Phase 3: Configuration - Deployer->>RewardsDistributor: addRewardToken(ELTA) - Deployer->>ElataXP: grantRole(XP_MINTER, LotPool) - - Note over Deployer, Verification: Phase 4: Verification - Deployer->>Verification: Run verification script - Verification-->>Deployer: All contracts verified ✅ +Or with the script directly: + +```bash +bash scripts/deploy-sepolia.sh --private-key ``` -### Gas Cost Estimation - -```mermaid -graph TD - subgraph "Deployment Costs by Network" - direction TB - - ETH[Ethereum Mainnet
13M gas × 20 gwei = $260] - BASE[Base Mainnet
13M gas × 0.05 gwei = $1.30] - SEPOLIA[Sepolia Testnet
13M gas × 0 gwei = FREE] - end - - subgraph "Cost Breakdown" - direction TB - - C1[ELTA: 2.3M gas (18%)] - C2[VeELTA: 3.3M gas (25%)] - C3[ElataXP: 3.0M gas (23%)] - C4[Others: 4.4M gas (34%)] - end - - style ETH fill:#ff9999 - style BASE fill:#99ccff - style SEPOLIA fill:#99ff99 +The script will: +- Compile contracts +- Deploy in the correct order +- Set up role permissions +- Mint initial ELTA to treasury +- Output addresses to `deployments/sepolia.json` + +### Step 4: Verify Contracts + +Verification usually happens automatically during deployment. If it fails: + +```bash +forge verify-contract
src/token/ELTA.sol:ELTA \ + --chain sepolia \ + --etherscan-api-key $ETHERSCAN_API_KEY \ + --constructor-args $(cast abi-encode "constructor(string,string,address,address,uint256,uint256)" "ELTA" "ELTA" "0x..." "0x..." 10000000000000000000000000 77000000000000000000000000) ``` -## ✅ **Verification Procedures** - -### Post-Deployment Verification - -```mermaid -graph TD - subgraph "Contract Verification" - CV1[Source Code
Block explorer verification] - CV2[ABI Matching
Interface consistency] - CV3[Bytecode Hash
Compilation verification] - end - - subgraph "Functional Verification" - FV1[Basic Operations
Token transfers work] - FV2[Access Control
Roles properly set] - FV3[Integration
Cross-contract calls] - FV4[Security
Protection mechanisms active] - end - - subgraph "Configuration Verification" - CFV1[Admin Roles
Multisig control] - CFV2[Initial State
Correct parameters] - CFV3[Token Supply
Expected amounts] - CFV4[Permissions
Proper role grants] - end - - CV1 --> FV1 - CV2 --> FV2 - CV3 --> FV3 - - FV1 --> CFV1 - FV2 --> CFV2 - FV3 --> CFV3 - FV4 --> CFV4 - - style CFV1 fill:#e8f5e8 - style CFV4 fill:#fff3e0 +### Step 5: Verify Deployment + +Run the verification script: + +```bash +bash scripts/verify-sepolia.sh ``` -### Verification Commands +Or manually check: ```bash -# Contract verification -cast call $ELTA_ADDRESS "name()" --rpc-url $RPC_URL -cast call $ELTA_ADDRESS "totalSupply()" --rpc-url $RPC_URL -cast call $ELTA_ADDRESS "MAX_SUPPLY()" --rpc-url $RPC_URL +# Token deployed correctly +cast call $ELTA_ADDRESS "name()" --rpc-url $SEPOLIA_RPC_URL +cast call $ELTA_ADDRESS "totalSupply()" --rpc-url $SEPOLIA_RPC_URL -# Access control verification +# Admin has correct roles cast call $ELTA_ADDRESS "hasRole(bytes32,address)" \ 0x0000000000000000000000000000000000000000000000000000000000000000 \ - $ADMIN_MSIG --rpc-url $RPC_URL + $ADMIN_MSIG --rpc-url $SEPOLIA_RPC_URL -# Integration verification -cast call $VEELTA_ADDRESS "ELTA()" --rpc-url $RPC_URL -cast call $LOTPOOL_ADDRESS "XP()" --rpc-url $RPC_URL +# Contracts are linked correctly +cast call $VEELTA_ADDRESS "ELTA()" --rpc-url $SEPOLIA_RPC_URL ``` -## 🚨 **Emergency Procedures** - -### Incident Response Flow - -```mermaid -graph TD - subgraph "Detection" - D1[Monitoring Alert] - D2[Community Report] - D3[Security Scan] - end - - subgraph "Assessment" - A1[Severity Analysis
Critical/High/Medium/Low] - A2[Impact Assessment
User funds/Protocol function] - A3[Response Planning
Immediate/Planned/Monitoring] - end - - subgraph "Response Actions" - R1[Emergency Pause
If available] - R2[Governance Proposal
Protocol changes] - R3[Community Communication
Transparency] - R4[Fix Development
Code changes] - end - - subgraph "Resolution" - RES1[Fix Deployment
New contracts if needed] - RES2[Migration Plan
User fund safety] - RES3[Post-mortem
Lessons learned] - end - - D1 --> A1 - D2 --> A1 - D3 --> A1 - - A1 --> R1 - A2 --> R2 - A3 --> R3 - - R1 --> RES1 - R2 --> RES2 - R3 --> RES3 - - style A1 fill:#ffebee - style R1 fill:#fff3e0 - style RES1 fill:#e8f5e8 +## Base Sepolia Deployment + +Base Sepolia deployment works the same way, with a few differences. + +### Environment File + +Create `.env.base-sepolia`: + +```bash +BASE_SEPOLIA_RPC_URL=https://sepolia.base.org +BASESCAN_API_KEY=YOUR_BASESCAN_KEY +DEPLOYER_PRIVATE_KEY=0xYOUR_PRIVATE_KEY +ADMIN_MSIG=0xYourGnosisSafeAddress +INITIAL_TREASURY=0xYourTreasuryAddress +UNISWAP_V2_ROUTER= ``` -### Emergency Contact Tree - -```mermaid -graph TD - INCIDENT[Security Incident Detected] - - subgraph "Immediate Response (0-1 hours)" - IR1[Technical Lead
Initial assessment] - IR2[Security Team
Threat analysis] - IR3[Multisig Signers
Emergency actions] - end - - subgraph "Extended Response (1-24 hours)" - ER1[Core Team
Solution development] - ER2[Legal Counsel
Compliance review] - ER3[Communications
Community updates] - end - - subgraph "Recovery Phase (24+ hours)" - RP1[External Auditors
Independent review] - RP2[Community DAO
Governance decisions] - RP3[Ecosystem Partners
Coordination] - end - - INCIDENT --> IR1 - INCIDENT --> IR2 - INCIDENT --> IR3 - - IR1 --> ER1 - IR2 --> ER2 - IR3 --> ER3 - - ER1 --> RP1 - ER2 --> RP2 - ER3 --> RP3 - - style INCIDENT fill:#ffcdd2 - style IR1 fill:#fff3e0 - style ER1 fill:#e8f5e8 - style RP1 fill:#e3f2fd +### Get Test ETH + +Fund from the Base faucet: https://www.coinbase.com/faucets/base-ethereum-sepolia-faucet + +### Deploy + +```bash +npm run deploy:base-sepolia ``` -## 📊 **Monitoring & Analytics** - -### Key Performance Indicators - -```mermaid -graph TD - subgraph "Protocol Health" - PH1[Total Value Locked
📈 Growth metric] - PH2[Active Users
👥 Engagement] - PH3[Transaction Volume
💱 Usage] - PH4[Governance Participation
🗳️ Decentralization] - end - - subgraph "Economic Metrics" - EM1[Token Price
💰 Market value] - EM2[Staking Ratio
🔒 Supply locked] - EM3[XP Distribution
🏅 Participation] - EM4[Funding Efficiency
💧 Capital allocation] - end - - subgraph "Security Metrics" - SM1[Failed Transactions
🚨 Error rate] - SM2[Unusual Patterns
🔍 Anomaly detection] - SM3[Emergency Usage
⚠️ Crisis indicators] - SM4[Access Control Events
🔐 Permission changes] - end - - PH1 --> EM1 - PH2 --> EM2 - PH3 --> EM3 - PH4 --> EM4 - - EM1 --> SM1 - EM2 --> SM2 - EM3 --> SM3 - EM4 --> SM4 - - style PH1 fill:#e8f5e8 - style EM1 fill:#fff3e0 - style SM1 fill:#ffebee +### Contract Size Note + +AppModuleFactory exceeds the 24KB EIP-170 limit on L1 Ethereum. On Base (and other L2s), this limit doesn't apply, so all contracts deploy successfully. If deploying to Ethereum mainnet, you may need to optimize or split this contract. + +## Ledger Deployment + +For production deployments, use a hardware wallet instead of a private key. + +### Setup + +1. Connect Ledger device +2. Open Ethereum app +3. Enable "Blind signing" in Settings + +### Deploy + +```bash +bash scripts/deploy-sepolia.sh --ledger + +# Or with specific address +bash scripts/deploy-sepolia.sh --ledger --ledger-address 0xYourLedgerAddress ``` ---- +You'll approve each transaction on the device. + +## Post-Deployment Checklist + +After deploying, verify: + +- [ ] All contracts deployed and verified on block explorer +- [ ] Initial ELTA supply minted to treasury +- [ ] Admin roles assigned to multisig +- [ ] Deployer wallet has no remaining admin roles +- [ ] Timelock configured with correct delays +- [ ] Governor has proposer/executor roles on Timelock +- [ ] No ELTA stuck in deployer wallet + +### Configure Timelock Permissions + +The Governor needs roles on the Timelock to execute proposals: + +```bash +# Grant PROPOSER_ROLE to Governor +cast send $TIMELOCK_ADDRESS \ + "grantRole(bytes32,address)" \ + 0xb09aa5aeb3702cfd50b6b62bc4532604938f21248a27a1d5ca736082b6819cc1 \ + $GOVERNOR_ADDRESS \ + --rpc-url $RPC_URL + +# Grant EXECUTOR_ROLE to Governor +cast send $TIMELOCK_ADDRESS \ + "grantRole(bytes32,address)" \ + 0xfd643c72710c63c0180259aba6b2d05451e3591a24e58b62239378085726f783 \ + $GOVERNOR_ADDRESS \ + --rpc-url $RPC_URL +``` + +These should be executed from the multisig via Gnosis Safe. + +## Updating Frontend + +After deployment, update the App Store environment variables. + +For Vercel (production): +1. Go to elata-appstore project → Settings → Environment Variables +2. Add variables for the new network: + +``` +NEXT_PUBLIC_ELTA_ADDRESS_BASE_SEPOLIA=0x... +NEXT_PUBLIC_APP_FACTORY_ADDRESS_BASE_SEPOLIA=0x... +NEXT_PUBLIC_VE_ELTA_ADDRESS_BASE_SEPOLIA=0x... +NEXT_PUBLIC_ELATA_XP_ADDRESS_BASE_SEPOLIA=0x... +NEXT_PUBLIC_REWARDS_DISTRIBUTOR_ADDRESS_BASE_SEPOLIA=0x... +``` + +For local development, the deploy script generates these automatically. + +## Mainnet Deployment + +Mainnet deployment follows the same process with additional precautions: + +1. **Audit first** — Get an external security audit before mainnet +2. **Test thoroughly** — Run full E2E tests on testnet +3. **Use multisig** — Deploy from a secure multisig, not a hot wallet +4. **Double-check parameters** — Review all constructor arguments +5. **Monitor after deployment** — Watch for unusual activity -*Complete deployment guide with visual workflows for professional protocol deployment.* +### Cost Estimation +At 20 gwei on Ethereum mainnet: + +| Contract | Gas | Cost | +|----------|-----|------| +| ELTA | 2.3M | ~$46 | +| VeELTA | 3.0M | ~$60 | +| ElataXP | 1.8M | ~$36 | +| LotPool | 1.1M | ~$22 | +| AppFactory | 2.9M | ~$58 | +| Other contracts | ~4M | ~$80 | +| **Total** | ~15M | ~$300 | + +On Base mainnet, expect costs 50-100x lower. + +## Troubleshooting + +### Deployment fails with "insufficient funds" + +Fund the deployer wallet with more ETH. Mainnet deployments need ~0.5 ETH buffer. + +### Verification fails + +Wait 30 seconds after deployment, then retry. If it still fails: +- Check API key is valid +- Verify constructor arguments match exactly +- Try manual verification on the block explorer + +### Transaction stuck + +If a transaction is pending too long: + +```bash +# Send a replacement with higher gas +cast send --nonce --gas-price ... +``` + +### "Contract too large" error + +This happens on L1 for AppModuleFactory. Options: +- Deploy on L2 instead (Base, Arbitrum, Optimism) +- Increase optimizer runs (makes deployment cheaper but execution more expensive) +- Split into smaller contracts + +## Security Notes + +1. **Never commit private keys** — Use `.env` files that are gitignored +2. **Use dedicated deployer wallet** — Don't use your main wallet +3. **Transfer admin immediately** — Move admin roles to multisig right after deployment +4. **Delete private key from env** — Remove `DEPLOYER_PRIVATE_KEY` after deployment +5. **Verify all transactions** — Double-check addresses before signing + +## Deployment Artifacts + +After deployment, find artifacts in: + +``` +deployments/ +├── sepolia.json # Sepolia addresses +├── base-sepolia.json # Base Sepolia addresses +└── mainnet.json # Mainnet addresses + +broadcast/ +└── Deploy.sol/ + └── / + └── run-latest.json # Foundry broadcast log +``` diff --git a/docs/LOCAL_DEVELOPMENT.md b/docs/LOCAL_DEVELOPMENT.md index 2e91d6e..6ddefb7 100644 --- a/docs/LOCAL_DEVELOPMENT.md +++ b/docs/LOCAL_DEVELOPMENT.md @@ -1,601 +1,313 @@ # Local Development Guide -**Complete guide to running Elata Protocol locally with a mock blockchain** +This guide covers the complete local development environment for the Elata Protocol. Use this when you need more control than the [QUICKSTART](../QUICKSTART.md) provides, or when troubleshooting issues. -This guide will help you set up a full local development environment with all smart contracts deployed and seeded with test data. Perfect for frontend development and testing before deploying to testnets. +## Prerequisites ---- +Before starting, install: -## Quick Start - -### Prerequisites - -1. **Foundry** (Forge, Anvil, Cast) +1. **Foundry** (forge, anvil, cast) ```bash curl -L https://foundry.paradigm.xyz | bash foundryup ``` -2. **Node.js** (v18+) +2. **Node.js** v18 or later ```bash - # Check version - node --version + node --version # Should be 18+ ``` -3. **Git** -4. **Docker Desktop** (for App Store database via docker compose) +3. **Docker Desktop** (required for App Store database) ```bash docker --version docker compose version ``` - - Ensure Docker Desktop is running before starting the App Store (`npm run local:full`). + Make sure Docker Desktop is running before starting the App Store. - ```bash - git --version - ``` +4. **Git** + +## Starting the Environment -### One-Command Setup (Recommended) +### Recommended: One Command ```bash bash scripts/dev-local.sh ``` -This single command will: -- Start Anvil (local blockchain) -- Deploy ALL Elata Protocol contracts -- Seed test data (apps, XP, staking positions, funding rounds) -- Generate appstore configuration (.env.local) -- Set up test accounts with ELTA tokens - -**That's it!** Your local blockchain is ready for development. - ---- - -## 📋 Available Commands - -### Primary Commands - -| Command | Description | -|---------|-------------| -| `bash scripts/dev-local.sh` | Complete setup (start Anvil + deploy + seed) | -| `npm run dev:stop` | Stop Anvil blockchain | -| `npm run dev:restart` | Stop and restart everything | -| `cd ../elata-appstore && npm run local:full` | Start the App Store frontend | - -### Manual Commands (for fine-grained control) - -| Command | Description | -|---------|-------------| -| `npm run dev:anvil` | Start Anvil only | -| `npm run dev:deploy` | Deploy contracts only | -| `npm run dev:seed` | Seed test data only | -| `npm run dev:config` | Generate appstore .env.local only | - -### Testing Commands - -| Command | Description | -|---------|-------------| -| `npm test` | Run all tests | -| `npm run test:gas` | Run tests with gas report | -| `npm run test:coverage` | Generate coverage report | - ---- - -## 🏗️ What Gets Deployed +This script: +- Starts Anvil on port 8545 +- Deploys all protocol contracts +- Seeds test data (users, XP, apps, funding rounds) +- Generates the App Store's `.env.local` configuration +- Funds test accounts with ELTA -### Core Protocol Contracts +### Alternative: npm Command -- **ELTA Token** - Governance & utility token (77M cap) -- **ElataXP** - Experience points (soulbound) -- **VeELTA** - Vote-escrowed staking -- **LotPool** - XP-weighted funding rounds -- **RewardsDistributor** - Staker rewards -- **ElataGovernor** - On-chain governance -- **ElataTimelock** - Governance timelock - -### App Ecosystem Contracts - -- **AppFactory** - Token launcher with bonding curves -- **AppModuleFactory** - Utility module deployer -- **TournamentFactory** - Tournament infrastructure +```bash +npm run local:up +``` -### Mock Contracts (for local testing) +Same result, different entry point. -- **MockUniswapV2Factory** - DEX factory -- **MockUniswapV2Router** - DEX router +### Manual Steps ---- +If you need fine-grained control: -## 🌱 Seed Data +```bash +# Terminal 1: Start blockchain +npm run dev:anvil -The seed script automatically creates: +# Terminal 2: Deploy contracts +npm run dev:deploy -### Test Users with XP +# Terminal 3: Seed test data +npm run dev:seed -| Account | XP Amount | Description | -|---------|-----------|-------------| -| Account #1 | 5,000 XP | Power user | -| Account #2 | 3,000 XP | Active user | -| Account #3 | 1,500 XP | Regular user | -| Account #4 | 800 XP | Casual user | -| Account #5 | 300 XP | New user | +# Terminal 4: Generate frontend config +npm run dev:config +``` -### Staking Positions +## Running the App Store -- Position 1: 10,000 ELTA locked for 2 years -- Position 2: 5,000 ELTA locked for 1 year -- Position 3: 2,500 ELTA locked for 6 months +In a separate terminal: -### Test Apps (fully configured) +```bash +cd ../elata-appstore +npm run local:full +``` -1. **NeuroPong Token (NPONG)** - - EEG-controlled Pong game - - 3 item tiers (Basic, Premium, Legendary) - - Feature gating configured +This starts: +- Next.js dev server on port 3000 or 3001 +- PostgreSQL via Docker Compose +- Prisma database sync -2. **MindfulBreath Token (BREATH)** - - Meditation with EEG feedback - - Full economy with items and staking +The frontend reads contract addresses from the generated `.env.local` file. -3. **FocusTrainer Token (FOCUS)** - - Attention training - - Tournament-ready configuration +## Test Accounts -### Funding Round +Anvil provides 10 pre-funded accounts. The first six are configured with ELTA and XP: -- Active 7-day funding round with 3 options: - - PTSD Research - - Depression Study - - Focus Enhancement -- 10,000 ELTA in funding pool +| Account | Address | ELTA Balance | XP | +|---------|---------|--------------|-----| +| 0 (Deployer) | `0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266` | 10M | - | +| 1 | `0x70997970C51812dc3A010C7d01b50e0d17dc79C8` | 100k | 5,000 | +| 2 | `0x3C44CdDdB6a900fa2b585dd299e03d12FA4293BC` | 100k | 3,000 | +| 3 | `0x90F79bf6EB2c4f870365E785982E1f101E93b906` | 100k | 1,500 | +| 4 | `0x15d34AAf54267DB7D7c367839AAf71A00a2C6A65` | 100k | 800 | +| 5 | `0x9965507D1a55bcC2695C58ba16FB37d819B0A4dc` | 100k | 300 | ---- +Each account has 10,000 ETH for gas. -## Test Accounts & Keys +**Private keys** (Anvil defaults—never use on real networks): -All accounts are pre-funded with **100,000 ELTA** for testing. +``` +Account 0: 0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80 +Account 1: 0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d +Account 2: 0x5de4111afa1a4b94908f83103eb1f1706367c2e68ca870fc3fb9a804cdab365a +Account 3: 0x7c852118294e51e653712a81e05800f419141751be58f605c371e15141b007a6 +Account 4: 0x47e179ec197488593b187f80a00eb0da91f1b9d0b13f8733639f19c30a34926a +Account 5: 0x8b3a350cf5c34c9194ca85829a2df0ec3153be0318b5e2d3348e872092edffba +``` -### Anvil Default Accounts +## Seeded Test Data -| # | Address | Private Key | Balance | -|---|---------|-------------|---------| -| 0 | `0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266` | `0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80` | 10M ELTA + 10K ETH | -| 1 | `0x70997970C51812dc3A010C7d01b50e0d17dc79C8` | `0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d` | 100K ELTA + 10K ETH | -| 2 | `0x3C44CdDdB6a900fa2b585dd299e03d12FA4293BC` | `0x5de4111afa1a4b94908f83103eb1f1706367c2e68ca870fc3fb9a804cdab365a` | 100K ELTA + 10K ETH | -| 3 | `0x90F79bf6EB2c4f870365E785982E1f101E93b906` | `0x7c852118294e51e653712a81e05800f419141751be58f605c371e15141b007a6` | 100K ELTA + 10K ETH | -| 4 | `0x15d34AAf54267DB7D7c367839AAf71A00a2C6A65` | `0x47e179ec197488593b187f80a00eb0da91f1b9d0b13f8733639f19c30a34926a` | 100K ELTA + 10K ETH | -| 5 | `0x9965507D1a55bcC2695C58ba16FB37d819B0A4dc` | `0x8b3a350cf5c34c9194ca85829a2df0ec3153be0318b5e2d3348e872092edffba` | 100K ELTA + 10K ETH | +The seed script creates: -> **Warning**: These are Anvil's default test keys. Never use them on real networks! +**Staking Positions** +- 10,000 ELTA locked for 2 years +- 5,000 ELTA locked for 1 year +- 2,500 ELTA locked for 6 months ---- +**Sample Apps** +1. NeuroPong (NPONG) — EEG-controlled game with item tiers +2. MindfulBreath (BREATH) — Meditation app with staking +3. FocusTrainer (FOCUS) — Attention training with tournaments -## Network Configuration +**Funding Round** +- 7-day active round +- 10,000 ELTA in the pool +- Three proposals: PTSD Research, Depression Study, Focus Enhancement -### Local Blockchain (Anvil) +## Network Configuration -- **RPC URL**: `http://127.0.0.1:8545` -- **Chain ID**: `31337` -- **Block Time**: Instant (auto-mining) -- **Gas Limit**: Unlimited +| Setting | Value | +|---------|-------| +| RPC URL | `http://127.0.0.1:8545` | +| Chain ID | `31337` | +| Block Time | Instant (auto-mine) | ### MetaMask Setup -1. Open MetaMask -2. Add Network → Add Network Manually -3. Enter details: - - **Network Name**: Anvil Local - - **RPC URL**: `http://127.0.0.1:8545` - - **Chain ID**: `31337` - - **Currency Symbol**: `ETH` -4. Import one of the test private keys above +1. Open MetaMask → Settings → Networks → Add Network +2. Enter: + - Network Name: `Anvil Local` + - RPC URL: `http://127.0.0.1:8545` + - Chain ID: `31337` + - Currency Symbol: `ETH` +3. Import a test account using one of the private keys above ---- +## Generated Files -## Generated Files - -After running `npm run dev`, you'll find: +After running `dev-local.sh`, you'll have: ``` elata-protocol/ -├── deployments/ -│ └── local.json # All contract addresses -├── elata-appstore/ -│ └── .env.local # Environment variables for local addresses -├── anvil.log # Anvil blockchain logs -└── .anvil.pid # Anvil process ID +├── deployments/local.json # Contract addresses +├── anvil.log # Blockchain logs +└── .anvil.pid # Process ID + +elata-appstore/ +└── .env.local # Frontend configuration ``` -### `deployments/local.json` +**deployments/local.json** contains all contract addresses: ```json { "network": "localhost", "chainId": 31337, - "deployer": "0xf39Fd...", "contracts": { "ELTA": "0x5FbDB2315678afecb367f032d93F642f64180aa3", "ElataXP": "0xe7f1725E7734CE288F8367e1Bb143E90bb3F0512", - // ... all contract addresses - }, - "testAccounts": [...] + "VeELTA": "0x...", + ... + } } ``` -### `elata-appstore/.env.local` - -Auto-generated environment variables for appstore: - -```env -NEXT_PUBLIC_CHAIN_ID=31337 -NEXT_PUBLIC_RPC_URL=http://127.0.0.1:8545 -NEXT_PUBLIC_ELTA_ADDRESS_LOCAL=0x5FbDB... -# ... all contract addresses -``` - -The appstore reads contract addresses from these env vars and ABIs from src/abi. +## Common Commands ---- +| Command | Description | +|---------|-------------| +| `npm run local:up` | Start everything | +| `npm run local:down` | Stop Anvil | +| `npm run local:restart` | Stop and restart | +| `npm run faucet ` | Send 10k ELTA to address | +| `forge test` | Run contract tests | +| `forge test -vvv` | Tests with verbose output | +| `make gas-report` | Generate gas usage report | -## 🛠️ Development Workflows +## Interacting with Contracts -### Standard Development Flow +Use `cast` (part of Foundry) to call contracts directly: ```bash -# 1. Start local blockchain with everything -bash scripts/dev-local.sh - -# 2. In another terminal, start the App Store frontend -cd ../elata-appstore -npm run local:full +# Check ELTA balance +cast call 0x5FbDB2315678afecb367f032d93F642f64180aa3 \ + "balanceOf(address)" 0x70997970C51812dc3A010C7d01b50e0d17dc79C8 \ + --rpc-url http://127.0.0.1:8545 -# 3. Open http://localhost:3000 -# Your app is now connected to local blockchain! +# Get current block number +cast block-number --rpc-url http://127.0.0.1:8545 -# 4. When done, stop Anvil -npm run dev:stop +# Send a transaction +cast send 0x... "someFunction(uint256)" 100 \ + --private-key 0xac0974... \ + --rpc-url http://127.0.0.1:8545 ``` -### Testing Contract Changes - -```bash -# 1. Make changes to contracts in src/ - -# 2. Restart everything -npm run dev:restart +## Troubleshooting -# 3. Frontend automatically connects to new contracts -``` +### Anvil won't start -### Manual Workflow (for debugging) +Port 8545 is probably in use. Kill existing processes: ```bash -# Terminal 1: Start Anvil -npm run dev:anvil - -# Terminal 2: Deploy contracts -npm run dev:deploy - -# Terminal 3: Seed data -npm run dev:seed - -# Terminal 4: Generate config -npm run dev:config - -# Terminal 5: Start the App Store frontend -cd ../elata-appstore && npm run local:full +lsof -i :8545 # Find process +kill -9 # Kill it +npm run local:up # Restart ``` ---- - -## Viewing Blockchain State - -### Using Cast (Foundry CLI) +Or use the stop script: ```bash -# Check ELTA balance -cast call $ELTA_ADDRESS "balanceOf(address)" 0x70997970C51812dc3A010C7d01b50e0d17dc79C8 --rpc-url http://127.0.0.1:8545 - -# Check XP balance -cast call $XP_ADDRESS "balanceOf(address)" 0x70997970C51812dc3A010C7d01b50e0d17dc79C8 --rpc-url http://127.0.0.1:8545 - -# Get app info -cast call $APP_FACTORY_ADDRESS "apps(uint256)" 1 --rpc-url http://127.0.0.1:8545 - -# Current block number -cast block-number --rpc-url http://127.0.0.1:8545 +npm run local:down +npm run local:up ``` -### Using Console Logs +### Deployment hangs on "Waiting for pending transactions" -Watch Anvil logs in real-time: +Clear the broadcast cache and restart: ```bash -tail -f anvil.log +rm -rf broadcast/Deploy.sol/31337 +rm -rf broadcast/SeedLocalData.s.sol/31337 +npm run local:restart ``` ---- - -## 🧪 Testing Against Local Blockchain - -### Running Frontend Tests - -Run tests from the `elata-appstore` repository. - -### End-to-End Testing +### MetaMask shows "nonce too high" errors -```bash -# Start local environment -bash scripts/dev-local.sh +Anvil restarted but MetaMask cached the old state. Clear it: -# Run E2E tests (in another terminal) from appstore -cd ../elata-appstore -npm run test:e2e -``` +MetaMask → Settings → Advanced → Clear activity tab data ---- +Then hard-refresh the browser (Cmd+Shift+R or Ctrl+Shift+R). -## Troubleshooting +### Frontend can't find contracts -### Problem: Anvil won't start (port already in use) +Regenerate the configuration: ```bash -# Check what's using port 8545 -lsof -i :8545 - -# Kill the process -kill -9 - -# Or use our stop script -npm run dev:stop +npm run config:appstore ``` -### Problem: Contracts hang "Waiting for pending transactions" - -This happens if an old Anvil instance or stale broadcast cache confuses receipt polling. +Then restart the App Store: ```bash -# Clean restart -npm run dev:stop -bash scripts/dev-local.sh - -# If it persists, clear broadcast cache (safe): -rm -rf broadcast/Deploy.sol/31337 broadcast/SeedLocalData.s.sol/31337 -bash scripts/dev-local.sh +cd ../elata-appstore +npm run local:full ``` -### Problem: Contracts not deploying - -```bash -# Check Anvil is running -curl -X POST --data '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}' http://127.0.0.1:8545 - -# If Anvil is running but deployment fails, try: -npm run dev:restart -``` +### Contracts compile but deployment fails -### Problem: Frontend can't connect +Clean build artifacts and retry: ```bash -# 1. Verify appstore .env.local exists -ls -la ../elata-appstore/.env.local - -# 2. Regenerate config -npm run dev:config - -# 3. Restart appstore frontend -cd ../elata-appstore && npm run local:full +forge clean +npm run local:up ``` -### Problem: "Nonce too high" errors +### Need more ETH for gas -This happens when Anvil restarts but frontend still has old state. +Send ETH from the deployer account: ```bash -# Solution 1: Hard refresh browser (Cmd+Shift+R) -# Solution 2: Clear MetaMask activity -# Settings → Advanced → Clear activity tab data - -# Solution 3: Restart everything -npm run dev:restart +cast send --value 10ether \ + --private-key 0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80 \ + --rpc-url http://127.0.0.1:8545 ``` -### Problem: Test accounts have no ELTA +## Testing Contract Changes -The seed script should fund accounts automatically. If they're empty: +When you modify contracts: ```bash -# Manually run seed script +# Quick rebuild and redeploy (keeps Anvil running) +forge build +npm run dev:deploy npm run dev:seed -``` - -### Problem: I need ETH for gas on local network - -```bash -# Send 10 ETH from Anvil account #0 to your address -npm run faucet:eth 0xYourAddress 10 +npm run dev:config -# Verify -cast balance 0xYourAddress --rpc-url http://127.0.0.1:8545 +# Or restart everything +npm run local:restart ``` ---- - -## Performance & Optimization +The frontend will pick up new contract addresses automatically on page refresh. -### Fast Iteration +## State Persistence -Changes to contracts require redeployment: +By default, Anvil state resets when stopped. To persist state across restarts: ```bash -# Quick redeploy (keeps Anvil running) -npm run dev:deploy && npm run dev:seed && npm run dev:config -``` - -### State Persistence - -By default, Anvil state is ephemeral (resets on restart). To persist: - -```bash -# Start Anvil with state file +# Start with state saving anvil --state-interval 1 --dump-state anvil-state.json -# Load previous state +# Later, load saved state anvil --load-state anvil-state.json ``` ---- - -## 🔐 Security Notes - -### Local Development Only - - **Never use these private keys on real networks!** - -- All test keys are publicly known -- Anvil is for development only -- No security guarantees - -### Before Deploying to Testnet - -1. Generate new keys: `cast wallet new` -2. Fund with testnet ETH -3. Update deployment scripts -4. Never commit private keys to git - ---- - -## 🚢 Next Steps: Deploying to Testnet - -Once you're happy with local development: - -### 1. Get Testnet ETH - -- **Sepolia**: https://sepoliafaucet.com/ -- **Base Sepolia**: https://bridge.base.org/ - -### 2. Set Environment Variables - -```bash -# .env (don't commit this!) -SEPOLIA_RPC_URL=https://eth-sepolia.g.alchemy.com/v2/YOUR_KEY -PRIVATE_KEY=0xYOUR_TESTNET_KEY -ADMIN_MSIG=0xYourGnosisSafeAddress -INITIAL_TREASURY=0xYourTreasuryAddress -ETHERSCAN_API_KEY=YOUR_API_KEY -``` - -### 3. Deploy to Testnet - -```bash -npm run deploy:sepolia -``` - -### 4. Verify Contracts - -Verification happens automatically with `--verify` flag, or manually: - -```bash -forge verify-contract $CONTRACT_ADDRESS src/token/ELTA.sol:ELTA \ - --chain sepolia \ - --etherscan-api-key $ETHERSCAN_API_KEY -``` - ---- - -## Additional Resources - -- **Foundry Book**: https://book.getfoundry.sh/ -- **Anvil Docs**: https://book.getfoundry.sh/anvil/ -- **Cast Reference**: https://book.getfoundry.sh/reference/cast/ -- **Elata Docs**: https://docs.elata.bio - ---- - -## Tips & Best Practices - -### 1. Use Multiple Test Accounts - -Switch between accounts in MetaMask to test different user scenarios: -- Account 1: Power user with lots of XP -- Account 2: Regular user -- Account 3: New user with minimal XP - -### 2. Monitor Gas Usage - -```bash -npm run test:gas -``` - -Optimize contracts before deploying to mainnet where gas costs real money. - -### 3. Test Edge Cases - -Local blockchain is perfect for testing: -- Maximum values -- Overflow conditions -- Reentrancy attacks -- Access control bypasses - -### 4. Keep Scripts Updated - -When adding new contracts, update: -- `script/DeployLocalFull.s.sol` -- `script/SeedLocalData.s.sol` -- `scripts/generate-config.ts` - ---- - -## Contributing - -Found an issue with the local development setup? Please: - -1. Check existing issues -2. Create a new issue with: - - Your OS and versions - - Error messages - - Steps to reproduce - ---- - -## Quick Reference - -### Most Common Commands - -```bash -# Start everything -npm run dev - -# Stop Anvil -npm run dev:stop - -# Restart everything -npm run dev:restart - -# Start appstore frontend -cd ../elata-appstore && npm run local:full -``` - -### Contract Addresses - -Always read from `deployments/local.json` or use the generated TypeScript config. - -### Default RPC - -``` -http://127.0.0.1:8545 -``` - -### Chain ID - -``` -31337 -``` - ---- - -**Happy developing! ** - -For questions, join our Discord or open a GitHub issue. - +## Next Steps +- [ARCHITECTURE.md](./ARCHITECTURE.md) — How the contracts fit together +- [APP_LAUNCH_GUIDE.md](./APP_LAUNCH_GUIDE.md) — Building apps on the protocol +- [DEPLOYMENT.md](./DEPLOYMENT.md) — Deploying to testnet and mainnet diff --git a/docs/TOKENOMICS.md b/docs/TOKENOMICS.md new file mode 100644 index 0000000..2e93b00 --- /dev/null +++ b/docs/TOKENOMICS.md @@ -0,0 +1,282 @@ +# Tokenomics + +This document describes the economic design of the Elata Protocol: how ELTA tokens work, how value flows through the system, and how the incentives align participants toward long-term ecosystem growth. + +## ELTA Token + +ELTA is the governance and utility token for the Elata ecosystem. + +### Supply + +- **Maximum supply**: 77,000,000 ELTA (hard cap, enforced in contract) +- **Initial mint**: 10,000,000 ELTA to treasury +- **Remaining**: 67,000,000 ELTA available for future minting via governance + +The supply cap is immutable. Once set at deployment, it cannot be changed. Minting requires the `MINTER_ROLE`, which is initially held by the admin multisig and can be assigned or revoked through governance. + +### Token Properties + +ELTA is a standard ERC20 with these extensions: + +| Feature | Description | +|---------|-------------| +| ERC20Votes | On-chain governance delegation | +| ERC20Permit | Gasless approvals via signatures | +| Burnable | Anyone can burn their own tokens | +| No transfer fees | Compatible with all DeFi infrastructure | + +The token has no transfer taxes, rebasing mechanics, or other non-standard behaviors. It works with any DEX, aggregator, or DeFi protocol expecting a standard ERC20. + +### Token Utility + +ELTA serves three primary functions: + +1. **Governance** — Stake ELTA to receive veELTA voting power for protocol decisions +2. **App launches** — Pay ELTA to create new app tokens on the platform +3. **Economic base** — All app token trading uses ELTA as the quote currency + +## veELTA Staking + +Users lock ELTA to receive veELTA, a non-transferable token that represents voting power and entitles holders to protocol revenue. + +### Lock Parameters + +| Parameter | Value | +|-----------|-------| +| Minimum lock | 7 days | +| Maximum lock | 730 days (2 years) | +| Minimum boost | 1.0x | +| Maximum boost | 2.0x | + +### How Boost Works + +Longer locks give more veELTA per ELTA locked. The boost scales linearly: + +``` +boost = 1 + (lock_duration / max_lock) +veELTA = ELTA_locked × boost +``` + +Examples: + +| Lock Amount | Lock Duration | Boost | veELTA Received | +|-------------|---------------|-------|-----------------| +| 1,000 ELTA | 7 days (min) | 1.00x | 1,000 veELTA | +| 1,000 ELTA | 365 days | 1.50x | 1,500 veELTA | +| 1,000 ELTA | 730 days (max) | 2.00x | 2,000 veELTA | + +### Lock Operations + +- **Create lock**: Deposit ELTA with an unlock timestamp +- **Increase amount**: Add more ELTA to an existing lock +- **Extend lock**: Push the unlock timestamp further out +- **Unlock**: After expiry, withdraw your original ELTA + +veELTA is non-transferable to prevent vote buying. You can't sell or delegate your position to another address. + +### Why Time-Locked Staking? + +Time locks serve multiple purposes: + +1. **Governance alignment** — Long-term stakers have more say in decisions that affect the protocol's future +2. **Attack resistance** — Can't flash-loan ELTA to manipulate votes +3. **Supply predictability** — Locked tokens create predictable circulation + +## XP Reputation + +XP (Experience Points) is a non-transferable reputation token that tracks user participation. + +### Earning XP + +XP is awarded for activities that benefit the ecosystem: + +- Submitting EEG data sessions +- Playing apps and completing activities +- Participating in tournaments +- Voting in funding rounds +- Contributing to governance + +The exact amounts are set by XP operators and can vary based on activity type and quality. + +### Using XP + +XP determines voting weight in funding decisions. When the community votes on which research proposals to fund, votes are weighted by XP rather than ELTA. This means funding decisions reflect participation, not just capital. + +XP also gates early access to new app launches. For the first 6 hours after an app launches, only users with sufficient XP (default: 100 XP) can buy tokens. This rewards active community members. + +### XP vs ELTA + +The protocol separates reputation (XP) from ownership (ELTA) intentionally: + +| Aspect | XP | ELTA | +|--------|-----|------| +| Transferable | No | Yes | +| Earned by | Participation | Purchase or earnings | +| Used for | Funding votes, early access | Governance, staking, trading | +| Represents | Contribution | Economic stake | + +This separation prevents plutocracy. You can't simply buy XP to control funding decisions—you have to earn it through genuine participation. + +## Revenue and Distribution + +Protocol revenue comes from fees on economic activity and flows back to participants. + +### Revenue Sources + +| Source | Fee | Description | +|--------|-----|-------------| +| Trading fees | 1% | On bonding curve buys and sells | +| Tournament rake | 2.5% | Protocol share of tournament prizes | +| App transfer fees | 1% | On app token transfers (optional) | + +### Distribution Split + +All revenue flows through the RewardsDistributor, which splits it: + +``` +Incoming Fees +├── 70% → App token stakers +├── 15% → veELTA holders +└── 15% → Treasury +``` + +This split is fixed in the contract. Changes require governance approval. + +### How Claims Work + +veELTA holders can claim their share of accumulated fees. The distributor takes snapshots of veELTA balances, and claims are proportional to your share of total veELTA at each snapshot. + +App token stakers earn through their app's AppRewardsDistributor, which works similarly but tracks stakes in individual app tokens. + +### Example + +Monthly trading volume: 100,000 ELTA + +``` +Trading fee (1%): 1,000 ELTA + +Distribution: +├── App stakers: 700 ELTA (70%) +├── veELTA holders: 150 ELTA (15%) +└── Treasury: 150 ELTA (15%) +``` + +## App Launch Economics + +Developers can launch app tokens with built-in economic infrastructure. + +### Launch Costs + +To create an app: + +| Cost | Amount | Purpose | +|------|--------|---------| +| Seed liquidity | 100 ELTA | Initial bonding curve liquidity | +| Creation fee | 10 ELTA | Protocol fee to treasury | +| **Total** | 110 ELTA | | + +### Token Distribution + +Each app token has 1 billion total supply, distributed: + +- **50% to creator** — Auto-staked in the app's staking vault +- **50% to bonding curve** — Available for public trading + +The creator's tokens are auto-staked, meaning they earn rewards but can't immediately dump. To sell, they must unstake first, which is visible on-chain. + +### Bonding Curve + +The bonding curve provides price discovery without requiring initial liquidity provision: + +1. Price starts low and increases as more tokens are bought +2. 1% fee on each trade goes to the RewardsDistributor +3. Anyone can buy or sell at any time + +### Graduation + +When the bonding curve accumulates 42,000 ELTA, it "graduates": + +1. Remaining tokens and ELTA form a liquidity pair +2. LP tokens are locked for 2 years +3. Trading moves to the DEX + +This graduation mechanism ensures every successful app has permanent liquidity. + +### Transfer Fees (Optional) + +App tokens can optionally charge a 1% transfer fee (governance-adjustable, max 2%). This fee follows the same 70/15/15 distribution split, creating ongoing rewards for stakers. + +Certain addresses are exempt from transfer fees to prevent circular fee issues: the bonding curve, staking vault, and factory contracts. + +## Economic Flywheel + +The token economics create a reinforcing cycle: + +``` +Users play apps + ↓ +Generate data and usage + ↓ +Protocol captures fees + ↓ +Community votes on funding + ↓ +Research and development funded + ↓ +Better apps built + ↓ +More users play apps +``` + +Simultaneously: + +``` +Protocol captures fees + ↓ +Distributed to stakers + ↓ +Attracts long-term holders + ↓ +Better governance decisions + ↓ +Protocol improves + ↓ +More fee generation +``` + +The key insight is that XP guides *what* gets funded (through voting), while ELTA staking captures *the value* of that funding (through yield). + +## Governance Parameters + +The Governor contract controls protocol changes: + +| Parameter | Value | +|-----------|-------| +| Voting delay | 1 day | +| Voting period | 7 days | +| Proposal threshold | 0.1% of supply (~77,000 ELTA) | +| Quorum | 4% of supply (~3.08M ELTA) | + +**Emergency proposals** require 5% of supply to propose but have an expedited 3-day voting period for critical fixes. + +## Security Considerations + +The economic design includes several security measures: + +1. **Supply cap** — Cannot mint beyond 77M ELTA, preventing inflation attacks +2. **Time-locked staking** — Prevents flash-loan governance attacks +3. **Non-transferable XP** — Prevents reputation buying +4. **Locked liquidity** — Graduated app tokens have permanently locked LP +5. **Role-based minting** — Only authorized addresses can mint ELTA + +## Contract References + +| Contract | Source | +|----------|--------| +| ELTA | [src/token/ELTA.sol](../src/token/ELTA.sol) | +| VeELTA | [src/staking/VeELTA.sol](../src/staking/VeELTA.sol) | +| ElataXP | [src/experience/ElataXP.sol](../src/experience/ElataXP.sol) | +| RewardsDistributor | [src/rewards/RewardsDistributor.sol](../src/rewards/RewardsDistributor.sol) | +| AppFactory | [src/apps/AppFactory.sol](../src/apps/AppFactory.sol) | +| AppBondingCurve | [src/apps/AppBondingCurve.sol](../src/apps/AppBondingCurve.sol) | +