//! 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 solana_pubkey::Pubkey;
use crate::generated::types::TunaPositionState;
use crate::generated::types::MarketMaker;
use borsh::BorshSerialize;
use borsh::BorshDeserialize;


#[derive(BorshSerialize, BorshDeserialize, Clone, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct TunaLpPosition {
pub discriminator: [u8; 8],
/// Struct version
pub version: u16,
/// Bump seed for the tuna position account
pub bump: [u8; 1],
/// The authority address used for managing the position
#[cfg_attr(feature = "serde", serde(with = "serde_with::As::<serde_with::DisplayFromStr>"))]
pub authority: Pubkey,
/// Liquidity pool address this position belongs to
#[cfg_attr(feature = "serde", serde(with = "serde_with::As::<serde_with::DisplayFromStr>"))]
pub pool: Pubkey,
/// The mint address for token A
#[cfg_attr(feature = "serde", serde(with = "serde_with::As::<serde_with::DisplayFromStr>"))]
pub mint_a: Pubkey,
/// The mint address for token B
#[cfg_attr(feature = "serde", serde(with = "serde_with::As::<serde_with::DisplayFromStr>"))]
pub mint_b: Pubkey,
/// The mint address for the position token (minted and used in Orca/Fusion)
#[cfg_attr(feature = "serde", serde(with = "serde_with::As::<serde_with::DisplayFromStr>"))]
pub position_mint: Pubkey,
/// Total minted liquidity
pub liquidity: u128,
/// Position lower tick
pub tick_lower_index: i32,
/// Position upper tick
pub tick_upper_index: i32,
/// The amount of shares borrowed by user from vault A.
pub loan_shares_a: u64,
/// The amount of shares borrowed by user from vault B.
pub loan_shares_b: u64,
/// The amount of funds borrowed by user from vault A. Doesn't include accrued interest.
pub loan_funds_a: u64,
/// The amount of funds borrowed by user from vault B. Doesn't include accrued interest.
pub loan_funds_b: u64,
/// The leftovers are funds that couldn't be added to a pool as liquidity. They remain in the position token account.
pub leftovers_a: u64,
/// The leftovers are funds that couldn't be added to a pool as liquidity. They remain in the position token account.
pub leftovers_b: u64,
/// OBSOLETE: Position entry tick index. (For position version <= 6)
pub tick_entry_index: i32,
/// OBSOLETE: Position stop loss tick index (for position version <= 6).
pub tick_stop_loss_index: i32,
/// OBSOLETE: Position stop loss tick index (for position version <= 6).
pub tick_take_profit_index: i32,
/// Position state: normal, liquidated, closed by limit order
pub state: TunaPositionState,
/// OBSOLETE: Which token to swap collateral to when a limit order is executed. (For position version <= 4)
pub unused1: u8,
/// Yield amount in token A that has already been collected and compounded into the position.
pub compounded_yield_a: u64,
/// Yield amount in token B that has already been collected and compounded into the position.
pub compounded_yield_b: u64,
/// Position options.
pub flags: u32,
/// Market maker (Orca, Fusion)
pub market_maker: MarketMaker,
/// Position entry sqrt price.
pub entry_sqrt_price: u128,
/// Position lower limit order sqrt price (stop loss for a LONG position).
pub lower_limit_order_sqrt_price: u128,
/// Position upper limit order sqrt price (take profit for a LONG position).
pub upper_limit_order_sqrt_price: u128,
/// The position might be re-balanced if the current tick is lower than tick_lower_index or
/// higher than tick_higher_index by a threshold value.
pub rebalance_threshold_ticks: u32,
/// Reserved
pub reserved: [u8; 9],
}


pub const TUNA_LP_POSITION_DISCRIMINATOR: [u8; 8] = [76, 197, 161, 51, 232, 15, 137, 220];

impl TunaLpPosition {
      pub const LEN: usize = 339;
  
  
  
  #[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 TunaLpPosition {
  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_tuna_lp_position(
  rpc: &solana_client::rpc_client::RpcClient,
  address: &solana_pubkey::Pubkey,
) -> Result<crate::shared::DecodedAccount<TunaLpPosition>, std::io::Error> {
  let accounts = fetch_all_tuna_lp_position(rpc, &[*address])?;
  Ok(accounts[0].clone())
}

#[cfg(feature = "fetch")]
pub fn fetch_all_tuna_lp_position(
  rpc: &solana_client::rpc_client::RpcClient,
  addresses: &[solana_pubkey::Pubkey],
) -> Result<Vec<crate::shared::DecodedAccount<TunaLpPosition>>, 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<TunaLpPosition>> = 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 = TunaLpPosition::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_tuna_lp_position(
  rpc: &solana_client::rpc_client::RpcClient,
  address: &solana_pubkey::Pubkey,
) -> Result<crate::shared::MaybeAccount<TunaLpPosition>, std::io::Error> {
    let accounts = fetch_all_maybe_tuna_lp_position(rpc, &[*address])?;
    Ok(accounts[0].clone())
}

#[cfg(feature = "fetch")]
pub fn fetch_all_maybe_tuna_lp_position(
  rpc: &solana_client::rpc_client::RpcClient,
  addresses: &[solana_pubkey::Pubkey],
) -> Result<Vec<crate::shared::MaybeAccount<TunaLpPosition>>, 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<TunaLpPosition>> = Vec::new();
    for i in 0..addresses.len() {
      let address = addresses[i];
      if let Some(account) = accounts[i].as_ref() {
        let data = TunaLpPosition::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 TunaLpPosition {
      fn try_deserialize_unchecked(buf: &mut &[u8]) -> anchor_lang::Result<Self> {
        Ok(Self::deserialize(buf)?)
      }
  }

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

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

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

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

