approve.rs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. #![cfg(feature = "test-sbf")]
  2. mod setup;
  3. use setup::{account, mint, TOKEN_PROGRAM_ID};
  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(TOKEN_PROGRAM_ID ; "p-token")]
  13. #[tokio::test]
  14. async fn approve(token_program: Pubkey) {
  15. let mut context = ProgramTest::new("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 approve a delegate.
  43. let delegate = Pubkey::new_unique();
  44. let mut approve_ix = spl_token::instruction::approve(
  45. &spl_token::ID,
  46. &account,
  47. &delegate,
  48. &owner.pubkey(),
  49. &[],
  50. 50,
  51. )
  52. .unwrap();
  53. approve_ix.program_id = token_program;
  54. let tx = Transaction::new_signed_with_payer(
  55. &[approve_ix],
  56. Some(&context.payer.pubkey()),
  57. &[&context.payer, &owner],
  58. context.last_blockhash,
  59. );
  60. context.banks_client.process_transaction(tx).await.unwrap();
  61. // Then the account should have the delegate and delegated amount.
  62. let account = context.banks_client.get_account(account).await.unwrap();
  63. assert!(account.is_some());
  64. let account = account.unwrap();
  65. let account = spl_token::state::Account::unpack(&account.data).unwrap();
  66. assert!(account.delegate.is_some());
  67. assert!(account.delegate.unwrap() == delegate);
  68. assert!(account.delegated_amount == 50);
  69. }