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
use {
    crate::state::*,
    anchor_lang::prelude::*,
    hpl_utils::{reallocate, traits::Default},
    // sol_did::{
    //     cpi::{
    //         accounts::{AddVerificationMethod, Initialize, RemoveVerificationMethod},
    //         add_verification_method, initialize, remove_verification_method,
    //     },
    //     program::SolDid,
    //     state::VerificationMethod,
    // },
    spl_account_compression::Noop,
};

#[derive(Accounts)]
#[instruction(args: InitializeUserArgs)]
pub struct InitializeUser<'info> {
    /// The User accout
    #[account(
        init, payer = wallet,
        space = User::LEN,
        seeds = [b"user".as_ref(), args.username.as_bytes()],
        bump
    )]
    pub user: Account<'info, User>,

    /// The wallet resolver for the primary wallet
    #[account(
        init, payer = wallet,
        space = WalletResolver::LEN,
        seeds = [b"wallet_resolver".as_ref(), wallet.key().as_ref()],
        bump
    )]
    pub wallet_resolver: Account<'info, WalletResolver>,

    /// The decentralized identity account
    /// CHECK: Checked in the DID program
    #[account(mut)]
    pub did_data: AccountInfo<'info>,

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

    /// SYSVAR RENT ACCOUNT
    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>,
}

/// Structure representing the arguments for initializing a user.
///
/// # Fields
///
/// - `username`: The username of the user to be initialized.
/// - `name`: The name of the user to be initialized.
/// - `bio`: The biography of the user to be initialized.
/// - `pfp`: The profile picture URL or identifier of the user to be initialized.
#[derive(AnchorSerialize, AnchorDeserialize, Clone, Debug, PartialEq)]
pub struct InitializeUserArgs {
    pub username: String,
    pub name: String,
    pub bio: String,
    pub pfp: String,
}

pub fn initialize_user(ctx: Context<InitializeUser>, args: InitializeUserArgs) -> Result<()> {
    let user = &mut ctx.accounts.user;
    user.set_defaults();

    let user_info = user.to_account_info();
    let mut diff: usize = 0;

    let username_len = args.username.as_bytes().len();
    if username_len > 24 {
        diff += username_len - 24;
    }

    let name_len = args.name.as_bytes().len();
    if name_len > 24 {
        diff += name_len - 24;
    }

    let bio_len = args.bio.as_bytes().len();
    if bio_len > 24 {
        diff += bio_len - 24;
    }

    let pfp_len = args.pfp.as_bytes().len();
    if pfp_len > 24 {
        diff += pfp_len - 24;
    }

    if diff > 0 {
        reallocate(
            diff as isize,
            user_info,
            ctx.accounts.wallet.to_account_info(),
            &ctx.accounts.rent_sysvar,
            &ctx.accounts.system_program,
        )?;
    }

    user.bump = ctx.bumps["user"];
    user.primary_wallet = ctx.accounts.wallet.key();
    user.username = args.username;
    user.name = args.name;
    user.bio = args.bio;
    user.pfp = args.pfp;

    let wallet_resolver = &mut ctx.accounts.wallet_resolver;
    wallet_resolver.set_defaults();
    wallet_resolver.bump = ctx.bumps["wallet_resolver"];
    wallet_resolver.user = user.key();
    wallet_resolver.wallet = ctx.accounts.wallet.key();

    // let user_seeds = [b"user".as_ref(), user.username.as_bytes(), &[user.bump]];
    // let user_signer = &[&user_seeds[..]];
    // initialize(
    //     CpiContext::new_with_signer(
    //         ctx.accounts.sol_did_program.to_account_info(),
    //         Initialize {
    //             did_data: ctx.accounts.did_data.to_account_info(),
    //             authority: user.to_account_info(),
    //             payer: ctx.accounts.wallet.to_account_info(),
    //             system_program: ctx.accounts.system_program.to_account_info(),
    //         },
    //         user_signer,
    //     ),
    //     1024,
    // )?;

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

    Ok(())
}

#[derive(Accounts)]
pub struct CloseUser<'info> {
    /// The user accout
    #[account(
        mut,
        close = wallet,
    )]
    pub user: Account<'info, User>,

    /// The wallet resolver of the primary wallet
    #[account(mut, has_one = user, close = wallet)]
    pub wallet_resolver: Account<'info, WalletResolver>,

    /// The primary wallet
    #[account(mut)]
    pub wallet: Signer<'info>,

    /// System Program
    pub system_program: Program<'info, System>,
}
pub fn close_user(_ctx: Context<CloseUser>) -> Result<()> {
    Ok(())
}

#[derive(Accounts)]
#[instruction(_env: String)]
pub struct UpdateUser<'info> {
    /// The public info account
    #[account(
        seeds = [b"public_info".as_ref(), _env.as_bytes(), crate::id().as_ref()],
        bump = public_info.bump,
      )]
    pub public_info: Account<'info, PublicInfo>,

    /// The user account
    #[account(mut)]
    pub user: Account<'info, User>,

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

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

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

/// Structure representing the arguments for updating a user.
///
/// # Fields
///
/// - `name`: [Option] new name for the user. If provided, the user's name will be updated.
/// - `bio`: [Option] new biography for the user. If provided, the user's biography will be updated.
/// - `pfp`: [Option] new profile picture URL for the user. If provided, the user's profile picture will be updated.
#[derive(AnchorSerialize, AnchorDeserialize, Clone, Debug, PartialEq)]
pub struct UpdateUserArgs {
    pub name: Option<String>,
    pub bio: Option<String>,
    pub pfp: Option<String>,
}

pub fn update_user(ctx: Context<UpdateUser>, _env: String, args: UpdateUserArgs) -> Result<()> {
    let user = &mut ctx.accounts.user;
    user.name = args.name.unwrap_or(user.name.clone());
    user.bio = args.bio.unwrap_or(user.bio.clone());
    user.pfp = args.pfp.unwrap_or(user.pfp.clone());

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

    Ok(())
}

#[derive(Accounts)]
#[instruction(_env: String)]
pub struct AddWallet<'info> {
    /// The public info account
    #[account(
        seeds = [b"public_info".as_ref(), _env.as_bytes(), crate::id().as_ref()],
        bump = public_info.bump,
      )]
    pub public_info: Account<'info, PublicInfo>,

    /// The wallet resolver for the new wallet
    #[account(
        init, payer = new_wallet,
        space = WalletResolver::LEN,
        seeds = [b"wallet_resolver".as_ref(), new_wallet.key().as_ref()],
        bump
    )]
    pub wallet_resolver: Account<'info, WalletResolver>,

    /// The user accout
    #[account(mut)]
    pub user: Account<'info, User>,

    /// The user's did data account
    /// CHECK: This is not dangerous, not serializing because of version mismatch
    #[account(mut)]
    pub did_data: AccountInfo<'info>,

    /// The new wallet being added to the user account
    #[account(mut)]
    pub new_wallet: Signer<'info>,

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

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

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

pub fn add_wallet(ctx: Context<AddWallet>, _env: String) -> Result<()> {
    let user = &mut ctx.accounts.user;

    reallocate(
        32 as isize,
        user.to_account_info(),
        ctx.accounts.new_wallet.to_account_info(),
        &ctx.accounts.rent_sysvar,
        &ctx.accounts.system_program,
    )?;

    user.secondary_wallets.push(ctx.accounts.new_wallet.key());

    let wallet_resolver = &mut ctx.accounts.wallet_resolver;
    wallet_resolver.set_defaults();
    wallet_resolver.bump = ctx.bumps["wallet_resolver"];
    wallet_resolver.user = user.key();
    wallet_resolver.wallet = ctx.accounts.new_wallet.key();

    // let user_seeds = [b"user".as_ref(), user.username.as_bytes(), &[user.bump]];
    // let user_signer = &[&user_seeds[..]];
    // add_verification_method(
    //     CpiContext::new_with_signer(
    //         ctx.accounts.sol_did_program.to_account_info(),
    //         AddVerificationMethod {
    //             did_data: ctx.accounts.did_data.to_account_info(),
    //             authority: user.to_account_info(),
    //         },
    //         user_signer,
    //     ),
    //     VerificationMethod {
    //         fragment: ctx.accounts.new_wallet.key().to_string(),
    //         flags: 0,
    //         method_type: 0,
    //         key_data: ctx.accounts.new_wallet.key().as_ref().to_vec(),
    //     },
    //     None,
    // )?;

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

    Ok(())
}

#[derive(Accounts)]
#[instruction(_env: String)]
pub struct DeleteWallet<'info> {
    /// The public info account
    #[account(
        seeds = [b"public_info".as_ref(), _env.as_bytes(), crate::id().as_ref()],
        bump = public_info.bump,
      )]
    pub public_info: Account<'info, PublicInfo>,

    /// The wallet resolver of the wallet being removed
    #[account( mut, has_one = user, has_one = wallet, close = wallet )]
    pub wallet_resolver: Account<'info, WalletResolver>,

    /// The user account
    #[account(mut)]
    pub user: Account<'info, User>,

    /// The user's did data account
    /// CHECK: This is not dangerous, not serializing because of version mismatch
    #[account(mut)]
    pub did_data: AccountInfo<'info>,

    /// The wallet being removed
    /// CHECK: This is not dangerous
    #[account(mut)]
    pub wallet: AccountInfo<'info>,

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

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

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

pub fn delete_wallet(ctx: Context<DeleteWallet>, _env: String) -> Result<()> {
    let user = &mut ctx.accounts.user;

    // remove wallet from secondary_wallets
    let index = user
        .secondary_wallets
        .clone()
        .into_iter()
        .position(|x| x == ctx.accounts.wallet.key());
    if let Some(i) = index {
        user.secondary_wallets.swap_remove(i);
    }

    reallocate(
        -32 as isize,
        user.to_account_info(),
        ctx.accounts.wallet.to_account_info(),
        &ctx.accounts.rent_sysvar,
        &ctx.accounts.system_program,
    )?;

    // let user_seeds = [b"user".as_ref(), user.username.as_bytes(), &[user.bump]];
    // let user_signer = &[&user_seeds[..]];
    // remove_verification_method(
    //     CpiContext::new_with_signer(
    //         ctx.accounts.sol_did_program.to_account_info(),
    //         RemoveVerificationMethod {
    //             did_data: ctx.accounts.did_data.to_account_info(),
    //             authority: user.to_account_info(),
    //         },
    //         user_signer,
    //     ),
    //     ctx.accounts.wallet.key().to_string(),
    //     None,
    // )?;

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

    Ok(())
}