# Get Borrow/Deposit Amount for an User

Drift supports both lending and borrowing tokens and assets. You can query deposits, and borrowed amounts via the `spotPositions` field in <mark style="color:yellow;">drift\_User</mark> account. If token amount is greater than 0, it is a deposit. If less than zero, it is a borrow.

You can directly copy paste this code on <mark style="color:yellow;">replit</mark> and see it in action.

#### Fetch Borrowed/Lending Amounts for a user, based on user authority and market index

{% tabs %}
{% tab title="Code Snippet" %}
{% code overflow="wrap" %}

```javascript
const BN = require("bn.js");
const SHYFT_API_KEY = "YOUR-API-KEY";

function divCeil(a, b) {
  const quotient = a.div(b);

  const remainder = a.mod(b);

  if (remainder.gt(ZERO)) {
    return quotient.add(ONE);
  } else {
    return quotient;
  }
}

function getTokenAmount(
  balanceAmount,
  spotMarket, 
  balanceType, 
) {
  const precisionDecrease = new BN(10).pow(new BN(19 - spotMarket.decimals));

  if (balanceType === "deposit") {
    return balanceAmount
      .mul(spotMarket.cumulativeDepositInterest)
      .div(precisionDecrease);
  } else {
    return divCeil(
      balanceAmount.mul(spotMarket.cumulativeBorrowInterest),
      precisionDecrease,
    );
  }
}

async function getSpotMarketDataByGraphQl(marketIndex) {
  
  const operationsDoc = `
      query MyQuery {
        drift_SpotMarket(where: {marketIndex: {_eq: ${marketIndex}}}) {
          decimals
          cumulativeDepositInterest
          cumulativeBorrowInterest
          marketIndex
        }
      }
    `; //graphQl query
  const result = await fetch(
    `https://programs.shyft.to/v0/graphql/accounts?api_key=${SHYFT_API_KEY}&network=mainnet-beta`, //SHYFT's GQL endpoint
    {
      method: "POST",
      body: JSON.stringify({
        query: operationsDoc,
        variables: {},
        operationName: "MyQuery",
      }),
    },
  );

  return await result.json();
}

async function getDataByGraphQl(authAddress) {
 
  const operationsDoc = `
      query MyQuery {
        drift_User(
          limit: 1
          where: {authority: {_eq: ${authAddress}}}
        ) {
          pubkey
          authority
          spotPositions
        }
      }
    `; //graphQl query
  const result = await fetch(
    `https://programs.shyft.to/v0/graphql/accounts?api_key=${SHYFT_API_KEY}&network=mainnet-beta`, //SHYFT's GQL endpoint
    {
      method: "POST",
      body: JSON.stringify({
        query: operationsDoc,
        variables: {},
        operationName: "MyQuery",
      }),
    },
  );

  return await result.json();
}

async function getLendingBorrowByauthority(authorityPubkey, marketIndex) {
  const { errors, data } = await getDataByGraphQl(authorityPubkey);

  if (errors) {
    console.error(errors);
    console.log("Some Error Occured, please check your API key or try again");
  }

  const marketIndexData = data.drift_User[0].spotPositions.find(
    (mIndex) => mIndex.marketIndex === marketIndex,
  );
  if (!marketIndexData) {
    console.log("No market Index data found");
    return 0;
  }
  

  const marketIndexDetails = await getSpotMarketDataByGraphQl(marketIndex);

  if (marketIndexDetails.errors) {
    console.error(errors);
    console.log(
      "Some Error Occured in Market Index Details, please check your API key or try again",
    );
  }
  

  const tokenAmountValues = {
    ...marketIndexDetails.data.drift_SpotMarket[0],
    decimals: new BN(marketIndexDetails.data.drift_SpotMarket[0].decimals),
    cumulativeDepositInterest: new BN(
      marketIndexDetails.data.drift_SpotMarket[0].cumulativeDepositInterest,
    ),
    cumulativeBorrowInterest: new BN(
      marketIndexDetails.data.drift_SpotMarket[0].cumulativeBorrowInterest,
    ),
  };
  console.log("Token Amount Values: ", tokenAmountValues);
  
  const finalTokenValues = getTokenAmount(
    new BN(marketIndexData.scaledBalance),
    tokenAmountValues,
    Object.keys(marketIndexData.balanceType)[0],
  );
  
  let signedBorrowOrDeposit;
  if(Object.keys(marketIndexData.balanceType)[0] === "deposit")
    signedBorrowOrDeposit = finalTokenValues;
  else 
    signedBorrowOrDeposit = finalTokenValues.abs().neg();

  console.log("\nType: ",Object.keys(marketIndexData.balanceType)[0]);
  console.log("Value: ", signedBorrowOrDeposit.toNumber())
}
getLendingBorrowByauthority("BgGAVukE1j8JDsvXwcnneuoN8LTpDuiRUtYfQWociQjL", 17); //accepts authority address and market index


```

{% endcode %}
{% endtab %}

{% tab title="Response" %}

```json
Token Amount Values:  {
  decimals: <BN: 9>,
  cumulativeDepositInterest: <BN: 2540cc18e>,
  cumulativeBorrowInterest: <BN: 25460d69f>,
  marketIndex: 17
}

Type:  deposit
Value:  6364108649 //positive number also indicates it is a deposit
```

{% endtab %}
{% endtabs %}


---

# 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.shyft.to/solana-indexers/case-studies/drift/get-borrow-deposit-amount-for-an-user.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.
