2020-01-30 09:47:22 -08:00
|
|
|
//! @brief Example Rust-based BPF program that exercises error handling
|
|
|
|
|
|
|
|
extern crate solana_sdk;
|
|
|
|
use num_derive::FromPrimitive;
|
|
|
|
use solana_sdk::{
|
|
|
|
account_info::AccountInfo, entrypoint, info, program_error::ProgramError, pubkey::Pubkey,
|
|
|
|
};
|
|
|
|
use thiserror::Error;
|
|
|
|
|
|
|
|
/// Custom program errors
|
|
|
|
#[derive(Error, Debug, Clone, PartialEq, FromPrimitive)]
|
|
|
|
pub enum MyError {
|
2020-01-31 10:58:07 -08:00
|
|
|
#[error("Default enum start")]
|
|
|
|
DefaultEnumStart,
|
2020-01-30 09:47:22 -08:00
|
|
|
#[error("The Answer")]
|
|
|
|
TheAnswer = 42,
|
|
|
|
}
|
|
|
|
impl From<MyError> for ProgramError {
|
|
|
|
fn from(e: MyError) -> Self {
|
|
|
|
ProgramError::CustomError(e as u32)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
entrypoint!(process_instruction);
|
|
|
|
fn process_instruction(
|
|
|
|
_program_id: &Pubkey,
|
2020-01-30 20:40:27 -08:00
|
|
|
accounts: &[AccountInfo],
|
2020-01-30 09:47:22 -08:00
|
|
|
instruction_data: &[u8],
|
|
|
|
) -> Result<(), ProgramError> {
|
|
|
|
match instruction_data[0] {
|
|
|
|
1 => {
|
|
|
|
info!("return success");
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
2 => {
|
|
|
|
info!("return a builtin");
|
2020-01-30 20:40:27 -08:00
|
|
|
Err(ProgramError::InvalidAccountData)
|
2020-01-30 09:47:22 -08:00
|
|
|
}
|
|
|
|
3 => {
|
2020-01-31 10:58:07 -08:00
|
|
|
info!("return default enum start value");
|
|
|
|
Err(MyError::DefaultEnumStart.into())
|
2020-01-30 09:47:22 -08:00
|
|
|
}
|
|
|
|
4 => {
|
2020-01-31 10:58:07 -08:00
|
|
|
info!("return custom error");
|
|
|
|
Err(MyError::TheAnswer.into())
|
2020-01-30 09:47:22 -08:00
|
|
|
}
|
2020-01-30 20:40:27 -08:00
|
|
|
6 => {
|
|
|
|
let data = accounts[0].try_borrow_mut_data()?;
|
|
|
|
let data2 = accounts[0].try_borrow_mut_data()?;
|
|
|
|
assert_eq!(*data, *data2);
|
|
|
|
Ok(())
|
|
|
|
}
|
2020-01-30 09:47:22 -08:00
|
|
|
_ => {
|
|
|
|
info!("Unrecognized command");
|
|
|
|
Err(ProgramError::InvalidInstructionData)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|