//! 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 TunaPosition {
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,
/// Position entry tick index.
pub tick_entry_index: i32,
/// Position stop loss tick index.
pub tick_stop_loss_index: i32,
/// Position stop loss tick index.
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. Used for position ver 4 or older.
/// bits 0..1: Stop loss swap. 0 - no swap, 1 - swap to token A, 2 - swap to token B
/// bits 2..3: Take profit swap. 0 - no swap, 1 - swap to token A, 2 - swap to token B
pub swap_to_token_on_limit_order: 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.
/// Bits 0..1: Stop loss swap. 0 - no swap, 1 - swap to token A, 2 - swap to token B
/// Bits 2..3: Take profit swap. 0 - no swap, 1 - swap to token A, 2 - swap to token B
/// Bits 4..5: Yield auto compounding. 0 - don't compound, 1 - compound yield, 2 - compound yield with leverage
pub flags: u32,
/// Market maker (Orca, Fusion)
pub market_maker: MarketMaker,
/// 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
#[cfg_attr(feature = "serde", serde(with = "serde_with::As::<serde_with::Bytes>"))]
pub reserved: [u8; 57],
}


impl TunaPosition {
      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 TunaPosition {
  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_position(
  rpc: &solana_client::rpc_client::RpcClient,
  address: &solana_pubkey::Pubkey,
) -> Result<crate::shared::DecodedAccount<TunaPosition>, std::io::Error> {
  let accounts = fetch_all_tuna_position(rpc, &[*address])?;
  Ok(accounts[0].clone())
}

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

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

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

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

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

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

