1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
use anchor_lang::{
prelude::{ProgramError, Pubkey},
AccountDeserialize, Discriminator,
};
use regex::Regex;
use solana_account_decoder::UiAccountEncoding;
use solana_clap_utils::keypair::DefaultSigner;
use solana_cli_config::{Config, ConfigInput};
use solana_client::{
client_error::ClientError as SolanaClientError,
pubsub_client::PubsubClientError,
rpc_client::RpcClient,
rpc_config::{
RpcAccountInfoConfig, RpcProgramAccountsConfig, RpcSendTransactionConfig,
RpcSimulateTransactionAccountsConfig, RpcSimulateTransactionConfig,
},
rpc_filter::{Memcmp, MemcmpEncodedBytes, RpcFilterType},
rpc_response::RpcSimulateTransactionResult,
};
use solana_program::instruction::Instruction;
use solana_remote_wallet::remote_wallet::RemoteWalletManager;
use solana_sdk::{
account::Account,
bs58,
commitment_config::{CommitmentConfig, CommitmentLevel},
signer::Signer,
transaction::Transaction,
};
use std::{io, iter::Map, sync::Arc, time::Duration, vec::IntoIter};
use tabled::Tabled;
use thiserror::Error;
use crate::render::render_object;
const PROGRAM_LOG: &str = "Program log: ";
const PROGRAM_DATA: &str = "Program data: ";
pub struct ProgramAccountsIterator<T> {
inner: Map<IntoIter<(Pubkey, Account)>, AccountConverterFunction<T>>,
}
type AccountConverterFunction<T> = fn((Pubkey, Account)) -> Result<(Pubkey, T), ClientError>;
impl<T> Iterator for ProgramAccountsIterator<T> {
type Item = Result<(Pubkey, T), ClientError>;
fn next(&mut self) -> Option<Self::Item> {
self.inner.next()
}
}
#[derive(Debug, Error)]
pub enum ClientError {
#[error("Account not found")]
AccountNotFound,
#[error("{0}")]
AnchorError(#[from] anchor_lang::error::Error),
#[error("{0}")]
ProgramError(#[from] ProgramError),
#[error("{0}")]
SolanaClientError(#[from] SolanaClientError),
#[error("{0}")]
SolanaClientPubsubError(#[from] PubsubClientError),
#[error("Unable to parse log: {0}")]
LogParseError(String),
#[error("Unable to parse event")]
EventParseError,
#[error("Simulate error{0}")]
SimulateError(String),
}
pub struct SimulateResult {
result: RpcSimulateTransactionResult,
lamports: u64,
}
pub struct Client {
pub config_path: String,
pub config: Config,
pub rpc_timeout: Duration,
pub commitment: CommitmentConfig,
pub confirm_transaction_initial_timeout: Duration,
pub signers: Vec<Box<dyn Signer>>,
}
impl Client {
pub fn new(config_path: String) -> Result<Self, io::Error> {
let mut config = Config::load(config_path.as_str())?;
let rpc_timeout = Duration::from_secs(30);
if config.websocket_url.is_empty() {
config.websocket_url = Config::compute_websocket_url(&config.json_rpc_url);
}
let commitment = CommitmentConfig {
commitment: CommitmentLevel::Processed,
};
let confirm_transaction_initial_timeout = Duration::from_secs(30);
let default_signer_arg_name = "keypair".to_string();
let (_, default_signer_path) =
ConfigInput::compute_keypair_path_setting("", &config.keypair_path);
let default_signer = DefaultSigner::new(default_signer_arg_name, &default_signer_path);
let mut wallet_manager: Option<Arc<RemoteWalletManager>> = None;
let payer = default_signer.signer_from_path(&Default::default(), &mut wallet_manager);
Ok(Client {
config_path,
config,
rpc_timeout,
commitment,
confirm_transaction_initial_timeout,
signers: vec![payer.unwrap()],
})
}
#[allow(dead_code)]
pub fn rpc_client(&self) -> RpcClient {
RpcClient::new_with_timeouts_and_commitment(
self.config.json_rpc_url.to_string(),
self.rpc_timeout,
self.commitment,
self.confirm_transaction_initial_timeout,
)
}
pub fn lamports(&self) -> u64 {
let lamports = self.rpc_client().get_balance(&self.payer_key());
lamports.unwrap()
}
pub fn payer_key(&self) -> Pubkey {
self.signers[0].pubkey()
}
pub fn account<T: AccountDeserialize>(&self, address: Pubkey) -> Result<T, ClientError> {
let account = self
.rpc_client()
.get_account_with_commitment(&address, CommitmentConfig::processed())?
.value
.ok_or(ClientError::AccountNotFound)?;
let mut data: &[u8] = &account.data;
T::try_deserialize(&mut data).map_err(Into::into)
}
pub fn accounts<T: AccountDeserialize + Discriminator>(
&self,
program_id: &Pubkey,
filters: Vec<RpcFilterType>,
) -> Result<Vec<(Pubkey, T)>, ClientError> {
self.accounts_lazy(program_id, filters)?.collect()
}
pub fn accounts_lazy<T: AccountDeserialize + Discriminator>(
&self,
program_id: &Pubkey,
filters: Vec<RpcFilterType>,
) -> Result<ProgramAccountsIterator<T>, ClientError> {
let account_type_filter = RpcFilterType::Memcmp(Memcmp {
offset: 0,
bytes: MemcmpEncodedBytes::Base58(bs58::encode(T::discriminator()).into_string()),
encoding: None,
});
let config = RpcProgramAccountsConfig {
filters: Some([vec![account_type_filter], filters].concat()),
account_config: RpcAccountInfoConfig {
encoding: Some(UiAccountEncoding::Base64),
..RpcAccountInfoConfig::default()
},
..RpcProgramAccountsConfig::default()
};
Ok(ProgramAccountsIterator {
inner: self
.rpc_client()
.get_program_accounts_with_config(program_id, config)?
.into_iter()
.map(|(key, account)| {
Ok((key, T::try_deserialize(&mut (&account.data as &[u8]))?))
}),
})
}
pub fn send_and_confirm(&self, ixs: &[Instruction]) {
let rpc_client = self.rpc_client();
let recent_blockhash = rpc_client.get_latest_blockhash().unwrap();
let tx = Transaction::new_signed_with_payer(
ixs,
Some(&self.payer_key()),
&self.signers,
recent_blockhash,
);
let resp = rpc_client.send_and_confirm_transaction_with_spinner_and_config(
&tx,
self.commitment,
RpcSendTransactionConfig {
skip_preflight: true,
preflight_commitment: None,
encoding: None,
max_retries: Some(3),
min_context_slot: None,
},
);
if resp.is_err() {
println!(
"{}",
resp.err()
.unwrap()
.get_transaction_error()
.unwrap()
.to_string()
);
} else {
println!("{}", resp.unwrap().to_string());
}
}
pub fn simulate(&self, ixs: &[Instruction]) -> Result<SimulateResult, ClientError> {
let rpc_client = self.rpc_client();
let recent_blockhash = rpc_client.get_latest_blockhash().unwrap();
let tx = Transaction::new_signed_with_payer(
ixs,
Some(&self.payer_key()),
&self.signers,
recent_blockhash,
);
let mut config = RpcSimulateTransactionConfig::default();
config.replace_recent_blockhash = true;
config.commitment = Some(self.commitment);
config.accounts = Some(RpcSimulateTransactionAccountsConfig {
encoding: Some(UiAccountEncoding::Base64),
addresses: vec![self.payer_key().to_string()],
});
let before_lamports = self.lamports();
let resp = rpc_client.simulate_transaction_with_config(&tx, config);
if resp.is_err() {
return Err(ClientError::SimulateError(resp.err().unwrap().to_string()));
}
let result = resp.unwrap().value;
let lamports = if result.accounts.is_some() {
let accounts = result.accounts.clone().unwrap();
if accounts[0].is_some() {
before_lamports - accounts[0].clone().unwrap().lamports
} else {
before_lamports
}
} else {
before_lamports
};
Ok(SimulateResult { result, lamports })
}
pub fn simulate_and_print<
T: anchor_lang::Event + anchor_lang::AnchorDeserialize + Tabled + Copy,
>(
&self,
program_id: &Pubkey,
ixs: &[Instruction],
) -> Option<T> {
let resp = self.simulate(ixs);
if resp.is_err() {
println!("Simulate error:{:?}", resp.err());
None
} else {
let result = resp.unwrap();
let event_parsed: Result<T, ClientError> = result.parse_event(program_id);
if event_parsed.is_err() {
for log in result.result.logs.clone().unwrap() {
println!("{}", log);
}
None
} else {
let event = event_parsed.unwrap();
println!(
"{}",
render_object(
event,
format!(
"SimulateSwap\n fee_lamports:{} units:{}",
result.lamports,
result.result.units_consumed.unwrap()
)
.as_str(),
None
)
);
Some(event)
}
}
}
}
pub trait EventParser {
fn parse_event<T: anchor_lang::Event + anchor_lang::AnchorDeserialize>(
&self,
program_id: &Pubkey,
) -> Result<T, ClientError>;
}
impl EventParser for SimulateResult {
fn parse_event<T: anchor_lang::Event + anchor_lang::AnchorDeserialize>(
&self,
program_id: &Pubkey,
) -> Result<T, ClientError> {
let mut logs = &self.result.logs.clone().unwrap()[..];
if logs.len() == 0 {
println!("{:?}", self.result);
return Err(ClientError::EventParseError);
}
let mut execution = Execution::new(&mut logs)?;
let self_program_str = program_id.to_string();
for l in logs {
let (event, new_program, did_pop) = {
if self_program_str == execution.program() {
handle_program_log(&self_program_str, l).unwrap_or_else(|e| {
println!("Unable to parse log: {}", e);
std::process::exit(1);
})
} else {
let (program, did_pop) = handle_system_log(&self_program_str, l);
(None, program, did_pop)
}
};
if let Some(e) = event {
return Ok(e);
}
if let Some(new_program) = new_program {
execution.push(new_program);
}
if did_pop {
execution.pop();
}
}
Err(ClientError::EventParseError)
}
}
struct Execution {
stack: Vec<String>,
}
impl Execution {
pub fn new(logs: &mut &[String]) -> Result<Self, ClientError> {
let l = &logs[0];
*logs = &logs[1..];
let re = Regex::new(r"^Program (.*) invoke.*$").unwrap();
let c = re
.captures(l)
.ok_or_else(|| ClientError::LogParseError(l.to_string()))?;
let program = c
.get(1)
.ok_or_else(|| ClientError::LogParseError(l.to_string()))?
.as_str()
.to_string();
Ok(Self {
stack: vec![program],
})
}
pub fn program(&self) -> String {
assert!(!self.stack.is_empty());
self.stack[self.stack.len() - 1].clone()
}
pub fn push(&mut self, new_program: String) {
self.stack.push(new_program);
}
pub fn pop(&mut self) {
assert!(!self.stack.is_empty());
self.stack.pop().unwrap();
}
}
fn handle_program_log<T: anchor_lang::Event + anchor_lang::AnchorDeserialize>(
self_program_str: &str,
l: &str,
) -> Result<(Option<T>, Option<String>, bool), ClientError> {
if let Some(log) = l
.strip_prefix(PROGRAM_LOG)
.or_else(|| l.strip_prefix(PROGRAM_DATA))
{
let borsh_bytes = match anchor_lang::__private::base64::decode(&log) {
Ok(borsh_bytes) => borsh_bytes,
_ => {
return Ok((None, None, false));
}
};
let mut slice: &[u8] = &borsh_bytes[..];
let disc: [u8; 8] = {
let mut disc = [0; 8];
disc.copy_from_slice(&borsh_bytes[..8]);
slice = &slice[8..];
disc
};
let mut event = None;
if disc == T::discriminator() {
let e: T = anchor_lang::AnchorDeserialize::deserialize(&mut slice)
.map_err(|e| ClientError::LogParseError(e.to_string()))?;
event = Some(e);
}
Ok((event, None, false))
}
else {
let (program, did_pop) = handle_system_log(self_program_str, l);
Ok((None, program, did_pop))
}
}
fn handle_system_log(this_program_str: &str, log: &str) -> (Option<String>, bool) {
if log.starts_with(&format!("Program {} log:", this_program_str)) {
(Some(this_program_str.to_string()), false)
} else if log.contains("invoke") {
(Some("cpi".to_string()), false) } else {
let re = Regex::new(r"^Program (.*) success*$").unwrap();
if re.is_match(log) {
(None, true)
} else {
(None, false)
}
}
}