use gemachain_program::{
account_info::AccountInfo, program_error::ProgramError, program_pack::IsInitialized,
pubkey::Pubkey,
};
use borsh::{BorshDeserialize, BorshSchema, BorshSerialize};
use gpl_governance_tools::account::{get_account_data, AccountMaxSize};
use crate::{error::GovernanceError, state::enums::GovernanceAccountType};
#[derive(Clone, Debug, PartialEq, BorshDeserialize, BorshSerialize, BorshSchema)]
pub struct RealmConfigAccount {
pub account_type: GovernanceAccountType,
pub realm: Pubkey,
pub community_voter_weight_addin: Option<Pubkey>,
pub community_max_vote_weight_addin: Option<Pubkey>,
pub council_voter_weight_addin: Option<Pubkey>,
pub council_max_vote_weight_addin: Option<Pubkey>,
pub reserved: [u8; 128],
}
impl AccountMaxSize for RealmConfigAccount {
fn get_max_size(&self) -> Option<usize> {
Some(1 + 32 + 33 * 4 + 128)
}
}
impl IsInitialized for RealmConfigAccount {
fn is_initialized(&self) -> bool {
self.account_type == GovernanceAccountType::RealmConfig
}
}
pub fn get_realm_config_data(
program_id: &Pubkey,
realm_config_info: &AccountInfo,
) -> Result<RealmConfigAccount, ProgramError> {
get_account_data::<RealmConfigAccount>(program_id, realm_config_info)
}
pub fn get_realm_config_data_for_realm(
program_id: &Pubkey,
realm_config_info: &AccountInfo,
realm: &Pubkey,
) -> Result<RealmConfigAccount, ProgramError> {
let realm_config_data = get_realm_config_data(program_id, realm_config_info)?;
if realm_config_data.realm != *realm {
return Err(GovernanceError::InvalidRealmConfigForRealm.into());
}
Ok(realm_config_data)
}
pub fn get_realm_config_address_seeds(realm: &Pubkey) -> [&[u8]; 2] {
[b"realm-config", realm.as_ref()]
}
pub fn get_realm_config_address(program_id: &Pubkey, realm: &Pubkey) -> Pubkey {
Pubkey::find_program_address(&get_realm_config_address_seeds(realm), program_id).0
}
#[cfg(test)]
mod test {
use super::*;
use crate::state::{enums::GovernanceAccountType, realm_config::RealmConfigAccount};
#[test]
fn test_max_size() {
let realm_config = RealmConfigAccount {
account_type: GovernanceAccountType::Realm,
realm: Pubkey::new_unique(),
community_voter_weight_addin: Some(Pubkey::new_unique()),
community_max_vote_weight_addin: Some(Pubkey::new_unique()),
council_voter_weight_addin: Some(Pubkey::new_unique()),
council_max_vote_weight_addin: Some(Pubkey::new_unique()),
reserved: [0; 128],
};
let size = realm_config.try_to_vec().unwrap().len();
assert_eq!(realm_config.get_max_size(), Some(size));
}
}