lib.rs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874
  1. #![cfg_attr(docsrs, feature(doc_auto_cfg))]
  2. //! An RPC client to interact with Solana programs written in [`anchor_lang`].
  3. //!
  4. //! # Examples
  5. //!
  6. //! A simple example that creates a client, sends a transaction and fetches an account:
  7. //!
  8. //! ```ignore
  9. //! use std::rc::Rc;
  10. //!
  11. //! use anchor_client::{
  12. //! solana_sdk::{
  13. //! signature::{read_keypair_file, Keypair},
  14. //! signer::Signer,
  15. //! system_program,
  16. //! },
  17. //! Client, Cluster,
  18. //! };
  19. //! use my_program::{accounts, instruction, MyAccount};
  20. //!
  21. //! fn main() -> Result<(), Box<dyn std::error::Error>> {
  22. //! // Create client
  23. //! let payer = read_keypair_file("keypair.json")?;
  24. //! let client = Client::new(Cluster::Localnet, Rc::new(payer));
  25. //!
  26. //! // Create program
  27. //! let program = client.program(my_program::ID)?;
  28. //!
  29. //! // Send a transaction
  30. //! let my_account_kp = Keypair::new();
  31. //! program
  32. //! .request()
  33. //! .accounts(accounts::Initialize {
  34. //! my_account: my_account_kp.pubkey(),
  35. //! payer: program.payer(),
  36. //! system_program: system_program::ID,
  37. //! })
  38. //! .args(instruction::Initialize { field: 42 })
  39. //! .signer(&my_account_kp)
  40. //! .send()?;
  41. //!
  42. //! // Fetch an account
  43. //! let my_account: MyAccount = program.account(my_account_kp.pubkey())?;
  44. //! assert_eq!(my_account.field, 42);
  45. //!
  46. //! Ok(())
  47. //! }
  48. //! ```
  49. //!
  50. //! More examples can be found in [here].
  51. //!
  52. //! [here]: https://github.com/coral-xyz/anchor/tree/v0.30.1/client/example/src
  53. //!
  54. //! # Features
  55. //!
  56. //! The client is blocking by default. To enable asynchronous client, add `async` feature:
  57. //!
  58. //! ```toml
  59. //! anchor-client = { version = "0.30.1 ", features = ["async"] }
  60. //! ````
  61. use anchor_lang::solana_program::program_error::ProgramError;
  62. use anchor_lang::solana_program::pubkey::Pubkey;
  63. use anchor_lang::{AccountDeserialize, Discriminator, InstructionData, ToAccountMetas};
  64. use futures::{Future, StreamExt};
  65. use regex::Regex;
  66. use solana_account_decoder::UiAccountEncoding;
  67. use solana_client::rpc_config::{
  68. RpcAccountInfoConfig, RpcProgramAccountsConfig, RpcSendTransactionConfig,
  69. RpcTransactionLogsConfig, RpcTransactionLogsFilter,
  70. };
  71. use solana_client::rpc_filter::{Memcmp, RpcFilterType};
  72. use solana_client::{
  73. client_error::ClientError as SolanaClientError,
  74. nonblocking::{
  75. pubsub_client::{PubsubClient, PubsubClientError},
  76. rpc_client::RpcClient as AsyncRpcClient,
  77. },
  78. rpc_client::RpcClient,
  79. rpc_response::{Response as RpcResponse, RpcLogsResponse},
  80. };
  81. use solana_sdk::account::Account;
  82. use solana_sdk::commitment_config::CommitmentConfig;
  83. use solana_sdk::hash::Hash;
  84. use solana_sdk::instruction::{AccountMeta, Instruction};
  85. use solana_sdk::signature::{Signature, Signer};
  86. use solana_sdk::transaction::Transaction;
  87. use std::iter::Map;
  88. use std::marker::PhantomData;
  89. use std::ops::Deref;
  90. use std::pin::Pin;
  91. use std::sync::Arc;
  92. use std::vec::IntoIter;
  93. use thiserror::Error;
  94. use tokio::{
  95. runtime::Handle,
  96. sync::{
  97. mpsc::{unbounded_channel, UnboundedReceiver},
  98. RwLock,
  99. },
  100. task::JoinHandle,
  101. };
  102. pub use anchor_lang;
  103. pub use cluster::Cluster;
  104. pub use solana_client;
  105. pub use solana_sdk;
  106. mod cluster;
  107. #[cfg(not(feature = "async"))]
  108. mod blocking;
  109. #[cfg(feature = "async")]
  110. mod nonblocking;
  111. const PROGRAM_LOG: &str = "Program log: ";
  112. const PROGRAM_DATA: &str = "Program data: ";
  113. type UnsubscribeFn = Box<dyn FnOnce() -> Pin<Box<dyn Future<Output = ()> + Send>> + Send>;
  114. /// Client defines the base configuration for building RPC clients to
  115. /// communicate with Anchor programs running on a Solana cluster. It's
  116. /// primary use is to build a `Program` client via the `program` method.
  117. pub struct Client<C> {
  118. cfg: Config<C>,
  119. }
  120. impl<C: Clone + Deref<Target = impl Signer>> Client<C> {
  121. pub fn new(cluster: Cluster, payer: C) -> Self {
  122. Self {
  123. cfg: Config {
  124. cluster,
  125. payer,
  126. options: None,
  127. },
  128. }
  129. }
  130. pub fn new_with_options(cluster: Cluster, payer: C, options: CommitmentConfig) -> Self {
  131. Self {
  132. cfg: Config {
  133. cluster,
  134. payer,
  135. options: Some(options),
  136. },
  137. }
  138. }
  139. pub fn program(&self, program_id: Pubkey) -> Result<Program<C>, ClientError> {
  140. let cfg = Config {
  141. cluster: self.cfg.cluster.clone(),
  142. options: self.cfg.options,
  143. payer: self.cfg.payer.clone(),
  144. };
  145. Program::new(program_id, cfg)
  146. }
  147. }
  148. /// Auxiliary data structure to align the types of the Solana CLI utils with Anchor client.
  149. /// Client<C> implementation requires <C: Clone + Deref<Target = impl Signer>> which does not comply with Box<dyn Signer>
  150. /// that's used when loaded Signer from keypair file. This struct is used to wrap the usage.
  151. pub struct DynSigner(pub Arc<dyn Signer>);
  152. impl Signer for DynSigner {
  153. fn pubkey(&self) -> Pubkey {
  154. self.0.pubkey()
  155. }
  156. fn try_pubkey(&self) -> Result<Pubkey, solana_sdk::signer::SignerError> {
  157. self.0.try_pubkey()
  158. }
  159. fn sign_message(&self, message: &[u8]) -> solana_sdk::signature::Signature {
  160. self.0.sign_message(message)
  161. }
  162. fn try_sign_message(
  163. &self,
  164. message: &[u8],
  165. ) -> Result<solana_sdk::signature::Signature, solana_sdk::signer::SignerError> {
  166. self.0.try_sign_message(message)
  167. }
  168. fn is_interactive(&self) -> bool {
  169. self.0.is_interactive()
  170. }
  171. }
  172. // Internal configuration for a client.
  173. #[derive(Debug)]
  174. pub struct Config<C> {
  175. cluster: Cluster,
  176. payer: C,
  177. options: Option<CommitmentConfig>,
  178. }
  179. pub struct EventUnsubscriber<'a> {
  180. handle: JoinHandle<Result<(), ClientError>>,
  181. rx: UnboundedReceiver<UnsubscribeFn>,
  182. #[cfg(not(feature = "async"))]
  183. runtime_handle: &'a Handle,
  184. _lifetime_marker: PhantomData<&'a Handle>,
  185. }
  186. impl<'a> EventUnsubscriber<'a> {
  187. async fn unsubscribe_internal(mut self) {
  188. if let Some(unsubscribe) = self.rx.recv().await {
  189. unsubscribe().await;
  190. }
  191. let _ = self.handle.await;
  192. }
  193. }
  194. /// Program is the primary client handle to be used to build and send requests.
  195. pub struct Program<C> {
  196. program_id: Pubkey,
  197. cfg: Config<C>,
  198. sub_client: Arc<RwLock<Option<PubsubClient>>>,
  199. #[cfg(not(feature = "async"))]
  200. rt: tokio::runtime::Runtime,
  201. }
  202. impl<C: Deref<Target = impl Signer> + Clone> Program<C> {
  203. pub fn payer(&self) -> Pubkey {
  204. self.cfg.payer.pubkey()
  205. }
  206. pub fn id(&self) -> Pubkey {
  207. self.program_id
  208. }
  209. pub fn rpc(&self) -> RpcClient {
  210. RpcClient::new_with_commitment(
  211. self.cfg.cluster.url().to_string(),
  212. self.cfg.options.unwrap_or_default(),
  213. )
  214. }
  215. pub fn async_rpc(&self) -> AsyncRpcClient {
  216. AsyncRpcClient::new_with_commitment(
  217. self.cfg.cluster.url().to_string(),
  218. self.cfg.options.unwrap_or_default(),
  219. )
  220. }
  221. async fn account_internal<T: AccountDeserialize>(
  222. &self,
  223. address: Pubkey,
  224. ) -> Result<T, ClientError> {
  225. let rpc_client = AsyncRpcClient::new_with_commitment(
  226. self.cfg.cluster.url().to_string(),
  227. self.cfg.options.unwrap_or_default(),
  228. );
  229. let account = rpc_client
  230. .get_account_with_commitment(&address, CommitmentConfig::processed())
  231. .await?
  232. .value
  233. .ok_or(ClientError::AccountNotFound)?;
  234. let mut data: &[u8] = &account.data;
  235. T::try_deserialize(&mut data).map_err(Into::into)
  236. }
  237. async fn accounts_lazy_internal<T: AccountDeserialize + Discriminator>(
  238. &self,
  239. filters: Vec<RpcFilterType>,
  240. ) -> Result<ProgramAccountsIterator<T>, ClientError> {
  241. let account_type_filter =
  242. RpcFilterType::Memcmp(Memcmp::new_base58_encoded(0, &T::discriminator()));
  243. let config = RpcProgramAccountsConfig {
  244. filters: Some([vec![account_type_filter], filters].concat()),
  245. account_config: RpcAccountInfoConfig {
  246. encoding: Some(UiAccountEncoding::Base64),
  247. ..RpcAccountInfoConfig::default()
  248. },
  249. ..RpcProgramAccountsConfig::default()
  250. };
  251. Ok(ProgramAccountsIterator {
  252. inner: self
  253. .async_rpc()
  254. .get_program_accounts_with_config(&self.id(), config)
  255. .await?
  256. .into_iter()
  257. .map(|(key, account)| {
  258. Ok((key, T::try_deserialize(&mut (&account.data as &[u8]))?))
  259. }),
  260. })
  261. }
  262. async fn init_sub_client_if_needed(&self) -> Result<(), ClientError> {
  263. let lock = &self.sub_client;
  264. let mut client = lock.write().await;
  265. if client.is_none() {
  266. let sub_client = PubsubClient::new(self.cfg.cluster.ws_url()).await?;
  267. *client = Some(sub_client);
  268. }
  269. Ok(())
  270. }
  271. async fn on_internal<T: anchor_lang::Event + anchor_lang::AnchorDeserialize>(
  272. &self,
  273. f: impl Fn(&EventContext, T) + Send + 'static,
  274. ) -> Result<
  275. (
  276. JoinHandle<Result<(), ClientError>>,
  277. UnboundedReceiver<UnsubscribeFn>,
  278. ),
  279. ClientError,
  280. > {
  281. self.init_sub_client_if_needed().await?;
  282. let (tx, rx) = unbounded_channel::<_>();
  283. let config = RpcTransactionLogsConfig {
  284. commitment: self.cfg.options,
  285. };
  286. let program_id_str = self.program_id.to_string();
  287. let filter = RpcTransactionLogsFilter::Mentions(vec![program_id_str.clone()]);
  288. let lock = Arc::clone(&self.sub_client);
  289. let handle = tokio::spawn(async move {
  290. if let Some(ref client) = *lock.read().await {
  291. let (mut notifications, unsubscribe) =
  292. client.logs_subscribe(filter, config).await?;
  293. tx.send(unsubscribe).map_err(|e| {
  294. ClientError::SolanaClientPubsubError(PubsubClientError::RequestFailed {
  295. message: "Unsubscribe failed".to_string(),
  296. reason: e.to_string(),
  297. })
  298. })?;
  299. while let Some(logs) = notifications.next().await {
  300. let ctx = EventContext {
  301. signature: logs.value.signature.parse().unwrap(),
  302. slot: logs.context.slot,
  303. };
  304. let events = parse_logs_response(logs, &program_id_str);
  305. for e in events {
  306. f(&ctx, e);
  307. }
  308. }
  309. }
  310. Ok::<(), ClientError>(())
  311. });
  312. Ok((handle, rx))
  313. }
  314. }
  315. /// Iterator with items of type (Pubkey, T). Used to lazily deserialize account structs.
  316. /// Wrapper type hides the inner type from usages so the implementation can be changed.
  317. pub struct ProgramAccountsIterator<T> {
  318. inner: Map<IntoIter<(Pubkey, Account)>, AccountConverterFunction<T>>,
  319. }
  320. /// Function type that accepts solana accounts and returns deserialized anchor accounts
  321. type AccountConverterFunction<T> = fn((Pubkey, Account)) -> Result<(Pubkey, T), ClientError>;
  322. impl<T> Iterator for ProgramAccountsIterator<T> {
  323. type Item = Result<(Pubkey, T), ClientError>;
  324. fn next(&mut self) -> Option<Self::Item> {
  325. self.inner.next()
  326. }
  327. }
  328. pub fn handle_program_log<T: anchor_lang::Event + anchor_lang::AnchorDeserialize>(
  329. self_program_str: &str,
  330. l: &str,
  331. ) -> Result<(Option<T>, Option<String>, bool), ClientError> {
  332. use anchor_lang::__private::base64;
  333. use base64::engine::general_purpose::STANDARD;
  334. use base64::Engine;
  335. // Log emitted from the current program.
  336. if let Some(log) = l
  337. .strip_prefix(PROGRAM_LOG)
  338. .or_else(|| l.strip_prefix(PROGRAM_DATA))
  339. {
  340. let borsh_bytes = match STANDARD.decode(log) {
  341. Ok(borsh_bytes) => borsh_bytes,
  342. _ => {
  343. #[cfg(feature = "debug")]
  344. println!("Could not base64 decode log: {}", log);
  345. return Ok((None, None, false));
  346. }
  347. };
  348. let mut slice: &[u8] = &borsh_bytes[..];
  349. let disc: [u8; 8] = {
  350. let mut disc = [0; 8];
  351. disc.copy_from_slice(&borsh_bytes[..8]);
  352. slice = &slice[8..];
  353. disc
  354. };
  355. let mut event = None;
  356. if disc == T::discriminator() {
  357. let e: T = anchor_lang::AnchorDeserialize::deserialize(&mut slice)
  358. .map_err(|e| ClientError::LogParseError(e.to_string()))?;
  359. event = Some(e);
  360. }
  361. Ok((event, None, false))
  362. }
  363. // System log.
  364. else {
  365. let (program, did_pop) = handle_system_log(self_program_str, l);
  366. Ok((None, program, did_pop))
  367. }
  368. }
  369. pub fn handle_system_log(this_program_str: &str, log: &str) -> (Option<String>, bool) {
  370. if log.starts_with(&format!("Program {this_program_str} log:")) {
  371. (Some(this_program_str.to_string()), false)
  372. // `Invoke [1]` instructions are pushed to the stack in `parse_logs_response`,
  373. // so this ensures we only push CPIs to the stack at this stage
  374. } else if log.contains("invoke") && !log.ends_with("[1]") {
  375. (Some("cpi".to_string()), false) // Any string will do.
  376. } else {
  377. let re = Regex::new(r"^Program (.*) success*$").unwrap();
  378. if re.is_match(log) {
  379. (None, true)
  380. } else {
  381. (None, false)
  382. }
  383. }
  384. }
  385. pub struct Execution {
  386. stack: Vec<String>,
  387. }
  388. impl Execution {
  389. pub fn new(logs: &mut &[String]) -> Result<Self, ClientError> {
  390. let l = &logs[0];
  391. *logs = &logs[1..];
  392. let re = Regex::new(r"^Program (.*) invoke.*$").unwrap();
  393. let c = re
  394. .captures(l)
  395. .ok_or_else(|| ClientError::LogParseError(l.to_string()))?;
  396. let program = c
  397. .get(1)
  398. .ok_or_else(|| ClientError::LogParseError(l.to_string()))?
  399. .as_str()
  400. .to_string();
  401. Ok(Self {
  402. stack: vec![program],
  403. })
  404. }
  405. pub fn program(&self) -> String {
  406. assert!(!self.stack.is_empty());
  407. self.stack[self.stack.len() - 1].clone()
  408. }
  409. pub fn push(&mut self, new_program: String) {
  410. self.stack.push(new_program);
  411. }
  412. pub fn pop(&mut self) {
  413. assert!(!self.stack.is_empty());
  414. self.stack.pop().unwrap();
  415. }
  416. }
  417. #[derive(Debug)]
  418. pub struct EventContext {
  419. pub signature: Signature,
  420. pub slot: u64,
  421. }
  422. #[derive(Debug, Error)]
  423. pub enum ClientError {
  424. #[error("Account not found")]
  425. AccountNotFound,
  426. #[error("{0}")]
  427. AnchorError(#[from] anchor_lang::error::Error),
  428. #[error("{0}")]
  429. ProgramError(#[from] ProgramError),
  430. #[error("{0}")]
  431. SolanaClientError(#[from] SolanaClientError),
  432. #[error("{0}")]
  433. SolanaClientPubsubError(#[from] PubsubClientError),
  434. #[error("Unable to parse log: {0}")]
  435. LogParseError(String),
  436. #[error(transparent)]
  437. IOError(#[from] std::io::Error),
  438. }
  439. pub trait AsSigner {
  440. fn as_signer(&self) -> &dyn Signer;
  441. }
  442. impl<'a> AsSigner for Box<dyn Signer + 'a> {
  443. fn as_signer(&self) -> &dyn Signer {
  444. self.as_ref()
  445. }
  446. }
  447. /// `RequestBuilder` provides a builder interface to create and send
  448. /// transactions to a cluster.
  449. pub struct RequestBuilder<'a, C, S: 'a> {
  450. cluster: String,
  451. program_id: Pubkey,
  452. accounts: Vec<AccountMeta>,
  453. options: CommitmentConfig,
  454. instructions: Vec<Instruction>,
  455. payer: C,
  456. instruction_data: Option<Vec<u8>>,
  457. signers: Vec<S>,
  458. #[cfg(not(feature = "async"))]
  459. handle: &'a Handle,
  460. _phantom: PhantomData<&'a ()>,
  461. }
  462. // Shared implementation for all RequestBuilders
  463. impl<'a, C: Deref<Target = impl Signer> + Clone, S: AsSigner> RequestBuilder<'a, C, S> {
  464. #[must_use]
  465. pub fn payer(mut self, payer: C) -> Self {
  466. self.payer = payer;
  467. self
  468. }
  469. #[must_use]
  470. pub fn cluster(mut self, url: &str) -> Self {
  471. self.cluster = url.to_string();
  472. self
  473. }
  474. #[must_use]
  475. pub fn instruction(mut self, ix: Instruction) -> Self {
  476. self.instructions.push(ix);
  477. self
  478. }
  479. #[must_use]
  480. pub fn program(mut self, program_id: Pubkey) -> Self {
  481. self.program_id = program_id;
  482. self
  483. }
  484. /// Set the accounts to pass to the instruction.
  485. ///
  486. /// `accounts` argument can be:
  487. ///
  488. /// - Any type that implements [`ToAccountMetas`] trait
  489. /// - A vector of [`AccountMeta`]s (for remaining accounts)
  490. ///
  491. /// Note that the given accounts are appended to the previous list of accounts instead of
  492. /// overriding the existing ones (if any).
  493. ///
  494. /// # Example
  495. ///
  496. /// ```ignore
  497. /// program
  498. /// .request()
  499. /// // Regular accounts
  500. /// .accounts(accounts::Initialize {
  501. /// my_account: my_account_kp.pubkey(),
  502. /// payer: program.payer(),
  503. /// system_program: system_program::ID,
  504. /// })
  505. /// // Remaining accounts
  506. /// .accounts(vec![AccountMeta {
  507. /// pubkey: remaining,
  508. /// is_signer: true,
  509. /// is_writable: true,
  510. /// }])
  511. /// .args(instruction::Initialize { field: 42 })
  512. /// .send()?;
  513. /// ```
  514. #[must_use]
  515. pub fn accounts(mut self, accounts: impl ToAccountMetas) -> Self {
  516. let mut metas = accounts.to_account_metas(None);
  517. self.accounts.append(&mut metas);
  518. self
  519. }
  520. #[must_use]
  521. pub fn options(mut self, options: CommitmentConfig) -> Self {
  522. self.options = options;
  523. self
  524. }
  525. #[must_use]
  526. pub fn args(mut self, args: impl InstructionData) -> Self {
  527. self.instruction_data = Some(args.data());
  528. self
  529. }
  530. pub fn instructions(&self) -> Result<Vec<Instruction>, ClientError> {
  531. let mut instructions = self.instructions.clone();
  532. if let Some(ix_data) = &self.instruction_data {
  533. instructions.push(Instruction {
  534. program_id: self.program_id,
  535. data: ix_data.clone(),
  536. accounts: self.accounts.clone(),
  537. });
  538. }
  539. Ok(instructions)
  540. }
  541. fn signed_transaction_with_blockhash(
  542. &self,
  543. latest_hash: Hash,
  544. ) -> Result<Transaction, ClientError> {
  545. let instructions = self.instructions()?;
  546. let signers: Vec<&dyn Signer> = self.signers.iter().map(|s| s.as_signer()).collect();
  547. let mut all_signers = signers;
  548. all_signers.push(&*self.payer);
  549. let tx = Transaction::new_signed_with_payer(
  550. &instructions,
  551. Some(&self.payer.pubkey()),
  552. &all_signers,
  553. latest_hash,
  554. );
  555. Ok(tx)
  556. }
  557. pub fn transaction(&self) -> Result<Transaction, ClientError> {
  558. let instructions = &self.instructions;
  559. let tx = Transaction::new_with_payer(instructions, Some(&self.payer.pubkey()));
  560. Ok(tx)
  561. }
  562. async fn signed_transaction_internal(&self) -> Result<Transaction, ClientError> {
  563. let latest_hash =
  564. AsyncRpcClient::new_with_commitment(self.cluster.to_owned(), self.options)
  565. .get_latest_blockhash()
  566. .await?;
  567. let tx = self.signed_transaction_with_blockhash(latest_hash)?;
  568. Ok(tx)
  569. }
  570. async fn send_internal(&self) -> Result<Signature, ClientError> {
  571. let rpc_client = AsyncRpcClient::new_with_commitment(self.cluster.to_owned(), self.options);
  572. let latest_hash = rpc_client.get_latest_blockhash().await?;
  573. let tx = self.signed_transaction_with_blockhash(latest_hash)?;
  574. rpc_client
  575. .send_and_confirm_transaction(&tx)
  576. .await
  577. .map_err(Into::into)
  578. }
  579. async fn send_with_spinner_and_config_internal(
  580. &self,
  581. config: RpcSendTransactionConfig,
  582. ) -> Result<Signature, ClientError> {
  583. let rpc_client = AsyncRpcClient::new_with_commitment(self.cluster.to_owned(), self.options);
  584. let latest_hash = rpc_client.get_latest_blockhash().await?;
  585. let tx = self.signed_transaction_with_blockhash(latest_hash)?;
  586. rpc_client
  587. .send_and_confirm_transaction_with_spinner_and_config(
  588. &tx,
  589. rpc_client.commitment(),
  590. config,
  591. )
  592. .await
  593. .map_err(Into::into)
  594. }
  595. }
  596. fn parse_logs_response<T: anchor_lang::Event + anchor_lang::AnchorDeserialize>(
  597. logs: RpcResponse<RpcLogsResponse>,
  598. program_id_str: &str,
  599. ) -> Vec<T> {
  600. let mut logs = &logs.value.logs[..];
  601. let mut events: Vec<T> = Vec::new();
  602. if !logs.is_empty() {
  603. if let Ok(mut execution) = Execution::new(&mut logs) {
  604. // Create a new peekable iterator so that we can peek at the next log whilst iterating
  605. let mut logs_iter = logs.iter().peekable();
  606. while let Some(l) = logs_iter.next() {
  607. // Parse the log.
  608. let (event, new_program, did_pop) = {
  609. if program_id_str == execution.program() {
  610. handle_program_log(program_id_str, l).unwrap_or_else(|e| {
  611. println!("Unable to parse log: {e}");
  612. std::process::exit(1);
  613. })
  614. } else {
  615. let (program, did_pop) = handle_system_log(program_id_str, l);
  616. (None, program, did_pop)
  617. }
  618. };
  619. // Emit the event.
  620. if let Some(e) = event {
  621. events.push(e);
  622. }
  623. // Switch program context on CPI.
  624. if let Some(new_program) = new_program {
  625. execution.push(new_program);
  626. }
  627. // Program returned.
  628. if did_pop {
  629. execution.pop();
  630. // If the current iteration popped then it means there was a
  631. //`Program x success` log. If the next log in the iteration is
  632. // of depth [1] then we're not within a CPI and this is a new instruction.
  633. //
  634. // We need to ensure that the `Execution` instance is updated with
  635. // the next program ID, or else `execution.program()` will cause
  636. // a panic during the next iteration.
  637. if let Some(&next_log) = logs_iter.peek() {
  638. if next_log.ends_with("invoke [1]") {
  639. let re = Regex::new(r"^Program (.*) invoke.*$").unwrap();
  640. let next_instruction =
  641. re.captures(next_log).unwrap().get(1).unwrap().as_str();
  642. // Within this if block, there will always be a regex match.
  643. // Therefore it's safe to unwrap and the captured program ID
  644. // at index 1 can also be safely unwrapped.
  645. execution.push(next_instruction.to_string());
  646. }
  647. };
  648. }
  649. }
  650. }
  651. }
  652. events
  653. }
  654. #[cfg(test)]
  655. mod tests {
  656. use solana_client::rpc_response::RpcResponseContext;
  657. // Creating a mock struct that implements `anchor_lang::events`
  658. // for type inference in `test_logs`
  659. use anchor_lang::prelude::*;
  660. #[derive(Debug, Clone, Copy)]
  661. #[event]
  662. pub struct MockEvent {}
  663. use super::*;
  664. #[test]
  665. fn new_execution() {
  666. let mut logs: &[String] =
  667. &["Program 7Y8VDzehoewALqJfyxZYMgYCnMTCDhWuGfJKUvjYWATw invoke [1]".to_string()];
  668. let exe = Execution::new(&mut logs).unwrap();
  669. assert_eq!(
  670. exe.stack[0],
  671. "7Y8VDzehoewALqJfyxZYMgYCnMTCDhWuGfJKUvjYWATw".to_string()
  672. );
  673. }
  674. #[test]
  675. fn handle_system_log_pop() {
  676. let log = "Program 7Y8VDzehoewALqJfyxZYMgYCnMTCDhWuGfJKUvjYWATw success";
  677. let (program, did_pop) = handle_system_log("asdf", log);
  678. assert_eq!(program, None);
  679. assert!(did_pop);
  680. }
  681. #[test]
  682. fn handle_system_log_no_pop() {
  683. let log = "Program 7swsTUiQ6KUK4uFYquQKg4epFRsBnvbrTf2fZQCa2sTJ qwer";
  684. let (program, did_pop) = handle_system_log("asdf", log);
  685. assert_eq!(program, None);
  686. assert!(!did_pop);
  687. }
  688. #[test]
  689. fn test_parse_logs_response() -> Result<()> {
  690. // Mock logs received within an `RpcResponse`. These are based on a Jupiter transaction.
  691. let logs = vec![
  692. "Program VeryCoolProgram invoke [1]", // Outer instruction #1 starts
  693. "Program log: Instruction: VeryCoolEvent",
  694. "Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA invoke [2]",
  695. "Program log: Instruction: Transfer",
  696. "Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA consumed 4645 of 664387 compute units",
  697. "Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA success",
  698. "Program VeryCoolProgram consumed 42417 of 700000 compute units",
  699. "Program VeryCoolProgram success", // Outer instruction #1 ends
  700. "Program EvenCoolerProgram invoke [1]", // Outer instruction #2 starts
  701. "Program log: Instruction: EvenCoolerEvent",
  702. "Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA invoke [2]",
  703. "Program log: Instruction: TransferChecked",
  704. "Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA consumed 6200 of 630919 compute units",
  705. "Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA success",
  706. "Program HyaB3W9q6XdA5xwpU4XnSZV94htfmbmqJXZcEbRaJutt invoke [2]",
  707. "Program log: Instruction: Swap",
  708. "Program log: INVARIANT: SWAP",
  709. "Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA invoke [3]",
  710. "Program log: Instruction: Transfer",
  711. "Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA consumed 4736 of 539321 compute units",
  712. "Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA success",
  713. "Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA invoke [3]",
  714. "Program log: Instruction: Transfer",
  715. "Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA consumed 4645 of 531933 compute units",
  716. "Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA success",
  717. "Program HyaB3W9q6XdA5xwpU4XnSZV94htfmbmqJXZcEbRaJutt consumed 84670 of 610768 compute units",
  718. "Program HyaB3W9q6XdA5xwpU4XnSZV94htfmbmqJXZcEbRaJutt success",
  719. "Program EvenCoolerProgram invoke [2]",
  720. "Program EvenCoolerProgram consumed 2021 of 523272 compute units",
  721. "Program EvenCoolerProgram success",
  722. "Program HyaB3W9q6XdA5xwpU4XnSZV94htfmbmqJXZcEbRaJutt invoke [2]",
  723. "Program log: Instruction: Swap",
  724. "Program log: INVARIANT: SWAP",
  725. "Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA invoke [3]",
  726. "Program log: Instruction: Transfer",
  727. "Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA consumed 4736 of 418618 compute units",
  728. "Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA success",
  729. "Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA invoke [3]",
  730. "Program log: Instruction: Transfer",
  731. "Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA consumed 4645 of 411230 compute units",
  732. "Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA success",
  733. "Program HyaB3W9q6XdA5xwpU4XnSZV94htfmbmqJXZcEbRaJutt consumed 102212 of 507607 compute units",
  734. "Program HyaB3W9q6XdA5xwpU4XnSZV94htfmbmqJXZcEbRaJutt success",
  735. "Program EvenCoolerProgram invoke [2]",
  736. "Program EvenCoolerProgram consumed 2021 of 402569 compute units",
  737. "Program EvenCoolerProgram success",
  738. "Program 9W959DqEETiGZocYWCQPaJ6sBmUzgfxXfqGeTEdp3aQP invoke [2]",
  739. "Program log: Instruction: Swap",
  740. "Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA invoke [3]",
  741. "Program log: Instruction: Transfer",
  742. "Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA consumed 4736 of 371140 compute units",
  743. "Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA success",
  744. "Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA invoke [3]",
  745. "Program log: Instruction: MintTo",
  746. "Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA consumed 4492 of 341800 compute units",
  747. "Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA success",
  748. "Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA invoke [3]",
  749. "Program log: Instruction: Transfer",
  750. "Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA consumed 4645 of 334370 compute units",
  751. "Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA success",
  752. "Program 9W959DqEETiGZocYWCQPaJ6sBmUzgfxXfqGeTEdp3aQP consumed 57610 of 386812 compute units",
  753. "Program 9W959DqEETiGZocYWCQPaJ6sBmUzgfxXfqGeTEdp3aQP success",
  754. "Program EvenCoolerProgram invoke [2]",
  755. "Program EvenCoolerProgram consumed 2021 of 326438 compute units",
  756. "Program EvenCoolerProgram success",
  757. "Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA invoke [2]",
  758. "Program log: Instruction: TransferChecked",
  759. "Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA consumed 6173 of 319725 compute units",
  760. "Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA success",
  761. "Program EvenCoolerProgram consumed 345969 of 657583 compute units",
  762. "Program EvenCoolerProgram success", // Outer instruction #2 ends
  763. "Program ComputeBudget111111111111111111111111111111 invoke [1]",
  764. "Program ComputeBudget111111111111111111111111111111 success",
  765. "Program ComputeBudget111111111111111111111111111111 invoke [1]",
  766. "Program ComputeBudget111111111111111111111111111111 success"];
  767. // Converting to Vec<String> as expected in `RpcLogsResponse`
  768. let logs: Vec<String> = logs.iter().map(|&l| l.to_string()).collect();
  769. let program_id_str = "VeryCoolProgram";
  770. // No events returned here. Just ensuring that the function doesn't panic
  771. // due an incorrectly emptied stack.
  772. let _: Vec<MockEvent> = parse_logs_response(
  773. RpcResponse {
  774. context: RpcResponseContext::new(0),
  775. value: RpcLogsResponse {
  776. signature: "".to_string(),
  777. err: None,
  778. logs: logs.to_vec(),
  779. },
  780. },
  781. program_id_str,
  782. );
  783. Ok(())
  784. }
  785. }