forked from jamesbachini/Solana-JSON
-
Notifications
You must be signed in to change notification settings - Fork 0
/
solana-json.rs
56 lines (47 loc) · 1.42 KB
/
solana-json.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
use solana_program::{
account_info::{next_account_info, AccountInfo},
entrypoint,
entrypoint::ProgramResult,
log::{sol_log_compute_units, sol_log_params, sol_log_slice},
msg,
program_error::ProgramError,
pubkey::Pubkey,
};
use borsh::{BorshDeserialize, BorshSerialize};
use std::mem;
pub trait Serdes: Sized + BorshSerialize + BorshDeserialize {
fn pack(&self, dst: &mut [u8]) {
let encoded = self.try_to_vec().unwrap();
dst[..encoded.len()].copy_from_slice(&encoded);
}
fn unpack(src: &[u8]) -> Result<Self, ProgramError> {
Self::try_from_slice(src).map_err(|_| ProgramError::InvalidAccountData)
}
}
#[derive(BorshSerialize, BorshDeserialize, PartialEq, Debug)]
pub struct Message {
pub txt: String,
}
impl Serdes for Message {}
entrypoint!(entry);
fn entry(
program_id: &Pubkey,
accounts: &[AccountInfo],
instruction_data: &[u8],
) -> ProgramResult {
let accounts_iter = &mut accounts.iter();
let account = next_account_info(accounts_iter)?;
let mut data = account.try_borrow_mut_data()?;
let mut unpacked = Message::unpack(&data).expect("Failed to read data");
let mut memo = String::from_utf8(instruction_data.to_vec()).map_err(|err| {
msg!("Invalid UTF-8, from byte {}");
ProgramError::InvalidInstructionData
})?;
let mut iter = memo.chars();
let mut slice = iter.as_str();
let mut txtFinal = String::from(slice);
txtFinal.truncate(996);
unpacked.txt = txtFinal;
unpacked.pack(&mut data);
Ok(())
}