openapi: 3.0.3
info:
  title: AwesomeFee API
  description: |
    # AwesomeFee - TRON Resource Delegation Service

    ## Overview

    AwesomeFee provides instant Energy and Bandwidth delegation for TRON blockchain transactions, reducing transaction costs by up to 90%. Instead of burning TRX for resources, delegate them temporarily from our resource pool.

    ## The Problem

    TRON blockchain transactions require two types of resources:

    **Energy** - Required for smart contract execution (USDT transfers, DeFi interactions)
    **Bandwidth** - Required for all transactions (data transmission)

    Without these resources, transactions consume TRX at market rates:
    - USDT TRC-20 transfer: 13.65-27.30 TRX per transaction
    - Smart contract calls: 50-200 TRX depending on complexity
    - Simple TRX transfer: 0.268-1.268 TRX

    ## Our Solution

    AwesomeFee maintains a large pool of pre-staked resources that can be instantly delegated to any TRON address:

    1. **90% Cost Reduction** - Pay only for actual resource usage, not market rates
    2. **Instant Delegation** - Resources delegated in under 1 second
    3. **1-Hour Duration** - Fixed delegation period with automatic reclaim
    4. **Pay-As-You-Go** - No upfront staking or long-term commitments
    5. **Credit System** - Use credit when balance is low

    ## 🚀 Getting Started

    ### Step 1: Get API Credentials 🔑

    Contact us to receive your API credentials:
    - 📧 Email: support@awesomefee.com
    - 📝 Include: Organization name, expected volume, use case
    - ⏱️ Response time: Within 24 hours
    - 🎁 New users receive $10 test balance

    You'll receive:
    ```
    X-API-Key: ak_live_1234567890abcdef
    X-API-Secret: sk_live_abcdefghijklmnop
    ```

    ⚠️ **Important**: Store these securely! Never commit to version control.

    ### Step 2: Test Your Connection ✅

    ```bash
    curl -X GET https://awesomefee.com/api/v1/health \
      -H "X-API-Key: ak_live_1234567890abcdef" \
      -H "X-API-Secret: sk_live_abcdefghijklmnop"
    ```

    ### Step 3: Check Your Balance 💰

    ```bash
    curl -X GET https://awesomefee.com/api/v1/user/balance \
      -H "X-API-Key: ak_live_1234567890abcdef" \
      -H "X-API-Secret: sk_live_abcdefghijklmnop"
    ```

    ### Step 4: Delegate Energy ⚡

    ```bash
    curl -X POST https://awesomefee.com/api/v1/delegation/energy \
      -H "X-API-Key: ak_live_1234567890abcdef" \
      -H "X-API-Secret: sk_live_abcdefghijklmnop" \
      -H "Content-Type: application/json" \
      -d '{
        "to_address": "TYourTronAddress123456789",
        "amount": 65000
      }'
    ```

    ## 🔐 Authentication

    All authenticated requests require two headers:
    ```http
    X-API-Key: ak_live_1234567890abcdef
    X-API-Secret: sk_live_abcdefghijklmnop
    ```

    **Security Notes:**
    - Never commit API keys to version control
    - Use environment variables for credentials
    - Rotate keys every 90 days
    - API keys work only with HTTPS

    ## 💰 Cost Comparison

    | Transaction Type | Traditional Cost | With AwesomeFee | Savings |
    |-----------------|------------------|-----------------|---------|
    | USDT Transfer (First) | 27.30 TRX | 2.73 TRX | 90% |
    | USDT Transfer (Regular) | 13.65 TRX | 1.37 TRX | 90% |
    | Smart Contract Call | 50-200 TRX | 5-20 TRX | 90% |
    | TRX Transfer | 0.268 TRX | 0.027 TRX | 90% |

    ## 🔄 How Delegation Works

    1. **Request Delegation** - POST to `/delegation/energy` or `/delegation/bandwidth`
    2. **System Validates** - Checks your balance, address format, and pool capacity
    3. **Instant Delegation** - Resources delegated from our pool to your address
    4. **Use Resources** - Execute your transaction within 1 hour
    5. **Auto-Reclaim** - System automatically reclaims resources after 1 hour

    ### Wait Methods (Recommended)

    For synchronous confirmation, use wait endpoints:
    - `/delegation/energy/{id}/wait` - Blocks until energy delegation confirmed
    - `/delegation/bandwidth/{id}/wait` - Blocks until bandwidth delegation confirmed
    - `/address/activate/{id}/wait` - Blocks until address activation confirmed

    These endpoints wait up to 30 seconds for blockchain confirmation, eliminating the need for manual polling.

    ## ⚙️ Advanced Features

    ### Dry-Run Mode
    Test any endpoint without executing real transactions:
    - Query parameter: `?dry_run=true`
    - Header: `X-Dry-Run: true`

    ### Request Tracking
    Every request includes a unique `requestID` in the response for tracking and support.

    ### Rate Limiting
    - **Standard Tier**: 10 requests/second
    - **Enterprise Tier**: 100 requests/second

    ## 🏢 Enterprise Solutions

    For high-volume operations, we offer:
    - **Credit Limits** - Up to 1,000,000 TRX credit line
    - **NET 30 Terms** - Post-payment billing cycles
    - **Priority Support** - 24/7 dedicated support with 1-hour SLA
    - **Volume Discounts** - Up to 50% additional savings

    Contact enterprise@awesomefee.com for custom solutions.

    ## Error Handling

    All errors follow a consistent format:
    ```json
    {
      "error": true,
      "success": false,
      "requestID": "550e8400-e29b-41d4-a716-446655440000",
      "errorCode": "INSUFFICIENT_RESOURCES",
      "errorMessage": "Not enough Energy available in pool - required: 65000, available: 50000"
    }
    ```

    **Response fields:**
    - `error` (boolean) - Always `true` for errors
    - `success` (boolean) - Always `false` for errors
    - `requestID` (string) - Unique request identifier for tracking and support
    - `errorCode` (string) - Machine-readable error code
    - `errorMessage` (string) - Human-readable error description with details

    Common error codes:
    - `BAD_REQUEST` - Invalid request parameters
    - `UNAUTHORIZED` - Authentication failed
    - `INSUFFICIENT_BALANCE` - Not enough balance or credit
    - `RESOURCE_UNAVAILABLE` - Resources temporarily unavailable
    - `RATE_LIMITED` - Too many requests
    - `TIMEOUT` - Request timeout
    - `INTERNAL_ERROR` - Internal server error

    ## 📞 Support

    **Contact channels:**
    - 📧 **Email**: support@awesomefee.com
    - 💬 **Telegram**: @awesomefee_support

    **When reporting issues, please include:**
    - Request ID from error response
    - Delegation ID (if applicable)
    - Timestamp and error message

  version: 1.2.0
  contact:
    email: support@awesomefee.com
  license:
    name: MIT
    url: https://opensource.org/licenses/MIT
  x-logo:
    url: https://awesomefee.com/assets/logo.png
    altText: AwesomeFee Logo

servers:
  - url: https://awesomefee.com/api/v1
    description: Production server

tags:
  - name: Health
    description: Service health check and status monitoring
  - name: User
    description: User account balance and credit management
  - name: Delegation
    description: |
      Energy and Bandwidth resource delegation. Delegate resources from our pool to any TRON address for 1 hour.
      Use wait endpoints for synchronous confirmation without manual polling.
  - name: Activation
    description: |
      TRON address activation service. Inactive addresses require 1 TRX activation before receiving resources.
      Use wait endpoint for synchronous confirmation.
  - name: Mate Addresses
    description: |
      Automatic resource monitoring and management for TRON addresses. Monitor addresses continuously
      and automatically top-up Energy, Bandwidth, and TRX when resources fall below configured thresholds.

      **Key Features:**
      - Automatic monitoring of blockchain transactions
      - Configurable minimum and target resource levels
      - Subscription plans with different pricing tiers
      - Complete cost tracking and history
      - Automatic address activation if needed
      - Balance integration with credit support
  - name: Subscription Plans
    description: |
      Subscription plan management for Mate Addresses. Plans define default resource thresholds,
      pricing markup percentages, and usage limits.

paths:
  /health:
    get:
      tags:
        - Health
      summary: Health check
      description: Check if the API service is running and healthy
      operationId: healthCheck
      responses:
        '200':
          description: Service is healthy
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HealthResponse'
              example:
                error: false
                success: true
                requestID: "550e8400-e29b-41d4-a716-446655440000"
                data:
                  status: "healthy"
                  timestamp: "2024-01-15T10:30:00Z"
                  version: "1.1.0"
                  services:
                    api: "running"
                    mongodb: "connected"
                    monitor: "active"

  /transaction/calculate:
    post:
      tags:
        - Calculation
      summary: Calculate transaction resource requirements
      description: |
        📊 **Transaction Resource Calculator**

        Calculate required resources (Energy, Bandwidth) and costs for TRON transactions.
        Returns price range, address information, and human-readable recommendations.

        ### Features
        - Real address verification (checks if active on blockchain)
        - Automatic resource calculation based on currency
        - Price range (min-max) in USDT
        - Address balances and available resources
        - Human-readable summary and recommendations

        ### Supported Currencies
        - **TRX**: Native TRON transfers (268 Bandwidth)
        - **USDT**: TRC-20 token transfers (65,000-130,000 Energy + 345 Bandwidth)

        ### No Authentication Required
        This is a public endpoint for price estimation.

      operationId: calculateTransactionResources
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/TransactionCalculationRequest'
      responses:
        '200':
          description: Resource calculation successful
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/APIResponse'
                  - type: object
                    properties:
                      data:
                        type: object
                        properties:
                          currency:
                            type: string
                            example: "USDT"
                          amount:
                            type: string
                            example: "100"
                          address_from:
                            $ref: '#/components/schemas/AddressDetails'
                          address_to:
                            $ref: '#/components/schemas/AddressDetails'
                          resources_required:
                            $ref: '#/components/schemas/ResourcesRequired'
                          pricing_options:
                            type: object
                            properties:
                              min_price_usdt:
                                type: string
                                example: "0.70"
                              max_price_usdt:
                                type: string
                                example: "1.56"
                          summary:
                            type: string
                            example: "Sending 100 USDT requires 130000 Energy and 345 Bandwidth. Cost: 0.70 - 1.56 USDT."
                          recommendations:
                            type: array
                            items:
                              type: string
                            example:
                              - "Sender address is not activated. Activation required before transaction (costs 1 TRX)"
                              - "First USDT transfer to receiver requires double energy (130,000 vs 65,000)"

  /user/balance:
    get:
      tags:
        - User
      summary: Get user balance and credit info
      description: |
        💰 **Get Current Balance and Credit Information**

        Returns your current USDT balance, credit limit, and available credit.

        ---

        ### 💳 Understanding the Credit System

        | Field | Description |
        |-------|-------------|
        | **balance_usdt** | Your actual available balance |
        | **credit_limit_usdt** | Maximum credit you can use |
        | **credit_used_usdt** | Currently used credit amount |
        | **credit_available** | Remaining credit (limit - used) |
        | **total_available** | Balance + Available Credit |

        **Example Scenario:**
        - Balance: $10
        - Credit Limit: $100
        - Credit Used: $20
        - Available Credit: $80
        - **Total you can spend: $90** ($10 balance + $80 credit)

        ---

        ### 💡 How Credit Works

        1. **Payments reduce credit first**: When you receive payment, it pays off any used credit before increasing balance
        2. **Delegations use balance first**: When ordering delegations, balance is used before credit
        3. **Credit limit is fixed**: Contact support to increase your credit limit

        ---

        ### 📊 Balance vs Credit Priority

        **When receiving payment ($100):**
        - Credit used: $30 → Reduces to $0
        - Remaining $70 → Added to balance

        **When ordering delegation ($50):**
        - Balance: $40 → Reduces to $0
        - Remaining $10 → Taken from credit ($10 credit used)

      operationId: getUserBalance
      security:
        - ApiKeyAuth: []
        - BearerAuth: []
      x-code-samples:
        - lang: curl
          label: cURL
          source: |
            curl -X GET https://awesomefee.com/api/v1/user/balance \
              -H "X-API-Key: ak_live_1234567890abcdef" \
              -H "X-API-Secret: sk_live_abcdefghijklmnop"
        - lang: javascript
          label: JavaScript
          source: |
            const response = await fetch('https://awesomefee.com/api/v1/user/balance', {
              headers: {
                'X-API-Key': 'ak_live_1234567890abcdef',
                'X-API-Secret': 'sk_live_abcdefghijklmnop'
              }
            });

            const data = await response.json();
            console.log('Balance:', data.data.balance_usdt);
            console.log('Total Available:', data.data.total_available);
            console.log('Credit Used:', data.data.credit_used_usdt);
        - lang: python
          label: Python
          source: |
            import requests

            response = requests.get(
                'https://awesomefee.com/api/v1/user/balance',
                headers={
                    'X-API-Key': 'ak_live_1234567890abcdef',
                    'X-API-Secret': 'sk_live_abcdefghijklmnop'
                }
            )

            data = response.json()['data']
            print(f"Balance: ${data['balance_usdt']}")
            print(f"Credit Available: ${data['credit_available']}")
            print(f"Total Available: ${data['total_available']}")

            # Check if we can afford a $50 delegation
            if float(data['total_available']) >= 50:
                print("✅ Can afford $50 delegation")
            else:
                print("❌ Insufficient funds")
      responses:
        '200':
          description: User balance and credit information
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/UserBalanceResponse'
              examples:
                with_balance:
                  summary: ✅ User with balance and available credit
                  value:
                    success: true
                    request_id: "550e8400-e29b-41d4-a716-446655440000"
                    data:
                      user_id: "507f1f77bcf86cd799439011"
                      email: "user@example.com"
                      balance_usdt: "125.50"
                      credit_limit_usdt: "1000.00"
                      credit_used_usdt: "45.30"
                      credit_available: "954.70"
                      total_available: "1080.20"
                      last_payment_at: "2024-01-15T09:30:00Z"
                      updated_at: "2024-01-15T10:30:00Z"
                with_credit_used:
                  summary: 💳 User using credit (low balance)
                  value:
                    success: true
                    request_id: "660f2f88cdf97de899550022"
                    data:
                      user_id: "608f2f88cdf97de899550033"
                      email: "poweruser@example.com"
                      balance_usdt: "5.20"
                      credit_limit_usdt: "500.00"
                      credit_used_usdt: "125.80"
                      credit_available: "374.20"
                      total_available: "379.40"
                      last_payment_at: "2024-01-14T15:20:00Z"
                      updated_at: "2024-01-15T10:35:00Z"
                      warning: "Balance low - consider topping up to avoid using more credit"
                no_credit:
                  summary: 🆕 New user (no credit limit)
                  value:
                    success: true
                    request_id: "770f3f99def98ef900660044"
                    data:
                      user_id: "709f3f99def98ef900660055"
                      email: "newuser@example.com"
                      balance_usdt: "50.00"
                      credit_limit_usdt: "0.00"
                      credit_used_usdt: "0.00"
                      credit_available: "0.00"
                      total_available: "50.00"
                      last_payment_at: "2024-01-15T10:00:00Z"
                      updated_at: "2024-01-15T10:40:00Z"
                      note: "Contact support@awesomefee.com to request credit limit"
        '401':
          $ref: '#/components/responses/Unauthorized'

  /delegation/energy:
    post:
      tags:
        - Delegation
      summary: Delegate energy directly
      description: |
        🎯 **Direct Energy Delegation to TRON Address**

        Instantly delegate energy resources to any TRON address with automatic confirmation
        and balance/credit management.

        💡 **For synchronous confirmation**: Use `/delegation/energy/{id}/wait` endpoint that blocks
        until blockchain confirmation (up to 30 seconds), eliminating the need for manual status polling.

        ---

        ### ✨ Key Features

        | Feature | Description |
        |---------|-------------|
        | **Minimum Amount** | 65,000 energy units |
        | **Duration** | Fixed 1 hour (3600 seconds) |
        | **Operation Mode** | Synchronous with blockchain confirmation |
        | **Payment** | Balance + Credit support |
        | **Verification** | Real-time blockchain monitoring |
        | **Auto-Reclaim** | Resources automatically returned after expiration |

        ---

        ### 📊 Process Flow

        1. **Validation** ✓
           - Validates TRON address format
           - Checks minimum energy requirement (65,000)
           - Verifies address is not already delegated

        2. **Balance Check** 💰
           - Checks user USDT balance
           - If insufficient, automatically uses available credit
           - Fails if total (balance + credit) is insufficient

        3. **Delegation** ⚡
           - Creates delegation order
           - Initiates resource transfer from pool
           - Monitors blockchain for confirmation

        4. **Confirmation** ✅
           - Waits up to 15 seconds for blockchain confirmation
           - Verifies actual energy on target address
           - Returns success with delegation details

        5. **Background Processing** 🔄
           - Transaction hash may be updated asynchronously
           - Balance charged after confirmation
           - Delegation expires after 1 hour
           - Resources automatically reclaimed by system

        ---

        ### 🔄 Transaction Hash Updates

        ⚠️ **Important**: The `tx_hash` field may not be immediately available in the response
        for some delegations. The system updates it in the background.

        **To get the latest transaction hash:**
        ```bash
        GET /api/v1/delegation/status/{delegation_id}
        ```

        The hash is typically available within 10-30 seconds after the initial response.

        ---

        ### 💳 Credit System

        If your balance is insufficient, the system automatically uses your credit limit:

        | Scenario | Behavior |
        |----------|----------|
        | Balance = $5, Cost = $3 | ✅ Uses balance only |
        | Balance = $1, Cost = $3, Credit = $10 | ✅ Uses $1 balance + $2 credit |
        | Balance = $0, Cost = $3, Credit = $10 | ✅ Uses $3 credit |
        | Balance = $1, Cost = $3, Credit = $0 | ❌ Insufficient funds error |

        ---

        ### 🔁 Automatic Resource Reclaim

        After 1 hour, our reclaim worker automatically:
        - Calls `UnDelegateResource` on blockchain
        - Returns energy to resource pool
        - Updates database with reclaim transaction hash
        - Makes resources available for new delegations

        No manual intervention required! ✨

        ---

        ### 💡 Pro Tips

        - **First-time users**: Start with exact 65,000 energy (minimum)
        - **Check status**: Use `/delegation/status/{id}` to track TX hash updates
        - **Balance management**: Top up before hitting credit limit
        - **Multiple delegations**: Wait for confirmation before next delegation to same address

        ---

        ℹ️ For automatic resource calculation based on transaction type, consider using
        **Smart Delegation** (`/api/v1/smart-delegate`) instead.
      operationId: delegateEnergy
      security:
        - ApiKeyAuth: []
        - BearerAuth: []
      x-code-samples:
        - lang: curl
          label: cURL
          source: |
            curl -X POST https://awesomefee.com/api/v1/delegation/energy \
              -H "X-API-Key: ak_live_1234567890abcdef" \
              -H "X-API-Secret: sk_live_abcdefghijklmnop" \
              -H "Content-Type: application/json" \
              -d '{
                "to_address": "TYourAddressHere123456789",
                "amount": 65000
              }'
        - lang: javascript
          label: JavaScript (Node.js)
          source: |
            const response = await fetch('https://awesomefee.com/api/v1/delegation/energy', {
              method: 'POST',
              headers: {
                'X-API-Key': 'ak_live_1234567890abcdef',
                'X-API-Secret': 'sk_live_abcdefghijklmnop',
                'Content-Type': 'application/json'
              },
              body: JSON.stringify({
                to_address: 'TYourAddressHere123456789',
                amount: 65000
              })
            });

            const data = await response.json();
            console.log('Delegation ID:', data.data.id);
            console.log('Status:', data.data.status);

            // Check for TX hash updates
            if (!data.data.tx_hash) {
              console.log('TX hash will be available at:');
              console.log(`GET /api/v1/delegation/status/${data.data.id}`);
            }
        - lang: python
          label: Python
          source: |
            import requests
            import time

            # Create delegation
            response = requests.post(
                'https://awesomefee.com/api/v1/delegation/energy',
                headers={
                    'X-API-Key': 'ak_live_1234567890abcdef',
                    'X-API-Secret': 'sk_live_abcdefghijklmnop',
                    'Content-Type': 'application/json'
                },
                json={
                    'to_address': 'TYourAddressHere123456789',
                    'amount': 65000
                }
            )

            data = response.json()
            delegation_id = data['data']['id']
            print(f"Delegation created: {delegation_id}")
            print(f"Status: {data['data']['status']}")

            # Wait for TX hash if not available
            if not data['data'].get('tx_hash'):
                print("Waiting for TX hash...")
                time.sleep(10)

                status_response = requests.get(
                    f'https://awesomefee.com/api/v1/delegation/status/{delegation_id}',
                    headers={
                        'X-API-Key': 'ak_live_1234567890abcdef',
                        'X-API-Secret': 'sk_live_abcdefghijklmnop'
                    }
                )

                status_data = status_response.json()
                print(f"TX Hash: {status_data['data'].get('tx_hash')}")
        - lang: go
          label: Go
          source: |
            package main

            import (
                "bytes"
                "encoding/json"
                "fmt"
                "net/http"
                "time"
            )

            type DelegationRequest struct {
                ToAddress string `json:"to_address"`
                Amount    int64  `json:"amount"`
            }

            func main() {
                // Create delegation
                reqBody := DelegationRequest{
                    ToAddress: "TYourAddressHere123456789",
                    Amount:    65000,
                }

                jsonData, _ := json.Marshal(reqBody)
                req, _ := http.NewRequest("POST",
                    "https://awesomefee.com/api/v1/delegation/energy",
                    bytes.NewBuffer(jsonData))

                req.Header.Set("X-API-Key", "ak_live_1234567890abcdef")
                req.Header.Set("X-API-Secret", "sk_live_abcdefghijklmnop")
                req.Header.Set("Content-Type", "application/json")

                client := &http.Client{}
                resp, _ := client.Do(req)
                defer resp.Body.Close()

                var result map[string]interface{}
                json.NewDecoder(resp.Body).Decode(&result)

                data := result["data"].(map[string]interface{})
                delegationID := data["id"].(string)

                fmt.Printf("Delegation ID: %s\n", delegationID)
                fmt.Printf("Status: %s\n", data["status"])

                // Check for TX hash after delay if not available
                if data["tx_hash"] == nil {
                    time.Sleep(10 * time.Second)
                    // Check status endpoint for TX hash update
                }
            }
      parameters:
        - $ref: '#/components/parameters/DryRunQuery'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/DelegationRequest'
      responses:
        '201':
          description: Energy delegation confirmed successfully
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/DelegationResponse'
              examples:
                success_with_tx_hash:
                  summary: ✅ Success - TX hash available immediately
                  description: |
                    Delegation confirmed with TX hash available in the response.
                    Balance was sufficient, so no credit used.
                  value:
                    success: true
                    request_id: "550e8400-e29b-41d4-a716-446655440000"
                    data:
                      id: "507f1f77bcf86cd799439011"
                      tx_hash: "a1b2c3d4e5f6789abc123def456789012345678901234567890abcdef123456"
                      status: "confirmed"
                      resource_type: "ENERGY"
                      amount: 65000
                      to_address: "TYourAddressHere123456789"
                      duration: 1
                      expires_at: "2024-01-15T11:30:15Z"
                      price_trx: "14.40"
                      price_usdt: "2.16"
                      balance_before: "5.50"
                      balance_after: "3.34"
                      credit_used: "0.00"
                      created_at: "2024-01-15T10:30:00Z"
                      confirmed_at: "2024-01-15T10:30:15Z"
                success_with_credit:
                  summary: ✅ Success - Used credit (partial balance)
                  description: |
                    Balance was insufficient, so credit was automatically used.
                    Total cost $2.16: $1.00 from balance + $1.16 from credit.
                  value:
                    success: true
                    request_id: "660f2f88cdf97de899550022"
                    data:
                      id: "608f2f88cdf97de899550033"
                      tx_hash: "b2c3d4e5f6789abc234def567890123456789012345678901234567890abcd"
                      status: "confirmed"
                      resource_type: "ENERGY"
                      amount: 65000
                      to_address: "TYourAddressHere123456789"
                      duration: 1
                      expires_at: "2024-01-15T11:35:00Z"
                      price_trx: "14.40"
                      price_usdt: "2.16"
                      balance_before: "1.00"
                      balance_after: "0.00"
                      credit_limit: "100.00"
                      credit_used_before: "5.00"
                      credit_used_after: "6.16"
                      credit_available: "93.84"
                      created_at: "2024-01-15T10:35:00Z"
                      confirmed_at: "2024-01-15T10:35:08Z"
                success_pending_tx:
                  summary: ⏳ Success - TX hash will be available shortly
                  description: |
                    Delegation confirmed on blockchain, but TX hash not yet available.
                    The system is updating it in background - check status endpoint.
                  value:
                    success: true
                    request_id: "770f3f99def98ef900660044"
                    data:
                      id: "709f3f99def98ef900660055"
                      tx_hash: null
                      status: "confirmed"
                      resource_type: "ENERGY"
                      amount: 65000
                      to_address: "TYourAddressHere123456789"
                      duration: 1
                      expires_at: "2024-01-15T11:40:00Z"
                      price_trx: "14.40"
                      price_usdt: "2.16"
                      created_at: "2024-01-15T10:40:00Z"
                      confirmed_at: "2024-01-15T10:40:12Z"
                      instructions:
                        message: "Delegation successful! Transaction hash will be available shortly."
                        next_step: "Check status for TX hash"
                        endpoint: "/api/v1/delegation/status/709f3f99def98ef900660055"
                        estimated_wait: "10-30 seconds"
        '400':
          description: Bad request
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/APIResponse'
              examples:
                invalid_amount:
                  summary: Amount below minimum
                  value:
                    error: true
                    success: false
                    requestID: "550e8400-e29b-41d4-a716-446655440000"
                    errorCode: "INVALID_AMOUNT"
                    errorMessage: "Minimum energy amount is 65,000"
                invalid_address:
                  summary: Invalid TRON address
                  value:
                    error: true
                    success: false
                    requestID: "550e8400-e29b-41d4-a716-446655440001"
                    errorCode: "INVALID_ADDRESS"
                    errorMessage: "Invalid TRON address"
        '401':
          $ref: '#/components/responses/Unauthorized'
        '402':
          description: Insufficient balance
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/APIResponse'
              example:
                error: true
                success: false
                requestID: "550e8400-e29b-41d4-a716-446655440002"
                errorCode: "INSUFFICIENT_BALANCE"
                errorMessage: "Insufficient balance - required: 2.05 USDT, available: 1.50 USDT"
        '408':
          description: Request timeout - delegation not confirmed in time
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/APIResponse'
              example:
                error: true
                success: false
                requestID: "550e8400-e29b-41d4-a716-446655440003"
                errorCode: "TIMEOUT"
                errorMessage: "Delegation failed or timed out - timeout waiting for delegation confirmation"

  /delegation/bandwidth:
    post:
      tags:
        - Delegation
      summary: Delegate bandwidth directly (Internal Pool)
      description: |
        🌐 **Direct Bandwidth Delegation from Internal Pool**

        Delegate bandwidth resources from our internal resource pool to any TRON address.

        💡 **For synchronous confirmation**: Use `/delegation/bandwidth/{id}/wait` endpoint that blocks
        until blockchain confirmation (up to 30 seconds), eliminating the need for manual status polling.

        ---

        ### ✨ Key Features

        | Feature | Description |
        |---------|-------------|
        | **Minimum Amount** | 1,000 bandwidth units |
        | **Duration** | Fixed 1 hour (3600 seconds) |
        | **Source** | Internal pool only (NOT CPF) |
        | **Lock Period** | 0 (allows immediate reclaim) |
        | **Payment** | Balance + Credit support |
        | **Auto-Reclaim** | Resources automatically returned after 1 hour |

        ---

        ### 🔄 Auto-Reclaim Process

        After 1 hour expiration, our reclaim worker automatically:
        1. Calls `UnDelegateResource` on blockchain
        2. Returns bandwidth to internal pool
        3. Updates database with reclaim TX hash
        4. Makes resources available for new delegations

        ---

        ### ⚠️ Important Notes

        - **Internal resources only**: Does NOT use CPF external provider
        - **Minimum enforcement**: Requests below 1,000 units will be rejected
        - **Lock period = 0**: Allows system to reclaim immediately after expiration
        - **Different from energy**: Energy may use CPF for large orders

        ---

        ### 💡 When to Use Bandwidth Delegation

        - TRX transfers (268 bandwidth)
        - USDT transfers (345 bandwidth)
        - Small contract interactions
        - Testing and development

        For complex transactions requiring energy, use `/delegation/energy` instead.
      operationId: delegateBandwidth
      security:
        - ApiKeyAuth: []
        - BearerAuth: []
      x-code-samples:
        - lang: curl
          label: cURL
          source: |
            curl -X POST https://awesomefee.com/api/v1/delegation/bandwidth \
              -H "X-API-Key: ak_live_1234567890abcdef" \
              -H "X-API-Secret: sk_live_abcdefghijklmnop" \
              -H "Content-Type: application/json" \
              -d '{
                "to_address": "TYourAddressHere123456789",
                "amount": 1000
              }'
        - lang: javascript
          label: JavaScript
          source: |
            const response = await fetch('https://awesomefee.com/api/v1/delegation/bandwidth', {
              method: 'POST',
              headers: {
                'X-API-Key': 'ak_live_1234567890abcdef',
                'X-API-Secret': 'sk_live_abcdefghijklmnop',
                'Content-Type': 'application/json'
              },
              body: JSON.stringify({
                to_address: 'TYourAddressHere123456789',
                amount: 1000
              })
            });

            const data = await response.json();
            console.log('Delegation ID:', data.data.id);
            console.log('Status:', data.data.status);
        - lang: python
          label: Python
          source: |
            import requests

            response = requests.post(
                'https://awesomefee.com/api/v1/delegation/bandwidth',
                headers={
                    'X-API-Key': 'ak_live_1234567890abcdef',
                    'X-API-Secret': 'sk_live_abcdefghijklmnop',
                    'Content-Type': 'application/json'
                },
                json={
                    'to_address': 'TYourAddressHere123456789',
                    'amount': 1000
                }
            )

            data = response.json()
            print(f"Delegation ID: {data['data']['id']}")
            print(f"Status: {data['data']['status']}")
            print(f"Cost: {data['data']['price_usdt']} USDT")
      parameters:
        - $ref: '#/components/parameters/DryRunQuery'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - to_address
                - amount
              properties:
                to_address:
                  type: string
                  description: TRON address to receive bandwidth delegation (base58 format)
                  example: "TYourAddressHere123456789"
                  pattern: "^T[a-zA-Z0-9]{33}$"
                amount:
                  type: integer
                  format: int64
                  description: Amount of bandwidth to delegate (minimum 1,000)
                  minimum: 1000
                  example: 1000
      responses:
        '201':
          description: Bandwidth delegation created successfully
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/APIResponse'
                  - type: object
                    properties:
                      data:
                        type: object
                        properties:
                          id:
                            type: string
                            example: "507f1f77bcf86cd799439011"
                          tx_hash:
                            type: string
                            example: "a1b2c3d4e5f6..."
                          status:
                            type: string
                            enum: [pending, confirmed]
                            example: "confirmed"
                          resource_type:
                            type: string
                            example: "BANDWIDTH"
                          amount:
                            type: integer
                            example: 1000
                          to_address:
                            type: string
                            example: "TYourAddressHere123456789"
                          duration:
                            type: integer
                            example: 1
                          expires_at:
                            type: string
                            format: date-time
                          price_trx:
                            type: string
                            example: "1.20"
                          price_usdt:
                            type: string
                            example: "0.18"
                          created_at:
                            type: string
                            format: date-time
                          confirmed_at:
                            type: string
                            format: date-time
              examples:
                success:
                  summary: ✅ Bandwidth delegation successful
                  value:
                    success: true
                    requestID: "550e8400-e29b-41d4-a716-446655440000"
                    data:
                      id: "507f1f77bcf86cd799439011"
                      tx_hash: "a1b2c3d4e5f6789abc123def456789012345678901234567890abcdef123456"
                      status: "confirmed"
                      resource_type: "BANDWIDTH"
                      amount: 1000
                      to_address: "TYourAddressHere123456789"
                      duration: 1
                      expires_at: "2024-01-15T11:30:00Z"
                      price_trx: "1.20"
                      price_usdt: "0.18"
                      balance_before: "5.00"
                      balance_after: "4.82"
                      credit_used: "0.00"
                      created_at: "2024-01-15T10:30:00Z"
                      confirmed_at: "2024-01-15T10:30:05Z"
        '400':
          description: Bad request
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/APIResponse'
              examples:
                invalid_amount:
                  summary: Amount below minimum
                  value:
                    error: true
                    success: false
                    requestID: "550e8400-e29b-41d4-a716-446655440004"
                    errorCode: "INVALID_AMOUNT"
                    errorMessage: "Minimum bandwidth amount is 1,000"
                invalid_address:
                  summary: Invalid TRON address
                  value:
                    error: true
                    success: false
                    requestID: "550e8400-e29b-41d4-a716-446655440005"
                    errorCode: "INVALID_ADDRESS"
                    errorMessage: "Invalid TRON address format"
        '401':
          $ref: '#/components/responses/Unauthorized'
        '402':
          description: Insufficient balance
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/APIResponse'
              example:
                error: true
                success: false
                requestID: "550e8400-e29b-41d4-a716-446655440006"
                errorCode: "INSUFFICIENT_BALANCE"
                errorMessage: "Insufficient balance - required: 0.18 USDT, available: 0.10 USDT"
        '503':
          description: No resources available
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/APIResponse'
              example:
                error: true
                success: false
                requestID: "550e8400-e29b-41d4-a716-446655440007"
                errorCode: "RESOURCE_UNAVAILABLE"
                errorMessage: "No bandwidth resources available in internal pool"

  /delegation/history:
    get:
      tags:
        - Delegation
      summary: Get delegation history
      description: Get delegation history for authenticated user
      operationId: getDelegationHistory
      security:
        - ApiKeyAuth: []
        - BearerAuth: []
      parameters:
        - name: page
          in: query
          schema:
            type: integer
            default: 1
            minimum: 1
        - name: limit
          in: query
          schema:
            type: integer
            default: 20
            minimum: 1
            maximum: 100
        - name: status
          in: query
          schema:
            type: string
            enum: [pending, confirmed, failed, expired]
      responses:
        '200':
          description: Delegation history
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/DelegationHistoryResponse'
        '401':
          $ref: '#/components/responses/Unauthorized'

  /delegation/status/{id}:
    get:
      tags:
        - Delegation
      summary: Get delegation status
      description: |
        Get current status of a specific delegation.

        This endpoint returns the latest information about a delegation, including
        any updates that may have occurred after the initial response. Transaction
        hashes and other details may be populated asynchronously and will be
        available through this endpoint once processing is complete.

        **Use cases:**
        - Check if transaction hash has been updated
        - Monitor delegation confirmation status
        - Retrieve final pricing information
        - Track delegation lifecycle
      operationId: getDelegationStatus
      security:
        - ApiKeyAuth: []
        - BearerAuth: []
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Delegation status
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/DelegationStatusResponse'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '404':
          $ref: '#/components/responses/NotFound'

  /delegation/energy/{id}/wait:
    post:
      tags:
        - Delegation
      summary: Wait for energy delegation confirmation
      description: |
        ⏳ **Blocking Endpoint - Waits for Blockchain Confirmation**

        This endpoint blocks (waits) until the energy delegation is confirmed on the blockchain
        or until timeout (30 seconds). Simplifies client integration by eliminating the need
        for polling.

        ---

        ### 🎯 How It Works

        1. **Retrieve delegation** from database by ID
        2. **Wait for TX hash** (if using CPF, may take a few seconds)
        3. **Poll blockchain** with adaptive intervals
        4. **Return immediately** when confirmed or failed
        5. **Timeout after 30 seconds** if not confirmed

        ---

        ### ⚡ Adaptive Polling

        The endpoint uses intelligent polling intervals:
        - **First check**: 3 seconds
        - **Second check**: 1.5 seconds
        - **Third check**: 0.75 seconds
        - **Subsequent**: Minimum 100ms

        This ensures fast response when blockchain is quick, while not overwhelming it with requests.

        ---

        ### 📊 Response Scenarios

        | Scenario | Status Code | Description |
        |----------|-------------|-------------|
        | ✅ **Success** | 200 | Delegation confirmed on blockchain |
        | ⏰ **Timeout** | 408 | Not confirmed within 30 seconds |
        | ❌ **Failed** | 500 | Delegation failed on blockchain |
        | 🔍 **Not Found** | 404 | Delegation ID doesn't exist |

        ---

        ### 💡 When to Use This Endpoint

        **Use this endpoint when:**
        - You need guaranteed confirmation before proceeding
        - You want to simplify your client code (no polling loop)
        - You're processing transactions sequentially
        - You need to verify energy is available before executing transaction

        **Don't use this if:**
        - You're processing many delegations in parallel (use status endpoint instead)
        - You have your own timeout/retry logic
        - Your application can't handle 30-second blocking calls

        ---

        ### 🔄 Alternative: Manual Polling

        If you prefer manual polling, use:
        ```bash
        GET /api/v1/delegation/status/{id}
        ```

        Poll every 2-5 seconds until `status = "confirmed"` or `"failed"`.

        ---

        ### ⚠️ Important Notes

        - **Blocking call**: Your HTTP client must support 30+ second timeouts
        - **CPF orders**: May take 10-30 seconds to get TX hash first
        - **Internal orders**: Usually confirm within 3-5 seconds
        - **Network issues**: May cause longer wait times or timeouts
      operationId: waitForEnergyConfirmation
      security:
        - ApiKeyAuth: []
        - BearerAuth: []
      x-code-samples:
        - lang: curl
          label: cURL
          source: |
            curl -X POST https://awesomefee.com/api/v1/delegation/energy/507f1f77bcf86cd799439011/wait \
              -H "X-API-Key: ak_live_1234567890abcdef" \
              -H "X-API-Secret: sk_live_abcdefghijklmnop" \
              --max-time 35
        - lang: javascript
          label: JavaScript
          source: |
            // Increase fetch timeout to 35 seconds
            const controller = new AbortController();
            const timeoutId = setTimeout(() => controller.abort(), 35000);

            try {
              const response = await fetch(
                'https://awesomefee.com/api/v1/delegation/energy/507f1f77bcf86cd799439011/wait',
                {
                  method: 'POST',
                  headers: {
                    'X-API-Key': 'ak_live_1234567890abcdef',
                    'X-API-Secret': 'sk_live_abcdefghijklmnop'
                  },
                  signal: controller.signal
                }
              );

              const data = await response.json();

              if (data.success) {
                console.log('✅ Delegation confirmed!');
                console.log('TX Hash:', data.data.tx_hash);
                console.log('Energy delegated:', data.data.amount);
              }
            } catch (error) {
              if (error.name === 'AbortError') {
                console.error('⏰ Request timeout - check status endpoint');
              }
            } finally {
              clearTimeout(timeoutId);
            }
        - lang: python
          label: Python
          source: |
            import requests

            delegation_id = "507f1f77bcf86cd799439011"

            try:
                response = requests.post(
                    f'https://awesomefee.com/api/v1/delegation/energy/{delegation_id}/wait',
                    headers={
                        'X-API-Key': 'ak_live_1234567890abcdef',
                        'X-API-Secret': 'sk_live_abcdefghijklmnop'
                    },
                    timeout=35  # Set timeout to 35 seconds
                )

                data = response.json()

                if data['success']:
                    print(f"✅ Delegation confirmed!")
                    print(f"TX Hash: {data['data']['tx_hash']}")
                    print(f"Status: {data['data']['status']}")
                    print(f"Confirmed at: {data['data']['confirmed_at']}")
                else:
                    print(f"❌ Error: {data['error']['message']}")

            except requests.Timeout:
                print("⏰ Request timeout - delegation may still be pending")
                print(f"Check status: GET /delegation/status/{delegation_id}")
            except requests.RequestException as e:
                print(f"Error: {e}")
      parameters:
        - name: id
          in: path
          required: true
          description: Delegation ID to wait for
          schema:
            type: string
            example: "507f1f77bcf86cd799439011"
      responses:
        '200':
          description: Delegation confirmed successfully
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/APIResponse'
                  - type: object
                    properties:
                      data:
                        type: object
                        properties:
                          id:
                            type: string
                            example: "507f1f77bcf86cd799439011"
                          tx_hash:
                            type: string
                            example: "a1b2c3d4e5f6789abc123def456789012345678901234567890abcdef123456"
                          status:
                            type: string
                            example: "confirmed"
                          resource_type:
                            type: string
                            example: "ENERGY"
                          amount:
                            type: integer
                            example: 65000
                          to_address:
                            type: string
                            example: "TYourAddressHere123456789"
                          duration:
                            type: integer
                            example: 1
                          expires_at:
                            type: string
                            format: date-time
                          price_trx:
                            type: string
                            example: "14.40"
                          price_usdt:
                            type: string
                            example: "2.16"
                          created_at:
                            type: string
                            format: date-time
                          confirmed_at:
                            type: string
                            format: date-time
                          blockchain_confirmed:
                            type: boolean
                            example: true
                          message:
                            type: string
                            example: "Transaction confirmed! You can now execute your transaction."
              example:
                error: false
                success: true
                requestID: "550e8400-e29b-41d4-a716-446655440000"
                data:
                  id: "507f1f77bcf86cd799439011"
                  tx_hash: "a1b2c3d4e5f6789abc123def456789012345678901234567890abcdef123456"
                  status: "confirmed"
                  resource_type: "ENERGY"
                  amount: 65000
                  to_address: "TYourAddressHere123456789"
                  duration: 1
                  expires_at: "2024-01-15T11:30:00Z"
                  price_trx: "14.40"
                  price_usdt: "2.16"
                  created_at: "2024-01-15T10:30:00Z"
                  confirmed_at: "2024-01-15T10:30:08Z"
                  blockchain_confirmed: true
                  message: "Transaction confirmed! You can now execute your transaction."
        '400':
          description: Invalid delegation ID format
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/APIResponse'
              example:
                error: true
                success: false
                requestID: "550e8400-e29b-41d4-a716-446655440008"
                errorCode: "INVALID_ID"
                errorMessage: "Invalid delegation ID format"
        '401':
          $ref: '#/components/responses/Unauthorized'
        '404':
          description: Delegation not found
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/APIResponse'
              example:
                error: true
                success: false
                requestID: "550e8400-e29b-41d4-a716-446655440009"
                errorCode: "NOT_FOUND"
                errorMessage: "Delegation not found"
        '408':
          description: Confirmation timeout
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/APIResponse'
              example:
                success: false
                error: true
                requestID: "550e8400-e29b-41d4-a716-446655440000"
                errorCode: "TIMEOUT"
                errorMessage: "Transaction confirmation timeout - Please check delegation status manually"
                delegation_id: "507f1f77bcf86cd799439011"
        '500':
          description: Delegation failed
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/APIResponse'
              example:
                success: false
                error: true
                requestID: "550e8400-e29b-41d4-a716-446655440000"
                errorCode: "DELEGATION_FAILED"
                errorMessage: "Delegation failed during confirmation"
                delegation_id: "507f1f77bcf86cd799439011"

  /delegation/bandwidth/{id}/wait:
    post:
      tags:
        - Delegation
      summary: Wait for bandwidth delegation confirmation
      description: |
        ⏳ **Blocking Endpoint - Waits for Blockchain Confirmation**

        Identical to the energy wait endpoint, but for bandwidth delegations.
        Blocks until confirmation or 30-second timeout.

        ---

        ### Key Features

        - **Max wait time**: 30 seconds
        - **Adaptive polling**: 3s → 1.5s → 0.75s → min 100ms
        - **Internal pool**: Usually confirms in 3-5 seconds
        - **Returns full details**: Complete delegation info on success

        ---

        For detailed documentation, see `/delegation/energy/{id}/wait` - behavior is identical.
      operationId: waitForBandwidthConfirmation
      security:
        - ApiKeyAuth: []
        - BearerAuth: []
      parameters:
        - name: id
          in: path
          required: true
          description: Delegation ID to wait for
          schema:
            type: string
            example: "507f1f77bcf86cd799439011"
      responses:
        '200':
          description: Delegation confirmed successfully
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/APIResponse'
              example:
                error: false
                success: true
                requestID: "550e8400-e29b-41d4-a716-446655440000"
                data:
                  id: "507f1f77bcf86cd799439011"
                  tx_hash: "a1b2c3d4e5f6789abc123def456789012345678901234567890abcdef123456"
                  status: "confirmed"
                  resource_type: "BANDWIDTH"
                  amount: 1000
                  to_address: "TYourAddressHere123456789"
                  duration: 1
                  expires_at: "2024-01-15T11:30:00Z"
                  price_trx: "1.20"
                  price_usdt: "0.18"
                  created_at: "2024-01-15T10:30:00Z"
                  confirmed_at: "2024-01-15T10:30:05Z"
                  blockchain_confirmed: true
                  message: "Transaction confirmed! You can now execute your transaction."
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '404':
          $ref: '#/components/responses/NotFound'
        '408':
          description: Confirmation timeout
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/APIResponse'
              example:
                success: false
                error: true
                requestID: "550e8400-e29b-41d4-a716-446655440000"
                errorCode: "TIMEOUT"
                errorMessage: "Transaction confirmation timeout - Please check delegation status manually"
                delegation_id: "507f1f77bcf86cd799439011"
        '500':
          description: Delegation failed
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/APIResponse'
              example:
                success: false
                error: true
                requestID: "550e8400-e29b-41d4-a716-446655440000"
                errorCode: "DELEGATION_FAILED"
                errorMessage: "Delegation failed during confirmation"
                delegation_id: "507f1f77bcf86cd799439011"

  /address/activate:
    post:
      tags:
        - Activation
      summary: Activate TRON address
      description: |
        🔓 **Activate Inactive TRON Address**

        Send 0.11 TRX to activate an inactive TRON address on the blockchain. Required before
        the address can receive TRC-20 tokens or participate in smart contracts.

        💡 **For synchronous confirmation**: Use `/address/activate/{id}/wait` endpoint that blocks
        until blockchain confirmation (up to 30 seconds), eliminating the need for manual status polling.

        ---

        ### ✨ Key Features

        | Feature | Description |
        |---------|-------------|
        | **Cost** | 1 TRX flat |
        | **Pre-check** | Validates address not already active |
        | **Wallet Selection** | Uses wallet with >600 staked bandwidth |
        | **Payment** | Balance + Credit support |
        | **Amount** | Fixed 110,000 SUN (0.11 TRX) |

        ---

        ### 💰 Pricing

        - **Fixed cost**: 0.11 TRX (110,000 SUN)
        - **Current USDT**: Approximately $0.033 (varies with TRX price)

        ---

        ### 🔍 Address Validation

        Before sending TRX, the system checks:
        1. **Format valid**: Must be base58 format (T + 33 characters)
        2. **Not activated**: Address must not exist on blockchain
        3. **Wallet available**: Internal wallet must have >600 bandwidth staked

        If address is already active, request returns error immediately (no charge).

        ---

        ### 💳 Balance & Credit

        Activation uses the same balance + credit system as delegations:

        | Scenario | Behavior |
        |----------|----------|
        | Balance ≥ $0.35 | ✅ Uses balance only |
        | Balance < $0.35, has credit | ✅ Uses balance + credit |
        | Total < $0.35 | ❌ Insufficient funds error |

        ---

        ### 📊 Process Flow

        1. **Validate address** format and check if already active
        2. **Find internal wallet** with >600 staked bandwidth
        3. **Calculate cost** (1 TRX in USDT at current rate)
        4. **Check balance** (balance + available credit)
        5. **Send 1 TRX** to target address via blockchain
        6. **Create activation record** in database
        7. **Charge balance** or credit
        8. **Return activation ID** for status tracking

        ---

        ### 🔄 Confirmation

        After activation, use the wait endpoint for confirmation:
        ```bash
        POST /api/v1/address/activate/{id}/wait
        ```

        Or manually check status:
        ```bash
        # Wait 5-10 seconds, then verify on blockchain
        # Address should now be visible on TRONScan
        ```

        ---

        ### 💡 When to Use

        **Activate an address before:**
        - Sending USDT TRC-20 tokens to it
        - Using it as a smart contract recipient
        - Delegating resources to it (some cases)

        **You don't need activation for:**
        - Sending native TRX (activates automatically)
        - Addresses that already received TRX before

        ---

        ### ⚠️ Important Notes

        - **One-time operation**: Once activated, address stays active forever
        - **Instant on-chain**: Address becomes active immediately after TX confirms
        - **Balance remains**: The 1 TRX stays in the address (increases its balance)
        - **Check first**: API automatically checks if already active (no duplicate charge)
      operationId: activateAddress
      security:
        - ApiKeyAuth: []
        - BearerAuth: []
      x-code-samples:
        - lang: curl
          label: cURL
          source: |
            curl -X POST https://awesomefee.com/api/v1/address/activate \
              -H "X-API-Key: ak_live_1234567890abcdef" \
              -H "X-API-Secret: sk_live_abcdefghijklmnop" \
              -H "Content-Type: application/json" \
              -d '{
                "to_address": "TNewAddressToActivate123456789"
              }'
        - lang: javascript
          label: JavaScript
          source: |
            const response = await fetch('https://awesomefee.com/api/v1/address/activate', {
              method: 'POST',
              headers: {
                'X-API-Key': 'ak_live_1234567890abcdef',
                'X-API-Secret': 'sk_live_abcdefghijklmnop',
                'Content-Type': 'application/json'
              },
              body: JSON.stringify({
                to_address: 'TNewAddressToActivate123456789'
              })
            });

            const data = await response.json();

            if (data.success) {
              console.log('✅ Activation initiated!');
              console.log('Activation ID:', data.data.id);
              console.log('TX Hash:', data.data.tx_hash);

              // Wait for confirmation
              // POST /api/v1/address/activate/{data.data.id}/wait
            } else {
              console.error('Error:', data.error.message);
            }
        - lang: python
          label: Python
          source: |
            import requests

            response = requests.post(
                'https://awesomefee.com/api/v1/address/activate',
                headers={
                    'X-API-Key': 'ak_live_1234567890abcdef',
                    'X-API-Secret': 'sk_live_abcdefghijklmnop',
                    'Content-Type': 'application/json'
                },
                json={
                    'to_address': 'TNewAddressToActivate123456789'
                }
            )

            data = response.json()

            if data['success']:
                print(f"✅ Activation initiated!")
                print(f"Activation ID: {data['data']['id']}")
                print(f"TX Hash: {data['data']['tx_hash']}")
                print(f"Cost: {data['data']['cost_usdt']} USDT")

                # Wait for confirmation
                activation_id = data['data']['id']
                # POST /api/v1/address/activate/{activation_id}/wait
            else:
                print(f"❌ Error: {data['error']['message']}")
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - to_address
              properties:
                to_address:
                  type: string
                  description: TRON address to activate (base58 format)
                  example: "TNewAddressToActivate123456789"
                  pattern: "^T[a-zA-Z0-9]{33}$"
      responses:
        '201':
          description: Address activation initiated
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/APIResponse'
                  - type: object
                    properties:
                      data:
                        type: object
                        properties:
                          id:
                            type: string
                            example: "507f1f77bcf86cd799439011"
                          to_address:
                            type: string
                            example: "TNewAddressToActivate123456789"
                          from_address:
                            type: string
                            example: "TInternalWallet123456789"
                          amount:
                            type: integer
                            description: Amount in SUN (1 TRX = 1,000,000 SUN)
                            example: 1000000
                          tx_hash:
                            type: string
                            example: "a1b2c3d4e5f6789abc123def456789012345678901234567890abcdef123456"
                          status:
                            type: string
                            enum: [pending, confirmed]
                            example: "pending"
                          cost_usdt:
                            type: string
                            example: "0.35"
                          balance_before:
                            type: string
                            example: "5.00"
                          balance_after:
                            type: string
                            example: "4.85"
                          created_at:
                            type: string
                            format: date-time
              example:
                error: false
                success: true
                requestID: "550e8400-e29b-41d4-a716-446655440000"
                data:
                  id: "507f1f77bcf86cd799439011"
                  to_address: "TNewAddressToActivate123456789"
                  from_address: "TInternalWallet123456789"
                  amount: 1000000
                  tx_hash: "a1b2c3d4e5f6789abc123def456789012345678901234567890abcdef123456"
                  status: "pending"
                  cost_usdt: "0.35"
                  balance_before: "5.00"
                  balance_after: "4.85"
                  credit_used: "0.00"
                  created_at: "2024-01-15T10:30:00Z"
        '400':
          description: Bad request
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/APIResponse'
              examples:
                already_active:
                  summary: Address already active
                  value:
                    success: false
                    error: true
                    requestID: "550e8400-e29b-41d4-a716-446655440000"
                    errorCode: "ADDRESS_ALREADY_ACTIVE"
                    errorMessage: "Address is already activated"
                invalid_address:
                  summary: Invalid address format
                  value:
                    success: false
                    error: true
                    requestID: "550e8400-e29b-41d4-a716-446655440001"
                    errorCode: "INVALID_ADDRESS"
                    errorMessage: "Invalid TRON address format"
        '401':
          $ref: '#/components/responses/Unauthorized'
        '402':
          description: Insufficient balance
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/APIResponse'
              example:
                success: false
                error: true
                requestID: "550e8400-e29b-41d4-a716-446655440002"
                errorCode: "INSUFFICIENT_BALANCE"
                errorMessage: "Insufficient balance for activation - required: 0.15 USDT, available: 0.10 USDT"
        '503':
          description: No wallet available
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/APIResponse'
              example:
                success: false
                error: true
                requestID: "550e8400-e29b-41d4-a716-446655440003"
                errorCode: "NO_WALLET_AVAILABLE"
                errorMessage: "No internal wallet available with sufficient bandwidth"

  /address/activate/{id}/wait:
    post:
      tags:
        - Activation
      summary: Wait for address activation confirmation
      description: |
        ⏳ **Blocking Endpoint - Waits for Activation Confirmation**

        Blocks until the address activation is confirmed on the blockchain or timeout (30 seconds).
        Identical behavior to delegation wait endpoints.

        ---

        ### Key Features

        - **Max wait time**: 30 seconds
        - **Adaptive polling**: 3s → 1.5s → 0.75s → min 100ms
        - **Quick confirmation**: Usually 3-5 seconds
        - **Returns full details**: Complete activation info on success

        ---

        For detailed documentation, see `/delegation/energy/{id}/wait` - behavior is identical.
      operationId: waitForActivationConfirmation
      security:
        - ApiKeyAuth: []
        - BearerAuth: []
      parameters:
        - name: id
          in: path
          required: true
          description: Activation ID to wait for
          schema:
            type: string
            example: "507f1f77bcf86cd799439011"
      responses:
        '200':
          description: Activation confirmed successfully
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/APIResponse'
              example:
                error: false
                success: true
                requestID: "550e8400-e29b-41d4-a716-446655440000"
                data:
                  id: "507f1f77bcf86cd799439011"
                  to_address: "TNewAddressToActivate123456789"
                  from_address: "TInternalWallet123456789"
                  amount: 1000000
                  tx_hash: "a1b2c3d4e5f6789abc123def456789012345678901234567890abcdef123456"
                  status: "confirmed"
                  cost_usdt: "0.35"
                  balance_before: "5.00"
                  balance_after: "4.85"
                  created_at: "2024-01-15T10:30:00Z"
                  confirmed_at: "2024-01-15T10:30:05Z"
                  blockchain_confirmed: true
                  message: "Address activated successfully!"
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '404':
          $ref: '#/components/responses/NotFound'
        '408':
          description: Confirmation timeout
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/APIResponse'
              example:
                success: false
                error: true
                requestID: "550e8400-e29b-41d4-a716-446655440000"
                errorCode: "TIMEOUT"
                errorMessage: "Activation confirmation timeout - Please check activation manually on TRONScan"
                activation_id: "507f1f77bcf86cd799439011"
        '500':
          description: Activation failed
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/APIResponse'
              example:
                success: false
                error: true
                requestID: "550e8400-e29b-41d4-a716-446655440001"
                errorCode: "ACTIVATION_FAILED"
                errorMessage: "Activation failed on blockchain"
                activation_id: "507f1f77bcf86cd799439011"

  /subscription-plans:
    get:
      tags:
        - Subscription Plans
      summary: Get available subscription plans
      description: |
        📋 **Get Available Subscription Plans (Public)**

        Returns all active subscription plans for Mate Address auto-management service.
        Plans define default resource thresholds, pricing markups, and usage limits.

        **No authentication required** - public endpoint for browsing available options.

        ---

        ### Plan Types

        | Type | Description | Markup Range |
        |------|-------------|--------------|
        | **Basic** | Entry-level plan for personal use | 15-20% |
        | **Standard** | Most popular for regular users | 20-25% |
        | **Pro** | High-volume addresses | 25-30% |
        | **Enterprise** | Custom plans with volume discounts | 30-35% |

        ---

        ### What Plans Include

        Each plan specifies:
        - **Default Thresholds**: Minimum levels that trigger auto top-ups
        - **Default Targets**: Levels to restore resources to
        - **Markup Percentages**: Pricing markup for each resource type
        - **Usage Limits**: Max top-ups per day/month (0 = unlimited)
        - **Monthly Fee**: Subscription cost (most plans are pay-as-you-go)

        ---

        ### Choosing a Plan

        When creating a Mate Address:
        - **If user has custom plan** (User.SubscriptionPlanID set) → Uses that plan
        - **Otherwise** → Uses default plan from config
        - **Thresholds can be customized** per address (within plan limits)
      operationId: getSubscriptionPlans
      responses:
        '200':
          description: List of available subscription plans
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/APIResponse'
                  - type: object
                    properties:
                      data:
                        type: array
                        items:
                          $ref: '#/components/schemas/SubscriptionPlan'
                      count:
                        type: integer
                        description: Total number of plans
                        example: 4
              example:
                success: true
                requestID: "550e8400-e29b-41d4-a716-446655440000"
                data:
                  - id: "64f1a2b3c4d5e6f7g8h9i0j1"
                    name: "Basic Plan"
                    type: "basic"
                    description: "Entry-level automatic resource management"
                    default_min_energy: 30000
                    default_min_bandwidth: 200
                    default_min_trx: 3000000
                    default_target_energy: 100000
                    default_target_bandwidth: 600
                    default_target_trx: 8000000
                    energy_markup_percent: 20.0
                    bandwidth_markup_percent: 15.0
                    trx_markup_percent: 10.0
                    max_top_ups_per_day: 0
                    max_top_ups_per_month: 0
                    monthly_fee_usdt: "0.00"
                    is_default: false
                  - id: "64f1a2b3c4d5e6f7g8h9i0j2"
                    name: "Standard Plan"
                    type: "standard"
                    description: "Most popular plan for regular users"
                    default_min_energy: 50000
                    default_target_energy: 200000
                    energy_markup_percent: 25.0
                    is_default: true
                count: 2

  /mate-addresses:
    post:
      tags:
        - Mate Addresses
      summary: Create new mate address
      description: |
        ✨ **Create Mate Address for Automatic Resource Management**

        Add a TRON address to automatic monitoring system. The system will continuously monitor
        the address and automatically top-up Energy, Bandwidth, and TRX when resources fall
        below configured thresholds.

        ---

        ### 🔑 Key Features

        - **Auto Plan Selection**: Uses User.SubscriptionPlanID or config defaults
        - **No subscription_plan_id required**: System determines plan automatically
        - **All thresholds optional**: Uses plan defaults if not specified
        - **Automatic activation**: If address is inactive, activates it (costs ~1.268 TRX)
        - **Duplicate prevention**: Same address cannot be added twice for same user
        - **Validation**: Ensures min < target for all resources

        ---

        ### 📊 How It Works

        1. **Create mate address** with this endpoint
        2. **System validates** address format and checks for duplicates
        3. **Determines subscription plan** (user's custom plan or config defaults)
        4. **Checks if address active** on blockchain
        5. **Activates if needed** (sends 1.268 TRX, updates balance)
        6. **Starts monitoring** address in mate-monitor service
        7. **Auto top-ups** trigger when resources drop below minimums

        ---

        ### ⚙️ Resource Thresholds

        All threshold fields are **optional**. If not provided, plan defaults are used:

        | Field | Description | Example (Basic Plan) |
        |-------|-------------|---------------------|
        | `min_energy` | Trigger level | 30,000 |
        | `target_energy` | Restore to level | 100,000 |
        | `min_bandwidth` | Trigger level | 200 |
        | `target_bandwidth` | Restore to level | 600 |
        | `min_trx` | Trigger level (SUN) | 3,000,000 (3 TRX) |
        | `target_trx` | Restore to level (SUN) | 8,000,000 (8 TRX) |

        **Validation rules:**
        - All values must be ≥ 0
        - min < target for each resource
        - Cannot exceed plan limits

        ---

        ### 💰 Activation Cost

        If address is not activated on blockchain:
        - **Cost**: ~1.268 TRX (1.0 TRX activation + 268 bandwidth)
        - **Charged from**: User balance (with credit support)
        - **Automatic**: No additional action required
        - **One-time**: Address stays activated forever

        ---

        ### 💡 Best Practices

        **For beginners:**
        - Start with plan defaults (don't specify thresholds)
        - Monitor for a few days
        - Adjust based on actual usage

        **For power users:**
        - Set higher minimums to reduce top-up frequency
        - Target should be 3-5x higher than minimum
        - Monitor total_cost_usdt in top-up history
      operationId: createMateAddress
      security:
        - ApiKeyAuth: []
        - BearerAuth: []
      x-code-samples:
        - lang: curl
          label: cURL - Simple
          source: |
            curl -X POST https://awesomefee.com/api/v1/mate-addresses \
              -H "X-API-Key: ak_live_1234567890abcdef" \
              -H "X-API-Secret: sk_live_abcdefghijklmnop" \
              -H "Content-Type: application/json" \
              -d '{
                "address": "TYourTronAddress123456789",
                "alias": "My Main Wallet"
              }'
        - lang: curl
          label: cURL - Custom Thresholds
          source: |
            curl -X POST https://awesomefee.com/api/v1/mate-addresses \
              -H "X-API-Key: ak_live_1234567890abcdef" \
              -H "X-API-Secret: sk_live_abcdefghijklmnop" \
              -H "Content-Type: application/json" \
              -d '{
                "address": "TYourTronAddress123456789",
                "alias": "High-Volume Wallet",
                "min_energy": 70000,
                "target_energy": 200000,
                "min_bandwidth": 400,
                "target_bandwidth": 1000
              }'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateMateAddressRequest'
      responses:
        '201':
          description: Mate address created successfully
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/MateAddressResponse'
              examples:
                created_inactive:
                  summary: ✅ Created and activated
                  description: Address was not active, so system activated it automatically
                  value:
                    success: true
                    requestID: "550e8400-e29b-41d4-a716-446655440000"
                    data:
                      id: "64f1a2b3c4d5e6f7g8h9i0j1"
                      address: "TYourTronAddress123456789"
                      alias: "My Main Wallet"
                      status: "active"
                      min_energy: 30000
                      target_energy: 100000
                      min_bandwidth: 200
                      target_bandwidth: 600
                      min_trx: 3000000
                      target_trx: 8000000
                      is_activated: true
                      activation_cost_usdt: "0.44"
                      created_at: "2025-10-06T10:30:00Z"
                created_active:
                  summary: ✅ Created (already active)
                  value:
                    success: true
                    requestID: "550e8400-e29b-41d4-a716-446655440001"
                    data:
                      id: "64f1a2b3c4d5e6f7g8h9i0j2"
                      address: "TActiveAddress123456789"
                      status: "active"
                      is_activated: true
                      created_at: "2025-10-06T10:35:00Z"
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '409':
          description: Duplicate address
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/APIResponse'
              example:
                success: false
                error: "address already exists for this user"
                requestID: "550e8400-e29b-41d4-a716-446655440000"
    get:
      tags:
        - Mate Addresses
      summary: Get all mate addresses
      description: |
        📋 **Get All Mate Addresses for Current User**

        Returns all mate addresses owned by the authenticated user with current resource states.
      operationId: getMateAddresses
      security:
        - ApiKeyAuth: []
        - BearerAuth: []
      responses:
        '200':
          description: List of mate addresses
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/APIResponse'
                  - type: object
                    properties:
                      data:
                        type: array
                        items:
                          $ref: '#/components/schemas/MateAddress'
                      count:
                        type: integer
              example:
                success: true
                requestID: "550e8400-e29b-41d4-a716-446655440000"
                data:
                  - id: "64f1a2b3c4d5e6f7g8h9i0j1"
                    address: "TAddress1..."
                    alias: "Main Wallet"
                    status: "active"
                    current_energy: 85000
                    current_bandwidth: 450
                    current_trx: 6500000
                    min_energy: 50000
                    target_energy: 200000
                    total_top_ups: 5
                    total_cost_usdt: "12.50"
                    last_top_up_at: "2025-10-05T14:20:00Z"
                count: 1
        '401':
          $ref: '#/components/responses/Unauthorized'

  /mate-addresses/{id}:
    get:
      tags:
        - Mate Addresses
      summary: Get mate address details
      description: Get detailed information about a specific mate address
      operationId: getMateAddress
      security:
        - ApiKeyAuth: []
        - BearerAuth: []
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Mate address details
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/MateAddressResponse'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '404':
          $ref: '#/components/responses/NotFound'
    put:
      tags:
        - Mate Addresses
      summary: Update mate address settings
      description: |
        ✏️ **Update Mate Address Configuration**

        Update resource thresholds or monitoring status. Changes take effect immediately.

        **What can be updated:**
        - Resource thresholds (min/target for energy, bandwidth, TRX)
        - Monitoring status (active/paused/inactive)

        **Validation:**
        - min < target for all resources
        - Values cannot exceed plan limits
        - Cannot update other users' addresses
      operationId: updateMateAddress
      security:
        - ApiKeyAuth: []
        - BearerAuth: []
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/UpdateMateAddressRequest'
      responses:
        '200':
          description: Mate address updated successfully
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/MateAddressResponse'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '404':
          $ref: '#/components/responses/NotFound'
    delete:
      tags:
        - Mate Addresses
      summary: Delete mate address
      description: |
        🗑️ **Delete Mate Address and Stop Monitoring**

        Permanently removes mate address from monitoring system. This action:
        - Stops all automatic monitoring
        - Prevents future top-ups
        - Removes address from database
        - Cannot be undone

        ⚠️ **Note**: The TRON address itself is not affected - only monitoring stops.
      operationId: deleteMateAddress
      security:
        - ApiKeyAuth: []
        - BearerAuth: []
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Mate address deleted successfully
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/APIResponse'
              example:
                success: true
                requestID: "550e8400-e29b-41d4-a716-446655440000"
                data:
                  message: "Mate address deleted successfully"
        '401':
          $ref: '#/components/responses/Unauthorized'
        '404':
          $ref: '#/components/responses/NotFound'

  /mate-addresses/{id}/topups:
    get:
      tags:
        - Mate Addresses
      summary: Get top-up history
      description: |
        📊 **Get Top-Up History for Mate Address**

        Returns complete history of all automatic resource top-ups for this address.
        Includes cost breakdowns, amounts, and transaction hashes.

        **Useful for:**
        - Monitoring costs over time
        - Verifying automatic top-ups occurred
        - Tracking resource usage patterns
        - Accounting and reconciliation
      operationId: getMateAddressTopUps
      security:
        - ApiKeyAuth: []
        - BearerAuth: []
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
        - name: limit
          in: query
          schema:
            type: integer
            default: 50
            maximum: 200
        - name: offset
          in: query
          schema:
            type: integer
            default: 0
      responses:
        '200':
          description: Top-up history
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/APIResponse'
                  - type: object
                    properties:
                      data:
                        type: array
                        items:
                          $ref: '#/components/schemas/ResourceTopUp'
                      count:
                        type: integer
                      total_cost_usdt:
                        type: string
                        description: Total cost of all top-ups
              example:
                success: true
                requestID: "550e8400-e29b-41d4-a716-446655440000"
                data:
                  - id: "64f1a2b3c4d5e6f7g8h9i0j1"
                    type: "energy"
                    energy_amount: 150000
                    base_cost_usdt: "2.50"
                    markup_usdt: "0.50"
                    total_cost_usdt: "3.00"
                    markup_percent: 20.0
                    tx_hash: "abc123..."
                    status: "completed"
                    created_at: "2025-10-06T10:30:00Z"
                count: 5
                total_cost_usdt: "15.00"
        '401':
          $ref: '#/components/responses/Unauthorized'
        '404':
          $ref: '#/components/responses/NotFound'

components:
  securitySchemes:
    ApiKeyAuth:
      type: apiKey
      in: header
      name: X-API-Key
      description: |
        **API Key Authentication (Recommended)**

        Required headers:
        - `X-API-Key`: Your unique API key
        - `X-API-Secret`: Your API secret key

        **How to get API credentials:**
        1. Contact support@awesomefee.com with your organization details
        2. Receive your API credentials via secure channel
        3. Store credentials securely (never commit to git)

        **Example usage:**
        ```bash
        curl -X GET https://awesomefee.com/api/v1/health \
          -H "X-API-Key: ak_live_1234567890abcdef" \
          -H "X-API-Secret: sk_live_abcdefghijklmnop"
        ```

        ⚠️ **Security Note**: Always use HTTPS in production. Never expose your API secret in client-side code.
      x-default: "ak_live_YOUR_API_KEY_HERE"
    BearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT
      description: |
        **JWT Token Authentication (Alternative)**

        Use JWT tokens for temporary access or when API keys are not suitable.

        **Example usage:**
        ```bash
        curl -X GET https://awesomefee.com/api/v1/health \
          -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
        ```

  parameters:
    DryRunQuery:
      name: dry_run
      in: query
      description: Execute in dry-run mode (no real transactions)
      schema:
        type: boolean
        default: false
    DryRunHeader:
      name: X-Dry-Run
      in: header
      description: Execute in dry-run mode (alternative to query parameter)
      schema:
        type: string
        enum: ["true", "false"]

  schemas:
    APIResponse:
      type: object
      required:
        - success
        - requestID
      properties:
        success:
          type: boolean
          description: Whether the request was successful
        error:
          type: boolean
          description: Whether an error occurred (true for errors, false for success)
        requestID:
          type: string
          description: Unique request identifier for tracking
        errorCode:
          type: string
          description: Machine-readable error code (only present when error = true)
          example: "INSUFFICIENT_BALANCE"
        errorMessage:
          type: string
          description: Human-readable error message with details (only present when error = true)
          example: "Insufficient balance - required: 2.05 USDT, available: 1.50 USDT"
        data:
          type: object
          description: Response data (varies by endpoint, only present when success = true)
        meta:
          $ref: '#/components/schemas/Meta'

    Meta:
      type: object
      properties:
        dry_run:
          type: boolean
          description: Whether this was a dry-run request
        timestamp:
          type: integer
          format: int64
          description: Unix timestamp
        version:
          type: string
          description: API version
          example: "v1"
        duration_ms:
          type: integer
          format: int64
          description: Request processing time in milliseconds

    HealthResponse:
      allOf:
        - $ref: '#/components/schemas/APIResponse'
        - type: object
          properties:
            data:
              type: object
              properties:
                status:
                  type: string
                  example: "healthy"
                timestamp:
                  type: string
                  format: date-time
                version:
                  type: string
                  example: "1.1.0"
                services:
                  type: object
                  properties:
                    api:
                      type: string
                      example: "running"
                    mongodb:
                      type: string
                      example: "connected"
                    monitor:
                      type: string
                      example: "active"

    PriceResponse:
      allOf:
        - $ref: '#/components/schemas/APIResponse'
        - type: object
          properties:
            data:
              type: object
              properties:
                energy:
                  $ref: '#/components/schemas/ResourcePrice'
                bandwidth:
                  $ref: '#/components/schemas/ResourcePrice'
                trx:
                  $ref: '#/components/schemas/TRXPrice'

    ResourcePrice:
      type: object
      properties:
        price_per_unit:
          type: string
          description: Price per unit in TRX
          example: "0.00021"
        price_per_1000:
          type: string
          description: Price per 1000 units in TRX
          example: "0.21"
        minimum_order:
          type: integer
          format: int64
          example: 65000
        available_capacity:
          type: integer
          format: int64
          example: 10000000

    TRXPrice:
      type: object
      properties:
        usd:
          type: string
          example: "0.35"
        eur:
          type: string
          example: "0.14"

    SmartDelegateRequest:
      type: object
      required:
        - sender_address
        - receiver_address
        - currency
        - amount
      properties:
        sender_address:
          type: string
          description: Sender TRON address
          example: "TRoSQSowmRdNZHPRQxgGMEYbZCxvf4Jvja"
        receiver_address:
          type: string
          description: Receiver TRON address
          example: "TXph11MGRajJiNppcSyn3HDQqmxXHH84K2"
        currency:
          type: string
          enum: [TRX, USDT]
          description: Transaction currency
        amount:
          type: string
          description: Amount to transfer
          example: "100.5"
        auto_calculate:
          type: boolean
          description: Automatically calculate optimal resources
          default: true
        delegation_period:
          type: integer
          description: Delegation period in hours
          default: 1
        priority:
          type: string
          enum: [normal, high]
          default: normal
          description: Processing priority

    SmartDelegateResponse:
      allOf:
        - $ref: '#/components/schemas/APIResponse'
        - type: object
          properties:
            data:
              type: object
              properties:
                session_id:
                  type: string
                  description: Smart delegation session ID
                status:
                  type: string
                  enum: [pending, in_progress, completed, failed]
                steps:
                  type: array
                  items:
                    $ref: '#/components/schemas/DelegationStep'
                total_cost:
                  type: string
                  description: Total cost in TRX
                total_cost_usdt:
                  type: string
                  description: Total cost in USDT
                savings:
                  type: string
                  description: Amount saved vs traditional transaction
                estimated_duration:
                  type: integer
                  description: Estimated duration in seconds

    AddressDetails:
      type: object
      properties:
        address:
          type: string
          example: "TRoSQSowmRdNZHPRQxgGMEYbZCxvf4Jvja"
        is_active:
          type: boolean
          example: false
        balance_trx:
          type: string
          example: "0.000000"
        balance_usdt:
          type: string
          example: "0.000000"
        energy_available:
          type: integer
          example: 0
        bandwidth_available:
          type: integer
          example: 0

    ResourcesRequired:
      type: object
      properties:
        energy:
          type: integer
          example: 130000
        bandwidth:
          type: integer
          example: 345
        activation_required:
          type: boolean
          example: false
        description:
          type: string
          example: "USDT transfer requires 130,000 Energy (first transfer to receiver)"

    DelegationStep:
      type: object
      properties:
        step:
          type: string
          description: Step identifier
        status:
          type: string
          enum: [pending, in_progress, completed, failed]
        description:
          type: string
        tx_hash:
          type: string
          description: Transaction hash (if applicable)
        completed_at:
          type: string
          format: date-time

    TransactionCalculationRequest:
      type: object
      required:
        - address_from
        - address_to
        - currency
        - amount
      properties:
        address_from:
          type: string
          description: Sender address
        address_to:
          type: string
          description: Receiver address
        currency:
          type: string
          enum: [TRX, USDT]
        amount:
          type: string
          description: Amount to transfer

    TransactionCalculationResponse:
      allOf:
        - $ref: '#/components/schemas/APIResponse'
        - type: object
          properties:
            data:
              type: object
              properties:
                energy_required:
                  type: integer
                  format: int64
                bandwidth_required:
                  type: integer
                  format: int64
                activation_fee:
                  type: string
                  description: Activation fee if receiver is new (in TRX)
                total_cost_trx:
                  type: string
                total_cost_usdt:
                  type: string
                breakdown:
                  type: object
                  description: Detailed cost breakdown

    WebhookConfigResponse:
      allOf:
        - $ref: '#/components/schemas/APIResponse'
        - type: object
          properties:
            data:
              type: object
              properties:
                webhook:
                  $ref: '#/components/schemas/WebhookConfig'
                available_events:
                  type: array
                  items:
                    type: string
                  example: ["payment.received", "payment.confirmed", "delegation.confirmed"]

    WebhookConfig:
      type: object
      properties:
        url:
          type: string
          description: Webhook endpoint URL
          example: "https://your-domain.com/webhook"
        events:
          type: array
          items:
            type: string
          description: List of subscribed events
        active:
          type: boolean
          description: Whether webhooks are enabled
        max_retries:
          type: integer
          description: Maximum retry attempts
          default: 3
        timeout_sec:
          type: integer
          description: Request timeout in seconds
          default: 10
        last_success:
          type: string
          format: date-time
          description: Last successful webhook delivery
        last_failure:
          type: string
          format: date-time
          description: Last failed webhook delivery
        failure_count:
          type: integer
          description: Consecutive failure count

    WebhookUpdateRequest:
      type: object
      required:
        - url
        - events
      properties:
        url:
          type: string
          format: uri
          description: Webhook endpoint URL
        events:
          type: array
          items:
            type: string
            enum:
              - payment.received
              - payment.confirmed
              - payment.failed
              - delegation.created
              - delegation.confirmed
              - delegation.expired
              - delegation.failed
              - resource.delegated
              - resource.undelegated
              - transaction.created
              - transaction.confirmed
              - transaction.failed
          minItems: 1
        active:
          type: boolean
          default: true
        max_retries:
          type: integer
          minimum: 0
          maximum: 10
          default: 3
        timeout_sec:
          type: integer
          minimum: 1
          maximum: 60
          default: 10

    WebhookUpdateResponse:
      allOf:
        - $ref: '#/components/schemas/APIResponse'
        - type: object
          properties:
            data:
              type: object
              properties:
                message:
                  type: string
                  example: "Webhook configuration updated"
                webhook:
                  allOf:
                    - $ref: '#/components/schemas/WebhookConfig'
                    - type: object
                      properties:
                        secret:
                          type: string
                          description: Webhook secret for HMAC verification (shown only once!)
                          example: "whs_a1b2c3d4e5f6..."

    WebhookTestRequest:
      type: object
      required:
        - event_type
      properties:
        event_type:
          type: string
          description: Type of event to send
          example: "payment.received"
        data:
          type: object
          description: Custom test data (optional)
          example:
            amount: "100"
            currency: "USDT"
            test: true

    WebhookEventsResponse:
      allOf:
        - $ref: '#/components/schemas/APIResponse'
        - type: object
          properties:
            data:
              type: object
              properties:
                events:
                  type: array
                  items:
                    $ref: '#/components/schemas/WebhookEvent'
                count:
                  type: integer
                skip:
                  type: integer
                limit:
                  type: integer

    WebhookEvent:
      type: object
      properties:
        event_id:
          type: string
          description: Unique event ID
        type:
          type: string
          description: Event type
        timestamp:
          type: string
          format: date-time
        data:
          type: object
          description: Event-specific data
        requestID:
          type: string
          description: Related API request ID

    WebhookPayload:
      type: object
      description: Payload sent to webhook endpoints
      properties:
        event_id:
          type: string
          description: Unique event identifier
        type:
          type: string
          description: Event type
        timestamp:
          type: string
          format: date-time
        data:
          type: object
          description: Event-specific data
        requestID:
          type: string
          description: Related API request ID
        metadata:
          type: object
          description: Additional metadata

    DelegationRequest:
      type: object
      required:
        - to_address
        - amount
      properties:
        to_address:
          type: string
          description: TRON address to receive energy delegation (base58 format)
          example: "TYourAddressHere123456789"
          pattern: "^T[a-zA-Z0-9]{33}$"
        amount:
          type: integer
          format: int64
          description: Amount of energy to delegate (minimum 65,000)
          minimum: 65000
          example: 65000

    UserBalanceResponse:
      allOf:
        - $ref: '#/components/schemas/APIResponse'
        - type: object
          properties:
            data:
              type: object
              properties:
                user_id:
                  type: string
                  description: Unique user identifier
                  example: "507f1f77bcf86cd799439011"
                email:
                  type: string
                  description: User email address
                  example: "user@example.com"
                balance_usdt:
                  type: string
                  description: Current available balance in USDT
                  example: "125.50"
                credit_limit_usdt:
                  type: string
                  description: Maximum credit limit in USDT
                  example: "1000.00"
                credit_used_usdt:
                  type: string
                  description: Currently used credit amount in USDT
                  example: "45.30"
                credit_available:
                  type: string
                  description: Available credit (limit - used) in USDT
                  example: "954.70"
                total_available:
                  type: string
                  description: Total funds available (balance + available credit) in USDT
                  example: "1080.20"
                last_payment_at:
                  type: string
                  format: date-time
                  description: Timestamp of last payment received
                  example: "2024-01-15T09:30:00Z"
                updated_at:
                  type: string
                  format: date-time
                  description: Timestamp of last balance update
                  example: "2024-01-15T10:30:00Z"

    DelegationResponse:
      allOf:
        - $ref: '#/components/schemas/APIResponse'
        - type: object
          properties:
            data:
              type: object
              properties:
                id:
                  type: string
                  description: Unique delegation identifier
                  example: "507f1f77bcf86cd799439011"
                tx_hash:
                  type: string
                  description: Blockchain transaction hash (may be updated asynchronously)
                  example: "0x123abc..."
                  nullable: true
                status:
                  type: string
                  description: Delegation status
                  enum: [pending, confirmed, failed]
                  example: "confirmed"
                resource_type:
                  type: string
                  description: Type of resource delegated
                  enum: [ENERGY]
                  example: "ENERGY"
                amount:
                  type: integer
                  format: int64
                  description: Actual amount of energy delegated
                  example: 65000
                to_address:
                  type: string
                  description: Recipient address
                  example: "TYourAddressHere123456789"
                duration:
                  type: integer
                  description: Duration in hours (always 1)
                  example: 1
                price_trx:
                  type: string
                  description: Price paid in TRX
                  example: "13.65"
                price_usdt:
                  type: string
                  description: Price paid in USDT
                  example: "2.05"
                created_at:
                  type: string
                  format: date-time
                  description: When delegation was created
                confirmed_at:
                  type: string
                  format: date-time
                  description: When delegation was confirmed on blockchain

    SmartDelegateStatusResponse:
      allOf:
        - $ref: '#/components/schemas/APIResponse'

    PoolStatisticsResponse:
      allOf:
        - $ref: '#/components/schemas/APIResponse'
        - type: object
          properties:
            data:
              type: object
              properties:
                total_addresses:
                  type: integer
                active_addresses:
                  type: integer
                total_energy:
                  type: integer
                  format: int64
                available_energy:
                  type: integer
                  format: int64
                total_bandwidth:
                  type: integer
                  format: int64
                available_bandwidth:
                  type: integer
                  format: int64
                delegations_last_24h:
                  type: integer
                success_rate:
                  type: number
                  format: float

    DelegationHistoryResponse:
      allOf:
        - $ref: '#/components/schemas/APIResponse'

    DelegationStatusResponse:
      allOf:
        - $ref: '#/components/schemas/APIResponse'

    CreateMateAddressRequest:
      type: object
      required:
        - address
      properties:
        address:
          type: string
          description: TRON address to monitor (base58 format starting with 'T')
          pattern: "^T[a-zA-Z0-9]{33}$"
          example: "TYourTronAddress123456789"
        alias:
          type: string
          description: Human-readable name for the address
          maxLength: 100
          example: "My Main Wallet"
        min_energy:
          type: integer
          format: int64
          description: Minimum energy level (triggers top-up when below). Uses plan default if not specified.
          minimum: 0
          example: 50000
        min_bandwidth:
          type: integer
          format: int64
          description: Minimum bandwidth level (triggers top-up when below). Uses plan default if not specified.
          minimum: 0
          example: 300
        min_trx:
          type: integer
          format: int64
          description: Minimum TRX balance in SUN (triggers top-up when below). Uses plan default if not specified.
          minimum: 0
          example: 5000000
        target_energy:
          type: integer
          format: int64
          description: Target energy level to restore to during top-up. Must be greater than min_energy.
          minimum: 0
          example: 200000
        target_bandwidth:
          type: integer
          format: int64
          description: Target bandwidth level to restore to during top-up. Must be greater than min_bandwidth.
          minimum: 0
          example: 1000
        target_trx:
          type: integer
          format: int64
          description: Target TRX balance in SUN to restore to during top-up. Must be greater than min_trx.
          minimum: 0
          example: 10000000

    UpdateMateAddressRequest:
      type: object
      properties:
        min_energy:
          type: integer
          format: int64
          minimum: 0
        min_bandwidth:
          type: integer
          format: int64
          minimum: 0
        min_trx:
          type: integer
          format: int64
          minimum: 0
        target_energy:
          type: integer
          format: int64
          minimum: 0
        target_bandwidth:
          type: integer
          format: int64
          minimum: 0
        target_trx:
          type: integer
          format: int64
          minimum: 0
        status:
          type: string
          enum: [active, paused, inactive]
          description: Monitoring status

    MateAddress:
      type: object
      properties:
        id:
          type: string
          description: Unique mate address identifier
          example: "64f1a2b3c4d5e6f7g8h9i0j1"
        user_id:
          type: string
          description: Owner user ID
        address:
          type: string
          description: TRON address (base58 format)
          example: "TYourTronAddress123456789"
        address_hex:
          type: string
          description: TRON address (hex format)
        alias:
          type: string
          description: Human-readable name
        subscription_plan_id:
          type: string
          description: Subscription plan ID (null if using default from config)
          nullable: true
        min_energy:
          type: integer
          format: int64
        min_bandwidth:
          type: integer
          format: int64
        min_trx:
          type: integer
          format: int64
        target_energy:
          type: integer
          format: int64
        target_bandwidth:
          type: integer
          format: int64
        target_trx:
          type: integer
          format: int64
        current_energy:
          type: integer
          format: int64
          description: Current energy level on blockchain
        current_bandwidth:
          type: integer
          format: int64
          description: Current bandwidth level on blockchain
        current_trx:
          type: integer
          format: int64
          description: Current TRX balance in SUN
        last_checked_at:
          type: string
          format: date-time
          description: Last time resources were checked
        total_top_ups:
          type: integer
          description: Total number of top-ups performed
        total_cost_usdt:
          type: string
          description: Total cost of all top-ups in USDT
        last_top_up_at:
          type: string
          format: date-time
          nullable: true
        status:
          type: string
          enum: [active, paused, inactive]
        is_activated:
          type: boolean
          description: Whether TRON address is activated on blockchain
        activated_at:
          type: string
          format: date-time
          nullable: true
        activation_tx_hash:
          type: string
          nullable: true
        needs_top_up:
          type: boolean
        top_up_in_progress:
          type: boolean
        created_at:
          type: string
          format: date-time
        updated_at:
          type: string
          format: date-time

    MateAddressResponse:
      allOf:
        - $ref: '#/components/schemas/APIResponse'
        - type: object
          properties:
            data:
              $ref: '#/components/schemas/MateAddress'

    SubscriptionPlan:
      type: object
      properties:
        id:
          type: string
          example: "64f1a2b3c4d5e6f7g8h9i0j1"
        name:
          type: string
          example: "Standard Plan"
        type:
          type: string
          enum: [basic, standard, pro, enterprise, custom]
          example: "standard"
        description:
          type: string
          example: "Most popular plan for regular users"
        default_min_energy:
          type: integer
          format: int64
          example: 50000
        default_min_bandwidth:
          type: integer
          format: int64
          example: 300
        default_min_trx:
          type: integer
          format: int64
          example: 5000000
        default_target_energy:
          type: integer
          format: int64
          example: 200000
        default_target_bandwidth:
          type: integer
          format: int64
          example: 1000
        default_target_trx:
          type: integer
          format: int64
          example: 10000000
        energy_markup_percent:
          type: number
          format: float
          description: Markup percentage for energy delegation
          example: 25.0
        bandwidth_markup_percent:
          type: number
          format: float
          description: Markup percentage for bandwidth delegation
          example: 20.0
        trx_markup_percent:
          type: number
          format: float
          description: Markup percentage for TRX transfers
          example: 15.0
        max_top_ups_per_day:
          type: integer
          description: Maximum top-ups allowed per day (0 = unlimited)
          example: 0
        max_top_ups_per_month:
          type: integer
          description: Maximum top-ups allowed per month (0 = unlimited)
          example: 0
        monthly_fee_usdt:
          type: string
          description: Monthly subscription fee in USDT
          example: "0.00"
        is_active:
          type: boolean
        is_default:
          type: boolean
          description: Whether this is the default plan for new users
        created_at:
          type: string
          format: date-time
        updated_at:
          type: string
          format: date-time

    ResourceTopUp:
      type: object
      description: Record of an automatic resource top-up for a mate address
      properties:
        id:
          type: string
          example: "64f1a2b3c4d5e6f7g8h9i0j1"
        mate_address_id:
          type: string
        user_id:
          type: string
        mate_address:
          type: string
          description: TRON address that was topped up
        type:
          type: string
          enum: [energy, bandwidth, trx, mixed, activation]
          description: Type of resource that was topped up
        source:
          type: string
          enum: [internal, catfee, transfer]
          description: Source of the resources
        energy_amount:
          type: integer
          format: int64
          description: Amount of energy delegated (0 if not applicable)
        bandwidth_amount:
          type: integer
          format: int64
          description: Amount of bandwidth delegated (0 if not applicable)
        trx_amount:
          type: integer
          format: int64
          description: Amount of TRX transferred in SUN (0 if not applicable)
        energy_before:
          type: integer
          format: int64
          description: Energy level before top-up
        energy_after:
          type: integer
          format: int64
          description: Energy level after top-up
        bandwidth_before:
          type: integer
          format: int64
        bandwidth_after:
          type: integer
          format: int64
        trx_before:
          type: integer
          format: int64
        trx_after:
          type: integer
          format: int64
        base_cost_usdt:
          type: string
          description: Base cost before markup
          example: "2.50"
        markup_usdt:
          type: string
          description: Markup amount
          example: "0.50"
        total_cost_usdt:
          type: string
          description: Total cost charged to user
          example: "3.00"
        markup_percent:
          type: number
          format: float
          description: Markup percentage applied
          example: 20.0
        balance_before:
          type: string
          description: User balance before top-up
        balance_after:
          type: string
          description: User balance after top-up
        tx_hash:
          type: string
          description: Blockchain transaction hash
          nullable: true
        status:
          type: string
          enum: [pending, processing, completed, failed]
        trigger:
          type: string
          description: What triggered this top-up
          example: "auto_monitor"
        created_at:
          type: string
          format: date-time
        started_at:
          type: string
          format: date-time
          nullable: true
        completed_at:
          type: string
          format: date-time
          nullable: true

  responses:
    BadRequest:
      description: Bad request
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/APIResponse'
          example:
            success: false
            error: true
            requestID: "550e8400-e29b-41d4-a716-446655440000"
            errorCode: "BAD_REQUEST"
            errorMessage: "Invalid request parameters - field 'amount' must be greater than 0"

    Unauthorized:
      description: Unauthorized
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/APIResponse'
          example:
            success: false
            error: true
            requestID: "550e8400-e29b-41d4-a716-446655440000"
            errorCode: "UNAUTHORIZED"
            errorMessage: "Authentication required"

    NotFound:
      description: Resource not found
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/APIResponse'
          example:
            success: false
            error: true
            requestID: "550e8400-e29b-41d4-a716-446655440000"
            errorCode: "NOT_FOUND"
            errorMessage: "Resource not found"

    InternalError:
      description: Internal server error
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/APIResponse'
          example:
            success: false
            requestID: "550e8400-e29b-41d4-a716-446655440000"
            error: true
            errorCode: "INTERNAL_ERROR"
            errorMessage: "An internal error occurred"