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
use {
    crate::{
        assertions::{assert_merkle_tree, assert_user},
        errors::ErrorCode,
        state::*,
    },
    anchor_lang::prelude::*,
    hpl_utils::{reallocate, traits::Default},
    // sol_did::{
    //     cpi::{
    //         accounts::{AddService, RemoveService},
    //         add_service, remove_service,
    //     },
    //     program::SolDid,
    //     state::{DidAccount, Service},
    // },
    spl_account_compression::{
        cpi::{
            accounts::{CloseTree, Initialize, Modify, VerifyLeaf},
            append, close_empty_tree, init_empty_merkle_tree, replace_leaf, verify_leaf,
        },
        program::SplAccountCompression,
        Node, Noop,
    },
};

#[derive(Accounts)]
#[instruction(args: CreateProfileArgs)]
pub struct CreateProfile<'info> {
    /// The user state account
    #[account()]
    pub user: Box<Account<'info, User>>,

    /// The project state account
    #[account()]
    pub project: Box<Account<'info, Project>>,

    /// User's profile for the provided project
    #[account(
        init, payer = wallet,
        space = Profile::LEN,
        seeds = [
            b"profile".as_ref(),
            project.key().as_ref(),
            user.key().as_ref(),
            &args.identity.to_bytes()[..]
        ],
        bump
      )]
    pub profile: Account<'info, Profile>,

    /// User's decentralized identity data account
    /// CHECK: This is not dangerous, not deserializing becase of version mismatch
    #[account(mut)]
    pub did_data: AccountInfo<'info>,

    /// One of the user's wallet
    #[account(mut)]
    pub wallet: Signer<'info>,

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

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

    /// SOL DID Program
    /// CHECK: This is not dangerous, not deserializing becase of version mismatch
    pub sol_did_program: AccountInfo<'info>,

    /// 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
    #[account(mut)]
    pub vault: AccountInfo<'info>,
}

/// Structure representing the arguments for creating a new profile on the chain.
#[derive(AnchorSerialize, AnchorDeserialize, Clone, Debug, PartialEq)]
pub struct CreateProfileArgs {
    /// Identity of the profile being created. It can be one of the following variants:
    /// - `ProfileIdentity::Main`: Represents the main identity of the profile.
    /// - `ProfileIdentity::Wallet`: Represents an identity associated with a specific wallet.
    /// - `ProfileIdentity::Value`: Represents an identity with a custom string value.
    pub identity: ProfileIdentity,
}

pub fn create_profile(ctx: Context<CreateProfile>, args: CreateProfileArgs) -> Result<()> {
    assert_user(&ctx.accounts.user, ctx.accounts.wallet.key())?;

    let profile = &mut ctx.accounts.profile;
    profile.set_defaults();
    profile.bump = ctx.bumps["profile"];
    profile.project = ctx.accounts.project.key();
    profile.user = ctx.accounts.user.key();
    profile.identity = args.identity.clone();

    // let did_data = DidAccount::try_from(&ctx.accounts.did_data, &ctx.accounts.user.key(), None)?;
    // msg!("Services: {}", did_data.services.len());
    // if did_data.services.len() < 5 {
    //     let user_seeds = [
    //         b"user".as_ref(),
    //         ctx.accounts.user.username.as_bytes(),
    //         &[ctx.accounts.user.bump],
    //     ];
    //     let user_signer = &[&user_seeds[..]];
    //     // TODO: DID account size limitation; create issue and open PR
    //     add_service(
    //         CpiContext::new_with_signer(
    //             ctx.accounts.sol_did_program.to_account_info(),
    //             AddService {
    //                 did_data: ctx.accounts.did_data.to_account_info(),
    //                 authority: ctx.accounts.user.to_account_info(),
    //             },
    //             user_signer,
    //         ),
    //         Service {
    //             fragment: format!(
    //                 "{};{}",
    //                 ctx.accounts.project.key().to_string(),
    //                 args.identity.to_string()
    //             ),
    //             service_type: "HoneycombProject".to_string(),
    //             service_endpoint: "https://did-resolver.honeycombprotocol.com".to_string(),
    //         },
    //         false,
    //         None,
    //     )?;
    // }

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

    Ok(())
}

#[derive(Accounts)]
pub struct DeleteProfile<'info> {
    /// The user state account
    #[account()]
    pub user: Box<Account<'info, User>>,

    /// The project state account
    #[account()]
    pub project: Box<Account<'info, Project>>,

    /// User's profile for the provided project
    #[account(mut, has_one = user, has_one = project, close = wallet)]
    pub profile: Account<'info, Profile>,

    /// User's decentralized identity data account
    /// CHECK: This is not dangerous, not deserializing becase of version mismatch
    #[account(mut)]
    pub did_data: AccountInfo<'info>,

    /// One of the user's wallet
    #[account(mut)]
    pub wallet: Signer<'info>,

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

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

    /// SOL DID Program
    /// CHECK: This is not dangerous, not deserializing becase of version mismatch
    pub sol_did_program: AccountInfo<'info>,

    /// 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
    #[account(mut)]
    pub vault: AccountInfo<'info>,
}

pub fn delete_profile(ctx: Context<DeleteProfile>) -> Result<()> {
    assert_user(&ctx.accounts.user, ctx.accounts.wallet.key())?;

    // let fragment = format!(
    //     "{};{}",
    //     ctx.accounts.project.key().to_string(),
    //     ctx.accounts.profile.identity.to_string()
    // );
    // let found = ctx
    //     .accounts
    //     .did_data
    //     .services
    //     .iter()
    //     .find(|s| s.fragment == fragment);

    // if found.is_some() {
    //     let user_seeds = [
    //         b"user".as_ref(),
    //         ctx.accounts.user.username.as_bytes(),
    //         &[ctx.accounts.user.bump],
    //     ];
    //     let user_signer = &[&user_seeds[..]];

    //     remove_service(
    //         CpiContext::new_with_signer(
    //             ctx.accounts.sol_did_program.to_account_info(),
    //             RemoveService {
    //                 did_data: ctx.accounts.did_data.to_account_info(),
    //                 authority: ctx.accounts.user.to_account_info(),
    //             },
    //             user_signer,
    //         ),
    //         fragment,
    //         None,
    //     )?;
    // }

    Ok(())
}

#[derive(Accounts)]
pub struct ManageProfileData<'info> {
    /// The project state account
    #[account()]
    pub project: Box<Account<'info, Project>>,

    /// User's profile for the provided project
    #[account(mut, has_one = project)]
    pub profile: Box<Account<'info, Profile>>,

    /// [Option] The merkle tree account
    /// CHECK: This account must have same authority as profile
    #[account(mut)]
    pub merkle_tree: Option<UncheckedAccount<'info>>,

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

    /// The authority (or delegate) 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>,

    /// NATIVE Instructions SYSVAR
    /// CHECK: This is not dangerous
    #[account(address = anchor_lang::solana_program::sysvar::instructions::ID)]
    pub instructions_sysvar: AccountInfo<'info>,

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

    /// SPL Account Compression program
    pub compression_program: Program<'info, SplAccountCompression>,

    /// 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
    #[account(mut)]
    pub vault: AccountInfo<'info>,
}
/// Structure representing the arguments for adding profile data to a profile.
///
/// # Fields
///
/// - `label`: Label or name of the profile data being added.
/// - `value`: Value of the profile data being added. It can be one of the following variants:
///     - `None`: If no value is provided.
///     - `Some(AddProfileDataArgsValue::SingleValue)`: Represents a single string value.
///     - `Some(AddProfileDataArgsValue::MultiValue)`: Represents a list of string values.
///     - `Some(AddProfileDataArgsValue::EntityData)`: Represents an entity data node (32-byte array).
#[derive(AnchorSerialize, AnchorDeserialize)]
pub struct AddProfileDataArgs {
    pub label: String,
    pub value: Option<AddProfileDataArgsValue>,
}

/// Enum representing different types of profile data values that can be added to a profile.
///
/// # Variants
///
/// - `SingleValue`: Represents a single string value.
///     - `value`: The single string value to be added to the profile.
///
/// - `MultiValue`: Represents a list of string values.
///     - `value`: The list of string values to be added to the profile.
///
/// - `EntityData`: Represents an merkle tree node (32-byte array).
///     - `node`: The 32-byte array representing the entity data node to be added to the cocurret merkle tree.
#[derive(AnchorSerialize, AnchorDeserialize, Clone)]
pub enum AddProfileDataArgsValue {
    SingleValue { value: String },
    MultiValue { value: Vec<String> },
    EntityData { node: [u8; 32] },
}

pub fn add_profile_data(ctx: Context<ManageProfileData>, args: AddProfileDataArgs) -> Result<()> {
    assert_eq!(
        ctx.accounts
            .project
            .profile_data_config
            .contains_key(&args.label),
        true
    );

    let profile = &mut ctx.accounts.profile;

    if args.value.is_none()
        || !matches!(
            args.value.clone().unwrap(),
            AddProfileDataArgsValue::EntityData { node: _ }
        )
    {
        reallocate(
            40 + 24 as isize,
            profile.to_account_info(),
            ctx.accounts.payer.to_account_info(),
            &ctx.accounts.rent_sysvar,
            &ctx.accounts.system_program,
        )?
    }

    let config = ctx
        .accounts
        .project
        .profile_data_config
        .get(&args.label)
        .unwrap();

    match config {
        ProfileDataType::SingleValue => {
            if args.value.is_none() {
                return Err(ErrorCode::InvalidValueType.into());
            }

            if profile.data.get(&args.label).is_some() {
                match profile.data.get(&args.label).unwrap() {
                    ProfileData::SingleValue { value } => {
                        if value != "" {
                            return Err(ErrorCode::NonEmptyDataAdd.into());
                        }
                    }
                    _ => return Err(ErrorCode::InvalidValueType.into()),
                }
            }

            if let AddProfileDataArgsValue::SingleValue { value } = args.value.unwrap() {
                profile
                    .data
                    .insert(args.label, ProfileData::SingleValue { value });
                return Ok(());
            } else {
                return Err(ErrorCode::InvalidValueType.into());
            }
        }
        ProfileDataType::MultiValue => {
            if args.value.is_none() {
                return Err(ErrorCode::InvalidValueType.into());
            }

            if profile.data.get(&args.label).is_some() {
                match profile.data.get(&args.label).unwrap() {
                    ProfileData::MultiValue { value } => {
                        if value.len() > 0 {
                            return Err(ErrorCode::NonEmptyDataAdd.into());
                        }
                    }
                    _ => return Err(ErrorCode::InvalidValueType.into()),
                }
            }

            if let AddProfileDataArgsValue::MultiValue { value } = args.value.unwrap() {
                profile
                    .data
                    .insert(args.label, ProfileData::MultiValue { value });
                return Ok(());
            } else {
                return Err(ErrorCode::InvalidValueType.into());
            }
        }
        ProfileDataType::Entity {
            merkle_tree_max_depth,
            merkle_tree_max_buffer_size,
        } => {
            let project_seeds = [
                b"project".as_ref(),
                ctx.accounts.project.key.as_ref(),
                &[ctx.accounts.project.bump],
            ];
            let project_signer = &[&project_seeds[..]];

            let merkle_tree = ctx
                .accounts
                .merkle_tree
                .as_ref()
                .ok_or(ErrorCode::MissingMerkleTree)?;

            if args.value.is_none() {
                init_empty_merkle_tree(
                    CpiContext::new_with_signer(
                        ctx.accounts.compression_program.to_account_info(),
                        Initialize {
                            merkle_tree: merkle_tree.to_account_info(),
                            authority: ctx.accounts.project.to_account_info(),
                            noop: ctx.accounts.log_wrapper.to_account_info(),
                        },
                        project_signer,
                    ),
                    *merkle_tree_max_depth,
                    *merkle_tree_max_buffer_size,
                )?;

                profile.data.insert(
                    args.label,
                    ProfileData::Entity {
                        tree: merkle_tree.key(),
                    },
                );
            } else {
                if let AddProfileDataArgsValue::EntityData { node } = args.value.unwrap() {
                    assert_merkle_tree(&ctx.accounts.profile, merkle_tree.key())?;
                    return append(
                        CpiContext::new_with_signer(
                            ctx.accounts.compression_program.to_account_info(),
                            Modify {
                                merkle_tree: merkle_tree.to_account_info(),
                                authority: ctx.accounts.project.to_account_info(),
                                noop: ctx.accounts.log_wrapper.to_account_info(),
                            },
                            project_signer,
                        ),
                        node,
                    );
                } else {
                    return Err(ErrorCode::InvalidValueType.into());
                }
            }
        }
    }

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

    Ok(())
}

/// Structure representing the arguments for modifying profile data in a profile.
///
/// # Fields
///
/// - `label`: Label or name of the profile data being modified.
/// - `value`: Value of the profile data being modified. It can be one of the following variants:
///     - `ModifyProfileDataArgsValue::SingleValue`: Represents a single string value.
///         - `value`: The updated single string value for the profile data.
///     - `ModifyProfileDataArgsValue::MultiValue`: Represents a list of string values.
///         - `value`: The updated list of string values for the profile data.
///     - `ModifyProfileDataArgsValue::EntityData`: Represents an updated entity data node (32-byte array) in a Merkle tree.
///         - `root`: The 32-byte array representing the Merkle root hash.
///         - `leaf`: The original 32-byte array representing the Merkle leaf hash to be updated.
///         - `updated_leaf`: The updated 32-byte array representing the new Merkle leaf hash.
///         - `leaf_index`: The index of the leaf node to be updated in the Merkle tree.
#[derive(AnchorSerialize, AnchorDeserialize)]
pub struct ModifyProfileDataArgs {
    pub label: String,
    pub value: ModifyProfileDataArgsValue,
}

/// Enum representing different types of profile data values that can be modified in a profile.
///
/// # Variants
///
/// - `SingleValue`: Represents a single string value.
///     - `value`: The updated single string value for the profile data.
///
/// - `MultiValue`: Represents a list of string values.
///     - `value`: The updated list of string values for the profile data.
///
/// - `EntityData`: Represents an updated entity data node (32-byte array) in a Merkle tree.
///     - `root`: The 32-byte array representing the Merkle root hash.
///     - `leaf`: The original 32-byte array representing the Merkle leaf hash to be updated.
///     - `updated_leaf`: The updated 32-byte array representing the new Merkle leaf hash.
///     - `leaf_index`: The index of the leaf node to be updated in the Merkle tree.
#[derive(AnchorSerialize, AnchorDeserialize)]
pub enum ModifyProfileDataArgsValue {
    SingleValue {
        value: String,
    },
    MultiValue {
        value: Vec<String>,
    },
    EntityData {
        root: [u8; 32],
        leaf: [u8; 32],
        updated_leaf: [u8; 32],
        leaf_index: u32,
    },
}

pub fn modify_profile_data(
    ctx: Context<ManageProfileData>,
    args: ModifyProfileDataArgs,
) -> Result<()> {
    let profile = &mut ctx.accounts.profile;
    let res = match &profile.data[&args.label] {
        ProfileData::SingleValue { value: _ } => {
            if let ModifyProfileDataArgsValue::SingleValue { value } = args.value {
                profile
                    .data
                    .insert(args.label, ProfileData::SingleValue { value });
                Ok(())
            } else {
                Err(ErrorCode::InvalidValueType.into())
            }
        }
        ProfileData::MultiValue { value: _ } => {
            if let ModifyProfileDataArgsValue::MultiValue { value } = args.value {
                profile
                    .data
                    .insert(args.label, ProfileData::MultiValue { value });
                Ok(())
            } else {
                Err(ErrorCode::InvalidValueType.into())
            }
        }
        ProfileData::Entity { tree: _ } => {
            if let ModifyProfileDataArgsValue::EntityData {
                root,
                leaf,
                updated_leaf,
                leaf_index,
            } = args.value
            {
                let merkle_tree = ctx
                    .accounts
                    .merkle_tree
                    .as_ref()
                    .ok_or(ErrorCode::MissingMerkleTree)?;
                assert_merkle_tree(&profile, merkle_tree.key())?;

                let project_seeds = [
                    b"project".as_ref(),
                    ctx.accounts.project.key.as_ref(),
                    &[ctx.accounts.project.bump],
                ];
                let project_signer = &[&project_seeds[..]];

                replace_leaf(
                    CpiContext::new_with_signer(
                        ctx.accounts.compression_program.to_account_info(),
                        Modify {
                            merkle_tree: merkle_tree.to_account_info(),
                            authority: ctx.accounts.project.to_account_info(),
                            noop: ctx.accounts.log_wrapper.to_account_info(),
                        },
                        project_signer,
                    ),
                    root,
                    leaf,
                    updated_leaf,
                    leaf_index,
                )
            } else {
                Err(ErrorCode::InvalidValueType.into())
            }
        }
    };

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

    res
}

/// Structure representing the arguments for removing profile data from a profile.
///
/// # Fields
///
/// - `label`: Label or name of the profile data being removed.
/// - `value`: Value of the profile data being removed. It can be one of the following variants:
///     - `RemoveProfileDataArgsValue::SingleValue`: Represents a single string value to be removed.
///     - `RemoveProfileDataArgsValue::MultiValue`: Represents a list of string values to be removed.
///     - `RemoveProfileDataArgsValue::EntityData`: Represents an entity data node (32-byte array) in a Merkle tree to be removed.
///         - `root`: The 32-byte array representing the Merkle root hash.
///         - `leaf`: The 32-byte array representing the Merkle leaf hash to be removed.
///         - `leaf_index`: The index of the leaf node to be removed in the Merkle tree.
///     - `RemoveProfileDataArgsValue::Entity`: Represents a complete entity profile to be removed.
#[derive(AnchorSerialize, AnchorDeserialize)]
pub struct RemoveProfileDataArgs {
    pub label: String,
    pub value: RemoveProfileDataArgsValue,
}

/// Enum representing different types of profile data values that can be removed from a profile.
///
/// # Variants
///
/// - `SingleValue`: Represents a single string value to be removed.
///
/// - `MultiValue`: Represents a list of string values to be removed.
///
/// - `EntityData`: Represents an entity data node (32-byte array) in a Merkle tree to be removed.
///     - `root`: The 32-byte array representing the Merkle root hash.
///     - `leaf`: The 32-byte array representing the Merkle leaf hash to be removed.
///     - `leaf_index`: The index of the leaf node to be removed in the Merkle tree.
///
/// - `Entity`: Represents a complete entity profile to be removed.
#[derive(AnchorSerialize, AnchorDeserialize, PartialEq)]
pub enum RemoveProfileDataArgsValue {
    SingleValue,
    MultiValue,
    EntityData {
        root: [u8; 32],
        leaf: [u8; 32],
        leaf_index: u32,
    },
    Entity,
}

pub fn remove_profile_data(
    ctx: Context<ManageProfileData>,
    args: RemoveProfileDataArgs,
) -> Result<()> {
    let project_seeds = [
        b"project".as_ref(),
        ctx.accounts.project.key.as_ref(),
        &[ctx.accounts.project.bump],
    ];
    let project_signer = &[&project_seeds[..]];

    let res = match args.value {
        RemoveProfileDataArgsValue::EntityData {
            root,
            leaf,
            leaf_index,
        } => {
            let merkle_tree = ctx
                .accounts
                .merkle_tree
                .as_ref()
                .ok_or(ErrorCode::MissingMerkleTree)?;
            assert_merkle_tree(&ctx.accounts.profile, merkle_tree.key())?;

            replace_leaf(
                CpiContext::new_with_signer(
                    ctx.accounts.compression_program.to_account_info(),
                    Modify {
                        merkle_tree: merkle_tree.to_account_info(),
                        authority: ctx.accounts.project.to_account_info(),
                        noop: ctx.accounts.log_wrapper.to_account_info(),
                    },
                    project_signer,
                ),
                root,
                leaf,
                Node::default(),
                leaf_index,
            )
        }
        _ => {
            if args.value == RemoveProfileDataArgsValue::Entity {
                let merkle_tree = ctx
                    .accounts
                    .merkle_tree
                    .as_ref()
                    .ok_or(ErrorCode::MissingMerkleTree)?;
                assert_merkle_tree(&ctx.accounts.profile, merkle_tree.key())?;

                close_empty_tree(CpiContext::new_with_signer(
                    ctx.accounts.compression_program.to_account_info(),
                    CloseTree {
                        merkle_tree: merkle_tree.to_account_info(),
                        authority: ctx.accounts.project.to_account_info(),
                        recipient: ctx.accounts.payer.to_account_info(),
                    },
                    project_signer,
                ))?;
            }

            let profile = &mut ctx.accounts.profile;
            profile.data.remove(&args.label);

            reallocate(
                -40 - 24 as isize,
                profile.to_account_info(),
                ctx.accounts.payer.to_account_info(),
                &ctx.accounts.rent_sysvar,
                &ctx.accounts.system_program,
            )
        }
    };

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

    res
}

/// Structure representing the arguments for verifying profile entity data in a profile.
///
/// # Fields
///
/// - `root`: The 32-byte array representing the Merkle root hash of the profile.
/// - `leaf`: The 32-byte array representing the Merkle leaf hash to be verified.
/// - `leaf_index`: The index of the leaf node to be verified in the Merkle tree.
#[derive(AnchorSerialize, AnchorDeserialize)]
pub struct VerifyProfileEntityDataArgs {
    root: [u8; 32],
    leaf: [u8; 32],
    leaf_index: u32,
}

pub fn verify_profile_entity_data(
    ctx: Context<ManageProfileData>,
    args: VerifyProfileEntityDataArgs,
) -> Result<()> {
    let merkle_tree = ctx
        .accounts
        .merkle_tree
        .as_ref()
        .ok_or(ErrorCode::MissingMerkleTree)?;
    assert_merkle_tree(&ctx.accounts.profile, merkle_tree.key())?;

    let project_seeds = [
        b"project".as_ref(),
        ctx.accounts.project.key.as_ref(),
        &[ctx.accounts.project.bump],
    ];
    let project_signer = &[&project_seeds[..]];

    verify_leaf(
        CpiContext::new_with_signer(
            ctx.accounts.compression_program.to_account_info(),
            VerifyLeaf {
                merkle_tree: merkle_tree.to_account_info(),
            },
            project_signer,
        ),
        args.root,
        args.leaf,
        args.leaf_index,
    )
}