use std::str::FromStr;
use std::sync::Arc;
use clap::ArgMatches;
use solana_clap_utils::keypair::DefaultSigner;
use solana_client::rpc_client::RpcClient;
use solana_program::pubkey::Pubkey;
use solana_remote_wallet::remote_wallet::RemoteWalletManager;
use spl_associated_token_account::get_associated_token_address;
use crate::check_and_update_err;
use crate::clmmpool::pair::create_tick_array::calculate_tick_array_key;
use crate::command::{CliCommand, CliCommandInfo, CliConfig, CliError, ProcessResult};
use crate::contract::instructions::collect_fee::new_collect_fee;
use crate::contract::state::clmmpools::Clmmpool;
use crate::contract::state::position::Position;
use crate::contract::state::tick_array::TickArray;
use crate::program::get_pubkey_for_program_with_seeds;
use crate::utils::send::send_tx;
pub fn parse_collect_fee<'a>(
matches: &'a ArgMatches,
default_signer: &DefaultSigner,
wallet_manager: &mut Option<Arc<RemoteWalletManager>>,
) -> Result<CliCommandInfo<'a>, CliError> {
let mint = matches.value_of("mint");
Ok(CliCommandInfo {
command: CliCommand::PairCollectFee {
mint: Pubkey::from_str(mint.unwrap()).unwrap(),
},
signers: vec![check_and_update_err!(
default_signer.signer_from_path(matches, wallet_manager),
CliError::RpcRequestError("owner key is invalid".to_string())
)?],
})
}
pub fn process_collect_fee(
rpc_client: &RpcClient,
config: &CliConfig,
mint: &Pubkey,
) -> ProcessResult {
let (position, _) = get_pubkey_for_program_with_seeds(&[b"position", mint.as_ref()]);
let position_info = Position::get_info(rpc_client, &position);
let clmmpool_info = Clmmpool::get_info(rpc_client, &position_info.clmmpool);
let position_ata =
get_associated_token_address(&config.pubkey().unwrap(), &position_info.position_nft_mint);
let token_a_ata =
get_associated_token_address(&config.pubkey().unwrap(), &clmmpool_info.token_a);
let token_b_ata =
get_associated_token_address(&config.pubkey().unwrap(), &clmmpool_info.token_b);
let array_lower_index =
TickArray::array_index(position_info.tick_lower_index, clmmpool_info.tick_spacing).unwrap();
let (tick_array_lower_pubkey, _) = calculate_tick_array_key(
position_info.clmmpool.as_ref(),
array_lower_index.to_le_bytes().as_ref(),
);
let array_upper_index =
TickArray::array_index(position_info.tick_upper_index, clmmpool_info.tick_spacing).unwrap();
let (tick_array_upper_pubkey, _) = calculate_tick_array_key(
position_info.clmmpool.as_ref(),
array_upper_index.to_le_bytes().as_ref(),
);
let ixs = [new_collect_fee(
&position_info.clmmpool,
&position,
&position_ata,
&token_a_ata,
&token_b_ata,
&clmmpool_info.token_a_vault,
&clmmpool_info.token_b_vault,
&tick_array_lower_pubkey,
&tick_array_upper_pubkey,
config.pubkey().unwrap(),
)];
let res = send_tx(rpc_client, config, &ixs)?;
Ok("signers : ".to_owned() + res.to_string().as_str())
}