# BakerDAO Subgraph

The BakerDAO subgraph indexes all activity relating to `BREAD`. It tracks loans, collateral, liquidations, and user incentive weights. If you need to query loan data, calculate user rewards, or analyze protocol metrics, this is your go-to data source.

```
https://api.goldsky.com/api/public/project_clpx84oel0al201r78jsl0r3i/subgraphs/bakerdao-subgraph/1.0.9/gn
```

### Key Concepts

#### User Weights & Incentives

The protocol calculates user weights based on a simple formula: your borrowed amount multiplied by the square root of days remaining on your loan. This rewards longer-term positions more heavily than short-term ones.

```
userWeight = borrowedTimesSqrtDays / totalBorrowedTimesSqrtDays
```

Only loans created after block `5623025` are eligible for incentives.

#### Snapshot System

The subgraph creates automatic snapshots to preserve historical data:

* **User snapshots**: Created every hour for all active users
* **Global snapshots**: Created every 4 hours for protocol-wide metrics
* **Real-time data**: Query main entities directly for current state

These snapshots are essential for reward calculations and historical analysis.

### Core Entities

#### User

Tracks individual user data and loan history.

```
type User {
  id: ID!                           # User's wallet address
  activeLoan: Loan                  # Current active loan (if any)
  totalLoansCreated: BigInt!        # Lifetime loan count
  totalCollateralProvided: BigInt!  # Total collateral ever provided
  totalBorrowed: BigInt!            # Total ever borrowed
  userWeight: BigDecimal!           # Current incentive weight (0-1)
  lastUpdated: BigInt!              # Last activity timestamp
}
```

#### Loan

Individual loan positions with time-based calculations.

```
type Loan {
  id: ID!                        # User's wallet address
  user: User!                    # Link to user
  collateral: BigInt!            # Current collateral amount
  borrowed: BigInt!              # Current borrowed amount
  endDate: BigInt!               # When loan expires
  numberOfDays: BigInt!          # Original loan duration
  isActive: Boolean!             # Whether loan is still active
  loanType: String!              # "BORROW" or "LOOP"
  daysRemaining: BigInt!         # Days until expiration
  borrowedTimesSqrtDays: BigInt! # Borrowed * √(days remaining)
  borrowedTimesDays: BigInt!     # Borrowed * days remaining
  isEligibleForIncentives: Boolean!
}
```

#### UserLoanSnapshot

Hourly snapshots of user loan data for historical analysis.

```
type UserLoanSnapshot {
  id: ID!                        # "userAddress-hourTimestamp"
  user: User!
  timestamp: BigInt!             # Snapshot time
  period: BigInt!                # timestamp / 3600 (hour number)
  hasActiveLoan: Boolean!        # Whether user had active loan
  collateral: BigInt!            # Collateral at snapshot time
  borrowed: BigInt!              # Borrowed amount at snapshot time
  daysRemaining: BigInt!         # Days remaining at snapshot time
  borrowedTimesSqrtDays: BigInt! # Weight calculation component
  borrowedTimesDays: BigInt!     # Weight calculation component
  userWeight: BigDecimal!        # Weight at snapshot time
  isEligibleForIncentives: Boolean!
}
```

#### GlobalStats

Protocol-wide statistics (single entity with ID "global\_v2").

```
type GlobalStats {
  currentActiveLoans: BigInt!           # Number of active loans
  currentTotalCollateral: BigInt!       # Total collateral locked
  currentTotalBorrowed: BigInt!         # Total amount borrowed
  totalBorrowedTimesSqrtDays: BigInt!   # Sum of all user weights
  totalLiquidations: BigInt!            # Lifetime liquidations
  incentiveEligibilityBlock: BigInt!    # Block when incentives started
  lastToastDate: BigInt!                # Last liquidation processing date
  lastUpdated: BigInt!                  # Last time stats were updated
  lastUserSnapshotHour: BigInt!         # Tracking for hourly snapshots
  lastGlobalSnapshotPeriod: BigInt!     # Tracking for 4-hour snapshots
}
```

#### ActiveUser

Tracks which users currently have active loans.

```
type ActiveUser {
  id: ID!                   # User's wallet address
  user: User!               # Link to user entity
  addedAt: BigInt!          # When user became active
  lastValidated: BigInt!    # Last time status was confirmed
}
```

### Common Queries

#### Get Current User Weights and Positions

```
query GetAllUserWeights($block: Int) {
  users(
    where: { userWeight_gt: "0" }
    block: { number: $block }
    first: 1000
  ) {
    id
    userWeight
    activeLoan {
      collateral
      borrowed
      daysRemaining
      borrowedTimesSqrtDays
      isEligibleForIncentives
    }
    totalCollateralProvided
    totalBorrowed
  }
}
```

#### Get Protocol Statistics

```
query GetProtocolStats($block: Int) {
  globalStats(id: "global_v2", block: { number: $block }) {
    currentActiveLoans
    currentTotalCollateral
    currentTotalBorrowed
    totalBorrowedTimesSqrtDays
    totalLiquidations
  }
}
```

#### Get Active Loans

```
query GetActiveLoans($block: Int) {
  loans(
    where: { isActive: true }
    block: { number: $block }
    first: 1000
  ) {
    id
    user {
      id
      userWeight
    }
    collateral
    borrowed
    daysRemaining
    loanType
    isEligibleForIncentives
  }
}
```

#### Historical User Weight Analysis

```javascript
query GetUserWeightHistory($userId: String!, $fromTime: Int!, $toTime: Int!) {
  userLoanSnapshots(
    where: { 
      user: $userId
      timestamp_gte: $fromTime
      timestamp_lte: $toTime 
    }
    orderBy: timestamp
    orderDirection: asc
  ) {
    timestamp
    userWeight
    borrowed
    collateral
    daysRemaining
    hasActiveLoan
  }
}
```


---

# 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://documentation.bakerdao.io/bakerdao-subgraph.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.
