|
1 | 1 | use crate::id; |
2 | 2 | use crate::ConfigState; |
| 3 | +use bincode::serialize; |
| 4 | +use serde_derive::{Deserialize, Serialize}; |
3 | 5 | use solana_sdk::instruction::{AccountMeta, Instruction}; |
4 | 6 | use solana_sdk::pubkey::Pubkey; |
| 7 | +use solana_sdk::short_vec; |
5 | 8 | use solana_sdk::system_instruction; |
6 | 9 |
|
| 10 | +/// A collection of keys to be stored in Config account data. |
| 11 | +#[derive(Debug, Default, Deserialize, Serialize)] |
| 12 | +pub struct ConfigKeys { |
| 13 | + // Each key tuple comprises a unique `Pubkey` identifier, |
| 14 | + // and `bool` whether that key is a signer of the data |
| 15 | + #[serde(with = "short_vec")] |
| 16 | + pub keys: Vec<(Pubkey, bool)>, |
| 17 | +} |
| 18 | + |
| 19 | +impl ConfigKeys { |
| 20 | + pub fn serialized_size(keys: Vec<(Pubkey, bool)>) -> usize { |
| 21 | + serialize(&ConfigKeys { keys }) |
| 22 | + .unwrap_or_else(|_| vec![]) |
| 23 | + .len() |
| 24 | + } |
| 25 | +} |
| 26 | + |
7 | 27 | /// Create a new, empty configuration account |
8 | 28 | pub fn create_account<T: ConfigState>( |
9 | 29 | from_account_pubkey: &Pubkey, |
10 | 30 | config_account_pubkey: &Pubkey, |
11 | 31 | lamports: u64, |
| 32 | + keys: Vec<(Pubkey, bool)>, |
12 | 33 | ) -> Instruction { |
| 34 | + let space = T::max_space() + ConfigKeys::serialized_size(keys) as u64; |
13 | 35 | system_instruction::create_account( |
14 | 36 | from_account_pubkey, |
15 | 37 | config_account_pubkey, |
16 | 38 | lamports, |
17 | | - T::max_space(), |
| 39 | + space, |
18 | 40 | &id(), |
19 | 41 | ) |
20 | 42 | } |
21 | 43 |
|
22 | 44 | /// Store new data in a configuration account |
23 | | -pub fn store<T: ConfigState>(config_account_pubkey: &Pubkey, data: &T) -> Instruction { |
24 | | - let account_metas = vec![AccountMeta::new(*config_account_pubkey, true)]; |
25 | | - Instruction::new(id(), data, account_metas) |
| 45 | +pub fn store<T: ConfigState>( |
| 46 | + config_account_pubkey: &Pubkey, |
| 47 | + is_config_signer: bool, |
| 48 | + keys: Vec<(Pubkey, bool)>, |
| 49 | + data: &T, |
| 50 | +) -> Instruction { |
| 51 | + let mut account_metas = vec![AccountMeta::new(*config_account_pubkey, is_config_signer)]; |
| 52 | + for (signer_pubkey, _) in keys.iter().filter(|(_, is_signer)| *is_signer) { |
| 53 | + if signer_pubkey != config_account_pubkey { |
| 54 | + account_metas.push(AccountMeta::new(*signer_pubkey, true)); |
| 55 | + } |
| 56 | + } |
| 57 | + let account_data = (ConfigKeys { keys }, data); |
| 58 | + Instruction::new(id(), &account_data, account_metas) |
26 | 59 | } |
0 commit comments