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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
use borsh::maybestd::io::Write;
use std::slice::Iter;
use borsh::{BorshDeserialize, BorshSchema, BorshSerialize};
use solana_program::{
account_info::{next_account_info, AccountInfo},
borsh::try_from_slice_unchecked,
program_error::ProgramError,
program_pack::IsInitialized,
pubkey::Pubkey,
};
use spl_governance_addin_api::voter_weight::VoterWeightAction;
use spl_governance_tools::account::{
assert_is_valid_account_of_types, get_account_data, AccountMaxSize,
};
use crate::{
error::GovernanceError,
state::{
enums::{GovernanceAccountType, MintMaxVoteWeightSource},
legacy::RealmV1,
token_owner_record::get_token_owner_record_data_for_realm,
},
PROGRAM_AUTHORITY_SEED,
};
#[repr(C)]
#[derive(Clone, Debug, PartialEq, BorshDeserialize, BorshSerialize, BorshSchema)]
pub struct RealmConfigArgs {
pub use_council_mint: bool,
pub min_community_weight_to_create_governance: u64,
pub community_mint_max_vote_weight_source: MintMaxVoteWeightSource,
pub use_community_voter_weight_addin: bool,
pub use_max_community_voter_weight_addin: bool,
}
#[derive(Clone, Debug, PartialEq, BorshDeserialize, BorshSerialize, BorshSchema)]
pub enum SetRealmAuthorityAction {
SetUnchecked,
SetChecked,
Remove,
}
#[repr(C)]
#[derive(Clone, Debug, PartialEq, BorshDeserialize, BorshSerialize, BorshSchema)]
pub struct RealmConfig {
pub use_community_voter_weight_addin: bool,
pub use_max_community_voter_weight_addin: bool,
pub reserved: [u8; 6],
pub min_community_weight_to_create_governance: u64,
pub community_mint_max_vote_weight_source: MintMaxVoteWeightSource,
pub council_mint: Option<Pubkey>,
}
#[repr(C)]
#[derive(Clone, Debug, PartialEq, BorshDeserialize, BorshSerialize, BorshSchema)]
pub struct RealmV2 {
pub account_type: GovernanceAccountType,
pub community_mint: Pubkey,
pub config: RealmConfig,
pub reserved: [u8; 6],
pub voting_proposal_count: u16,
pub authority: Option<Pubkey>,
pub name: String,
pub reserved_v2: [u8; 128],
}
impl AccountMaxSize for RealmV2 {
fn get_max_size(&self) -> Option<usize> {
Some(self.name.len() + 264)
}
}
impl IsInitialized for RealmV2 {
fn is_initialized(&self) -> bool {
self.account_type == GovernanceAccountType::RealmV2
}
}
pub fn is_realm_account_type(account_type: &GovernanceAccountType) -> bool {
match account_type {
GovernanceAccountType::RealmV1 | GovernanceAccountType::RealmV2 => true,
GovernanceAccountType::GovernanceV2
| GovernanceAccountType::ProgramGovernanceV2
| GovernanceAccountType::MintGovernanceV2
| GovernanceAccountType::TokenGovernanceV2
| GovernanceAccountType::Uninitialized
| GovernanceAccountType::RealmConfig
| GovernanceAccountType::TokenOwnerRecordV1
| GovernanceAccountType::TokenOwnerRecordV2
| GovernanceAccountType::GovernanceV1
| GovernanceAccountType::ProgramGovernanceV1
| GovernanceAccountType::MintGovernanceV1
| GovernanceAccountType::TokenGovernanceV1
| GovernanceAccountType::ProposalV1
| GovernanceAccountType::ProposalV2
| GovernanceAccountType::SignatoryRecordV1
| GovernanceAccountType::SignatoryRecordV2
| GovernanceAccountType::ProposalInstructionV1
| GovernanceAccountType::ProposalTransactionV2
| GovernanceAccountType::VoteRecordV1
| GovernanceAccountType::VoteRecordV2
| GovernanceAccountType::ProgramMetadata => false,
}
}
impl RealmV2 {
pub fn assert_is_valid_governing_token_mint(
&self,
governing_token_mint: &Pubkey,
) -> Result<(), ProgramError> {
if self.community_mint == *governing_token_mint {
return Ok(());
}
if self.config.council_mint == Some(*governing_token_mint) {
return Ok(());
}
Err(GovernanceError::InvalidGoverningTokenMint.into())
}
pub fn assert_is_valid_governing_token_mint_and_holding(
&self,
program_id: &Pubkey,
realm: &Pubkey,
governing_token_mint: &Pubkey,
governing_token_holding: &Pubkey,
) -> Result<(), ProgramError> {
self.assert_is_valid_governing_token_mint(governing_token_mint)?;
let governing_token_holding_address =
get_governing_token_holding_address(program_id, realm, governing_token_mint);
if governing_token_holding_address != *governing_token_holding {
return Err(GovernanceError::InvalidGoverningTokenHoldingAccount.into());
}
Ok(())
}
pub fn asset_governing_tokens_deposits_allowed(
&self,
governing_token_mint: &Pubkey,
) -> Result<(), ProgramError> {
if self.config.use_community_voter_weight_addin
&& self.community_mint == *governing_token_mint
{
return Err(GovernanceError::GoverningTokenDepositsNotAllowed.into());
}
Ok(())
}
pub fn assert_create_authority_can_create_governance(
&self,
program_id: &Pubkey,
realm: &Pubkey,
token_owner_record_info: &AccountInfo,
create_authority_info: &AccountInfo,
account_info_iter: &mut Iter<AccountInfo>,
) -> Result<(), ProgramError> {
if self.authority == Some(*create_authority_info.key) {
return if !create_authority_info.is_signer {
Err(GovernanceError::RealmAuthorityMustSign.into())
} else {
Ok(())
};
}
let token_owner_record_data =
get_token_owner_record_data_for_realm(program_id, token_owner_record_info, realm)?;
token_owner_record_data.assert_token_owner_or_delegate_is_signer(create_authority_info)?;
let realm_config_info = next_account_info(account_info_iter)?;
let voter_weight = token_owner_record_data.resolve_voter_weight(
program_id,
realm_config_info,
account_info_iter,
realm,
self,
VoterWeightAction::CreateGovernance,
realm,
)?;
token_owner_record_data.assert_can_create_governance(self, voter_weight)?;
Ok(())
}
pub fn serialize<W: Write>(self, writer: &mut W) -> Result<(), ProgramError> {
if self.account_type == GovernanceAccountType::RealmV2 {
BorshSerialize::serialize(&self, writer)?
} else if self.account_type == GovernanceAccountType::RealmV1 {
if self.reserved_v2 != [0; 128] {
panic!("Extended data not supported by RealmV1")
}
let realm_data_v1 = RealmV1 {
account_type: self.account_type,
community_mint: self.community_mint,
config: self.config,
reserved: self.reserved,
voting_proposal_count: self.voting_proposal_count,
authority: self.authority,
name: self.name,
};
BorshSerialize::serialize(&realm_data_v1, writer)?;
}
Ok(())
}
}
pub fn assert_is_valid_realm(
program_id: &Pubkey,
realm_info: &AccountInfo,
) -> Result<(), ProgramError> {
assert_is_valid_account_of_types(program_id, realm_info, is_realm_account_type)
}
pub fn get_realm_data(
program_id: &Pubkey,
realm_info: &AccountInfo,
) -> Result<RealmV2, ProgramError> {
let account_type: GovernanceAccountType = try_from_slice_unchecked(&realm_info.data.borrow())?;
if account_type == GovernanceAccountType::RealmV1 {
let realm_data_v1 = get_account_data::<RealmV1>(program_id, realm_info)?;
return Ok(RealmV2 {
account_type,
community_mint: realm_data_v1.community_mint,
config: realm_data_v1.config,
reserved: realm_data_v1.reserved,
voting_proposal_count: realm_data_v1.voting_proposal_count,
authority: realm_data_v1.authority,
name: realm_data_v1.name,
reserved_v2: [0; 128],
});
}
get_account_data::<RealmV2>(program_id, realm_info)
}
pub fn get_realm_data_for_authority(
program_id: &Pubkey,
realm_info: &AccountInfo,
realm_authority: &Pubkey,
) -> Result<RealmV2, ProgramError> {
let realm_data = get_realm_data(program_id, realm_info)?;
if realm_data.authority.is_none() {
return Err(GovernanceError::RealmHasNoAuthority.into());
}
if realm_data.authority.unwrap() != *realm_authority {
return Err(GovernanceError::InvalidAuthorityForRealm.into());
}
Ok(realm_data)
}
pub fn get_realm_data_for_governing_token_mint(
program_id: &Pubkey,
realm_info: &AccountInfo,
governing_token_mint: &Pubkey,
) -> Result<RealmV2, ProgramError> {
let realm_data = get_realm_data(program_id, realm_info)?;
realm_data.assert_is_valid_governing_token_mint(governing_token_mint)?;
Ok(realm_data)
}
pub fn get_realm_address_seeds(name: &str) -> [&[u8]; 2] {
[PROGRAM_AUTHORITY_SEED, name.as_bytes()]
}
pub fn get_realm_address(program_id: &Pubkey, name: &str) -> Pubkey {
Pubkey::find_program_address(&get_realm_address_seeds(name), program_id).0
}
pub fn get_governing_token_holding_address_seeds<'a>(
realm: &'a Pubkey,
governing_token_mint: &'a Pubkey,
) -> [&'a [u8]; 3] {
[
PROGRAM_AUTHORITY_SEED,
realm.as_ref(),
governing_token_mint.as_ref(),
]
}
pub fn get_governing_token_holding_address(
program_id: &Pubkey,
realm: &Pubkey,
governing_token_mint: &Pubkey,
) -> Pubkey {
Pubkey::find_program_address(
&get_governing_token_holding_address_seeds(realm, governing_token_mint),
program_id,
)
.0
}
pub fn assert_valid_realm_config_args(config_args: &RealmConfigArgs) -> Result<(), ProgramError> {
match config_args.community_mint_max_vote_weight_source {
MintMaxVoteWeightSource::SupplyFraction(fraction) => {
if !(1..=MintMaxVoteWeightSource::SUPPLY_FRACTION_BASE).contains(&fraction) {
return Err(GovernanceError::InvalidMaxVoteWeightSupplyFraction.into());
}
}
MintMaxVoteWeightSource::Absolute(_) => {
return Err(GovernanceError::MintMaxVoteWeightSourceNotSupported.into())
}
}
Ok(())
}
#[cfg(test)]
mod test {
use crate::instruction::GovernanceInstruction;
use solana_program::borsh::try_from_slice_unchecked;
use super::*;
#[test]
fn test_max_size() {
let realm = RealmV2 {
account_type: GovernanceAccountType::RealmV2,
community_mint: Pubkey::new_unique(),
reserved: [0; 6],
authority: Some(Pubkey::new_unique()),
name: "test-realm".to_string(),
config: RealmConfig {
council_mint: Some(Pubkey::new_unique()),
use_community_voter_weight_addin: false,
use_max_community_voter_weight_addin: false,
reserved: [0; 6],
community_mint_max_vote_weight_source: MintMaxVoteWeightSource::Absolute(100),
min_community_weight_to_create_governance: 10,
},
voting_proposal_count: 0,
reserved_v2: [0; 128],
};
let size = realm.try_to_vec().unwrap().len();
assert_eq!(realm.get_max_size(), Some(size));
}
#[derive(Clone, Debug, PartialEq, BorshDeserialize, BorshSerialize, BorshSchema)]
pub struct RealmConfigArgsV1 {
pub use_council_mint: bool,
pub min_community_weight_to_create_governance: u64,
pub community_mint_max_vote_weight_source: MintMaxVoteWeightSource,
}
#[derive(Clone, Debug, PartialEq, BorshDeserialize, BorshSerialize, BorshSchema)]
pub enum GovernanceInstructionV1 {
CreateRealm {
#[allow(dead_code)]
name: String,
#[allow(dead_code)]
config_args: RealmConfigArgsV1,
},
DepositGoverningTokens {
#[allow(dead_code)]
amount: u64,
},
}
#[test]
fn test_deserialize_v1_create_realm_instruction_from_v2() {
let create_realm_ix_v2 = GovernanceInstruction::CreateRealm {
name: "test-realm".to_string(),
config_args: RealmConfigArgs {
use_council_mint: true,
min_community_weight_to_create_governance: 100,
community_mint_max_vote_weight_source:
MintMaxVoteWeightSource::FULL_SUPPLY_FRACTION,
use_community_voter_weight_addin: false,
use_max_community_voter_weight_addin: false,
},
};
let mut create_realm_ix_data = vec![];
create_realm_ix_v2
.serialize(&mut create_realm_ix_data)
.unwrap();
let create_realm_ix_v1: GovernanceInstructionV1 =
try_from_slice_unchecked(&create_realm_ix_data).unwrap();
if let GovernanceInstructionV1::CreateRealm { name, config_args } = create_realm_ix_v1 {
assert_eq!("test-realm", name);
assert_eq!(
MintMaxVoteWeightSource::FULL_SUPPLY_FRACTION,
config_args.community_mint_max_vote_weight_source
);
} else {
panic!("Can't deserialize v1 CreateRealm instruction from v2");
}
}
}