transfer_checked.rs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. mod setup;
  2. use {
  3. setup::{account, mint, TOKEN_PROGRAM_ID},
  4. solana_program_test::{tokio, ProgramTest},
  5. solana_sdk::{
  6. program_pack::Pack,
  7. pubkey::Pubkey,
  8. signature::{Keypair, Signer},
  9. transaction::Transaction,
  10. },
  11. };
  12. #[test_case::test_case(TOKEN_PROGRAM_ID ; "p-token")]
  13. #[tokio::test]
  14. async fn transfer_checked(token_program: Pubkey) {
  15. let mut context = ProgramTest::new("pinocchio_token_program", TOKEN_PROGRAM_ID, None)
  16. .start_with_context()
  17. .await;
  18. // Given a mint account.
  19. let mint_authority = Keypair::new();
  20. let freeze_authority = Pubkey::new_unique();
  21. let mint = mint::initialize(
  22. &mut context,
  23. mint_authority.pubkey(),
  24. Some(freeze_authority),
  25. &token_program,
  26. )
  27. .await
  28. .unwrap();
  29. // And a token account with 100 tokens.
  30. let owner = Keypair::new();
  31. let account = account::initialize(&mut context, &mint, &owner.pubkey(), &token_program).await;
  32. mint::mint(
  33. &mut context,
  34. &mint,
  35. &account,
  36. &mint_authority,
  37. 100,
  38. &token_program,
  39. )
  40. .await
  41. .unwrap();
  42. // When we transfer the tokens.
  43. let destination = Pubkey::new_unique();
  44. let destination_account =
  45. account::initialize(&mut context, &mint, &destination, &token_program).await;
  46. let mut transfer_ix = spl_token::instruction::transfer_checked(
  47. &spl_token::ID,
  48. &account,
  49. &mint,
  50. &destination_account,
  51. &owner.pubkey(),
  52. &[],
  53. 100,
  54. 4,
  55. )
  56. .unwrap();
  57. transfer_ix.program_id = token_program;
  58. let tx = Transaction::new_signed_with_payer(
  59. &[transfer_ix],
  60. Some(&context.payer.pubkey()),
  61. &[&context.payer, &owner],
  62. context.last_blockhash,
  63. );
  64. context.banks_client.process_transaction(tx).await.unwrap();
  65. // Then an account has the correct data.
  66. let account = context.banks_client.get_account(account).await.unwrap();
  67. assert!(account.is_some());
  68. let account = account.unwrap();
  69. let account = spl_token::state::Account::unpack(&account.data).unwrap();
  70. assert!(account.amount == 0);
  71. }