test.rs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. use borsh::BorshDeserialize;
  2. use litesvm::LiteSVM;
  3. use program_derived_addresses_native_program::state::{IncrementPageVisits, PageVisits};
  4. use solana_instruction::{AccountMeta, Instruction};
  5. use solana_keypair::{Keypair, Signer};
  6. use solana_native_token::LAMPORTS_PER_SOL;
  7. use solana_pubkey::Pubkey;
  8. use solana_rent::Rent;
  9. use solana_system_interface::instruction::create_account;
  10. use solana_transaction::Transaction;
  11. #[test]
  12. fn test_pda() {
  13. let mut svm = LiteSVM::new();
  14. let program_id = Pubkey::new_unique();
  15. let program_bytes =
  16. include_bytes!("../../tests/fixtures/program_derived_addresses_native_program.so");
  17. svm.add_program(program_id, program_bytes).unwrap();
  18. let payer = Keypair::new();
  19. svm.airdrop(&payer.pubkey(), LAMPORTS_PER_SOL * 10).unwrap();
  20. let test_user = Keypair::new();
  21. let rent = Rent::default();
  22. let create_ix = create_account(
  23. &payer.pubkey(),
  24. &test_user.pubkey(),
  25. solana_rent::Rent::minimum_balance(&rent, 0),
  26. 0,
  27. &solana_system_interface::program::ID,
  28. );
  29. let tx = Transaction::new_signed_with_payer(
  30. &[create_ix],
  31. Some(&payer.pubkey()),
  32. &[&payer, &test_user],
  33. svm.latest_blockhash(),
  34. );
  35. let _ = svm.send_transaction(tx).is_ok();
  36. let (pda, bump) =
  37. Pubkey::find_program_address(&[b"page_visits", test_user.pubkey().as_ref()], &program_id);
  38. let data = borsh::to_vec(&PageVisits {
  39. page_visits: 0,
  40. bump,
  41. })
  42. .unwrap();
  43. let ix = Instruction {
  44. program_id,
  45. accounts: vec![
  46. AccountMeta::new(pda, false),
  47. AccountMeta::new(test_user.pubkey(), false),
  48. AccountMeta::new(payer.pubkey(), true),
  49. AccountMeta::new(solana_system_interface::program::ID, false),
  50. ],
  51. data,
  52. };
  53. let tx = Transaction::new_signed_with_payer(
  54. &[ix],
  55. Some(&payer.pubkey()),
  56. &[&payer],
  57. svm.latest_blockhash(),
  58. );
  59. let _ = svm.send_transaction(tx).is_ok();
  60. let data = borsh::to_vec(&IncrementPageVisits {}).unwrap();
  61. let ix = Instruction {
  62. program_id,
  63. accounts: vec![
  64. AccountMeta::new(pda, false),
  65. AccountMeta::new(payer.pubkey(), true),
  66. ],
  67. data,
  68. };
  69. let tx = Transaction::new_signed_with_payer(
  70. &[ix],
  71. Some(&payer.pubkey()),
  72. &[&payer],
  73. svm.latest_blockhash(),
  74. );
  75. let _ = svm.send_transaction(tx).is_ok();
  76. // read page visits
  77. let account_info = svm.get_account(&pda).unwrap();
  78. let read_page_visits = PageVisits::try_from_slice(&account_info.data).unwrap();
  79. assert_eq!(read_page_visits.page_visits, 1);
  80. }