ui_amount_to_amount.rs 1.0 KB

1234567891011121314151617181920212223242526272829303132
  1. use {
  2. super::{check_account_owner, try_ui_amount_into_amount},
  3. core::str::from_utf8,
  4. pinocchio::{
  5. account_info::AccountInfo, program::set_return_data, program_error::ProgramError,
  6. ProgramResult,
  7. },
  8. spl_token_interface::{
  9. error::TokenError,
  10. state::{load, mint::Mint},
  11. },
  12. };
  13. pub fn process_ui_amount_to_amount(
  14. accounts: &[AccountInfo],
  15. instruction_data: &[u8],
  16. ) -> ProgramResult {
  17. let ui_amount = from_utf8(instruction_data).map_err(|_error| TokenError::InvalidInstruction)?;
  18. let mint_info = accounts.first().ok_or(ProgramError::NotEnoughAccountKeys)?;
  19. check_account_owner(mint_info)?;
  20. // SAFETY: single immutable borrow to `mint_info` account data and
  21. // `load` validates that the mint is initialized.
  22. let mint = unsafe {
  23. load::<Mint>(mint_info.borrow_data_unchecked()).map_err(|_| TokenError::InvalidMint)?
  24. };
  25. let amount = try_ui_amount_into_amount(ui_amount, mint.decimals)?;
  26. set_return_data(&amount.to_le_bytes());
  27. Ok(())
  28. }