# Indexing and Querying Data

### **Introduction**

Studio Blockchain’s advanced indexing and querying system ensures developers have seamless access to blockchain data for dApp development, analytics, and transaction monitoring. Leveraging a PostgreSQL-backed indexer and comprehensive REST APIs, Studio Blockchain provides real-time and historical data with robust performance enhancements. This guide walks you through the capabilities of the indexer and how to query data effectively.

***

### **1. Key Features of the Studio Blockchain Indexer**

1. **Dual Connection System:**
   * Supports both HTTP and WebSocket connections for data access.
   * Real-time block processing ensures minimal latency.
2. **Optimized Data Storage:**
   * Uses PostgreSQL for efficient storage and retrieval of blockchain data.
   * Provides advanced features like pagination and filtering.
3. **Comprehensive REST API:**
   * Endpoints to access blocks, transactions, contracts, and addresses.
   * Historical and real-time data available.
4. **Scalability and Performance:**
   * AI-enhanced query optimization ensures fast response times.
   * Designed to handle high transaction throughput without bottlenecks.

***

### **2. Setting Up the Indexer**

The Studio Blockchain indexer requires PostgreSQL as a backend. Follow these steps to set it up:

#### **Step 1: Install PostgreSQL**

1. Install PostgreSQL on your machine:

   ```bash
   bashCopy codesudo apt update
   sudo apt install postgresql postgresql-contrib
   ```
2. Start the PostgreSQL service:

   ```bash
   bashCopy codesudo service postgresql start
   ```

#### **Step 2: Configure the Database**

1. Create a new PostgreSQL user and database:

   ```bash
   bashCopy codesudo -u postgres createuser studio-indexer
   sudo -u postgres createdb studio-db --owner=studio-indexer
   ```
2. Set a password for the `studio-indexer` user:

   ```bash
   bashCopy codesudo -u postgres psql
   ALTER USER "studio-indexer" WITH PASSWORD 'yourpassword';
   \q
   ```

#### **Step 3: Run the Indexer**

Clone the Studio Blockchain repository if not done already:

```bash
bashCopy codegit clone https://github.com/studio-blockchain/studio-blockchain.git
cd studio-blockchain
```

Run the indexer:

```bash
bashCopy code./build/bin/studio-indexer --config=config/indexer-config.yaml
```

Ensure the configuration file (`indexer-config.yaml`) is correctly set up with your database credentials and network RPC.

***

### **3. REST API Endpoints**

Studio Blockchain’s REST API provides developers with extensive capabilities for querying blockchain data. Below are the key endpoints:

#### **Block Data**

* **Get Latest Block:**

  ```bash
  bashCopy codeGET /blocks/latest
  ```

  Example Response:

  ```json
  jsonCopy code{
    "number": 123456,
    "hash": "0xabc123...",
    "timestamp": "2024-01-01T12:34:56Z",
    "transactions": 30,
    "miner": "0xValidatorAddress"
  }
  ```
* **Get Block by Number:**

  ```bash
  bashCopy codeGET /blocks/:number
  ```

  Replace `:number` with the block number (e.g., `/blocks/100`).

***

#### **Transaction Data**

* **Get Latest Transactions:**

  ```bash
  bashCopy codeGET /transactions/latest
  ```

  Example Response:

  ```json
  jsonCopy code[
    {
      "hash": "0xtransaction123...",
      "from": "0xSenderAddress",
      "to": "0xRecipientAddress",
      "value": "1000000000000000000",
      "gasUsed": 21000
    }
  ]
  ```
* **Get Transaction by Hash:**

  ```bash
  bashCopy codeGET /transactions/:hash
  ```

  Replace `:hash` with the transaction hash.

***

#### **Address Activity**

* **Get Transactions for an Address:**

  ```bash
  bashCopy codeGET /address/:address/transactions
  ```

  Replace `:address` with the wallet address.

***

#### **Contract Verification**

* **Submit Contract for Verification:**

  ```bash
  bashCopy codePOST /v2/contract/verify
  ```

  Example Payload:

  ```json
  jsonCopy code{
    "address": "0xContractAddress",
    "sourceCode": "pragma solidity ^0.8.0; contract MyContract { ... }",
    "compilerVersion": "0.8.19",
    "evmVersion": "PARIS",
    "constructorArgs": "..."
  }
  ```

***

#### **Health Check**

* **Check Indexer Health:**

  ```bash
  bashCopy codeGET /health
  ```

  Example Response:

  ```json
  jsonCopy code{
    "status": "healthy",
    "lastIndexedBlock": 123456,
    "connectedPeers": 10
  }
  ```

***

### **4. WebSocket for Real-Time Updates**

Studio Blockchain’s WebSocket endpoint provides developers with real-time data feeds.

#### **Subscription Example:**

```javascript
javascriptCopy codeconst WebSocket = require('ws');
const ws = new WebSocket('wss://ws.studio-blockchain.com');

ws.on('open', function open() {
    ws.send(JSON.stringify({
        jsonrpc: '2.0',
        method: 'eth_subscribe',
        params: ['newBlockHeaders'],
        id: 1
    }));
});

ws.on('message', function message(data) {
    console.log('New Block:', data);
});
```

***

### **5. Querying Gas Usage Metrics**

Access block-level gas metrics via the API:

* **Get Gas Usage Statistics:**

  ```bash
  bashCopy codeGET /blocks/:number/gas
  ```

  Example Response:

  ```json
  jsonCopy code{
    "gasUsed": 12000000,
    "gasLimit": 15000000,
    "baseFeePerGas": "20000000000"
  }
  ```

***

### **6. Best Practices**

1. **Efficient Querying:**
   * Use pagination for endpoints that return large datasets (e.g., `/blocks`).
   * Subscribe to WebSocket events for real-time updates instead of polling.
2. **Indexing Custom Data:**
   * Extend the indexer to store application-specific data (e.g., NFT metadata or custom token statistics).
3. **Monitoring Indexer Health:**
   * Regularly check the `/health` endpoint for service status and performance metrics.

***

### **Next Steps**

Now that you understand how to index and query data:

1. Proceed to explore **Ecosystem Development** for insights into Studio Blockchain’s broader dApp ecosystem.
2. Set up real-time data analytics pipelines using WebSocket subscriptions and the REST API.
3. Contribute to Studio Blockchain by extending the indexer or creating new tools for developers.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.studio-blockchain.com/developers/indexing-and-querying-data.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
