use anchor_lang::{
prelude::{ProgramError, Pubkey},
AccountDeserialize, Discriminator,
};
use regex::Regex;
use solana_account_decoder::UiAccountEncoding;
use solana_clap_utils::keypair::DefaultSigner;
use solana_cli_config::{Config, ConfigInput};
use solana_client::{
client_error::ClientError as SolanaClientError,
pubsub_client::PubsubClientError,
rpc_client::RpcClient,
rpc_config::{
RpcAccountInfoConfig, RpcProgramAccountsConfig, RpcSendTransactionConfig,
RpcSimulateTransactionAccountsConfig, RpcSimulateTransactionConfig,
},
rpc_filter::{Memcmp, MemcmpEncodedBytes, RpcFilterType},
rpc_response::RpcSimulateTransactionResult,
};
use solana_program::instruction::Instruction;
use solana_remote_wallet::remote_wallet::RemoteWalletManager;
use solana_sdk::{
account::Account,
bs58,
commitment_config::{CommitmentConfig, CommitmentLevel},
signer::Signer,
transaction::Transaction,
};
use std::{io, iter::Map, sync::Arc, time::Duration, vec::IntoIter};
use tabled::Tabled;
use thiserror::Error;
use crate::render::render_object;
const PROGRAM_LOG: &str = "Program log: ";
const PROGRAM_DATA: &str = "Program data: ";
pub struct ProgramAccountsIterator<T> {
inner: Map<IntoIter<(Pubkey, Account)>, AccountConverterFunction<T>>,
}
type AccountConverterFunction<T> = fn((Pubkey, Account)) -> Result<(Pubkey, T), ClientError>;
impl<T> Iterator for ProgramAccountsIterator<T> {
type Item = Result<(Pubkey, T), ClientError>;
fn next(&mut self) -> Option<Self::Item> {
self.inner.next()
}
}
#[derive(Debug, Error)]
pub enum ClientError {
#[error("Account not found")]
AccountNotFound,
#[error("{0}")]
AnchorError(#[from] anchor_lang::error::Error),
#[error("{0}")]
ProgramError(#[from] ProgramError),
#[error("{0}")]
SolanaClientError(#[from] SolanaClientError),
#[error("{0}")]
SolanaClientPubsubError(#[from] PubsubClientError),
#[error("Unable to parse log: {0}")]
LogParseError(String),
#[error("Unable to parse event")]
EventParseError,
#[error("Simulate error{0}")]
SimulateError(String),
}
pub struct SimulateResult {
result: RpcSimulateTransactionResult,
lamports: u64,
}
pub struct Client {
pub config_path: String,
pub config: Config,
pub rpc_timeout: Duration,
pub commitment: CommitmentConfig,
pub confirm_transaction_initial_timeout: Duration,
pub signers: Vec<Box<dyn Signer>>,
}
impl Client {
pub fn new(config_path: String) -> Result<Self, io::Error> {
let mut config = Config::load(config_path.as_str())?;
let rpc_timeout = Duration::from_secs(30);
if config.websocket_url.is_empty() {
config.websocket_url = Config::compute_websocket_url(&config.json_rpc_url);
}
let commitment = CommitmentConfig {
commitment: CommitmentLevel::Processed,
};
let confirm_transaction_initial_timeout = Duration::from_secs(30);
let default_signer_arg_name = "keypair".to_string();
let (_, default_signer_path) =
ConfigInput::compute_keypair_path_setting("", &config.keypair_path);
let default_signer = DefaultSigner::new(default_signer_arg_name, &default_signer_path);
let mut wallet_manager: Option<Arc<RemoteWalletManager>> = None;
let payer = default_signer.signer_from_path(&Default::default(), &mut wallet_manager);
Ok(Client {
config_path,
config,
rpc_timeout,
commitment,
confirm_transaction_initial_timeout,
signers: vec![payer.unwrap()],
})
}
#[allow(dead_code)]
pub fn rpc_client(&self) -> RpcClient {
RpcClient::new_with_timeouts_and_commitment(
self.config.json_rpc_url.to_string(),
self.rpc_timeout,
self.commitment,
self.confirm_transaction_initial_timeout,
)
}
pub fn lamports(&self) -> u64 {
let lamports = self.rpc_client().get_balance(&self.payer_key());
lamports.unwrap()
}
pub fn payer_key(&self) -> Pubkey {
self.signers[0].pubkey()
}
pub fn account<T: AccountDeserialize>(&self, address: Pubkey) -> Result<T, ClientError> {
let account = self
.rpc_client()
.get_account_with_commitment(&address, CommitmentConfig::processed())?
.value
.ok_or(ClientError::AccountNotFound)?;
let mut data: &[u8] = &account.data;
T::try_deserialize(&mut data).map_err(Into::into)
}
pub fn accounts<T: AccountDeserialize + Discriminator>(
&self,
program_id: &Pubkey,
filters: Vec<RpcFilterType>,
) -> Result<Vec<(Pubkey, T)>, ClientError> {
self.accounts_lazy(program_id, filters)?.collect()
}
pub fn accounts_lazy<T: AccountDeserialize + Discriminator>(
&self,
program_id: &Pubkey,
filters: Vec<RpcFilterType>,
) -> Result<ProgramAccountsIterator<T>, ClientError> {
let account_type_filter = RpcFilterType::Memcmp(Memcmp {
offset: 0,
bytes: MemcmpEncodedBytes::Base58(bs58::encode(T::discriminator()).into_string()),
encoding: None,
});
let config = RpcProgramAccountsConfig {
filters: Some([vec![account_type_filter], filters].concat()),
account_config: RpcAccountInfoConfig {
encoding: Some(UiAccountEncoding::Base64),
..RpcAccountInfoConfig::default()
},
..RpcProgramAccountsConfig::default()
};
Ok(ProgramAccountsIterator {
inner: self
.rpc_client()
.get_program_accounts_with_config(program_id, config)?
.into_iter()
.map(|(key, account)| {
Ok((key, T::try_deserialize(&mut (&account.data as &[u8]))?))
}),
})
}
pub fn send_and_confirm(&self, ixs: &[Instruction]) {
let rpc_client = self.rpc_client();
let recent_blockhash = rpc_client.get_latest_blockhash().unwrap();
let tx = Transaction::new_signed_with_payer(
ixs,
Some(&self.payer_key()),
&self.signers,
recent_blockhash,
);
let resp = rpc_client.send_and_confirm_transaction_with_spinner_and_config(
&tx,
self.commitment,
RpcSendTransactionConfig {
skip_preflight: true,
preflight_commitment: None,
encoding: None,
max_retries: Some(3),
min_context_slot: None,
},
);
if resp.is_err() {
println!(
"{}",
resp.err()
.unwrap()
.get_transaction_error()
.unwrap()
.to_string()
);
} else {
println!("{}", resp.unwrap().to_string());
}
}
pub fn simulate(&self, ixs: &[Instruction]) -> Result<SimulateResult, ClientError> {
let rpc_client = self.rpc_client();
let recent_blockhash = rpc_client.get_latest_blockhash().unwrap();
let tx = Transaction::new_signed_with_payer(
ixs,
Some(&self.payer_key()),
&self.signers,
recent_blockhash,
);
let mut config = RpcSimulateTransactionConfig::default();
config.replace_recent_blockhash = true;
config.commitment = Some(self.commitment);
config.accounts = Some(RpcSimulateTransactionAccountsConfig {
encoding: Some(UiAccountEncoding::Base64),
addresses: vec![self.payer_key().to_string()],
});
let before_lamports = self.lamports();
let resp = rpc_client.simulate_transaction_with_config(&tx, config);
if resp.is_err() {
return Err(ClientError::SimulateError(resp.err().unwrap().to_string()));
}
let result = resp.unwrap().value;
let lamports = if result.accounts.is_some() {
let accounts = result.accounts.clone().unwrap();
if accounts[0].is_some() {
before_lamports - accounts[0].clone().unwrap().lamports
} else {
before_lamports
}
} else {
before_lamports
};
Ok(SimulateResult { result, lamports })
}
pub fn simulate_and_print<
T: anchor_lang::Event + anchor_lang::AnchorDeserialize + Tabled + Copy,
>(
&self,
program_id: &Pubkey,
ixs: &[Instruction],
) -> Option<T> {
let resp = self.simulate(ixs);
if resp.is_err() {
println!("Simulate error:{:?}", resp.err());
None
} else {
let result = resp.unwrap();
let event_parsed: Result<T, ClientError> = result.parse_event(program_id);
if event_parsed.is_err() {
for log in result.result.logs.clone().unwrap() {
println!("{}", log);
}
None
} else {
let event = event_parsed.unwrap();
println!(
"{}",
render_object(
event,
format!(
"SimulateSwap\n fee_lamports:{} units:{}",
result.lamports,
result.result.units_consumed.unwrap()
)
.as_str(),
None
)
);
Some(event)
}
}
}
}
pub trait EventParser {
fn parse_event<T: anchor_lang::Event + anchor_lang::AnchorDeserialize>(
&self,
program_id: &Pubkey,
) -> Result<T, ClientError>;
}
impl EventParser for SimulateResult {
fn parse_event<T: anchor_lang::Event + anchor_lang::AnchorDeserialize>(
&self,
program_id: &Pubkey,
) -> Result<T, ClientError> {
let mut logs = &self.result.logs.clone().unwrap()[..];
if logs.len() == 0 {
println!("{:?}", self.result);
return Err(ClientError::EventParseError);
}
let mut execution = Execution::new(&mut logs)?;
let self_program_str = program_id.to_string();
for l in logs {
let (event, new_program, did_pop) = {
if self_program_str == execution.program() {
handle_program_log(&self_program_str, l).unwrap_or_else(|e| {
println!("Unable to parse log: {}", e);
std::process::exit(1);
})
} else {
let (program, did_pop) = handle_system_log(&self_program_str, l);
(None, program, did_pop)
}
};
if let Some(e) = event {
return Ok(e);
}
if let Some(new_program) = new_program {
execution.push(new_program);
}
if did_pop {
execution.pop();
}
}
Err(ClientError::EventParseError)
}
}
struct Execution {
stack: Vec<String>,
}
impl Execution {
pub fn new(logs: &mut &[String]) -> Result<Self, ClientError> {
let l = &logs[0];
*logs = &logs[1..];
let re = Regex::new(r"^Program (.*) invoke.*$").unwrap();
let c = re
.captures(l)
.ok_or_else(|| ClientError::LogParseError(l.to_string()))?;
let program = c
.get(1)
.ok_or_else(|| ClientError::LogParseError(l.to_string()))?
.as_str()
.to_string();
Ok(Self {
stack: vec![program],
})
}
pub fn program(&self) -> String {
assert!(!self.stack.is_empty());
self.stack[self.stack.len() - 1].clone()
}
pub fn push(&mut self, new_program: String) {
self.stack.push(new_program);
}
pub fn pop(&mut self) {
assert!(!self.stack.is_empty());
self.stack.pop().unwrap();
}
}
fn handle_program_log<T: anchor_lang::Event + anchor_lang::AnchorDeserialize>(
self_program_str: &str,
l: &str,
) -> Result<(Option<T>, Option<String>, bool), ClientError> {
if let Some(log) = l
.strip_prefix(PROGRAM_LOG)
.or_else(|| l.strip_prefix(PROGRAM_DATA))
{
let borsh_bytes = match anchor_lang::__private::base64::decode(&log) {
Ok(borsh_bytes) => borsh_bytes,
_ => {
return Ok((None, None, false));
}
};
let mut slice: &[u8] = &borsh_bytes[..];
let disc: [u8; 8] = {
let mut disc = [0; 8];
disc.copy_from_slice(&borsh_bytes[..8]);
slice = &slice[8..];
disc
};
let mut event = None;
if disc == T::discriminator() {
let e: T = anchor_lang::AnchorDeserialize::deserialize(&mut slice)
.map_err(|e| ClientError::LogParseError(e.to_string()))?;
event = Some(e);
}
Ok((event, None, false))
}
else {
let (program, did_pop) = handle_system_log(self_program_str, l);
Ok((None, program, did_pop))
}
}
fn handle_system_log(this_program_str: &str, log: &str) -> (Option<String>, bool) {
if log.starts_with(&format!("Program {} log:", this_program_str)) {
(Some(this_program_str.to_string()), false)
} else if log.contains("invoke") {
(Some("cpi".to_string()), false) } else {
let re = Regex::new(r"^Program (.*) success*$").unwrap();
if re.is_match(log) {
(None, true)
} else {
(None, false)
}
}
}