project-serum / serum-dex

Project Serum Rust Monorepo
https://projectserum.com
Apache License 2.0
620 stars 324 forks source link

How to get market id? #267

Open winktool opened 3 months ago

winktool commented 3 months ago

I want to write a Solana smart contract to get the market id via Cross Program Invocation (CPI) by providing the address of the tokens ,is this achievable, is there a simple example please? Thanks.

mubarizkyc commented 2 months ago

Yes it is


use serum_dex::market::Market;

pub mod my_program {
    use super::*;

    pub fn get_market_id(ctx: Context<GetMarketId>, token_mint: Pubkey) -> Result<()> {
        let market = Market::load(ctx.accounts.market.to_account_info(), false)?;

        let token_account = TokenAccount::load(ctx.accounts.token_account.to_account_info())?;
        require_eq!(token_account.mint, token_mint, MarketError::InvalidTokenMint);

        let token_program = Token::load(ctx.accounts.token_program.to_account_info())?;

        let market_info = market.get_market_info(&token_program, &token_account.mint)?;

        msg!("Market ID: {}", market_info.market_index);

        Ok(())
    }
}

#[derive(Accounts)]
pub struct GetMarketId<'info> {
    #[account(address = serum_dex::id())]
    pub serum_program: AccountInfo<'info>,

    #[account(address = token::ID)]
    pub token_program: AccountInfo<'info>,

    #[account(address = spl_associated_token_account::ID)]
    pub associated_token_program: AccountInfo<'info>,

    #[account(address = serum_dex::market::ID)]
    pub market: AccountInfo<'info>,

    #[account(
        mut,
        associated_token::mint = token_mint,
        associated_token::authority = user
    )]
    pub token_account: AccountInfo<'info>,

    #[account(mut)]
    pub user: Signer<'info>,

    pub system_program: Program<'info, System>,
}
gildastone commented 2 months ago

@mubarizkyc Any link to a repository with the full rust project? Lot of context is missing. Thanks.

winktool commented 2 months ago
ctx.accounts.market.to_account_info()
ctx.accounts.market.to_account_info()

???