Get Borrow/Deposit Amount for an User

Fetch Borrow or deposit details for a particular user and market index on Drift v2

Drift supports both lending and borrowing tokens and assets. You can query deposits, and borrowed amounts via the spotPositions field in drift_User 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 replit and see it in action.

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

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

Last updated