lib.rs 30 KB

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