amount_to_ui_amount.rs 2.3 KB

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