Get Pool and OpenBook Market Info
Fetch pool and OpenBook market info required for building a swap transaction.
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 Raydium's Pool API. 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"
}
Last updated