approve_checked.rs 2.3 KB

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