> ## Documentation Index
> Fetch the complete documentation index at: https://docs.believe.app/llms.txt
> Use this file to discover all available pages before exploring further.

# Get Current Batch

> This endpoint retrieves the currently active flywheel batch for a specific token, if one exists.

## Overview

The Get Current Batch endpoint retrieves the currently active flywheel batch for a specified token. This is useful for checking if there's already an ongoing batch operation before creating a new one, or for getting the status of the current batch without needing to know the specific batch ID.

Returns `null` if no current batch exists for the token.

## Authentication

This endpoint requires API key authentication. The API key must have either `burn` or `airdrop` scopes.

To authenticate, provide your API key in the `x-believe-api-key` request header.

Example:

```
x-believe-api-key: your_actual_api_key_here
```

## Rate Limiting

Requests to this endpoint are rate-limited to 10 requests per second per API key.

## Request

This endpoint requires no request body. The current batch is determined based on the authenticated API key.

### Example Request

```
GET /v1/flywheel/batch/current
x-believe-api-key: your_actual_api_key_here
```

## Response Body

On success, the API returns either:

* A JSON object containing the current batch information (same structure as `/batch/{batchId}`)
* `null` if no current batch exists for the token

### Example Response (Current Batch Exists)

```json theme={null}
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "flywheelId": "flywheel_abc123",
  "tokenId": "token_def456",
  "mintAddress": "So11111111111111111111111111111111111111112",
  "status": "FINALIZED",
  "batchIndex": "42",
  "vaultIndex": "0",
  "multisig": "9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM",
  "vaultAddress": "HF8dF3nXy48op4dgdNPc86vqG79JTta7wvEbAWW8NXKv",
  "initResult": {
    "total": 3,
    "totalSuccessful": 3,
    "totalFailed": 0,
    "successfulExecutions": [
      {
        "bundleId": "a1b2c3d4e5f6789012345678901234567890abcdef",
        "txHashes": ["3M9kLp8sVxT2YhF6bE4CfN7ZvB5TdP1JqJ8LoX2GbM4aC9eR", "7Q6nMjKsEgC8WfYpR2CeL5ZhB3TdN9PqJ4LoX7GbV1bF2sC"]
      }
    ],
    "batchIndex": 42
  },
  "dateCreated": "2025-01-27T12:00:00.000Z",
  "dateUpdated": "2025-01-27T12:05:00.000Z"
}
```

### Example Response (No Current Batch)

```json theme={null}
null
```

## Batch Status Values

When a current batch exists, it will have one of these status values:

| Status               | Description                                                            |
| -------------------- | ---------------------------------------------------------------------- |
| `AVAILABLE_TO_QUEUE` | Batch has been created but not yet finalized for execution.            |
| `FINALIZED`          | Batch has been finalized and is ready for execution approval.          |
| `EXECUTED`           | Batch has been successfully executed (may still be "current" briefly). |
| `FAILED`             | Batch execution failed.                                                |

## Use Cases

1. **Pre-Creation Check**: Verify no active batch exists before creating a new one.

2. **Status Monitoring**: Get the current batch status without needing to store batch IDs.

3. **Workflow Management**: Determine if your application should wait for current operations to complete.

4. **Error Recovery**: Check if a batch is stuck in a particular state and needs intervention.

5. **Dashboard Display**: Show users the current state of their token's flywheel operations.

## Integration Patterns

### Before Creating New Batch

```javascript theme={null}
// Check for current batch before creating new one
const currentBatch = await getCurrentBatch(tokenId);

if (currentBatch) {
  if (currentBatch.status === "FINALIZED") {
    // Wait for execution or execute it
    console.log("Batch ready for execution:", currentBatch.id);
  } else if (currentBatch.status === "EXECUTED") {
    // Previous batch completed, safe to create new one
    await createNewBatch(pipelines);
  } else {
    // Batch still in progress
    console.log("Batch in progress:", currentBatch.status);
  }
} else {
  // No current batch, safe to create new one
  await createNewBatch(pipelines);
}
```

### Status Monitoring Loop

```javascript theme={null}
// Monitor current batch until completion
let currentBatch;
do {
  currentBatch = await getCurrentBatch(tokenId);
  if (currentBatch && currentBatch.status === "FINALIZED") {
    console.log("Batch ready for execution");
    break;
  }
  await sleep(5000); // Wait 5 seconds
} while (currentBatch && currentBatch.status !== "EXECUTED");
```

## Error Codes

The current batch endpoint can return specific error codes.

| Error Code                 | Status | Description                                   |
| -------------------------- | ------ | --------------------------------------------- |
| `ERR_BATCH_CURRENT_FAILED` | 500    | Failed to retrieve current batch information. |

### Example Error Response

```json theme={null}
{
  "error": "ERR_BATCH_CURRENT_FAILED",
  "message": "Database connection failed"
}
```

## Important Notes

1. **Null Response**: A `null` response is normal and indicates no current batch exists for the token.

2. **Current Definition**: A batch is considered "current" if it's the most recent batch that hasn't reached a final state.

3. **State Transitions**: Once a batch reaches `EXECUTED` or `FAILED` status, it may no longer be considered "current" depending on your implementation.

4. **Race Conditions**: In high-frequency applications, check for current batch immediately before creating new ones to avoid conflicts.

5. **Token Scoping**: This endpoint only returns batches for the specific token ID provided, ensuring proper isolation between different tokens.


## OpenAPI

````yaml GET /v1/flywheel/batch/current
openapi: 3.1.0
info:
  title: OpenAPI Plant Store
  description: >-
    A sample API that uses a plant store as an example to demonstrate features
    in the OpenAPI specification
  license:
    name: MIT
  version: 1.0.0
servers:
  - url: https://public.believe.app
security:
  - bearerAuth: []
paths:
  /v1/flywheel/batch/current:
    get:
      tags:
        - Flywheel
      summary: Get Current Batch
      description: >-
        This endpoint retrieves the currently active flywheel batch for a
        specific token, if one exists.
      responses:
        '200':
          description: Current batch information or null if no current batch exists.
          content:
            application/json:
              schema:
                oneOf:
                  - $ref: '#/components/schemas/BatchStatusResponse'
                  - type: 'null'
        '401':
          description: Unauthorized - API key is missing or invalid.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '500':
          description: Internal Server Error - Failed to retrieve current batch.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
      security:
        - apiKeyAuth: []
components:
  schemas:
    BatchStatusResponse:
      type: object
      required:
        - id
        - flywheelId
        - tokenId
        - mintAddress
        - status
        - batchIndex
        - vaultIndex
        - multisig
        - vaultAddress
        - dateCreated
        - dateUpdated
      properties:
        id:
          type: string
          description: The unique batch identifier (UUID).
        flywheelId:
          type: string
          description: The flywheel this batch belongs to.
        tokenId:
          type: string
          description: The token ID associated with this batch.
        mintAddress:
          type: string
          description: The Solana mint address for the token.
        status:
          type: string
          enum:
            - AVAILABLE_TO_QUEUE
            - FINALIZED
            - EXECUTED
            - FAILED
          description: Current batch status.
        batchIndex:
          type: string
          description: The multisig batch index used for execution.
        vaultIndex:
          type: string
          description: The vault index within the multisig.
        multisig:
          type: string
          description: The multisig wallet address.
        vaultAddress:
          type: string
          description: The vault address for token operations.
        initResult:
          $ref: '#/components/schemas/InitResult'
          description: Results from the batch initialization process (optional).
        executeResult:
          $ref: '#/components/schemas/ExecutionResult'
          description: Results from the batch execution process (optional).
        dateCreated:
          type: string
          format: date-time
          description: ISO 8601 timestamp when the batch was created.
        dateUpdated:
          type: string
          format: date-time
          description: ISO 8601 timestamp when the batch was last updated.
    Error:
      required:
        - error
        - message
      type: object
      properties:
        error:
          type: integer
          format: int32
        message:
          type: string
    InitResult:
      type: object
      required:
        - total
        - totalSuccessful
        - totalFailed
        - successfulExecutions
        - batchIndex
      properties:
        total:
          type: number
          description: Total number of setup transactions processed.
        totalSuccessful:
          type: number
          description: Number of setup transactions that succeeded.
        totalFailed:
          type: number
          description: Number of setup transactions that failed.
        successfulExecutions:
          type: array
          description: Array of successful bundle executions during setup.
          items:
            $ref: '#/components/schemas/SuccessfulExecution'
        failedTxMsg:
          type: string
          description: Error message if setup failed (optional).
        batchIndex:
          type: number
          description: The batch index used in the multisig.
    ExecutionResult:
      type: object
      required:
        - total
        - totalSuccessful
        - totalFailed
        - successfulExecutions
      properties:
        total:
          type: number
          description: Total number of pipeline transactions in the batch.
        totalSuccessful:
          type: number
          description: Number of pipeline transactions that executed successfully.
        totalFailed:
          type: number
          description: Number of pipeline transactions that failed to execute.
        successfulExecutions:
          type: array
          description: Array of successful bundle executions with their details.
          items:
            $ref: '#/components/schemas/SuccessfulExecution'
        failedOnTransactionIndex:
          type: number
          description: Transaction index where failure occurred (optional).
        failedStartTransactionIndex:
          type: number
          description: Starting transaction index of the failed batch (optional).
        failedTxMsg:
          type: string
          description: Error message describing the failure (optional).
    SuccessfulExecution:
      type: object
      required:
        - bundleId
        - txHashes
      properties:
        bundleId:
          type: string
          description: Jito bundle ID (hex string) for this group of transactions.
        txHashes:
          type: array
          description: >-
            Array of Solana transaction signatures (base58 strings) for executed
            transactions.
          items:
            type: string
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
    apiKeyAuth:
      type: apiKey
      in: header
      name: x-believe-api-key

````