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
        • 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
Powered by GitBook
On this page

Was this helpful?

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

Get Pool and OpenBook Market Info

Fetch pool and OpenBook market info required for building a swap transaction.

PreviousGet Liquidity Details of a PoolNextGet Token Supply Percentage In Pool

Last updated 1 year ago

Was this helpful?

Liquidity pool info alone is not enough to execute a swap transaction on Raydium. You also need the OpenBook market info as well. The pool provides some keys fields, such as marketId and marketProgramId, which we would use to fetch the further necessary details.

Our aim is to get the same information which we get from . You can directly use this API as well. The issue is that this API returns 250+ MB of data, which you have to manually filter for required info. On top of that, new pools take some time to reflect here.

With Shyft's GraphQL API, you can get the same information in the lowest latency possible. Copy and run this code directly in Replit to see it in action.

import { gql, GraphQLClient } from 'graphql-request';
import { Connection, PublicKey } from "@solana/web3.js";
import { Market } from "@project-serum/serum";

const SHYFT_API_KEY = 'YOUR-KEY'

const endpoint = `https://programs.shyft.to/v0/graphql?api_key=${SHYFT_API_KEY}`; //Shyft's gQl endpoint
const rpcEndpoint = `https://rpc.shyft.to/?api_key=${SHYFT_API_KEY}`;

const graphQLClient = new GraphQLClient(endpoint, {
  method: `POST`,
  jsonSerializer: {
    parse: JSON.parse,
    stringify: JSON.stringify,
  },
}); //Initialize gQL Client

async function getPoolInfo(address: string) {
  // We only fetch fields necessary for us
  const query = gql`
    query MyQuery($where: Raydium_LiquidityPoolv4_bool_exp) {
  Raydium_LiquidityPoolv4(
    where: {pubkey: {_eq: ${JSON.stringify(address)}}}
  ) {
    amountWaveRatio
    baseDecimal
    baseLotSize
    baseMint
    baseNeedTakePnl
    baseTotalPnl
    baseVault
    depth
    lpMint
    lpReserve
    lpVault
    marketId
    marketProgramId
    maxOrder
    maxPriceMultiplier
    minPriceMultiplier
    minSeparateDenominator
    minSeparateNumerator
    minSize
    nonce
    openOrders
    orderbookToInitTime
    owner
    pnlDenominator
    pnlNumerator
    poolOpenTime
    punishCoinAmount
    punishPcAmount
    quoteDecimal
    quoteLotSize
    quoteMint
    quoteNeedTakePnl
    quoteTotalPnl
    quoteVault
    resetFlag
    state
    status
    swapBase2QuoteFee
    swapBaseInAmount
    swapBaseOutAmount
    swapFeeDenominator
    swapFeeNumerator
    swapQuote2BaseFee
    swapQuoteInAmount
    swapQuoteOutAmount
    systemDecimalValue
    targetOrders
    tradeFeeDenominator
    tradeFeeNumerator
    volMaxCutRatio
    withdrawQueue
    pubkey
  }
}`;

  return await graphQLClient.request(query);
}

async function addMarketInfo(pool: any) {
  //to load Market Info from openbook
  const connection = new Connection(rpcEndpoint, "confirmed");

  const marketPubKey = new PublicKey(pool.marketId);
  const nullProgramId = new PublicKey("11111111111111111111111111111111");
  const marketProgramPubKey = new PublicKey(pool.marketProgramId);
  const market = await Market.load(connection, marketPubKey, undefined, marketProgramPubKey);
  const marketInfo = market?._decoded;

  //Fetch market authority
  const associatedAuthority = getAssociatedAuthority(
    {
      programId: marketProgramPubKey,
      marketId: marketPubKey,
    }
  )

//This is in the same format as you get from Raydium's mainnet.json
  return {
    baseDecimals: pool.baseDecimal,
    baseMint: new PublicKey(pool.baseMint),
    baseVault: new PublicKey(pool.baseVault),
    quoteDecimals: pool.quoteDecimal,
    quoteMint: new PublicKey(pool.quoteMint),
    quoteVault: new PublicKey(pool.quoteVault),
    marketId: marketPubKey,
    marketAuthority: associatedAuthority?.publicKey,
    marketProgramId: marketProgramPubKey,
    version: 4,
    withdrawQueue: new PublicKey(pool?.withdrawQueue),
    lpVault: new PublicKey(pool.lpVault),
    openOrders: new PublicKey(pool.openOrders),
    marketVersion: 3,
    marketBaseVault: marketInfo?.baseVault,
    marketQuoteVault: marketInfo?.quoteVault,
    marketBids: marketInfo?.bids,
    marketAsks: marketInfo?.asks,
    marketEventQueue: marketInfo?.eventQueue,
    lpMint: new PublicKey(pool.lpMint),
    programId: new PublicKey("675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8"), //hardcoded raydium program id
    targetOrders: new PublicKey(pool.targetOrders),
    lookupTableAccount: nullProgramId,
    lpDecimals: pool.baseDecimal,
    id: new PublicKey(pool.pubkey),
  }
}

function getAssociatedAuthority({ programId, marketId }: { programId: PublicKey; marketId: PublicKey }) {
  const seeds = [marketId.toBuffer()]

  let nonce = 0
  let publicKey: PublicKey

  while (nonce < 100) {
    try {
      // Buffer.alloc(7) nonce u64
      const seedsWithNonce = seeds.concat(Buffer.from([nonce]), Buffer.alloc(7))
      publicKey = PublicKey.createProgramAddressSync(seedsWithNonce, programId)
    } catch (err) {
      if (err instanceof TypeError) {
        throw err
      }
      nonce++
      continue
    }
    return { publicKey, nonce }
  }

  return console.log('unable to find a viable program address nonce', 'params', {
    programId,
    marketId,
  })
}

//replace this with token address for which you want to get Pools
const pool = await getPoolInfo('6a1CsrpeZubDjEJE9s1CMVheB6HWM5d7m1cj2jkhyXhj');

//This just needs parsed pool, you can fetch through token address, pair, etc.
const poolAndMarketInfo = await addMarketInfo(pool.Raydium_LiquidityPoolv4[0]);
console.log('Combined wth market info')
console.log(poolAndMarketInfo)
{
  "baseDecimals": 9,
  "baseMint": "7dHbWXmci3dT8UFYWYZweBLXgycu7Y3iL6trKn1Y7ARj",
  "baseVault": "DD6oh3HRCvMzqHkGeUW3za4pLgWNPJdV6aNYW3gVjXXi",
  "quoteDecimals": 6,
  "quoteMint": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",
  "quoteVault": "6KR4qkJN91LGko2gdizheri8LMtCwsJrhtsQt6QPwCi5",
  "marketId": "JCKa72xFYGWBEVJZ7AKZ2ofugWPBfrrouQviaGaohi3R",
  "marketAuthority": "DYVAKTk5icrGV5ouuMyQT2kCAN8ECP5qx9q7Bwk2Uxbi",
  "marketProgramId": "srmqPvymJeFKQ4zGQed1GFppgkRHL9kaELCbyksJtPX",
  "version": 4,
  "withdrawQueue": "11111111111111111111111111111111",
  "lpVault": "11111111111111111111111111111111",
  "openOrders": "F7WxjsWUC7hMkpC9kqougx8wFTpZxhX8FfyTgYrGxQoH",
  "marketVersion": 3,
  "marketBaseVault": "6q3zjhjZrC2f8Xd8CLqxQJaeSATQDhKMcDvF8KL3yHB4",
  "marketQuoteVault": "BExFcur6aLQBLhtbngfs37yxvNad3N5u1Kg3pWzSeuNn",
  "marketBids": "GUQP2dWc6e2saQJL1Ep3QSZdTboNfpF8uzCj9th4CRUM",
  "marketAsks": "7JynbAyCjg8Rvia8hizfRSaLhEWnHQxxBKUh5FqjRncY",
  "marketEventQueue": "9ttPB4KHXuwxDD8668WiY1L8jdvYMFvZtwKn5PGNMCHX",
  "lpMint": "HDUJMwYZkjUZre63xUeDhdCi8c6LgUDiBqxmP3QC3VPX",
  "programId": "675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8",
  "targetOrders": "B8nmqinHQjyqAnMWNiqSzs1Jb8VbMpX5k9VUMnDp1gUA",
  "lookupTableAccount": "11111111111111111111111111111111",
  "lpDecimals": 9,
  "id": "6a1CsrpeZubDjEJE9s1CMVheB6HWM5d7m1cj2jkhyXhj"
}
📀
Raydium's Pool API