gpl_core/instructions/
profile.rs

1use crate::state::{Namespace, Profile, User};
2use anchor_lang::prelude::*;
3use std::convert::AsRef;
4use std::str::FromStr;
5
6use crate::constants::*;
7use crate::events::{ProfileDeleted, ProfileNew};
8
9// Initialize a new profile account
10#[derive(Accounts)]
11#[instruction(namespace: String)]
12pub struct CreateProfile<'info> {
13    // The account that will be initialized as a Profile
14    #[account(
15        init,
16        seeds = [
17            PROFILE_PREFIX_SEED.as_bytes(),
18            namespace.as_bytes(),
19            user.to_account_info().key.as_ref()
20        ],
21        bump,
22        payer = authority,
23        space = Profile::LEN
24    )]
25    pub profile: Account<'info, Profile>,
26    #[account(
27        seeds = [
28            USER_PREFIX_SEED.as_bytes(),
29            user.random_hash.as_ref(),
30        ],
31        bump,
32        has_one = authority,
33    )]
34    pub user: Account<'info, User>,
35    #[account(mut)]
36    pub authority: Signer<'info>,
37    // The system program
38    pub system_program: Program<'info, System>,
39}
40
41// Handler to create a new Profile account
42pub fn create_profile_handler(ctx: Context<CreateProfile>, namespace: String) -> Result<()> {
43    let profile = &mut ctx.accounts.profile;
44    profile.namespace = Namespace::from_str(&namespace).unwrap();
45    profile.user = *ctx.accounts.user.to_account_info().key;
46
47    // Emit new profile event
48    emit!(ProfileNew {
49        profile: *profile.to_account_info().key,
50        namespace: profile.namespace,
51        user: *ctx.accounts.user.to_account_info().key,
52        timestamp: Clock::get()?.unix_timestamp,
53    });
54    Ok(())
55}
56
57// Delete a profile account
58#[derive(Accounts)]
59pub struct DeleteProfile<'info> {
60    // The Profile account to delete
61    #[account(
62        mut,
63        seeds = [
64            PROFILE_PREFIX_SEED.as_bytes(),
65            profile.namespace.as_ref().as_bytes(),
66            profile.user.as_ref(),
67        ],
68        bump,
69        has_one = user,
70        close = authority,
71    )]
72    pub profile: Account<'info, Profile>,
73    #[account(
74        seeds = [
75            USER_PREFIX_SEED.as_bytes(),
76            user.random_hash.as_ref(),
77        ],
78        bump,
79        has_one = authority,
80    )]
81    pub user: Account<'info, User>,
82    #[account(mut)]
83    pub authority: Signer<'info>,
84}
85
86// Handler to close a profile account
87pub fn delete_profile_handler(ctx: Context<DeleteProfile>) -> Result<()> {
88    // Emit profile deleted event
89    emit!(ProfileDeleted {
90        profile: *ctx.accounts.profile.to_account_info().key,
91        namespace: ctx.accounts.profile.namespace,
92        user: *ctx.accounts.user.to_account_info().key,
93        timestamp: Clock::get()?.unix_timestamp,
94    });
95    Ok(())
96}