Solana program to receive Serial Data

PHOTO EMBED

Wed Mar 22 2023 19:09:28 GMT+0000 (Coordinated Universal Time)

Saved by @luisjdominguezp #typescript

use borsh::{BorshDeserialize, BorshSerialize};
use solana_program::{
    account_info::{next_account_info, AccountInfo},
    entrypoint,
    entrypoint::ProgramResult,
    msg,
    program_error::ProgramError,
    pubkey::Pubkey,
};

/// Define the type of state stored in accounts
#[derive(BorshSerialize, BorshDeserialize, Debug)]
pub struct GreetingAccount {
    pub counter: u32,
}

entrypoint!(process_instruction);

pub fn process_instruction(
    program_id: &Pubkey, // Public key of the account the hello world program was loaded into
    accounts: &[AccountInfo], // The account to say hello to
    _instruction_data: &[u8], // Ignored, all helloworld instructions are hellos
) -> ProgramResult {

    let accounts_iter = &mut accounts.iter();
    let account = next_account_info(accounts_iter)?;
    
    msg!("Start instruction decode");
    let data_received = GreetingAccount::try_from_slice(_instruction_data).map_err(|err| {
      msg!("Receiving counter u32, {:?}", err);
      ProgramError::InvalidInstructionData  
    })?;
    msg!("Greeting passed to program is {:?}", data_received);
    msg!("Count: {}!", data_received.counter);

   // The account must be owned by the program in order to modify its data
    if account.owner != program_id {
        msg!("Wrong permissions. Greeted account does not have the correct program id");
        return Err(ProgramError::IncorrectProgramId);
    }

    let mut greeting_account = GreetingAccount::try_from_slice(&account.data.borrow())?;
    greeting_account.counter += data_received.counter;
    greeting_account.serialize(&mut &mut account.data.borrow_mut()[..])?;

    msg!("Greeted {} time(s)!", greeting_account.counter);

    Ok(())
}
content_copyCOPY