lib.rs 30 KB

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