惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

GbyAI
GbyAI
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园 - 叶小钗
大猫的无限游戏
大猫的无限游戏
H
Help Net Security
G
Google Developers Blog
D
Docker
阮一峰的网络日志
阮一峰的网络日志
A
About on SuperTechFans
aimingoo的专栏
aimingoo的专栏
博客园 - 聂微东
Hugging Face - Blog
Hugging Face - Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
Apple Machine Learning Research
Apple Machine Learning Research
云风的 BLOG
云风的 BLOG
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
腾讯CDC
T
The Blog of Author Tim Ferriss
Microsoft Security Blog
Microsoft Security Blog
WordPress大学
WordPress大学
I
InfoQ
Engineering at Meta
Engineering at Meta
Stack Overflow Blog
Stack Overflow Blog
Google DeepMind News
Google DeepMind News

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
How I built a Counter program in Anchor and learned to tr...
Siddhant Chavan · 2026-06-22 · via DEV Community

Siddhant Chavan

My first Anchor program finally started feeling like a real on-chain application when I stopped thinking of accounts as “database rows” and started understanding how ownership, constraints, and tests work together.

The first thing Anchor made clear was the account context.

[derive(Accounts)]

pub struct Initialize<'info> {
pub counter: Account<'info, Counter>,
pub authority: Signer<'info>,
pub system_program: Program<'info, System>,
}

The Accounts struct is where Anchor changes the way you think compared to a Web2 backend.

Instead of manually validating requests, allocating storage, and checking permissions, you describe the rules. counter is the on-chain state account, authority is the wallet signing the transaction, and system_program handles account creation. Anchor uses this information to generate the validation logic before your instruction runs.

The initialize handler is surprisingly small:

pub fn initialize(ctx: Context) -> Result<()> {
let counter = &mut ctx.accounts.counter;
counter.authority = ctx.accounts.authority.key();
counter.count = 0;
Ok(())
}

ctx.accounts gives direct access to the accounts passed into the transaction. Because Anchor already verified the accounts, the handler only focuses on business logic: storing the owner and setting the initial value.

Then came the increment instruction:

pub fn increment(ctx: Context) -> Result<()> {
let counter = &mut ctx.accounts.counter;
counter.count = counter.count
.checked_add(1)
.ok_or(ProgramError::ArithmeticOverflow)?;
Ok(())
}

The important part was not the increment itself, but the constraint:

[account(mut, has_one = authority)]

pub counter: Account<'info, Counter>,

has_one = authority guarantees that the signer calling increment is the same wallet stored as the counter owner. The check happens before my code executes.

My tests became the proof that these guarantees actually worked.

The happy path test checks that initialization creates the correct state:

assert_eq!(parsed.count, 0);
assert_eq!(parsed.authority, authority.pubkey());

If this fails, something is wrong with account creation or state initialization.

The failure test checks that unauthorized users cannot modify someone else’s counter:

let result = svm.send_transaction(bad_tx);

assert!(
result.is_err(),
"increment should fail when signed by the wrong authority"
);

If this fails, the program is allowing a wallet that does not own the counter to update it.

The most interesting experiment was breaking the program on purpose.

I changed:

checked_add(1)

to:

checked_add(2)

The program still ran, but the test caught the bug:

assertion left == right failed
left: 2
right: 1

That was the moment I understood why tests matter on-chain. A green test is not just a checkmark — it is evidence that a specific rule is still protected.

Next week, I would build on this by adding more realistic account relationships, better error handling, and connecting the Anchor program with a frontend client.

100DaysOfSolana #solana #rust #anchor #testing