1use anchor_lang::prelude::*;
2
3declare_id!("3mQdn2TX5x4sX5Niisy6Q5B8yHDqtGxvYUXj58DCcuJ7");
5
6#[program]
7pub mod pda_counter {
8 use super::*;
9
10 pub fn initialize(ctx: Context<Initialize>) -> Result<()> {
12 let counter = &mut ctx.accounts.counter; counter.count = 0; counter.user = *ctx.accounts.user.key;
15
16 emit!(CounterInit {
18 user: counter.user,
19 count: counter.count,
20 });
21
22 Ok(())
23 }
24
25 pub fn increment(ctx: Context<Increment>) -> Result<()> {
27 let counter = &mut ctx.accounts.counter;
28
29 if counter.user != *ctx.accounts.user.key {
31 return err!(CounterError::InvalidUser);
32 }
33 counter.count += 1;
34
35 emit!(CounterIncrease {
37 user: counter.user,
38 count: counter.count,
39 });
40
41 Ok(())
42 }
43
44 pub fn reset(ctx: Context<Reset>) -> Result<()> {
46 let counter = &mut ctx.accounts.counter;
47
48 if counter.user != *ctx.accounts.user.key {
50 return err!(CounterError::InvalidUser);
51 }
52 counter.count = 0;
53
54 emit!(CounterReset { user: counter.user });
56
57 Ok(())
58 }
59}
60
61#[derive(Accounts)]
65pub struct Initialize<'info> {
66 #[account(
67 init,
68 payer = user,
69 space = 8 + 32 + 8,
70 seeds = [b"counte", user.key().as_ref()], bump )]
72 pub counter: Account<'info, Counter>,
73 #[account(mut)]
74 pub user: Signer<'info>,
75 pub system_program: Program<'info, System>,
76}
77
78#[derive(Accounts)]
80pub struct Increment<'info> {
81 #[account(
82 mut,
83 seeds = [b"counte", user.key().as_ref()], bump
84 )]
85 pub counter: Account<'info, Counter>,
86 pub user: Signer<'info>,
87}
88
89#[derive(Accounts)]
91pub struct Reset<'info> {
92 #[account(mut,
93 seeds = [b"counte", user.key().as_ref()], bump,
94 close = user,
95 )]
96 pub counter: Account<'info, Counter>,
97 pub user: Signer<'info>,
98}
99
100#[account]
104pub struct Counter {
105 pub user: Pubkey,
106 pub count: u64,
107}
108
109#[event]
113pub struct CounterInit {
114 pub user: Pubkey,
115 pub count: u64,
116}
117
118#[event]
120pub struct CounterIncrease {
121 pub user: Pubkey,
122 pub count: u64,
123}
124
125#[event]
127pub struct CounterReset {
128 pub user: Pubkey,
129}
130
131#[error_code]
135pub enum CounterError {
136 #[msg("Unauthorised User")]
137 InvalidUser,
138}