shadow_drive_sdk/client/top_up.rs
1use crate::{
2 constants::TOKEN_MINT,
3 derived_addresses,
4 models::{ShadowDriveResult, ShdwDriveResponse},
5 ShadowDriveClient,
6};
7use solana_sdk::{pubkey::Pubkey, signer::Signer, transaction::Transaction};
8use spl_associated_token_account::get_associated_token_address;
9use spl_token::instruction::transfer;
10
11impl<T> ShadowDriveClient<T>
12where
13 T: Signer,
14{
15 /// Allows user to top up stake account, transfering some amount of $SHDW.
16 /// * `storage_account_key` - The public key of the [`StorageAccount`](crate::models::StorageAccount) that you want to top up stake for.
17 /// * `amount` - The amount of $SHDW to transfer into stake account
18 /// # Example
19 ///
20 /// ```
21 /// # use shadow_drive_rust::{ShadowDriveClient, derived_addresses::storage_account};
22 /// # use solana_client::rpc_client::RpcClient;
23 /// # use solana_sdk::{
24 /// # pubkey::Pubkey,
25 /// # signature::Keypair,
26 /// # signer::{keypair::read_keypair_file, Signer},
27 /// # };
28 /// #
29 /// # let keypair = read_keypair_file(KEYPAIR_PATH).expect("failed to load keypair at path");
30 /// # let user_pubkey = keypair.pubkey();
31 /// # let rpc_client = RpcClient::new("https://ssc-dao.genesysgo.net");
32 /// # let shdw_drive_client = ShadowDriveClient::new(keypair, rpc_client);
33 /// # let (storage_account_key, _) = storage_account(&user_pubkey, 0);
34 /// # let top_up_amount: u64 = 1000
35 /// #
36 /// let top_up = shdw_drive_client
37 /// .top_up(&storage_account_key, top_up_amount)
38 /// .await?;
39 /// ```
40 pub async fn top_up(
41 &self,
42 storage_account_key: &Pubkey,
43 amount: u64,
44 ) -> ShadowDriveResult<ShdwDriveResponse> {
45 let wallet_pubkey = self.wallet.pubkey();
46 let owner_ata = get_associated_token_address(&wallet_pubkey, &TOKEN_MINT);
47 let (stake_account, _) = derived_addresses::stake_account(storage_account_key);
48
49 let instruction = transfer(
50 &spl_token::id(),
51 &owner_ata,
52 &stake_account,
53 &self.wallet.pubkey(),
54 &[&self.wallet.pubkey()],
55 amount,
56 )
57 .unwrap();
58
59 let mut txn = Transaction::new_with_payer(&[instruction], Some(&wallet_pubkey));
60 let recent_blockhash = self.rpc_client.get_latest_blockhash().await?;
61 txn.try_sign(&[&self.wallet], recent_blockhash)?;
62 let txn_result = self.rpc_client.send_and_confirm_transaction(&txn).await?;
63
64 Ok(ShdwDriveResponse {
65 txid: txn_result.to_string(),
66 })
67 }
68}