//! This code was AUTOGENERATED using the codama library.
//! Please DO NOT EDIT THIS FILE, instead use visitors
//! to add features, then rerun codama to update it.
//!
//! <https://github.com/codama-idl/codama>
//!

use crate::generated::types::MarketMaker;
use solana_pubkey::Pubkey;
use borsh::BorshSerialize;
use borsh::BorshDeserialize;


#[derive(BorshSerialize, BorshDeserialize, Clone, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Market {
pub discriminator: [u8; 8],
/// Struct version
pub version: u16,
/// Bump seed for the market account
pub bump: [u8; 1],
/// Market maker: Orca, Fusion, etc...
pub market_maker: MarketMaker,
/// Liquidity pool address
#[cfg_attr(feature = "serde", serde(with = "serde_with::As::<serde_with::DisplayFromStr>"))]
pub pool: Pubkey,
/// Address Lookup Table address for this market
#[cfg_attr(feature = "serde", serde(with = "serde_with::As::<serde_with::DisplayFromStr>"))]
pub address_lookup_table: Pubkey,
/// Maximum allowed leverage for this market
pub max_leverage: u32,
/// Protocol fee represented as hundredths of a basis point. (Value of 100 is equal to 0.01%)
pub protocol_fee: u16,
/// Protocol fee on collateral (funds provided by a user) represented as hundredths of a basis point. (Value of 100 is equal to 0.01%)
pub protocol_fee_on_collateral: u16,
/// Liquidation fee represented as hundredths of a basis point. (Value of 100 is equal to 0.01%)
pub liquidation_fee: u32,
/// Liquidation threshold represented as hundredths of a basis point. The position is treated as unhealthy if debt > balance * (liquidation_threshold / HUNDRED_PERCENT).
pub liquidation_threshold: u32,
/// Obsolete: Limit order execution fee represented as hundredths of a basis point. (Value of 100 is equal to 0.01%)
pub unused1: u32,
/// Oracle price deviation threshold represented as hundredths of a basis point. If it's set to zero, the default value from the global config is used.
pub oracle_price_deviation_threshold: u32,
/// True if the market is disabled (no more position can be opened).
pub disabled: bool,
/// Total borrowed shares of token A.
pub borrowed_shares_a: u64,
/// Total borrowed shares of token B.
pub borrowed_shares_b: u64,
/// Total borrow limit for this market in token A.
pub borrow_limit_a: u64,
/// Total borrow limit for this market in token B.
pub borrow_limit_b: u64,
/// Maximum allowed swap slippage represented as hundredths of a basis point. If it's set to zero, the default value from the global config is used.
pub max_swap_slippage: u32,
/// The protocol fee taken from yield when a position is re-balanced.
pub rebalance_protocol_fee: u32,
/// Maximum allowed position size in token A. 0 means no limit.
pub spot_position_size_limit_a: u64,
/// Maximum allowed position size in token B. 0 means no limit.
pub spot_position_size_limit_b: u64,
/// Lending vault A address
#[cfg_attr(feature = "serde", serde(with = "serde_with::As::<serde_with::DisplayFromStr>"))]
pub vault_a: Pubkey,
/// Lending vault B address
#[cfg_attr(feature = "serde", serde(with = "serde_with::As::<serde_with::DisplayFromStr>"))]
pub vault_b: Pubkey,
/// Bad debt size in token A.
pub bad_debt_a: u64,
/// Bad debt size in token B.
pub bad_debt_b: u64,
/// Market creator authority or Pubkey::default() for non-permissionless markets
#[cfg_attr(feature = "serde", serde(with = "serde_with::As::<serde_with::DisplayFromStr>"))]
pub authority: Pubkey,
/// Reserved
#[cfg_attr(feature = "serde", serde(with = "serde_with::As::<serde_with::Bytes>"))]
pub reserved: [u8; 79],
}


pub const MARKET_DISCRIMINATOR: [u8; 8] = [219, 190, 213, 55, 0, 227, 198, 154];

impl Market {
      pub const LEN: usize = 348;
  
  
  
  #[inline(always)]
  pub fn from_bytes(data: &[u8]) -> Result<Self, std::io::Error> {
    let mut data = data;
    Self::deserialize(&mut data)
  }
}

impl<'a> TryFrom<&solana_account_info::AccountInfo<'a>> for Market {
  type Error = std::io::Error;

  fn try_from(account_info: &solana_account_info::AccountInfo<'a>) -> Result<Self, Self::Error> {
      let mut data: &[u8] = &(*account_info.data).borrow();
      Self::deserialize(&mut data)
  }
}

#[cfg(feature = "fetch")]
pub fn fetch_market(
  rpc: &solana_client::rpc_client::RpcClient,
  address: &solana_pubkey::Pubkey,
) -> Result<crate::shared::DecodedAccount<Market>, std::io::Error> {
  let accounts = fetch_all_market(rpc, &[*address])?;
  Ok(accounts[0].clone())
}

#[cfg(feature = "fetch")]
pub fn fetch_all_market(
  rpc: &solana_client::rpc_client::RpcClient,
  addresses: &[solana_pubkey::Pubkey],
) -> Result<Vec<crate::shared::DecodedAccount<Market>>, std::io::Error> {
    let accounts = rpc.get_multiple_accounts(addresses)
      .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e.to_string()))?;
    let mut decoded_accounts: Vec<crate::shared::DecodedAccount<Market>> = Vec::new();
    for i in 0..addresses.len() {
      let address = addresses[i];
      let account = accounts[i].as_ref()
        .ok_or(std::io::Error::new(std::io::ErrorKind::Other, format!("Account not found: {}", address)))?;
      let data = Market::from_bytes(&account.data)?;
      decoded_accounts.push(crate::shared::DecodedAccount { address, account: account.clone(), data });
    }
    Ok(decoded_accounts)
}

#[cfg(feature = "fetch")]
pub fn fetch_maybe_market(
  rpc: &solana_client::rpc_client::RpcClient,
  address: &solana_pubkey::Pubkey,
) -> Result<crate::shared::MaybeAccount<Market>, std::io::Error> {
    let accounts = fetch_all_maybe_market(rpc, &[*address])?;
    Ok(accounts[0].clone())
}

#[cfg(feature = "fetch")]
pub fn fetch_all_maybe_market(
  rpc: &solana_client::rpc_client::RpcClient,
  addresses: &[solana_pubkey::Pubkey],
) -> Result<Vec<crate::shared::MaybeAccount<Market>>, std::io::Error> {
    let accounts = rpc.get_multiple_accounts(addresses)
      .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e.to_string()))?;
    let mut decoded_accounts: Vec<crate::shared::MaybeAccount<Market>> = Vec::new();
    for i in 0..addresses.len() {
      let address = addresses[i];
      if let Some(account) = accounts[i].as_ref() {
        let data = Market::from_bytes(&account.data)?;
        decoded_accounts.push(crate::shared::MaybeAccount::Exists(crate::shared::DecodedAccount { address, account: account.clone(), data }));
      } else {
        decoded_accounts.push(crate::shared::MaybeAccount::NotFound(address));
      }
    }
  Ok(decoded_accounts)
}

  #[cfg(feature = "anchor")]
  impl anchor_lang::AccountDeserialize for Market {
      fn try_deserialize_unchecked(buf: &mut &[u8]) -> anchor_lang::Result<Self> {
        Ok(Self::deserialize(buf)?)
      }
  }

  #[cfg(feature = "anchor")]
  impl anchor_lang::AccountSerialize for Market {}

  #[cfg(feature = "anchor")]
  impl anchor_lang::Owner for Market {
      fn owner() -> Pubkey {
        crate::TUNA_ID
      }
  }

  #[cfg(feature = "anchor-idl-build")]
  impl anchor_lang::IdlBuild for Market {}

  
  #[cfg(feature = "anchor-idl-build")]
  impl anchor_lang::Discriminator for Market {
    const DISCRIMINATOR: &[u8] = &[0; 8];
  }

