get_pda.rs 1.0 KB

1234567891011121314151617181920212223242526272829303132
  1. use solana_program::{
  2. entrypoint::ProgramResult,
  3. account_info::{ AccountInfo, next_account_info},
  4. msg,
  5. pubkey::Pubkey,
  6. program_error::ProgramError
  7. };
  8. use borsh::BorshDeserialize;
  9. use crate::state::Favorites;
  10. pub fn get_pda(
  11. program_id: &Pubkey,
  12. accounts: &[AccountInfo],
  13. ) -> ProgramResult {
  14. let account_iter = &mut accounts.iter();
  15. let user = next_account_info(account_iter)?;
  16. let favorite_account = next_account_info(account_iter)?;
  17. // deriving the favorite pda
  18. let (favorite_pda, _) = Pubkey::find_program_address(&[b"favorite", user.key.as_ref()], program_id);
  19. // Checking if the favorite account is same as the derived favorite pda
  20. if favorite_account.key != &favorite_pda {
  21. return Err(ProgramError::IncorrectProgramId);
  22. };
  23. let favorites = Favorites::try_from_slice(&favorite_account.data.borrow())?;
  24. msg!("User {}'s favorite number is {}, favorite color is: {}, and their hobbies are {:#?}", user.key, favorites.number, favorites.color, favorites.hobbies);
  25. Ok(())
  26. }