-
Notifications
You must be signed in to change notification settings - Fork 524
/
Copy pathlib.rs
1405 lines (1294 loc) · 54.3 KB
/
lib.rs
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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
pub mod utils;
use solana_program::sysvar::{instructions::get_instruction_relative, SysvarId};
use {
crate::utils::{
assert_initialized, assert_is_ata, assert_keys_equal, assert_owned_by,
assert_valid_go_live, spl_token_burn, spl_token_transfer, TokenBurnParams,
TokenTransferParams,
},
anchor_lang::{
prelude::*,
solana_program::{
program::{invoke, invoke_signed},
serialize_utils::{read_pubkey, read_u16},
system_instruction, sysvar,
},
AnchorDeserialize, AnchorSerialize, Discriminator, Key,
},
anchor_spl::token::Token,
arrayref::array_ref,
mpl_token_metadata::{
assertions::collection::assert_master_edition,
error::MetadataError,
instruction::{
approve_collection_authority, create_master_edition_v3, create_metadata_accounts_v2,
revoke_collection_authority, set_and_verify_collection, update_metadata_accounts_v2,
},
state::{
Metadata, MAX_CREATOR_LEN, MAX_CREATOR_LIMIT, MAX_NAME_LENGTH, MAX_SYMBOL_LENGTH,
MAX_URI_LENGTH,
},
utils::{assert_derivation, create_or_allocate_account_raw},
},
spl_token::state::Mint,
std::{cell::RefMut, ops::Deref, str::FromStr},
};
anchor_lang::declare_id!("cndy3Z4yapfJBmL3ShUp5exZKqR3z33thTzeNMm2gRZ");
const EXPIRE_OFFSET: i64 = 10 * 60;
const PREFIX: &str = "candy_machine";
// here just in case solana removes the var
const BLOCK_HASHES: &str = "SysvarRecentB1ockHashes11111111111111111111";
#[program]
pub mod candy_machine {
use super::*;
#[inline(never)]
pub fn mint_nft<'info>(
ctx: Context<'_, '_, '_, 'info, MintNFT<'info>>,
creator_bump: u8,
) -> ProgramResult {
let candy_machine = &mut ctx.accounts.candy_machine;
let candy_machine_creator = &ctx.accounts.candy_machine_creator;
let clock = &ctx.accounts.clock;
// Note this is the wallet of the Candy machine
let wallet = &ctx.accounts.wallet;
let payer = &ctx.accounts.payer;
let token_program = &ctx.accounts.token_program;
//Account name the same for IDL compatability
let recent_slothashes = &ctx.accounts.recent_blockhashes;
let instruction_sysvar_account = &ctx.accounts.instruction_sysvar_account;
if recent_slothashes.key().to_string() == BLOCK_HASHES {
msg!("recent_blockhashes is deprecated and will break soon");
}
if recent_slothashes.key() != sysvar::slot_hashes::SlotHashes::id()
&& recent_slothashes.key().to_string() != BLOCK_HASHES
{
return Err(ErrorCode::IncorrectSlotHashesPubkey.into());
}
let mut price = candy_machine.data.price;
if let Some(es) = &candy_machine.data.end_settings {
match es.end_setting_type {
EndSettingType::Date => {
if clock.unix_timestamp > es.number as i64 {
if ctx.accounts.payer.key() != candy_machine.authority {
return Err(ErrorCode::CandyMachineNotLive.into());
}
}
}
EndSettingType::Amount => {
if candy_machine.items_redeemed >= es.number {
return Err(ErrorCode::CandyMachineNotLive.into());
}
}
}
}
let mut remaining_accounts_counter: usize = 0;
if let Some(gatekeeper) = &candy_machine.data.gatekeeper {
if ctx.remaining_accounts.len() <= remaining_accounts_counter {
return Err(ErrorCode::GatewayTokenMissing.into());
}
let gateway_token_info = &ctx.remaining_accounts[remaining_accounts_counter];
let gateway_token = ::solana_gateway::borsh::try_from_slice_incomplete::<
::solana_gateway::state::GatewayToken,
>(*gateway_token_info.data.borrow())?;
// stores the expire_time before the verification, since the verification
// will update the expire_time of the token and we won't be able to
// calculate the creation time
let expire_time = gateway_token
.expire_time
.ok_or(ErrorCode::GatewayTokenExpireTimeInvalid)?
as i64;
remaining_accounts_counter += 1;
if gatekeeper.expire_on_use {
if ctx.remaining_accounts.len() <= remaining_accounts_counter {
return Err(ErrorCode::GatewayAppMissing.into());
}
let gateway_app = &ctx.remaining_accounts[remaining_accounts_counter];
remaining_accounts_counter += 1;
if ctx.remaining_accounts.len() <= remaining_accounts_counter {
return Err(ErrorCode::NetworkExpireFeatureMissing.into());
}
let network_expire_feature = &ctx.remaining_accounts[remaining_accounts_counter];
remaining_accounts_counter += 1;
::solana_gateway::Gateway::verify_and_expire_token(
gateway_app.clone(),
gateway_token_info.clone(),
payer.deref().clone(),
&gatekeeper.gatekeeper_network,
network_expire_feature.clone(),
)?;
} else {
::solana_gateway::Gateway::verify_gateway_token_account_info(
gateway_token_info,
&payer.key(),
&gatekeeper.gatekeeper_network,
None,
)?;
}
// verifies that the gatway token was not created before the candy
// machine go_live_date (avoids pre-solving the captcha)
match candy_machine.data.go_live_date {
Some(val) => {
if (expire_time - EXPIRE_OFFSET) < val {
if let Some(ws) = &candy_machine.data.whitelist_mint_settings {
// when dealing with whitelist, the expire_time can be
// before the go_live_date only if presale enabled
if !ws.presale {
msg!(
"Invalid gateway token: calculated creation time {} and go_live_date {}",
expire_time - EXPIRE_OFFSET,
val);
return Err(ErrorCode::GatewayTokenExpireTimeInvalid.into());
}
} else {
msg!(
"Invalid gateway token: calculated creation time {} and go_live_date {}",
expire_time - EXPIRE_OFFSET,
val);
return Err(ErrorCode::GatewayTokenExpireTimeInvalid.into());
}
}
}
None => {}
}
}
if let Some(ws) = &candy_machine.data.whitelist_mint_settings {
let whitelist_token_account = &ctx.remaining_accounts[remaining_accounts_counter];
remaining_accounts_counter += 1;
// If the user has not actually made this account,
// this explodes and we just check normal dates.
// If they have, we check amount, if it's > 0 we let them use the logic
// if 0, check normal dates.
match assert_is_ata(whitelist_token_account, &payer.key(), &ws.mint) {
Ok(wta) => {
if wta.amount > 0 {
if ws.mode == WhitelistMintMode::BurnEveryTime {
let whitelist_token_mint =
&ctx.remaining_accounts[remaining_accounts_counter];
remaining_accounts_counter += 1;
let whitelist_burn_authority =
&ctx.remaining_accounts[remaining_accounts_counter];
remaining_accounts_counter += 1;
assert_keys_equal(whitelist_token_mint.key(), ws.mint)?;
spl_token_burn(TokenBurnParams {
mint: whitelist_token_mint.clone(),
source: whitelist_token_account.clone(),
amount: 1,
authority: whitelist_burn_authority.clone(),
authority_signer_seeds: None,
token_program: token_program.to_account_info(),
})?;
}
match candy_machine.data.go_live_date {
None => {
if ctx.accounts.payer.key() != candy_machine.authority
&& !ws.presale
{
return Err(ErrorCode::CandyMachineNotLive.into());
}
}
Some(val) => {
if clock.unix_timestamp < val
&& ctx.accounts.payer.key() != candy_machine.authority
&& !ws.presale
{
return Err(ErrorCode::CandyMachineNotLive.into());
}
}
}
if let Some(dp) = ws.discount_price {
price = dp;
}
} else {
if wta.amount == 0 && ws.discount_price.is_none() && !ws.presale {
// A non-presale whitelist with no discount price is a forced whitelist
// If a pre-sale has no discount, its no issue, because the "discount"
// is minting first - a presale whitelist always has an open post sale.
return Err(ErrorCode::NoWhitelistToken.into());
}
assert_valid_go_live(payer, clock, candy_machine)?;
if ws.mode == WhitelistMintMode::BurnEveryTime {
remaining_accounts_counter += 2;
}
}
}
Err(_) => {
if ws.discount_price.is_none() && !ws.presale {
// A non-presale whitelist with no discount price is a forced whitelist
// If a pre-sale has no discount, its no issue, because the "discount"
// is minting first - a presale whitelist always has an open post sale.
return Err(ErrorCode::NoWhitelistToken.into());
}
if ws.mode == WhitelistMintMode::BurnEveryTime {
remaining_accounts_counter += 2;
}
assert_valid_go_live(payer, clock, candy_machine)?
}
}
} else {
// no whitelist means normal datecheck
assert_valid_go_live(payer, clock, candy_machine)?;
}
if candy_machine.items_redeemed >= candy_machine.data.items_available {
return Err(ErrorCode::CandyMachineEmpty.into());
}
if let Some(mint) = candy_machine.token_mint {
let token_account_info = &ctx.remaining_accounts[remaining_accounts_counter];
remaining_accounts_counter += 1;
let transfer_authority_info = &ctx.remaining_accounts[remaining_accounts_counter];
remaining_accounts_counter += 1;
let token_account = assert_is_ata(token_account_info, &payer.key(), &mint)?;
if token_account.amount < price {
return Err(ErrorCode::NotEnoughTokens.into());
}
spl_token_transfer(TokenTransferParams {
source: token_account_info.clone(),
destination: wallet.to_account_info(),
authority: transfer_authority_info.clone(),
authority_signer_seeds: &[],
token_program: token_program.to_account_info(),
amount: price,
})?;
} else {
if ctx.accounts.payer.lamports() < price {
return Err(ErrorCode::NotEnoughSOL.into());
}
invoke(
&system_instruction::transfer(&ctx.accounts.payer.key(), &wallet.key(), price),
&[
ctx.accounts.payer.to_account_info(),
wallet.to_account_info(),
ctx.accounts.system_program.to_account_info(),
],
)?;
}
let data = recent_slothashes.data.borrow();
let most_recent = array_ref![data, 12, 8];
let index = u64::from_le_bytes(*most_recent);
let modded: usize = index
.checked_rem(candy_machine.data.items_available)
.ok_or(ErrorCode::NumericalOverflowError)? as usize;
let config_line = get_config_line(&candy_machine, modded, candy_machine.items_redeemed)?;
candy_machine.items_redeemed = candy_machine
.items_redeemed
.checked_add(1)
.ok_or(ErrorCode::NumericalOverflowError)?;
let cm_key = candy_machine.key();
let authority_seeds = [PREFIX.as_bytes(), cm_key.as_ref(), &[creator_bump]];
let mut creators: Vec<mpl_token_metadata::state::Creator> =
vec![mpl_token_metadata::state::Creator {
address: candy_machine_creator.key(),
verified: true,
share: 0,
}];
for c in &candy_machine.data.creators {
creators.push(mpl_token_metadata::state::Creator {
address: c.address,
verified: false,
share: c.share,
});
}
let metadata_infos = vec![
ctx.accounts.metadata.to_account_info(),
ctx.accounts.mint.to_account_info(),
ctx.accounts.mint_authority.to_account_info(),
ctx.accounts.payer.to_account_info(),
ctx.accounts.token_metadata_program.to_account_info(),
ctx.accounts.token_program.to_account_info(),
ctx.accounts.system_program.to_account_info(),
ctx.accounts.rent.to_account_info(),
candy_machine_creator.to_account_info(),
];
let master_edition_infos = vec![
ctx.accounts.master_edition.to_account_info(),
ctx.accounts.mint.to_account_info(),
ctx.accounts.mint_authority.to_account_info(),
ctx.accounts.payer.to_account_info(),
ctx.accounts.metadata.to_account_info(),
ctx.accounts.token_metadata_program.to_account_info(),
ctx.accounts.token_program.to_account_info(),
ctx.accounts.system_program.to_account_info(),
ctx.accounts.rent.to_account_info(),
candy_machine_creator.to_account_info(),
];
invoke_signed(
&create_metadata_accounts_v2(
ctx.accounts.token_metadata_program.key(),
ctx.accounts.metadata.key(),
ctx.accounts.mint.key(),
ctx.accounts.mint_authority.key(),
ctx.accounts.payer.key(),
candy_machine_creator.key(),
config_line.name,
candy_machine.data.symbol.clone(),
config_line.uri,
Some(creators),
candy_machine.data.seller_fee_basis_points,
true,
candy_machine.data.is_mutable,
None,
None,
),
metadata_infos.as_slice(),
&[&authority_seeds],
)?;
invoke_signed(
&create_master_edition_v3(
ctx.accounts.token_metadata_program.key(),
ctx.accounts.master_edition.key(),
ctx.accounts.mint.key(),
candy_machine_creator.key(),
ctx.accounts.mint_authority.key(),
ctx.accounts.metadata.key(),
ctx.accounts.payer.key(),
Some(candy_machine.data.max_supply),
),
master_edition_infos.as_slice(),
&[&authority_seeds],
)?;
let mut new_update_authority = Some(candy_machine.authority);
if !candy_machine.data.retain_authority {
new_update_authority = Some(ctx.accounts.update_authority.key());
}
invoke_signed(
&update_metadata_accounts_v2(
ctx.accounts.token_metadata_program.key(),
ctx.accounts.metadata.key(),
candy_machine_creator.key(),
new_update_authority,
None,
Some(true),
if !candy_machine.data.is_mutable {
Some(false)
} else {
None
},
),
&[
ctx.accounts.token_metadata_program.to_account_info(),
ctx.accounts.metadata.to_account_info(),
candy_machine_creator.to_account_info(),
],
&[&authority_seeds],
)?;
let instruction_sysvar_account_info = instruction_sysvar_account.to_account_info();
let instruction_sysvar = instruction_sysvar_account_info.data.borrow();
let mut idx = 0;
let num_instructions = read_u16(&mut idx, &instruction_sysvar)
.map_err(|_| ProgramError::InvalidAccountData)?;
let associated_token =
Pubkey::from_str("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL").unwrap();
for index in 0..num_instructions {
let mut current = 2 + (index * 2) as usize;
let start = read_u16(&mut current, &instruction_sysvar).unwrap();
current = start as usize;
let num_accounts = read_u16(&mut current, &instruction_sysvar).unwrap();
current += (num_accounts as usize) * (1 + 32);
let program_id = read_pubkey(&mut current, &instruction_sysvar).unwrap();
if program_id != candy_machine::id()
&& program_id != spl_token::id()
&& program_id != anchor_lang::solana_program::system_program::ID
&& program_id != associated_token
{
msg!("Transaction had ix with program id {}", program_id);
return Err(ErrorCode::SuspiciousTransaction.into());
}
}
Ok(())
}
pub fn set_collection_during_mint(ctx: Context<SetCollectionDuringMint>) -> ProgramResult {
let ixs = &ctx.accounts.instructions;
let previous_instruction = get_instruction_relative(-1, ixs)?;
if &previous_instruction.program_id != &candy_machine::id() {
msg!(
"Transaction had ix with program id {}",
&previous_instruction.program_id
);
return Err(ErrorCode::SuspiciousTransaction.into());
}
let discriminator = &previous_instruction.data[0..8];
if discriminator != [211, 57, 6, 167, 15, 219, 35, 251] {
msg!(
"Transaction had ix with data {:?}",
discriminator
);
return Err(ErrorCode::SuspiciousTransaction.into());
}
let mint_ix_accounts = previous_instruction.accounts;
let mint_ix_cm = mint_ix_accounts[0].pubkey;
let mint_ix_metadata = mint_ix_accounts[4].pubkey;
let signer = mint_ix_accounts[6].pubkey;
let candy_key = ctx.accounts.candy_machine.key();
let metadata = ctx.accounts.metadata.key();
let payer = ctx.accounts.payer.key();
if &signer != &payer {
msg!("Signer with pubkey {} does not match the mint ix Signer with pubkey {}", mint_ix_cm, candy_key);
return Err(ErrorCode::SuspiciousTransaction.into());
}
if &mint_ix_cm != &candy_key {
msg!("Candy Machine with pubkey {} does not match the mint ix Candy Machine with pubkey {}", mint_ix_cm, candy_key);
return Err(ErrorCode::SuspiciousTransaction.into());
}
if mint_ix_metadata != metadata {
msg!(
"Metadata with pubkey {} does not match the mint ix metadata with pubkey {}",
mint_ix_metadata,
metadata
);
return Err(ErrorCode::SuspiciousTransaction.into());
}
let collection_pda = &ctx.accounts.collection_pda;
let collection_mint = ctx.accounts.collection_mint.to_account_info();
if &collection_pda.mint != &collection_mint.key() {
return Err(ErrorCode::MismatchedCollectionMint.into());
}
let seeds = [b"collection".as_ref(), candy_key.as_ref()];
let bump = assert_derivation(&candy_machine::id(), &collection_pda.to_account_info(), &seeds)?;
let signer_seeds = [b"collection".as_ref(), candy_key.as_ref(), &[bump]];
let set_collection_infos = vec![
ctx.accounts.metadata.to_account_info(),
collection_pda.to_account_info(),
ctx.accounts.payer.to_account_info(),
ctx.accounts.authority.to_account_info(),
collection_mint.to_account_info(),
ctx.accounts.collection_metadata.to_account_info(),
ctx.accounts.collection_master_edition.to_account_info(),
ctx.accounts.collection_authority_record.to_account_info(),
];
invoke_signed(
&set_and_verify_collection(
ctx.accounts.token_metadata_program.key(),
ctx.accounts.metadata.key(),
collection_pda.key(),
ctx.accounts.payer.key(),
ctx.accounts.authority.key(),
collection_mint.key(),
ctx.accounts.collection_metadata.key(),
ctx.accounts.collection_master_edition.key(),
Some(ctx.accounts.collection_authority_record.key()),
),
set_collection_infos.as_slice(),
&[&signer_seeds],
)?;
Ok(())
}
pub fn update_candy_machine(
ctx: Context<UpdateCandyMachine>,
data: CandyMachineData,
) -> ProgramResult {
let candy_machine = &mut ctx.accounts.candy_machine;
if data.items_available != candy_machine.data.items_available
&& data.hidden_settings.is_none()
{
return Err(ErrorCode::CannotChangeNumberOfLines.into());
}
if candy_machine.data.items_available > 0
&& candy_machine.data.hidden_settings.is_none()
&& data.hidden_settings.is_some()
{
return Err(ErrorCode::CannotSwitchToHiddenSettings.into());
}
candy_machine.wallet = ctx.accounts.wallet.key();
candy_machine.data = data;
if ctx.remaining_accounts.len() > 0 {
candy_machine.token_mint = Some(ctx.remaining_accounts[0].key())
} else {
candy_machine.token_mint = None;
}
Ok(())
}
pub fn add_config_lines(
ctx: Context<AddConfigLines>,
index: u32,
config_lines: Vec<ConfigLine>,
) -> ProgramResult {
let candy_machine = &mut ctx.accounts.candy_machine;
let account = candy_machine.to_account_info();
let current_count = get_config_count(&account.data.borrow_mut())?;
let mut data = account.data.borrow_mut();
let mut fixed_config_lines = vec![];
// No risk overflow because you literally cant store this many in an account
// going beyond u32 only happens with the hidden store candies, which dont use this.
if index > (candy_machine.data.items_available as u32) - 1 {
return Err(ErrorCode::IndexGreaterThanLength.into());
}
if candy_machine.data.hidden_settings.is_some() {
return Err(ErrorCode::HiddenSettingsConfigsDoNotHaveConfigLines.into());
}
for line in &config_lines {
let mut array_of_zeroes = vec![];
while array_of_zeroes.len() < MAX_NAME_LENGTH - line.name.len() {
array_of_zeroes.push(0u8);
}
let name = line.name.clone() + std::str::from_utf8(&array_of_zeroes).unwrap();
let mut array_of_zeroes = vec![];
while array_of_zeroes.len() < MAX_URI_LENGTH - line.uri.len() {
array_of_zeroes.push(0u8);
}
let uri = line.uri.clone() + std::str::from_utf8(&array_of_zeroes).unwrap();
fixed_config_lines.push(ConfigLine { name, uri })
}
let as_vec = fixed_config_lines.try_to_vec()?;
// remove unneeded u32 because we're just gonna edit the u32 at the front
let serialized: &[u8] = &as_vec.as_slice()[4..];
let position = CONFIG_ARRAY_START + 4 + (index as usize) * CONFIG_LINE_SIZE;
let array_slice: &mut [u8] =
&mut data[position..position + fixed_config_lines.len() * CONFIG_LINE_SIZE];
array_slice.copy_from_slice(serialized);
let bit_mask_vec_start = CONFIG_ARRAY_START
+ 4
+ (candy_machine.data.items_available as usize) * CONFIG_LINE_SIZE
+ 4;
let mut new_count = current_count;
for i in 0..fixed_config_lines.len() {
let position = (index as usize)
.checked_add(i)
.ok_or(ErrorCode::NumericalOverflowError)?;
let my_position_in_vec = bit_mask_vec_start
+ position
.checked_div(8)
.ok_or(ErrorCode::NumericalOverflowError)?;
let position_from_right = 7 - position
.checked_rem(8)
.ok_or(ErrorCode::NumericalOverflowError)?;
let mask = u8::pow(2, position_from_right as u32);
let old_value_in_vec = data[my_position_in_vec];
data[my_position_in_vec] = data[my_position_in_vec] | mask;
msg!(
"My position in vec is {} my mask is going to be {}, the old value is {}",
position,
mask,
old_value_in_vec
);
msg!(
"My new value is {} and my position from right is {}",
data[my_position_in_vec],
position_from_right
);
if old_value_in_vec != data[my_position_in_vec] {
msg!("Increasing count");
new_count = new_count
.checked_add(1)
.ok_or(ErrorCode::NumericalOverflowError)?;
}
}
// plug in new count.
data[CONFIG_ARRAY_START..CONFIG_ARRAY_START + 4]
.copy_from_slice(&(new_count as u32).to_le_bytes());
Ok(())
}
pub fn initialize_candy_machine(
ctx: Context<InitializeCandyMachine>,
data: CandyMachineData,
) -> ProgramResult {
let candy_machine_account = &mut ctx.accounts.candy_machine;
if data.uuid.len() != 6 {
return Err(ErrorCode::UuidMustBeExactly6Length.into());
}
let mut candy_machine = CandyMachine {
data,
authority: ctx.accounts.authority.key(),
wallet: ctx.accounts.wallet.key(),
token_mint: None,
items_redeemed: 0,
};
if ctx.remaining_accounts.len() > 0 {
let token_mint_info = &ctx.remaining_accounts[0];
let _token_mint: Mint = assert_initialized(&token_mint_info)?;
let token_account: spl_token::state::Account =
assert_initialized(&ctx.accounts.wallet)?;
assert_owned_by(&token_mint_info, &spl_token::id())?;
assert_owned_by(&ctx.accounts.wallet, &spl_token::id())?;
if token_account.mint != token_mint_info.key() {
return Err(ErrorCode::MintMismatch.into());
}
candy_machine.token_mint = Some(*token_mint_info.key);
}
let mut array_of_zeroes = vec![];
while array_of_zeroes.len() < MAX_SYMBOL_LENGTH - candy_machine.data.symbol.len() {
array_of_zeroes.push(0u8);
}
let new_symbol =
candy_machine.data.symbol.clone() + std::str::from_utf8(&array_of_zeroes).unwrap();
candy_machine.data.symbol = new_symbol;
// - 1 because we are going to be a creator
if candy_machine.data.creators.len() > MAX_CREATOR_LIMIT - 1 {
return Err(ErrorCode::TooManyCreators.into());
}
let mut new_data = CandyMachine::discriminator().try_to_vec().unwrap();
new_data.append(&mut candy_machine.try_to_vec().unwrap());
let mut data = candy_machine_account.data.borrow_mut();
// god forgive me couldnt think of better way to deal with this
for i in 0..new_data.len() {
data[i] = new_data[i];
}
let vec_start = CONFIG_ARRAY_START
+ 4
+ (candy_machine.data.items_available as usize) * CONFIG_LINE_SIZE;
let as_bytes = (candy_machine
.data
.items_available
.checked_div(8)
.ok_or(ErrorCode::NumericalOverflowError)? as u32)
.to_le_bytes();
for i in 0..4 {
data[vec_start + i] = as_bytes[i]
}
Ok(())
}
pub fn set_collection(ctx: Context<SetCollection>) -> ProgramResult {
let mint = ctx.accounts.mint.to_account_info();
let metadata: Metadata =
Metadata::from_account_info(&ctx.accounts.metadata.to_account_info())?;
if &metadata.update_authority != &ctx.accounts.authority.key() {
return Err(ErrorCode::IncorrectCollectionAuthority.into());
};
if &metadata.mint != &mint.key() {
return Err(MetadataError::MintMismatch.into());
}
let edition = ctx.accounts.edition.to_account_info();
let authority_record = ctx.accounts.collection_authority_record.to_account_info();
let candy_machine = &ctx.accounts.candy_machine;
if authority_record.data_is_empty() {
assert_master_edition(&metadata, &edition)?;
let approve_collection_infos = vec![
authority_record.clone(),
ctx.accounts.collection_pda.to_account_info(),
ctx.accounts.authority.to_account_info(),
ctx.accounts.payer.to_account_info(),
ctx.accounts.metadata.to_account_info(),
mint.clone(),
ctx.accounts.system_program.to_account_info(),
ctx.accounts.rent.to_account_info(),
];
msg!(
"About to approve collection authority for {} with new authority {}.",
ctx.accounts.metadata.key(),
ctx.accounts.collection_pda.key
);
invoke(
&approve_collection_authority(
ctx.accounts.token_metadata_program.key(),
authority_record.key(),
ctx.accounts.collection_pda.to_account_info().key(),
ctx.accounts.authority.key(),
ctx.accounts.payer.key(),
ctx.accounts.metadata.key(),
mint.key.clone(),
),
approve_collection_infos.as_slice(),
)?;
msg!(
"Successfully approved collection authority. Now setting PDA mint to {}.",
mint.key()
);
if ctx.accounts.collection_pda.data_is_empty() {
create_or_allocate_account_raw(
crate::id(),
&ctx.accounts.collection_pda.to_account_info(),
&ctx.accounts.rent.to_account_info(),
&ctx.accounts.system_program.to_account_info(),
&ctx.accounts.authority.to_account_info(),
COLLECTION_PDA_SIZE,
&[
b"collection".as_ref(),
&candy_machine.key().as_ref(),
&[*ctx.bumps.get("collection_pda").unwrap()],
],
)?;
let mut data_ref: &mut [u8] =
&mut ctx.accounts.collection_pda.try_borrow_mut_data()?;
let mut collection_pda_object: CollectionPDA =
AnchorDeserialize::deserialize(&mut &*data_ref)?;
collection_pda_object.mint = mint.key();
collection_pda_object.candy_machine = candy_machine.key();
collection_pda_object.try_serialize(&mut data_ref)?;
}
}
Ok(())
}
pub fn remove_collection(ctx: Context<RemoveCollection>) -> ProgramResult {
let mint = ctx.accounts.mint.to_account_info();
let metadata: Metadata =
Metadata::from_account_info(&ctx.accounts.metadata.to_account_info())?;
if &metadata.update_authority != &ctx.accounts.authority.key() {
return Err(ErrorCode::IncorrectCollectionAuthority.into());
};
if &metadata.mint != &mint.key() {
return Err(MetadataError::MintMismatch.into());
}
let authority_record = ctx.accounts.collection_authority_record.to_account_info();
let revoke_collection_infos = vec![
authority_record.clone(),
ctx.accounts.collection_pda.to_account_info(),
ctx.accounts.authority.to_account_info(),
ctx.accounts.metadata.to_account_info(),
mint.clone(),
];
msg!(
"About to revoke collection authority for {}.",
ctx.accounts.metadata.key()
);
invoke(
&revoke_collection_authority(
ctx.accounts.token_metadata_program.key(),
authority_record.key(),
ctx.accounts.collection_pda.key(),
ctx.accounts.authority.key(),
ctx.accounts.metadata.key(),
mint.key(),
),
revoke_collection_infos.as_slice(),
)?;
Ok(())
}
pub fn update_authority(
ctx: Context<UpdateCandyMachine>,
new_authority: Option<Pubkey>,
) -> ProgramResult {
let candy_machine = &mut ctx.accounts.candy_machine;
if let Some(new_auth) = new_authority {
candy_machine.authority = new_auth;
}
Ok(())
}
pub fn withdraw_funds<'info>(ctx: Context<WithdrawFunds<'info>>) -> ProgramResult {
let authority = &ctx.accounts.authority;
let pay = &ctx.accounts.candy_machine.to_account_info();
let snapshot: u64 = pay.lamports();
**pay.lamports.borrow_mut() = 0;
**authority.lamports.borrow_mut() = authority
.lamports()
.checked_add(snapshot)
.ok_or(ErrorCode::NumericalOverflowError)?;
if ctx.remaining_accounts.len() > 0 {
let seeds = [b"collection".as_ref(), pay.key.as_ref()];
let pay = &ctx.remaining_accounts[0];
if &pay.key() != &Pubkey::find_program_address(&seeds, &candy_machine::id()).0 {
return Err(ErrorCode::MismatchedCollectionPDA.into());
}
let snapshot: u64 = pay.lamports();
**pay.lamports.borrow_mut() = 0;
**authority.lamports.borrow_mut() = authority
.lamports()
.checked_add(snapshot)
.ok_or(ErrorCode::NumericalOverflowError)?;
}
Ok(())
}
}
fn get_space_for_candy(data: CandyMachineData) -> core::result::Result<usize, ProgramError> {
let num = if data.hidden_settings.is_some() {
CONFIG_ARRAY_START
} else {
CONFIG_ARRAY_START
+ 4
+ (data.items_available as usize) * CONFIG_LINE_SIZE
+ 8
+ 2 * ((data
.items_available
.checked_div(8)
.ok_or(ErrorCode::NumericalOverflowError)?
+ 1) as usize)
};
Ok(num)
}
/// Create a new candy machine.
#[derive(Accounts)]
#[instruction(data: CandyMachineData)]
pub struct InitializeCandyMachine<'info> {
/// CHECK: account constraints checked in account trait
#[account(zero, rent_exempt = skip, constraint = candy_machine.to_account_info().owner == program_id && candy_machine.to_account_info().data_len() >= get_space_for_candy(data)?)]
candy_machine: UncheckedAccount<'info>,
/// CHECK: wallet can be any account and is not written to or read
wallet: UncheckedAccount<'info>,
/// CHECK: authority can be any account and is not written to or read
authority: UncheckedAccount<'info>,
payer: Signer<'info>,
system_program: Program<'info, System>,
rent: Sysvar<'info, Rent>,
}
/// Sets and verifies the collection during a candy machine mint
#[derive(Accounts)]
pub struct SetCollectionDuringMint<'info> {
#[account(has_one = authority)]
candy_machine: Account<'info, CandyMachine>,
/// CHECK: account checked in CPI/instruction sysvar
metadata: UncheckedAccount<'info>,
payer: Signer<'info>,
#[account(mut, seeds = [b"collection".as_ref(), candy_machine.to_account_info().key.as_ref()], bump)]
collection_pda: Account<'info, CollectionPDA>,
/// CHECK: account constraints checked in account trait
#[account(address = mpl_token_metadata::id())]
token_metadata_program: UncheckedAccount<'info>,
/// CHECK: account constraints checked in account trait
#[account(address = sysvar::instructions::id())]
instructions: UncheckedAccount<'info>,
/// CHECK: account checked in CPI
collection_mint: UncheckedAccount<'info>,
/// CHECK: account checked in CPI
collection_metadata: UncheckedAccount<'info>,
/// CHECK: account checked in CPI
collection_master_edition: UncheckedAccount<'info>,
/// CHECK: authority can be any account and is checked in CPI
authority: UncheckedAccount<'info>,
/// CHECK: account checked in CPI
collection_authority_record: UncheckedAccount<'info>,
}
/// Set the collection PDA for the candy machine
#[derive(Accounts)]
pub struct SetCollection<'info> {
#[account(has_one = authority)]
candy_machine: Account<'info, CandyMachine>,
authority: Signer<'info>,
/// CHECK: account constraints checked in account trait
#[account(mut, seeds = [b"collection".as_ref(), candy_machine.to_account_info().key.as_ref()], bump)]
collection_pda: UncheckedAccount<'info>,
payer: Signer<'info>,
system_program: Program<'info, System>,
rent: Sysvar<'info, Rent>,
/// CHECK: account checked in CPI
metadata: UncheckedAccount<'info>,
/// CHECK: account checked in CPI
mint: UncheckedAccount<'info>,
/// CHECK: account checked in CPI
edition: UncheckedAccount<'info>,
/// CHECK: account checked in CPI
#[account(mut)]
collection_authority_record: UncheckedAccount<'info>,
/// CHECK: account checked in CPI
#[account(address = mpl_token_metadata::id())]
token_metadata_program: UncheckedAccount<'info>,
}
/// Set the collection PDA for the candy machine
#[derive(Accounts)]
pub struct RemoveCollection<'info> {
#[account(has_one = authority)]
candy_machine: Account<'info, CandyMachine>,
authority: Signer<'info>,
#[account(mut, seeds = [b"collection".as_ref(), candy_machine.to_account_info().key.as_ref()], bump, close=authority)]
collection_pda: Account<'info, CollectionPDA>,
/// CHECK: account checked in CPI
metadata: UncheckedAccount<'info>,
/// CHECK: account checked in CPI
mint: UncheckedAccount<'info>,
/// CHECK: account checked in CPI
#[account(mut)]
collection_authority_record: UncheckedAccount<'info>,
/// CHECK: account checked in CPI
#[account(address = mpl_token_metadata::id())]
token_metadata_program: UncheckedAccount<'info>,
}
/// Add multiple config lines to the candy machine.
#[derive(Accounts)]
pub struct AddConfigLines<'info> {
#[account(mut, has_one = authority)]
candy_machine: Account<'info, CandyMachine>,
authority: Signer<'info>,
}
/// Withdraw SOL from candy machine account.
#[derive(Accounts)]
pub struct WithdrawFunds<'info> {
#[account(mut, has_one = authority)]
candy_machine: Account<'info, CandyMachine>,
#[account(address = candy_machine.authority)]
authority: Signer<'info>,
// > Only if collection
// CollectionPDA account
}
/// Mint a new NFT pseudo-randomly from the config array.
#[derive(Accounts)]
#[instruction(creator_bump: u8)]
pub struct MintNFT<'info> {
#[account(
mut,
has_one = wallet
)]
candy_machine: Box<Account<'info, CandyMachine>>,
/// CHECK: account constraints checked in account trait
#[account(seeds=[PREFIX.as_bytes(), candy_machine.key().as_ref()], bump=creator_bump)]
candy_machine_creator: UncheckedAccount<'info>,
payer: Signer<'info>,
/// CHECK: wallet can be any account and is not written to or read
#[account(mut)]
wallet: UncheckedAccount<'info>,
// With the following accounts we aren't using anchor macros because they are CPI'd