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 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720
use crate::{config::CONFIG, Reader, TempClone};
use anchor_client::{
anchor_lang::{
prelude::System, solana_program::program_pack::Pack, AccountDeserialize, Id,
InstructionData, ToAccountMetas,
},
solana_client::rpc_config::RpcTransactionConfig,
solana_sdk::{
account::Account,
bpf_loader,
commitment_config::CommitmentConfig,
instruction::Instruction,
loader_instruction,
pubkey::Pubkey,
signer::{keypair::Keypair, Signer},
system_instruction,
transaction::Transaction,
},
Client as AnchorClient, ClientError as Error, Cluster, Program,
};
use borsh::BorshDeserialize;
use fehler::{throw, throws};
use futures::stream::{self, StreamExt};
use log::debug;
use serde::de::DeserializeOwned;
use solana_account_decoder::parse_token::UiTokenAmount;
use solana_cli_output::display::println_transaction;
use solana_transaction_status::{EncodedConfirmedTransactionWithStatusMeta, UiTransactionEncoding};
// The deprecated `create_associated_token_account` function is used because of different versions
// of some crates are required in this `client` crate and `anchor-spl` crate
#[allow(deprecated)]
use spl_associated_token_account::{create_associated_token_account, get_associated_token_address};
use std::{mem, rc::Rc};
use std::{thread::sleep, time::Duration};
// @TODO: Make compatible with the latest Anchor deps.
// https://github.com/project-serum/anchor/pull/1307#issuecomment-1022592683
const RETRY_LOCALNET_EVERY_MILLIS: u64 = 500;
type Payer = Rc<Keypair>;
/// `Client` allows you to send typed RPC requests to a Solana cluster.
pub struct Client {
payer: Keypair,
anchor_client: AnchorClient<Payer>,
}
impl Client {
/// Creates a new `Client` instance.
pub fn new(payer: Keypair) -> Self {
Self {
payer: payer.clone(),
anchor_client: AnchorClient::new_with_options(
Cluster::Localnet,
Rc::new(payer),
CommitmentConfig::confirmed(),
),
}
}
/// Gets client's payer.
pub fn payer(&self) -> &Keypair {
&self.payer
}
/// Gets the internal Anchor client to call Anchor client's methods directly.
pub fn anchor_client(&self) -> &AnchorClient<Payer> {
&self.anchor_client
}
/// Creates [Program] instance to communicate with the selected program.
pub fn program(&self, program_id: Pubkey) -> Program<Payer> {
self.anchor_client.program(program_id).unwrap()
}
/// Finds out if the Solana localnet is running.
///
/// Set `retry` to `true` when you want to wait for up to 15 seconds until
/// the localnet is running (until 30 retries with 500ms delays are performed).
pub async fn is_localnet_running(&self, retry: bool) -> bool {
let rpc_client = self
.anchor_client
.program(System::id())
.unwrap()
.async_rpc();
for _ in 0..(if retry {
CONFIG.test.validator_startup_timeout / RETRY_LOCALNET_EVERY_MILLIS
} else {
1
}) {
if rpc_client.get_health().await.is_ok() {
return true;
}
if retry {
sleep(Duration::from_millis(RETRY_LOCALNET_EVERY_MILLIS));
}
}
false
}
/// Gets deserialized data from the chosen account serialized with Anchor
///
/// # Errors
///
/// It fails when:
/// - the account does not exist.
/// - the Solana cluster is not running.
/// - deserialization failed.
#[throws]
pub async fn account_data<T>(&self, account: Pubkey) -> T
where
T: AccountDeserialize + Send + 'static,
{
let program = self.anchor_client.program(System::id()).unwrap();
program.account::<T>(account).await.unwrap()
}
/// Gets deserialized data from the chosen account serialized with Bincode
///
/// # Errors
///
/// It fails when:
/// - the account does not exist.
/// - the Solana cluster is not running.
/// - deserialization failed.
#[throws]
pub async fn account_data_bincode<T>(&self, account: Pubkey) -> T
where
T: DeserializeOwned + Send + 'static,
{
let account = self
.get_account(account)
.await?
.ok_or(Error::AccountNotFound)?;
bincode::deserialize(&account.data)
.map_err(|_| Error::LogParseError("Bincode deserialization failed".to_string()))?
}
/// Gets deserialized data from the chosen account serialized with Borsh
///
/// # Errors
///
/// It fails when:
/// - the account does not exist.
/// - the Solana cluster is not running.
/// - deserialization failed.
#[throws]
pub async fn account_data_borsh<T>(&self, account: Pubkey) -> T
where
T: BorshDeserialize + Send + 'static,
{
let account = self
.get_account(account)
.await?
.ok_or(Error::AccountNotFound)?;
T::try_from_slice(&account.data)
.map_err(|_| Error::LogParseError("Bincode deserialization failed".to_string()))?
}
/// Returns all information associated with the account of the provided [Pubkey].
///
/// # Errors
///
/// It fails when the Solana cluster is not running.
#[throws]
pub async fn get_account(&self, account: Pubkey) -> Option<Account> {
let rpc_client = self.anchor_client.program(System::id())?.async_rpc();
rpc_client
.get_account_with_commitment(&account, rpc_client.commitment())
.await
.unwrap()
.value
}
/// Sends the Anchor instruction with associated accounts and signers.
///
/// # Example
///
/// ```rust,ignore
/// use trdelnik_client::*;
///
/// pub async fn initialize(
/// client: &Client,
/// state: Pubkey,
/// user: Pubkey,
/// system_program: Pubkey,
/// signers: impl IntoIterator<Item = Keypair> + Send + 'static,
/// ) -> Result<EncodedConfirmedTransactionWithStatusMeta, ClientError> {
/// Ok(client
/// .send_instruction(
/// PROGRAM_ID,
/// turnstile::instruction::Initialize {},
/// turnstile::accounts::Initialize {
/// state: a_state,
/// user: a_user,
/// system_program: a_system_program,
/// },
/// signers,
/// )
/// .await?)
/// }
/// ```
#[throws]
pub async fn send_instruction(
&self,
program: Pubkey,
instruction: impl InstructionData + Send + 'static,
accounts: impl ToAccountMetas + Send + 'static,
signers: impl IntoIterator<Item = Keypair> + Send + 'static,
) -> EncodedConfirmedTransactionWithStatusMeta {
let program = self.anchor_client.program(program).unwrap();
let mut request = program.request().args(instruction).accounts(accounts);
let signers = signers.into_iter().collect::<Vec<_>>();
for signer in &signers {
request = request.signer(signer);
}
let signature = request.send().await.unwrap();
let rpc_client = self.anchor_client.program(System::id())?.async_rpc();
rpc_client
.get_transaction_with_config(
&signature,
RpcTransactionConfig {
encoding: Some(UiTransactionEncoding::Binary),
commitment: Some(CommitmentConfig::confirmed()),
max_supported_transaction_version: None,
},
)
.await
.unwrap()
}
/// Sends the transaction with associated instructions and signers.
///
/// # Example
///
/// ```rust,ignore
/// #[throws]
/// pub async fn create_account(
/// &self,
/// keypair: &Keypair,
/// lamports: u64,
/// space: u64,
/// owner: &Pubkey,
/// ) -> EncodedConfirmedTransaction {
/// self.send_transaction(
/// &[system_instruction::create_account(
/// &self.payer().pubkey(),
/// &keypair.pubkey(),
/// lamports,
/// space,
/// owner,
/// )],
/// [keypair],
/// )
/// .await?
/// }
/// ```
#[throws]
pub async fn send_transaction(
&self,
instructions: &[Instruction],
signers: impl IntoIterator<Item = &Keypair> + Send,
) -> EncodedConfirmedTransactionWithStatusMeta {
let rpc_client = self
.anchor_client
.program(System::id())
.unwrap()
.async_rpc();
let mut signers = signers.into_iter().collect::<Vec<_>>();
signers.push(self.payer());
let tx = &Transaction::new_signed_with_payer(
instructions,
Some(&self.payer.pubkey()),
&signers,
rpc_client.get_latest_blockhash().await.unwrap(),
);
// @TODO make this call async with task::spawn_blocking
let signature = rpc_client.send_and_confirm_transaction(tx).await.unwrap();
let transaction = rpc_client
.get_transaction_with_config(
&signature,
RpcTransactionConfig {
encoding: Some(UiTransactionEncoding::Binary),
commitment: Some(CommitmentConfig::confirmed()),
max_supported_transaction_version: None,
},
)
.await
.unwrap();
transaction
}
/// Airdrops lamports to the chosen account.
#[throws]
pub async fn airdrop(&self, address: Pubkey, lamports: u64) {
let rpc_client = self
.anchor_client
.program(System::id())
.unwrap()
.async_rpc();
let signature = rpc_client
.request_airdrop(&address, lamports)
.await
.unwrap();
let (airdrop_result, error) = loop {
match rpc_client.get_signature_status(&signature).await.unwrap() {
Some(Ok(_)) => {
debug!("{} lamports airdropped", lamports);
break (true, None);
}
Some(Err(transaction_error)) => break (false, Some(transaction_error)),
None => sleep(Duration::from_millis(500)),
}
};
if !airdrop_result {
throw!(Error::SolanaClientError(error.unwrap().into()));
}
}
/// Get balance of an account
#[throws]
pub async fn get_balance(&mut self, address: &Pubkey) -> u64 {
let rpc_client = self.anchor_client.program(System::id())?.async_rpc();
rpc_client.get_balance(address).await?
}
/// Get token balance of an token account
#[throws]
pub async fn get_token_balance(&mut self, address: Pubkey) -> UiTokenAmount {
let rpc_client = self.anchor_client.program(System::id())?.async_rpc();
rpc_client.get_token_account_balance(&address).await?
}
/// Deploys a program based on it's name.
/// This function wraps boilerplate code required for the successful deployment of a program,
/// i.e. SOLs airdrop etc.
///
/// # Arguments
///
/// * `program_keypair` - [Keypair] used for the program
/// * `program_name` - Name of the program to be deployed
///
/// # Example:
///
/// *Project structure*
///
/// ```text
/// project/
/// - programs/
/// - awesome_contract/
/// - ...
/// - Cargo.toml
/// - turnstile/
/// - ...
/// - Cargo.toml
/// - ...
/// - Cargo.toml
/// ```
///
/// *Code*
///
/// ```rust,ignore
/// client.deploy_program(program_keypair(0), "awesome_contract");
/// client.deploy_program(program_keypair(1), "turnstile");
/// ```
#[throws]
pub async fn deploy_by_name(&self, program_keypair: &Keypair, program_name: &str) {
debug!("reading program data");
let reader = Reader::new();
let mut program_data = reader
.program_data(program_name)
.await
.expect("reading program data failed");
debug!("airdropping the minimum balance required to deploy the program");
// TODO: This will fail on devnet where airdrops are limited to 1 SOL
self.airdrop(self.payer().pubkey(), 5_000_000_000)
.await
.expect("airdropping for deployment failed");
debug!("deploying program");
self.deploy(program_keypair.clone(), mem::take(&mut program_data))
.await?;
// this will slow down the process because if we call program instruction right after deploy,
// data are not yet completely deployed so error occures
let deploy_done = loop {
match self.anchor_client.program(program_keypair.pubkey()) {
Ok(_) => {
debug!("program deployed succefully");
sleep(Duration::from_millis(1000));
break true;
}
Err(_) => {
sleep(Duration::from_millis(500));
}
}
};
// this is not necessarry, but we want to avoid "throws" macro warning of unused code
if !deploy_done {
throw!(Error::ProgramError(
solana_sdk::program_error::ProgramError::Custom(0)
));
}
}
/// Deploys the program.
#[throws]
async fn deploy(&self, program_keypair: Keypair, program_data: Vec<u8>) {
const PROGRAM_DATA_CHUNK_SIZE: usize = 900;
let program_data_len = program_data.len();
let rpc_client = self
.anchor_client
.program(System::id())
.unwrap()
.async_rpc();
let system_program = self.anchor_client.program(System::id()).unwrap();
debug!("program_data_len: {}", program_data_len);
debug!("create program account");
let min_balance_for_rent_exemption = rpc_client
.get_minimum_balance_for_rent_exemption(program_data_len)
.await
.unwrap();
let create_account_ix: Instruction = system_instruction::create_account(
&self.payer.pubkey(),
&program_keypair.pubkey(),
min_balance_for_rent_exemption,
program_data_len as u64,
&bpf_loader::id(),
);
system_program
.request()
.instruction(create_account_ix)
.signer(&program_keypair)
.send()
.await
.unwrap();
debug!("write program data");
let mut offset = 0usize;
let mut futures_vec = Vec::new();
for chunk in program_data.chunks(PROGRAM_DATA_CHUNK_SIZE) {
let loader_write_ix = loader_instruction::write(
&program_keypair.pubkey(),
&bpf_loader::id(),
offset as u32,
chunk.to_vec(),
);
futures_vec.push(async {
let system_program = self.anchor_client.program(System::id()).unwrap();
system_program
.request()
.instruction(loader_write_ix)
.signer(&program_keypair)
.send()
.await
.unwrap();
});
offset += chunk.len();
}
stream::iter(futures_vec)
.buffer_unordered(500)
.collect::<Vec<_>>()
.await;
debug!("finalize program");
let loader_finalize_ix =
loader_instruction::finalize(&program_keypair.pubkey(), &bpf_loader::id());
system_program
.request()
.instruction(loader_finalize_ix)
.signer(&program_keypair)
.send()
.await
.unwrap();
debug!("program deployed");
}
/// Creates accounts.
#[throws]
pub async fn create_account(
&self,
keypair: &Keypair,
lamports: u64,
space: u64,
owner: &Pubkey,
) -> EncodedConfirmedTransactionWithStatusMeta {
self.send_transaction(
&[system_instruction::create_account(
&self.payer().pubkey(),
&keypair.pubkey(),
lamports,
space,
owner,
)],
[keypair],
)
.await?
}
/// Creates rent exempt account.
#[throws]
pub async fn create_account_rent_exempt(
&mut self,
keypair: &Keypair,
space: u64,
owner: &Pubkey,
) -> EncodedConfirmedTransactionWithStatusMeta {
let rpc_client = self.anchor_client.program(System::id())?.async_rpc();
self.send_transaction(
&[system_instruction::create_account(
&self.payer().pubkey(),
&keypair.pubkey(),
rpc_client
.get_minimum_balance_for_rent_exemption(space as usize)
.await?,
space,
owner,
)],
[keypair],
)
.await?
}
/// Executes a transaction constructing a token mint.
#[throws]
pub async fn create_token_mint(
&self,
mint: &Keypair,
authority: Pubkey,
freeze_authority: Option<Pubkey>,
decimals: u8,
) -> EncodedConfirmedTransactionWithStatusMeta {
let rpc_client = self.anchor_client.program(System::id())?.async_rpc();
self.send_transaction(
&[
system_instruction::create_account(
&self.payer().pubkey(),
&mint.pubkey(),
rpc_client
.get_minimum_balance_for_rent_exemption(spl_token::state::Mint::LEN)
.await?,
spl_token::state::Mint::LEN as u64,
&spl_token::ID,
),
spl_token::instruction::initialize_mint(
&spl_token::ID,
&mint.pubkey(),
&authority,
freeze_authority.as_ref(),
decimals,
)
.unwrap(),
],
[mint],
)
.await?
}
/// Executes a transaction that mints tokens from a mint to an account belonging to that mint.
#[throws]
pub async fn mint_tokens(
&self,
mint: Pubkey,
authority: &Keypair,
account: Pubkey,
amount: u64,
) -> EncodedConfirmedTransactionWithStatusMeta {
self.send_transaction(
&[spl_token::instruction::mint_to(
&spl_token::ID,
&mint,
&account,
&authority.pubkey(),
&[],
amount,
)
.unwrap()],
[authority],
)
.await?
}
/// Executes a transaction constructing a token account of the specified mint. The account needs to be empty and belong to system for this to work.
/// Prefer to use [create_associated_token_account] if you don't need the provided account to contain the token account.
#[throws]
pub async fn create_token_account(
&self,
account: &Keypair,
mint: &Pubkey,
owner: &Pubkey,
) -> EncodedConfirmedTransactionWithStatusMeta {
let rpc_client = self.anchor_client.program(System::id())?.async_rpc();
self.send_transaction(
&[
system_instruction::create_account(
&self.payer().pubkey(),
&account.pubkey(),
rpc_client
.get_minimum_balance_for_rent_exemption(spl_token::state::Account::LEN)
.await?,
spl_token::state::Account::LEN as u64,
&spl_token::ID,
),
spl_token::instruction::initialize_account(
&spl_token::ID,
&account.pubkey(),
mint,
owner,
)
.unwrap(),
],
[account],
)
.await?
}
/// Executes a transaction constructing the associated token account of the specified mint belonging to the owner. This will fail if the account already exists.
#[throws]
pub async fn create_associated_token_account(&self, owner: &Keypair, mint: Pubkey) -> Pubkey {
self.send_transaction(
#[allow(deprecated)]
&[create_associated_token_account(
&self.payer().pubkey(),
&owner.pubkey(),
&mint,
)],
&[],
)
.await?;
get_associated_token_address(&owner.pubkey(), &mint)
}
/// Executes a transaction creating and filling the given account with the given data.
/// The account is required to be empty and will be owned by bpf_loader afterwards.
#[throws]
pub async fn create_account_with_data(&self, account: &Keypair, data: Vec<u8>) {
const DATA_CHUNK_SIZE: usize = 900;
let rpc_client = self.anchor_client.program(System::id())?.async_rpc();
self.send_transaction(
&[system_instruction::create_account(
&self.payer().pubkey(),
&account.pubkey(),
rpc_client
.get_minimum_balance_for_rent_exemption(data.len())
.await?,
data.len() as u64,
&bpf_loader::id(),
)],
[account],
)
.await?;
let mut offset = 0usize;
for chunk in data.chunks(DATA_CHUNK_SIZE) {
debug!("writing bytes {} to {}", offset, offset + chunk.len());
self.send_transaction(
&[loader_instruction::write(
&account.pubkey(),
&bpf_loader::id(),
offset as u32,
chunk.to_vec(),
)],
[account],
)
.await?;
offset += chunk.len();
}
}
}
/// Utility trait for printing transaction results.
pub trait PrintableTransaction {
/// Pretty print the transaction results, tagged with the given name for distinguishability.
fn print_named(&self, name: &str);
/// Pretty print the transaction results.
fn print(&self) {
self.print_named("");
}
}
impl PrintableTransaction for EncodedConfirmedTransactionWithStatusMeta {
fn print_named(&self, name: &str) {
let tx = self.transaction.transaction.decode().unwrap();
debug!("EXECUTE {} (slot {})", name, self.slot);
match self.transaction.meta.clone() {
Some(meta) => println_transaction(&tx, Some(&meta), " ", None, None),
_ => println_transaction(&tx, None, " ", None, None),
}
}
}