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
use anchor_lang::{
prelude::{ProgramError, Pubkey},
AccountDeserialize, Discriminator,
};
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},
rpc_filter::{Memcmp, MemcmpEncodedBytes, RpcFilterType},
};
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, rc::Rc, sync::Arc, time::Duration, vec::IntoIter};
use thiserror::Error;
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),
}
pub struct Client {
pub config_path: String,
pub config: Config,
pub rpc_timeout: Duration,
pub commitment: CommitmentConfig,
pub confirm_transaction_initial_timeout: Duration,
pub payer: Rc<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,
payer: Rc::from(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 payer_key(&self) -> Pubkey {
self.payer.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 mut signers = vec![];
signers.push(&*self.payer);
let tx = Transaction::new_signed_with_payer(
ixs,
Some(&self.payer_key()),
&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());
}
}
}