# Staking System

The Treem DAO staking system allows token holders to lock their TREEM tokens for specified periods to gain voting rights and earn rewards.

### Overview

Staking is mandatory for governance participation. By staking tokens, users demonstrate long-term commitment to the DAO and gain the right to vote on proposals and earn rewards.

### Staking Tiers

#### 6-Month Staking Tier

**Lock Period**: 180 days

**Benefits**:

* Vote on general proposals
* Vote on grant proposals
* Earn base voting rewards
* Participate in governance discussions

**Use Cases**:

* Regular governance participation
* Community members seeking voting rights
* Users wanting moderate commitment

#### 12-Month Staking Tier

**Lock Period**: 365 days

**Benefits**:

* All 6-month tier benefits
* Create grant proposals
* Higher voting reward multipliers
* Priority in certain governance features

**Use Cases**:

* Long-term DAO contributors
* Project creators seeking funding
* Core community members

### Staking Process

#### Prerequisites

* TREEM tokens in your wallet
* Connected Ethereum wallet
* Sufficient ETH for gas fees

#### Step-by-Step Staking

1. **Navigate to Staking Interface**
   * Go to Dashboard → Token Staking
   * Or use the dedicated Staking page
2. **Choose Staking Parameters**
   * Enter amount of TREEM to stake
   * Select lock period (6 or 12 months)
   * Review staking benefits summary
3. **Approve Token Transfer**
   * Click "Stake Tokens"
   * Approve TREEM token spending (if first time)
   * Confirm staking transaction
4. **Confirm Staking**
   * Transaction processes on blockchain
   * Stake appears in your dashboard
   * Voting power is automatically updated

#### Multiple Stakes

Users can create multiple separate stakes:

* Each stake has its own lock period
* Voting power cumulates across all stakes
* Unstaking is done individually per stake

### Voting Power Calculation

#### Base Voting Power

```
Voting Power = Sum of All Staked Token Amounts
```

#### Delegation

* Default: Voting power delegated to yourself
* Option: Delegate to another address
* Delegation can be changed anytime
* Delegated voting power appears instantly

#### Snapshot Mechanism

* Voting power calculated at proposal creation time
* Prevents vote manipulation through token transfers
* Historical voting power preserved for active proposals

### Lock Periods and Unlocking

#### Lock Period Rules

1. **Fixed Duration**: Cannot be changed after staking
2. **No Early Exit**: Tokens locked for entire period
3. **Automatic Unlock**: Tokens become unstakable after period expires

#### Tracking Lock Progress

**Dashboard Display**:

* Time remaining until unlock
* Progress bar showing completion percentage
* Exact unlock date and time

**Calculation**:

```
Progress = (Current Time - Start Time) / Lock Period
Time Remaining = Unlock Time - Current Time
```

#### Unstaking Process

1. **Wait for Unlock**: Lock period must be completed
2. **Navigate to Stakes**: View your active stakes
3. **Unstake Tokens**: Click "Unstake" on expired stakes
4. **Confirm Transaction**: Approve unstaking transaction
5. **Receive Tokens**: Tokens returned to wallet

### Rewards System

#### Voting Rewards

**Base Reward**: 100 TREEM per vote cast

**Earning Mechanism**:

* Vote on any proposal (general or grant)
* Rewards accumulate in your account
* Claim manually when ready

**Annual Limits**:

* Maximum 50,000 TREEM per user per year
* Prevents reward farming
* Resets annually

#### Reward Calculation

```
Total Rewards = Votes Cast × Base Reward (100 TREEM)
Claimable = min(Total Rewards, Annual Cap - Already Claimed)
```

#### Claiming Rewards

1. **Navigate to Rewards**: Go to Rewards section
2. **View Accumulated**: See unclaimed reward amount
3. **Claim Rewards**: Click "Claim Rewards" button
4. **Confirm Transaction**: Approve claim transaction
5. **Receive Tokens**: Rewards transferred to wallet

### Smart Contract Integration

#### TreemStaking Contract

**Key Functions**:

* `stake(uint256 amount, StakeTier tier)`: Create new stake
* `unstake()`: Remove expired stake
* `claimBonus()`: Claim voting rewards
* `canProposeGrants(address user)`: Check grant proposal rights

**Events**:

* `Staked(address user, uint256 amount, StakeTier tier)`
* `Unstaked(address user, uint256 amount)`
* `BonusClaimed(address user, uint256 bonusAmount)`

#### Staking Tiers Enum

```solidity
enum StakeTier { 
    NONE,           // 0 - No active stake
    SIX_MONTHS,     // 1 - 6-month lock period
    TWELVE_MONTHS   // 2 - 12-month lock period
}
```

### Frontend Integration

#### React Hooks

**useStaking Hook**:

```typescript
const {
  stakes,              // Array of user's stakes
  loading,            // Loading state
  createStake,        // Function to create stake
  unstakeTokens,      // Function to unstake
  getTimeRemaining    // Function to calculate time left
} = useStaking();
```

#### Key Components

* **EnhancedTokenStaking**: Main staking interface
* **StakingDashboard**: Comprehensive staking overview
* **VotingRewardsDashboard**: Reward tracking and claiming

### Security Considerations

#### Smart Contract Security

* **Reentrancy Protection**: Prevents recursive calls
* **Access Controls**: Owner-only administrative functions
* **Time Validation**: Prevents manipulation of lock periods
* **Balance Checks**: Ensures sufficient tokens for operations

#### User Security

* **Wallet Security**: Keep private keys secure
* **Transaction Verification**: Always verify transaction details
* **Phishing Protection**: Only use official DAO interfaces
* **Gas Management**: Monitor network congestion and fees

### Troubleshooting

#### Common Issues

**Staking Transaction Fails**:

* Check TREEM token balance
* Verify token approval
* Ensure sufficient ETH for gas
* Try increasing gas limit

**Cannot Unstake**:

* Verify lock period is complete
* Check stake status in dashboard
* Ensure stake is active
* Try refreshing the interface

**Voting Power Not Updated**:

* Wait for blockchain confirmation
* Check if delegation is correct
* Verify stake transaction succeeded
* Contact support if persistent

#### Error Messages

| Error                  | Meaning                        | Solution                             |
| ---------------------- | ------------------------------ | ------------------------------------ |
| "Invalid tier"         | Wrong staking tier selected    | Use SIX\_MONTHS or TWELVE\_MONTHS    |
| "Already staked"       | User has existing active stake | Unstake previous stake first         |
| "Lock period not over" | Attempting early unstake       | Wait for lock period completion      |
| "Insufficient balance" | Not enough TREEM tokens        | Acquire more tokens or reduce amount |

### Advanced Features

#### Delegation Management

**Self Delegation** (Default):

```typescript
// Automatic on staking
votesToken.delegate(msg.sender);
```

**Delegate to Others**:

```typescript
// Delegate voting power to another address
await treemToken.delegate(delegateeAddress);
```

#### Batch Operations

**Multiple Stakes**:

* Create separate stakes for different time periods
* Manage risk across different lock periods
* Optimize for various governance scenarios

**Batch Unstaking**:

* Unstake multiple expired stakes
* Claim multiple reward periods
* Optimize gas costs

### Best Practices

#### Staking Strategy

1. **Diversify Lock Periods**: Mix 6-month and 12-month stakes
2. **Consider Gas Costs**: Batch operations when possible
3. **Monitor Unlock Dates**: Plan for token liquidity needs
4. **Active Participation**: Vote regularly to maximize rewards

#### Risk Management

1. **Start Small**: Begin with smaller amounts to learn system
2. **Understand Locks**: Fully comprehend lock period implications
3. **Stay Informed**: Follow DAO announcements and updates
4. **Community Engagement**: Participate in discussions before voting

### Migration and Upgrades

#### Contract Upgrades

The staking system may be upgraded in the future:

* User stakes will be preserved
* Migration paths will be provided
* Community governance will decide upgrades
* Advance notice will be given

#### Database Integration

**Stake Tracking**:

```sql
-- stake_locks table structure
CREATE TABLE stake_locks (
    id UUID PRIMARY KEY,
    user_id UUID NOT NULL,
    amount INTEGER NOT NULL,
    lock_period INTEGER NOT NULL,
    stake_tier TEXT NOT NULL,
    start_time TIMESTAMP NOT NULL,
    unlock_time TIMESTAMP NOT NULL,
    is_active BOOLEAN DEFAULT TRUE
);
```

### API Reference

#### REST Endpoints

**Get User Stakes**:

```
GET /api/staking/user/{userId}/stakes
```

**Create Stake**:

```
POST /api/staking/stake
Body: { amount: number, lockPeriod: 6|12 }
```

**Unstake Tokens**:

```
POST /api/staking/unstake/{stakeId}
```

**Get Rewards**:

```
GET /api/rewards/user/{userId}
```

This comprehensive staking documentation covers all aspects of the Treem DAO staking system, from basic concepts to advanced integration details.
