Shyft
Start BuildingSupportWebsite
  • Welcome
    • 👋Introducing Shyft
    • 🏗️Start Building
  • Solana Infrastructure
    • 🚁Shyft RPCs
  • Yellowstone gRPC Network
    • Decoding gRPC Latency
    • ⚡gRPC Docs
      • Introduction
      • Authentication
      • Subscribe Requests
      • FAQ
      • Getting Started
        • Initializing the Yellowstone Client
        • Making a gRPC connection
        • Adding a Reconnection Mechanism
        • 🔥Replaying Slots with Solana yellowstone gRPCs
        • Modifying your Subscribe Request
        • Closing a gRPC Connection
      • Subscribing to Transactions
        • All Transactions of an address
        • Subscribing to all transactions of a Liquidity Pool
        • Subscribing to all transactions of multiple addresses
        • Subscribing to all transactions of a Token
      • Subscribing to Accounts
        • Account Updates for a Program
        • Account Updates for an Address
        • Account updates using memcmp
      • Streaming Blocks & BlocksMeta
        • Streaming Block Updates
        • Subscribing to BlocksMeta
      • Modifying & Unsubscribing
  • Solana defi data
    • DeFI APIs
      • Get Pool By Address
      • Get Pools By Token Pair
      • Get All Pools for a Token
      • Get Liquidity Details of a Pool
  • Callbacks
    • ☎️What are Callbacks?
      • Transaction Callbacks
      • Account Callbacks
    • 📔Callback APIs
      • Response Structure
      • List Callbacks
      • Register callback
      • Remove callback
      • 🔥Pause a callback
      • 🔥Resume a callback
      • Update Callbacks
      • Add Addresses
      • Remove addresses
  • Solana Super Indexers
    • 🌩️GraphQL APIs
      • Getting Started
      • Building Queries
      • Paginating Response
      • Applying Filters
      • Ordering and Sorting Data
    • 📀Case Studies
      • Tensor
        • Get Active Listings of a Wallet
        • Get Active Bids of a Wallet
        • Get Active Listings of a Collection
        • Get all Bids of a Collection
        • Get all Pools of a Margin Account
        • Get all Pools by Owner
      • Raydium
        • Get Pool By Address
        • Get Pools By Token Address
        • Get Pools Created Between Time
        • Get Pool Burn Percentage
        • Get Liquidity Details of a Pool
        • Get Pool and OpenBook Market Info
        • Get Token Supply Percentage In Pool
      • Orca Whirlpool
        • Get Pool by Address
        • Get Pool by Token Address
        • Get Positions for a Pool
        • Get Positions for a Wallet
        • Get Liquidity Details of a Pool
      • Kamino
        • Get Borrow Details of a Wallet
        • Get Deposit Details of a Wallet
        • Get Reserve Details
      • Cross Marketplace Queries
        • Get active listings across marketplaces for a wallet
        • Get listings for a collection across marketplaces
        • Get floor price of a collection
      • Cross Defi Queries
        • Fetch Liquidity Pools for Token
      • Native Staking
        • Get Stakes for a Wallet
        • Get Stakes For Validator
      • Governance/Realms
        • Get DAO Token Owners
        • Get Proposals For Governing Mint
        • Get All Proposals For DAO
        • Get DAO Treasury Info
        • Get All Active Proposals For Wallet
      • Meteora
        • Get All LB Position Pairs
        • Get Position of a User Wallet
        • Get Pool by Token Addresses
        • Get All Deposits for a User
        • Get All Withdraws for a User
        • Get All Fees Claimed by a User
        • Get All User Positions and Deposits for a Pool
        • Get All User Positions and Withdrawals for a Pool
      • Fluxbeam
        • Get Pool by Address
        • Get Pool by Token Addresses
      • Drift
        • Get User account for Delegate
        • Get User accounts based on authority
        • Get User details based on Referrer
        • Get Borrow/Deposit Amount for an User
        • Get PrepPositions for an User Account
        • Getting OrderId and userOrderId
        • Get OpenOrders for a User Account
      • 🔥Pumpswap
        • 🔥Get Pool by Address
        • 🔥Get Pool by Creator Address
        • 🔥Get Pools by Token Addresses
      • Raydium Launchpad
        • Get Bonding Curve Details by Pool Address
        • Get All Pools for a Creator
        • Get Pools by Token Addresses
        • Get Migration details of a Pool
  • Solana APIs
    • API Reference
    • Transactions
      • Parsed Transaction Structure
      • Transaction APIs
        • History
        • Parse Signature
        • Parse Multiple Signatures
        • Send
        • Send Multiple
    • NFT
      • 🔥Create Gasless
      • Create
      • Read All
      • Burn
      • 🔥Burn Multiple NFTs V2
      • Update
      • 🔥Create NFT from Metadata
      • 🔥Read Wallet Nfts
      • 🔥Read Selected NFTs
      • 🔥Get NFT Owners
      • 🔥Update NFT Metadata Uri
      • 🔥Update V2
      • Search
      • Transfer
      • Transfer Multiple NFTs
      • Mint
      • Read
    • Wallet
      • Get Balance
      • Get Token Balance
      • Get All Tokens Balance
      • Get Portfolio
      • Resolve Address
      • Get All Domains
      • Get Stake Accounts
    • Fungible Tokens
      • Create
      • Mint
      • Burn
      • 🔥Update
      • Get Token Info
      • Transfer
      • Airdrop
  • 📘Dev Guides
    • 📀gRPC Case Studies
      • Pumpfun
        • Streaming and Parsing Pump.fun Transactions
        • Streaming and Parsing Pump.fun Accounts
        • Detecting new Token launches on Pump.fun
        • Detecting Buy/Sell Transactions on Pump.fun
        • Detecting tokens migrating from Pump.fun to Pump Swap AMM
      • PumpSwap AMM
        • Streaming and Parsing Pump Swap Transactions
        • Streaming and Parsing Pump Swap AMM Accounts
        • Detecting Buy/Sell Transactions on Pump Swap AMM
        • Detecting tokens migrating from Pump.fun to Pump Swap AMM
Powered by GitBook
On this page

Was this helpful?

  1. Solana Super Indexers
  2. Case Studies
  3. Drift

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

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

PreviousGet User details based on ReferrerNextGet PrepPositions for an User Account

Last updated 8 months ago

Was this helpful?

📀