1
0

mint.rs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. use std::mem::size_of;
  2. use solana_program_test::{BanksClientError, ProgramTestContext};
  3. use solana_sdk::{
  4. program_error::ProgramError, pubkey::Pubkey, signature::Keypair, signer::Signer,
  5. system_instruction, transaction::Transaction,
  6. };
  7. use spl_token_interface::state::mint::Mint;
  8. pub async fn initialize(
  9. context: &mut ProgramTestContext,
  10. mint_authority: Pubkey,
  11. freeze_authority: Option<Pubkey>,
  12. program_id: &Pubkey,
  13. ) -> Result<Pubkey, ProgramError> {
  14. // Mint account keypair.
  15. let account = Keypair::new();
  16. let account_size = size_of::<Mint>();
  17. let rent = context.banks_client.get_rent().await.unwrap();
  18. let mut initialize_ix = spl_token::instruction::initialize_mint(
  19. &spl_token::ID,
  20. &account.pubkey(),
  21. &mint_authority,
  22. freeze_authority.as_ref(),
  23. 4,
  24. )
  25. .unwrap();
  26. // Switches the program id in case we are using a "custom" one.
  27. initialize_ix.program_id = *program_id;
  28. // Create a new account and initialize as a mint.
  29. let instructions = vec![
  30. system_instruction::create_account(
  31. &context.payer.pubkey(),
  32. &account.pubkey(),
  33. rent.minimum_balance(account_size),
  34. account_size as u64,
  35. program_id,
  36. ),
  37. initialize_ix,
  38. ];
  39. let tx = Transaction::new_signed_with_payer(
  40. &instructions,
  41. Some(&context.payer.pubkey()),
  42. &[&context.payer, &account],
  43. context.last_blockhash,
  44. );
  45. context.banks_client.process_transaction(tx).await.unwrap();
  46. Ok(account.pubkey())
  47. }
  48. pub async fn mint(
  49. context: &mut ProgramTestContext,
  50. mint: &Pubkey,
  51. account: &Pubkey,
  52. mint_authority: &Keypair,
  53. amount: u64,
  54. program_id: &Pubkey,
  55. ) -> Result<(), BanksClientError> {
  56. let mut mint_ix = spl_token::instruction::mint_to(
  57. &spl_token::ID,
  58. mint,
  59. account,
  60. &mint_authority.pubkey(),
  61. &[],
  62. amount,
  63. )
  64. .unwrap();
  65. // Switches the program id to the token program.
  66. mint_ix.program_id = *program_id;
  67. let tx = Transaction::new_signed_with_payer(
  68. &[mint_ix],
  69. Some(&context.payer.pubkey()),
  70. &[&context.payer, mint_authority],
  71. context.last_blockhash,
  72. );
  73. context.banks_client.process_transaction(tx).await
  74. }