0

I've already got the SPL token mint address using @solana/spl-token and @solana/web3.js, now I want to get how much this SPL token is valued in SOL using the Raydium SDK. I've looked at some answers but the solutions are pretty complicated for someone who's pretty new to Raydium SDK and Solana terminology in general. Would be appreciated if someone could explain more simply and beginner-friendly. Thanks a lot.

2 Answers 2

0

It is the easiest way to get sol usdc price directly from raydium CLMM

async getSolanaPrice() {
    const id = new PublicKey('8sLbNZoA1cfnvMJLPfp98ZLAnFSYCFApfJKMbiXNLwxj')

    const accountInfo = await solanaConnection.getAccountInfo(id)

    if (accountInfo === null) throw Error(' get pool info error ')

    const poolData = PoolInfoLayout.decode(accountInfo.data)

    console.log('current price -> ', SqrtPriceMath.sqrtPriceX64ToPrice(poolData.sqrtPriceX64, poolData.mintDecimalsA, poolData.mintDecimalsB).toFixed(2))

  }

Don't forgot to install @raydium-io/raydium-sdk and @solana/web3.js and create connection variable finally you can get the price of solana in usdc

1
  • Perfect answer, thanks alot.
    – Tyran
    Commented Apr 12 at 10:31
0

Below code is completely coded by me so be careful with your credentials and I'm not responsible for any security issues . In that code you can directly get live data from Raydium sdk in typescript

const market = await getMinimalMarketV3(solanaConnection, accountData.marketId, commitment);

tokenAccount = saveTokenAccount(accountData.baseMint, market);    
tokenAccount.poolKeys = createPoolKeys(accountId, accountData, market!);
            const poolInfo = await Liquidity.fetchInfo({ connection: solanaConnection, poolKeys: tokenAccount.poolKeys });
            console.log(poolInfo);
            const computeamount = Liquidity.computeAmountOut({
                poolKeys: tokenAccount.poolKeys,
                poolInfo: poolInfo,
                amountIn: quoteAmount,
                currencyOut: new Token(TOKEN_PROGRAM_ID, tokenAccount.mint, tokenAccount.poolKeys.baseDecimals),
                slippage: new Percent(0),
            })
            var TOKENS_PER_SOL = computeamount.currentPrice.toFixed(accountData.baseDecimal.toNumber());
            var PRICE = 1 / parseFloat(TOKENS_PER_SOL);

Here is the function for how to get accountData

async function fetchMarketAccounts(connection: Connection, base: PublicKey, quote: PublicKey, commitment: Commitment) {
    const accounts = await connection.getProgramAccounts(
        RAYDIUM_LIQUIDITY_PROGRAM_ID_V4,
        {
            commitment,
            filters: [
                { dataSize: LIQUIDITY_STATE_LAYOUT_V4.span },
                {
                    memcmp: {
                        offset: LIQUIDITY_STATE_LAYOUT_V4.offsetOf("baseMint"),
                        bytes: base.toBase58(),
                    },
                },
                {
                    memcmp: {
                        offset: LIQUIDITY_STATE_LAYOUT_V4.offsetOf("quoteMint"),
                        bytes: quote.toBase58(),
                    },
                },
            ],
        }
    );

    return accounts.map(({ pubkey, account }) => ({
        id: pubkey,
        poolstate: {
            ...LIQUIDITY_STATE_LAYOUT_V4.decode(account.data)
        }
    }));
}
const AccountInfo = await fetchMarketAccounts(solanaConnection, new PublicKey('GM3BR5yjG5A5cxPukjBj2FPjLsuvCYrXZzVWQkP6DQWQ'), new PublicKey('So11111111111111111111111111111111111111112'), commitment);
const accountId = AccountInfo[0].id;
const accountData = AccountData[0].poolstate;
        

Here is the getMinimalAccountv3 and createPoolKeys function

async function getMinimalMarketV3(
  connection: Connection,
  marketId: PublicKey,
  commitment?: Commitment,
): Promise<MinimalMarketLayoutV3> {
  const marketInfo = await connection.getAccountInfo(marketId, {
    commitment,
    dataSlice: {
      offset: MARKET_STATE_LAYOUT_V3.offsetOf('eventQueue'),
      length: 32 * 3,
    },
  });
  // console.log(MINIMAL_MARKET_STATE_LAYOUT_V3.decode(marketInfo!.data))
  return MINIMAL_MARKET_STATE_LAYOUT_V3.decode(marketInfo!.data);
}

function createPoolKeys(
  id: PublicKey,
  accountData: LiquidityStateV4,
  minimalMarketLayoutV3: MinimalMarketLayoutV3,
): LiquidityPoolKeys {
  return {
    id,
    baseMint: accountData.baseMint,
    quoteMint: accountData.quoteMint,
    lpMint: accountData.lpMint,
    baseDecimals: accountData.baseDecimal.toNumber(),
    quoteDecimals: accountData.quoteDecimal.toNumber(),
    lpDecimals: 5,
    version: 4,
    programId: RAYDIUM_LIQUIDITY_PROGRAM_ID_V4,
    authority: Liquidity.getAssociatedAuthority({
      programId: RAYDIUM_LIQUIDITY_PROGRAM_ID_V4,
    }).publicKey,
    openOrders: accountData.openOrders,
    targetOrders: accountData.targetOrders,
    baseVault: accountData.baseVault,
    quoteVault: accountData.quoteVault,
    marketVersion: 3,
    marketProgramId: accountData.marketProgramId,
    marketId: accountData.marketId,
    marketAuthority: Market.getAssociatedAuthority({
      programId: accountData.marketProgramId,
      marketId: accountData.marketId,
    }).publicKey,
    marketBaseVault: accountData.baseVault,
    marketQuoteVault: accountData.quoteVault,
    marketBids: minimalMarketLayoutV3.bids,
    marketAsks: minimalMarketLayoutV3.asks,
    marketEventQueue: minimalMarketLayoutV3.eventQueue,
    withdrawQueue: accountData.withdrawQueue,
    lpVault: accountData.lpVault,
    lookupTableAccount: PublicKey.default,
  };
}

Import necessary modules from Raydium sdk and Solanaweb3 js Additionall use the fetchMarketAccount function to get pool id and use it to get All information of liquidity pool in raydium

Now you can get price of any spl token live

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.