2. Auto-incrementing counter
Goals
1. Building a counter program
anchor init counter
cd counteruse anchor_lang::prelude::*;
// 1️⃣ We define an account to hold our counter state
#[account]
pub struct Counter {
pub current_value: u64, // the value of the counter
pub updated_at: i64, // last time the counter has been updated
}
#[program]
pub mod counter {
use super::*;
// 2️⃣ We define an instruction to mutate the `Counter`
pub fn increment(ctx: Context<Increment>) -> Result<()> {
ctx.accounts.counter.current_value = ctx.accounts.counter.current_value.checked_add(1).unwrap();
ctx.accounts.counter.updated_at = Clock::get().unwrap().unix_timestamp;
Ok(())
}
}
/// Seed for `Counter` account Program Derived Address
/// ⚠ Make sure it matches whatever you are using on the client-side
pub const SEED_COUNTER: &[u8] = b"counter";
// 3️⃣ We define constraints for the `increment` instruction with Anchor macros
#[derive(Accounts)]
pub struct Increment<'info> {
/// The counter account.
#[account(mut, seeds = [SEED_COUNTER], bump)]
pub counter: Account<'info, Counter>,
/// Verify that only this thread can execute the Increment Instruction
#[account(signer, constraint = thread.authority.eq(&thread_authority.key()))]
pub thread: Account<'info, Thread>,
/// The Thread Admin
/// The authority that was used as a seed to derive the thread address
/// `thread_authority` should equal `thread.thread_authority`
#[account(seeds = [THREAD_AUTHORITY_SEED], bump)]
pub thread_authority: SystemAccount<'info>,
}2. Getting familiar with the thread program
3. Creating a thread via CPI
4. Testing our automation

Key Learnings
Appendix
Dependency
Version
Learn more
Last updated