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
use {
    crate::{assertions::assert_user, errors::ErrorCode, state::*},
    anchor_lang::prelude::*,
    hpl_events::HplEvents,
    hpl_utils::{reallocate, traits::Default},
};

#[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::get_initial_len(&args),
        seeds = [
            b"profile".as_ref(),
            project.key().as_ref(),
            user.key().as_ref(),
            &args.identity.to_bytes()[..]
        ],
        bump
      )]
    pub profile: Account<'info, Profile>,

    /// 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>,

    /// NO OP program
    pub hpl_events: Program<'info, HplEvents>,

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

    /// NATIVE INSTRUCTIONS SYSVAR
    /// CHECK: This is not dangerous because we don't read or write from this account
    #[account(address = anchor_lang::solana_program::sysvar::instructions::ID)]
    pub instructions_sysvar: AccountInfo<'info>,

    /// 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::Value`: Represents an identity with a custom string value.
    pub identity: ProfileIdentity,

    /// Profile specific name.
    pub name: Option<String>,

    /// Profile specific description.
    pub bio: Option<String>,

    /// Profile specific pfp url.
    pub pfp: Option<String>,
}

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();
    profile.name = args.name.clone();
    profile.bio = args.bio.clone();
    profile.pfp = args.pfp.clone();

    Event::new_profile(
        profile.key(),
        profile.try_to_vec().unwrap(),
        &ctx.accounts.clock,
    )
    .emit(ctx.accounts.hpl_events.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>,

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

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

    /// NO OP program
    pub hpl_events: Program<'info, HplEvents>,

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

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

    /// NATIVE INSTRUCTIONS SYSVAR
    /// CHECK: This is not dangerous because we don't read or write from this account
    #[account(address = anchor_lang::solana_program::sysvar::instructions::ID)]
    pub instructions_sysvar: AccountInfo<'info>,

    /// 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())?;
    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] 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>,

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

    /// NO OP program
    pub hpl_events: Program<'info, HplEvents>,

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

    /// 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 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(ManageProfileDataArgsValue::SingleValue)`: Represents a single string value.
///     - `Some(ManageProfileDataArgsValue::MultiValue)`: Represents a list of string values.
///     - `Some(ManageProfileDataArgsValue::EntityData)`: Represents an entity data node (32-byte array).
#[derive(AnchorSerialize, AnchorDeserialize)]
pub struct ManageProfileDataArgs {
    pub label: String,
    pub value: Option<ProfileData>,
    pub is_app_context: bool,
}

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

    let profile_info = ctx.accounts.profile.to_account_info();
    let profile = &mut ctx.accounts.profile;

    let to_update = if args.is_app_context {
        &mut profile.app_context
    } else {
        &mut profile.data
    };

    let mut len = if to_update.contains_key(&args.label) {
        if args.value.is_none() {
            args.label.len() as isize * -1
        } else {
            0
        }
    } else {
        args.label.len() as isize
    };

    if let Some(v) = to_update.get(&args.label) {
        len -= v.size() as isize;
    }

    if let Some(value) = &args.value {
        len += value.size() as isize;
    }

    if len > 0 {
        reallocate(
            len,
            profile_info.clone(),
            ctx.accounts.payer.to_account_info(),
            &ctx.accounts.rent_sysvar,
            &ctx.accounts.system_program,
        )?;
    }

    if let Some(profile_data) = args.value {
        if !ctx
            .accounts
            .project
            .validate_profile_data(&args.label, &profile_data)
        {
            return Err(ErrorCode::InvalidValueType.into());
        }
        profile.data.insert(args.label, profile_data);
    } else {
        profile.data.remove(&args.label);
    }

    if len < 0 {
        reallocate(
            len,
            profile_info,
            ctx.accounts.payer.to_account_info(),
            &ctx.accounts.rent_sysvar,
            &ctx.accounts.system_program,
        )?;
    }

    Event::update_profile(
        profile.key(),
        profile.try_to_vec().unwrap(),
        &ctx.accounts.clock,
    )
    .emit(ctx.accounts.hpl_events.to_account_info())?;

    Ok(())
}