<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Shriya on Medium]]></title>
        <description><![CDATA[Stories by Shriya on Medium]]></description>
        <link>https://medium.com/@2001shriya?source=rss-be3ee38604d3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*44V8cKEX1LAJnye0dTg6cg.png</url>
            <title>Stories by Shriya on Medium</title>
            <link>https://medium.com/@2001shriya?source=rss-be3ee38604d3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 13:40:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@2001shriya/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Transfer-Token Anchor Smart Contract]]></title>
            <link>https://medium.com/@2001shriya/transfer-token-anchor-smart-contract-1113db00d5d1?source=rss-be3ee38604d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/1113db00d5d1</guid>
            <category><![CDATA[anchor-rust]]></category>
            <category><![CDATA[rust-programming-language]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[anchor-smart-contract]]></category>
            <category><![CDATA[token-transfer]]></category>
            <dc:creator><![CDATA[Shriya]]></dc:creator>
            <pubDate>Sat, 04 Jul 2026 13:38:12 GMT</pubDate>
            <atom:updated>2026-07-04T13:59:53.376Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O28WfVxvXr8KOKaV8iRqLg.jpeg" /></figure><p><strong>From Vulnerable to Auditable: Journey Of Building a Production-Ready Token on Solana (Anchor)</strong></p><h3>Introduction: The Goal</h3><p>Every blockchain developer starts somewhere. For me, it was building a basic SPL token on Solana using the Anchor framework. I wanted to create a program that could create, mint, and transfer tokens.</p><p>However, I quickly realized that <strong>“it compiles” is not the same as “it is secure.”</strong></p><p>This blog is a brutally honest log of my journey. I documented every cryptic compiler error, every logical security flaw, and every Git workflow mistake I made while turning a basic transfer_token program into an industrial-grade, auditable smart contract.</p><p>Here is everything I learned.</p><h3>Phase 1: The Naive Implementation (The “It Works!” Stage)</h3><p>I started with the standard Anchor pattern. I had three instructions: create_token, mint_token, and transfer_tokens.</p><p><strong>My initial thought process:</strong></p><ul><li>“I’ll just use init for accounts.&quot;</li><li>“The payer can be the mint_authority.&quot;</li><li>“I’ll set the metadata to false (immutable), because I won&#39;t need to change it.&quot;</li></ul><h3>Mistake #1: The Authority Fallacy</h3><p>I set mint::authority = payer.key(). This meant the private key of the person deploying the contract was the <em>only</em> key that could mint new tokens.</p><p><em>Why this is wrong:</em> If that computer gets hacked (or the private key is leaked), the attacker can mint infinite tokens and rug the project in seconds.</p><h3>Mistake #2: The Front-Running Blindspot</h3><p>I used init for the Associated Token Accounts (ATAs).</p><p><em>Why this is wrong:</em> An attacker could front-run my mint_token transaction, create the recipient&#39;s ATA <em>first</em>, and cause my init to fail because the account already exists. This creates a Denial of Service (DoS) vector. Anyone can brick my minting function for a few cents.</p><h3>Phase 2: Compilation Hell — The Technical Errors</h3><p>This is where the journey got tough. When I tried to compile my secure version, the Rust compiler threw a wall of red text at me. Here are the exact errors and how I solved them.</p><h3>Error 1: could not find &#39;metadata&#39; in &#39;anchor_spl&#39;</h3><ul><li><strong>The Problem:</strong> I imported anchor_spl::metadata, but the compiler couldn&#39;t find it.</li><li><strong>The Deep Dive:</strong> Anchor libraries have <strong>optional Cargo features</strong>. This is done to speed up compilation. If you don’t explicitly tell Cargo to turn on the metadata feature, the compiler ignores that entire folder of code.</li><li><strong>The Fix:</strong> I opened programs/transfer_token/Cargo.toml and explicitly told the compiler to turn it on:</li></ul><pre>anchor-spl = { version = &quot;0.30.1&quot;, features = [&quot;metadata&quot;] }</pre><h3>Error 2: the trait bound &#39;Token: AccountSerialize&#39; is not satisfied</h3><ul><li><strong>The Code:</strong> I declared pub token_program: Account&lt;&#39;info, Token&gt;.</li><li><strong>The Learning:</strong> Token represents the <strong>SPL Token Program</strong> (the factory), not a user data account. Programs don&#39;t hold serialized data; they hold code.</li><li><strong>The Fix:</strong> I changed it to pub token_program: Program&lt;&#39;info, Token&gt;. Account is for data; Program is for executable logic.</li></ul><h3>Error 3: init_if_needed requires that anchor-lang be imported with the init-if-needed cargo feature</h3><ul><li><strong>The Problem:</strong> I used the magical init_if_needed to prevent front-running, but Anchor didn&#39;t know what it was.</li><li><strong>The Fix:</strong> Added the feature to anchor-lang in Cargo.toml:</li></ul><pre>anchor-lang = { version = &quot;0.30.1&quot;, features = [&quot;init-if-needed&quot;] }</pre><h3>💀 The Scariest Error: unresolved import &#39;crate&#39; (The Ghost Error)</h3><ul><li><strong>The Situation:</strong> The compiler threw a vague unresolved import &#39;crate&#39; pointing at the #[program] macro. It didn&#39;t tell me where the real problem was.</li><li><strong>The Root Cause:</strong> I created a new file state.rs to hold my TokenConfig struct. However, I <strong>forgot to declare it</strong> in lib.rs.</li><li><strong>Why it was scary:</strong> When the #[program] macro runs, it scans your account structs. It looked for crate::state::TokenConfig, but state wasn&#39;t a valid module yet. The macro failed internally, and Rust panicked by giving me this cryptic unresolved import error instead of pointing to the missing file.</li><li><strong>The Fix:</strong> I added pub mod state; to the top of lib.rs. <em>Lesson: Always check your module declarations first. Rust macros are brittle; a missing file breaks the entire expansion.</em></li></ul><h3>Error 5: Custom Errors not found (Scope Issues)</h3><ul><li><strong>The Problem:</strong> I used require!(amount &gt; 0, CustomError::ZeroAmountNotAllowed); in transfer.rs, but forgot to define the CustomError enum at the bottom of that file.</li><li><strong>The Fix:</strong> Copied the #[error_code] enum into the file. <em>Lesson: In Rust,</em> use <em>statements and enum definitions don&#39;t automatically cross file boundaries just because you are in the same project. Scope matters!</em></li></ul><h3>Phase 3: Thinking Like a Hacker (The Security Audit)</h3><p>After fixing the compiler, I put on my “Attacker” hat. I realized my initial code was like a house with the front door unlocked.</p><h3>Vulnerability 1: The Griefing Attack</h3><ul><li><strong>Attack:</strong> Attacker creates the recipient’s ATA before the mint occurs.</li><li><strong>Consequence:</strong> Honest users waste transaction fees because the init fails.</li><li><strong>Mitigation:</strong> Replaced init with init_if_needed in both mint.rs and transfer.rs. If the account exists, we just use it.</li></ul><h3>Vulnerability 2: The Arithmetic Bomb</h3><ul><li><strong>Attack:</strong> Attacker calls mint_token with amount = u64::MAX.</li><li><strong>Consequence:</strong> The calculation amount * 10^decimals overflows and panics instantly, killing the transaction.</li><li><strong>Mitigation:</strong> Replaced direct multiplication (*) with checked_mul and checked_add. The transaction now safely returns a custom error instead of panicking.</li></ul><h3>Vulnerability 3: The Hot Wallet Ransom</h3><ul><li><strong>Attack:</strong> The payer&#39;s private key is exposed.</li><li><strong>Consequence:</strong> Infinite tokens printed.</li><li><strong>Mitigation:</strong> I introduced a <strong>Program Derived Address (PDA)</strong> as the mint authority. The private key to this authority doesn’t exist. The program signs the mint transaction via CpiContext::new_with_signer, using the PDA&#39;s seeds. Even if the deployer&#39;s laptop is hacked, no one can mint without the program logic verifying the max_supply.</li></ul><h3>Phase 4: The “Industrial-Grade” Features</h3><p>I added features that real protocols use for compliance and operations:</p><ol><li><strong>Supply Cap (</strong>TokenConfig<strong>)</strong>: I created a state.rs file with a TokenConfig account. It tracks total_minted and max_supply, enforcing a hard cap.</li><li><strong>Input Validation</strong>: I restricted token_name to 32 chars and token_uri to 200 chars to prevent griefing via &quot;Metadata Bombs.&quot;</li><li><strong>Mutable Metadata</strong>: I changed the Metaplex is_mutable flag to true. If I typo an IPFS link, I can fix it later without redeploying a new token.</li><li><strong>On-Chain Events</strong>: I added #[event] structs. Off-chain indexers (like Helius) can now parse these events to build dashboards easily.</li></ol><h3>Phase 5: The Git and GitHub Workflow (The Real World)</h3><p>Writing the code was only 50% of the battle. The other 50% was navigating standard open-source DevOps.</p><h3>📧 The “Green Square” Mystery (Email Mismatch)</h3><p>When I pushed my code, my GitHub contribution graph didn’t turn green.</p><ul><li><strong>The Investigation:</strong> I ran git show and saw the author was sony &lt;other user name&gt;.</li><li><strong>The Reason:</strong> GitHub uses the <strong>commit author’s email address</strong> to map contributions to your profile, not your username. If the email doesn’t match your verified GitHub email, the code shows up on the repo, but you get zero green squares.</li><li><strong>The Fix:</strong> I updated my global Git config:</li></ul><pre>git config --global user.email &quot;my-real-email@github.com&quot; <br>git commit --amend --reset-author  # Fix the previous commit <br>git push --force-with-lease        # Update the PR</pre><h3>🔒 The “Permission Denied” Wall (Fork Authentication)</h3><p>I forked the repo to contribute to it. But when I tried git push, I got ! [remote rejected] fix/security-hardening-pr -&gt; fix/security-hardening-pr (permission denied).</p><ul><li><strong>The Reason:</strong> I was logged into VS Code as my main account (shriyasingh03), but I was trying to push to my <strong>dummy account&#39;s fork</strong> (shriyacontributor). GitHub refused because shriyasingh03 doesn&#39;t have write access to shriyacontributor&#39;s fork.</li><li><strong>The Fix (The Professional Way):</strong> I generated a <strong>Personal Access Token (PAT)</strong> for the dummy account. I pushed using:</li></ul><pre>git push <br>https://shriyacontributor:ghp_XXXXX@github.com/shriyacontributor/repo.git fix/security-hardening-pr</pre><ul><li>This bypassed the credential manager and authenticated me specifically as the fork owner.</li></ul><h3>Phase 6: The Pull Request Flow (The Final Act)</h3><p>With the technical and authentication hurdles cleared, I successfully executed the full open-source cycle:</p><ol><li><strong>Forked</strong> the original repo to my dummy account.</li><li><strong>Branched</strong> off main into fix/security-hardening-pr.</li><li><strong>Committed</strong> with a conventional commit message (fix: Hardened security...).</li><li><strong>Pushed</strong> to my fork using the PAT.</li><li><strong>Opened a Pull Request</strong> against the original main branch.</li><li><strong>Merged</strong> it successfully as the maintainer.</li></ol><h3>Phase 7: The Code Transformation — Before &amp; After (A File-by-File Breakdown)</h3><p>The most rewarding part of this journey was watching the code evolve from a naive, vulnerable script into a hardened, production-grade program.</p><p>Here is a <strong>file-by-file comparison</strong> of what changed, what was added, and exactly <em>why</em> I made each change.</p><h3>1. Cargo.toml (Dependencies)</h3><p><strong>❌ BEFORE (The Broke State):</strong></p><pre>[dependencies]<br>anchor-lang = &quot;0.30.1&quot;<br>anchor-spl = &quot;0.30.1&quot;</pre><p><strong>✅ AFTER (The Fixed State):</strong></p><pre>[dependencies]<br>anchor-lang = { version = &quot;0.30.1&quot;, features = [&quot;init-if-needed&quot;] }<br>anchor-spl = { version = &quot;0.30.1&quot;, features = [&quot;metadata&quot;] }</pre><p><strong>Why the change?</strong> Rust uses “feature flags” to speed up compilation. I was using init_if_needed (which is an advanced Anchor feature) and anchor_spl::metadata (Metaplex). The compiler flat-out refused to recognize them until I explicitly turned these features on in Cargo.toml. Without this, my code wouldn&#39;t even parse.</p><h3>2. state.rs (BRAND NEW FILE)</h3><p><strong>❌ BEFORE:</strong> This file did not exist. <strong>✅ AFTER:</strong> I added programs/transfer_token/src/state.rs:</p><pre>use anchor_lang::prelude::*;</pre><pre>#[account]<br>pub struct TokenConfig {<br>    pub mint: Pubkey,          // Which token this belongs to<br>    pub max_supply: u64,       // Hard cap (e.g., 1 billion)<br>    pub total_minted: u64,     // Tracks how many have been minted<br>    pub authority_bump: u8,    // Stores the PDA bump for signing<br>}</pre><p><strong>Why the change?</strong> In the original version, I had no way to enforce a supply cap. An attacker could mint forever if they compromised the authority. This new TokenConfig account is a separate on-chain data structure that lives in a deterministic PDA. It acts as the &quot;brain&quot; of the token, tracking the cap and the current minted amount.</p><h3>3. mod.rs (Module Exports)</h3><p><strong>❌ BEFORE (The Wildcard Trap):</strong></p><pre>pub mod create;<br>pub mod mint;<br>pub mod transfer;</pre><pre>pub use create::*;<br>pub use mint::*;<br>pub use transfer::*;</pre><p><strong>✅ AFTER (The Explicit Fix):</strong></p><pre>pub mod create;<br>pub mod mint;<br>pub mod transfer;</pre><pre>pub use create::create_token;<br>pub use mint::mint_token;<br>pub use transfer::transfer_tokens;</pre><p><strong>Why the change?</strong> In Rust, pub use * exposes <strong>everything</strong>, including the CustomError enums. Since create.rs, mint.rs, and transfer.rs all had their own CustomError enum, the compiler threw a scary ambiguous_glob_reexports warning. By explicitly exporting just the instruction functions, I cleaned up the namespace and made the imports predictable.</p><h3>4. lib.rs (The Main Program)</h3><p><strong>❌ BEFORE:</strong></p><pre>use anchor_lang::prelude::*;<br>pub mod instructions;<br>use instructions::*;<br>// ... program logic ...</pre><p><strong>✅ AFTER:</strong></p><pre>use anchor_lang::prelude::*;<br>pub mod instructions;<br>pub mod state;   // &lt;-- Declared the new module!<br>use instructions::*;</pre><pre>// Added On-Chain Events<br>#[event]<br>pub struct MintEvent { ... }<br>#[event]<br>pub struct TransferEvent { ... }</pre><p><strong>Why the change?</strong> I added pub mod state; to tell Rust to compile the new state.rs file. Without this, the compiler gave me that terrifying unresolved import &#39;crate&#39; error. I also added #[event] structs. In Solana, msg! logs are hard for indexers to parse. Events are structured, cheap, and allow off-chain services to easily track mint/transfer activity.</p><h3>5. create.rs (Token Creation)</h3><p><strong>❌ BEFORE (Vulnerable):</strong></p><pre>mint::decimals = 9,<br>mint::authority = payer.key(), // Payday for hackers!<br>// ... <br>// Metadata was set to `false` (Immutable)<br>create_metadata_accounts_v3(..., false, true, None);</pre><p><strong>✅ AFTER (Industrial):</strong></p><pre>// Authority is now a PDA!<br>mint::authority = authority_pda.key(),<br>// Strict input validation to prevent memory bombs<br>require!(token_name.len() &lt;= 32, CustomError::NameTooLong);<br>require!(token_uri.len() &lt;= 200, CustomError::UriTooLong);<br>// Initialize the TokenConfig account<br>#[account(init, seeds = [b&quot;config&quot;, mint_account.key().as_ref()], ...)]<br>pub token_config: Account&lt;&#39;info, TokenConfig&gt;;<br>// Metadata is mutable so we can fix typos later!<br>create_metadata_accounts_v3(..., true, true, None);</pre><p><strong>Why the change?</strong> The original code gave the mint authority to a human wallet (payer). The new code uses a <strong>PDA (Program Derived Address)</strong>. A PDA is an address controlled by the program, not a private key. This means even if my laptop is hacked, the hacker cannot mint tokens because they don&#39;t have the private key—only the program logic can authorize the mint. I also set is_mutable to true. If I accidentally paste a broken IPFS link, I can update it later without redeploying a new token.</p><h3>6. mint.rs (Minting Tokens)</h3><p><strong>❌ BEFORE (Grief-able &amp; Unsafe):</strong></p><pre>#[account(init, ...)] // Front-running vulnerability!<br>pub associated_token_account: Account&lt;&#39;info, TokenAccount&gt;;</pre><pre>mint_to(..., amount * 10u64.pow(decimals)); // Panic risk!</pre><p><strong>✅ AFTER (Hardened):</strong></p><pre>#[account(init_if_needed, ...)] // Safe: uses it if it exists!<br>pub associated_token_account: Account&lt;&#39;info, TokenAccount&gt;;</pre><pre>// Enforce Supply Cap<br>let new_supply = config.total_minted.checked_add(amount).unwrap();<br>require!(new_supply &lt;= config.max_supply, ...);</pre><pre>// PDA signs the transaction<br>let seeds = &amp;[b&quot;authority&quot;, mint.key.as_ref(), &amp;[bump]];<br>mint_to(CpiContext::new_with_signer(..., signer_seeds), <br>        amount.checked_mul(10u64.pow(decimals)).unwrap() // Safe math!<br>);</pre><p><strong>Why the change?</strong> Two major upgrades:</p><ol><li>init_if_needed prevents attackers from front-running my transaction and creating the ATA first to make my mint fail.</li><li>checked_mul<strong> and </strong>checked_add are safe math operations. In the original, passing u64::MAX as the amount would cause the math to overflow and panic, killing the transaction. checked_mul returns None on overflow, allowing me to handle it gracefully with a custom error.</li></ol><h3>7. transfer.rs (Transferring Tokens)</h3><p><strong>❌ BEFORE:</strong></p><pre>#[account(init, ...)] // Attacker can brick the transfer!<br>pub recipient_token_account: Account&lt;&#39;info, TokenAccount&gt;;</pre><pre>transfer(..., amount * 10u64.pow(decimals)); // Unsafe math</pre><p><strong>✅ AFTER:</strong></p><pre>#[account(init_if_needed, ...)] // Safe!<br>pub recipient_token_account: Account&lt;&#39;info, TokenAccount&gt;;</pre><pre>// Prevent zero-amount spam<br>require!(amount &gt; 0, CustomError::ZeroAmountNotAllowed);</pre><pre>// Safe math and structured event<br>transfer(..., amount.checked_mul(...).unwrap());<br>emit!(TransferEvent { ... });</pre><p><strong>Why the change?</strong> Just like in mint.rs, init_if_needed stops the front-running griefing attack. I also added an explicit amount &gt; 0 check. Spamming zero-amount transfers wastes compute units and network fees. The event emission ensures that I have an immutable, indexable record of every transfer for regulatory/audit purposes.</p><h3>📊 Summary of the Transformation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*B_Uey3Ogm2BtWf2hRRQ7TA.png" /></figure><h3>The Final Code Structure</h3><p>Here is what my final programs/transfer_token/src/ folder looks like:</p><pre>├── lib.rs          (Program entry, event definitions)<br>├── state.rs        (TokenConfig struct)<br>└── instructions/<br>    ├── mod.rs      (Module exports)<br>    ├── create.rs   (PDA authority, supply cap init)<br>    ├── mint.rs     (Max supply check, PDA signing, event emit)<br>    └── transfer.rs (Zero-amount check, init_if_needed)</pre><h3>Key Takeaways for New Solana Developers</h3><ol><li><strong>Never trust the</strong> payer <strong>as the authority.</strong> Use PDAs for critical permissions. Always ask: <em>&quot;If this private key leaks, can my protocol survive?&quot;</em></li><li><strong>Always use</strong> checked_mul <strong>or</strong> checked_add <strong>when doing integer math.</strong> Rust panics kill transactions. Defensive programming saves millions.</li><li>init_if_needed <strong>is your friend.</strong> It prevents front-running griefing. But remember to enable the feature flag in Cargo.toml for anchor-lang.</li><li><strong>Compiler errors are often dominoes.</strong> A missing pub mod state; can manifest as a vague unresolved import &#39;crate&#39;. Always check your module imports first when the macro fails.</li><li><strong>In Git, your email is your identity.</strong> Ensure git config user.email matches your GitHub primary email <em>before</em> you commit, or your green squares will vanish.</li><li><strong>Fork authentication is strict.</strong> If you own multiple accounts, use a Personal Access Token (PAT) to push to your fork. The local VS Code session won’t always cut it.</li></ol><h3>Conclusion</h3><p>Building this token taught me that smart contract development is <strong>Defense in Depth</strong>. You aren’t just writing business logic; you are writing code that holds financial value and operates in a hostile environment where <em>everyone</em> is looking for a mistake.</p><p>From fighting the Anchor compiler (and the ghost unresolved import macro) to managing Git emails and PATs, I now feel confident in building secure, auditable, and production-ready Solana programs.</p><p>If you are reading this and building your first dApp, don’t stop when it compiles. Ask yourself: <em>“How would I break this?”</em> Because if you can break it, so can someone else. And remember: the green squares on GitHub are nice, but the security of the code is what truly matters.</p><p>Happy Coding! 🚀</p><p>Github Code : <a href="https://github.com/shriyasingh03/solana-anchor-smart-contract-examples/tree/main/transfer_token">https://github.com/shriyasingh03/solana-anchor-smart-contract-examples/tree/main/transfer_token</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1113db00d5d1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Favourites Smart Contract-Anchor]]></title>
            <link>https://medium.com/@2001shriya/favourites-smart-contract-anchor-cb01030f253e?source=rss-be3ee38604d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb01030f253e</guid>
            <category><![CDATA[anchor-smart-contract]]></category>
            <category><![CDATA[solanas]]></category>
            <category><![CDATA[examplesmartcontracts]]></category>
            <category><![CDATA[rust]]></category>
            <dc:creator><![CDATA[Shriya]]></dc:creator>
            <pubDate>Wed, 01 Jul 2026 11:07:59 GMT</pubDate>
            <atom:updated>2026-07-01T11:07:59.762Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dz7jxhsvgSt2CTYRoWbk5A.png" /></figure><p><strong>From basic to more secure version</strong></p><h3>📚 Introduction</h3><p>Hey there! In this blog, I’ll walk you through three versions of an Anchor program that lets users store their favorite number, color, and hobbies on the Solana blockchain. We’ll start with a basic implementation, add a cleaner code style, and finally build a <strong>production‑grade, hardened version</strong> with enterprise‑level security.</p><p>By the end of this tutorial, you’ll understand:</p><ul><li>How to manage per‑user state with PDAs (Program Derived Addresses)</li><li>Why set_inner() makes your code cleaner and safer</li><li>How to protect against common attacks</li><li>What it takes to write a Solana program that passes a security audit</li></ul><p>Let’s dive in! 🚀</p><h3>🏗️ Version 1: The Initial Program (The “Get It Working” Version)</h3><p>This is the simplest possible version. It uses init_if_needed to either create or update a user&#39;s favorites in a single instruction. I like to think of this as the &quot;MVP&quot; (Minimum Viable Product) version – it gets the job done, but it&#39;s not production-ready.</p><pre>use anchor_lang::prelude::*;</pre><pre>declare_id!(&quot;ENuWjmte9BG9YFG5TE2xcZBkhEme6GesosJTMH9ZG5Ls&quot;);</pre><pre>pub const ANCHOR_DISCRIMINATOR_SIZE: usize = 8;</pre><pre>#[program]<br>pub mod favorites {<br>    use super::*;</pre><pre>    pub fn set_favorites(<br>        context: Context&lt;SetFavorites&gt;,<br>        number: u64,<br>        color: String,<br>        hobbies: Vec&lt;String&gt;,<br>    ) -&gt; Result&lt;()&gt; {<br>        msg!(&quot;Greetings from {}&quot;, context.program_id);<br>        let user_public_key = context.accounts.user.key();<br>        msg!(<br>            &quot;User {user_public_key}&#39;s favorite number is {number}, favorite color is: {color}, and their hobbies are {hobbies:?}&quot;,<br>        );</pre><pre>        // Manual assignment (no set_inner)<br>        let favorites = &amp;mut context.accounts.favorites;<br>        favorites.number = number;<br>        favorites.color = color;<br>        favorites.hobbies = hobbies;</pre><pre>        Ok(())<br>    }<br>}</pre><pre>#[account]<br>#[derive(InitSpace)]<br>pub struct Favorites {<br>    pub number: u64,<br>    #[max_len(50)]<br>    pub color: String,<br>    #[max_len(5, 50)]<br>    pub hobbies: Vec&lt;String&gt;,<br>}</pre><pre>#[derive(Accounts)]<br>pub struct SetFavorites&lt;&#39;info&gt; {<br>    #[account(mut)]<br>    pub user: Signer&lt;&#39;info&gt;,</pre><pre>    #[account(<br>        init_if_needed,<br>        payer = user,<br>        space = ANCHOR_DISCRIMINATOR_SIZE + Favorites::INIT_SPACE,<br>        seeds = [b&quot;favorites&quot;, user.key().as_ref()],<br>        bump<br>    )]<br>    pub favorites: Account&lt;&#39;info, Favorites&gt;,</pre><pre>    pub system_program: Program&lt;&#39;info, System&gt;,<br>}</pre><h3>🔍 What’s Happening Here?</h3><p>Let me break down each component:</p><p>Component</p><p>What it does</p><p>declare_id! : Sets the program’s address on-chain — this must match your deployed program ID.</p><p>#[program] : Defines the instruction handlers (the functions users can call).</p><p>set_favorites : Takes a number, color, and hobbies vector from the user.</p><p>Favorites : The data structure stored on-chain for each user</p><p>SetFavorites : Defines which accounts are required for the transaction.</p><p>init_if_needed : Creates the PDA if it doesn’t exist, or updates it if it does.</p><p><strong>Manual assignment</strong></p><p>Directly assigns each field (favorites.number = number;)</p><h3>💭 My Thoughts on This Version</h3><p>This code works, and that’s great for learning! But when I look at it from a security perspective, I see several issues:</p><ol><li><strong>No ownership tracking</strong> — We don’t explicitly store who owns the account. We rely solely on the PDA seeds, but it’s better to be explicit.</li><li>init_if_needed <strong>can be risky</strong> – If a frontend bug passes the wrong PDA, it might accidentally create a new account instead of updating the intended one. This wastes the user&#39;s SOL on rent.</li><li><strong>No input validation</strong> — Users could store empty strings or gibberish data. This breaks the “garbage in, garbage out” problem.</li><li><strong>No</strong> close <strong>function</strong> – Once a user creates their favorites, their SOL is permanently locked in the rent. They can never get it back.</li></ol><p>So while Version 1 is great for learning and prototyping, I wouldn’t deploy this to mainnet with real money involved.</p><h3>✨ Version 2: Using set_inner() for Cleaner Code</h3><p>This version keeps the same functionality but uses set_inner() to make the code shorter and more robust. This is where we start thinking about code quality.</p><pre>use anchor_lang::prelude::*;</pre><pre>declare_id!(&quot;ENuWjmte9BG9YFG5TE2xcZBkhEme6GesosJTMH9ZG5Ls&quot;);</pre><pre>pub const ANCHOR_DISCRIMINATOR_SIZE: usize = 8;</pre><pre>#[program]<br>pub mod favorites_using_set_inner {<br>    use super::*;</pre><pre>    pub fn set_favorite(<br>        ctx: Context&lt;SetFavorites&gt;,<br>        number: u64,<br>        color: String,<br>        hobbies: Vec&lt;String&gt;,<br>    ) -&gt; Result&lt;()&gt; {<br>        msg!(&quot;Greeting from {}&quot;, ctx.program_id);<br>        let user_public_key = ctx.accounts.user.key();<br>        msg!(<br>            &quot;User {user_public_key}&#39;s favorite number is {number}, favorite color is: {color}, and their hobbies are {hobbies:?}&quot;,<br>        );</pre><pre>        // Use set_inner() – cleaner and safer!<br>        ctx.accounts.favorites.set_inner(Favorites {<br>            number,<br>            color,<br>            hobbies,<br>        });<br>        Ok(())<br>    }<br>}</pre><pre>#[account]<br>#[derive(InitSpace)]<br>pub struct Favorites {<br>    pub number: u64,<br>    #[max_len(50)]<br>    pub color: String,<br>    #[max_len(5, 50)]<br>    pub hobbies: Vec&lt;String&gt;,<br>}</pre><pre>#[derive(Accounts)]<br>pub struct SetFavorites&lt;&#39;info&gt; {<br>    #[account(mut)]<br>    pub user: Signer&lt;&#39;info&gt;,</pre><pre>    #[account(<br>        init_if_needed,<br>        payer = user,<br>        space = ANCHOR_DISCRIMINATOR_SIZE + Favorites::INIT_SPACE,<br>        seeds = [b&quot;favorites&quot;, user.key().as_ref()],<br>        bump<br>    )]<br>    pub favorites: Account&lt;&#39;info, Favorites&gt;,</pre><pre>    pub system_program: Program&lt;&#39;info, System&gt;,<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/911/1*px9tPKvbywML6RRbbeR9hg.png" /></figure><h3>🧠 Why set_inner() is Better</h3><p>Let me explain what set_inner() actually does behind the scenes:</p><ul><li><strong>Atomic</strong> — writes all fields at once. No partial writes that could corrupt your data.</li><li><strong>Safe</strong> — forces you to provide a complete struct. If you add a new field later, the compiler will remind you to set it.</li><li><strong>Readable</strong> — one line instead of three. Less code = fewer bugs.</li><li><strong>Maintainable</strong> — when you add a new field, you update it in one place (the struct definition) and the compiler catches any places where you forgot to set it.</li></ul><h3>🤔 What Does set_inner() Actually Do?</h3><p>When you call set_inner(), Anchor does this:</p><ol><li><strong>Serializes</strong> your Favorites struct into a byte array using Borsh (the binary serialization format Solana uses).</li><li><strong>Writes</strong> that byte array into the account’s data buffer — <strong>starting at offset 8</strong>.</li><li><strong>Leaves the first 8 bytes untouched</strong> — those are the Anchor <strong>discriminator</strong>, which uniquely identifies the account type.</li></ol><p>This means the account remains identifiable as a Favorites account, and the entire data payload is replaced atomically.</p><p><strong>When NOT to use</strong> set_inner()<strong>:</strong></p><ul><li>If you only want to increment a counter (e.g., favorites.number += 1), manual assignment is more efficient.</li><li>If your struct has very large fields and you’re only changing a tiny one — but in practice, the performance difference is negligible.</li></ul><h3>🔐 Version 3: The Hardened, Production‑Ready Program</h3><p>This is the <strong>Fort Knox</strong> version — it’s what I’d deploy to mainnet with millions of dollars at stake. I’ve added multiple layers of security and user-friendliness.</p><pre>use anchor_lang::prelude::*;</pre><pre>declare_id!(&quot;ENuWjmte9BG9YFG5TE2xcZBkhEme6GesosJTMH9ZG5Ls&quot;);</pre><pre>pub const ANCHOR_DISCRIMINATOR_SIZE: usize = 8;<br></pre><pre>// ============================================================<br>// 1. PROGRAM LOGIC (Instructions)<br>// ============================================================</pre><pre>#[program]<br>pub mod favorites {<br>    use super::*;</pre><pre>    // --- CREATE: First-time setup ---<br>    pub fn initialize(<br>        ctx: Context&lt;Initialize&gt;,<br>        number: u64,<br>        color: String,<br>        hobbies: Vec&lt;String&gt;,<br>    ) -&gt; Result&lt;()&gt; {<br>        // ✅ Input validation – reject empty or garbage data<br>        require!(!color.is_empty(), FavoritesError::EmptyColor);<br>        require!(!hobbies.is_empty(), FavoritesError::NoHobbies);<br>        for hobby in &amp;hobbies {<br>            require!(!hobby.is_empty(), FavoritesError::EmptyHobby);<br>        }</pre><pre>        // Get the user&#39;s public key<br>        let user_key = ctx.accounts.user.key();<br>        let bump = ctx.bumps.favorites; // Anchor gives us the bump</pre><pre>        // Write everything in one atomic operation using set_inner()<br>        ctx.accounts.favorites.set_inner(Favorites {<br>            owner: user_key,<br>            bump,               // Store the bump for future updates<br>            number,<br>            color,<br>            hobbies,<br>        });</pre><pre>        msg!(&quot;✅ Favorites initialized for user: {}&quot;, user_key);</pre><pre>        Ok(())<br>    }</pre><pre>    // --- UPDATE: Modify existing data ---<br>    pub fn update(<br>        ctx: Context&lt;Update&gt;,<br>        number: u64,<br>        color: String,<br>        hobbies: Vec&lt;String&gt;,<br>    ) -&gt; Result&lt;()&gt; {<br>        // ✅ Input validation – same checks<br>        require!(!color.is_empty(), FavoritesError::EmptyColor);<br>        require!(!hobbies.is_empty(), FavoritesError::NoHobbies);<br>        for hobby in &amp;hobbies {<br>            require!(!hobby.is_empty(), FavoritesError::EmptyHobby);<br>        }</pre><pre>        // Get the existing account to preserve owner and bump<br>        let existing = &amp;ctx.accounts.favorites;<br>        let owner = existing.owner;<br>        let bump = existing.bump;</pre><pre>        // Replace the entire content using set_inner()<br>        ctx.accounts.favorites.set_inner(Favorites {<br>            owner,              // Keep the original owner<br>            bump,               // Keep the stored bump<br>            number,<br>            color,<br>            hobbies,<br>        });</pre><pre>        msg!(&quot;✅ Favorites updated for user: {}&quot;, ctx.accounts.user.key());</pre><pre>        Ok(())<br>    }</pre><pre>    // --- CLOSE: Delete the account and refund rent ---<br>    pub fn close(ctx: Context&lt;Close&gt;) -&gt; Result&lt;()&gt; {<br>        msg!(&quot;✅ Favorites account closed for user: {}&quot;, ctx.accounts.user.key());<br>        Ok(())<br>    }<br>}</pre><pre>// ============================================================<br>// 2. CUSTOM ERRORS<br>// ============================================================</pre><pre>#[error_code]<br>pub enum FavoritesError {<br>    #[msg(&quot;Color cannot be empty&quot;)]<br>    EmptyColor,<br>    #[msg(&quot;You must have at least one hobby&quot;)]<br>    NoHobbies,<br>    #[msg(&quot;Hobby cannot be an empty string&quot;)]<br>    EmptyHobby,<br>}<br></pre><pre>// ============================================================<br>// 3. CONTEXT STRUCTS (Account Validation)<br>// ============================================================</pre><pre>// Context for CREATING a new Favorites account<br>#[derive(Accounts)]<br>pub struct Initialize&lt;&#39;info&gt; {<br>    #[account(mut)]<br>    pub user: Signer&lt;&#39;info&gt;,</pre><pre>    #[account(<br>        init,                 // Only creates – fails if account already exists<br>        payer = user,<br>        space = ANCHOR_DISCRIMINATOR_SIZE + Favorites::INIT_SPACE,<br>        seeds = [b&quot;favorites&quot;, user.key().as_ref()],<br>        bump<br>    )]<br>    pub favorites: Account&lt;&#39;info, Favorites&gt;,</pre><pre>    pub system_program: Program&lt;&#39;info, System&gt;,<br>}</pre><pre>// Context for UPDATING an existing Favorites account<br>#[derive(Accounts)]<br>pub struct Update&lt;&#39;info&gt; {<br>    #[account(mut)]<br>    pub user: Signer&lt;&#39;info&gt;,</pre><pre>    #[account(<br>        mut,<br>        seeds = [b&quot;favorites&quot;, user.key().as_ref()],<br>        bump = favorites.bump,   // Use the stored bump<br>        has_one = user           // 🔒 Double-check: favorites.owner == user.key()<br>    )]<br>    pub favorites: Account&lt;&#39;info, Favorites&gt;,<br>}</pre><pre>// Context for CLOSING (deleting) a Favorites account and refunding rent<br>#[derive(Accounts)]<br>pub struct Close&lt;&#39;info&gt; {<br>    #[account(mut)]<br>    pub user: Signer&lt;&#39;info&gt;,</pre><pre>    #[account(<br>        mut,<br>        seeds = [b&quot;favorites&quot;, user.key().as_ref()],<br>        bump = favorites.bump,<br>        has_one = user,<br>        close = user            // 🔥 Refunds all lamports to &#39;user&#39; and deletes the account<br>    )]<br>    pub favorites: Account&lt;&#39;info, Favorites&gt;,<br>}</pre><pre>// ============================================================<br>// 4. ACCOUNT STRUCT (On-chain Data)<br>// ============================================================</pre><pre>#[account]<br>#[derive(InitSpace)]<br>pub struct Favorites {<br>    pub owner: Pubkey,        // Explicitly track the owner<br>    pub bump: u8,             // Store the PDA bump for efficient re-derivation<br>    pub number: u64,</pre><pre>    #[max_len(50)]<br>    pub color: String,</pre><pre>    #[max_len(5, 50)]<br>    pub hobbies: Vec&lt;String&gt;,<br>}</pre><h3>🛡️ What Makes This Version Secure?</h3><p>Let me walk you through each security feature:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*_IVy1AlMwepAbafpBX7Akw.png" /></figure><h3>🔍 Deep Dive: The has_one Constraint</h3><p>This is one of my favorite Anchor features. When you add has_one = user to an account constraint, Anchor automatically:</p><ol><li>Reads the owner field from the account.</li><li>Compares it to the user.key() that signed the transaction.</li><li>If they don’t match, the transaction fails BEFORE your instruction even runs.</li></ol><p>This is called <strong>defense‑in‑depth</strong> — even if the PDA derivation were somehow bypassed, the has_one check would still prevent unauthorized access.</p><h3>💰 The close Constraint</h3><p>The close = user constraint is brilliant for user experience. When a user closes their account:</p><ol><li>The account is deleted from the blockchain.</li><li>All SOL (lamports) in that account are transferred to the user.</li><li>The user gets their rent deposit back.</li></ol><p>This is a huge quality-of-life improvement — users aren’t permanently locking their SOL forever.</p><h3>📝 Input Validation</h3><p>In Version 1 and 2, a user could store:</p><ul><li>color = &quot;&quot; (empty string)</li><li>hobbies = [] (no hobbies)</li></ul><p>This might seem harmless, but it creates “garbage state” on-chain. If your frontend expects a non-empty color, it might crash (DoS by invalid state). By validating inputs, we prevent these edge cases.</p><h3>📊 Comparison Table</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/1*je--dS3anZVm4ChjBAik5Q.png" /></figure><h3>🧪 How to Use Version 3 (Client Side)</h3><p>Here’s how to interact with the hardened version from TypeScript:</p><pre>import * as anchor from &quot;@coral-xyz/anchor&quot;;<br>import { Program } from &quot;@coral-xyz/anchor&quot;;</pre><pre>// 1. Initialize (first time user)<br>await program.methods<br>  .initialize(new anchor.BN(42), &quot;blue&quot;, [&quot;gaming&quot;, &quot;reading&quot;])<br>  .accounts({<br>    user: wallet.publicKey,<br>    favorites: favoritesPda,<br>    systemProgram: anchor.web3.SystemProgram.programId,<br>  })<br>  .rpc();</pre><pre>// 2. Update (later)<br>await program.methods<br>  .update(new anchor.BN(7), &quot;green&quot;, [&quot;coding&quot;, &quot;hiking&quot;])<br>  .accounts({<br>    user: wallet.publicKey,<br>    favorites: favoritesPda,<br>  })<br>  .rpc();</pre><pre>// 3. Close (delete and get rent back)<br>await program.methods<br>  .close()<br>  .accounts({<br>    user: wallet.publicKey,<br>    favorites: favoritesPda,<br>  })<br>  .rpc();</pre><h3>🔍 Deriving the PDA in the Client</h3><p>You also need to derive the PDA address in your client:</p><pre>const [favoritesPda, bump] = await anchor.web3.PublicKey.findProgramAddress(<br>  [Buffer.from(&quot;favorites&quot;), wallet.publicKey.toBuffer()],<br>  program.programId<br>);</pre><p>This must match the derivation in the Rust program exactly:</p><ul><li>Seed 1: b&quot;favorites&quot;</li><li>Seed 2: user.key().as_ref()</li><li>Program ID: The program’s address</li></ul><h3>🎯 Key Takeaways</h3><h3>1. Use set_inner() whenever you&#39;re updating all fields</h3><p>It’s cleaner, safer, and prevents partial writes. When you add a new field, the compiler will catch any place where you forgot to initialize it.</p><h3>2. Store the owner explicitly and use has_one</h3><p>Defense‑in‑depth is your friend. Don’t rely solely on PDA derivation — explicit ownership checks add a second layer of security.</p><h3>3. Split initialize and update</h3><p>init_if_needed is convenient but risky. Explicit instructions are clearer and safer. They also force the client to know what state the account is in, preventing accidental rent burns.</p><h3>4. Always validate input</h3><p>Users can send anything. Reject empty strings, out‑of‑range values, and invalid data. This prevents “garbage state” on-chain.</p><h3>5. Provide a close instruction</h3><p>Users should be able to reclaim their SOL. It’s good UX and shows you care about your users’ funds.</p><h3>6. Store the bump</h3><p>It makes re‑derivation more efficient and eliminates edge‑case errors where the bump might be computed differently.</p><h3>7. Use custom errors</h3><p>Anchor’s require!() with custom errors makes debugging easier for everyone. Your users will thank you when they get clear error messages.</p><h3>8. Log important events</h3><p>Use msg!() to log key events like initialization, updates, and closings. This makes debugging transactions much easier.</p><h3>💡 Pro Tips for Production</h3><h3>1. Use a separate type for color</h3><p>Instead of a plain String, consider using an enum for colors. This prevents typos like &quot;blu&quot; instead of &quot;blue&quot;:</p><pre>#[derive(AnchorSerialize, AnchorDeserialize, Clone, Copy, PartialEq)]<br>pub enum Color {<br>    Red,<br>    Blue,<br>    Green,<br>    Purple,<br>}</pre><h3>2. Limit hobby length</h3><p>While we already limit to 5 hobbies of 50 characters each, consider whether 50 characters is appropriate. For social media, 50 chars is fine; for descriptions, you might want more.</p><h3>3. Add a “last updated” timestamp</h3><p>This can help with UI/UX showing when the user last updated their favorites:</p><pre>pub struct Favorites {<br>    // ... existing fields<br>    pub last_updated: i64,  // Unix timestamp<br>}</pre><h3>4. Consider rent exemptions</h3><p>Solana accounts need to be rent‑exempt. Our space calculation ensures the account has enough SOL to be rent‑exempt, but you might want to verify this in the client.</p><h3>5. Test thoroughly</h3><p>Use Anchor’s anchor test to run your TypeScript tests. Test happy paths, error paths, and edge cases.</p><h3>🔧 Common Build Issues &amp; Solutions</h3><h3>Issue 1: crypto-common v0.2.2 requires edition2024</h3><p><strong>Solution</strong>: Use Rust 1.80+ or patch the dependency:</p><pre>[patch.crates-io]<br>crypto-common = { git = &quot;https://github.com/RustCrypto/traits&quot;, tag = &quot;crypto-common-v0.1.6&quot; }</pre><h3>Issue 2: Solana CLI version mismatch</h3><p><strong>Solution</strong>: Use AVM to manage Anchor versions and ensure Solana CLI is 2.3.0+:</p><pre>avm install 0.31.0<br>avm use 0.31.0<br>solana --version  # Should be 2.3.0+</pre><h3>Issue 3: init_if_needed requires a feature flag</h3><p><strong>Solution</strong>: In Cargo.toml:</p><pre>anchor-lang = { version = &quot;0.31.0&quot;, features = [&quot;init-if-needed&quot;] }</pre><h3>🚀 Final Thoughts</h3><p>Solana programming is about <strong>security first, features second</strong>. The three versions in this blog show a natural progression:</p><ol><li><strong>Get it working</strong> — Version 1 gets the job done.</li><li><strong>Make it clean</strong> — Version 2 uses modern Anchor patterns.</li><li><strong>Make it bulletproof</strong> — Version 3 is ready for production.</li></ol><p>Always aim for Version 3 in production. Your users (and your auditors) will thank you.</p><h3>📚 What I’ve Learned Writing This</h3><p>Writing this blog taught me several things:</p><ol><li><strong>Security is a journey, not a destination</strong> — Each version improved security, but there’s always more to add.</li><li><strong>Small changes matter</strong> — Using set_inner() instead of manual assignment is a small change with big benefits.</li><li><strong>User experience matters</strong> — The close instruction might not seem like a security feature, but it shows you care about your users.</li><li><strong>Validation is essential</strong> — Always validate input. Always.</li></ol><p><strong>Happy coding on Solana!</strong> 🎉</p><p>If you have any questions or want to see more Anchor tutorials, feel free to reach out. And don’t forget to check out the <a href="https://www.anchor-lang.com/">Anchor documentation</a> for more advanced topics!</p><h3>📝 Example: Complete Client Code</h3><p>Here’s a complete example of how to interact with the hardened program:</p><pre>import * as anchor from &quot;@coral-xyz/anchor&quot;;<br>import { Program } from &quot;@coral-xyz/anchor&quot;;<br>import { Favorites } from &quot;../target/types/favorites&quot;;</pre><pre>async function main() {<br>  // Setup<br>  const provider = anchor.AnchorProvider.env();<br>  anchor.setProvider(provider);<br>  const program = anchor.workspace.Favorites as Program&lt;Favorites&gt;;<br>  const user = provider.wallet;</pre><pre>  // Derive PDA<br>  const [favoritesPda, _bump] = await anchor.web3.PublicKey.findProgramAddress(<br>    [Buffer.from(&quot;favorites&quot;), user.publicKey.toBuffer()],<br>    program.programId<br>  );</pre><pre>  // Initialize<br>  await program.methods<br>    .initialize(new anchor.BN(42), &quot;blue&quot;, [&quot;gaming&quot;, &quot;reading&quot;])<br>    .accounts({<br>      user: user.publicKey,<br>      favorites: favoritesPda,<br>      systemProgram: anchor.web3.SystemProgram.programId,<br>    })<br>    .rpc();</pre><pre>  console.log(&quot;✅ Favorites initialized!&quot;);</pre><pre>  // Fetch and display<br>  const data = await program.account.favorites.fetch(favoritesPda);<br>  console.log(&quot;📊 Current favorites:&quot;, {<br>    owner: data.owner.toString(),<br>    number: data.number.toString(),<br>    color: data.color,<br>    hobbies: data.hobbies,<br>    bump: data.bump,<br>  });</pre><pre>  // Update<br>  await program.methods<br>    .update(new anchor.BN(7), &quot;green&quot;, [&quot;coding&quot;, &quot;hiking&quot;])<br>    .accounts({<br>      user: user.publicKey,<br>      favorites: favoritesPda,<br>    })<br>    .rpc();</pre><pre>  console.log(&quot;✅ Favorites updated!&quot;);</pre><pre>  // Close (optional)<br>  // await program.methods<br>  //   .close()<br>  //   .accounts({<br>  //     user: user.publicKey,<br>  //     favorites: favoritesPda,<br>  //   })<br>  //   .rpc();<br>  // console.log(&quot;✅ Favorites closed and rent refunded!&quot;);<br>}</pre><p>That’s it! I hope this blog helped you understand Anchor programming better. Let me know if you have any questions! 🚀</p><p>github code 🔗 <a href="https://github.com/shriyasingh03/solana-anchor-smart-contract-examples/blob/main/favorites/programs/favorites/src/lib_more_secre_version.rs">https://github.com/shriyasingh03/solana-anchor-smart-contract-examples/blob/main/favorites/programs/favorites/src/lib_more_secre_version.rs</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb01030f253e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building A Secure Counter]]></title>
            <link>https://medium.com/@2001shriya/building-a-secure-counter-6b2ba533fdd1?source=rss-be3ee38604d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b2ba533fdd1</guid>
            <dc:creator><![CDATA[Shriya]]></dc:creator>
            <pubDate>Thu, 25 Jun 2026 12:44:42 GMT</pubDate>
            <atom:updated>2026-06-25T12:44:42.105Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MyaeSOcMKWNKSlPO64S7hw.png" /></figure><p>How To Turn a Vulnerable Smart Contract into Production-Ready Code(offcourse Counter thhh)</p><h3>The Beginning of My Solana Adventure</h3><p>When I first started learning Solana blockchain development, I thought building a simple counter app would be a breeze. “It’s just increment, decrement, set, and reset,” I told myself. “What could possibly go wrong?”</p><p><strong>Turns out, quite a lot.</strong></p><p>This blog post documents my journey from writing a naive, vulnerable counter program to understanding the security pitfalls that even simple smart contracts can hide. If you’re starting your Solana journey, this is for you.</p><h3>Chapter 1: The Naive Counter (My First Attempt)</h3><p>I began with the Anchor framework, eager to write my first Solana program. Here’s what I initially wrote:</p><p>programs/counter/src/lib.rs <strong>(vulnerable):</strong></p><pre>use anchor_lang::prelude::*;</pre><pre>declare_id!(&quot;DnhGSQsfDTmkaWH2wyb6BscZnNqdRdpETpdeNjJDFC46&quot;);</pre><pre>#[program]<br>pub mod counter {<br>    use super::*;</pre><pre>    pub fn initialize(ctx: Context&lt;Initialize&gt;) -&gt; Result&lt;()&gt; {<br>        let counter = &amp;mut ctx.accounts.counter;<br>        counter.value = 0;<br>        Ok(())<br>    }</pre><pre>    pub fn increment(ctx: Context&lt;UpdateCounter&gt;) -&gt; Result&lt;()&gt; {<br>        let counter = &amp;mut ctx.accounts.counter;<br>        counter.value = counter.value.checked_add(1).unwrap();<br>        Ok(())<br>    }</pre><pre>    pub fn decrement(ctx: Context&lt;UpdateCounter&gt;) -&gt; Result&lt;()&gt; {<br>        let counter = &amp;mut ctx.accounts.counter;<br>        counter.value = counter.value.checked_sub(1).unwrap();<br>        Ok(())<br>    }</pre><pre>    pub fn set(ctx: Context&lt;UpdateCounter&gt;, new_value: u64) -&gt; Result&lt;()&gt; {<br>        let counter = &amp;mut ctx.accounts.counter;<br>        counter.value = new_value;<br>        Ok(())<br>    }</pre><pre>    pub fn reset(ctx: Context&lt;UpdateCounter&gt;) -&gt; Result&lt;()&gt; {<br>        let counter = &amp;mut ctx.accounts.counter;<br>        counter.value = 0;<br>        Ok(())<br>    }<br>}</pre><pre>#[derive(Accounts)]<br>pub struct Initialize&lt;&#39;info&gt; {<br>    #[account(init, seeds = [b&quot;counter&quot;], bump, payer = user, space = 8 + 8)]<br>    pub counter: Account&lt;&#39;info, Counter&gt;,<br>    #[account(mut)]<br>    pub user: Signer&lt;&#39;info&gt;,<br>    pub system_program: Program&lt;&#39;info, System&gt;,<br>}</pre><pre>#[derive(Accounts)]<br>pub struct UpdateCounter&lt;&#39;info&gt; {<br>    #[account(mut, seeds = [b&quot;counter&quot;], bump)]<br>    pub counter: Account&lt;&#39;info, Counter&gt;,<br>    pub user: Signer&lt;&#39;info&gt;,<br>}</pre><pre>#[account]<br>pub struct Counter {<br>    pub value: u64,<br>}</pre><h3>What I Thought Was Fine (But Wasn’t)</h3><p>The code above <em>works</em> — it compiles, it deploys, and it increments the counter. But hidden within those innocent unwrap() calls were landmines waiting to explode.</p><h3>The Moment I Realized There Was a Problem</h3><p>While testing my program, I tried to decrement when the counter was at zero. Instead of a friendly error message, I got:</p><pre>Program log: panicked at programs/counter/src/lib.rs:28:54:<br>called `Option::unwrap()` on a `None` value</pre><p><strong>A panic!</strong> In a smart contract!</p><p>My users would see this cryptic message and have no idea what went wrong. Even worse, if someone called increment at u64::MAX, they&#39;d get the same panic. The transaction would fail, but the error was opaque and unhelpful.</p><h3>Chapter 2: The Vulnerabilities I Discovered</h3><h3>1. Arithmetic Overflow/Underflow Panics</h3><pre>counter.value = counter.value.checked_add(1).unwrap();  // ❌<br>counter.value = counter.value.checked_sub(1).unwrap();  // ❌</pre><p><strong>Problem:</strong> When checked_add or checked_sub returns None, unwrap() panics. The client receives a generic &quot;called Option::unwrap() on a None value&quot; error.</p><p><strong>Why It’s Dangerous:</strong></p><ul><li><strong>Poor User Experience:</strong> Users don’t understand what went wrong.</li><li><strong>Unreliable:</strong> The program behaves unexpectedly when hitting limits.</li><li><strong>No Recovery:</strong> There’s no way to handle the error gracefully.</li></ul><h3>2. No Input Validation</h3><p>The set instruction accepts any u64 value, including values that might cause unexpected behavior later.</p><h3>3. Missing Clear Error Messages</h3><p>Without custom errors, debugging becomes a nightmare. You only get the panic message, which doesn’t tell you <em>why</em> the panic occurred.</p><h3>Chapter 3: The Improvements — Making It Secure</h3><h3>I Went Back to the Drawing Board</h3><p>After understanding the issues, I rewrote the program with security and user experience in mind.</p><p>programs/counter/src/lib.rs <strong>(improved &amp; secure):</strong></p><pre>use anchor_lang::prelude::*;</pre><pre>declare_id!(&quot;DnhGSQsfDTmkaWH2wyb6BscZnNqdRdpETpdeNjJDFC46&quot;);</pre><pre>#[program]<br>pub mod counter {<br>    use super::*;</pre><pre>    pub fn initialize(ctx: Context&lt;Initialize&gt;) -&gt; Result&lt;()&gt; {<br>        let counter = &amp;mut ctx.accounts.counter;<br>        counter.value = 0;<br>        Ok(())<br>    }</pre><pre>    pub fn increment(ctx: Context&lt;UpdateCounter&gt;) -&gt; Result&lt;()&gt; {<br>        let counter = &amp;mut ctx.accounts.counter;<br>        require!(counter.value &lt; u64::MAX, MyError::Overflow);<br>        counter.value += 1;<br>        Ok(())<br>    }</pre><pre>    pub fn decrement(ctx: Context&lt;UpdateCounter&gt;) -&gt; Result&lt;()&gt; {<br>        let counter = &amp;mut ctx.accounts.counter;<br>        require!(counter.value &gt; 0, MyError::Underflow);<br>        counter.value -= 1;<br>        Ok(())<br>    }</pre><pre>    pub fn set(ctx: Context&lt;UpdateCounter&gt;, new_value: u64) -&gt; Result&lt;()&gt; {<br>        let counter = &amp;mut ctx.accounts.counter;<br>        counter.value = new_value;<br>        Ok(())<br>    }</pre><pre>    pub fn reset(ctx: Context&lt;UpdateCounter&gt;) -&gt; Result&lt;()&gt; {<br>        let counter = &amp;mut ctx.accounts.counter;<br>        counter.value = 0;<br>        Ok(())<br>    }<br>}</pre><pre>#[error_code]<br>pub enum MyError {<br>    #[msg(&quot;Counter overflow&quot;)]<br>    Overflow,<br>    #[msg(&quot;Counter underflow&quot;)]<br>    Underflow,<br>}</pre><pre>#[derive(Accounts)]<br>pub struct Initialize&lt;&#39;info&gt; {<br>    #[account(<br>        init,<br>        seeds = [b&quot;counter&quot;],<br>        bump,<br>        payer = user,<br>        space = 8 + 8,<br>    )]<br>    pub counter: Account&lt;&#39;info, Counter&gt;,<br>    #[account(mut)]<br>    pub user: Signer&lt;&#39;info&gt;,<br>    pub system_program: Program&lt;&#39;info, System&gt;,<br>}</pre><pre>#[derive(Accounts)]<br>pub struct UpdateCounter&lt;&#39;info&gt; {<br>    #[account(<br>        mut,<br>        seeds = [b&quot;counter&quot;],<br>        bump,<br>    )]<br>    pub counter: Account&lt;&#39;info, Counter&gt;,<br>    pub user: Signer&lt;&#39;info&gt;,<br>}</pre><pre>#[account]<br>pub struct Counter {<br>    pub value: u64,<br>}</pre><h3>What Changed and Why</h3><h3>1. Replaced unwrap() with require!</h3><p><strong>Before:</strong></p><pre>counter.value = counter.value.checked_add(1).unwrap();</pre><p><strong>After:</strong></p><pre>require!(counter.value &lt; u64::MAX, MyError::Overflow);<br>counter.value += 1;</pre><p><strong>Why:</strong> The require! macro performs a conditional check and returns a custom error if it fails. No panic, no unwrap – just clean, predictable error handling.</p><h3>2. Added Custom Error Enums</h3><pre>#[error_code]<br>pub enum MyError {<br>    #[msg(&quot;Counter overflow&quot;)]<br>    Overflow,<br>    #[msg(&quot;Counter underflow&quot;)]<br>    Underflow,<br>}</pre><p><strong>Why:</strong> Now clients receive clear, actionable error messages like &quot;Counter overflow&quot; instead of a panic. This is crucial for:</p><ul><li><strong>User Experience:</strong> Users know exactly what went wrong.</li><li><strong>Frontend Integration:</strong> The frontend can display specific error messages.</li><li><strong>Debugging:</strong> Developers can quickly identify the issue.</li></ul><h3>3. Explicit Bounds Checking</h3><pre>require!(counter.value &lt; u64::MAX, MyError::Overflow);<br>counter.value += 1;  // safe after check</pre><pre>require!(counter.value &gt; 0, MyError::Underflow);<br>counter.value -= 1;  // safe after check</pre><p><strong>Why:</strong> By checking the bounds first, we guarantee the operation is safe before performing it.</p><h3>The Updated Tests</h3><p>I also updated my tests to validate the new error messages:</p><p>tests/counter.ts <strong>(excerpt):</strong></p><pre>it(&quot;Fails when decrementing below 0 (underflow)&quot;, async () =&gt; {<br>  await program.methods<br>    .reset()<br>    .accounts({ counter: counterPDA, user: wallet.publicKey })<br>    .rpc();</pre><pre>  try {<br>    await program.methods<br>      .decrement()<br>      .accounts({ counter: counterPDA, user: wallet.publicKey })<br>      .rpc();<br>    assert.fail(&quot;Expected underflow error but transaction succeeded&quot;);<br>  } catch (error: any) {<br>    const message = error.error?.errorMessage || error.message || &quot;&quot;;<br>    assert.include(message, &quot;Counter underflow&quot;);<br>  }<br>});</pre><pre>it(&quot;Fails when incrementing beyond u64::MAX (overflow)&quot;, async () =&gt; {<br>  const max = new BN(&quot;18446744073709551615&quot;);<br>  await program.methods<br>    .set(max)<br>    .accounts({ counter: counterPDA, user: wallet.publicKey })<br>    .rpc();</pre><pre>  try {<br>    await program.methods<br>      .increment()<br>      .accounts({ counter: counterPDA, user: wallet.publicKey })<br>      .rpc();<br>    assert.fail(&quot;Expected overflow error but transaction succeeded&quot;);<br>  } catch (error: any) {<br>    const message = error.error?.errorMessage || error.message || &quot;&quot;;<br>    assert.include(message, &quot;Counter overflow&quot;);<br>  }<br>});</pre><p>Now the tests check for the <strong>exact custom error messages</strong>, ensuring the program behaves as expected.</p><h3>What I Learned from This Journey</h3><h3>1. Even Simple Contracts Need Security</h3><p>A counter seems trivial, but arithmetic vulnerabilities can cause serious issues in production. <strong>Always handle edge cases.</strong></p><h3>2. Custom Errors Are Essential</h3><p>Never let your program panic. Use require! with custom errors to provide clear feedback to users.</p><h3>3. Test for Failure</h3><p>Your tests shouldn’t just verify success — they must also confirm that failures are handled correctly.</p><h3>4. Secure Your PDAs</h3><p>Always use seeds and bump constraints to ensure the correct PDA is being accessed. This prevents unauthorized access.</p><h3>The Frontend Experience</h3><p>With the improved program, the frontend now receives clear error messages:</p><p><strong>Before:</strong></p><pre>Error: called `Option::unwrap()` on a `None` value</pre><p><strong>After:</strong></p><pre>Error: Counter overflow</pre><p>Now users understand the issue immediately.</p><h3>Key Takeaways for Solana Developers</h3><p><strong>Vulnerability</strong></p><p><strong>Fix</strong></p><p>Arithmetic panic with unwrap()</p><p>Use require! with custom errors</p><p>Opaque error messages</p><p>Define #[error_code] enums with clear #[msg(...)]</p><p>Missing input validation</p><p>Check bounds before operations</p><p>Tests expecting panic messages</p><p>Tests check for custom error strings</p><h3>Conclusion: The Journey Continues</h3><p>Building a simple counter on Solana taught me more than I expected. It showed me that security isn’t just for complex DeFi protocols — even the simplest programs can hide vulnerabilities.</p><p>If you’re just starting your Solana journey, <strong>never underestimate the importance of error handling</strong>. Use require!, define custom errors, and always test for failure cases.</p><p>The improved counter program is now secure, user-friendly, and ready for production. It may be a simple counter, but the principles I learned will guide me through building more complex applications.</p><h3>🚀 Check Out the Complete Code!</h3><p>The full, improved counter program is now available on my GitHub repository. You can explore the code, run the tests yourself, and even use it as a template for your own Solana projects.</p><p><strong>🔗 Explore the code:</strong><br><a href="https://github.com/shriyasingh03/solana-anchor-smart-contract-examples/tree/main/counter">https://github.com/shriyasingh03/solana-anchor-smart-contract-examples/tree/main/counter</a></p><h3>💬 Let’s Connect!</h3><p>I’m just getting started on my Solana journey, and I’d love to learn from you too. Follow me on GitHub to see what I build next:</p><p><strong>GitHub:</strong> <a href="https://github.com/shriyasingh03">github.com/shriyasingh03</a></p><p><strong>Happy coding, and may your transactions always be successful!</strong> 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b2ba533fdd1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Comprehensive Guide: GitHub Actions CI/CD for Solana Anchor Projects]]></title>
            <link>https://medium.com/@2001shriya/comprehensive-guide-github-actions-ci-cd-for-solana-anchor-projects-218242c576c5?source=rss-be3ee38604d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/218242c576c5</guid>
            <dc:creator><![CDATA[Shriya]]></dc:creator>
            <pubDate>Wed, 24 Jun 2026 13:24:03 GMT</pubDate>
            <atom:updated>2026-06-24T13:24:03.049Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1007/1*euhzbq9dDilaKxvhoVfp0g.png" /></figure><h4><strong>A Detailed Report on Common Pitfalls and Their Solutions</strong></h4><h3>1. Introduction to GitHub Actions</h3><h3>What is GitHub Actions?</h3><p>GitHub Actions is a powerful continuous integration and continuous deployment (CI/CD) platform that automates your software development workflows. It enables you to build, test, and deploy your code directly from your GitHub repository.</p><h3>Why Use GitHub Actions?</h3><ul><li>Automation: Automatically run tests on every push or pull request.</li><li>Consistency: Ensure consistent build environments across all contributors.</li><li>Early Bug Detection: Catch issues before they reach production.</li><li>Parallel Execution: Run multiple jobs simultaneously for faster feedback.</li><li>Reusable Workflows: Share and reuse workflow templates across projects.</li><li>Cost-Effective: Free for public repositories and includes generous free minutes for private ones.</li></ul><h3>Key Components of GitHub Actions</h3><p>ComponentDescriptionExampleWorkflowAn automated procedure defined in YAML.github/workflows/test.ymlEventWhat triggers the workflowpush, pull_request, scheduleJobA set of steps executed on the same runnertest, build, deployStepIndividual tasks within a jobcheckout code, install dependenciesActionReusable units of workactions/checkout@v4, actions/setup-node@v4RunnerThe virtual machine that executes the jobubuntu-latest, windows-latest</p><h3>Basic Workflow Structure</h3><pre>name: Workflow Name</pre><pre>on:<br>  push:<br>    branches: [main]<br>  pull_request:<br>    branches: [main]<br>  workflow_dispatch:        # Manual trigger</pre><pre>jobs:<br>  build-and-test:<br>    runs-on: ubuntu-latest<br>    steps:<br>      - uses: actions/checkout@v4<br>      - name: Run a command<br>        run: echo &quot;Hello, World!&quot;</pre><h3>2. Common GitHub Actions Errors and Solutions</h3><h3>Category 1: YAML Syntax Errors</h3><h4>Error: Workflow Not Showing in Actions Tab</h4><p>Symptoms:</p><ul><li>Workflow file exists but doesn’t appear in the Actions tab.</li><li>No error messages visible in the interface.</li></ul><p>Common Causes:</p><p>Error TypeExampleFixIndentation errorsWrong spacing (tabs vs spaces)Use 2 spaces, validate with linterMissing keywordson or jobs omittedInclude all required sectionsInvalid structureJobs nested incorrectlyFollow the YAML schemaTrailing charactersExtra spaces or charactersRemove all trailing spaces</p><p>Example of Invalid YAML:</p><pre>name: Test<br>on: [push]     # Missing colon after pull_request<br>jobs:<br>  test:<br>    runs-on: ubuntu-latest<br>    steps:<br>      - uses: actions/checkout@v4<br>      - run: echo &quot;test&quot;    # Wrong indentation</pre><p>Solution:</p><pre>name: Test<br>on: <br>  push:<br>  pull_request:      # ✅ Correct structure<br>jobs:<br>  test:<br>    runs-on: ubuntu-latest<br>    steps:<br>      - uses: actions/checkout@v4<br>      - run: echo &quot;test&quot;</pre><p>Prevention:</p><ol><li>Use <a href="https://yamllint.com/">YAML Lint</a> to validate your workflow.</li><li>Use VS Code with YAML extension for syntax highlighting.</li><li>Commit and check the Actions tab immediately.</li></ol><h3>Category 2: Path and Directory Issues</h3><h4>Error 1: No Such File or Directory</h4><p>Symptoms:</p><pre>Error: An error occurred trying to start process &#39;/usr/bin/bash&#39; with <br>working directory &#39;/home/runner/work/repo/repo/folder&#39;. <br>No such file or directory</pre><p>Common Causes:</p><p>MistakeCorrectWhyworking-directory: hello-worldworking-directory: hello_worldFolder name mismatchpaths: &quot;hello-world/**&quot;paths: &quot;hello_world/**&quot;Inconsistent namingworking-directory: programs/hello-worldworking-directory: hello_worldWrong project structure</p><p>Example of Incorrect Paths:</p><pre>on:<br>  push:<br>    paths:<br>      - &quot;hello-world/**&quot;          # ❌ Wrong folder name<br>  pull_request:<br>    paths:<br>      - &quot;hello_world/**&quot;          # ❌ Inconsistent</pre><pre>jobs:<br>  test:<br>    defaults:<br>      run:<br>        working-directory: hello-world   # ❌ Folder doesn&#39;t exist</pre><p>Solution:</p><pre>on:<br>  push:<br>    paths:<br>      - &quot;hello_world/**&quot;          # ✅ Consistent with actual folder name<br>  pull_request:<br>    paths:<br>      - &quot;hello_world/**&quot;</pre><pre>jobs:<br>  test:<br>    defaults:<br>      run:<br>        working-directory: hello_world   # ✅ Exact folder name</pre><p>Best Practices for Paths:</p><ol><li>Use ls -la locally to confirm folder names.</li><li>Be consistent: use underscore (_) OR hyphen (-) throughout.</li><li>Use ** for recursive matching (all subfolders).</li><li>Test locally with act to simulate GitHub Actions.</li></ol><h4>Error 2: Trigger Paths Not Matching</h4><p>Symptoms:</p><ul><li>Workflow appears but doesn’t run when files change.</li><li>Push doesn’t trigger the expected workflow.</li></ul><p>Example of Wrong Trigger Configuration:</p><pre>on:<br>  push:<br>    paths:<br>      - &quot;src/**&quot;          # ❌ Folder doesn&#39;t exist</pre><p>Solution:</p><pre>on:<br>  push:<br>    paths:<br>      - &quot;hello_world/**&quot;          # ✅ Correct path<br>      - &quot;README.md&quot;               # ✅ Specific file<br>      - &quot;!hello_world/ignore/**&quot;  # ✅ Exclude paths</pre><h3>Category 3: Environment and Toolchain Issues</h3><h4>Error: edition2024 Feature Required</h4><p>Symptoms:</p><pre>error: failed to parse manifest at `/path/to/cpufeatures-0.3.0/Cargo.toml`</pre><pre>Caused by:<br>  feature `edition2024` is required</pre><pre>  The package requires the Cargo feature called `edition2024`, <br>  but that feature is not stabilized in this version of Cargo (1.79.0)</pre><p>Root Cause:</p><ul><li>The cpufeatures crate version 0.3.0 uses the experimental edition2024 feature.</li><li>The GitHub runner’s default Rust version (1.79.0) doesn’t support it.</li><li>The edition2024 feature requires Rust 1.85.0 or later.</li></ul><p>Solutions:</p><p>Solution 1: Install Specific Rust Version (Recommended)</p><pre>steps:<br>  - name: Install Rust<br>    uses: actions-rs/toolchain@v1<br>    with:<br>      toolchain: 1.85.0<br>      override: true</pre><p>Solution 2: Use Nightly Toolchain</p><pre>steps:<br>  - name: Install Rust Nightly<br>    uses: actions-rs/toolchain@v1<br>    with:<br>      toolchain: nightly<br>      override: true</pre><p>Solution 3: Pin Dependency Version</p><pre># In Cargo.toml<br>[patch.crates-io]<br>cpufeatures = { git = &quot;https://github.com/RustCrypto/utils&quot;, rev = &quot;a51fe1b&quot; }</pre><p>Best Practices:</p><ol><li>Always specify a Rust version in CI workflows.</li><li>Use actions-rs/toolchain for reliable version management.</li><li>Test with multiple Rust versions using matrix builds.</li></ol><h3>Category 4: Git Branch Management</h3><h4>Error: Divergent Branches</h4><p>Symptoms:</p><pre>! [rejected]        main -&gt; main (fetch first)<br>error: failed to push some refs<br>Updates were rejected because the remote contains work that you do not have locally</pre><p>Visual Explanation:</p><pre>Local repository (main)          Remote repository (origin/main)<br>─────────────────────────        ──────────────────────────────</pre><pre>   A - B - C - D - X                 A - B - C - D - Y<br>         (your commit)                     (someone else&#39;s commit)</pre><pre>   - Local is ahead by 1 commit (X)<br>   - Remote is ahead by 1 commit (Y)<br>   - They diverged from common commit D</pre><p>Solutions:</p><p>Solution 1: Rebase (Recommended)</p><pre>git pull --rebase origin main</pre><p>Result After Rebase:</p><pre>A - B - C - D - Y - X&#39;   (local main)<br>                       ^<br>                       your commit reapplied on top</pre><p>Solution 2: Merge</p><pre>git pull --no-rebase origin main</pre><p>Result After Merge:</p><pre>A - B - C - D - X - M<br>                \     /<br>                 Y ---</pre><p>Set Rebase as Default:</p><pre>git config --global pull.rebase true</pre><p>Best Practices:</p><ol><li>Use git pull --rebase for cleaner history.</li><li>Pull before pushing to avoid divergence.</li><li>Use feature branches for collaborative work.</li><li>Resolve conflicts locally before pushing.</li></ol><h3>Category 5: Dependency Installation Issues</h3><h4>Error: Node.js or Package Manager Not Found</h4><p>Symptoms:</p><pre>Command &#39;yarn&#39; not found<br>Command &#39;npm&#39; not found</pre><p>Solution:</p><pre>- name: Setup Node.js<br>  uses: actions/setup-node@v4<br>  with:<br>    node-version: &#39;20&#39;<br>    cache: &#39;yarn&#39;           # Caches dependencies for faster runs</pre><pre>- name: Install dependencies<br>  run: yarn install</pre><h4>Error: Solana CLI Version Issues</h4><p>Symptoms:</p><pre>No such file or directory: solana-keygen<br>anchor: command not found</pre><p>Solution:</p><pre>- name: Install Solana CLI<br>  run: |<br>    sh -c &quot;$(curl -sSfL https://release.anza.xyz/v2.1.21/install)&quot;<br>    echo &quot;\(HOME/.local/share/solana/install/active_release/bin&quot; &gt;&gt; \)GITHUB_PATH</pre><pre>- name: Verify Solana Installation<br>  run: solana --version</pre><h3>3. My Complete Journey: From Setup to Success</h3><h3>Project Structure</h3><pre>solana-anchor-smart-contract-examples/<br>├── .github/<br>│   └── workflows/<br>│       └── test-hello-world.yml<br>├── hello_world/                    # Anchor project<br>│   ├── Anchor.toml<br>│   ├── Cargo.toml<br>│   ├── package.json<br>│   ├── programs/<br>│   │   └── hello_world/<br>│   └── tests/<br>├── README.md<br>└── .gitignore</pre><h3>Attempt 1: Basic Workflow (Failed)</h3><p>What I Did Wrong:</p><ul><li>Inconsistent path naming (hello-world vs hello_world).</li><li>Wrong working directory.</li><li>No Rust version specification.</li></ul><p>Result:</p><pre>Error: No such file or directory<br>Workflow didn&#39;t appear in Actions tab</pre><h3>Attempt 2: Corrected Paths (Partially Worked)</h3><p>What I Fixed:</p><ul><li>Used consistent paths: hello_world/**</li><li>Set correct working directory: hello_world</li><li>Validated YAML syntax</li></ul><p>Result:</p><ul><li>Workflow appeared but failed with Rust toolchain error</li></ul><h3>Attempt 3: Full Working Solution</h3><p>What I Added:</p><ul><li>Rust 1.85.0 installation</li><li>Proper Solana and Anchor installation</li><li>Environment variables for Anchor test</li></ul><p>Final Working Workflow:</p><pre>name: Test Hello World Program</pre><pre>on:<br>  push:<br>    branches: [main]<br>    paths:<br>      - &quot;hello_world/**&quot;<br>  pull_request:<br>    branches: [main]<br>    paths:<br>      - &quot;hello_world/**&quot;<br>  workflow_dispatch:</pre><pre>jobs:<br>  test:<br>    runs-on: ubuntu-24.04</pre><pre>    defaults:<br>      run:<br>        working-directory: hello_world</pre><pre>    steps:<br>      - uses: actions/checkout@v4</pre><pre>      - name: Install Rust<br>        uses: actions-rs/toolchain@v1<br>        with:<br>          toolchain: 1.85.0<br>          override: true</pre><pre>      - name: Install Solana CLI<br>        run: |<br>          sh -c &quot;$(curl -sSfL https://release.anza.xyz/v2.1.21/install)&quot;<br>          echo &quot;\(HOME/.local/share/solana/install/active_release/bin&quot; &gt;&gt; \)GITHUB_PATH</pre><pre>      - name: Install Anchor<br>        run: cargo install --git <a href="https://github.com/coral-xyz/anchor">https://github.com/coral-xyz/anchor</a> --tag v0.31.1 anchor-cli --locked</pre><pre>      - name: Generate keypair<br>        run: solana-keygen new --outfile $HOME/.config/solana/id.json --no-bip39-passphrase --force</pre><pre>      - name: Install Node dependencies<br>        run: yarn install</pre><pre>      - name: Run Anchor tests<br>        run: anchor test<br>        env:<br>          ANCHOR_PROVIDER_URL: &quot;http://127.0.0.1:8899&quot;<br>          ANCHOR_WALLET: &quot;$HOME/.config/solana/id.json&quot;</pre><h3>4. Best Practices and Recommendations</h3><h3>1. Workflow Organization</h3><pre># Use descriptive names<br>name: Test Hello World Program</pre><pre># Be specific with triggers<br>on:<br>  push:<br>    branches: [main]<br>    paths:<br>      - &quot;hello_world/**&quot;<br>  workflow_dispatch:  # Manual trigger</pre><pre># Use environment variables for configuration<br>env:<br>  ANCHOR_VERSION: &quot;0.31.1&quot;<br>  RUST_VERSION: &quot;1.85.0&quot;</pre><h3>2. Caching for Performance</h3><pre>- name: Cache Cargo registry<br>  uses: actions/cache@v3<br>  with:<br>    path: ~/.cargo/registry<br>    key: \({{ runner.os }}-cargo-registry-\){{ hashFiles(&#39;**/Cargo.lock&#39;) }}</pre><pre>- name: Cache Node modules<br>  uses: actions/cache@v3<br>  with:<br>    path: hello_world/node_modules<br>    key: \({{ runner.os }}-node-modules-\){{ hashFiles(&#39;hello_world/yarn.lock&#39;) }}</pre><h3>3. Matrix Builds for Multiple Programs</h3><pre>strategy:<br>  matrix:<br>    program: [&quot;hello_world&quot;, &quot;counter&quot;]</pre><pre>steps:<br>  - name: Test program<br>    run: |<br>      cd ${{ matrix.program }}<br>      anchor test</pre><h3>4. Error Handling</h3><pre>- name: Run tests<br>  run: anchor test<br>  continue-on-error: false   # Fail workflow if tests fail</pre><pre>- name: Upload logs on failure<br>  if: failure()<br>  uses: actions/upload-artifact@v3<br>  with:<br>    name: test-logs<br>    path: |<br>      **/test-ledger/*.log<br>      **/*.txt</pre><h3>5. Troubleshooting Cheat Sheet</h3><p>SymptomLikely CauseSolutionWorkflow doesn’t appearYAML syntax errorValidate with linter”No such file” errorWrong pathCheck exact folder namesFails during buildMissing toolchainAdd Rust installation step”edition2024&quot; errorOld Rust versionUse Rust 1.85+Push rejectedDivergent branchesgit pull --rebaseCache not workingWrong cache keyUse hashFiles()Test validator failsPort conflictIncrease startup_wait</p><h3>6. Conclusion</h3><p>Setting up GitHub Actions for a Solana Anchor project requires attention to detail, especially regarding:</p><ol><li>YAML Syntax: Always validate your workflow files.</li><li>Path Precision: Match exact folder names (underscore vs. hyphen matters!).</li><li>Toolchain Version: Specify compatible Rust versions.</li><li>Git Management: Use rebase to avoid divergent branches.</li><li>Dependencies: Properly install and cache dependencies.</li></ol><p>The journey from a failing workflow to a green checkmark is educational and rewarding. Each error teaches you something new about how CI/CD pipelines work and how to debug them effectively.</p><h3>7. Additional Resources</h3><ul><li><a href="https://docs.github.com/en/actions">GitHub Actions Documentation</a></li><li><a href="https://github.com/solana-developers/github-workflows">Solana Developers GitHub Workflows</a></li><li><a href="https://github.com/marketplace?type=actions&amp;query=solana">Actions for Solana</a></li><li><a href="https://yamllint.com/">YAML Lint</a></li><li><a href="https://github.com/nektos/act">Act — Run GitHub Actions Locally</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=218242c576c5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The First Step Into Solana Smart Contracts: My Brutal “Hello World” Journey on WSL]]></title>
            <link>https://medium.com/@2001shriya/the-first-step-into-solana-smart-contracts-my-brutal-hello-world-journey-on-wsl-1c7f3f56b32d?source=rss-be3ee38604d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c7f3f56b32d</guid>
            <dc:creator><![CDATA[Shriya]]></dc:creator>
            <pubDate>Tue, 23 Jun 2026 13:04:25 GMT</pubDate>
            <atom:updated>2026-06-23T13:04:25.875Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iRv4XV1yBFt2LLJWhaNhgA.jpeg" /></figure><h4><strong>Specific, visceral, debugging war story</strong></h4><p>I remember the excitement vividly. I had just set up my WSL (Windows Subsystem for Linux) environment, painstakingly followed the Anchor installation guide, and finally typed anchor init hello_world. I was ready to conquer Solana.</p><p>Then, I ran anchor build and was immediately humiliated by the terminal.</p><pre>thread &#39;main&#39; panicked at cli/src/lib.rs:1367:47: Not in workspace.</pre><p>That single error spiraled into a 2-hour debugging session. It wasn’t just about getting “Hello, Solana!” to print; it was about fighting with the very tools I was trying to learn. But after pushing through, I discovered the hidden quirks of Solana development that no YouTube tutorial openly talks about.</p><p>Here is a brutally honest, step-by-step report of every error I encountered writing my first Solana smart contract (in Anchor) on WSL, and the golden lessons I extracted from each failure.</p><h3>Error #1: The “Not in workspace” Panic</h3><p>What I did: I created a folder manually (mkdir Hello_World), navigated inside it, and ran anchor build to test if things worked.</p><p>The Error (Full Text):</p><pre>thread &#39;main&#39; panicked at cli/src/lib.rs:1367:47:<br>Not in workspace.<br>note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace</pre><p>Why it happened: anchor build relies entirely on the existence of an Anchor.toml file to determine where your program is located. Since I created the folder manually, that file didn&#39;t exist. Anchor panicked because it looked for a configuration file and found nothing.</p><p>The Fix: I deleted my manual folder (rm -rf Hello_World) and let Anchor do what it does best:</p><pre>anchor init hello_world</pre><p>This created the proper Anchor.toml and the correct folder hierarchy.</p><p>What I learned: Never build the scaffolding yourself. This is the “Framework’s Law.” Frameworks like Anchor, Rails, or Django are religious about their file structure. If you try to outsmart them by creating files manually, they will punish you. Always, always use the CLI scaffolding tool to bootstrap the project. It saves you from obscure pathing errors before you even write a single line of logic.</p><h3>Error #2: The Program ID Phantom Mismatch</h3><p>What I did: I wrote the lib.rs code with the generic placeholder:</p><pre>declare_id!(&quot;11111111111111111111111111111111&quot;);</pre><p>I ran anchor build and then anchor test.</p><p>The Error (or rather, the silent disaster): The build succeeded, but when I tried to run the test, I got:</p><pre>Error: ProgramFailedToComplete: Program failed to complete: AccountNotInitialized</pre><p>Why it happened: The declare_id! macro is the immutable public address of your program. When you deploy, the runtime checks if the executable bytecode you are sending matches the address you are signing with. If I deploy the code with 111..., it expects a program at address 111..., but Anchor generated a new, random keypair in target/deploy/ for me. Since the keys didn&#39;t match, the transaction failed.</p><p>The Fix: I ran:</p><pre>anchor keys sync</pre><p>This command reads the *.json keypair file in target/deploy/, extracts its public key, and <em>automagically</em> overwrites the address inside the declare_id! macro in my lib.rs. I rebuilt and it worked.</p><p>What I learned: The Program ID is a Hard Commitment. In Ethereum, you can theoretically deploy the same code to a random address. In Solana, the Program ID is the address. You must treat the target/deploy/*-keypair.json as the <em>actual</em> identity of your contract.</p><p>Pro tip: Run anchor keys sync after every time you clone a repo or start a new project. It is the &quot;fix-it&quot; button for 70% of deployment errors.</p><h3>Error #3: The getTransaction Deprecation Warning (The SDK Catch)</h3><p>What I did: I used the standard test file generated by Anchor, specifically this snippet to verify the logs:</p><pre>const transaction = await provider.connection.getTransaction(txSignature, {<br>  commitment: &quot;confirmed&quot;,<br>});</pre><p>The Error (VS Code warning + Logs):</p><pre>DeprecationWarning: &#39;getTransaction&#39; is deprecated. Use &#39;getParsedTransaction&#39; instead.</pre><p>Why it happened: The @solana/web3.js library evolves faster than Anchors&#39; default templates. The getTransaction method, which fetches raw transaction data and logs, was considered too rigid. The Solana team shifted towards getParsedTransaction to automatically decode system instructions and token transfers into a human-readable JSON format.</p><p>The Fix: I updated my tests/hello_world.ts to use the newer standard:</p><pre>const transaction = await provider.connection.getParsedTransaction(txSignature, {<br>  commitment: &quot;confirmed&quot;,<br>  maxSupportedTransactionVersion: 0, // Ensures versioned transactions are parsed<br>});</pre><p>What I learned: Never trust the scaffold completely. When you run anchor init, it clones a template from the internet. If the template is two months old, it might rely on deprecated dependencies.</p><p>Actionable advice: Always run solana --version and anchor --version and cross-check them with the @solana/web3.js version in your package.json. If you see deprecation warnings, treat them as blockers, not hints. They often signal that a crucial security update or API change has occurred.</p><h3>Error #4: The WSL Path Permissions &amp; Airdrop Failure</h3><p>What I did: I tried to run anchor test against the local validator. The validator booted up, but I kept getting:</p><pre>Error: Airdrop failed. Custom program error: 0x1</pre><p>Why it happened: This was a subtle WSL-specific issue. WSL uses a different file system for Linux (EXT4) and Windows (NTFS). If you mount your project on the Windows drive (e.g., /mnt/c/Users/...), the file permissions for the socket files used by the local validator often break. The validator couldn&#39;t read the keypair file properly to sign the airdrop transaction because the Linux permissions weren&#39;t applied correctly.</p><p>The Fix: I moved my entire ~/solana-projects folder to a WSL native path (e.g., ~/projects/solana) instead of the /mnt/c/ drive.</p><p>What I learned: WSL is Linux, not Windows. When doing heavy I/O operations like building Rust binaries or running local validators, always store your projects inside the WSL virtual file system (e.g., /home/username/projects). The performance is vastly superior, and the permission issues vanish. Accessing the Windows drive from WSL is a trap for blockchain developers.</p><h3>Error #5: The “Private Key on GitHub” Panic (The Big Scare)</h3><p>What I did: I wasn’t looking at errors; I was just pushing to GitHub. I ran git add . and git push.</p><p>The Scare: I looked at my GitHub repository and saw the target/deploy/ folder.</p><p>Why it was catastrophic: Inside target/deploy/hello_world-keypair.json is the private key to my deployed program. If I had pushed this and someone cloned it, they would have the authority to upgrade my smart contract or even drain its vaults. Solana&#39;s security bots actively scan GitHub for these files and will drain wallets instantly if they find a matching keypair.</p><p>The Fix: I immediately removed the file from GitHub history (force pushed with git filter-repo), generated new keys, and created a strict .gitignore.</p><p>What I learned: Security is the developer’s responsibility. The framework doesn’t protect you from yourself. I created a .gitignore file that specifically targets:</p><pre># Never ever commit these<br>*.json<br>!package.json<br>target/<br>**/*-keypair.json</pre><p>Lesson: Always run git status before git add .. Look for target/ or .json files. If you see them, pause. You are about to commit your digital life.</p><h3>Error #6: The msg! Macro Not Showing in Logs</h3><p>What I did: I ran anchor test successfully, but I couldn&#39;t see my beautiful &quot;Hello, Solana!&quot; message in the terminal output.</p><p>Why it happened: I was only looking at the terminal output of anchor test. This only shows the output of the TypeScript test runner, not the full RPC logs. The msg! macro prints to the validator&#39;s log output, not to the standard test output.</p><p>The Fix: I opened a second WSL terminal and ran:</p><pre>solana logs</pre><p>Then I ran the test again. In the second terminal, I saw:</p><pre>Program log: Hello, Solana!<br>Program log: Called by: Fg6Pa...</pre><p>What I learned: Solana is asynchronous. The blockchain doesn’t output to your console. You need to subscribe to the logs either via the solana logs CLI or by using connection.onLogs() in your frontend.</p><h3>The Final Summary: A “Hello World” Reality Check</h3><p>Writing my first Solana contract taught me that “Hello World” in blockchain isn’t just about syntax; it’s about orchestration.</p><ul><li>Syntax was easy (msg!(&quot;Hello, World&quot;);)</li><li>Infrastructure was hard (WSL permissions, RPC connections, local validators)</li><li>Security was terrifying (GitHub leaks, program authority)</li></ul><p>Here is what I walked away with:</p><ol><li>anchor keys sync is your best friend. Use it to cure existential crisis.</li><li>Don’t use the Windows drive (/mnt/c/) for Solana projects. Stick to the WSL home directory.</li><li>Update your .gitignore before you write a single line of code. Treat it as essential as lib.rs.</li><li>Learn to read the validator logs. solana logs is your window into the blockchain.</li><li>Always update deprecated methods in tests. getParsedTransaction over getTransaction.</li></ol><p>Getting that single line “Hello, Solana!” to print was the most frustrating, educational, and ultimately rewarding 5 hours of my engineering career. If you are facing these errors, know that you are not alone. The path is filled with these hidden landmines, but every single error is a lesson on how the Solana Virtual Machine actually works.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c7f3f56b32d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Same Places In Dreams]]></title>
            <link>https://medium.com/@2001shriya/same-places-in-dreams-d2b8126f4d78?source=rss-be3ee38604d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/d2b8126f4d78</guid>
            <dc:creator><![CDATA[Shriya]]></dc:creator>
            <pubDate>Mon, 09 Oct 2023 16:43:52 GMT</pubDate>
            <atom:updated>2023-10-09T16:43:52.486Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0K8mByj4b0i5wLGfhxEFyg.jpeg" /></figure><p>Dream Chapter:</p><p>This is the third time I dreamed of the same place in my dream. Is it even possible on a psychological level to remember the same place that had once appeared in a dream?</p><p>I was reading and researching on the same topic when I encountered an interesting thesis put forth by Thomas Kilduff, Ph.D., director of the Center for Neuroscience at SRI International, Menlo Park, California, and a senior author of the study published in Science. “Ever wonder why we forget many of our dreams? Our results suggest that the firing of a particular group of neurons during REM sleep controls whether the brain remembers new information after a good night’s sleep.”</p><p><em>[Rapid eye movement, or REM, sleep is a fascinating period when most of our dreams are made. ]</em></p><p>REM first occurs about 90 minutes after falling asleep and is characterized by darting eyes, raised heart rates, paralyzed limbs, awakened brain waves and dreaming.</p><p>In this study, Dr. Kilduff worked with Dr. Yamanaka’s lab and Akira Terao’s, D.V.M., Ph.D., lab at Hokkaido University, Sapporo, Japan, to look at neighboring cells that produce melanin-concentrating hormone (MCH), a molecule known to be involved in the control of both sleep and appetite. The researchers found that a majority (52.8%) of hypothalamic MCH cells fired when mice underwent REM sleep whereas about 35% fired only when the mice were awake and about 12% fired at both times.</p><p>They also uncovered clues suggesting that these cells may play a role in learning and memory. Electrical recordings and tracing experiments showed that many of the hypothalamic MCH cells sent inhibitory messages, via long stringy axons, to the hippocampus, the brain’s memory center.</p><p>“From previous studies done in other labs, we already knew that MCH cells were active during REM sleep. After discovering this new circuit, we thought these cells might help the brain store memories,” said Dr. Kilduff.</p><p>The question then arises why do some people remember every detail of some dreams? What causes them to remember?</p><p>Some theory suggests that dreams occur when our brain processes information, eliminates unnecessary stuff, and moves important short-term memories into our long-term memory. So people who recall dreams may have a difference in their ability to memorize things in general.</p><p>According to a study conducted by Lambert-“Researchers also looked at the most common personality traits that are presented in people who can recall their dreams. Overall, such people are prone to daydreaming, creative thinking, and introspection. At the same time, those who are more practical and focused on what is outside themselves tend to have difficulty remembering their dreams.” Other factors, like stress or experiencing trauma, can also cause people to have <a href="https://www.healthline.com/health/vivid-dreams-causes">vivid dreams</a> or <a href="https://www.healthline.com/health/sleep/night-terrors-vs-nightmares">nightmares</a> that they’re more likely to recall the next day.</p><p>But again, why do you see the same things in dreams as a recurring pattern?</p><p>I certainly have no trauma though. I was reading on Quora to satisfy my curiosity when I came to this post by Alri Menerski-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/1*xSqg4UgZXt7Q3tEgI3HDmQ.png" /></figure><p>Well, I don’t know for sure if I am falling back into old habits or committing the same mistakes but I will definitely give thought to it. Also, I am not that creative of the kind.</p><p>Am I stupid? I don’t know.</p><p>But certain strange places do repeatedly come into my dreams that I haven’t even visited in real life. What are they trying to imply? I don’t know.</p><p>Have you given some thought to it?</p><p>Credite-National Institute of Health</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d2b8126f4d78" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Pampering Study Pressure]]></title>
            <link>https://medium.com/@2001shriya/the-pampering-study-pressure-e8e66dc1bdc2?source=rss-be3ee38604d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8e66dc1bdc2</guid>
            <dc:creator><![CDATA[Shriya]]></dc:creator>
            <pubDate>Mon, 27 Jun 2022 20:03:39 GMT</pubDate>
            <atom:updated>2022-06-27T20:22:39.540Z</atom:updated>
            <content:encoded><![CDATA[<p><em>The face of the rat race ;</em></p><p><em>Making every student a messy mace;</em></p><p><em>Busy cramping things in mind they are;</em></p><p><em>Discretized with present society so far ;</em></p><p><em>Veiled with tartly study trash;</em></p><p><em>Minds are getting intellectuality a blank space;</em></p><p><em>WhatsApp, Facebook, groups, and chat;</em></p><p><em>Molding the abilities in a tat;</em></p><p><em>Virtuality actual games pursuing them on trackless trace;</em></p><p><em>Parents nowadays forcing to go out for refresh;</em></p><p><em>What an atrocious situation they are making;</em></p><p><em>Souls are scratching them and minds are baking;</em></p><p><em>Cut-throat competitions, school, coaching, and tuition press;</em></p><p><em>Encompassing in a room with books life like hanged brace;</em></p><p><em>Seeking pocketful sunshine ;</em></p><p><em>Weeping and sobbing in loneliness pretending to be frisking fine;</em></p><p><em>Reckless minds are growing into fearful kind ;</em></p><p><em>How sad the shooting stars are now let’s find.</em></p><h4><strong>-Bobbish Shriya-</strong></h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8e66dc1bdc2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>