# Raids

The **Raids** feature in Bragabot is a powerful tool for group admins to organize and incentivize within their Telegram communities. Raids are essentially community-driven campaigns where users complete designated tasks in exchange for a share of a bounty. The implementation of Raids involves multiple stages, including task creation, validation, and reward distribution, all of which are handled by various components within Bragabot's architecture.

## Architecture Overview

1. **Frontend**: The user interface where group admins create and manage raids, and where Auto Raids settings can be configured.
2. **Backend**: Handles the logic for raid creation, validation, and management.
3. **Custom Twitter Endpoint**: A dedicated service responsible for task validation and user engagement tracking.
4. **Raid Validation Module**: Manages the validation of tasks submitted by users.
5. **Web3 Claim Contract**: A smart contract on the Polygon network used for distributing rewards to users who complete tasks.

## Workflow

<figure><img src="https://1288977065-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FFxGgNZO7ar52lsrkVXYY%2Fuploads%2FyUntsAD6HZho3dXYnLLE%2Fdiagram.png?alt=media&#x26;token=940ce0f8-16fb-4813-a027-66a2818e8e01" alt=""><figcaption></figcaption></figure>

## Components and Implementation Details

### **1. Manual Raid Creation**

Raid creation is initiated by group admins through the Bragabot frontend. The process involves extensive validation checks to ensure the integrity of the raid and the tasks associated with it.

**Steps**:

1. **Request Initiation**:
   * The group admin initiates a raid creation request via the Bragabot frontend.
   * The request is sent to the backend via a secure API call.
2.  **Initial Validation**:

    * **Task Type Verification**:
      * The backend checks if the task is associated with Telegram or Twitter.
      * For Telegram tasks, the system verifies the validity of the provided Telegram links.
      * For Twitter tasks, the system checks the Twitter links to ensure they are valid and have not been used before for another task.

    **Code Example**: Verifying task type and checking links\


    ```python
    def validate_task_links(task):
        if task['platform'] == 'telegram':
            if not is_valid_telegram_link(task['link']):
                raise ValueError("Invalid Telegram link.")
        elif task['platform'] == 'twitter':
            if not is_valid_twitter_link(task['link']):
                raise ValueError("Invalid Twitter link.")
            if is_task_already_exists(task):
                raise ValueError("Task already exists.")
        else:
            raise ValueError("Unsupported platform.")

    # Usage
    validate_task_links(task_data)
    ```
3.  **Bounty Verification**:

    * The backend checks the bounty associated with the raid.
    * The system verifies if the group has sufficient funds to cover the bounty. If not, an error is returned to the group admin.

    **Code Example**: Verifying and deducting bounty.\


    ```python
    def verify_and_deduct_bounty(group_id, bounty):
        group_balance = fetch_group_balance(group_id)
        if group_balance < bounty:
            return False, "Insufficient funds to create raid."
        
        # Deduct bounty
        update_group_balance(group_id, group_balance - bounty)
        return True, "Bounty deducted successfully."

    # Usage
    success, message = verify_and_deduct_bounty(group_id, raid_bounty)
    if not success:
        raise ValueError(message)
    ```
4. **Raid Creation**:
   * If all validations pass and the bounty is successfully deducted, the raid is created in the system.
   * The raid details, including tasks, rewards, and timelines, are stored in the database.
5. **Notification to Group**:
   * Once the raid is created, a notification is sent to the Telegram group, informing users of the new raid and encouraging participation.

### **2. Auto Raid Creation**

**Overview**: Auto Raids are automatically generated when a new tweet is posted by the project's Twitter account. This feature ensures continuous community engagement without manual intervention, provided there are sufficient funds.

**Steps**:

1. **Auto Raids Configuration**:
   * Group admins can enable Auto Raids via the frontend, specifying the conditions under which raids should be automatically created.
   * The backend stores these settings and monitors the project's Twitter account for new tweets.
2. **Monitoring for New Tweets**:
   * The Custom Twitter Endpoint monitors the project's Twitter account in real-time using Streams and Recent Search as detailed in [Tweets Forwarding Section](tweets-forwarding). When a new tweet is detected, it checks if Auto Raids are enabled for the associated group.
3.  **Auto Raid Validation and Creation**:

    * **Bounty Verification**:
      * Before creating the raid, the system checks if the group has sufficient funds for the bounty.
      * If funds are insufficient, Auto Raids are disabled, and group admins are notified.

    **Code Example**: Verifying funds for Auto Raids.\


    ```python
    def create_auto_raid_for_tweet(group_id, tweet, settings):
        bounty = settings['bounty_per_task']
        success, message = verify_and_deduct_bounty(group_id, bounty)
        
        if success:
            raid_data = {
                "task": {
                    "platform": "twitter",
                    "link": tweet['url'],
                    "description": f"Engage with the tweet: {tweet['text']}"
                },
                "bounty": bounty,
                "type": "auto"
            }
            create_raid(group_id, raid_data)
        else:
            disable_auto_raids(group_id)
            notify_admin_of_insufficient_funds(group_id)

    # Usage
    create_auto_raid_for_tweet(group_id, tweet, auto_raid_settings)
    ```

### **3. Task Completion and Validation**

Users participate in the raid by completing the assigned tasks. Once a task is completed, the user clicks "Done," triggering a validation process to confirm the task's completion.

**Steps**:

1. **User Task Submission**:
   * A user submits their task completion by clicking "Done" in the frontend.
   * The frontend sends a request to the backend with the task details.
2.  **Enqueueing Task for Validation**:

    * The backend enqueues the task for validation by sending the task details to the Custom Twitter Endpoint.
    * The user receives a queue number and a message indicating that their task is being processed.

    **Code Example**: Enqueueing task for validation.\


    ```python
    def enqueue_task_for_validation(task_submission_id):
        queue_number = add_to_validation_queue(task_submission_id)
        return queue_number

    # Usage
    queue_number = enqueue_task_for_validation(task_submission_id)
    ```
3.  **Task Validation Process**:

    * The Custom Twitter Endpoint runs a job every 3 minutes to process the queued tasks.
    * The job fetches tasks from the queue and validates them by making requests to the Twitter API to check if the user has completed the task.

    **Code Example**: Validating task completion.\


    ```python
    def validate_task(task_submission):
        task_details = fetch_task_details(task_submission['task_id'])
        user_action = check_twitter_user_action(task_submission['user_id'], task_details)
        
        if user_action:
            mark_task_as_completed(task_submission['id'])
            return True
        else:
            mark_task_as_failed(task_submission['id'])
            return False

    # Usage
    for task_submission in fetch_queued_tasks():
        validate_task(task_submission)
    ```
4.  **User Notification**:

    * Once the task is validated, the user is notified of the result (success or failure) through a Telegram message.

    **Code Example**: Notifying the user of task validation result.

    ```python
    def notify_user_of_task_result(user_id, task_submission_id):
        task_status = fetch_task_status(task_submission_id)
        if task_status == 'completed':
            message = "✅ Congratulations, you have completed the raid. You are whitelisted to claim a portion of the bounty. \nYou have also won 1000 extra EXP points."
        else:
            message = "⚠️ Raid is not yet completed."
        send_user_notification(user_id, message)

    # Usage
    notify_user_of_task_result(user_id, task_submission_id)
    ```

### **4. Raid Finalization and Reward Distribution**

After the raid ends, the system calculates the share of the bounty for each user who successfully completed the tasks. If the raid is unsuccessful (i.e., the target is not met), the remaining bounty is refunded to the group. Rewards are distributed through a Web3 claim contract on the Polygon network.

**Steps**:

1. **Raid Completion**:
   * When the raid reaches its end time, the backend automatically triggers the finalization process.
   * The system fetches all users who successfully completed tasks during the raid.
2. **Calculating Reward Shares**:
   * The system calculates each user's share of the bounty.
   * If the raid target is not met, the remaining bounty is refunded to the group admin.
3. **Refunding Remaining Bounty**:
   * If the raid target is not met, the remaining bounty (which was not distributed as rewards) is refunded to the group's account.
4. **Web3 Claim Contract for Reward Distribution**:
   * The system interacts with a Web3 smart contract on the Polygon network, allowing users to claim their rewards.
   * The frontend of this is available at https://claim.bragabot.com where users can claim their rewards
5. **User Notification and Reward Claiming**:
   * Users receive a notification whenever rewards are distributed for claim. They can then, claim their rewards from the claiming website.



The **Raids** feature in Bragabot provides a comprehensive system for group admins to create, manage, and reward community-driven tasks on Telegram and Twitter. The process begins with the creation of a raid, where tasks are defined and validated to ensure integrity. As users complete tasks, they are queued for validation, ensuring that only legitimate completions are rewarded. Upon completion of the raid, rewards are calculated and distributed via a Web3 claim contract, ensuring a transparent and secure reward process. This extensive system allows group admins to engage their communities effectively while providing users with tangible incentives for their participation.
