Add get_sysvar() helper to sdk
This commit is contained in:
committed by
mergify[bot]
parent
45552d271a
commit
2c99b23ad7
@ -4,6 +4,7 @@ use solana_sdk::{
|
||||
keyed_account::{create_keyed_accounts_unified, KeyedAccount},
|
||||
message::Message,
|
||||
pubkey::Pubkey,
|
||||
sysvar::Sysvar,
|
||||
};
|
||||
use std::{cell::RefCell, fmt::Debug, rc::Rc, sync::Arc};
|
||||
|
||||
@ -100,7 +101,7 @@ pub trait InvokeContext {
|
||||
deserialize_us: u64,
|
||||
);
|
||||
/// Get sysvar data
|
||||
fn get_sysvar_data(&mut self, id: &Pubkey) -> Option<Rc<Vec<u8>>>;
|
||||
fn get_sysvar_data(&self, id: &Pubkey) -> Option<Rc<Vec<u8>>>;
|
||||
}
|
||||
|
||||
/// Convenience macro to log a message with an `Rc<RefCell<dyn Logger>>`
|
||||
@ -133,6 +134,21 @@ macro_rules! ic_msg {
|
||||
};
|
||||
}
|
||||
|
||||
pub fn get_sysvar<T: Sysvar>(
|
||||
invoke_context: &dyn InvokeContext,
|
||||
id: &Pubkey,
|
||||
) -> Result<T, InstructionError> {
|
||||
let sysvar_data = invoke_context.get_sysvar_data(id).ok_or_else(|| {
|
||||
ic_msg!(invoke_context, "Unable to get sysvar {}", id);
|
||||
InstructionError::UnsupportedSysvar
|
||||
})?;
|
||||
|
||||
bincode::deserialize(&sysvar_data).map_err(|err| {
|
||||
ic_msg!(invoke_context, "Unable to get sysvar {}: {:?}", id, err);
|
||||
InstructionError::UnsupportedSysvar
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, AbiExample)]
|
||||
pub struct BpfComputeBudget {
|
||||
/// Number of compute units that an instruction is allowed. Compute units
|
||||
@ -338,6 +354,22 @@ impl<'a> MockInvokeContext<'a> {
|
||||
invoke_context
|
||||
}
|
||||
}
|
||||
|
||||
pub fn mock_set_sysvar<T: Sysvar>(
|
||||
mock_invoke_context: &mut MockInvokeContext,
|
||||
id: Pubkey,
|
||||
sysvar: T,
|
||||
) -> Result<(), InstructionError> {
|
||||
let mut data = Vec::with_capacity(T::size_of());
|
||||
|
||||
bincode::serialize_into(&mut data, &sysvar).map_err(|err| {
|
||||
ic_msg!(mock_invoke_context, "Unable to serialize sysvar: {:?}", err);
|
||||
InstructionError::GenericError
|
||||
})?;
|
||||
mock_invoke_context.sysvars.push((id, Some(Rc::new(data))));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
impl<'a> InvokeContext for MockInvokeContext<'a> {
|
||||
fn push(
|
||||
&mut self,
|
||||
@ -425,7 +457,7 @@ impl<'a> InvokeContext for MockInvokeContext<'a> {
|
||||
_deserialize_us: u64,
|
||||
) {
|
||||
}
|
||||
fn get_sysvar_data(&mut self, id: &Pubkey) -> Option<Rc<Vec<u8>>> {
|
||||
fn get_sysvar_data(&self, id: &Pubkey) -> Option<Rc<Vec<u8>>> {
|
||||
self.sysvars
|
||||
.iter()
|
||||
.find_map(|(key, sysvar)| if id == key { sysvar.clone() } else { None })
|
||||
|
Reference in New Issue
Block a user