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
use std::collections::HashMap;

use {
    crate::{errors::ErrorCode, state::*},
    anchor_lang::prelude::*,
    hpl_utils::{reallocate, Default},
    spl_account_compression::Noop,
};

#[derive(Accounts)]
pub struct CreateProject<'info> {
    /// The unique key of the project.
    /// CHECK: This is not dangerous because we don't read or write from this account
    pub key: AccountInfo<'info>,

    /// The project account.
    #[account(
        init, payer = payer,
        space = Project::LEN,
        seeds = [b"project".as_ref(), key.key().as_ref()],
        bump
    )]
    pub project: Account<'info, Project>,

    /// The (delegate) authority of the project.
    /// CHECK: This is not dangerous because we don't read or write from this account
    pub authority: AccountInfo<'info>,

    /// The wallet that will pay for the project.
    #[account(mut)]
    pub payer: Signer<'info>,

    /// System Program
    pub system_program: Program<'info, System>,

    /// NO OP program
    pub log_wrapper: Program<'info, Noop>,

    /// NATIVE SYSVAR CLOCK
    pub clock: Sysvar<'info, Clock>,

    /// NATIVE RENT SYSVAR
    pub rent_sysvar: Sysvar<'info, Rent>,

    /// The vault that collects the fees.
    /// CHECK: This is not dangerous because we don't read or write from this account
    #[account(mut)]
    pub vault: AccountInfo<'info>,
}

/// Structure representing the arguments for creating a new project.
///
/// # Fields
///
/// - `name`: The name of the project.
/// - `expected_mint_addresses`: The expected number of mint addresses for the project.
/// - `driver`: [Option] Public key representing the driver authority for the project.
/// - `allowed_programs`: [Option]<[Vec]> of Public keys representing the allowed programs that can interact (CPI) with project.
/// - `collections`: [Option]<[Vec]> of Public keys representing the nft collections associated with the project.
/// - `creators`: [Option]<[Vec]> of Public keys representing the nft creators associated with the project.
#[derive(AnchorSerialize, AnchorDeserialize, Clone)]
pub struct CreateProjectArgs {
    pub name: String,
    pub expected_mint_addresses: u64,
    pub driver: Option<Pubkey>,
    pub allowed_programs: Option<Vec<Pubkey>>,
    pub collections: Option<Vec<Pubkey>>,
    pub creators: Option<Vec<Pubkey>>,
}

pub fn create_project(ctx: Context<CreateProject>, args: CreateProjectArgs) -> Result<()> {
    let project = &mut ctx.accounts.project;
    project.set_defaults();
    project.bump = ctx.bumps["project"];
    project.key = ctx.accounts.key.key();
    project.driver = args.driver.unwrap_or(Pubkey::default());
    project.authority = ctx.accounts.authority.key();
    project.name = args.name;
    project.mint_indexing = Indexing {
        expected: args.expected_mint_addresses,
        ..Indexing::default()
    };

    if args.allowed_programs.is_some() {
        let allowed_programs = args.allowed_programs.unwrap();
        reallocate(
            allowed_programs.len() as isize * 32,
            project.to_account_info(),
            ctx.accounts.payer.to_account_info(),
            &ctx.accounts.rent_sysvar,
            &ctx.accounts.system_program,
        )?;
        project.allowed_programs = allowed_programs;
    }

    if args.collections.is_some() {
        let collections = args.collections.unwrap();
        reallocate(
            collections.len() as isize * 32,
            project.to_account_info(),
            ctx.accounts.payer.to_account_info(),
            &ctx.accounts.rent_sysvar,
            &ctx.accounts.system_program,
        )?;
        project.collections = collections;
    }

    if args.creators.is_some() {
        let creators = args.creators.unwrap();
        reallocate(
            creators.len() as isize * 32,
            project.to_account_info(),
            ctx.accounts.payer.to_account_info(),
            &ctx.accounts.rent_sysvar,
            &ctx.accounts.system_program,
        )?;
        project.creators = creators;
    }

    Event::new_project(project.key(), &project, &ctx.accounts.clock)
        .wrap(ctx.accounts.log_wrapper.to_account_info())?;

    Ok(())
}

#[derive(Accounts)]
pub struct ChangeDriver<'info> {
    /// The project account.
    #[account(mut)]
    pub project: Account<'info, Project>,

    /// The driver for this project.
    /// CHECK: This is not dangerous because we don't read or write from this account
    pub driver: AccountInfo<'info>,

    /// [Option] delegate authority state account
    #[account()]
    pub delegate_authority: Option<Account<'info, DelegateAuthority>>,

    /// The (delegate) authority of the project.
    pub authority: Signer<'info>,

    /// The wallet that pays for the rent.
    #[account(mut)]
    pub payer: Signer<'info>,

    /// NATIVE RENT SYSVAR
    pub rent_sysvar: Sysvar<'info, Rent>,

    /// System Program
    pub system_program: Program<'info, System>,

    /// NO OP program
    pub log_wrapper: Program<'info, Noop>,

    /// NATIVE SYSVAR CLOCK
    pub clock: Sysvar<'info, Clock>,

    /// The vault that collects the fees.
    /// CHECK: This is not dangerous because we don't read or write from this account
    #[account(mut)]
    pub vault: AccountInfo<'info>,
}

pub fn change_driver(ctx: Context<ChangeDriver>) -> Result<()> {
    let project = &mut ctx.accounts.project;
    project.driver = ctx.accounts.driver.key();

    Event::update_project(project.key(), &project, &ctx.accounts.clock)
        .wrap(ctx.accounts.log_wrapper.to_account_info())?;
    Ok(())
}

#[derive(Accounts)]
pub struct AddRemoveCriteria<'info> {
    /// The project account.
    #[account(mut)]
    pub project: Account<'info, Project>,

    /// [Option] delegate authority state account
    #[account()]
    pub delegate_authority: Option<Account<'info, DelegateAuthority>>,

    /// The (delegate) authority of the project.
    pub authority: Signer<'info>,

    /// The wallet that pays for the rent.
    #[account(mut)]
    pub payer: Signer<'info>,

    /// The vault that collects the fees.
    /// CHECK: This is not dangerous because we don't read or write from this account
    #[account(mut)]
    pub vault: AccountInfo<'info>,

    /// System Program.
    pub system_program: Program<'info, System>,

    /// NO OP program
    pub log_wrapper: Program<'info, Noop>,

    /// NATIVE SYSVAR CLOCK
    pub clock: Sysvar<'info, Clock>,

    /// NATIVE RENT SYSVAR
    pub rent_sysvar: Sysvar<'info, Rent>,
}
/// Structure representing the arguments for adding or removing criteria (i.e. collection or creator) in a project.
///
/// # Fields
///
/// - `allowed_program`: [Option] Public key representing the allowed program to be added or removed as a criterion.
/// - `collection`: [Option] Public key representing the collection to be added or removed as a criterion.
/// - `creator`: [Option] Public key representing the creator to be added or removed as a criterion.
/// - `remove`: [Option] boolean value indicating whether the specified criteria should be added (`false` or `None`) or removed (`true`).
#[derive(AnchorSerialize, AnchorDeserialize, Clone)]
pub struct AddRemoveCriteriaArgs {
    pub allowed_program: Option<Pubkey>,
    pub collection: Option<Pubkey>,
    pub creator: Option<Pubkey>,
    pub remove: Option<bool>,
}

pub fn add_remove_criteria(
    ctx: Context<AddRemoveCriteria>,
    args: AddRemoveCriteriaArgs,
) -> Result<()> {
    let project = &mut ctx.accounts.project;

    if let Some(allowed_program) = args.allowed_program {
        if args.remove.unwrap_or(false) {
            project
                .allowed_programs
                .retain(|key| !(*key).eq(&allowed_program.key()));
            reallocate(
                -32isize,
                project.to_account_info(),
                ctx.accounts.payer.to_account_info(),
                &ctx.accounts.rent_sysvar,
                &ctx.accounts.system_program,
            )?;
        } else {
            reallocate(
                32isize,
                project.to_account_info(),
                ctx.accounts.payer.to_account_info(),
                &ctx.accounts.rent_sysvar,
                &ctx.accounts.system_program,
            )?;
            project.allowed_programs.push(allowed_program.key());
        }
    }

    if let Some(collection) = args.collection {
        if args.remove.unwrap_or(false) {
            project.collections.retain(|key| !(*key).eq(&collection));
            reallocate(
                -32isize,
                project.to_account_info(),
                ctx.accounts.payer.to_account_info(),
                &ctx.accounts.rent_sysvar,
                &ctx.accounts.system_program,
            )?;
        } else {
            reallocate(
                32isize,
                project.to_account_info(),
                ctx.accounts.payer.to_account_info(),
                &ctx.accounts.rent_sysvar,
                &ctx.accounts.system_program,
            )?;
            project.collections.push(collection);
        }
    }

    if let Some(creator) = args.creator {
        if args.remove.unwrap_or(false) {
            project.creators.retain(|key| !(*key).eq(&creator));
            reallocate(
                -32isize,
                project.to_account_info(),
                ctx.accounts.payer.to_account_info(),
                &ctx.accounts.rent_sysvar,
                &ctx.accounts.system_program,
            )?;
        } else {
            reallocate(
                32isize,
                project.to_account_info(),
                ctx.accounts.payer.to_account_info(),
                &ctx.accounts.rent_sysvar,
                &ctx.accounts.system_program,
            )?;
            project.creators.push(creator);
        }
    }

    Event::update_project(project.key(), &project, &ctx.accounts.clock)
        .wrap(ctx.accounts.log_wrapper.to_account_info())?;

    Ok(())
}

#[derive(Accounts)]
pub struct AddRemoveService<'info> {
    /// The project account.
    #[account(mut)]
    pub project: Account<'info, Project>,

    /// [Option] delegate authority state account
    #[account()]
    pub delegate_authority: Option<Account<'info, DelegateAuthority>>,

    /// The (delegate) authority of the project.
    pub authority: Signer<'info>,

    /// The wallet that pays for the rent.
    #[account(mut)]
    pub payer: Signer<'info>,

    /// NATIVE RENT SYSVAR
    pub rent_sysvar: Sysvar<'info, Rent>,

    /// System Program.
    pub system_program: Program<'info, System>,

    /// NO OP program
    pub log_wrapper: Program<'info, Noop>,

    /// NATIVE SYSVAR CLOCK
    pub clock: Sysvar<'info, Clock>,

    /// The vault that collects the fees.
    /// CHECK: This is not dangerous because we don't read or write from this account
    #[account(mut)]
    pub vault: AccountInfo<'info>,
}

/// Structure representing the arguments for adding or removing a service in a project.
///
/// # Fields
///
/// - `service`: A `Service` object representing the service to be added or removed.
/// - `remove`: An optional boolean value indicating whether the specified service should be added (`false`) or removed (`true`).
#[derive(AnchorSerialize, AnchorDeserialize, Clone)]
pub struct AddRemoveServiceArgs {
    pub service: Service,
    pub remove: Option<bool>,
}

pub fn add_remove_service(
    ctx: Context<AddRemoveService>,
    args: AddRemoveServiceArgs,
) -> Result<()> {
    let project = &mut ctx.accounts.project;
    if args.remove.unwrap_or(false) {
        project.services.retain(|service| service != &args.service);
        reallocate(
            -33isize,
            project.to_account_info(),
            ctx.accounts.payer.to_account_info(),
            &ctx.accounts.rent_sysvar,
            &ctx.accounts.system_program,
        )?;
    } else {
        reallocate(
            33isize,
            project.to_account_info(),
            ctx.accounts.payer.to_account_info(),
            &ctx.accounts.rent_sysvar,
            &ctx.accounts.system_program,
        )?;
        project.services.push(args.service);
    }

    Event::update_project(project.key(), &project, &ctx.accounts.clock)
        .wrap(ctx.accounts.log_wrapper.to_account_info())?;

    Ok(())
}

#[derive(Accounts)]
#[instruction(args: AddAddressContainerToProjectArgs)]
pub struct AddAddressContainerToProject<'info> {
    /// The project account.
    #[account(mut)]
    pub project: Account<'info, Project>,

    /// The address container account.
    #[account(
        init, payer = payer,
        space = AddressContainer::LEN,
        seeds = [b"address_container", format!("{:?}", args.role).as_bytes(), project.key().as_ref(), &[project.mint_indexing.containers]],
        bump
    )]
    pub address_container: Account<'info, AddressContainer>,

    /// [Option] delegate authority state account
    #[account()]
    pub delegate_authority: Option<Account<'info, DelegateAuthority>>,

    /// The (delegate) authority of the project.
    pub authority: Signer<'info>,

    /// The wallet that pays for the rent.
    #[account(mut)]
    pub payer: Signer<'info>,

    /// System Program.
    pub system_program: Program<'info, System>,

    /// NO OP program
    pub log_wrapper: Program<'info, Noop>,

    /// NATIVE SYSVAR CLOCK
    pub clock: Sysvar<'info, Clock>,

    /// The vault that collects the fees.
    /// CHECK: This is not dangerous because we don't read or write from this account
    #[account(mut)]
    pub vault: AccountInfo<'info>,
}

/// Structure representing the arguments for adding an address container to a project.
///
/// # Fields
///
/// - `role`: An `AddressContainerRole` enum representing the role of the address container to be added.
#[derive(AnchorSerialize, AnchorDeserialize, Clone)]
pub struct AddAddressContainerToProjectArgs {
    pub role: AddressContainerRole,
}

pub fn add_address_container_to_project(
    ctx: Context<AddAddressContainerToProject>,
    args: AddAddressContainerToProjectArgs,
) -> Result<()> {
    let project = &mut ctx.accounts.project;
    let address_container = &mut ctx.accounts.address_container;

    address_container.set_defaults();
    address_container.bump = ctx.bumps["address_container"];
    address_container.associated_with = project.key();
    address_container.role = args.role;
    project.mint_indexing.containers += 1;

    Event::add_address_container_to_project(
        project.key(),
        address_container.key(),
        &address_container,
        project.mint_indexing.containers,
        &ctx.accounts.clock,
    )
    .wrap(ctx.accounts.log_wrapper.to_account_info())?;

    Ok(())
}

#[derive(Accounts)]
#[instruction(args: AddMintAddressesToAddressContainerArgs)]
pub struct AddMintAddressesToAddressContainer<'info> {
    /// The project accounnt
    #[account(mut)]
    pub project: Account<'info, Project>,

    /// The address container account
    #[account(
        mut,
        seeds = [b"address_container", format!("{:?}", address_container.role).as_bytes(), project.key().as_ref(), &[args.index]],
        bump
    )]
    pub address_container: Account<'info, AddressContainer>,

    /// [Option] delegate authority state account
    #[account()]
    pub delegate_authority: Option<Account<'info, DelegateAuthority>>,

    /// The (delegate) authority of the project
    pub authority: Signer<'info>,

    /// The wallet that pays for the rent
    #[account(mut)]
    pub payer: Signer<'info>,

    /// SYSVAR RENT ACCOUNT
    pub rent_sysvar: Sysvar<'info, Rent>,

    /// System Program
    pub system_program: Program<'info, System>,

    /// NO OP program
    pub log_wrapper: Program<'info, Noop>,

    /// NATIVE SYSVAR CLOCK
    pub clock: Sysvar<'info, Clock>,
}

/// Structure representing the arguments for adding mint addresses to an address container.
///
/// # Fields
///
/// - `index`: The index of the address container to which the mint addresses will be added.
/// - `addresses`: A vector of Solana public keys representing the mint addresses to be added to the address container.
#[derive(AnchorSerialize, AnchorDeserialize, Clone)]
pub struct AddMintAddressesToAddressContainerArgs {
    pub index: u8,
    pub addresses: Vec<Pubkey>,
}

pub fn add_mint_addresses_to_address_container(
    ctx: Context<AddMintAddressesToAddressContainer>,
    args: AddMintAddressesToAddressContainerArgs,
) -> Result<()> {
    let project = &mut ctx.accounts.project;
    let address_container = &mut ctx.accounts.address_container;

    if address_container.role != AddressContainerRole::ProjectMints {
        return Err(ErrorCode::WrongAddressContainerRole.into());
    }

    if project.mint_indexing.indexed + args.addresses.len() as u64 > project.mint_indexing.expected
    {
        return Err(ErrorCode::TooManyAddresses.into());
    }

    if address_container.addresses.len() + args.addresses.len() > 317 {
        return Err(ErrorCode::TooManyAddresses.into());
    }

    reallocate(
        (args.addresses.len() * 32) as isize,
        address_container.to_account_info(),
        ctx.accounts.payer.to_account_info(),
        &ctx.accounts.rent_sysvar,
        &ctx.accounts.system_program,
    )?;

    address_container.addresses.extend(args.addresses.iter());
    project.mint_indexing.indexed += args.addresses.len() as u64;

    Event::update_address_container(
        address_container.key(),
        &address_container,
        &ctx.accounts.clock,
    )
    .wrap(ctx.accounts.log_wrapper.to_account_info())?;

    Ok(())
}

#[derive(Accounts)]
pub struct AddRemoveProfileDataConfig<'info> {
    /// The project account.
    #[account(mut)]
    pub project: Account<'info, Project>,

    /// [Option] delegate authority state account
    #[account()]
    pub delegate_authority: Option<Account<'info, DelegateAuthority>>,

    /// The (delegate) authority of the project.
    pub authority: Signer<'info>,

    /// The wallet that pays for the rent.
    #[account(mut)]
    pub payer: Signer<'info>,

    /// NATIVE RENT SYSVAR
    pub rent_sysvar: Sysvar<'info, Rent>,

    /// System Program.
    pub system_program: Program<'info, System>,

    /// NO OP program
    pub log_wrapper: Program<'info, Noop>,

    /// NATIVE SYSVAR CLOCK
    pub clock: Sysvar<'info, Clock>,

    /// The vault that collects the fees.
    /// CHECK: This is not dangerous because we don't read or write from this account
    #[account(mut)]
    pub vault: AccountInfo<'info>,
}
/// Structure representing the arguments for adding or removing a profile data configuration in a project.
///
/// # Fields
///
/// - `label`: The label of the profile data configuration to be added or removed.
/// - `data_type`: An optional `ProfileDataType` enum representing the data type for the profile data configuration.
#[derive(AnchorSerialize, AnchorDeserialize, Clone)]
pub struct AddRemoveProfileDataConfigArgs {
    pub label: String,
    pub data_type: Option<ProfileDataType>,
}

pub fn add_remove_profile_data_config(
    ctx: Context<AddRemoveProfileDataConfig>,
    args: AddRemoveProfileDataConfigArgs,
) -> Result<()> {
    let project = &mut ctx.accounts.project;

    msg!("{}", project.to_account_info().data_len());

    if let Some(data_type) = args.data_type {
        reallocate(
            args.label.as_bytes().len() as isize + ProfileDataType::LEN as isize,
            project.to_account_info(),
            ctx.accounts.payer.to_account_info(),
            &ctx.accounts.rent_sysvar,
            &ctx.accounts.system_program,
        )?;
        project.profile_data_config.insert(args.label, data_type);
    } else {
        project.profile_data_config.remove(&args.label);
        reallocate(
            (args.label.as_bytes().len() as isize + ProfileDataType::LEN as isize) * -1,
            project.to_account_info(),
            ctx.accounts.payer.to_account_info(),
            &ctx.accounts.rent_sysvar,
            &ctx.accounts.system_program,
        )?;
    }

    Event::update_project(project.key(), &project, &ctx.accounts.clock)
        .wrap(ctx.accounts.log_wrapper.to_account_info())?;

    Ok(())
}

#[derive(Accounts)]
pub struct ClearProfileDataConfig<'info> {
    /// The project account.
    #[account(mut)]
    pub project: Account<'info, Project>,

    /// [Option] delegate authority state account
    #[account()]
    pub delegate_authority: Option<Account<'info, DelegateAuthority>>,

    /// The (delegate) authority of the project.
    pub authority: Signer<'info>,

    /// The wallet that pays for the rent.
    #[account(mut)]
    pub payer: Signer<'info>,

    /// NATIVE RENT SYSVAR
    pub rent_sysvar: Sysvar<'info, Rent>,

    /// System Program.
    pub system_program: Program<'info, System>,

    /// NO OP program
    pub log_wrapper: Program<'info, Noop>,

    /// NATIVE SYSVAR CLOCK
    pub clock: Sysvar<'info, Clock>,

    /// The vault that collects the fees.
    /// CHECK: This is not dangerous because we don't read or write from this account
    #[account(mut)]
    pub vault: AccountInfo<'info>,
}
pub fn clear_profile_data_config(ctx: Context<ClearProfileDataConfig>) -> Result<()> {
    let project = &mut ctx.accounts.project;

    let mut size: isize = 0;
    project
        .profile_data_config
        .iter()
        .for_each(|(label, _config)| {
            size -= label.as_bytes().len() as isize;
            size -= ProfileDataType::LEN as isize;
        });
    project.profile_data_config = HashMap::new();
    reallocate(
        size,
        project.to_account_info(),
        ctx.accounts.payer.to_account_info(),
        &ctx.accounts.rent_sysvar,
        &ctx.accounts.system_program,
    )?;

    Event::update_project(project.key(), &project, &ctx.accounts.clock)
        .wrap(ctx.accounts.log_wrapper.to_account_info())?;

    Ok(())
}