ui_amount_to_amount.rs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. mod setup;
  2. use {
  3. crate::setup::mollusk::{create_mint_account, mollusk},
  4. core::str::from_utf8,
  5. mollusk_svm::result::Check,
  6. setup::{mint, TOKEN_PROGRAM_ID},
  7. solana_program_test::{tokio, ProgramTest},
  8. solana_pubkey::Pubkey,
  9. solana_signer::Signer,
  10. solana_transaction::Transaction,
  11. };
  12. #[tokio::test]
  13. async fn ui_amount_to_amount() {
  14. let mut context = ProgramTest::new("pinocchio_token_program", TOKEN_PROGRAM_ID, None)
  15. .start_with_context()
  16. .await;
  17. // Given a mint account.
  18. let mint_authority = Pubkey::new_unique();
  19. let freeze_authority = Pubkey::new_unique();
  20. let mint = mint::initialize(
  21. &mut context,
  22. mint_authority,
  23. Some(freeze_authority),
  24. &TOKEN_PROGRAM_ID,
  25. )
  26. .await
  27. .unwrap();
  28. let ui_amount_to_amount_ix =
  29. spl_token::instruction::ui_amount_to_amount(&spl_token::ID, &mint, "1000.00").unwrap();
  30. let tx = Transaction::new_signed_with_payer(
  31. &[ui_amount_to_amount_ix],
  32. Some(&context.payer.pubkey()),
  33. &[&context.payer],
  34. context.last_blockhash,
  35. );
  36. context.banks_client.process_transaction(tx).await.unwrap();
  37. // Then the transaction should succeed.
  38. let account = context.banks_client.get_account(mint).await.unwrap();
  39. assert!(account.is_some());
  40. }
  41. #[test]
  42. fn ui_amount_to_amount_with_maximum_decimals() {
  43. // Given a mint account with `u8::MAX` as decimals.
  44. let mint = Pubkey::new_unique();
  45. let mint_authority = Pubkey::new_unique();
  46. let freeze_authority = Pubkey::new_unique();
  47. let mint_account = create_mint_account(
  48. mint_authority,
  49. Some(freeze_authority),
  50. u8::MAX,
  51. &TOKEN_PROGRAM_ID,
  52. );
  53. // String representing the ui value `0.000....002`
  54. let mut ui_amount = [b'0'; u8::MAX as usize + 1];
  55. ui_amount[1] = b'.';
  56. ui_amount[ui_amount.len() - 1] = b'2';
  57. let input = from_utf8(&ui_amount).unwrap();
  58. // When we convert the ui amount using the mint, the transaction should
  59. // succeed and return 20 as the amount.
  60. let instruction =
  61. spl_token::instruction::ui_amount_to_amount(&spl_token::ID, &mint, input).unwrap();
  62. mollusk().process_and_validate_instruction(
  63. &instruction,
  64. &[(mint, mint_account)],
  65. &[Check::success(), Check::return_data(&20u64.to_le_bytes())],
  66. );
  67. }