<?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 Dhruv Patel on Medium]]></title>
        <description><![CDATA[Stories by Dhruv Patel on Medium]]></description>
        <link>https://medium.com/@d7511162?source=rss-8de3c9502bfd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*tBjYMX7Za9HiWce8hKNwMg.png</url>
            <title>Stories by Dhruv Patel on Medium</title>
            <link>https://medium.com/@d7511162?source=rss-8de3c9502bfd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 10:53:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@d7511162/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[The Solana Learning Ladder By Dhruv patel]]></title>
            <link>https://medium.com/@d7511162/the-solana-learning-ladder-by-dhruv-patel-da5044b6a671?source=rss-8de3c9502bfd------2</link>
            <guid isPermaLink="false">https://medium.com/p/da5044b6a671</guid>
            <category><![CDATA[solana-blockchain]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[blockchain-technology]]></category>
            <category><![CDATA[solana-ecosystem]]></category>
            <category><![CDATA[web3-development]]></category>
            <dc:creator><![CDATA[Dhruv Patel]]></dc:creator>
            <pubDate>Mon, 23 Mar 2026 18:01:54 GMT</pubDate>
            <atom:updated>2026-03-23T18:01:54.494Z</atom:updated>
            <content:encoded><![CDATA[<h4>Solana Learning Series — Complete Guide</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r935z8IWRLX7dBGwcZkc5w.png" /></figure><p>Welcome to the <strong>Solana Learning Series</strong>, where I break down everything step-by-step — from basics to advanced concepts — in a simple and practical way.</p><p>Whether you’re a beginner or someone with prior blockchain knowledge, this series will help you build a strong understanding of Solana and how to create real-world projects on it.</p><h3>💡 How to Follow This Series</h3><ul><li>It is recommended to follow the ladder step-by-step for the best understanding</li><li>Each ladder builds on the previous one</li><li>However, if you are already familiar with certain concepts, you can jump directly to any section</li></ul><h3>🔥 Goal of This Series</h3><p>By the end of this series, you will:</p><ul><li>Understand how Solana works internally</li><li>Learn how to interact with accounts and transactions</li><li>Build and deploy your own Solana programs</li><li>Create real-world decentralized applications (DApps)</li></ul><h3>🪜 Solana Learning Ladder</h3><h4>🪜 Step 1: <a href="https://medium.com/@d7511162/understanding-solana-a-complete-deep-dive-e8cc7ed761a9">Understanding Solana: A Complete Deep Dive By Dhruv Patel</a></h4><h4>🪜 Step 2:<a href="https://medium.com/@d7511162/mastering-solanas-account-model-the-complete-guide-by-dhruv-patel-5cb4885b2c81"> Mastering Solana’s Account Model: The Complete Guide By Dhruv Patel</a></h4><h4>🪜 Step 3: <a href="https://medium.com/@d7511162/mastering-solanas-account-model-the-complete-guide-by-dhruv-patel-5cb4885b2c81">Ethereum vs Solana: The Architecture Battle You Need to Understand</a></h4><h4>🪜Step 4: <a href="https://medium.com/@d7511162/solana-web3-js-by-dhruv-patel-4a4f6164670f">Solana Web3.js By Dhruv patel</a></h4><h4>🪜 Step 5: <a href="https://medium.com/@d7511162/mastering-spl-tokens-on-solana-the-complete-guide-to-fungible-tokens-by-dhruv-patel-5e052a1fca64">The Complete Guide to SPL Tokens on Solana By Dhruv Patel</a></h4><h4>🪜 Step 6: <a href="https://medium.com/@d7511162/complete-guide-to-solana-spl-token-creation-by-dhruv-patel-4d10fd8740e6">Complete Guide to Solana SPL Token Creation By Dhruv patel</a></h4><h4>🪜 Step 7: <a href="https://medium.com/@d7511162/creating-your-own-spl-token-on-solana-a-complete-walkthrough-by-dhruv-patel-3ed39f02a61d">Creating Your Own SPL Token on Solana: A Complete Walkthrough By Dhruv patel</a></h4><h4>🪜 Step 8: <a href="https://medium.com/@d7511162/the-complete-developers-guide-to-smart-contracts-on-solana-by-dhruv-patel-134ebbdb759d">The Complete Developer’s Guide to Smart Contracts on Solana by Dhruv Patel</a></h4><h4>🪜 Step 9: <a href="https://medium.com/@d7511162/building-your-own-token-on-solana-with-anchor-framework-spl-token-guide-by-dhruv-patel-bb0ae6ac2fd4">Building Your Own Token on Solana with Anchor Framework : SPL Token Guide</a></h4><h4>🪜 Step 10: <a href="https://medium.com/@d7511162/building-a-trustless-escrow-smart-contract-on-solana-the-ultimate-guide-by-dhruv-patel-1fa7b41a63ac">Building a Trustless Escrow Smart Contract on Solana: The Ultimate Guide By Dhruv patel</a></h4><h4>🪜 Step 11: <a href="https://medium.com/@d7511162/building-real-world-dapps-smart-contract-on-solana-voting-system-todo-manager-a71ed6ff4821">Building Real-World dApps Smart Contract on Solana: Voting System &amp; ToDo Manager</a></h4><h4>🪜 Step 12: <a href="https://medium.com/@d7511162/building-a-complete-voting-dapp-smart-contract-on-solana-7cbea7380f66">Building a Complete Voting dApp Smart Contract on Solana</a></h4><h4>🪜 Step 13: <a href="https://medium.com/@d7511162/i-built-a-decentralized-voting-platform-on-solana-f91431439475">I Built a Decentralized Voting Platform on Solana</a></h4><h3>🚀 What’s Next?</h3><p>This is just the beginning of the Solana journey.<br>Many more ladders and deep-dive articles are coming soon to take you even further — from advanced smart contracts to real-world production-level dApps.</p><p>📌 Make sure to follow this series and stay updated as new content drops regularly.</p><h3>🤝 Support &amp; Stay Connected</h3><p>If you found this helpful:</p><p>👏 <strong>Clap for the article</strong> — it helps reach more developers<br>🔗 <strong>Share this with your friends or fellow developers</strong><br>🚀 <strong>Follow me on Medium</strong> to stay updated with upcoming articles in this series</p><p>🔥 <strong>Stay tuned, keep learning, and keep building on Solana.</strong><br>🪜 The ladder doesn’t end here — we’re just getting started.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da5044b6a671" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Built a Decentralized Voting Platform on Solana]]></title>
            <link>https://medium.com/@d7511162/i-built-a-decentralized-voting-platform-on-solana-f91431439475?source=rss-8de3c9502bfd------2</link>
            <guid isPermaLink="false">https://medium.com/p/f91431439475</guid>
            <category><![CDATA[solana-blockchain]]></category>
            <category><![CDATA[blockchain-project]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[blockchain-development]]></category>
            <category><![CDATA[web3]]></category>
            <dc:creator><![CDATA[Dhruv Patel]]></dc:creator>
            <pubDate>Fri, 20 Mar 2026 16:55:02 GMT</pubDate>
            <atom:updated>2026-03-23T18:40:06.419Z</atom:updated>
            <content:encoded><![CDATA[<p>Proposal to earn, vote to decide; admin profits through proposal and transaction fees.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-Kmy9wF8zFoJVf_kTO9hnw.png" /><figcaption>THE FLOW OF OUR APP</figcaption></figure><blockquote><em>⚠️ </em><strong><em>Note for Readers</em></strong></blockquote><blockquote><em>This article is part of my Solana learning series.</em></blockquote><blockquote><em>👉 Before continuing, I highly recommend checking the complete series here:<br></em><a href="https://medium.com/@d7511162/the-solana-learning-ladder-by-dhruv-patel-da5044b6a671"><strong><em>View Full Solana Series</em></strong></a></blockquote><blockquote><em>Following the series in order will give you a much better understanding.</em></blockquote><blockquote><em>However, if you are already familiar with the basics, feel free to continue with this article.</em></blockquote><h3>📚 Full Code &amp; Resources</h3><p>If you’d like to explore this project in more detail, here are all the relevant resources:</p><h4>🎥 YouTube (Full Explanation Video)</h4><p>Watch the complete walkthrough of this project with step-by-step explanation:<br><a href="https://www.youtube.com/watch?v=Ki4D0Y1DmxM&amp;t=68s"><strong>https://www.youtube.com/watch?v=Ki4D0Y1DmxM&amp;t=68s</strong></a></p><h4>🔗 GitHub (Complete Code)</h4><p>You can check out the full implementation, smart contracts, and project structure here:<br><a href="https://github.com/Dhruv-0101/POLL-SOLANA-VOTING-APP.git"><strong>https://github.com/Dhruv-0101/POLL-SOLANA-VOTING-APP.git</strong></a></p><h4>🌐 Live Demo (Optional)</h4><p>you can try out the project here:<br><a href="https://poll-solana-voting-app.vercel.app/"><strong>https://poll-solana-voting-app.vercel.app/</strong></a></p><h4>📝 Medium (Detailed Articles)</h4><p>I’ve written in-depth articles explaining concepts like how Solana works, Solana account model, SPL token, anchor framework, escrow mechanism, and more:<br><a href="https://www.linkedin.com/safety/go?url=https%3A%2F%2Fmedium.com%2F%40d7511162&amp;trk=flagship-messaging-web&amp;messageThreadUrn=urn%3Ali%3AmessagingThread%3A2-OTc2ZjY3NjItZGUxZC00NDBkLTgwMTEtZDk4N2M0ZWM2MjM4XzEwMA%3D%3D"><strong>https://medium.com/@d7511162</strong></a></p><p>If you’re interested in learning Solana development from scratch to advanced concepts, make sure to explore my Medium articles — they cover everything in a structured way.</p><h4>If you found this helpful:<br>Clap 👏 Share 🔁 Follow 🚀</h4><h4>Thanks for reading ❤️</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f91431439475" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Complete Voting dApp Smart Contract on Solana]]></title>
            <link>https://medium.com/@d7511162/building-a-complete-voting-dapp-smart-contract-on-solana-7cbea7380f66?source=rss-8de3c9502bfd------2</link>
            <guid isPermaLink="false">https://medium.com/p/7cbea7380f66</guid>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[solana-network]]></category>
            <category><![CDATA[solana-blockchain]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[blockchain-technology]]></category>
            <dc:creator><![CDATA[Dhruv Patel]]></dc:creator>
            <pubDate>Thu, 19 Mar 2026 06:27:03 GMT</pubDate>
            <atom:updated>2026-03-23T18:38:24.630Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>A full-stack governance system with token sales, proposals, voting, and winner declaration</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f57xu5HMWdTav9-utmgaag.png" /></figure><blockquote><em>⚠️ </em><strong><em>Note for Readers</em></strong></blockquote><blockquote><em>This article is part of my Solana learning series.</em></blockquote><blockquote><em>👉 Before continuing, I highly recommend checking the complete series here:<br></em><a href="https://medium.com/@d7511162/the-solana-learning-ladder-by-dhruv-patel-da5044b6a671"><strong><em>View Full Solana Series</em></strong></a></blockquote><blockquote><em>Following the series in order will give you a much better understanding.</em></blockquote><blockquote><em>However, if you are already familiar with the basics, feel free to continue with this article.</em></blockquote><h4>📺 Tutorial Credit</h4><p>This project is built by following the excellent tutorial by <strong>Code Eater</strong> on YouTube. If you want to see the code being built step-by-step with detailed explanations, check out the original video:</p><p>🎥 <a href="https://youtu.be/VrOedBsazKE"><strong>Solana Voting dApp Tutorial — Code Eater</strong></a></p><p>This article serves as a comprehensive written guide with all code comments and additional explanations for better understanding.</p><h4>🎯 Introduction</h4><p>Welcome to the ultimate guide for building a production-ready voting platform on Solana! This isn’t just a simple voting system — it’s a <strong>complete tokenomics-driven governance platform</strong> with built-in economic incentives.</p><p><strong>What we’re building:</strong></p><ul><li>🎫 Token sale system (users buy voting tokens with SOL)</li><li>📝 Proposal marketplace (anyone can create proposals by paying fees)</li><li>🗳️ Secure voting mechanism (one person, one vote on only on proposal from many proposals)</li></ul><p><strong>The Economics:</strong></p><pre>1. Admin sells tokens → Collects SOL<br>2. Users pay token fees → Tokens return to treasury<br>3. Admin can resell/burn/reward → Sustainable economy</pre><p><strong>By the end, you’ll master:</strong></p><ul><li>Token-based governance systems</li><li>Treasury and vault management</li><li>PDA-based state accounts</li><li>Cross-program invocations (CPI)</li><li>Event emission for frontend integration</li><li>Production-grade error handling</li><li>Rent recovery mechanisms</li></ul><h4>The Tokenomics Flow</h4><pre>STEP 1: TOKEN SALE<br>├─ User pays SOL<br>├─ Receives X Tokens<br>└─ Can now participate in governance<br><br>STEP 2: CREATE PROPOSAL<br>├─ Creator pays token fee<br>├─ Proposal gets unique ID<br>└─ Tokens go to treasury vault<br><br>STEP 3: REGISTER &amp; VOTE<br>├─ Voter registers (one-time)<br>├─ Pays token fee per vote<br>└─ Vote recorded immutably<br><br>STEP 4: DECLARE WINNER<br>├─ Admin calls pick_winner<br>├─ Highest votes wins<br>└─ Results stored permanently<br><br>STEP 5: CLEANUP<br>├─ Close proposal accounts<br>├─ Close voter accounts<br>└─ Recover rent (SOL refund)</pre><h4>💰 Understanding the Economic Model</h4><h4>FEEL POINT: ADMIN’S DOUBLE ADVANTAGE 🤑</h4><p>Here’s the genius economics of this system:</p><p><strong>Phase 1: Token Sale</strong></p><pre>Admin creates 1,000,000 tokens<br>↓<br>Users buy tokens with SOL<br>↓<br>Admin collects SOL revenue</pre><p><strong>Phase 2: Fee Collection</strong></p><pre>Users spend tokens on:<br>├─ Creating proposals<br>└─ Casting votes<br>↓<br>Tokens return to treasury vault</pre><p><strong>Phase 3: Token Recycling</strong></p><pre>Admin now has tokens back and can:<br>├─ Resell to new users (more SOL!) ♻️<br>├─ Burn to reduce supply (scarcity) 🔥<br>└─ Distribute as rewards (incentives) 🎁</pre><p><strong>The Double Benefit:</strong></p><pre>1. First: Admin SOLD you tokens → Got your SOL 💰<br>2. Then: You PAY back those tokens as fees<br>3. Result: Tokens are Admin&#39;s property again!</pre><p><strong>This is how real protocols work:</strong></p><ul><li><strong>Ethereum</strong>: You buy ETH, then pay gas fees with it</li><li><strong>Uniswap</strong>: You buy UNI, then use it for governance</li><li><strong>Our System</strong>: Buy X tokens, pay them as voting fees</li></ul><p><strong>TOKEN LIFECYCLE:</strong></p><pre>Tokens deposited into &#39;treasury_token_account&#39;. Admin can:<br>- Resell them to new users again (Recycling).<br>- Burn them to reduce supply and increase value.<br>- Distribute them as rewards to active voters.<br><br>In short: These tokens are now Admin&#39;s property!</pre><h4>📁 File 1: state.rs — The Data Structures</h4><p>This file defines all the accounts that store data on the blockchain.</p><pre>use anchor_lang::prelude::*;<br><br>// --- TREASURY CONFIGURATION ---<br>// This account stores all the main system settings.<br>// Who is the admin, which token is being used, what&#39;s the SOL price, etc.<br>#[account]<br>#[derive(InitSpace)]<br>pub struct TreasuryConfig {<br>    // Admin&#39;s public key (the one who can withdraw SOL)<br>    pub authority: Pubkey,<br>    <br>    // The token used for voting (X Token)<br>    pub x_mint: Pubkey,<br>    <br>    // System&#39;s Main Treasury (Vault). When someone creates a Proposal or casts a Vote,<br>    // the Token Fees they pay get collected and deposited into this account.<br>    // Creator launches an election. They have to pay some tokens as a fee.<br>    pub treasury_token_account: Pubkey,<br>    <br>    /*<br>       FEEL POINT: ADMIN&#39;S ADVANTAGE (Tokenomics) 🤑<br>       Bro, here the Admin is getting double benefits:<br>       1. First, Admin &#39;Sold&#39; you tokens and took your SOL.<br>       2. Now you&#39;re giving back those same tokens to Admin as &#39;Fees&#39;.<br><br>       TOKEN LIFECYCLE:<br>       Tokens are being deposited into &#39;treasury_token_account&#39;. Admin can now:<br>       - Either resell them to new users again (Recycling).<br>       - Or &#39;Burn&#39; them to reduce supply.<br>       - Or distribute them as rewards.<br>       In short, these tokens are now Admin&#39;s property!<br>    */<br>    <br>    // How much SOL is needed to purchase 1 token<br>    pub sol_price: u64,<br>    <br>    // How many tokens you get in one purchase<br>    pub tokens_per_purchase: u64,<br>    <br>    // PDA bump (for security)<br>    pub bump: u8,<br>}<br><br>// --- VOTER ACCOUNT ---<br>// Every voter gets a unique account.<br>// This ensures that one person can only vote once.<br>#[account]<br>#[derive(InitSpace)]<br>pub struct Voter {<br>    // Voter&#39;s wallet address<br>    pub voter_id: Pubkey,<br>    <br>    // Which proposal ID they voted for (0 means haven&#39;t voted yet)<br>    pub proposal_voted: u8,<br>}<br><br>// --- PROPOSAL ACCOUNT ---<br>// When someone registers a new proposal (like &quot;Which feature should be next?&quot;).<br>#[account]<br>#[derive(InitSpace)]<br>pub struct Proposal {<br>    // Unique ID for this proposal<br>    pub proposal_id: u8,<br>    <br>    // How many votes this proposal has received so far<br>    pub number_of_votes: u8,<br>    <br>    // When can people vote until (Timestamp)<br>    pub deadline: i64,<br>    <br>    // Brief description about the proposal<br>    #[max_len(50)]<br>    pub proposal_info: String,<br>    <br>    // Who created this proposal (Creator)<br>    pub authority: Pubkey,<br>}<br><br>// --- PROPOSAL COUNTER ---<br>// This is a global counter that tracks how many proposals have been created in total.<br>#[account]<br>#[derive(InitSpace)]<br>pub struct ProposalCounter {<br>    // Counter&#39;s authority<br>    pub authority: Pubkey,<br>    <br>    // What the next proposal ID will be<br>    pub proposal_count: u8,<br>}<br><br>// --- WINNER ACCOUNT ---<br>// Final results are stored here.<br>#[account]<br>#[derive(InitSpace)]<br>pub struct Winner {<br>    // The winning proposal ID<br>    pub winning_proposal_id: u8,<br>    <br>    // How many votes it received<br>    pub winning_votes: u8,<br>    <br>    // Winner proposal&#39;s info<br>    #[max_len(50)]<br>    pub proposal_info: String,<br>    <br>    // When the winner was declared<br>    pub declared_at: i64,<br>}</pre><h4><strong>What each account does:</strong></h4><p><strong>TreasuryConfig</strong> — The Control Center</p><ul><li>Stores system configuration</li><li>Defines token economics</li><li>Links to treasury vault</li><li>Controls admin access</li></ul><p><strong>Voter</strong> — One Person, One Vote</p><ul><li>Prevents double voting</li><li>Tracks which proposal user voted for</li><li>Linked to user’s wallet</li></ul><p><strong>Proposal</strong> — The Ballot</p><ul><li>Stores proposal details</li><li>Counts votes</li><li>Enforces deadlines</li><li>Links to creator</li></ul><p><strong>ProposalCounter</strong> — Sequential ID Generator</p><ul><li>Generates unique IDs</li><li>Prevents ID conflicts</li><li>Like auto-increment in databases</li></ul><p><strong>Winner</strong> — The Results</p><ul><li>Permanent record</li><li>Transparent and immutable</li><li>Can be queried anytime</li></ul><h4>📁 File 2: errors.rs — Error Handling</h4><p>Custom errors make debugging easier and provide clear feedback to users.</p><pre>use anchor_lang::prelude::*;<br><br>// =============================================================================<br>// VOTE ERRORS - When something goes wrong, these codes appear<br>// =============================================================================<br>#[error_code]<br>pub enum VoteError {<br>    #[msg(&quot;Deadline must be a future timestamp&quot;)]<br>    InvalidDeadline,<br>    // Deadline can&#39;t be in the past.<br>    <br>    #[msg(&quot;Proposal counter has already been initialized&quot;)]<br>    ProposalCounterAlreadyInitialized,<br>    // The shop only opens once, bro!<br><br>    #[msg(&quot;Maximum proposal limit reached&quot;)]<br>    ProposalCounterOverflow,<br>    // When there are too many proposals.<br><br>    #[msg(&quot;Voting period has ended for this proposal&quot;)]<br>    ProposalEnded,<br>    // Time&#39;s up, can&#39;t vote anymore.<br><br>    #[msg(&quot;Vote count overflow - maximum votes exceeded&quot;)]<br>    ProposalVotesOverflow,<br>    // Vote limit has been exceeded.<br><br>    #[msg(&quot;Cannot declare winner while voting is still active&quot;)]<br>    VotingStillActive,<br>    // Let the voting finish first!<br><br>    #[msg(&quot;No votes have been cast for this proposal&quot;)]<br>    NoVotesCast,<br>    // If no one voted, how can there be a winner?<br><br>    #[msg(&quot;You are not authorized to perform this action&quot;)]<br>    UnauthorizedAccess,<br>    // This is beyond your authority, ask the Admin.<br>    <br>    #[msg(&quot;Token mint does not match the expected mint&quot;)]<br>    TokenMintMismatch,<br>    // You brought the wrong token.<br><br>    #[msg(&quot;Voter has already voted on this proposal&quot;)]<br>    VoterAlreadyVoted,<br>    // One vote is enough, not again!<br><br>    #[msg(&quot;Token account is not owned by the expected wallet&quot;)]<br>    InvalidTokenAccountOwner,<br>    // This wallet doesn&#39;t seem to be yours.<br><br>    #[msg(&quot;Provided mint account is invalid&quot;)]<br>    InvalidMint,<br>    // The Token Mint itself is wrong.<br>}</pre><p><strong>Error Categories:</strong></p><p><strong>Authorization Errors:</strong></p><ul><li>UnauthorizedAccess - Not authorized (ask Admin)</li><li>InvalidTokenAccountOwner - Wrong wallet ownership</li></ul><p><strong>Validation Errors:</strong></p><ul><li>InvalidDeadline - Deadline in the past</li><li>TokenMintMismatch - Wrong token type</li><li>InvalidMint - Invalid token mint</li></ul><p><strong>State Errors:</strong></p><ul><li>ProposalCounterAlreadyInitialized - Already set up</li><li>VoterAlreadyVoted - Already cast a vote</li><li>ProposalEnded - Voting period over</li></ul><p><strong>Overflow Errors:</strong></p><ul><li>ProposalCounterOverflow - Too many proposals</li><li>ProposalVotesOverflow - Too many votes</li></ul><p><strong>Logic Errors:</strong></p><ul><li>VotingStillActive - Can&#39;t declare winner yet</li><li>NoVotesCast - No votes to count</li></ul><h4>📁 File 3: events.rs — System Announcements</h4><p>Events are how the blockchain broadcasts what’s happening inside the program, enabling real-time updates on the Frontend (Website).</p><pre>use anchor_lang::prelude::*;<br><br>/* <br>================================================================================<br>EVENTS: System Announcements<br>================================================================================<br>Their job is to tell the world what&#39;s happening inside the Program.<br>So that real-time updates can appear on the Frontend (Website).<br>*/<br><br>#[event]<br>pub struct ProposalCounterInitialized {<br>    pub authority: Pubkey,<br>    pub timestamp: i64,<br>}<br><br>#[event]<br>pub struct VoterRegistered {<br>    pub voter: Pubkey,<br>    pub voter_account: Pubkey,<br>    pub timestamp: i64,<br>}<br><br>#[event]<br>pub struct ProposalCreated {<br>    pub proposal_id: u8,<br>    pub creator: Pubkey,<br>    pub proposal_info: String,<br>    pub deadline: i64,<br>    pub timestamp: i64,<br>}<br><br>#[event]<br>pub struct VoteCast {<br>    pub voter: Pubkey,<br>    pub proposal_id: u8,<br>    pub total_votes: u8,<br>    pub timestamp: i64,<br>}<br><br>#[event]<br>pub struct WinnerDeclared {<br>    pub winning_proposal_id: u8,<br>    pub proposal_info: String,<br>    pub total_votes: u8,<br>    pub declared_by: Pubkey,<br>    pub timestamp: i64,<br>}<br><br>#[event]<br>pub struct ProposalClosed {<br>    pub proposal_id: u8,<br>    pub rent_recovered: u64,<br>    pub recovered_to: Pubkey,<br>    pub timestamp: i64,<br>}<br><br>#[event]<br>pub struct VoterAccountClosed {<br>    pub voter: Pubkey,<br>    pub rent_recovered_to: Pubkey,<br>    pub timestamp: i64,<br>}<br><br>#[event]<br>pub struct TreasuryInitialized {<br>    pub authority: Pubkey,<br>    pub x_mint: Pubkey,<br>    pub sol_price: u64,<br>    pub tokens_per_purchase: u64,<br>    pub timestamp: i64,<br>}<br><br>#[event]<br>pub struct TokensPurchased {<br>    pub buyer: Pubkey,<br>    pub sol_paid: u64,<br>    pub tokens_received: u64,<br>    pub timestamp: i64,<br>}<br><br>#[event]<br>pub struct SolWithdrawn {<br>    pub authority: Pubkey,<br>    pub amount: u64,<br>    pub timestamp: i64,<br>}</pre><p><strong>Why Events Matter:</strong></p><p><strong>Frontend Integration:</strong></p><pre>// Listen to events in real-time<br>program.addEventListener(&#39;VoteCast&#39;, (event) =&gt; {<br>  console.log(`Vote on proposal ${event.proposal_id}`);<br>  updateVoteCount(event.total_votes);<br>});</pre><p><strong>Analytics &amp; Transparency:</strong></p><ul><li>Track voting trends</li><li>Monitor token flows</li><li>Audit the system</li><li>Verify vote counts</li></ul><h4>📁 File 4: contexts.rs — Account Validation (The Heart!)</h4><p>This is where ALL the magic happens! Every instruction needs specific accounts, and this file defines exactly which accounts are required and how they should be validated.</p><pre>use anchor_lang::prelude::*;<br>use crate::state::*;<br>use crate::errors::*;<br>use anchor_spl::{<br>    associated_token::AssociatedToken,<br>    token::{Mint, Token, TokenAccount}<br>};<br><br>// =============================================================================<br>// 1. INITIALIZE TREASURY - System Foundation (Shop Setup)<br>// =============================================================================<br>// This structure tells Solana which virtual &#39;Houses&#39; (Accounts) we&#39;ll need<br>// when we run the &#39;initialize_treasury&#39; function.<br>#[derive(Accounts)]<br>pub struct InitializeTreasury&lt;&#39;info&gt; {<br>    <br>    // Admin&#39;s wallet - This person will pay Rent (SOL) for all new accounts.<br>    #[account(mut)]<br>    pub authority: Signer&lt;&#39;info&gt;, <br><br>    // TREASURY CONFIG ACCOUNT: We save all system settings here.<br>    // &#39;init&#39; = We&#39;re creating a new account.<br>    // &#39;payer&#39; = The rent bill goes to &#39;authority&#39;.<br>    // &#39;space&#39; = How much hard drive space needed (8 bytes Anchor discriminator + Data size).<br>    // &#39;seeds&#39; = This account&#39;s Unique Name (PDA address generator).<br>    /* <br>       FEEL POINT: WHAT IS BUMP? (The Push 👊)<br>       In Solana, PDA addresses must be off the curve. Sometimes the address<br>       from seeds lands on the curve. So we add an extra number (Bump) to<br>       &#39;push&#39; the address off the curve (255, 254, 253...).<br>       The first number that works is the &#39;Bump&#39;!<br>    */<br>     /* <br>       FEEL POINT: SEEDS AND BUMP GAME 🎮<br>       1. [Seeds + Bump] ➔ Real PDA! (Program controls it, address from formula).<br>       2. [Only Seeds]   ➔ Error! (Need Bump to push address off curve).<br>       3. [No Seeds/No Bump] ➔ Regular Account (Like Admin&#39;s wallet, needs Keypair).<br>       <br>       Conclusion: Need a program-controlled &quot;Personal Locker&quot;? Both are essential!<br>    */<br>    #[account(<br>        init,<br>        payer = authority,<br>        space = 8 + TreasuryConfig::INIT_SPACE,<br>        seeds = [b&quot;treasury_config&quot;],<br>        bump<br>    )]<br>    pub treasury_config_account: Account&lt;&#39;info, TreasuryConfig&gt;, <br>    <br>    // X MINT: Our own new Custom Token! <br>    // We&#39;ll derive its address from &#39;x_mint&#39; seed.<br>    #[account(<br>        init,<br>        payer = authority,<br>        mint::authority = mint_authority, // Only &#39;mint_authority&#39; PDA can create new tokens (mint).<br>        mint::decimals = 6,               // 1 Token = 1,000,000 micro-tokens<br>        seeds = [b&quot;x_mint&quot;],<br>        bump<br>    )]<br>    pub x_mint: Account&lt;&#39;info, Mint&gt;, <br>    <br>    // TREASURY TOKEN ACCOUNT: Admin&#39;s wallet where system earnings (Fees) as tokens get collected.<br>    // This is called an &#39;ATA&#39; (Associated Token Account).<br>    /* <br>       FEEL POINT: WHY NO SEEDS/BUMP IN ATA? 🤔<br>       The above 2 accounts (Config and Mint) are &#39;Custom PDAs&#39;, so we<br>       named them ourselves with Seeds.<br>       <br>       But this &#39;treasury_token_account&#39; is a STANDARD account (ATA).<br>       In Solana, ATA address formula is fixed:<br>       [Authority + Token Program + Mint].<br>       <br>       Since the formula is fixed, Anchor doesn&#39;t need us to tell it<br>       &#39;seeds&#39; separately. Anchor calculates the address using the formula<br>       behind the scenes!<br><br>       ---<br>       NEW ADDITION: ATA CREATION &quot;INGREDIENTS&quot; LIST 📋<br>       In Anchor, to &#39;init&#39; an ATA, these 3 things are MANDATORY:<br>       1. associated_token::mint      ➔ Which token is this wallet for?<br>       2. associated_token::authority ➔ Who is the real owner of this wallet?<br>       3. Programs (But these are defined in the Context below).<br>    */<br>    #[account(<br>        init,<br>        payer = authority,<br>        associated_token::mint = x_mint,<br>        associated_token::authority = authority,<br>    )]<br>    pub treasury_token_account: Account&lt;&#39;info, TokenAccount&gt;, <br><br><br>    // PROPOSAL COUNTER: A global account that tracks how many proposals have been created.<br>    #[account(<br>        init,<br>        payer = authority,<br>        space = 8 + ProposalCounter::INIT_SPACE,<br>        seeds = [b&quot;proposal_counter&quot;],<br>        bump<br>    )]<br>    pub proposal_counter_account: Account&lt;&#39;info, ProposalCounter&gt;, <br><br><br>    // SOL VAULT: This is a &quot;Treasury&quot; (Piggy Bank). When people buy tokens, their SOL<br>    // comes into this PDA account and stays safe.<br>    /* <br>       FEEL POINT: DESERIALIZATION TROUBLE (🧱 -&gt; 📦)<br>       1. What is Deserialization? <br>          Blockchain data is in 0s and 1s (Bytes). Converting Bytes back into<br>          Rust structs so we can read `account.data` is called Deserialization.<br>       <br>       2. Account&lt;&#39;info, T&gt; vs AccountInfo&lt;&#39;info&gt;<br>          - Account&lt;&#39;info, Proposal&gt;: Tells Anchor to open the box and read the note (Deserialize).<br>          - AccountInfo&lt;&#39;info&gt;: Tells Anchor just show address and balance (Lamports),<br>            no need to open the box (Deserialize).<br>       <br>       3. Why AccountInfo for sol_vault? <br>          This is just a &quot;Piggy Bank&quot; where SOL will be deposited. We haven&#39;t saved any<br>          ID or Name inside it (EMPTY box). When there&#39;s no data, what will we get by<br>          opening the box (Deserialize)? Nothing!<br>          So we use direct AccountInfo to save rent and make work easier.<br><br>       ---<br>       NEW ADDITION: SOL VAULT vs TREASURY 🤔<br>       - sol_vault: Only SOL gets deposited here (When people buy tokens). Its job is to store Admin&#39;s earnings (Cash).<br>       - treasury_token_account: Only X-TOKENS get deposited here (Fees). Its job is to collect program&#39;s tokens back.<br>       <br>       Meaning: One has &#39;Cash&#39; (SOL) and one has &#39;Points&#39; (Tokens). They won&#39;t mix!<br>    */<br>    /// CHECK: This is just a PDA that will hold SOL.<br>    #[account(mut, seeds = [b&quot;sol_vault&quot;], bump)]<br>    pub sol_vault: AccountInfo&lt;&#39;info&gt;, <br><br>    // MINT AUTHORITY: This is the &quot;Key&quot; (PDA). Only it has the power to create X-Tokens.<br>    /// CHECK: This is a signature-less PDA that will act as authority.<br>    #[account(seeds = [b&quot;mint_authority&quot;], bump)]<br>    pub mint_authority: AccountInfo&lt;&#39;info&gt;, <br><br>    // Solana&#39;s standard programs - Without these we can&#39;t do token or data manipulation.<br>    pub token_program: Program&lt;&#39;info, Token&gt;,<br>    pub associated_token_program: Program&lt;&#39;info, AssociatedToken&gt;,<br>    pub system_program: Program&lt;&#39;info, System&gt;<br>}<br><br>// =============================================================================<br>// 2. BUY TOKENS - User gives SOL and buys Tokens<br>// =============================================================================<br>#[derive(Accounts)]<br>pub struct BuyTokens&lt;&#39;info&gt; {<br>    <br>    // Fetch config to know what the token rate is.<br>   #[account(<br>        seeds = [b&quot;treasury_config&quot;],<br>        bump,<br>        constraint = treasury_config_account.x_mint == x_mint.key() @ VoteError::InvalidMint<br>    )]<br>    pub treasury_config_account: Account&lt;&#39;info, TreasuryConfig&gt;,<br>    <br>    // Where buyer&#39;s SOL will go.<br>    /// CHECK: Validated via seeds.<br>    #[account(mut, seeds = [b&quot;sol_vault&quot;], bump = treasury_config_account.bump)]<br>    pub sol_vault: AccountInfo&lt;&#39;info&gt;, <br><br><br>    // NOTE: This account is technically &#39;USELESS&#39; here.<br>    // It&#39;s not being used in the logic because we&#39;re MINTING tokens,<br>    // not transferring from Treasury. But since it&#39;s here, let it stay, no harm done!<br>    #[account(mut)]<br>    pub treasury_token_account: Account&lt;&#39;info, TokenAccount&gt;, <br><br>    #[account(mut)]<br>    pub x_mint: Account&lt;&#39;info, Mint&gt;, <br><br>    // Buyer&#39;s Token Wallet - Where new tokens will be delivered.<br>    /* <br>       FEEL POINT: WHY NO &#39;INIT&#39; HERE? 🤔<br>       Previous Logic: You caught it right! To receive new tokens, an ATA should exist. But<br>       we didn&#39;t use &#39;init&#39; here because we gave this responsibility to the FRONTEND (Test file).<br>       <br>       1. Frontend Check: Our test file checks before sending the transaction:<br>          &quot;Is the &#39;Wallet&#39; (ATA) already created? If not, create it there.&quot;<br>       <br>       2. Why? ➔ So the program stays simple and doesn&#39;t use extra compute units (gas).<br>       <br>       3. Pro Tip: If you want the program to create it itself, we can use Anchor&#39;s<br>          &#39;init_if_needed&#39; attribute. But for now, the Frontend is handling it.<br><br>       ---<br>       REAL FEEL: &quot;DELIVERY vs BOX MAKING&quot; 📦🏠<br>       Imagine you ordered goods from Amazon (Vote App):<br><br>       1. Program (Shop/Delivery Boy): 🚚<br>          The delivery boy says—&quot;I&#39;ll come to your house (Wallet) with tokens, but<br>          there should already be a &#39;Box to keep items&#39; (Token Account/ATA) outside<br>          your house. I won&#39;t make the box myself, I&#39;ll just put items in it.&quot;<br>       <br>       2. Frontend (User): 🔍<br>          Before sending the transaction, you think—&quot;Oh, the delivery boy is coming,<br>          is there a box outside my house?&quot;<br>          - If box already exists, you send the address directly.<br>          - If box doesn&#39;t exist, you immediately call a Carpenter (Token Program),<br>            get the box made, and then tell the delivery boy—&quot;Now put the items in.&quot;<br><br>       3. Where does this happen in Frontend? (The Proof) 🔍<br>          In test file (tests/vote_app.ts), see this line:<br>```typescript<br>          const buyerATA = await getOrCreateAssociatedTokenAccount(<br>             connection, buyer, xMint, buyer.publicKey<br>          );<br>```<br>          This line is that &quot;Carpenter&quot; that checks or creates the box.<br><br>       4. Then why so much code in Program (Rust)? 🤔<br>          - constraint=buyer_token_account.owner == buyer.key()<br>          - constraint=buyer_token_account.mint == x_mint.key()<br>          <br>          These lines are the program&#39;s &quot;Security Guard&quot; 👮‍♂️. Before the delivery<br>          boy puts items in the box, he just checks: &quot;Is this box really this<br>          person&#39;s?&quot; and &quot;Is this box for this token?&quot;. Simple!<br>    */<br>    #[account(<br>        mut,<br>        constraint = buyer_token_account.owner == buyer.key() @ VoteError::InvalidTokenAccountOwner,<br>        constraint = buyer_token_account.mint == x_mint.key() @ VoteError::InvalidMint,<br>    )]<br>    pub buyer_token_account: Account&lt;&#39;info, TokenAccount&gt;, <br><br>    // The authority that has &quot;Create Tokens&quot; permission.<br>    /// CHECK: Validated via seeds.<br>    #[account(seeds = [b&quot;mint_authority&quot;], bump)]<br>    pub mint_authority: AccountInfo&lt;&#39;info&gt;, <br><br>    #[account(mut)]<br>    pub buyer: Signer&lt;&#39;info&gt;, // The person giving money and signing the transaction.<br><br>    pub token_program: Program&lt;&#39;info, Token&gt;,<br>    pub system_program: Program&lt;&#39;info, System&gt;<br>}<br><br><br>// =============================================================================<br>// 3. REGISTER VOTER - Voter&#39;s Digital Entry<br>// =============================================================================<br>#[derive(Accounts)]<br>pub struct RegisterVoter&lt;&#39;info&gt; {<br>    #[account(mut)]<br>    pub authority: Signer&lt;&#39;info&gt;, <br><br>    // Each voter gets a Unique Account.<br>    /*<br>       FEEL POINT: GLOBAL VOTER vs PER-PROPOSAL VOTE 🤔<br>       <br>       1. CURRENT DESIGN (Global Voter ID):<br>       Seeds [b&quot;voter&quot;, authority] ➔ Means: One User = Only One Voter Account.<br>       <br>       FEEL IT: 🗳️<br>       This is exactly like you getting a &quot;Voter ID Card&quot;. You go to any election<br>       booth, vote, and the officer puts a &#39;Permanent Ink Mark&#39; (Stamp) on your<br>       card: `proposal_voted = 1`.<br>       <br>       Now if you go to vote on another proposal, the Security Guard (Constraint)<br>       will check your card: `constraint = voter_account.proposal_voted == 0`.<br>       Since the stamp is already there (not zero), he&#39;ll push you out! ❌<br>       <br>       RESULT: In the current design, one person can only vote once in the entire system.<br><br>       ---<br><br>       2. WHAT IF WE WANT TO VOTE ON MULTIPLE PROPOSALS? (Per-Proposal PDA):<br>       If we want users to vote on both Proposal A and Proposal B,<br>       we&#39;d need to change the PDA Seeds:<br>```rust<br>       // If we do this (Not current code, but possible):<br>       seeds = [b&quot;voter&quot;, authority.key().as_ref(), &amp;proposal_id.to_le_bytes()]<br>```<br>       FEEL IT: 🎫<br>       Now for each Proposal, a new PDA (New Entry Ticket) will be created for the user.<br>       - Proposal #1 Ticket Address: [voter, You, 1] ➔ New PDA created.<br>       - Proposal #2 Ticket Address: [voter, You, 2] ➔ Another New PDA created.<br><br>       BENEFIT/DRAWBACK:<br>       - BENEFIT: User can vote on every proposal (Unlimited Rides).<br>       - DRAWBACK: User has to pay a little Rent (SOL) for each new account for each vote.<br><br>       🌯 SUMMARY FOR WOW FEEL:<br>       - Global Design (Current): Only one account, state gets updated. User is &quot;Locked&quot;. 🔒<br>         (Like: One Aadhaar card, use only once).<br>       - Per-Proposal Design: Each vote is a new account (PDA). (Like: Separate ticket for each ride). 🎫<br>    */<br>    #[account(<br>        init,<br>        payer = authority,<br>        space = 8 + Voter::INIT_SPACE,<br>        seeds = [b&quot;voter&quot;, authority.key().as_ref()],<br>        bump<br>    )]<br>    pub voter_account: Account&lt;&#39;info, Voter&gt;, <br><br>    pub system_program: Program&lt;&#39;info, System&gt;<br>}<br><br>// =============================================================================<br>// 4. REGISTER PROPOSAL - Create a new Proposal (Fee applies)<br>// =============================================================================<br>#[derive(Accounts)]<br>pub struct RegisterProposal&lt;&#39;info&gt; {<br>    #[account(mut)]<br>    pub authority: Signer&lt;&#39;info&gt;, <br><br>    // Proposal&#39;s account - Address will be generated using &quot;Proposal ID&quot;.<br>    #[account(<br>        init,<br>        payer = authority,<br>        space = 8 + Proposal::INIT_SPACE,<br>        seeds = [b&quot;proposal&quot;, proposal_counter_account.proposal_count.to_be_bytes().as_ref()],<br>        bump<br>    )]<br>    pub proposal_account: Account&lt;&#39;info, Proposal&gt;, <br>    <br>    #[account(mut)]<br>    pub proposal_counter_account: Account&lt;&#39;info, ProposalCounter&gt;, <br><br>    pub x_mint: Account&lt;&#39;info, Mint&gt;,<br><br>    // Creator&#39;s wallet where they&#39;ll pay Token Fees from.<br>    #[account(<br>        mut,<br>        constraint = proposal_token_account.mint == x_mint.key(),<br>        constraint = proposal_token_account.owner == authority.key()<br>    )]<br>    pub proposal_token_account: Account&lt;&#39;info, TokenAccount&gt;, <br>    <br>    // System&#39;s treasury where tokens get collected.<br>    #[account(mut, constraint = treasury_token_account.mint == x_mint.key())]<br>    pub treasury_token_account: Account&lt;&#39;info, TokenAccount&gt;, <br><br>    pub token_program: Program&lt;&#39;info, Token&gt;,<br>    pub system_program: Program&lt;&#39;info, System&gt;<br>}<br><br><br>// =============================================================================<br>// 5. VOTE - Cast a vote (Fee applies)<br>// =============================================================================<br>#[derive(Accounts)]<br>#[instruction(proposal_id: u8)] // Taking proposal_id from instruction input<br>pub struct Vote&lt;&#39;info&gt; {<br>    // Check voter&#39;s account - Have they already voted?<br>    #[account(<br>        mut,<br>        seeds = [b&quot;voter&quot;, authority.key().as_ref()],<br>        bump,<br>        constraint = voter_account.proposal_voted == 0 @ VoteError::VoterAlreadyVoted <br>     )]<br>    pub voter_account: Account&lt;&#39;info, Voter&gt;, <br><br>    pub x_mint: Account&lt;&#39;info, Mint&gt;,<br><br>    // Voter will give tokens for the vote.<br>    #[account(<br>         mut,<br>         constraint = voter_token_account.mint == x_mint.key() @ VoteError::TokenMintMismatch,<br>         constraint = voter_token_account.owner == authority.key()<br>     )]<br>    pub voter_token_account: Account&lt;&#39;info, TokenAccount&gt;, <br><br>    #[account(<br>        mut,<br>        constraint = treasury_token_account.mint == x_mint.key()<br>    )]<br>    pub treasury_token_account: Account&lt;&#39;info, TokenAccount&gt;, <br>   <br>    // To update the record of which proposal is being voted on.<br>    #[account(mut, seeds = [b&quot;proposal&quot;, proposal_id.to_be_bytes().as_ref()], bump)]<br>    pub proposal_account: Account&lt;&#39;info, Proposal&gt;, <br><br>    #[account(mut)]<br>    pub authority: Signer&lt;&#39;info&gt;, <br><br>    pub token_program: Program&lt;&#39;info, Token&gt;,<br>}<br><br>// =============================================================================<br>// 6. PICK WINNER - Declare results<br>// =============================================================================<br>#[derive(Accounts)]<br>#[instruction(proposal_id: u8)]<br>pub struct PickWinner&lt;&#39;info&gt; {<br>    // Account to save winner record (The Global Scoreboard).<br>    /* <br>       FEEL POINT: Why &#39;init_if_needed&#39;? (The Smart Switch 💡)<br>       Bro, the &#39;winner&#39; account is only ONE in the entire system.<br>       <br>       1. If only &#39;init&#39;:<br>          The account would be created when the first winner is declared. But<br>          when declaring the second winner, the program would crash because<br>          &quot;Account already exists!&quot;.<br>          <br>       2. If only &#39;Account&#39;:<br>          The first winner could never be declared because the account<br>          doesn&#39;t exist at the start!<br>          <br>       SOLUTION (init_if_needed):<br>       This tells Solana: &quot;Bro, if the board doesn&#39;t exist, CREATE a new one (init),<br>       and if it already exists, just LOAD it (Account) so we can change the<br>       topper&#39;s name.&quot;<br>    */<br>    #[account(<br>        init_if_needed, <br>        payer = authority,<br>        space = 8 + Winner::INIT_SPACE,<br>        seeds = [b&quot;winner&quot;],<br>        bump<br>    )]<br>    pub winner_account: Account&lt;&#39;info, Winner&gt;, <br><br>    // Check the proposal to see how many votes it got.<br>    // Note: Here &#39;to_le_bytes&#39; is being used, pay attention to seeds!<br>    #[account(seeds = [b&quot;proposal&quot;, proposal_id.to_le_bytes().as_ref()], bump)]<br>    pub proposal_account: Account&lt;&#39;info, Proposal&gt;, <br><br>    #[account(mut)]<br>    pub authority: Signer&lt;&#39;info&gt;,<br>    pub system_program: Program&lt;&#39;info, System&gt;,<br>}<br><br>// =============================================================================<br>// 7. CLOSE PROPOSAL - Cleanup Campaign (Process to close account and recover SOL)<br>// =============================================================================<br>#[derive(Accounts)]<br>#[instruction(proposal_id: u8)]<br>pub struct CloseProposal&lt;&#39;info&gt; {<br>    // FEEL POINT: The Magic of &#39;close = destination&#39; ✨<br>    /* <br>       Bro, this is the most &#39;Satisfying&#39; step.<br>       To keep data on Solana, we have to lock some SOL as &#39;Rent&#39;.<br>       <br>       When we write &#39;close = destination&#39;:<br>       1. This account immediately gets DELETED from the blockchain shelf (Delete). 🗑️<br>       2. The &#39;Rent Deposit&#39; (SOL) it was holding gets taken out and goes<br>          straight into the &#39;destination&#39; pocket!<br>          <br>       FEEL IT: This is exactly like when you return your Library Card and get<br>       your &#39;Security Deposit&#39; money back in cash. Money everywhere! 🤑<br>    */<br>    #[account(<br>        mut,<br>        seeds = [b&quot;proposal&quot;, proposal_id.to_le_bytes().as_ref()],<br>        bump,<br>        close = destination, <br>        constraint = proposal_account.authority == authority.key() @ VoteError::UnauthorizedAccess<br>    )]<br>    pub proposal_account: Account&lt;&#39;info, Proposal&gt;,<br><br>    /// CHECK: The account that will receive the rent.<br>    /* <br>       FEEL POINT: What is this &#39;destination&#39;? 🎯<br>       Bro, this is the &#39;Bowl&#39; (Wallet) where the rent money will fall.<br>       <br>       Q: Which account is this?<br>       A: It can be anyone! When you call &#39;close_proposal&#39; from the frontend,<br>          you decide where the money goes.<br>          <br>       - Case 1: If you send your own address in &#39;destination&#39;,<br>         the rent will be refunded to you.<br>       - Case 2: If you want the money to go to some other &#39;Cold Wallet&#39;,<br>         you can send that address here.<br>         <br>       FRONTEND CONNECTION: 🖥️<br>       Bro, this address is decided by your Frontend App (React/JS).<br>       When you write &#39;.accounts({ destination: myWallet })&#39;, that<br>       address comes here as &#39;destination&#39;.<br>       <br>       Meaning: Program just shows the path (Logic),<br>       Destination (Address) is always told by the Frontend!<br>    */<br>    #[account(mut)]<br>    pub destination: AccountInfo&lt;&#39;info&gt;, <br><br>    #[account(mut)]<br>    pub authority: Signer&lt;&#39;info&gt;,<br>}<br><br><br>// =============================================================================<br>// 8. CLOSE VOTER - Voter can recover their rent<br>// =============================================================================<br>#[derive(Accounts)]<br>pub struct CloseVoter&lt;&#39;info&gt; {<br>    /*<br>       Same story here! When the voter deletes their record after<br>       election ends, they get back their voter-card rent deposit (SOL).<br>    */<br>    #[account(<br>        mut,<br>        seeds = [b&quot;voter&quot;, authority.key().as_ref()],<br>        bump,<br>        close = authority // Rent goes back to user (authority) wallet! 💸<br>    )]<br>    pub voter_account: Account&lt;&#39;info, Voter&gt;,<br><br>    #[account(mut)]<br>    pub authority: Signer&lt;&#39;info&gt;,<br>}<br><br>// =============================================================================<br>// 9. WITHDRAW SOL - Admin withdraws SOL from Vault<br>// =============================================================================<br>#[derive(Accounts)]<br>pub struct WithdrawSol&lt;&#39;info&gt; {<br>    // Check if the person is really the Admin?<br>    #[account(<br>        seeds = [b&quot;treasury_config&quot;],<br>        bump,<br>        constraint = treasury_config.authority == authority.key() @ VoteError::UnauthorizedAccess<br>    )]<br>    pub treasury_config: Account&lt;&#39;info, TreasuryConfig&gt;,<br><br>    // Vault where SOL is stored.<br>    /// CHECK: Validated via seeds and TreasuryConfig bump.<br>    #[account(<br>        mut,<br>        seeds = [b&quot;sol_vault&quot;],<br>        bump = treasury_config.bump<br>    )]<br>    pub sol_vault: AccountInfo&lt;&#39;info&gt;,<br><br>    #[account(mut)]<br>    pub authority: Signer&lt;&#39;info&gt;,<br>    pub system_program: Program&lt;&#39;info, System&gt;,<br>}</pre><p><strong>KEY CONCEPTS FROM contexts.rs:</strong></p><p><strong>1. BUMP — The Push 👊</strong></p><pre>PDAs must be off-curve<br>Seeds might land on-curve<br>Bump pushes it off (255, 254...)<br>First number that works = Bump!</pre><p><strong>2. SEEDS vs BUMP Game 🎮</strong></p><pre>[Seeds + Bump] = PDA (program control)<br>[Only Seeds] = Error!<br>[Nothing] = Regular account (needs keypair)</pre><p><strong>3. ATA (Associated Token Account)</strong></p><pre>Standard account with fixed formula<br>No custom seeds needed<br>Anchor calculates automatically</pre><p><strong>4. Deserialization</strong></p><pre>Account&lt;&#39;info, T&gt; = Open and read data<br>AccountInfo&lt;&#39;info&gt; = Just address/balance<br>sol_vault = Empty box, no data to read</pre><p><strong>5. Global Voter vs Per-Proposal</strong></p><pre>Current: One vote per user total<br>Seeds: [b&quot;voter&quot;, user]<br>Result: Locked after voting<br><br>Alternative: Multiple votes possible<br>Seeds: [b&quot;voter&quot;, user, proposal_id]<br>Result: New account per vote</pre><p><strong>6. init_if_needed</strong></p><pre>First time: Creates account<br>Next time: Loads existing account<br>Perfect for winner board!</pre><p><strong>7. close = destination</strong></p><pre>Deletes account<br>Refunds rent to destination<br>Most satisfying feature! 🤑</pre><h4>📁 File 5: lib.rs — The Program Logic (THE BRAIN!)</h4><p>This file is the program’s ‘Brain’. Contexts and State are just structures, but the real ‘Work’ (logic) happens here. Feel every function!</p><pre>use anchor_lang::prelude::*;<br>mod contexts;<br>mod state;<br>use contexts::*;<br>mod errors;<br>use errors::*;<br>mod events;<br>use events::*;<br><br>declare_id!(&quot;Bc58xf4pTsFyTrMVfQXQCdDBu7uG4zqPgKeUMnLsVaZz&quot;);<br>use anchor_lang::system_program;<br>use anchor_spl::token::{mint_to, transfer, MintTo, Transfer};<br><br>/*<br>================================================================================<br>VOTE APP - MAIN LOGIC (THE BRAIN)<br>================================================================================<br>Bro, this file is your program&#39;s &#39;Brain&#39;. Contexts and State are just structures,<br>but the real &#39;Work&#39; (logic) happens here.<br>Feel each function:<br>*/<br><br>#[program]<br>pub mod vote_app {<br>    use super::*;<br><br>    // -------------------------------------------------------------------------<br>    // 1. INITIALIZE TREASURY: Opening the shop for the first time<br>    // -------------------------------------------------------------------------<br>    // Its job is to give life to the entire system.<br>    // We&#39;ll set SOL price, token amount, and counter to zero.<br>    pub fn initialize_treasury(<br>        ctx: Context&lt;InitializeTreasury&gt;,<br>        sol_price: u64, // How many SOL lamports needed to buy 1 Token<br>        tokens_per_purchase: u64, // How many tokens user gets in one purchase<br>    ) -&gt; Result&lt;()&gt; {<br>        // Filling settings into our &#39;treasury_config&#39; account (PDA)<br>        let treasury_config_account = &amp;mut ctx.accounts.treasury_config_account;<br>        treasury_config_account.authority = ctx.accounts.authority.key();<br>        treasury_config_account.bump = ctx.bumps.sol_vault; // Save PDA bump, will be useful later<br>        treasury_config_account.sol_price = sol_price;<br>        treasury_config_account.x_mint = ctx.accounts.x_mint.key();<br>        treasury_config_account.tokens_per_purchase = tokens_per_purchase;<br><br>        // Fire event - So frontend or bots know the system is ready!<br>        emit!(TreasuryInitialized {<br>            authority: ctx.accounts.authority.key(),<br>            x_mint: ctx.accounts.x_mint.key(),<br>            sol_price,<br>            tokens_per_purchase,<br>            timestamp: Clock::get()?.unix_timestamp,<br>        });<br><br>        // Initialize Proposal Counter. By default we start from 1.<br>        let proposal_counter_account = &amp;mut ctx.accounts.proposal_counter_account;<br><br>        // Security check: Is this not already initialized?<br>        require!(<br>            proposal_counter_account.proposal_count &lt;= 1, // If already initialized, count will be 1 or more<br>            VoteError::ProposalCounterAlreadyInitialized<br>        );<br><br>        proposal_counter_account.proposal_count = 1;<br>        proposal_counter_account.authority = ctx.accounts.authority.key();<br><br>        emit!(ProposalCounterInitialized {<br>            authority: ctx.accounts.authority.key(),<br>            timestamp: Clock::get()?.unix_timestamp,<br>        });<br><br>        Ok(())<br>    }<br><br>    // -------------------------------------------------------------------------<br>    // 2. BUY TOKENS: Give SOL, get X-Tokens<br>    // -------------------------------------------------------------------------<br>    // This function&#39;s job is to take SOL from the User and &#39;Create&#39; (Mint) X-Tokens for them.<br>    /*<br>       =========================================================================<br>       🚀 MASTER COMPARISON: DIFFERENCE BETWEEN ALL THREE CPIs (Feel it!)<br>       =========================================================================<br><br>       Bro, imprint this table in your mind, Solana development will become easy:<br><br>       | Feature        | SOL Transfer 🏦      | Token Transfer 💸    | Token Minting 🖨️     |<br>       |----------------|----------------------|----------------------|----------------------|<br>       | Which Manager? | System Program       | Token Program        | Token Program        |<br>       | What work?     | system_program::Xfer | token::transfer      | token::mint_to       |<br>       | Real Goods?    | SOL (Lamports)       | SPL Tokens (X-Token) | New Tokens (X-Token) |<br>       | Who Signs?     | User (Human 🤝)      | User (Human 🤝)      | PDA (Robot 🤖)       |<br>       | Context?       | CpiContext::new      | CpiContext::new      | CpiContext::new_with_signer |<br>       | Feel?          | Send cash from bank  | Give old tickets     | PRINT new tickets    |<br><br>       NOTE:<br>       - In Transfer, &#39;Old Goods&#39; always move (Take from somewhere and go somewhere).<br>       - In Minting, new goods are &#39;Created&#39; (Supply increases).<br>       =========================================================================<br>    */<br>    /*<br>       BIG COMPARISON: SOL vs MINT vs TRANSFER 📝<br><br>       Bro, don&#39;t get confused here! All three CPIs are different things:<br><br>       1. SOL Transfer (in buy_tokens):<br>          - Program: System Program.<br>          - Context: `CpiContext::new` (User&#39;s signature works).<br>          - Feel: &quot;Withdraw money (SOL) from bank&quot;.<br><br>       2. Token MINTING (in buy_tokens):<br>          - Program: Token Program.<br>          - Context: `CpiContext::new_with_signer` (PDA is signing).<br>          - Feel: &quot;Print new money (Tokens)&quot;.<br><br>       3. Token TRANSFER (Exactly HERE):<br>          - Program: Token Program.<br>          - Context: `CpiContext::new` (Because User gave authority).<br>          - Feel: &quot;Send old tickets (Tokens) from one wallet to another&quot;.<br><br>       Why not `new_with_signer` here?<br>       Because the authority here is not PDA, but the &#39;Creator&#39; (User) themselves.<br>       They signed the transaction, so no PDA hassle!<br>    */<br>    /*<br>    ================================================================================<br>    🚀 SOLANA SYNTAX CHEAT CODE (Feel the Magic ✨)<br>    ================================================================================<br>    Bro, if you understand these 3 steps, you&#39;re the KING of Solana! 👑<br><br>    Every CPI (Cross Program Call) is like sending a &#39;Letter&#39;:<br><br>    1. FILL THE FORM (The Struct): 📝<br>       - For SOL: `system_program::Transfer { from, to }`<br>       - Token Transfer: `token::Transfer { from, to, authority }`<br>       - Token Minting: `token::MintTo { mint, to, authority }`<br><br>    2. CHOOSE THE ENVELOPE (The Context): ✉️<br>       - If you signed yourself (Human 🤝): `CpiContext::new(Program, Form)`<br>       - If Robot (PDA 🤖) is signing: `CpiContext::new_with_signer(Program, Form, Seeds)`<br><br>    3. PRESS THE BUTTON (The Action): 🔘<br>       - SOL: `system_program::transfer(context, amount)?`<br>       - Token Transfer: `token::transfer(context, amount)?`<br>       - Token Minting: `token::mint_to(context, amount)?`<br><br>    WOW POINT: 🌟<br>    Notice? For tokens we use &#39;token::&#39; program, and for SOL we use<br>    &#39;system_program::&#39;. Syntax is exactly the same, just &#39;Form&#39; and &#39;Manager&#39; change!<br>    ================================================================================<br>    */<br>    pub fn buy_tokens(ctx: Context&lt;BuyTokens&gt;) -&gt; Result&lt;()&gt; {<br>        // First extract rate from system settings (TreasuryConfig)<br>        let treasury_config_account = &amp;ctx.accounts.treasury_config_account;<br>        let sol_to_pay = treasury_config_account.sol_price;<br>        let token_amount = treasury_config_account.tokens_per_purchase;<br><br>        // -------------------------------------------------------------------------<br>        // STEP A: Money Collection (SOL Transfer) - User -&gt; Program Vault<br>        // -------------------------------------------------------------------------<br>        /*<br>           FEEL POINT: CPI (Cross-Program Invocation) 📞<br>           Q: Why can&#39;t our program (Vote App) take SOL from someone&#39;s wallet itself?<br>           A: Because this power is only with Solana&#39;s &#39;System Program&#39; (Bank Manager).<br>           Our shop (Vote App) can only give Orders to the manager.<br><br>           ---<br>           BIG STORY TWIST: CpiContext::new vs new_with_signer 🤔<br><br>           1. STEP A (CpiContext::new): 🤝<br>              We use &#39;new&#39; because here the Buyer (Human) has already signed<br>              the transaction. It&#39;s exactly like a customer signing a &#39;Check&#39;<br>              at the bank counter and giving it. Manager just needs to see the sign.<br><br>           2. STEP B (CpiContext::new_with_signer): 🤖✨<br>              Here the authority is a PDA (Robot). Robot doesn&#39;t have a pen to<br>              sign a check. So we show the manager the Robot&#39;s &#39;Seeds&#39; (DNA/Aadhaar).<br>              These Seeds become the Robot&#39;s &#39;Virtual Signature&#39;.<br>              That&#39;s why &#39;new_with_signer&#39; is used (Signer with Seeds).<br>           ---<br><br>           Understand this in 3 steps:<br>           1. FILL THE FORM (Instruction Data):<br>              `Transfer { from, to }` ➔ Here we wrote that SOL goes from &#39;Buyer&#39; to &#39;Vault&#39;.<br><br>           2. PUT IN ENVELOPE (CpiContext):<br>              `CpiContext::new` ➔ Here we tell the &#39;Bank Manager&#39; to do our work (The Form).<br><br>           3. SUBMIT REQUEST (Action!):<br>              `system_program::transfer` ➔ When this line is called, Bank Manager (System Program)<br>              activates, does the transfer, and returns control to us.<br>        */<br>        let transfer_ix = system_program::Transfer {<br>            from: ctx.accounts.buyer.to_account_info(),<br>            to: ctx.accounts.sol_vault.to_account_info(),<br>        };<br><br>        let cpi_ctx_sol =<br>            CpiContext::new(ctx.accounts.system_program.to_account_info(), transfer_ix);<br><br>        system_program::transfer(cpi_ctx_sol, sol_to_pay)?;<br><br>        // -------------------------------------------------------------------------<br>        // STEP B: Token Factory (Minting) - Printing New Tokens<br>        // -------------------------------------------------------------------------<br>        /*<br>           REAL LIFE STORY: &quot;Robot Manager and Government Printing Press&quot; 🤖🖨️<br><br>           STORY TWIST:<br>           We want to print new tokens (Money). But the permission to print tokens<br>           is only with the &#39;Mint Authority&#39;.<br>           Our Authority is not a human, it&#39;s a ROBOT (PDA) named &#39;mint_authority&#39;.<br>           Robot doesn&#39;t have hands (Private Key) to sign, so what will it do?<br><br>           LET&#39;S SEE STEP-BY-STEP:<br>        */<br><br>        // 1. SEEDS (Robot&#39;s DNA/Aadhaar Card) 🆔<br>        // Robot goes to the Printing Press counter and shows its DNA (Seeds).<br>        // It says: &quot;Bro, I&#39;m that Robot made from the &#39;mint_authority&#39; word and<br>        // this special &#39;Bump&#39; (The Push).&quot;<br>        // - .as_ref() ➔ Just converting string to Solana&#39;s language (Bytes).<br>        /*<br>           FEEL POINT: What is this &#39;ctx.bumps.mint_authority&#39;? 🤔<br>           Bro, Anchor is very smart. When you created the &#39;mint_authority&#39; PDA,<br>           Anchor itself checked how much push (Bump) is needed to remove the<br>           address from the &#39;Curve&#39;.<br><br>           It saved that &#39;Bump number&#39; (e.g. 254) in its diary called<br>           &#39;ctx.bumps&#39;.<br><br>           FINAL FEEL (Why needed?):<br>           To sign a PDA, we have to give seeds + that same specific bump.<br>           It&#39;s exactly like I have an &#39;Aadhaar Card&#39; (Seeds), but my real<br>           proof is my fingerprint&#39;s &#39;Thumbprint&#39; (Bump). Without it, signature<br>           won&#39;t be verified (paka)!<br>        */<br>        let mint_authority_seeds = &amp;[<br>            b&quot;mint_authority&quot;.as_ref(),  // Seed 1 (Name)<br>            &amp;[ctx.bumps.mint_authority], // Seed 2 (Bump - DNA&#39;s special code)<br>        ];<br><br>        // 2. SIGNER_SEEDS (Envelope Hassle) 📂📂<br>        // The Printing Press manager is a bit fussy. He says: &quot;Don&#39;t give the Aadhaar<br>        // Card directly, first put it in an Envelope (Slice), then put that in a<br>        // Master Box (Outer Slice), only then will I take the file forward.&quot;<br>        // - [..] ➔ &quot;Take out the full card (seeds).&quot;<br>        // - Inner &amp; ➔ &quot;Put in envelope.&quot;<br>        // - Outer &amp;[] ➔ &quot;Put in big box.&quot; (Slice of Slices)<br>        let signer_seeds = &amp;[&amp;mint_authority_seeds[..]];<br><br>        // 3. BOOKING FORM (Accounts Involved) 📝<br>        // Now we fill a &#39;Booking Form&#39; (MintTo) which says:<br>        // - Which token to print? (x_mint)<br>        // - Where to deliver? (buyer_token_account)<br>        // - Who&#39;s the boss giving the order? (mint_authority PDA)<br>        let cpi_accounts = MintTo {<br>            mint: ctx.accounts.x_mint.to_account_info(),<br>            to: ctx.accounts.buyer_token_account.to_account_info(),<br>            authority: ctx.accounts.mint_authority.to_account_info(),<br>        };<br><br>        // 4. VERIFICATION WINDOW (CpiContext with Signer) ✅<br>        // We give the manager the &#39;Box&#39; (Signer Seeds) and &#39;Form&#39; (CpiAccounts).<br>        // Manager checks our DNA (Seeds), if it matches, they put our<br>        // &#39;Digital Signature&#39; (Virtual signing) on the transaction.<br>        let cpi_ctx_mint = CpiContext::new_with_signer(<br>            ctx.accounts.token_program.to_account_info(),<br>            cpi_accounts,<br>            signer_seeds, // PDA&#39;s &#39;Virtual Signature&#39; or &#39;Face ID&#39; is going here<br>        );<br><br>        // 5. PRINT ACTION! (mint_to call) 🖨️✨<br>        // If everything is correct, &#39;Token Program&#39;s Printing Press runs<br>        // and new tokens (token_amount) are created instantly!<br>        mint_to(cpi_ctx_mint, token_amount)?;<br><br>        // -------------------------------------------------------------------------<br>        // STEP C: Spread the News (Emit Event) 📢<br>        // -------------------------------------------------------------------------<br>        emit!(TokensPurchased {<br>            buyer: ctx.accounts.buyer.key(),<br>            sol_paid: sol_to_pay,<br>            tokens_received: token_amount,<br>            timestamp: Clock::get()?.unix_timestamp,<br>        });<br><br>        Ok(()) // Everything went smoothly!<br>    }<br><br>    // -------------------------------------------------------------------------<br>    // 3. REGISTER VOTER: Register identity<br>    // -------------------------------------------------------------------------<br>    pub fn register_voter(ctx: Context&lt;RegisterVoter&gt;) -&gt; Result&lt;()&gt; {<br>        // Just save data: &quot;This person is a voter&quot;<br>        let voter_account = &amp;mut ctx.accounts.voter_account;<br>        voter_account.voter_id = ctx.accounts.authority.key();<br>        // Default: hasn&#39;t voted yet (we kept 0 default in state.rs)<br><br>        emit!(VoterRegistered {<br>            voter: ctx.accounts.authority.key(),<br>            voter_account: ctx.accounts.voter_account.key(),<br>            timestamp: Clock::get()?.unix_timestamp,<br>        });<br><br>        Ok(())<br>    }<br><br>    // -------------------------------------------------------------------------<br>    // 4. REGISTER PROPOSAL: Launch an election/Proposal<br>    // -------------------------------------------------------------------------<br>    // Creator launches an election. They have to pay some tokens as fee.<br>    /*<br>       FEEL POINT: ADMIN&#39;S FUN (Tokenomics) 🤑<br>       Bro, here the Admin is getting double benefits:<br>       1. First Admin &#39;Sold&#39; you tokens and took your SOL.<br>       2. Now you&#39;re giving back those same tokens to Admin as &#39;Fees&#39;.<br><br>       TOKEN LIFECYCLE:<br>       Tokens are getting deposited into &#39;treasury_token_account&#39;. Now Admin can:<br>       - Either resell them to new users again (Recycling).<br>       - Or &#39;Burn&#39; them to reduce supply.<br>       - Or distribute them as rewards.<br>       In short, these tokens are now Admin&#39;s property!<br>    */<br>    pub fn register_proposal(<br>        ctx: Context&lt;RegisterProposal&gt;,<br>        proposal_info: String,<br>        deadline: i64,<br>        token_fee: u64,<br>    ) -&gt; Result&lt;()&gt; {<br>        let clock = Clock::get()?;<br>        // Deadline should be in the future, yesterday&#39;s election can&#39;t happen today!<br>        require!(deadline &gt; clock.unix_timestamp, VoteError::InvalidDeadline);<br><br>        // ---------------------------------------------------------------------<br>        // STEP A: Token transfer (Creator -&gt; Treasury)<br>        // ---------------------------------------------------------------------<br><br>        let cpi_accounts = Transfer {<br>            from: ctx.accounts.proposal_token_account.to_account_info(), // Where to take from?<br>            to: ctx.accounts.treasury_token_account.to_account_info(), // Where to send? (Treasury Vault)<br>            authority: ctx.accounts.authority.to_account_info(),       // Who&#39;s the Signer?<br>        };<br><br>        // Here CpiContext::new because Creator signed<br>        let cpi_ctx = CpiContext::new(ctx.accounts.token_program.to_account_info(), cpi_accounts);<br><br>        // Actual transfer command (Token Program Manager in action!)<br>        transfer(cpi_ctx, token_fee)?;<br><br>        // ---------------------------------------------------------------------<br>        // STEP B: Save proposal details in the account<br>        // ---------------------------------------------------------------------<br>        /*<br>           CURRENT WORK: Now we&#39;re writing in the &#39;Blockchain Register&#39; that<br>           a new Election (Proposal) has been set up.<br>        */<br>        let proposal_account = &amp;mut ctx.accounts.proposal_account;<br>        proposal_account.proposal_info = proposal_info;<br>        proposal_account.deadline = deadline;<br>        proposal_account.authority = ctx.accounts.authority.key();<br>        proposal_account.number_of_votes = 0; // Fresh proposal, Zero votes!<br><br>        // ---------------------------------------------------------------------<br>        // STEP C: Update counter (For Unique Identity)<br>        // ---------------------------------------------------------------------<br>        let proposal_counter_account = &amp;mut ctx.accounts.proposal_counter_account;<br>        proposal_account.proposal_id = proposal_counter_account.proposal_count;<br><br>        // Increase counter by 1, so next one gets the next number<br>        proposal_counter_account.proposal_count = proposal_counter_account<br>            .proposal_count<br>            .checked_add(1)<br>            .ok_or(VoteError::ProposalCounterOverflow)?;<br><br>        emit!(ProposalCreated {<br>            proposal_id: proposal_account.proposal_id,<br>            creator: proposal_account.authority,<br>            proposal_info: proposal_account.proposal_info.clone(),<br>            deadline: proposal_account.deadline,<br>            timestamp: Clock::get()?.unix_timestamp,<br>        });<br>        Ok(())<br>    }<br><br>    // -------------------------------------------------------------------------<br>    // 5. CAST VOTE: Cast a vote<br>    // -------------------------------------------------------------------------<br>    pub fn proposal_to_vote(ctx: Context&lt;Vote&gt;, proposal_id: u8, token_fee: u64) -&gt; Result&lt;()&gt; {<br>        let clock = Clock::get()?;<br>        let proposal_account = &amp;mut ctx.accounts.proposal_account;<br><br>        // Check 1: Has the election ended?<br>        require!(<br>            proposal_account.deadline &gt; clock.unix_timestamp,<br>            VoteError::ProposalEnded<br>        );<br><br>        // We&#39;ve already set &#39;constraint&#39; in Contexts.rs so person votes only once.<br>        // So no need to check again here.<br><br>        // STEP A: Take fee from Voter. Voter -&gt; Treasury<br>        let cpi_accounts = Transfer {<br>            from: ctx.accounts.voter_token_account.to_account_info(),<br>            to: ctx.accounts.treasury_token_account.to_account_info(),<br>            authority: ctx.accounts.authority.to_account_info(),<br>        };<br><br>        let cpi_ctx = CpiContext::new(ctx.accounts.token_program.to_account_info(), cpi_accounts);<br>        transfer(cpi_ctx, token_fee)?;<br><br>        // STEP B: Update Voter Profile<br>        let voter_account = &amp;mut ctx.accounts.voter_account;<br>        voter_account.proposal_voted = proposal_id; // Record that they voted here<br><br>        // STEP C: Increase Proposal&#39;s vote counter<br>        proposal_account.number_of_votes = proposal_account<br>            .number_of_votes<br>            .checked_add(1)<br>            .ok_or(VoteError::ProposalVotesOverflow)?;<br><br>        emit!(VoteCast {<br>            voter: ctx.accounts.authority.key(),<br>            proposal_id,<br>            total_votes: proposal_account.number_of_votes,<br>            timestamp: clock.unix_timestamp,<br>        });<br><br>        Ok(())<br>    }<br><br>    // -------------------------------------------------------------------------<br>    // 6. PICK WINNER: Election result (Leaderboard Update)<br>    // -------------------------------------------------------------------------<br>    pub fn pick_winner(ctx: Context&lt;PickWinner&gt;, proposal_id: u8) -&gt; Result&lt;()&gt; {<br>        let clock = Clock::get()?;<br>        let proposal = &amp;ctx.accounts.proposal_account;<br>        let winner = &amp;mut ctx.accounts.winner_account;<br><br>        // Check: Deadline should be over first!<br>        require!(<br>            clock.unix_timestamp &gt;= proposal.deadline,<br>            VoteError::VotingStillActive<br>        );<br><br>        // There should be some votes<br>        require!(proposal.number_of_votes &gt; 0, VoteError::NoVotesCast);<br><br>        // ---------------------------------------------------------------------<br>        // FEEL POINT: TOPPER DASHBOARD LOGIC (High Score 🎮)<br>        // ---------------------------------------------------------------------<br>        /*<br>           Bro, this winner_account is a permanent &#39;Scoreboard&#39;.<br>           It always saves the &#39;Global Topper&#39; till now.<br><br>           EXAMPLE:<br>           1. Scoreboard currently says: &quot;ID #2, 50 Votes&quot;.<br>           2. Now Proposal #5 comes with 70 votes.<br>           3. &#39;if 70 &gt; 50&#39; ➔ Condition True! 🏆<br>           4. Erase board and write new Topper: &quot;ID #5, 70 Votes&quot;.<br><br>           If Proposal #6 comes with only 40 votes, the condition<br>           will fail (40 &gt; 70 is false) and the board won&#39;t change!<br>        */<br>        if proposal.number_of_votes &gt; winner.winning_votes {<br>            // Update board: Now the new champion is &#39;proposal_id&#39;<br>            winner.winning_proposal_id = proposal_id;<br>            winner.winning_votes = proposal.number_of_votes;<br>            winner.proposal_info = proposal.proposal_info.clone();<br>            winner.declared_at = clock.unix_timestamp;<br><br>            // Spread the news everywhere (Event)! 📢<br>            emit!(WinnerDeclared {<br>                winning_proposal_id: proposal_id,<br>                proposal_info: proposal.proposal_info.clone(),<br>                total_votes: proposal.number_of_votes,<br>                declared_by: ctx.accounts.authority.key(),<br>                timestamp: clock.unix_timestamp,<br>            });<br>        }<br><br>        Ok(())<br>    }<br><br>    // -------------------------------------------------------------------------<br>    // 7. CLEANUP: Close proposal account (Solana cleanup)<br>    // -------------------------------------------------------------------------<br>    pub fn close_proposal(ctx: Context&lt;CloseProposal&gt;, proposal_id: u8) -&gt; Result&lt;()&gt; {<br>        let clock = Clock::get()?;<br>        // Deadline check, can&#39;t close account in the middle of election!<br>        require!(<br>            clock.unix_timestamp &gt;= ctx.accounts.proposal_account.deadline,<br>            VoteError::VotingStillActive<br>        );<br><br>        emit!(ProposalClosed {<br>            proposal_id,<br>            rent_recovered: ctx.accounts.proposal_account.to_account_info().lamports(),<br>            recovered_to: ctx.accounts.authority.key(),<br>            timestamp: clock.unix_timestamp,<br>        });<br>        // &#39;close&#39; constraint is set in Contexts.rs, so logic will execute automatically.<br>        Ok(())<br>    }<br><br>    // -------------------------------------------------------------------------<br>    // 8. CLEANUP: Remove voter profile<br>    // -------------------------------------------------------------------------<br>    pub fn close_voter(ctx: Context&lt;CloseVoter&gt;) -&gt; Result&lt;()&gt; {<br>        emit!(VoterAccountClosed {<br>            voter: ctx.accounts.voter_account.voter_id,<br>            rent_recovered_to: ctx.accounts.authority.key(),<br>            timestamp: Clock::get()?.unix_timestamp,<br>        });<br>        Ok(())<br>    }<br><br>    // -------------------------------------------------------------------------<br>    // 9. ADMIN WITHDRAW: Withdraw SOL from Treasury<br>    // -------------------------------------------------------------------------<br>    // When a lot of SOL accumulates in the vault, Admin can withdraw it.<br>    pub fn withdraw_sol(ctx: Context&lt;WithdrawSol&gt;, amount: u64) -&gt; Result&lt;()&gt; {<br>        let treasury_config = &amp;ctx.accounts.treasury_config;<br><br>        // To withdraw SOL from Vault (PDA), we need &#39;signer_seeds&#39;.<br>        // NOTE: Here we&#39;re using &#39;treasury_config.bump&#39; which we saved during<br>        // Initialization time. This is the same &#39;Push&#39; (Bump) that was used<br>        // to create the PDA!<br>        let sol_vault_seeds = &amp;[b&quot;sol_vault&quot;.as_ref(), &amp;[treasury_config.bump]];<br>        let signer_seeds = &amp;[&amp;sol_vault_seeds[..]];<br><br>        let transfer_ix = system_program::Transfer {<br>            from: ctx.accounts.sol_vault.to_account_info(),<br>            to: ctx.accounts.authority.to_account_info(),<br>        };<br><br>        // PDA is signing the withdrawal transaction<br>        system_program::transfer(<br>            CpiContext::new_with_signer(<br>                ctx.accounts.system_program.to_account_info(),<br>                transfer_ix,<br>                signer_seeds,<br>            ),<br>            amount,<br>        )?;<br><br>        emit!(SolWithdrawn {<br>            authority: ctx.accounts.authority.key(),<br>            amount,<br>            timestamp: Clock::get()?.unix_timestamp,<br>        });<br><br>        Ok(())<br>    }<br>}</pre><h4>🎯 Complete System Flow — Putting It All Together</h4><p>Now that we’ve seen all the code, let’s understand how everything flows together!</p><h4>Phase 1: System Initialization</h4><pre>Admin calls: initialize_treasury(sol_price, tokens_per_purchase)<br><br>What happens:<br>1. Treasury Config created ✅<br>2. X Mint created ✅<br>3. Treasury token account created ✅<br>4. Proposal counter initialized ✅<br>5. SOL vault PDA derived ✅<br>6. Mint authority PDA derived ✅<br><br>Events emitted:<br>- TreasuryInitialized<br>- ProposalCounterInitialized<br><br>System ready! 🚀</pre><h4>Phase 2: User Buys Tokens</h4><pre>User calls: buy_tokens()<br><br>What happens:<br>1. User pays SOL to sol_vault (CPI to System Program)<br>2. Mint authority (PDA) mints new X tokens (CPI with signer)<br>3. Tokens delivered to user&#39;s token account<br>4. User can now participate!<br><br>CPI #1: SOL Transfer (User signs)<br>CPI #2: Token Minting (PDA signs with seeds)<br><br>Event emitted: TokensPurchased</pre><h4>Phase 3: User Registers as Voter</h4><pre>User calls: register_voter()<br><br>What happens:<br>1. Voter account created with PDA<br>2. Seeds: [b&quot;voter&quot;, user_wallet]<br>3. proposal_voted set to 0 (not voted yet)<br>4. One account per user (global design)<br><br>Event emitted: VoterRegistered</pre><h4>Phase 4: Creator Registers Proposal</h4><pre>Creator calls: register_proposal(info, deadline, fee)<br><br>What happens:<br>1. Creator pays token fee to treasury (CPI)<br>2. Proposal counter incremented<br>3. Proposal account created with unique ID<br>4. Proposal data stored on-chain<br>5. Voting window opens!<br><br>CPI: Token Transfer (User signs)<br><br>Event emitted: ProposalCreated</pre><h4>Phase 5: User Casts Vote</h4><pre>Voter calls: proposal_to_vote(proposal_id, fee)<br><br>What happens:<br>1. Checks:<br>   - Deadline not passed? ✅<br>   - User not voted before? ✅<br>   - Correct tokens? ✅<br>2. Voter pays token fee to treasury (CPI)<br>3. voter.proposal_voted updated to proposal_id<br>4. proposal.number_of_votes incremented<br><br>CPI: Token Transfer (User signs)<br><br>Event emitted: VoteCast</pre><h4>Phase 6: Admin Declares Winner</h4><pre>Admin calls: pick_winner(proposal_id)<br><br>What happens:<br>1. Check deadline passed<br>2. Check votes exist<br>3. Compare with current winner<br>4. If higher votes, update winner account<br>5. Results stored permanently!<br><br>Comparison logic:<br>if (proposal.votes &gt; winner.votes) {<br>    Update winner board 🏆<br>}<br><br>Event emitted: WinnerDeclared (if winner)</pre><h4>Phase 7: Cleanup</h4><pre>Option A: Close Proposal<br>Creator calls: close_proposal(proposal_id)<br>- Proposal account deleted<br>- Rent refunded to destination<br>- Event emitted: ProposalClosed<br><br>Option B: Close Voter<br>Voter calls: close_voter()<br>- Voter account deleted<br>- Rent refunded to voter<br>- Event emitted: VoterAccountClosed<br><br>Option C: Withdraw SOL<br>Admin calls: withdraw_sol(amount)<br>- SOL transferred from vault to admin<br>- PDA signs with seeds<br>- Event emitted: SolWithdrawn</pre><h3>🎓 Key Takeaways</h3><p><strong>The 5 Files:</strong></p><pre>state.rs     → Data structures (what to store)<br>errors.rs    → Error definitions (what went wrong)<br>events.rs    → Event emissions (what happened)<br>contexts.rs  → Account validation (who can do what)<br>lib.rs       → Program logic (how it works)</pre><p><strong>The Tokenomics:</strong></p><pre>1. Admin creates tokens<br>2. Users buy with SOL → Admin gets SOL<br>3. Users pay tokens as fees → Tokens return<br>4. Admin can resell/burn/reward → Sustainable!</pre><p><strong>The Security:</strong></p><pre>- PDAs for program control<br>- Constraints for validation<br>- One vote per user (global design)<br>- Deadline enforcement<br>- Token type verification<br>- Admin authorization</pre><p><strong>The Events:</strong></p><pre>Every action emits events:<br>- Real-time updates<br>- Frontend integration<br>- Complete transparency<br>- Audit trail</pre><h4>🙏 Acknowledgments</h4><p>Special thanks to <strong>Code Eater</strong> for the excellent YouTube tutorial that this project is based on. The original video provides step-by-step guidance for building this voting dApp:</p><p>🎥 <strong>Watch the tutorial:</strong> <a href="https://youtu.be/VrOedBsazKE">Solana Voting dApp — Code Eater</a></p><p>This written guide expands on the tutorial with:</p><ul><li>All code comments translated from Hinglish to English</li><li>Additional explanations and feel points</li><li>Comprehensive system architecture breakdowns</li><li>Complete tokenomics analysis</li><li>Visual diagrams and flow charts</li><li>Production-ready patterns and best practices</li></ul><h4>💻 Source Code</h4><p>Want to explore the complete code with detailed comments? Check out the GitHub repository:</p><p>🔗 <a href="https://github.com/Dhruv-0101/code-eater-vote-dapp-with-my-code-comments.git"><strong>GitHub Repository — Voting dApp with Code Comments</strong></a></p><p>The repository includes:</p><ul><li>✅ All 5 files (state.rs, errors.rs, events.rs, contexts.rs, lib.rs)</li><li>✅ Detailed code comments explaining every concept</li><li>✅ Feel points and real-world analogies</li><li>✅ Complete working implementation</li><li>✅ Ready to clone and deploy</li></ul><p><strong>🎉 Congratulations!</strong> You now have a COMPLETE understanding of building a production-ready voting dApp on Solana with full tokenomics!</p><p><strong>Go build governance systems! 🗳️⚡</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7cbea7380f66" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Real-World dApps Smart Contract on Solana: Voting System & ToDo Manager]]></title>
            <link>https://medium.com/@d7511162/building-real-world-dapps-smart-contract-on-solana-voting-system-todo-manager-a71ed6ff4821?source=rss-8de3c9502bfd------2</link>
            <guid isPermaLink="false">https://medium.com/p/a71ed6ff4821</guid>
            <category><![CDATA[solana-network]]></category>
            <category><![CDATA[solana-blockchain]]></category>
            <category><![CDATA[smart-contract-blockchain]]></category>
            <category><![CDATA[dapps]]></category>
            <category><![CDATA[solana-ecosystem]]></category>
            <dc:creator><![CDATA[Dhruv Patel]]></dc:creator>
            <pubDate>Mon, 16 Mar 2026 11:33:00 GMT</pubDate>
            <atom:updated>2026-03-23T18:36:18.363Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Master practical blockchain applications with Anchor Framework</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lWaVZEah6xmOBhO0Ufs8ug.png" /></figure><blockquote><em>⚠️ </em><strong><em>Note for Readers</em></strong></blockquote><blockquote><em>This article is part of my Solana learning series.</em></blockquote><blockquote><em>👉 Before continuing, I highly recommend checking the complete series here:<br></em><a href="https://medium.com/@d7511162/building-real-world-dapps-smart-contract-on-solana-voting-system-todo-manager-a71ed6ff4821"><strong><em>View Full Solana Series</em></strong></a></blockquote><blockquote><em>Following the series in order will give you a much better understanding.</em></blockquote><blockquote><em>However, if you are already familiar with the basics, feel free to continue with this article.</em></blockquote><h4>📝 The Complete Code</h4><pre>use anchor_lang::prelude::*;<br><br>declare_id!(&quot;6VeiThsnKi8JpGRm9ZwFSTFYPuPeCuDMEhXkQ1jjCF89&quot;);<br><br>#[program]<br>pub mod vote {<br>    use super::*;<br><br>    pub fn initialize_candidate(<br>        ctx: Context&lt;InitializeCandidate&gt;,<br>        name: String<br>    ) -&gt; Result&lt;()&gt; {<br>        require!(name.len() &gt; 0, CandidateError::InvalidName);<br>        <br>        let candidate = &amp;mut ctx.accounts.candidate;<br>        candidate.set_inner(Candidate {<br>            c_name: name,<br>            vote_count: 0,<br>            candidate_id: ctx.accounts.owner.key()<br>        });<br>        <br>        msg!(&quot;Candidate registration successful&quot;);<br>        Ok(())<br>    }<br><br>    pub fn initialize_voter(<br>        ctx: Context&lt;InitializeVoter&gt;,<br>        name: String<br>    ) -&gt; Result&lt;()&gt; {<br>        require!(name.len() &gt; 0, VoterError::InvalidName);<br>        <br>        let voter = &amp;mut ctx.accounts.voter;<br>        voter.set_inner(Voter {<br>            v_name: name,<br>            is_voted: false,<br>            voter_id: ctx.accounts.owner.key()<br>        });<br>        <br>        msg!(&quot;Voter registration successful&quot;);<br>        Ok(())<br>    }<br><br>    pub fn cast_vote(ctx: Context&lt;CastVote&gt;) -&gt; Result&lt;()&gt; {<br>        let voter = &amp;mut ctx.accounts.voter;<br>        let candidate = &amp;mut ctx.accounts.candidate;<br><br>        // Ensure the voter is signing the transaction<br>        require!(<br>            ctx.accounts.voter_signer.key() == voter.voter_id,<br>            VoterError::UnauthorizedVoter<br>        );<br><br>        // Ensure the voter has not already voted<br>        require!(!voter.is_voted, VoterError::AlreadyVoted);<br><br>        // Ensure the candidate exists<br>        require!(<br>            candidate.vote_count &gt;= 0,<br>            CandidateError::CandidateNotFound<br>        );<br><br>        // Prevent self-voting<br>        require!(<br>            voter.voter_id != candidate.candidate_id,<br>            VoterError::CannotVoteForSelf<br>        );<br><br>        // Increment vote count with overflow check<br>        candidate.vote_count = candidate.vote_count<br>            .checked_add(1)<br>            .ok_or(VoterError::VoteOverflow)?;<br><br>        // Mark voter as voted<br>        voter.is_voted = true;<br><br>        msg!(<br>            &quot;Voter {} has voted for candidate {}&quot;,<br>            voter.voter_id,<br>            candidate.candidate_id<br>        );<br><br>        Ok(())<br>    }<br>}<br><br>#[account]<br>#[derive(InitSpace)]<br>pub struct Candidate {<br>    #[max_len(20)]<br>    c_name: String,<br>    vote_count: u8,<br>    candidate_id: Pubkey,<br>}<br><br>#[account]<br>#[derive(InitSpace)]<br>pub struct Voter {<br>    #[max_len(20)]<br>    v_name: String,<br>    is_voted: bool,<br>    voter_id: Pubkey,<br>}<br><br>#[derive(Accounts)]<br>#[instruction(c_name: String)]<br>pub struct InitializeCandidate&lt;&#39;info&gt; {<br>    #[account(mut)]<br>    pub owner: Signer&lt;&#39;info&gt;,<br><br>    #[account(<br>        init,<br>        seeds = [c_name.as_bytes(), owner.key().as_ref()],<br>        bump,<br>        space = 8 + Candidate::INIT_SPACE,<br>        payer = owner<br>    )]<br>    pub candidate: Account&lt;&#39;info, Candidate&gt;,<br><br>    pub system_program: Program&lt;&#39;info, System&gt;<br>}<br><br>#[derive(Accounts)]<br>#[instruction(v_name: String)]<br>pub struct InitializeVoter&lt;&#39;info&gt; {<br>    #[account(mut)]<br>    pub owner: Signer&lt;&#39;info&gt;,<br><br>    #[account(<br>        init,<br>        seeds = [v_name.as_bytes(), owner.key().as_ref()],<br>        bump,<br>        space = 8 + Voter::INIT_SPACE,<br>        payer = owner<br>    )]<br>    pub voter: Account&lt;&#39;info, Voter&gt;,<br><br>    pub system_program: Program&lt;&#39;info, System&gt;<br>}<br><br>#[derive(Accounts)]<br>pub struct CastVote&lt;&#39;info&gt; {<br>    #[account(mut)]<br>    pub voter: Account&lt;&#39;info, Voter&gt;,<br><br>    #[account(mut)]<br>    pub candidate: Account&lt;&#39;info, Candidate&gt;,<br><br>    #[account(mut)]<br>    pub voter_signer: Signer&lt;&#39;info&gt;<br>}<br><br>#[error_code]<br>pub enum CandidateError {<br>    #[msg(&quot;Candidate does not exist.&quot;)]<br>    CandidateNotFound,<br><br>    #[msg(&quot;Invalid name provided.&quot;)]<br>    InvalidName,<br>}<br><br>#[error_code]<br>pub enum VoterError {<br>    #[msg(&quot;Voter has already cast a vote.&quot;)]<br>    AlreadyVoted,<br><br>    #[msg(&quot;Candidates cannot vote for themselves.&quot;)]<br>    CannotVoteForSelf,<br><br>    #[msg(&quot;Vote count overflow occurred.&quot;)]<br>    VoteOverflow,<br><br>    #[msg(&quot;Invalid name provided.&quot;)]<br>    InvalidName,<br><br>    #[msg(&quot;Voter is not authorized.&quot;)]<br>    UnauthorizedVoter,<br>}</pre><pre>ELECTION SETUP<br>══════════════<br><br>Alice registers as candidate<br>    ↓<br>[Candidate Account Created]<br>- Name: &quot;Alice&quot;<br>- Vote Count: 0<br>- Candidate ID: Alice&#39;s pubkey<br><br>Bob registers as voter<br>    ↓<br>[Voter Account Created]<br>- Name: &quot;Bob&quot;<br>- Has Voted: false<br>- Voter ID: Bob&#39;s pubkey<br><br><br>VOTE CASTING<br>══════════════<br><br>Bob wants to vote for Alice<br>    ↓<br>SECURITY CHECKS:<br>    ├─ Is Bob signing? ✅<br>    ├─ Has Bob voted before? ✅ (No)<br>    ├─ Does Alice exist? ✅<br>    └─ Is Bob voting for himself? ✅ (No)<br>    ↓<br>EXECUTE VOTE:<br>    ├─ Alice.vote_count: 0 → 1<br>    └─ Bob.is_voted: false → true<br>    ↓<br>VOTE RECORDED ✅<br><br><br>ATTEMPT DOUBLE VOTE<br>══════════════<br><br>Bob tries to vote again<br>    ↓<br>SECURITY CHECKS:<br>    ├─ Is Bob signing? ✅<br>    └─ Has Bob voted before? ❌ (YES!)<br>    ↓<br>REJECTED! ❌<br>Error: &quot;Voter has already cast a vote.&quot;</pre><h4>✅ ToDo Manager</h4><p><strong>Master CRUD operations and sequential PDAs</strong></p><h4>📝 The Complete Code</h4><pre>use anchor_lang::prelude::*;<br><br>declare_id!(&quot;3FZXiZRkziBxQpS926XhKWv2k4zcgnFmznuDRKyBxmk5&quot;);<br><br>#[program]<br>pub mod todo_app {<br>    use super::*;<br><br>    /// Creates a new ToDo item with a unique task_id per user.<br>    pub fn create_task(<br>        ctx: Context&lt;CreateTask&gt;,<br>        task_id: u64,<br>        name: String,<br>        completed: bool,<br>    ) -&gt; Result&lt;()&gt; {<br>        let task = &amp;mut ctx.accounts.todo;<br>        task.id = task_id;<br>        task.name = name;<br>        task.completed = completed;<br>        Ok(())<br>    }<br><br>    /// Updates the name of an existing ToDo item.<br>    pub fn update_task_name(<br>        ctx: Context&lt;UpdateTaskName&gt;,<br>        new_name: String<br>    ) -&gt; Result&lt;()&gt; {<br>        let task = &amp;mut ctx.accounts.todo;<br>        task.name = new_name;<br>        Ok(())<br>    }<br><br>    /// Toggles or sets the completion status of a ToDo item.<br>    pub fn update_task_status(<br>        ctx: Context&lt;UpdateTaskStatus&gt;,<br>        completed: bool<br>    ) -&gt; Result&lt;()&gt; {<br>        let task = &amp;mut ctx.accounts.todo;<br>        task.completed = completed;<br>        Ok(())<br>    }<br>}<br><br>#[account]<br>#[derive(InitSpace)]<br>pub struct ToDo {<br>    pub id: u64,<br>    #[max_len(50)]<br>    pub name: String,<br>    pub completed: bool,<br>}<br><br>#[derive(Accounts)]<br>#[instruction(task_id: u64)]<br>pub struct CreateTask&lt;&#39;info&gt; {<br>    #[account(mut)]<br>    pub authority: Signer&lt;&#39;info&gt;,<br><br>    #[account(<br>        init,<br>        payer = authority,<br>        space = 8 + ToDo::INIT_SPACE,<br>        seeds = [<br>            b&quot;todo&quot;,<br>            authority.key().as_ref(),<br>            &amp;task_id.to_le_bytes()<br>        ],<br>        bump<br>    )]<br>    pub todo: Account&lt;&#39;info, ToDo&gt;,<br><br>    pub system_program: Program&lt;&#39;info, System&gt;,<br>}<br><br>#[derive(Accounts)]<br>pub struct UpdateTaskName&lt;&#39;info&gt; {<br>    #[account(mut)]<br>    pub authority: Signer&lt;&#39;info&gt;,<br><br>    #[account(<br>        mut,<br>        seeds = [<br>            b&quot;todo&quot;,<br>            authority.key().as_ref(),<br>            &amp;todo.id.to_le_bytes()<br>        ],<br>        bump,<br>    )]<br>    pub todo: Account&lt;&#39;info, ToDo&gt;,<br>}<br><br>#[derive(Accounts)]<br>pub struct UpdateTaskStatus&lt;&#39;info&gt; {<br>    #[account(mut)]<br>    pub authority: Signer&lt;&#39;info&gt;,<br><br>    #[account(<br>        mut,<br>        seeds = [<br>            b&quot;todo&quot;,<br>            authority.key().as_ref(),<br>            &amp;todo.id.to_le_bytes()<br>        ],<br>        bump,<br>    )]<br>    pub todo: Account&lt;&#39;info, ToDo&gt;,<br>}</pre><h4>🏗️ Architecture: Sequential PDAs</h4><h4>The Three-Seed Pattern</h4><pre>seeds = [<br>    b&quot;todo&quot;,                      // Seed 1: Type identifier<br>    authority.key().as_ref(),     // Seed 2: User ownership<br>    &amp;task_id.to_le_bytes()        // Seed 3: Task number<br>]</pre><p><strong>Why three seeds?</strong></p><p><strong>Seed 1: </strong><strong>b&quot;todo&quot;</strong> (Static)</p><ul><li>Identifies account type</li><li>Namespace separator</li><li>Same for all users and tasks</li></ul><p><strong>Seed 2: </strong><strong>authority.key().as_ref()</strong> (User-specific)</p><ul><li>Owner’s public key</li><li>Each user gets unique tasks</li><li>Provides user isolation</li></ul><p><strong>Seed 3: </strong><strong>&amp;task_id.to_le_bytes()</strong> (Sequential)</p><ul><li>Task number (0, 1, 2, 3…)</li><li>Stored as little-endian bytes</li><li>Unlimited tasks per user</li></ul><p><strong>Result:</strong></p><pre>User A, Task 0: hash([&quot;todo&quot;, userA, 0])<br>User A, Task 1: hash([&quot;todo&quot;, userA, 1])<br>User B, Task 0: hash([&quot;todo&quot;, userB, 0])</pre><p>Each task = unique, predictable address!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a71ed6ff4821" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Your Own Token on Solana with Anchor Framework : SPL Token Guide By Dhruv patel]]></title>
            <link>https://medium.com/@d7511162/building-your-own-token-on-solana-with-anchor-framework-spl-token-guide-by-dhruv-patel-bb0ae6ac2fd4?source=rss-8de3c9502bfd------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb0ae6ac2fd4</guid>
            <category><![CDATA[create-solana-token]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[solana-network]]></category>
            <category><![CDATA[blockchain-technology]]></category>
            <category><![CDATA[solana-blockchain]]></category>
            <dc:creator><![CDATA[Dhruv Patel]]></dc:creator>
            <pubDate>Fri, 13 Mar 2026 17:08:47 GMT</pubDate>
            <atom:updated>2026-03-23T18:34:18.604Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building Your Own Token on Solana with Anchor Framework : SPL Token Guide</h3><p><strong>Create, mint, and transfer tokens like a pro with Anchor Framework</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M-x3IU4J_GEU8nCvdVrHog.png" /></figure><blockquote><em>⚠️ </em><strong><em>Note for Readers</em></strong></blockquote><blockquote><em>This article is part of my Solana learning series.</em></blockquote><blockquote><em>👉 Before continuing, I highly recommend checking the complete series here:<br></em><a href="https://medium.com/@d7511162/the-solana-learning-ladder-by-dhruv-patel-da5044b6a671"><strong><em>View Full Solana Series</em></strong></a></blockquote><blockquote><em>Following the series in order will give you a much better understanding.</em></blockquote><blockquote><em>However, if you are already familiar with the basics, feel free to continue with this article.</em></blockquote><h4>🎯 Introduction</h4><p>Ever wondered how cryptocurrencies like USDC, Bonk, or your favorite Solana token work? In this comprehensive guide, we’ll build a <strong>complete SPL Token program</strong> that allows you to:</p><ul><li>🏭 <strong>Create your own token</strong> (the Mint)</li><li>💰 <strong>Create token accounts</strong> (wallets to hold tokens)</li><li>🖨️ <strong>Mint tokens</strong> (create new supply)</li><li>📤 <strong>Transfer tokens</strong> between users</li></ul><p><strong>By the end, you’ll understand:</strong></p><ul><li>How SPL tokens work on Solana</li><li>Mint vs Token Account architecture</li><li>Cross-Program Invocations (CPI)</li><li>Token decimals and precision</li><li>PDAs for program-controlled tokens</li></ul><h4>🏦 Understanding Token Architecture</h4><h4>The Banking Analogy</h4><p>Before diving into code, let’s understand the architecture:</p><pre>┌──────────────────────────────────────┐<br>│         MINT ACCOUNT                 │<br>│    (The Central Bank)                │<br>│                                      │<br>│  - Manages token supply              │<br>│  - Sets decimal places               │<br>│  - Controls who can mint             │<br>│  - Like: Reserve Bank of India (RBI) │<br>└────────────┬─────────────────────────┘<br>             │<br>             │ creates<br>             │<br>    ┌────────┴────────┬────────────┐<br>    │                 │            │<br>    ▼                 ▼            ▼<br>┌─────────┐      ┌─────────┐  ┌─────────┐<br>│ Token   │      │ Token   │  │ Token   │<br>│ Account │      │ Account │  │ Account │<br>│ (Alice) │      │ (Bob)   │  │ (Carol) │<br>│         │      │         │  │         │<br>│ Balance:│      │ Balance:│  │ Balance:│<br>│ 100 TKN │      │ 50 TKN  │  │ 25 TKN  │<br>└─────────┘      └─────────┘  └─────────┘<br>  (Your          (Your         (Your<br>   Savings       Checking      Investment<br>   Account)      Account)      Account)</pre><p><strong>Key Concept:</strong></p><ul><li><strong>Mint</strong> = The token itself (like “USD” or “USDC”)</li><li><strong>Token Account</strong> = A wallet that holds that specific token</li><li><strong>SPL Token Program</strong> = The system that manages everything</li></ul><h4>📝 The Complete Code</h4><pre>// Import the Anchor framework main library<br>// `prelude` provides commonly used items automatically<br>// Example: Result, Context, Account, Signer, etc.<br>use anchor_lang::prelude::*;<br><br><br>// Import SPL Token Interface from Anchor SPL<br>// SPL = Solana Program Library<br>// We use this to interact with the Token Program<br>use anchor_spl::token_interface::{<br>    self,            // token_interface module<br>    Mint,            // Structure representing the Mint account<br>    MintTo,          // Structure used for the MintTo instruction<br>    TokenAccount,    // Structure representing a Token Account<br>    TokenInterface,  // Interface for interacting with the token program<br>    TransferChecked, // Safe transfer instruction structure<br>};<br><br><br>// This is the program ID of your smart contract<br>// Once deployed, this becomes the permanent address of your program<br>// Think of it like the public address of your smart contract on Solana<br>declare_id!(&quot;D6qAB5NKLWm8MYSFTB3hUGLAgrsrU9zExezbC1LAL3QK&quot;);<br><br><br><br>// ------------------------------------------------------------<br>// PROGRAM MODULE<br>// ------------------------------------------------------------<br>// This module contains all instructions (functions)<br>// that can be called by the frontend<br>#[program]<br>pub mod token_example {<br><br>    // `super` allows access to items from the outer scope<br>    use super::*;<br><br><br>    // --------------------------------------------------------<br>    // CREATE MINT<br>    // --------------------------------------------------------<br>    // Mint = the token factory<br>    //<br>    // Real life example:<br>    // The Mint is like a central bank printing machine<br>    // (For example: RBI printing new currency notes)<br>    pub fn create_mint(ctx: Context&lt;CreateMint&gt;) -&gt; Result&lt;()&gt; {<br><br>        // msg! prints logs to the blockchain logs<br>        // very useful for debugging<br>        msg!(&quot;Created Mint Account: {:?}&quot;, ctx.accounts.mint.key());<br><br>        Ok(())<br>    }<br><br><br><br>    // --------------------------------------------------------<br>    // CREATE TOKEN ACCOUNT<br>    // --------------------------------------------------------<br>    // Token account = a wallet that stores tokens<br>    //<br>    // Real life example:<br>    // Mint = the bank<br>    // Token account = your bank account<br>    pub fn create_token_account(ctx: Context&lt;CreateTokenAccount&gt;) -&gt; Result&lt;()&gt; {<br><br>        msg!(<br>            &quot;Created Token Account: {:?}&quot;,<br>            ctx.accounts.token_account.key()<br>        );<br><br>        Ok(())<br>    }<br><br><br><br>    // --------------------------------------------------------<br>    // MINT TOKENS<br>    // --------------------------------------------------------<br>    // Minting tokens means creating new tokens<br>    //<br>    // Real life example:<br>    // The central bank printing new money<br>    pub fn mint_tokens(ctx: Context&lt;MintTokens&gt;, amount: u64) -&gt; Result&lt;()&gt; {<br><br>        // CPI = Cross Program Invocation<br>        // This means our program is calling another program<br>        // In this case we are calling the SPL Token Program<br><br>        let cpi_accounts = MintTo {<br><br>            // Which mint is producing the tokens<br>            mint: ctx.accounts.mint.to_account_info(),<br><br>            // Which token account will receive the tokens<br>            to: ctx.accounts.token_account.to_account_info(),<br><br>            // The authority allowed to mint tokens<br>            authority: ctx.accounts.signer.to_account_info(),<br>        };<br><br><br>        // Reference to the token program<br>        let cpi_program = ctx.accounts.token_program.to_account_info();<br><br><br>        // Create a CPI context<br>        // Think of this as a &quot;package of instruction + accounts&quot;<br>        // that we send to the token program<br>        let cpi_context = CpiContext::new(cpi_program, cpi_accounts);<br><br><br>        // Call the SPL Token Program mint instruction<br>        token_interface::mint_to(cpi_context, amount)?;<br><br>        Ok(())<br>    }<br><br><br><br><br>    // --------------------------------------------------------<br>    // TRANSFER TOKENS<br>    // --------------------------------------------------------<br>    // Transfer tokens from one account to another<br>    //<br>    // Real life example:<br>    // Sending money from one bank account to another<br>    pub fn transfer_tokens(ctx: Context&lt;TransferTokens&gt;, amount: u64) -&gt; Result&lt;()&gt; {<br><br>        // Read the decimals of the token<br>        // Example:<br>        // If decimals = 6<br>        // then 1 token = 1,000,000 base units<br>        let decimals = ctx.accounts.mint.decimals;<br><br><br>        // Transfer instruction structure<br>        let cpi_accounts = TransferChecked {<br><br>            // The mint of the token<br>            mint: ctx.accounts.mint.to_account_info(),<br><br>            // Sender&#39;s token account<br>            from: ctx.accounts.sender_token_account.to_account_info(),<br><br>            // Recipient&#39;s token account<br>            to: ctx.accounts.recipient_token_account.to_account_info(),<br><br>            // Authority allowed to transfer<br>            authority: ctx.accounts.signer.to_account_info(),<br>        };<br><br><br>        // Reference to the token program<br>        let cpi_program = ctx.accounts.token_program.to_account_info();<br><br><br>        // Create CPI context<br>        let cpi_context = CpiContext::new(cpi_program, cpi_accounts);<br><br><br>        // Perform the transfer<br>        // transfer_checked ensures decimals match<br>        token_interface::transfer_checked(cpi_context, amount, decimals)?;<br><br>        Ok(())<br>    }<br>}<br><br><br><br>// ------------------------------------------------------------<br>// CREATE MINT ACCOUNT STRUCTURE<br>// ------------------------------------------------------------<br>#[derive(Accounts)]<br>pub struct CreateMint&lt;&#39;info&gt; {<br><br><br>    // The user who signs the transaction<br>    // This is the person executing the instruction<br>    #[account(mut)]<br>    pub signer: Signer&lt;&#39;info&gt;,<br><br><br>    // Create the Mint account<br>    #[account(<br><br>        // Initialize the account<br>        init,<br><br>        // The signer pays the rent and creation fees<br>        payer = signer,<br><br>        // Number of decimal places<br>        // Example: 1 token = 1.000000<br>        mint::decimals = 6,<br><br>        // Authority allowed to mint new tokens<br>        mint::authority = signer.key(),<br><br>        // Authority allowed to freeze token accounts<br>        mint::freeze_authority = mint.key(),<br><br>        // PDA seed<br>        // Used to derive a program controlled address<br>        seeds = [b&quot;mint&quot;],<br><br>        // bump is automatically calculated<br>        bump<br>    )]<br>    pub mint: InterfaceAccount&lt;&#39;info, Mint&gt;,<br><br><br>    // Token program interface<br>    pub token_program: Interface&lt;&#39;info, TokenInterface&gt;,<br><br><br>    // System program used to create accounts<br>    pub system_program: Program&lt;&#39;info, System&gt;,<br>}<br><br><br><br>// ------------------------------------------------------------<br>// CREATE TOKEN ACCOUNT STRUCTURE<br>// ------------------------------------------------------------<br>#[derive(Accounts)]<br>pub struct CreateTokenAccount&lt;&#39;info&gt; {<br><br><br>    // Transaction signer<br>    #[account(mut)]<br>    pub signer: Signer&lt;&#39;info&gt;,<br><br><br>    // Token account being created<br>    #[account(<br><br>        // Create the account if it doesn&#39;t exist<br>        init_if_needed,<br><br>        // Signer pays the rent<br>        payer = signer,<br><br>        // Which mint this token account belongs to<br>        token::mint = mint,<br><br>        // Owner of this token account<br>        token::authority = signer,<br><br>        // Token program<br>        token::token_program = token_program,<br><br>        // PDA seeds<br>        seeds = [b&quot;token&quot;, signer.key().as_ref()],<br><br>        bump<br>    )]<br>    pub token_account: InterfaceAccount&lt;&#39;info, TokenAccount&gt;,<br><br><br>    // Reference to the mint<br>    pub mint: InterfaceAccount&lt;&#39;info, Mint&gt;,<br><br><br>    // Token program interface<br>    pub token_program: Interface&lt;&#39;info, TokenInterface&gt;,<br><br><br>    // System program<br>    pub system_program: Program&lt;&#39;info, System&gt;,<br>}<br><br><br><br>// ------------------------------------------------------------<br>// MINT TOKENS CONTEXT<br>// ------------------------------------------------------------<br>#[derive(Accounts)]<br>pub struct MintTokens&lt;&#39;info&gt; {<br><br><br>    // Mint authority<br>    #[account(mut)]<br>    pub signer: Signer&lt;&#39;info&gt;,<br><br><br>    // Mint account<br>    #[account(mut)]<br>    pub mint: InterfaceAccount&lt;&#39;info, Mint&gt;,<br><br><br>    // Token account receiving tokens<br>    #[account(mut)]<br>    pub token_account: InterfaceAccount&lt;&#39;info, TokenAccount&gt;,<br><br><br>    // Token program<br>    pub token_program: Interface&lt;&#39;info, TokenInterface&gt;,<br>}<br><br><br><br><br>// ------------------------------------------------------------<br>// TRANSFER TOKENS CONTEXT<br>// ------------------------------------------------------------<br>#[derive(Accounts)]<br>pub struct TransferTokens&lt;&#39;info&gt; {<br><br><br>    // Sender signing the transaction<br>    #[account(mut)]<br>    pub signer: Signer&lt;&#39;info&gt;,<br><br><br>    // Mint account<br>    #[account(mut)]<br>    pub mint: InterfaceAccount&lt;&#39;info, Mint&gt;,<br><br><br>    // Sender token account<br>    #[account(mut)]<br>    pub sender_token_account: InterfaceAccount&lt;&#39;info, TokenAccount&gt;,<br><br><br>    // Recipient token account<br>    #[account(mut)]<br>    pub recipient_token_account: InterfaceAccount&lt;&#39;info, TokenAccount&gt;,<br><br><br>    // Token program<br>    pub token_program: Interface&lt;&#39;info, TokenInterface&gt;,<br>}</pre><h4>Understanding Cross-Program Invocation (CPI)</h4><h4>What is CPI?</h4><p>CPI = One program calling another program</p><p><strong>Think of it like:</strong></p><ul><li>Your app (Uber) calling Maps API</li><li>Your website calling Payment Gateway</li><li>One microservice calling another</li></ul><p><strong>In our case:</strong></p><pre>Our Token Program → Calls → SPL Token Program</pre><h4>Why use CPI?</h4><p><strong>1. Reuse existing functionality</strong></p><ul><li>Don’t reinvent the wheel</li><li>SPL Token Program already handles tokens</li><li>We just coordinate the calls</li></ul><p><strong>2. Composability</strong></p><ul><li>Programs work together</li><li>Build complex systems from simple parts</li><li>Like LEGO blocks</li></ul><p><strong>3. Security</strong></p><ul><li>SPL Token Program is audited</li><li>Tested by millions of transactions</li><li>Battle-hardened code</li></ul><h4>CPI Step-by-Step</h4><pre><br>// STEP 1: Define which accounts to pass<br>let cpi_accounts = MintTo {<br>    mint: ctx.accounts.mint.to_account_info(),<br>    to: ctx.accounts.token_account.to_account_info(),<br>    authority: ctx.accounts.signer.to_account_info(),<br>};<br><br>// STEP 2: Get reference to the program we&#39;re calling<br>let cpi_program = ctx.accounts.token_program.to_account_info();<br><br>// STEP 3: Package everything into CPI Context<br>let cpi_context = CpiContext::new(cpi_program, cpi_accounts);<br><br>// STEP 4: Make the call!<br>token_interface::mint_to(cpi_context, amount)?;</pre><p><strong>Visual Flow:</strong></p><pre>┌─────────────────────┐<br>│  Your Program       │<br>│  (Token Example)    │<br>│                     │<br>│  1. Build accounts  │<br>│  2. Create context  │<br>│  3. Call SPL Token  │<br>└──────────┬──────────┘<br>           │<br>           │ CPI<br>           ▼<br>┌─────────────────────┐<br>│  SPL Token Program  │<br>│                     │<br>│  1. Validate        │<br>│  2. Execute         │<br>│  3. Return result   │<br>└─────────────────────┘</pre><p><strong>What happens via CPI : </strong>Mint Tokens</p><pre>// Our program calls SPL Token Program:<br><br>1. Build CPI Accounts:<br>   - mint: mintPDA<br>   - to: aliceTokenAccount<br>   - authority: signer<br><br>2. Create CPI Context:<br>   CpiContext::new(token_program, cpi_accounts)<br><br>3. Call Token Program:<br>   token_interface::mint_to(context, 1_000_000_000)<br><br>4. SPL Token Program executes:<br>   - Verifies authority is mint authority ✅<br>   - Increases mint.supply by 1_000_000_000<br>   - Increases alice_account.amount by 1_000_000_000<br>   - Emits MintTo event</pre><p><strong>What happens via CPI</strong>:Transfer Tokens</p><pre>// Our program calls SPL Token Program:<br><br>1. Read decimals from mint:<br>   decimals = 6<br><br>2. Build CPI Accounts:<br>   - mint: mintPDA<br>   - from: aliceTokenAccount<br>   - to: bobTokenAccount<br>   - authority: alice<br><br>3. Create CPI Context:<br>   CpiContext::new(token_program, cpi_accounts)<br><br>4. Call transfer_checked:<br>   token_interface::transfer_checked(<br>     context,<br>     500_000_000,  // amount<br>     6             // decimals<br>   )<br><br>5. SPL Token Program validates:<br>   - Does alice own sender account? ✅<br>   - Does alice have enough balance? ✅<br>   - Do decimals match? ✅<br>   <br>6. Execute transfer:<br>   - alice_account.amount -= 500_000_000<br>   - bob_account.amount += 500_000_000</pre><h4>⚠️ Production Enhancements</h4><h4>1. Supply Cap</h4><pre>pub fn mint_tokens(ctx: Context&lt;MintTokens&gt;, amount: u64) -&gt; Result&lt;()&gt; {<br>    const MAX_SUPPLY: u64 = 1_000_000_000_000; // 1M tokens with 6 decimals<br>    <br>    let current_supply = ctx.accounts.mint.supply;<br>    require!(<br>        current_supply + amount &lt;= MAX_SUPPLY,<br>        ErrorCode::MaxSupplyReached<br>    );<br>    <br>    // Continue with mint...<br>}</pre><h4>2. Burnable Tokens</h4><pre>pub fn burn_tokens(ctx: Context&lt;BurnTokens&gt;, amount: u64) -&gt; Result&lt;()&gt; {<br>    let cpi_accounts = Burn {<br>        mint: ctx.accounts.mint.to_account_info(),<br>        from: ctx.accounts.token_account.to_account_info(),<br>        authority: ctx.accounts.signer.to_account_info(),<br>    };<br>    <br>    let cpi_context = CpiContext::new(<br>        ctx.accounts.token_program.to_account_info(),<br>        cpi_accounts<br>    );<br>    <br>    token_interface::burn(cpi_context, amount)?;<br>    Ok(())<br>}</pre><h4>3. Pausable Transfers</h4><pre>#[account]<br>pub struct TokenConfig {<br>    pub is_paused: bool,<br>}<br><br>pub fn transfer_tokens(ctx: Context&lt;TransferTokens&gt;, amount: u64) -&gt; Result&lt;()&gt; {<br>    require!(!ctx.accounts.config.is_paused, ErrorCode::TransfersPaused);<br>    <br>    // Continue with transfer...<br>}</pre><h4>4. Token Metadata</h4><pre>use anchor_spl::metadata::{<br>    create_metadata_accounts_v3,<br>    CreateMetadataAccountsV3,<br>    Metadata,<br>};<br><br>pub fn create_token_metadata(<br>    ctx: Context&lt;CreateMetadata&gt;,<br>    name: String,<br>    symbol: String,<br>    uri: String,<br>) -&gt; Result&lt;()&gt; {<br>    // Create metadata for token<br>    // Stores name, symbol, image, etc.<br>}</pre><h4>5. Multi-Signature Mint Authority</h4><pre>#[account]<br>#[account]<br>pub struct MultiSigAuthority {<br>    pub signers: Vec&lt;Pubkey&gt;,<br>    pub threshold: u8,<br>    pub pending_mint: Option&lt;MintProposal&gt;,<br>}<br><br>// Requires multiple signatures before minting</pre><h3>🎓 What You’ve Learned</h3><p>✅ SPL Token architecture (Mint vs Token Account)</p><p>✅ Cross-Program Invocation (CPI)</p><p>✅ PDA-based token accounts</p><p>✅ Mint authority and controls</p><p>✅ Transfer mechanics</p><p><strong>🎉 Congratulations!</strong> You’ve mastered SPL Tokens on Solana! You now understand how every token on Solana works under the hood</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb0ae6ac2fd4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Trustless Escrow Smart Contract on Solana: The Ultimate Guide By Dhruv patel]]></title>
            <link>https://medium.com/@d7511162/building-a-trustless-escrow-smart-contract-on-solana-the-ultimate-guide-by-dhruv-patel-1fa7b41a63ac?source=rss-8de3c9502bfd------2</link>
            <guid isPermaLink="false">https://medium.com/p/1fa7b41a63ac</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[solana-network]]></category>
            <category><![CDATA[solana-blockchain]]></category>
            <category><![CDATA[smart-contract-blockchain]]></category>
            <category><![CDATA[escrow]]></category>
            <dc:creator><![CDATA[Dhruv Patel]]></dc:creator>
            <pubDate>Fri, 13 Mar 2026 16:38:59 GMT</pubDate>
            <atom:updated>2026-03-23T18:32:11.026Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Master secure peer-to-peer trading without intermediaries</strong></p><blockquote><em>⚠️ </em><strong><em>Note for Readers</em></strong></blockquote><blockquote><em>This article is part of my Solana learning series.</em></blockquote><blockquote><em>👉 Before continuing, I highly recommend checking the complete series here:<br></em><a href="https://medium.com/@d7511162/the-solana-learning-ladder-by-dhruv-patel-da5044b6a671"><strong><em>View Full Solana Series</em></strong></a></blockquote><blockquote><em>Following the series in order will give you a much better understanding.</em></blockquote><blockquote><em>However, if you are already familiar with the basics, feel free to continue with this article.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*coRCbeOthpeSVCte5mhxxw.png" /></figure><blockquote><strong>🎯 What is Escrow? Understanding the Concept</strong></blockquote><p>Imagine you’re buying a used iPhone from a stranger online for $500. Here’s the problem:</p><p><strong>❌ Without Escrow:</strong></p><ul><li>You send $500 → They might not send the phone</li><li>They send phone first → You might not pay</li></ul><p><strong>Nobody trusts each other!</strong></p><p><strong>✅ With Traditional Escrow:</strong></p><ol><li>You send $500 to a <strong>trusted third party</strong> (like eBay, Escrow.com)</li><li>They verify and hold your money</li><li>Seller ships the phone</li><li>Third party releases $500 to seller</li></ol><p><strong>Problems:</strong></p><ul><li>💰 Third party charges fees (3–5%)</li><li>⏰ Takes days to process</li><li>🏛️ You must trust the intermediary</li><li>🔒 They can freeze your funds</li></ul><h4>🌟 Enter: Blockchain Escrow (Non-Custodial)</h4><p><strong>What if the “trusted third party” was just… code?</strong></p><p>That’s exactly what we’re building! A <strong>smart contract</strong> that:</p><ul><li>✅ Holds funds securely</li><li>✅ Executes automatically</li><li>✅ Nobody can manipulate</li><li>✅ Zero fees (except blockchain gas)</li><li>✅ Instant settlement</li><li>✅ <strong>YOU control your assets</strong></li></ul><h4>🎬 Real-Life Scenario: Concert Ticket Exchange</h4><p>Let me paint you a picture:</p><p><strong>Meet Alice and Bob:</strong></p><p><strong>Alice</strong> has:</p><ul><li>100 concert tickets (Token X)</li><li>Wants 50 USDC for them</li></ul><p><strong>Bob</strong> has:</p><ul><li>50 USDC (Token Y)</li><li>Wants those 100 tickets</li></ul><p><strong>The Problem:</strong></p><ul><li>They don’t know each other</li><li>No trusted platform between them</li><li>Direct trade = too risky</li></ul><blockquote><strong>🧍 The Actors</strong></blockquote><h4>1. Alice (Seller)</h4><pre>[Seller] (Signer)<br>- Holds SOL &amp; is required to sign transactions</pre><p><strong>Alice owns:</strong></p><ul><li>Seller X Token Account → Has 100 tickets</li><li>Seller Y Token Account → Will receive USDC</li><li>Private key to sign transactions</li></ul><p><strong>Alice’s actions:</strong></p><ul><li>✅ Initialize escrow</li><li>✅ Lock tickets in vault</li><li>✅ Cancel if no buyer</li><li>❌ Cannot withdraw once locked (until cancel)</li></ul><h4>2. Bob (Buyer)</h4><pre>[Buyer] (Signer)<br>- Has token Y (USDC)<br>- Wants X (tickets)</pre><p><strong>Bob owns:</strong></p><ul><li>Buyer Y Token Account → Has 50 USDC</li><li>Buyer X Token Account → Will receive tickets</li><li>Private key to sign transactions</li></ul><p><strong>Bob’s actions:</strong></p><ul><li>✅ Accept the trade</li><li>✅ Pay USDC to Alice</li><li>✅ Receive tickets from vault</li><li>❌ Cannot access vault directly</li></ul><h4>🏭 The Token Mints</h4><h4>X Mint (Concert Tickets)</h4><pre>[X Mint] (Defines X Token)</pre><p><strong>What it is:</strong></p><ul><li>The “type” of token (like USD vs EUR)</li><li>Defines: Decimals, total supply, mint authority</li><li>Example: Concert ticket token</li></ul><p><strong>Purpose:</strong></p><ul><li>Ensures all X tokens are the same type</li><li>Validates token transfers</li></ul><h4>Y Mint (USDC)</h4><pre>[Y Mint] (Defines Y Token)</pre><p><strong>What it is:</strong></p><ul><li>Payment token type</li><li>Example: USDC, USDT, SOL, or custom token</li></ul><p><strong>Purpose:</strong></p><ul><li>Ensures payment is in correct currency</li><li>Validates transfers match expectations</li></ul><h4>💼 The Token Accounts</h4><p>Think of these as <strong>bank accounts</strong> for specific tokens:</p><h4>1. Seller X Token (Alice’s tickets)</h4><pre>[Seller X Token]<br>(Holds Seller&#39;s X)<br>Owner: Seller<br>Mint: X Mint</pre><ul><li><strong>Before Escrow:</strong> 100 tickets</li><li><strong>After Initialize:</strong> 0 tickets (moved to vault)</li><li><strong>After Cancel:</strong> 100 tickets (returned)</li></ul><h4>2. Buyer Y Token (Bob’s USDC)</h4><pre>[Buyer Y Token]<br>(Holds Buyer&#39;s Y)<br>Owner: Buyer<br>Mint: Y Mint</pre><ul><li><strong>Before Accept:</strong> 50 USDC</li><li><strong>After Accept:</strong> 0 USDC (paid to Alice)</li></ul><h4>3. Seller Y Token (Alice’s USDC account)</h4><pre>[Seller Y Token]<br>(Holds Seller&#39;s Y)<br>Owner: Seller<br>Mint: Y Mint</pre><ul><li><strong>Before Accept:</strong> 0 USDC</li><li><strong>After Accept:</strong> 50 USDC (received from Bob)</li></ul><h4>4. Buyer X Token (Bob’s ticket account)</h4><p>rust</p><pre>[Buyer X Token]<br>(Holds Buyer&#39;s X)<br>Owner: Buyer<br>Mint: X Mint</pre><ul><li><strong>Before Accept:</strong> 0 tickets</li><li><strong>After Accept:</strong> 100 tickets (received from vault)</li></ul><h4>🔐 The Vault (Escrowed X Tokens)</h4><p><strong>THE MOST IMPORTANT ACCOUNT!</strong></p><pre>[Escrowed X Tokens (TokenAccount)]<br>(Owned by Token Program, but escrow PDA is its authority)<br><br>Data:<br>- mint: X Mint&#39;s public key<br>- owner: The escrow PDA&#39;s public key (Crucial for non-custodial!)<br>- amount: Current balance of X tokens</pre><p><strong>What makes this special:</strong></p><ol><li><strong>Owned by Escrow PDA (not Alice or Bob)</strong></li></ol><ul><li>Nobody can directly withdraw</li><li>Only program logic controls it</li><li>Uses PDA (Program Derived Address)</li></ul><p><strong>2. Holds Alice’s tokens safely</strong></p><ul><li>Locks during initialize</li><li>Releases to Bob in accept</li><li>Returns to Alice in cancel</li></ul><p><strong>3. The Trust Mechanism</strong></p><ul><li>No human has private key</li><li>Only smart contract code can access</li><li>Cryptographically guaranteed</li></ul><pre>┌────────────────────────────────┐<br>│   Escrowed X Tokens (Vault)    │<br>│                                │<br>│   Owner: Escrow PDA            │<br>│   Authority: Escrow PDA        │<br>│   Mint: X Mint                 │<br>│   Amount: 100 tickets          │<br>│                                │<br>│   🔒 Locked by smart contract  │<br>│   ✅ No human control          │<br>│   🤖 Program logic only        │<br>└────────────────────────────────┘</pre><h4>📋 The Escrow State Account (PDA)</h4><p><strong>The “Brain” of the Escrow</strong></p><pre>[Escrow Account (PDA)]<br>(Owned by non_custodial_escrow program)<br><br>Data:<br>- authority: Public key of the original seller (used to derive PDA)<br>- escrow_x_token: Public key of the Escrowed X Tokens account<br>- bump: A nonce used to derive the PDA (ensures uniqueness)<br>- y_amount: The amount of Y tokens the seller expects<br>- y_mint: The public key of the Y token&#39;s mint</pre><p><strong>Purpose:</strong></p><ul><li>Stores trade parameters</li><li>Links to the vault</li><li>Verifies authorization</li><li>Controls the deal flow</li></ul><p><strong>Constraints:</strong></p><ul><li>Initialized by seller (Alice)</li><li>PDA derived from [&quot;escrow&quot;, seller&#39;s key]</li><li>Cannot be modified after creation</li><li>Closed when deal completes or cancels</li></ul><p><strong>Why PDA?</strong></p><ul><li>No private key exists</li><li>Deterministic address</li><li>Program controls it</li><li>Seller-specific (each seller gets unique PDA)</li></ul><h4>📝 The Complete Code</h4><pre>use anchor_lang::prelude::*;<br>use anchor_spl::token::{<br>    transfer,<br>    close_account,<br>    Mint,<br>    Token,<br>    TokenAccount,<br>    Transfer,<br>    CloseAccount<br>};<br><br>// Declare the program ID (like the unique ID of this marketplace program)<br>declare_id!(&quot;8GvYG8ULeLEzed37GncLHUvjPWUKYsLFMB3ReLo9oiiG&quot;);<br><br>#[program]<br>pub mod non_custodial_escrow {<br>    use super::*;<br><br>    // ========================================================<br>    // INSTRUCTION 1: INITIALIZE ESCROW<br>    // ========================================================<br>    // Alice sets up the trade:<br>    // - Locks her X tokens in vault<br>    // - Specifies how much Y she wants<br>    // - Creates escrow state to track the deal<br>    <br>    pub fn initialize(<br>        ctx: Context&lt;Initialize&gt;,<br>        x_amount: u64,<br>        y_amount: u64<br>    ) -&gt; Result&lt;()&gt; {<br>        <br>        // ────────────────────────────────────────────────<br>        // STEP 1: Create and fill escrow state account<br>        // ────────────────────────────────────────────────<br>        <br>        // Create a new escrow state account and fill it with necessary trade info<br>        let escrow = &amp;mut ctx.accounts.escrow;<br>        <br>        escrow.bump = ctx.bumps.escrow; // PDA bump seed<br>        escrow.authority = ctx.accounts.seller.key(); // Store seller&#39;s (Alice) public key<br>        escrow.escrow_x_token = ctx.accounts.escrowed_x_tokens.key(); // Vault holding Alice&#39;s tokens<br>        escrow.y_amount = y_amount; // Amount of Y tokens (e.g., USDC) Alice expects<br>        escrow.y_mint = ctx.accounts.y_mint.key(); // The mint of Y token (e.g., USDC)<br><br>        // ────────────────────────────────────────────────<br>        // STEP 2: Transfer X tokens from Alice to vault<br>        // ────────────────────────────────────────────────<br>        <br>        // Transfer X tokens (e.g., tickets) from Alice to vault (escrowed_x_tokens)<br>        let cpi_accounts = Transfer {<br>            from: ctx.accounts.seller_x_token.to_account_info(), // Alice&#39;s X token account<br>            to: ctx.accounts.escrowed_x_tokens.to_account_info(), // Vault<br>            authority: ctx.accounts.seller.to_account_info(), // Alice signs the transfer<br>        };<br><br>        let cpi_ctx = CpiContext::new(<br>            ctx.accounts.token_program.to_account_info(),<br>            cpi_accounts<br>        );<br><br>        // CpiContext::new(...): This builds the context for a Cross-Program Invocation (CPI).<br>        // You&#39;re saying: &quot;Hey Token Program! I&#39;m calling you from the Escrow Program and here are<br>        // the accounts you&#39;ll use.&quot;<br>        // ctx.accounts.token_program: This refers to the SPL Token program, which handles all<br>        // token transfers.<br>        // to_account_info(): Converts it into a format that can be passed into the CPI system.<br>        // cpi_accounts: These are the source, destination, and authority for the transfer (see<br>        // below).<br>        <br>        // 📦 Real-life analogy:<br>        // You&#39;re handing over a package to the token delivery service (SPL Token Program) and<br>        // saying:<br>        // &quot;Here&#39;s Alice&#39;s wallet, here&#39;s the vault, and Alice is authorizing this.&quot;<br><br>        transfer(cpi_ctx, x_amount)?; // Execute transfer<br>        <br>        // This is calling the actual token transfer function from anchor_spl::token::transfer.<br>        // x_amount: The number of tokens (e.g., tickets) being transferred.<br>        // ?: Rust syntax to bubble up errors if the transfer fails (like not enough balance or<br>        // bad authority).<br>        <br>        // 📦 Real-life analogy:<br>        // You now tell the delivery service: &quot;Move 3 tickets from Alice&#39;s wallet to the locker.&quot;<br>        // The service checks that Alice really authorized it (she&#39;s the signer), then moves the<br>        // tickets into the vault.<br><br>        Ok(())<br>    }<br><br>    // ========================================================<br>    // INSTRUCTION 2: ACCEPT TRADE<br>    // ========================================================<br>    // Bob completes the deal:<br>    // - Receives X tokens from vault<br>    // - Pays Y tokens to Alice<br>    // - Atomic swap (both happen or neither)<br>    <br>    pub fn accept(ctx: Context&lt;Accept&gt;) -&gt; Result&lt;()&gt; {<br>        <br>        // ────────────────────────────────────────────────<br>        // STEP 1: Transfer X tokens from vault to Bob<br>        // ────────────────────────────────────────────────<br>        <br>        // Transfer X tokens from vault to Bob<br>        transfer(<br>            CpiContext::new_with_signer(<br>                // 🔑 We&#39;re calling an external program (Token Program) and giving it permission<br>                // via a PDA (Program Derived Address) to sign on behalf of the escrow vault.<br>                <br>                ctx.accounts.token_program.to_account_info(),<br>                // This tells the system: &quot;I want to call the Token Program for this action.&quot;<br>                <br>                Transfer {<br>                    from: ctx.accounts.escrowed_x_tokens.to_account_info(), // Vault<br>                    // 📦 This is the vault/locker where Alice stored her X tokens (tickets).<br>                    <br>                    to: ctx.accounts.buyer_x_token.to_account_info(), // Bob&#39;s X token account<br>                    // 📫 Destination: Bob&#39;s token account — he&#39;s receiving the tickets.<br>                    <br>                    authority: ctx.accounts.escrow.to_account_info(), // Escrow PDA signs<br>                    // 🗝 Since the vault is controlled by the escrow PDA, we set it as the<br>                    // signing authority for this transfer.<br>                },<br>                &amp;[&amp;[<br>                    b&quot;escrow&quot;,<br>                    ctx.accounts.escrow.authority.as_ref(),<br>                    &amp;[ctx.accounts.escrow.bump]<br>                ]],<br>                /*This is the same seed recipe used to create the escrow PDA, but now used to<br>                authorize it as a signer.<br>                b&quot;escrow&quot;: a constant seed string (like &quot;locker-type&quot;).<br>                ctx.accounts.escrow.authority.as_ref(): the public key of the seller (Alice) —<br>                part of the PDA seed.<br>                ctx.accounts.escrow.bump: the bump (a special 1-byte value Solana adds to make<br>                sure the generated address doesn&#39;t collide with a real one). Stored during initialization. */<br>                <br>                /*<br>                📦 Real-life example<br>                Imagine:<br>                You create a locker for Alice using a secret code: &quot;escrow&quot; + Alice&#39;s pubkey<br>                Now someone (Bob or Alice) tries to use that locker<br>                Solana checks:<br>                &quot;Are you calling from the same program that created this locker with exactly<br>                that code?&quot;<br>                So this line is proving:<br>                &quot;I&#39;m the program that originally created this PDA (escrow) using these seeds,<br>                and here&#39;s the bump so Solana can find the right address.&quot; */<br>            ),<br>            ctx.accounts.escrowed_x_tokens.amount,<br>            //⬅️ This means: &quot;move everything from the vault to Bob&quot;<br>            <br>            /*<br>            Let&#39;s say Alice deposits 3 concert tickets into a locked ticket box during<br>            initialize.<br>            Then later, when Bob accepts the deal:<br>            The program opens the ticket box<br>            Sees that there are 3 tickets (escrowed_x_tokens.amount)<br>            Transfers exactly that number to Bob.<br>            So yes — the tokens were already deposited earlier, but now you&#39;re reading the<br>            amount from the vault and transferring it out. */<br>        )?;<br><br>        // ────────────────────────────────────────────────<br>        // STEP 2: Transfer Y tokens from Bob to Alice<br>        // ────────────────────────────────────────────────<br>        <br>        // Transfer Y tokens from Bob to Alice<br>        transfer(<br>            CpiContext::new(<br>                ctx.accounts.token_program.to_account_info(),<br>                Transfer {<br>                    from: ctx.accounts.buyer_y_token.to_account_info(), // Bob&#39;s Y token account<br>                    to: ctx.accounts.seller_y_token.to_account_info(), // Alice&#39;s Y token account<br>                    authority: ctx.accounts.buyer.to_account_info(), // Bob signs the transfer<br>                },<br>            ),<br>            ctx.accounts.escrow.y_amount, // Amount Alice requested<br>        )?;<br><br>        Ok(())<br>    }<br><br>    // ========================================================<br>    // INSTRUCTION 3: CANCEL ESCROW<br>    // ========================================================<br>    // Alice cancels the trade:<br>    // - Gets her X tokens back from vault<br>    // - Closes vault account (gets rent back)<br>    // - Escrow state account closed<br>    <br>    pub fn cancel(ctx: Context&lt;Cancel&gt;) -&gt; Result&lt;()&gt; {<br>        <br>        // ────────────────────────────────────────────────<br>        // STEP 1: Return X tokens to Alice<br>        // ────────────────────────────────────────────────<br>        <br>        // Transfer X tokens back from vault to Alice<br>        transfer(<br>            CpiContext::new_with_signer(<br>                ctx.accounts.token_program.to_account_info(),<br>                Transfer {<br>                    from: ctx.accounts.escrowed_x_tokens.to_account_info(), // Vault<br>                    to: ctx.accounts.seller_x_token.to_account_info(), // Alice&#39;s X token account<br>                    authority: ctx.accounts.escrow.to_account_info(), // Escrow PDA signs<br>                },<br>                &amp;[&amp;[<br>                    b&quot;escrow&quot;,<br>                    ctx.accounts.seller.key().as_ref(),<br>                    &amp;[ctx.accounts.escrow.bump]<br>                ]],<br>            ),<br>            ctx.accounts.escrowed_x_tokens.amount, // Send back all X tokens<br>        )?;<br><br>        // ────────────────────────────────────────────────<br>        // STEP 2: Close vault and refund rent<br>        // ────────────────────────────────────────────────<br>        <br>        // Close the vault account and send remaining SOL to Alice<br>        close_account(<br>            CpiContext::new_with_signer(<br>                ctx.accounts.token_program.to_account_info(),<br>                CloseAccount {<br>                    account: ctx.accounts.escrowed_x_tokens.to_account_info(), // Vault to close<br>                    destination: ctx.accounts.seller.to_account_info(), // Alice receives rent<br>                    authority: ctx.accounts.escrow.to_account_info(),<br>                },<br>                &amp;[&amp;[<br>                    b&quot;escrow&quot;,<br>                    ctx.accounts.seller.key().as_ref(),<br>                    &amp;[ctx.accounts.escrow.bump]<br>                ]],<br>            ),<br>        )?;<br><br>        Ok(())<br>    }<br>}<br><br>// ============================================================<br>// DATA STRUCTURES<br>// ============================================================<br><br>// This account stores the escrow state (who&#39;s trading, what amounts, etc.)<br>#[account]<br>#[derive(InitSpace)]<br>pub struct Escrow {<br>    pub authority: Pubkey,      // Seller (Alice) who created the escrow<br>    pub escrow_x_token: Pubkey, // Vault that holds Alice&#39;s X tokens<br>    pub bump: u8,               // PDA bump for escrow PDA<br>    pub y_amount: u64,          // Amount of Y tokens expected (e.g. USDC)<br>    pub y_mint: Pubkey,         // Mint address for Y token (e.g. USDC)<br>}<br><br>// ============================================================<br>// ACCOUNT VALIDATION STRUCTURES<br>// ============================================================<br><br>// Context for initialize: seller sets up the escrow<br>#[derive(Accounts)]<br>pub struct Initialize&lt;&#39;info&gt; {<br>    #[account(mut)]<br>    pub seller: Signer&lt;&#39;info&gt;, // Alice<br><br>    pub x_mint: Account&lt;&#39;info, Mint&gt;, // Token X (e.g. tickets)<br>    pub y_mint: Account&lt;&#39;info, Mint&gt;, // Token Y (e.g. USDC)<br><br>    #[account(<br>        mut,<br>        constraint = seller_x_token.mint == x_mint.key(),<br>        constraint = seller_x_token.owner == seller.key()<br>    )]<br>    pub seller_x_token: Account&lt;&#39;info, TokenAccount&gt;, // Alice&#39;s X token account<br><br>    // Create escrow account (PDA) to store the deal<br>    #[account(<br>        init,<br>        payer = seller,<br>        space = 8 + Escrow::INIT_SPACE,<br>        seeds = [b&quot;escrow&quot;, seller.key().as_ref()],<br>        bump<br>    )]<br>    pub escrow: Account&lt;&#39;info, Escrow&gt;,<br><br>    // Create a vault to hold Alice&#39;s X tokens (owned by escrow PDA)<br>    #[account(<br>        init,<br>        payer = seller,<br>        token::mint = x_mint,<br>        token::authority = escrow<br>    )]<br>    pub escrowed_x_tokens: Account&lt;&#39;info, TokenAccount&gt;,<br><br>    pub token_program: Program&lt;&#39;info, Token&gt;,<br>    pub rent: Sysvar&lt;&#39;info, Rent&gt;,<br>    pub system_program: Program&lt;&#39;info, System&gt;,<br>}<br><br>// Context for accept: buyer completes the deal<br>#[derive(Accounts)]<br>pub struct Accept&lt;&#39;info&gt; {<br>    pub buyer: Signer&lt;&#39;info&gt;, // Bob<br><br>    #[account(<br>        mut,<br>        seeds = [b&quot;escrow&quot;, escrow.authority.as_ref()],<br>        bump = escrow.bump<br>    )]<br>    pub escrow: Account&lt;&#39;info, Escrow&gt;,<br><br>    #[account(<br>        mut,<br>        constraint = escrowed_x_tokens.key() == escrow.escrow_x_token<br>    )]<br>    pub escrowed_x_tokens: Account&lt;&#39;info, TokenAccount&gt;,<br><br>    #[account(<br>        mut,<br>        constraint = seller_y_token.mint == escrow.y_mint<br>    )]<br>    pub seller_y_token: Account&lt;&#39;info, TokenAccount&gt;,<br><br>    #[account(<br>        mut,<br>        constraint = buyer_x_token.mint == escrowed_x_tokens.mint<br>    )]<br>    pub buyer_x_token: Account&lt;&#39;info, TokenAccount&gt;,<br><br>    #[account(<br>        mut,<br>        constraint = buyer_y_token.mint == escrow.y_mint,<br>        constraint = buyer_y_token.owner == buyer.key()<br>    )]<br>    pub buyer_y_token: Account&lt;&#39;info, TokenAccount&gt;,<br><br>    pub token_program: Program&lt;&#39;info, Token&gt;,<br>}<br><br>// Context for cancel: seller cancels escrow<br>#[derive(Accounts)]<br>pub struct Cancel&lt;&#39;info&gt; {<br>    pub seller: Signer&lt;&#39;info&gt;,<br><br>    #[account(<br>        mut,<br>        close = seller,<br>        constraint = escrow.authority == seller.key(),<br>        seeds = [b&quot;escrow&quot;, escrow.authority.as_ref()],<br>        bump = escrow.bump<br>    )]<br>    pub escrow: Account&lt;&#39;info, Escrow&gt;,<br><br>    #[account(<br>        mut,<br>        constraint = escrowed_x_tokens.key() == escrow.escrow_x_token<br>    )]<br>    pub escrowed_x_tokens: Account&lt;&#39;info, TokenAccount&gt;,<br><br>    #[account(<br>        mut,<br>        constraint = seller_x_token.mint == escrowed_x_tokens.mint,<br>        constraint = seller_x_token.owner == seller.key()<br>    )]<br>    pub seller_x_token: Account&lt;&#39;info, TokenAccount&gt;,<br><br>    pub token_program: Program&lt;&#39;info, Token&gt;,<br>}</pre><blockquote><strong>🎬 Complete Execution Flow</strong></blockquote><p>Let me show you EXACTLY what happens in each instruction with visual diagrams!</p><h4>📸 INSTRUCTION 1: Initialize — Lock the Assets</h4><p><strong>Visual Breakdown:</strong></p><pre>┌─────────────────────────────────────────────────────────────────┐<br>│                    INITIALIZE INSTRUCTION                       │<br>├─────────────────────────────────────────────────────────────────┤<br>│                                                                 │<br>│  ┌──────────┐                                                   │<br>│  │  Seller  │  (Alice - Orange Smiley)                         │<br>│  │    😊    │                                                   │<br>│  └────┬─────┘                                                   │<br>│       │                                                         │<br>│       │ initialize()                                            │<br>│       ├──────────────────────►                                 │<br>│       │                                                         │<br>│       │                      ┌────────────────────────────┐    │<br>│       │                      │  Escrow PDA Account        │    │<br>│       │                      │  ┌──────────────────────┐  │    │<br>│       │                      │  │ authority: Pubkey    │  │    │<br>│       │                      │  │ escrow_x_token: PK   │  │    │<br>│       │                      │  │ bump: u8             │  │    │<br>│       │                      │  │ y_amount: u64        │  │    │<br>│       │                      │  │ y_mint: Pubkey       │  │    │<br>│       │                      │  └──────────────────────┘  │    │<br>│       │                      └────────┬───────────────────┘    │<br>│       │                               │                        │<br>│       │                               │ authority              │<br>│       │ Transfer X tokens             │ (controls)             │<br>│       │                               ▼                        │<br>│       └──────────►          ┌─────────────────────┐           │<br>│                             │ escrowed_x_tokens   │           │<br>│                             │ (The Vault)         │           │<br>│                             │                     │           │<br>│                             │ ✅ Holds seller&#39;s   │           │<br>│                             │    X tokens         │           │<br>│                             │ 🔒 Locked safely    │           │<br>│                             └─────────────────────┘           │<br>│                                                                 │<br>└─────────────────────────────────────────────────────────────────┘</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bBkpCtaUMJGgZEXQVziBxA.png" /></figure><p><strong>What Happens Step-by-Step:</strong></p><p><strong>1. Seller Calls </strong><strong>initialize()</strong></p><ul><li>Alice (Orange smiley face) initiates the escrow</li><li>She specifies: “I’m offering X tokens, I want Y tokens in return”</li></ul><p><strong>2. Escrow PDA Account Created</strong></p><pre>Escrow State = {<br>  authority: Alice&#39;s public key,<br>  escrow_x_token: Vault address,<br>  bump: 254 (PDA bump),<br>  y_amount: 50 USDC (what she wants),<br>  y_mint: USDC mint address<br>}</pre><p><strong>3. The Magic: Authority Relationship</strong></p><ul><li>The <strong>Escrow PDA</strong> becomes the authority for the vault</li><li>This blue arrow shows who <strong>CONTROLS</strong> the vault</li><li>Alice cannot withdraw directly anymore</li><li>Only the smart contract (via PDA) can access the vault</li></ul><p><strong>4. Transfer X Tokens</strong></p><ul><li>Alice’s X tokens (100 tickets) move to the vault</li><li>This is a <strong>one-way lock</strong> during initialization</li><li>The vault is now holding her assets securely</li></ul><p><strong>Key Insight:</strong></p><p>The vault (escrowed_x_tokens) is owned by the Token Program, but its <strong>authority</strong> is the Escrow PDA. This means:</p><ul><li>No human has direct access</li><li>Only the program logic can sign for it</li><li>Alice’s tokens are cryptographically locked</li></ul><h4>📸 INSTRUCTION 2: Accept — Complete the Trade</h4><p><strong>Visual Breakdown:</strong></p><pre>┌─────────────────────────────────────────────────────────────────┐<br>│                     ACCEPT INSTRUCTION                          │<br>├─────────────────────────────────────────────────────────────────┤<br>│                                                                 │<br>│  ┌────────────┐              ┌──────────┐                      │<br>│  │   Buyer    │              │  Seller  │                      │<br>│  │ (Green 😊) │              │(Orange😊)│                      │<br>│  └──────┬─────┘              └────▲─────┘                      │<br>│         │                         │                            │<br>│         │ accept()                │                            │<br>│         │                         │                            │<br>│         ├─────────────────────►   │                            │<br>│         │                         │                            │<br>│    ┌────┴─────┐                   │                            │<br>│    │ buyer_y  │   Transfer Y      │  ┌──────────┐             │<br>│    │ _tokens  │   Tokens (USDC)   │  │ seller_y │             │<br>│    │          ├───────────────────┼─►│ _tokens  │             │<br>│    └──────────┘                   │  └──────────┘             │<br>│         │                         │                            │<br>│         │                         │                            │<br>│    ┌────┴─────┐                   │                            │<br>│    │ buyer_x  │◄─────┐            │                            │<br>│    │ _tokens  │      │            │                            │<br>│    └──────────┘      │            │                            │<br>│                      │            │                            │<br>│         ▲            │            │                            │<br>│         │ Transfer X │            │                            │<br>│         │ Tokens     │       ┌────┴───────────────┐           │<br>│         │            │       │ Escrow PDA Account │           │<br>│         │            │       │                    │           │<br>│         │            │       │ authority ────┐    │           │<br>│         │            │       │               │    │           │<br>│         │            │       └───────────────┼────┘           │<br>│         │            │                       │                │<br>│         │            │                       ▼                │<br>│         │            │            ┌─────────────────────┐     │<br>│         │            │            │ escrowed_x_tokens   │     │<br>│         │            └────────────│ (The Vault)         │     │<br>│         │                         │                     │     │<br>│         │                         │ ❌ Now empty        │     │<br>│         └─────────────────────────│ ✅ Tokens released │     │<br>│                                   └─────────────────────┘     │<br>│                                                                 │<br>└─────────────────────────────────────────────────────────────────┘</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O2QovhjXiCi-6HRyn9Kw_w.png" /></figure><p><strong>What Happens Step-by-Step:</strong></p><p><strong>1. Buyer Calls </strong><strong>accept()</strong></p><ul><li>Bob (Green smiley face) decides to complete the trade</li><li>He agrees to Alice’s terms</li></ul><p><strong>2. TWO Simultaneous Transfers (Atomic!)</strong></p><p><strong>Transfer #1: Vault → Buyer (X Tokens)</strong></p><pre>Direction: escrowed_x_tokens → buyer_x_tokens<br>Amount: ALL tokens in vault (100 tickets)<br>Authority: Escrow PDA (signs with seeds!)<br>Result: Bob gets tickets ✅</pre><p><strong>Transfer #2: Buyer → Seller (Y Tokens)</strong></p><pre>Direction: buyer_y_tokens → seller_y_tokens<br>Amount: y_amount from escrow state (50 USDC)<br>Authority: Buyer (Bob signs)<br>Result: Alice gets paid ✅</pre><p><strong>3. The Authority Magic</strong></p><ul><li><strong>Left Blue Arrow</strong>: Buyer has authority over his own tokens</li><li><strong>Right Blue Arrow</strong>: Escrow PDA has authority over the vault</li><li>Both authorities work together to complete the swap</li></ul><p><strong>4. Final State</strong></p><pre>Before:<br>- Vault: 100 tickets 🎫<br>- Bob&#39;s tickets: 0<br>- Bob&#39;s USDC: 50 💵<br>- Alice&#39;s USDC: 0<br><br>After:<br>- Vault: 0 (empty!)<br>- Bob&#39;s tickets: 100 🎫 ✅<br>- Bob&#39;s USDC: 0<br>- Alice&#39;s USDC: 50 💵 ✅</pre><p><strong>Key Insight:</strong></p><p>Both transfers happen in a <strong>single transaction</strong>. If either fails, BOTH are rolled back. This is called <strong>atomicity</strong> — the fundamental guarantee of blockchain escrow!</p><p><strong>The Beauty of This Design:</strong></p><ul><li>Bob cannot get tickets without paying</li><li>Alice cannot get paid without releasing tickets</li><li>Smart contract enforces fairness</li><li>No trust required! 🤝</li></ul><h4>📸 INSTRUCTION 3: Cancel — Get Refund</h4><pre>┌─────────────────────────────────────────────────────────────────┐<br>│                     CANCEL INSTRUCTION                          │<br>├─────────────────────────────────────────────────────────────────┤<br>│                                                                 │<br>│                                                                 │<br>│                         ┌──────────┐                            │<br>│                         │  Seller  │                            │<br>│                         │(Orange😊)│                            │<br>│                         └────▲─────┘                            │<br>│                              │                                  │<br>│                              │ cancel()                         │<br>│              ┌───────────────┤                                  │<br>│              │               │                                  │<br>│              │               │                                  │<br>│         ┌────┴─────┐         │                                  │<br>│         │ seller_x │◄────────┤                                  │<br>│         │ _tokens  │         │                                  │<br>│         └──────────┘         │                                  │<br>│              ▲               │                                  │<br>│              │ Transfer X    │                                  │<br>│              │ Tokens Back   │                                  │<br>│              │          ┌────┴───────────────┐                 │<br>│              │          │ Escrow PDA Account │                 │<br>│              │          │                    │                 │<br>│              │          │ authority ────┐    │                 │<br>│              │          │               │    │                 │<br>│              │          └───────────────┼────┘                 │<br>│              │                          │                      │<br>│              │                          ▼                      │<br>│              │               ┌─────────────────────┐           │<br>│              │               │ escrowed_x_tokens   │           │<br>│              └───────────────│ (The Vault)         │           │<br>│                              │                     │           │<br>│                              │ ❌ CLOSED           │           │<br>│                              │ ✅ Tokens returned  │           │<br>│                              │ 💰 Rent refunded    │           │<br>│                              └─────────────────────┘           │<br>│                                        │                       │<br>│                                        │                       │<br>│                                        ▼                       │<br>│                                      ┌───┐                     │<br>│                                      │ ❌ │                     │<br>│                                      │DEL│                     │<br>│                                      └───┘                     │<br>│                                   (Deleted)                    │<br>│                                                                 │<br>└─────────────────────────────────────────────────────────────────┘</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S4Yw94cZC3hlBm4F3rzuSQ.png" /></figure><p><strong>What Happens Step-by-Step:</strong></p><p><strong>1. Seller Calls </strong><strong>cancel()</strong></p><ul><li>Alice (Orange smiley) decides to cancel the escrow</li><li>Maybe no buyer showed up, or she changed her mind</li><li>Only the <strong>original seller</strong> can cancel (authority check!)</li></ul><p><strong>2. Return X Tokens</strong></p><pre>Direction: escrowed_x_tokens → seller_x_tokens<br>Amount: ALL tokens in vault (100 tickets)<br>Authority: Escrow PDA (signs with seeds)<br>Result: Alice gets her tickets back ✅</pre><p><strong>3. Close the Vault Account</strong></p><pre>Action: close_account()<br>Account: escrowed_x_tokens<br>Destination: seller (Alice)<br>Effect: <br>  - Vault account deleted<br>  - Rent (~0.002 SOL) returned to Alice 💰<br>  - Token account no longer exists</pre><p><strong>4. Escrow State Account Closed</strong></p><pre>The Escrow PDA account also closes:<br>  - Rent returned to Alice<br>  - All data deleted<br>  - Escrow no longer exists</pre><p><strong>Key Insight:</strong></p><p>When you close accounts on Solana, you get the <strong>rent back</strong>! This makes escrow very cheap:</p><ul><li>Initialize: ~0.004 SOL (locked as rent)</li><li>Cancel: ~0.000005 SOL fee, BUT you get ~0.004 SOL rent back!</li><li><strong>Net cost:</strong> Nearly free! 💰</li></ul><p><strong>Final State:</strong></p><pre>Before Cancel:<br>- Alice&#39;s tickets: 0<br>- Vault: 100 tickets (locked)<br>- Escrow: Active<br>- Rent: 0.004 SOL locked<br><br>After Cancel:<br>- Alice&#39;s tickets: 100 ✅ (returned)<br>- Vault: Deleted ❌<br>- Escrow: Deleted ❌<br>- Rent: 0.004 SOL ✅ (refunded)</pre><p><strong>Security </strong>Checks<strong>:</strong></p><pre>constraint = escrow.authority == seller.key()</pre><ul><li>Only Alice (original seller) can cancel</li><li>Bob (or anyone else) cannot cancel Alice’s escrow</li><li>The PDA seeds must match the seller’s key</li></ul><blockquote><strong>REVISION</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*qb6NsDslF20R5BNY2yqQJQ.png" /></figure><blockquote><strong>🔐 Security Deep Dive</strong></blockquote><h4>1. PDA Authority Pattern</h4><p><strong>Why PDAs are crucial:</strong></p><pre>seeds = [b&quot;escrow&quot;, seller.key().as_ref()]</pre><p><strong>What this guarantees:</strong></p><ul><li>✅ No private key exists for this address</li><li>✅ Only the program can sign for it</li><li>✅ Deterministic (same inputs = same address)</li><li>✅ Each seller gets unique escrow</li></ul><p><strong>Security implications:</strong></p><ul><li>Nobody can steal funds from vault</li><li>Only program logic can access</li><li>Cryptographically enforced</li></ul><h4>2. CPI with Signer</h4><pre>CpiContext::new_with_signer(<br>    token_program,<br>    transfer_accounts,<br>    &amp;[&amp;[b&quot;escrow&quot;, authority, &amp;[bump]]]<br>)</pre><p><strong>How it works:</strong></p><ol><li>Program re-derives PDA from seeds</li><li>Proves it owns this PDA</li><li>SPL Token Program validates</li><li>Transfer authorized</li></ol><p><strong>Attack scenarios prevented:</strong></p><ul><li>❌ User cannot fake PDA signature</li><li>❌ Wrong program cannot use PDA</li><li>❌ Incorrect seeds fail validation</li></ul><h4>3. Atomic Execution</h4><p><strong>In </strong><strong>accept function:</strong></p><p>rust</p><pre>// Step 1: Vault → Bob<br>transfer(..., tickets)?;<br>// Step 2: Bob → Alice<br>transfer(..., usdc)?;</pre><p><strong>If Step 2 fails:</strong></p><ul><li>Entire transaction reverts</li><li>Step 1 is undone</li><li>Nobody loses funds</li></ul><p><strong>This is atomicity:</strong></p><ul><li>Both happen or neither</li><li>No partial execution</li><li>Blockchain guarantee</li></ul><blockquote><strong>⚠️ Production Enhancements</strong></blockquote><h4>1. Time-Lock Escrow</h4><pre>#[account]<br>pub struct Escrow {<br>    pub authority: Pubkey,<br>    pub escrow_x_token: Pubkey,<br>    pub bump: u8,<br>    pub y_amount: u64,<br>    pub y_mint: Pubkey,<br>    pub expiry: i64,  // Unix timestamp<br>}<br>// In accept:<br>let clock = Clock::get()?;<br>require!(clock.unix_timestamp &lt; escrow.expiry, ErrorCode::Expired);</pre><h4>3. Multi-Token Escrow</h4><pre>#[account]<br>pub struct Escrow {<br>    pub authority: Pubkey,<br>    pub x_tokens: Vec&lt;TokenRequest&gt;,  // Multiple tokens wanted<br>    pub y_tokens: Vec&lt;TokenRequest&gt;,  // Multiple tokens offered<br>    // ...<br>}</pre><h3>🎓 What You’ve Learned</h3><p>✅ What escrow is and why it’s needed</p><p>✅ Non-custodial vs custodial escrow</p><p>✅ Complete escrow architecture</p><p>✅ PDA authority pattern</p><p>✅ CPI with signer (advanced!)</p><p>✅ Token vault mechanism</p><p>✅ Atomic swaps</p><p>✅ Account closing and rent refunds</p><p>✅ Production-ready patterns</p><p><strong>🎉 Congratulations!</strong> You’ve mastered one of the most powerful patterns in DeFi — non-custodial escrow!</p><p><strong>Go build trustless systems! 🤝⚡</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1fa7b41a63ac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ethereum vs Solana: The Architecture Battle You Need to Understand]]></title>
            <link>https://medium.com/@d7511162/ethereum-vs-solana-the-architecture-battle-you-need-to-understand-21e270e4343d?source=rss-8de3c9502bfd------2</link>
            <guid isPermaLink="false">https://medium.com/p/21e270e4343d</guid>
            <category><![CDATA[blockchain-technology]]></category>
            <category><![CDATA[eth-vs-sol]]></category>
            <category><![CDATA[solana-blockchain]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[blockchain-ecosystems]]></category>
            <dc:creator><![CDATA[Dhruv Patel]]></dc:creator>
            <pubDate>Tue, 10 Mar 2026 11:10:17 GMT</pubDate>
            <atom:updated>2026-03-23T18:30:33.662Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>Why one blockchain has a single cashier while the other runs a full-fledged supermarket</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OmTDo9W8vxtWGrAOOITyeA.png" /></figure><blockquote><em>⚠️ </em><strong><em>Note for Readers</em></strong></blockquote><blockquote><em>This article is part of my Solana learning series.</em></blockquote><blockquote><em>👉 Before continuing, I highly recommend checking the complete series here:<br></em><a href="https://medium.com/@d7511162/the-solana-learning-ladder-by-dhruv-patel-da5044b6a671"><strong><em>View Full Solana Series</em></strong></a></blockquote><blockquote><em>Following the series in order will give you a much better understanding.</em></blockquote><blockquote><em>However, if you are already familiar with the basics, feel free to continue with this article.</em></blockquote><p>Picture this: You’re building the next big social media app. On blockchain. Revolutionary, right?</p><p>But here’s where it gets interesting — the blockchain you choose will fundamentally change how you build it.</p><p>Let me break down the architectural philosophy that separates Ethereum and Solana, and trust me, it’s more fascinating than it sounds.</p><blockquote><strong>🏗️ The Fundamental Split: Where Does Your Data Live?</strong></blockquote><h4>Ethereum: The All-in-One Notebook</h4><p>When you deploy a contract on Ethereum, you’re essentially deploying a complete package:</p><ul><li>The rules (logic)</li><li>The storage (data)</li><li>Everything, together, in one place</li></ul><p>Your social media contract would hold:</p><ul><li>User profiles ✅</li><li>Posts ✅</li><li>Likes ✅</li><li>Comments ✅</li></ul><p>All bundled together. One contract, one package, one deployment.</p><p><strong>Simple. Straightforward. Self-contained.</strong></p><h4>Solana: The Separation of Church and State</h4><p>Solana looked at this and said, <em>“What if we didn’t do that?”</em></p><p>Instead, Solana splits things into two distinct entities:</p><p><strong>Programs</strong> = The Logic (the brain)<br> <strong>Accounts</strong> = The Data (the storage)</p><p>Think of programs as vending machines and accounts as the actual snacks inside.</p><p>The vending machine (program) has all the logic:</p><ul><li>How to dispense</li><li>How to accept payment</li><li>What to do when someone selects A3</li></ul><p>But the snacks themselves (accounts)? They’re separate. Replaceable. Independent.</p><p>In your social media app:</p><ul><li>The <strong>program</strong> knows how to create posts, add likes, verify users</li><li>Each <strong>account</strong> stores one specific piece of data — a profile, a post, a comment</li></ul><p><strong>This changes everything.</strong></p><blockquote><strong>♻️ Reusability: Why This Design Choice Matters</strong></blockquote><p>Here’s where Ethereum developers might raise an eyebrow.</p><p>On Ethereum, if 10 different teams want to build similar functionality, they often end up deploying 10 slightly different versions of the same contract logic.</p><p>It’s like having 10 different calculators that all do addition — just coded separately.</p><p><strong>On Solana?</strong></p><p>One program. Millions of users.</p><p>Because the program is just the logic, it can serve anyone. Think of it like a backend API server that multiple apps can call.</p><ul><li>The program = The server logic</li><li>Accounts = Database records</li></ul><p>One reusable program interacts with thousands of different accounts holding different data.</p><p><strong>Efficient. Elegant. Scalable.</strong></p><blockquote><strong>⚡ The Speed Secret: Parallel Execution</strong></blockquote><p>This is where Solana flexes.</p><h4>Ethereum: The Single Cashier Problem</h4><p>Imagine a supermarket with <strong>one cashier</strong>. Doesn’t matter how many customers show up — everyone waits in one line.</p><p>Customer 1 checks out → Customer 2 → Customer 3</p><p>One. By. One.</p><p>That’s Ethereum’s execution model. Transactions are processed sequentially, even if they’re completely unrelated.</p><h4>Solana: The Multi-Cashier Advantage</h4><p>Now imagine 20 cashiers.</p><p>If you’re buying bread and someone else is buying milk, you can both check out simultaneously.</p><p>But if two people try to grab the <strong>same</strong> loaf? They wait.</p><p>Solana’s smart enough to know which accounts each transaction will touch. If two transactions interact with different accounts, boom — they run in parallel on different CPU cores.</p><p><strong>This is the secret sauce.</strong></p><p>By separating programs and accounts, Solana can leverage modern multi-core processors. Ethereum’s single-threaded execution can’t do this as effectively.</p><blockquote><strong>📝 Transactions: One Call vs Multiple Instructions</strong></blockquote><p>On Ethereum, most transactions call <strong>one function</strong>:</p><ul><li>Swap tokens</li><li>Approve tokens</li><li>Transfer tokens</li></ul><p>Want to do three things? You’ll likely need three transactions.</p><p>Solana transactions are more like <strong>mini-scripts</strong>.</p><p>One transaction can:</p><ol><li>Create a user profile</li><li>Make a post</li><li>Update a counter</li></ol><p>All atomically. If step 2 fails, the whole thing rolls back.</p><p>It’s like running a batch file instead of typing commands one by one.</p><blockquote><strong>🚦 Mempool: The Waiting Room Dilemma</strong></blockquote><p><strong>Ethereum</strong> has a mempool — essentially a waiting room where transactions sit until a validator picks them up.</p><p>During peak times, this waiting room gets <em>packed</em>. Your transaction sits there, hoping to get picked, while gas prices surge.</p><p>It’s like sending a package that waits in a sorting warehouse before delivery.</p><p><strong>Solana</strong> said, <em>“Why wait?”</em></p><p>Instead of a mempool, Solana validators <strong>forward transactions directly</strong> to future block leaders. Since Solana already knows who’s producing the next blocks, transactions go straight there.</p><p>Less waiting. Faster processing. Higher throughput.</p><blockquote><strong>💰 Gas vs Compute Units</strong></blockquote><p><strong>Ethereum</strong> uses <strong>Gas</strong> — a measure of computational work that fluctuates with network demand.</p><p><strong>Solana</strong> uses <strong>Compute Units</strong> — a fixed measure of CPU work.</p><ul><li>~1.4M compute units per transaction</li><li>~48M compute units per block</li></ul><p>Because of parallel execution, Solana squeezes way more operations into the same time window.</p><blockquote><strong>🛠️ Developer Experience</strong></blockquote><p><strong>Ethereum devs</strong> live in:</p><ul><li>Hardhat</li><li>Remix</li><li>Ethers.js</li><li>Solidity</li></ul><p><strong>Solana devs</strong> work with:</p><ul><li>Anchor framework</li><li>@solana/web3.js</li><li>Rust (mostly)</li><li>Solana Test Validator</li></ul><p>The concepts translate, but the tools feel different.</p><p><strong>Plot twist:</strong> Projects like <strong>Neon EVM</strong> let you run Solidity contracts on Solana infrastructure. So Ethereum devs can keep their favorite language while riding Solana’s performance wave.</p><h3>The Core Philosophy</h3><p>At the end of the day, this all boils down to a fundamental design choice:</p><p><strong>Ethereum:</strong> Smart contracts are complete applications. Logic + state bundled together. Simple, secure, self-contained.</p><p><strong>Solana:</strong> Programs are logic. Accounts are data. Separated, reusable, parallelizable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B6JUdzSMriauGvLHtw8OEQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/1*cvqW9JlFxZZgZ6HmkORcMw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7F1-uRS1yC5Oo1OMdKoN0g.png" /></figure><h4><strong>Why Ethereum’s Approach Works:</strong></h4><p>✅ Simplicity<br> ✅ Strong security guarantees<br> ✅ Battle-tested architecture<br> ✅ Easier mental model for beginners</p><h4>Why Solana’s Approach Works:</h4><p>✅ Massive parallelization<br> ✅ Program reusability<br> ✅ Utilizes modern hardware<br> ✅ Higher throughput potential</p><h4>So Which One Should You Choose?</h4><p>That depends.</p><p>Are you building something where <strong>security and simplicity</strong> are paramount? Where you can tolerate slower speeds for battle-tested guarantees? <strong>Ethereum.</strong></p><p>Are you building something that demands <strong>speed, scale, and parallel execution</strong>? Where you need to process thousands of transactions per second? <strong>Solana.</strong></p><p>Both are powerful. Both have their place.</p><p>They’re not competitors in a zero-sum game — they’re different philosophies solving different problems.</p><p><strong>Understanding the architecture is what separates builders from button-pushers.</strong></p><p>Now you know the real difference. Not just <em>“Solana fast, Ethereum slow”</em> — but <em>why</em>.</p><p>If this helped you understand Solana a little better, consider following for more deep dives into Web3 concepts.</p><p>Have a question or something you’re curious about? Drop it in the comments — I’d love to discuss it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=21e270e4343d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Solana Web3.js By Dhruv patel]]></title>
            <link>https://medium.com/@d7511162/solana-web3-js-by-dhruv-patel-4a4f6164670f?source=rss-8de3c9502bfd------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a4f6164670f</guid>
            <category><![CDATA[solana-network]]></category>
            <category><![CDATA[solana-blockchain]]></category>
            <category><![CDATA[solana-web3js]]></category>
            <category><![CDATA[web3j]]></category>
            <category><![CDATA[libraries]]></category>
            <dc:creator><![CDATA[Dhruv Patel]]></dc:creator>
            <pubDate>Mon, 09 Mar 2026 18:10:39 GMT</pubDate>
            <atom:updated>2026-03-23T18:28:43.742Z</atom:updated>
            <content:encoded><![CDATA[<h4>Getting Started with Solana Web3.js: A Complete Guide from Installation to Your First Transaction</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sx0VFi0fTDvIGx2vlQMupg.png" /></figure><blockquote><em>⚠️ </em><strong><em>Note for Readers</em></strong></blockquote><blockquote><em>This article is part of my Solana learning series.</em></blockquote><blockquote><em>👉 Before continuing, I highly recommend checking the complete series here:<br></em><a href="https://medium.com/@d7511162/the-solana-learning-ladder-by-dhruv-patel-da5044b6a671"><strong><em>View Full Solana Series</em></strong></a></blockquote><blockquote><em>Following the series in order will give you a much better understanding.</em></blockquote><blockquote><em>However, if you are already familiar with the basics, feel free to continue with this article.</em></blockquote><p>Solana is one of the fastest blockchains in the world, and as a developer, the @solana/web3.js library is your gateway to interacting with it.</p><p>In this article, we’ll walk through everything you need to know: from setting up your environment to sending your first transaction on the Solana Devnet.</p><h4>Mandatory Step: Install Solana CLI</h4><p>you MUST install the <strong>Solana CLI (Command Line Interface) and all</strong>. This tool lets you:</p><ul><li>Create local wallets.</li><li>Interact with the network directly (Airdrops, config, etc.).</li><li>Deploy smart contracts.</li></ul><p>👉 <strong>Official Installation Guide:</strong> <a href="https://solana.com/docs/intro/installation">Install the Solana CLI</a>3. Installation and Setup.During the Solana installation, you must read and perform both the Solana CLI basics and the install dependencies sections</p><p>Now, let’s set up our project folder:</p><pre>mkdir solana-web3-js-tutorial<br>cd solana-web3-js-tutorial<br>npm init -y</pre><p>Now, install the Solana Web3.js library:</p><pre>npm install @solana/web3.js</pre><p>To use ES Modules (the import syntax), open your package.json and add &quot;type&quot;: &quot;module&quot;:</p><pre>{<br>  &quot;name&quot;: &quot;solana-web3js&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;type&quot;: &quot;module&quot;,<br>  &quot;dependencies&quot;: {<br>    &quot;@solana/web3.js&quot;: &quot;^1.98.2&quot;<br>  }<br>}</pre><h4>Step 1: Generating a New Wallet (Keypair)</h4><p>In Solana, a wallet is represented by a <strong>Keypair</strong>. It consists of a <strong>Public Key</strong> (your address) and a <strong>Secret Key</strong> (your password).</p><p>Create a file named</p><p>keypair.js:</p><pre>import { Keypair } from &quot;@solana/web3.js&quot;;<br><br>/**<br> * STEP 1: Generating a new Keypair<br> */<br><br>// Generate a brand new wallet<br>const keypair = Keypair.generate();<br><br>console.log(&quot;--- New Wallet Generated ---&quot;);<br>console.log(&quot;Public Key (Address):&quot;, keypair.publicKey.toBase58());<br>console.log(&quot;Secret Key (Uint8Array):&quot;, keypair.secretKey);<br>console.log(&quot;----------------------------&quot;);<br>console.log(&quot;TIP: Never share your Secret Key in production!&quot;);</pre><p><strong>Run it:</strong> node keypair.js</p><h4>4. Step 2: Connecting to the Network and Fetching Balance</h4><p>To interact with the blockchain, you need to connect to a <strong>Node</strong>. Solana has three main networks:</p><ul><li><strong>Mainnet Beta</strong>: Real money, live network.</li><li><strong>Devnet</strong>: For developers to test applications (FREE SOL!).</li><li><strong>Testnet</strong>: For testing network updates.</li></ul><p>Create a file named</p><p>balance.js:</p><pre>import { Connection, PublicKey, LAMPORTS_PER_SOL } from &quot;@solana/web3.js&quot;;<br><br>/**<br> * STEP 2: Connecting to the Network and Fetching Balance<br> */<br><br>// Connect to Devnet<br>const connection = new Connection(&quot;https://api.devnet.solana.com&quot;, &quot;confirmed&quot;);<br><br>const getBalance = async () =&gt; {<br>    // Replace this with your Public Key from Step 1<br>    const publicKey = new PublicKey(&quot;Your_Public_Key_Here&quot;);<br><br>    // Fetch balance in Lamports (1 SOL = 1 Billion Lamports)<br>    const balance = await connection.getBalance(publicKey);<br>    <br>    // Convert to SOL<br>    const balanceSOL = balance / LAMPORTS_PER_SOL;<br>    <br>    console.log(`Address: ${publicKey.toBase58()}`);<br>    console.log(`Balance: ${balanceSOL} SOL`);<br>}<br><br>getBalance();</pre><p><strong>Run it:</strong> node balance.js</p><p>Since you installed the Solana CLI , you can now get free SOL on Devnet:</p><ol><li>Open your terminal.</li><li>Run this command:</li></ol><pre>solana airdrop 2 Your_Public_Key_Here --url devnet</pre><p>This will give you 2 Devnet SOL to play with!</p><p>If the above command doesn’t work, you can request SOL from the faucet mentioned in the installation instructions.</p><h4>Step 3: Sending Your First Transaction</h4><p>Now, let’s move some “money”! To send SOL, we create a <strong>Transaction</strong>, add a <strong>Transfer Instruction</strong>, and sign it with our <strong>Secret Key</strong>.</p><p>Create a file named transfer.js:</p><pre>import {<br>  Keypair,<br>  Connection,<br>  PublicKey,<br>  Transaction,<br>  SystemProgram,<br>  sendAndConfirmTransaction,<br>} from &quot;@solana/web3.js&quot;;<br><br>/**<br> * STEP 3: Transferring SOL between Wallets<br> */<br><br>const connection = new Connection(&quot;https://api.devnet.solana.com&quot;, &quot;confirmed&quot;);<br><br>// Load your wallet using its Secret Key<br>const secretKey = Uint8Array.from([/* Paste your Secret Key array here */]);<br>const senderKeyPair = Keypair.fromSecretKey(secretKey);<br><br>const receiverPubKey = new PublicKey(&quot;Recipient_Address_Here&quot;);<br><br>const transaction = new Transaction();<br><br>// Define the transfer instruction<br>const sendSolInstruction = SystemProgram.transfer({<br>  fromPubkey: senderKeyPair.publicKey,<br>  toPubkey: receiverPubKey,<br>  lamports: 1000, // Very small amount for testing<br>});<br><br>transaction.add(sendSolInstruction);<br><br>(async () =&gt; {<br>  try {<br>    // Sign and send the transaction<br>    const txSignature = await sendAndConfirmTransaction(<br>      connection,<br>      transaction,<br>      [senderKeyPair]<br>    );<br>    <br>    console.log(&quot;Transaction Successful!&quot;);<br>    console.log(&quot;Explorer URL:&quot;, `https://explorer.solana.com/tx/${txSignature}?cluster=devnet`);<br>  } catch (error) {<br>    console.error(&quot;Transaction failed:&quot;, error);<br>  }<br>})();</pre><p><strong>Run it:</strong> node transfer.js</p><h4>Conclusion</h4><p>Congratulations! You’ve just:</p><ol><li>Setup a Solana development environment.</li><li>Generated a secure wallet.</li><li>Checked your balance on the Devnet.</li><li>Executed a real blockchain transaction.</li></ol><p><strong>📦 GitHub Repository:</strong> <a href="https://github.com/Dhruv-0101/SOLANA_WEB3JS.git">https://github.com/Dhruv-0101/SOLANA_WEB3JS.git</a></p><p><em>If you found this helpful, follow me for more Web3 tutorials and docs.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a4f6164670f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Complete Developer’s Guide to Smart Contracts on Solana by Dhruv Patel]]></title>
            <link>https://medium.com/@d7511162/the-complete-developers-guide-to-smart-contracts-on-solana-by-dhruv-patel-134ebbdb759d?source=rss-8de3c9502bfd------2</link>
            <guid isPermaLink="false">https://medium.com/p/134ebbdb759d</guid>
            <category><![CDATA[anchor]]></category>
            <category><![CDATA[blockchain-development]]></category>
            <category><![CDATA[blockchain-technology]]></category>
            <category><![CDATA[solana-blockchain]]></category>
            <category><![CDATA[solana-network]]></category>
            <dc:creator><![CDATA[Dhruv Patel]]></dc:creator>
            <pubDate>Mon, 09 Mar 2026 10:05:18 GMT</pubDate>
            <atom:updated>2026-03-23T18:27:03.809Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*OH_vbAtkra8rwLmpgcuM4Q.png" /></figure><blockquote><em>⚠️ </em><strong><em>Note for Readers</em></strong></blockquote><blockquote><em>This article is part of my Solana learning series.</em></blockquote><blockquote><em>👉 Before continuing, I highly recommend checking the complete series here:<br></em><a href="https://medium.com/@d7511162/the-solana-learning-ladder-by-dhruv-patel-da5044b6a671"><strong><em>View Full Solana Series</em></strong></a></blockquote><blockquote><em>Following the series in order will give you a much better understanding.</em></blockquote><blockquote><em>However, if you are already familiar with the basics, feel free to continue with this article.</em></blockquote><p><strong>Learn Smart Contract Development by Building Three Practical Projects</strong></p><ol><li><strong>Global Counter</strong> — A simple smart contract that maintains a single counter shared across all users.</li><li><strong>User-Specific Counters with PDAs</strong> — Counters uniquely associated with each user using <strong>Program Derived Addresses (PDAs)</strong>.</li><li><strong>Decentralized Instagram (On-Chain Logic)</strong> — A functional social application powered by smart contracts, featuring profiles, posts, likes, follows, comments, and other core Instagram-like interactions.</li></ol><h4>🎓 What You’ll Build</h4><p>By the end of this guide, you’ll have built <strong>three application’s smart contract</strong>:</p><h4>1. Global Counter 🌍</h4><p>Your first Solana program — a shared counter anyone can modify. Perfect for understanding:</p><ul><li>Basic Anchor structure</li><li>Account creation and management</li><li>Program instructions</li><li>On-chain data storage</li></ul><h4>2. User-Specific Counter 👤</h4><p>Level up with PDAs (Program Derived Addresses) — each user gets their own isolated counter. You’ll master:</p><ul><li>PDA derivation and security</li><li>Deterministic addressing</li><li>Access control</li><li>User-specific data isolation</li></ul><h4>3. Decentralized Instagram 📸</h4><p>The grand finale — a complete social media platform with profiles, posts, comments, likes, and follows. You’ll implement:</p><ul><li>Multi-account architectures</li><li>Hierarchical data relationships</li><li>Complex state management</li><li>Real-world dApp patterns</li></ul><h4>🎯 Who Is This Guide For?</h4><p><strong>Perfect if you:</strong></p><ul><li>✅ Have some Rust familiarity (we explain as we go)</li><li>✅ Want to build real Solana applications</li><li>✅ Are tired of incomplete tutorials</li><li>✅ Learn best by building actual projects</li></ul><h4>🛠️ What You’ll Learn</h4><p><strong>Core Concepts:</strong></p><ul><li>Anchor framework architecture</li><li>Program vs Data account separation</li><li>Account validation and constraints</li><li>Memory management and rent</li><li>Transaction lifecycle</li></ul><p><strong>Advanced Patterns:</strong></p><ul><li>PDA (Program Derived Address) design</li><li>Seeds-based addressing</li><li>Multi-account relationships</li><li>Security best practices</li></ul><h3>🌍 Building a Global Counter on Solana with Anchor Framework</h3><p><strong>A step-by-step guide to creating your first Solana smart contract</strong></p><h4>🎯 What We’re Building</h4><p>In this tutorial, we’ll build a simple but powerful <strong>Global Counter</strong> on Solana blockchain using the Anchor framework. This counter can be:</p><ul><li>Initialized by anyone</li><li>Incremented by anyone</li><li>Decremented by anyone</li><li>Permanently stored on-chain</li></ul><p>This is the perfect starting point for understanding Solana program development!</p><h4>📝 The Complete Code</h4><pre>// ======================================================<br>// 1️⃣ IMPORT ANCHOR FRAMEWORK<br>// ======================================================<br><br>// Anchor framework makes writing Solana programs easy.<br>// This prelude contains all common types and macros:<br>// Account, Context, Result, Signer, Program etc.<br><br>use anchor_lang::prelude::*;<br><br><br>// ======================================================<br>// 2️⃣ PROGRAM ID<br>// ======================================================<br><br>// This is the program&#39;s unique blockchain address.<br>//<br>// When you run `anchor deploy`, a PROGRAM ACCOUNT is created<br>// on the Solana blockchain with this address.<br>//<br>// The compiled code is stored in this program account.<br><br>declare_id!(&quot;Cnacumam4T7iJwvtCcbgcFsJgUVX84aspw7177UwQjP&quot;);<br><br><br><br>// ======================================================<br>// 3️⃣ PROGRAM MODULE (SMART CONTRACT LOGIC)<br>// ======================================================<br><br>// ⚠️ IMPORTANT<br>// The #[program] macro tells Anchor:<br>//<br>// &quot;This module defines Solana instructions&quot;<br>//<br>// The functions inside this module<br>// become callable instructions on the blockchain.<br>//<br>// Example:<br>// initialize_counter()<br>// increment_counter()<br>// decrement_counter()<br><br>#[program]<br>pub mod counter {<br><br>    // imports from parent scope<br>    use super::*;<br><br>    // ==================================================<br>    // 4️⃣ INSTRUCTION → INITIALIZE COUNTER<br>    // ==================================================<br><br>    // When a user calls the initialize_counter instruction,<br>    // this function will execute.<br><br>    pub fn initialize_counter(ctx: Context&lt;InitializeCounter&gt;) -&gt; Result&lt;()&gt; {<br><br>        // ------------------------------------------------<br>        // What is ctx?<br>        // ------------------------------------------------<br>        //<br>        // ctx = Context object<br>        //<br>        // It contains all the accounts that came<br>        // with the transaction.<br>        //<br>        // Structure looks like this:<br>        //<br>        // ctx<br>        //  └── accounts<br>        //        ├── payer<br>        //        ├── counter<br>        //        └── system_program<br><br><br>        // ------------------------------------------------<br>        // What is ctx.accounts.counter?<br>        // ------------------------------------------------<br>        //<br>        // This is a DATA ACCOUNT on the blockchain.<br>        //<br>        // This account&#39;s data type is:<br>        //<br>        // Counter struct<br>        //<br>        // ⚠️ Important<br>        //<br>        // &quot;counter&quot; here is NOT a program.<br>        //<br>        // It&#39;s just an ACCOUNT VARIABLE<br>        // that represents a data account on the blockchain.<br><br><br>        // getting mutable reference<br>        let counter_account = &amp;mut ctx.accounts.counter;<br><br><br>        // ------------------------------------------------<br>        // Initializing the data<br>        // ------------------------------------------------<br>        //<br>        // Setting the field of Counter struct<br><br>        counter_account.count = 0;<br><br><br>        // return success<br>        Ok(())<br>    }<br><br><br><br>    // ==================================================<br>    // 5️⃣ INSTRUCTION → INCREMENT COUNTER<br>    // ==================================================<br><br>    pub fn increment_counter(ctx: Context&lt;IncrementCounter&gt;) -&gt; Result&lt;()&gt; {<br><br>        // This instruction will modify the blockchain account&#39;s data.<br><br>        ctx.accounts.counter.count += 1;<br><br>        Ok(())<br>    }<br><br><br><br>    // ==================================================<br>    // 6️⃣ INSTRUCTION → DECREMENT COUNTER<br>    // ==================================================<br><br>    pub fn decrement_counter(ctx: Context&lt;DecrementCounter&gt;) -&gt; Result&lt;()&gt; {<br><br>        ctx.accounts.counter.count -= 1;<br><br>        Ok(())<br>    }<br>}<br><br><br><br>// ======================================================<br>// 7️⃣ BLOCKCHAIN DATA STRUCTURE<br>// ======================================================<br><br>// ⚠️ IMPORTANT<br>//<br>// This is NOT a program.<br>//<br>// It&#39;s just a DATA STRUCTURE that<br>// gets stored inside a blockchain account.<br><br>#[account]<br><br>// InitSpace automatically calculates<br>// the required memory for the struct<br>#[derive(InitSpace)]<br>pub struct Counter {<br><br>    // This is the actual state stored on the blockchain<br><br>    pub count: i64,<br>}<br><br><br><br>// ======================================================<br>// 8️⃣ ACCOUNTS REQUIRED FOR INITIALIZATION<br>// ======================================================<br><br>// This struct defines:<br>//<br>// Which accounts are required for the<br>// initialize_counter instruction to run.<br><br>#[derive(Accounts)]<br>pub struct InitializeCounter&lt;&#39;info&gt; {<br><br>    // --------------------------------------------------<br>    // payer account<br>    // --------------------------------------------------<br>    //<br>    // This is the user&#39;s wallet that will sign the transaction<br>    // and pay the rent for the new account.<br><br>    #[account(mut)]<br>    pub payer: Signer&lt;&#39;info&gt;,<br><br><br>    // --------------------------------------------------<br>    // COUNTER DATA ACCOUNT<br>    // --------------------------------------------------<br><br>    #[account(<br><br>        // init = create a new account<br>        init,<br><br>        // payer will pay the SOL<br>        payer = payer,<br><br>        // allocating memory for the account<br>        //<br>        // 8 bytes → Anchor discriminator<br>        // + Counter struct&#39;s size<br><br>        space = 8 + Counter::INIT_SPACE<br>    )]<br><br>    // ⚠️ IMPORTANT CONCEPT<br>    //<br>    // &quot;counter&quot; here is just a VARIABLE NAME<br>    //<br>    // This is NOT a deployed program.<br>    //<br>    // Account&lt;&#39;info, Counter&gt; means:<br>    //<br>    // A Solana DATA ACCOUNT that will store Counter struct&#39;s data.<br><br>    pub counter: Account&lt;&#39;info, Counter&gt;,<br><br><br>    // --------------------------------------------------<br>    // SYSTEM PROGRAM<br>    // --------------------------------------------------<br>    //<br>    // This is Solana&#39;s built-in program<br>    // that handles tasks like account creation.<br><br>    pub system_program: Program&lt;&#39;info, System&gt;,<br>}<br><br><br><br>// ======================================================<br>// 9️⃣ ACCOUNTS REQUIRED FOR INCREMENT<br>// ======================================================<br><br>#[derive(Accounts)]<br>pub struct IncrementCounter&lt;&#39;info&gt; {<br><br>    // This is the same DATA ACCOUNT<br>    // that was created in initialize_counter.<br><br>    #[account(mut)]<br>    pub counter: Account&lt;&#39;info, Counter&gt;,<br>}<br><br><br><br>// ======================================================<br>// 🔟 ACCOUNTS REQUIRED FOR DECREMENT<br>// ======================================================<br><br>#[derive(Accounts)]<br>pub struct DecrementCounter&lt;&#39;info&gt; {<br><br>    #[account(mut)]<br>    pub counter: Account&lt;&#39;info, Counter&gt;,<br>}</pre><h4>🔍 Understanding the Architecture</h4><h4>The Program vs Data Account Separation</h4><p>One of the most important concepts to understand:</p><pre>┌─────────────────────────────────────────┐<br>│      PROGRAM ACCOUNT                    │<br>│  (Your deployed smart contract code)   │<br>│                                         │<br>│  Address: Cnacumam4T7i...              │<br>│  Contains: Compiled bytecode            │<br>│  Immutable: Code cannot change          │<br>└─────────────────────────────────────────┘<br>              │<br>              │ creates &amp; manages<br>              ▼<br>┌─────────────────────────────────────────┐<br>│      DATA ACCOUNT                       │<br>│  (Stores the counter value)             │<br>│                                         │<br>│  Address: Generated at creation         │<br>│  Contains: Counter { count: i64 }       │<br>│  Mutable: Data can change               │<br>└─────────────────────────────────────────┘</pre><p><strong>Key Point:</strong> The counter variable in the code is <strong>NOT</strong> the program itself. It&#39;s a <strong>data account</strong> that stores the state (the count value). you can call like Myaccount, storage anything like that. it’s just name for data account.</p><h4>📊 Visual Flow Diagram</h4><pre>USER ACTION          BLOCKCHAIN STATE          RESULT<br>─────────────────────────────────────────────────────────<br><br>Initialize<br>    │<br>    ├─► Create Account  ────► Counter { count: 0 }<br>    │<br>    └─► Set count = 0<br><br>─────────────────────────────────────────────────────────<br><br>Increment (User A)<br>    │<br>    ├─► Load Account   ────► Counter { count: 0 }<br>    │<br>    ├─► count += 1<br>    │<br>    └─► Save           ────► Counter { count: 1 }<br><br>─────────────────────────────────────────────────────────<br><br>Increment (User B)<br>    │<br>    ├─► Load Account   ────► Counter { count: 1 }<br>    │<br>    ├─► count += 1<br>    │<br>    └─► Save           ────► Counter { count: 2 }<br><br>─────────────────────────────────────────────────────────</pre><h4>⚠️ Common Mistakes to Avoid</h4><h4>Mistake 1: Confusing Program and Data</h4><p>❌ Wrong thinking : <em>“The counter is the program”</em></p><p>✅ Correct understanding : <em>“The program </em><strong><em>manages</em></strong><em> a data account that </em><strong><em>contains</em></strong><em> the counter”</em></p><h4>Mistake 2: Forgetting mut</h4><pre>#[account(mut)]  // ← REQUIRED for modifications!<br>pub counter: Account&lt;&#39;info, Counter&gt;,</pre><p>Without mut, you can&#39;t modify the account.</p><h4>Mistake 3: Wrong Space Calculation</h4><pre>space = 8 + Counter::INIT_SPACE  // ✅ Correct<br>space = Counter::INIT_SPACE      // ❌ Missing discriminator!</pre><p>Always add 8 bytes for Anchor’s discriminator.</p><h4>🎓 What You’ve Learned</h4><p>✅ How to structure an Anchor program</p><p>✅ The difference between program and data accounts</p><p>✅ How to define instructions (functions)</p><p>✅ How to validate accounts with constraints</p><p>✅ How to initialize, read, and modify on-chain data</p><p>✅ How Anchor’s macros simplify development</p><p>You can play around with this and understand it better using <strong>Solana Playground</strong>:<br> <a href="https://beta.solpg.io/">https://beta.solpg.io/</a></p><p><strong>🎉 Congratulations!</strong> You’ve built your first Solana smart contract with Anchor! This foundation will help you build more complex programs in the future.</p><h3>👤 Building a User-Specific Counter with PDAs</h3><p><strong>Taking it to the next level: Each user gets their own counter!</strong></p><h4>🎯 The Problem with Global Counters</h4><p>The global counter we just built has a limitation:</p><ul><li><strong>Everyone shares the same counter</strong></li><li>No way to track individual users</li><li>No user-specific data</li></ul><p>What if we want:</p><ul><li>Each user to have their own counter?</li><li>Users to only modify their own data?</li><li>Secure, isolated user accounts?</li></ul><p><strong>Solution:</strong> User-Specific Counters with <strong>PDAs (Program Derived Addresses)</strong>!</p><h4>🔑 What are PDAs?</h4><p><strong>PDA = Program Derived Address</strong></p><p>A PDA is a special address that:</p><ul><li>✅ Has NO private key (no one can sign for it)</li><li>✅ Is derived from seeds (predictable)</li><li>✅ Can ONLY be controlled by your program</li><li>✅ Provides user-specific isolation</li></ul><p><strong>The Magic Formula:</strong></p><pre>PDA = hash(seeds + program_id + bump)</pre><p><strong>For our counter:</strong></p><pre>User A&#39;s Counter = hash([&quot;counter&quot;, userA_pubkey] + program_id + bump)<br>User B&#39;s Counter = hash([&quot;counter&quot;, userB_pubkey] + program_id + bump)</pre><p>Each user gets a <strong>unique, predictable address</strong>!</p><h4>📝 The Complete Code</h4><pre>// ==========================================================<br>// 1️⃣ IMPORT ANCHOR FRAMEWORK<br>// ==========================================================<br><br>// Importing common tools from Anchor framework<br>// like Context, Account, Signer, Result, macros etc.<br><br>use anchor_lang::prelude::*;<br><br><br>// ==========================================================<br>// 2️⃣ PROGRAM ID<br>// ==========================================================<br><br>// This is the program&#39;s unique address on Solana blockchain.<br>// When you run `anchor deploy`, a PROGRAM ACCOUNT is created<br>// on the blockchain where the compiled code is stored.<br><br>declare_id!(&quot;Cnacumam4T7iJwvtCcbgcFsJgUVX84aspw7177UwQjP&quot;);<br><br><br>// ==========================================================<br>// 3️⃣ PROGRAM MODULE (SMART CONTRACT LOGIC)<br>// ==========================================================<br><br>#[program]<br>pub mod counter {<br><br>    use super::*;<br><br>    // ------------------------------------------------------<br>    // INSTRUCTION 1 → INITIALIZE USER COUNTER<br>    // ------------------------------------------------------<br><br>    // This instruction will create a unique counter for each user.<br><br>    pub fn initialize_counter(<br>        ctx: Context&lt;InitializeCounter&gt;,<br>        bump: u8<br>    ) -&gt; Result&lt;()&gt; {<br><br>        // ctx.accounts.counter<br>        //<br>        // This is a PDA account that will store Counter struct&#39;s data.<br><br>        ctx.accounts.counter.count = 0;<br><br>        Ok(())<br>    }<br><br><br>    // ------------------------------------------------------<br>    // INSTRUCTION 2 → INCREMENT<br>    // ------------------------------------------------------<br><br>    pub fn increment_counter(ctx: Context&lt;UpdateCounter&gt;) -&gt; Result&lt;()&gt; {<br><br>        // incrementing counter value by 1<br>        /*<br>        ctx<br>            ├── accounts<br>            │     ├── counter<br>            │     └── user<br>            ├── program_id<br>            ├── remaining_accounts<br>            └── bumps<br>        */<br><br>        ctx.accounts.counter.count += 1;<br><br>        Ok(())<br>    }<br><br><br>    // ------------------------------------------------------<br>    // INSTRUCTION 3 → DECREMENT<br>    // ------------------------------------------------------<br><br>    pub fn decrement_counter(ctx: Context&lt;UpdateCounter&gt;) -&gt; Result&lt;()&gt; {<br><br>        ctx.accounts.counter.count -= 1;<br><br>        Ok(())<br>    }<br>}<br><br><br><br>// ==========================================================<br>// 4️⃣ DATA STRUCTURE (STATE)<br>// ==========================================================<br><br>// This struct is stored inside a blockchain account.<br><br>#[account]<br>#[derive(InitSpace)]<br>pub struct Counter {<br><br>    // This is the actual state stored on the blockchain.<br><br>    pub count: i64,<br>}<br><br><br><br>// ==========================================================<br>// 5️⃣ INITIALIZE COUNTER ACCOUNTS<br>// ==========================================================<br><br>// This defines which accounts are required<br>// for the initialize instruction.<br><br>#[derive(Accounts)]<br>pub struct InitializeCounter&lt;&#39;info&gt; {<br><br>    // ------------------------------------------------------<br>    // USER WALLET<br>    // ------------------------------------------------------<br><br>    // This is the user&#39;s wallet that will sign the transaction<br>    // and pay the rent for account creation.<br><br>    #[account(mut)]<br>    pub user: Signer&lt;&#39;info&gt;,<br><br><br>    // ------------------------------------------------------<br>    // COUNTER PDA ACCOUNT<br>    // ------------------------------------------------------<br><br>    #[account(<br><br>        // init = create a new account<br>        init,<br><br>        // user will pay the rent for account creation<br>        payer = user,<br><br>        // allocate account memory<br>        space = 8 + Counter::INIT_SPACE,<br><br>        // --------------------------------------------------<br>        // PDA SEEDS<br>        // --------------------------------------------------<br><br>        // seeds define how the PDA&#39;s address will be generated<br><br>        seeds = [<br><br>            b&quot;counter&quot;,              // constant seed<br>            user.key().as_ref()      // user&#39;s public key<br>        ],<br><br>        // bump = to avoid PDA collision<br>        bump<br>    )]<br><br>    // ⚠️ IMPORTANT<br><br>    // This is a PDA account<br>    // whose owner is the program.<br><br>    // It will store Counter struct&#39;s data.<br><br>    pub counter: Account&lt;&#39;info, Counter&gt;,<br><br><br>    // ------------------------------------------------------<br>    // SYSTEM PROGRAM<br>    // ------------------------------------------------------<br><br>    // Solana&#39;s built-in program that creates accounts.<br><br>    pub system_program: Program&lt;&#39;info, System&gt;,<br>}<br><br><br><br>// ==========================================================<br>// 6️⃣ UPDATE COUNTER ACCOUNTS<br>// ==========================================================<br><br>#[derive(Accounts)]<br>pub struct UpdateCounter&lt;&#39;info&gt; {<br><br>    // ------------------------------------------------------<br>    // EXISTING PDA ACCOUNT<br>    // ------------------------------------------------------<br><br>    #[account(<br><br>        // mut = data will be modified<br><br>        mut,<br><br>        // verifying the PDA<br>        seeds = [<br><br>            b&quot;counter&quot;,<br>            user.key().as_ref()<br><br>        ],<br><br>        bump<br>    )]<br><br>    // This is the same PDA account<br>    // that was created in initialize_counter.<br><br>    pub counter: Account&lt;&#39;info, Counter&gt;,<br><br><br>    // user signer<br>    pub user: Signer&lt;&#39;info&gt;,<br>}</pre><h4>🔍 Understanding PDA Seeds</h4><h4>The Seeds Array</h4><pre>seeds = [<br>    b&quot;counter&quot;,              // Seed 1: Static string<br>    user.key().as_ref()      // Seed 2: User&#39;s public key<br>]</pre><p><strong>Why two seeds?</strong></p><p><strong>Seed 1:</strong> b&quot;counter&quot; (constant)</p><ul><li>Same for all users</li><li>Identifies this as a “counter” type account</li><li>Provides namespace</li></ul><p><strong>Seed 2:</strong> user.key().as_ref() (variable)</p><ul><li>Different for each user</li><li>Makes each PDA unique</li><li>Ties the counter to a specific user</li></ul><p><strong>Result:</strong></p><pre>User A: hash([&quot;counter&quot;, userA_pubkey]) = PDA_A<br>User B: hash([&quot;counter&quot;, userB_pubkey]) = PDA_B</pre><h4>🛡️ Security: How PDAs Prevent Attacks</h4><h4>Attack Scenario: User A tries to modify User B’s counter</h4><pre>// User A attempts to hack User B&#39;s counter<br>await program.methods<br>  .incrementCounter()<br>  .accounts({<br>    counter: userB_counterPDA,  // ⚠️ User B&#39;s counter!<br>    user: userA,                // But User A is signing<br>  })<br>  .rpc();</pre><p><strong>What happens:</strong></p><pre>// Anchor&#39;s validation (automatic)<br>seeds = [b&quot;counter&quot;, user.key().as_ref()]<br>                    //  ↑ This is userA!</pre><pre>// Step 1: Derive PDA from signer (userA)<br>let expected_pda = derive([b&quot;counter&quot;, userA_pubkey])<br>// Result: userA_counter_pda</pre><pre>// Step 2: Compare with passed account<br>let passed = userB_counterPDA</pre><pre>// Step 3: Check if match<br>if (expected_pda != passed) {<br>    // userA_counter_pda != userB_counterPda<br>    return Err(ConstraintSeeds);  // ❌ REJECTED!<br>}</pre><p><strong>Transaction fails!</strong> User A cannot access User B’s counter. 🛑</p><h4>🎨 Visual: User-Specific Architecture</h4><pre>┌────────────────────────────────────────────────┐<br>│           PROGRAM ACCOUNT                      │<br>│       (Your Smart Contract Code)               │<br>│                                                │<br>│   Address: Cnacumam4T7i...                     │<br>│   Contains: Compiled bytecode                  │<br>└────────────────┬───────────────────────────────┘<br>                 │<br>                 │ creates &amp; manages<br>                 │<br>    ┌────────────┴────────────┐<br>    │                         │<br>    ▼                         ▼<br>┌─────────────────┐   ┌─────────────────┐<br>│  User A&#39;s PDA   │   │  User B&#39;s PDA   │<br>│                 │   │                 │<br>│ Seeds:          │   │ Seeds:          │<br>│ [&quot;counter&quot;,     │   │ [&quot;counter&quot;,     │<br>│  userA_pubkey]  │   │  userB_pubkey]  │<br>│                 │   │                 │<br>│ Data:           │   │ Data:           │<br>│ count: 5        │   │ count: 12       │<br>└─────────────────┘   └─────────────────┘<br>        ▲                       ▲<br>        │                       │<br>   Only User A            Only User B<br>   can modify             can modify</pre><h4>📊 Comparison: Global vs User-Specific</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/1*56dJ0MKZvH4sj3bb5PhRag.png" /></figure><h4>🎯 Key Concepts Explained</h4><h4>1. The Bump</h4><pre>pub fn initialize_counter(<br>    ctx: Context&lt;InitializeCounter&gt;,<br>    bump: u8  // ← This is the bump!<br>) -&gt; Result&lt;()&gt;</pre><p><strong>What is it?</strong></p><ul><li>A number (0–255) added to the seeds</li><li>Makes the address “off-curve”</li><li>Ensures no private key exists for the PDA</li></ul><p><strong>Why off-curve?</strong></p><ul><li>On-curve addresses can have private keys</li><li>Off-curve addresses cannot</li><li>This guarantees only your program can control the account</li></ul><p><strong>What is a bump? (The punchline 👊)</strong><br> On Solana, a Program Derived Address (PDA) must lie <strong>outside the elliptic curve</strong> so that no private key can exist for it. When a PDA is created using seeds, sometimes the generated address accidentally falls <strong>on the curve</strong>. If that happens, it would behave like a normal keypair address, which is not allowed for a PDA. To prevent this, Solana adds an extra number called the <strong>bump</strong>. The runtime tries bump values starting from <strong>255, then 254, 253, and so on</strong>, appending the bump to the seeds until it finds an address that lies <strong>off the curve</strong>. The first value that successfully produces an off-curve address becomes the <strong>bump</strong> for that PDA.</p><p><strong>How seeds and bump work together 🎮</strong><br> When <strong>seeds and bump are used together</strong>, Solana deterministically generates the PDA address. Because the program knows the seeds and bump, it can always re-derive the same PDA and prove that the address belongs to the program’s control. If you try to derive a PDA using <strong>only seeds without a bump</strong>, Solana cannot guarantee that the address will be off the curve, so the derivation may fail. On the other hand, if you <strong>don’t use seeds or a bump at all</strong>, then the account is simply a normal Solana account. In that case, it must be controlled by a regular keypair with a private key, like a typical wallet address, rather than being program-derived.</p><h4>2. Seeds Validation</h4><p>Every time UpdateCounter is called:</p><pre>#[account(<br>    mut,<br>    seeds = [b&quot;counter&quot;, user.key().as_ref()],<br>    bump<br>)]<br>pub counter: Account&lt;&#39;info, Counter&gt;</pre><p><strong>Anchor automatically:</strong></p><ol><li>Re-derives PDA from seeds using the <strong>signer’s</strong> key</li><li>Compares derived address with passed account</li><li>If mismatch → Rejects transaction</li></ol><p>This makes it <strong>impossible</strong> for users to access each other’s counters!</p><h4>3. Account Ownership</h4><pre>pub counter: Account&lt;&#39;info, Counter&gt;</pre><p>The Account type checks:</p><ul><li>✅ Is this account owned by our program?</li><li>✅ Does it contain Counter data?</li><li>✅ Is the discriminator correct?</li></ul><p><strong>Without Anchor:</strong> You’d write 100+ lines of validation code manually!</p><h4>⚠️ Common Mistakes to Avoid</h4><h4>Mistake 1: Forgetting the Bump Parameter</h4><p>❌ Wrong:</p><pre>pub fn initialize_counter(<br>    ctx: Context&lt;InitializeCounter&gt;<br>) -&gt; Result&lt;()&gt;</pre><p>✅ Correct:</p><pre>pub fn initialize_counter(<br>    ctx: Context&lt;InitializeCounter&gt;,<br>    bump: u8  // ← Don&#39;t forget!<br>) -&gt; Result&lt;()&gt;</pre><h4>Mistake 2: Wrong Seeds Order</h4><p>Seeds must match <strong>exactly</strong> in both structs:</p><pre>// In InitializeCounter<br>seeds = [b&quot;counter&quot;, user.key().as_ref()]<br>// In UpdateCounter (must be identical!)<br>seeds = [b&quot;counter&quot;, user.key().as_ref()]</pre><p>If order changes → Different PDA → Account not found!</p><h4>Mistake 3: Missing Signer in Update</h4><pre>#[derive(Accounts)]<br>pub struct UpdateCounter&lt;&#39;info&gt; {<br>    #[account(mut, seeds = [...], bump)]<br>    pub counter: Account&lt;&#39;info, Counter&gt;,<br>    <br>    pub user: Signer&lt;&#39;info&gt;,  // ← REQUIRED!<br>}</pre><p>Without Signer, anyone could modify any counter!</p><h4>🎓 What You’ve Learned</h4><p>✅ What PDAs are and why they’re powerful</p><p>✅ How to derive deterministic addresses from seeds</p><p>✅ How to create user-specific accounts</p><p>✅ How seeds validation prevents unauthorized access</p><p>✅ The role of bumps in PDA generation</p><p>✅ How to implement secure, isolated user data</p><h4>📚 Key Takeaways</h4><p><strong>PDAs Enable:</strong></p><ul><li>✅ User-specific data isolation</li><li>✅ Predictable address generation</li><li>✅ Secure access control</li><li>✅ Scalable user systems</li></ul><p><strong>Security Model:</strong></p><ul><li>Seeds validation (automatic)</li><li>Signer requirements (explicit)</li><li>Program ownership (enforced)</li></ul><p><strong>The Pattern:</strong></p><ol><li>Define seeds (identify the account type and owner)</li><li>Calculate PDA off-chain</li><li>Pass bump to initialization</li><li>Anchor validates on every interaction</li></ol><p><strong>🎉 Congratulations!</strong> You now understand both global and user-specific counters on Solana! You’re ready to build complex, multi-user applications with proper access control and data isolation.</p><h3>📸 Building a Decentralized Instagram Smart Contract on Solana</h3><p><strong>Putting it all together: A complete social media application Smart Contract with profiles, posts, and interactions!</strong></p><h4>🎯 What We’re Building</h4><ul><li>✅ User profiles (username, bio, stats)</li><li>✅ Posts (create, delete, like, comment, repost)</li><li>✅ Social features (follow/unfollow)</li><li>✅ All data stored on-chain</li><li>✅ User-specific PDAs for data isolation</li><li>✅ No centralized database required!</li></ul><h4>🏗️ Application Architecture</h4><pre>┌──────────────────────────────────────────────┐<br>│           INSTAGRAM PROGRAM                  │<br>│         (Smart Contract Code)                │<br>└──────────────┬───────────────────────────────┘<br>               │<br>               │ manages<br>               │<br>    ┌──────────┴──────────┬──────────────────┐<br>    │                     │                  │<br>    ▼                     ▼                  ▼<br>┌─────────┐         ┌─────────┐       ┌──────────┐<br>│ Profile │         │  Post   │       │ Comment  │<br>│  PDAs   │         │  PDAs   │       │   PDAs   │<br>└─────────┘         └─────────┘       └──────────┘</pre><h4>📝 The Complete Code</h4><pre>use anchor_lang::prelude::*;<br><br>declare_id!(&quot;Insta1111111111111111111111111111111111111&quot;);<br><br><br>// =====================================================<br>// PROGRAM MODULE<br>// =====================================================<br><br>#[program]<br>pub mod instagram {<br><br>    use super::*;<br><br>    // -------------------------------------------------<br>    // CREATE PROFILE<br>    // -------------------------------------------------<br><br>    pub fn create_profile(<br>        ctx: Context&lt;CreateProfile&gt;,<br>        username: String,<br>        bio: String<br>    ) -&gt; Result&lt;()&gt; {<br><br>        let profile = &amp;mut ctx.accounts.profile;<br><br>        profile.username = username;<br>        profile.bio = bio;<br><br>        profile.followers = 0;<br>        profile.following = 0;<br>        profile.posts = 0;<br><br>        Ok(())<br>    }<br><br><br>    // -------------------------------------------------<br>    // UPDATE PROFILE<br>    // -------------------------------------------------<br><br>    pub fn update_profile(<br>        ctx: Context&lt;UpdateProfile&gt;,<br>        new_bio: String<br>    ) -&gt; Result&lt;()&gt; {<br><br>        ctx.accounts.profile.bio = new_bio;<br><br>        Ok(())<br>    }<br><br><br>    // -------------------------------------------------<br>    // FOLLOW USER<br>    // -------------------------------------------------<br><br>    pub fn follow_user(ctx: Context&lt;FollowUser&gt;) -&gt; Result&lt;()&gt; {<br><br>        let follower = &amp;mut ctx.accounts.follower_profile;<br>        let target = &amp;mut ctx.accounts.target_profile;<br><br>        follower.following += 1;<br>        target.followers += 1;<br><br>        Ok(())<br>    }<br><br><br>    // -------------------------------------------------<br>    // UNFOLLOW USER<br>    // -------------------------------------------------<br><br>    pub fn unfollow_user(ctx: Context&lt;UnfollowUser&gt;) -&gt; Result&lt;()&gt; {<br><br>        let follower = &amp;mut ctx.accounts.follower_profile;<br>        let target = &amp;mut ctx.accounts.target_profile;<br><br>        follower.following -= 1;<br>        target.followers -= 1;<br><br>        Ok(())<br>    }<br><br><br>    // -------------------------------------------------<br>    // CREATE POST<br>    // -------------------------------------------------<br><br>    pub fn create_post(<br>        ctx: Context&lt;CreatePost&gt;,<br>        content: String<br>    ) -&gt; Result&lt;()&gt; {<br><br>        let post = &amp;mut ctx.accounts.post;<br><br>        post.author = ctx.accounts.user.key();<br>        post.content = content;<br><br>        post.likes = 0;<br>        post.comments = 0;<br>        post.reposts = 0;<br><br>        ctx.accounts.profile.posts += 1;<br><br>        Ok(())<br>    }<br><br><br>    // -------------------------------------------------<br>    // DELETE POST<br>    // -------------------------------------------------<br><br>    pub fn delete_post(ctx: Context&lt;DeletePost&gt;) -&gt; Result&lt;()&gt; {<br><br>        ctx.accounts.profile.posts -= 1;<br><br>        Ok(())<br>    }<br><br><br>    // -------------------------------------------------<br>    // LIKE POST<br>    // -------------------------------------------------<br><br>    pub fn like_post(ctx: Context&lt;LikePost&gt;) -&gt; Result&lt;()&gt; {<br><br>        ctx.accounts.post.likes += 1;<br><br>        Ok(())<br>    }<br><br><br>    // -------------------------------------------------<br>    // COMMENT POST<br>    // -------------------------------------------------<br><br>    pub fn comment_post(<br>        ctx: Context&lt;CommentPost&gt;,<br>        content: String<br>    ) -&gt; Result&lt;()&gt; {<br><br>        let comment = &amp;mut ctx.accounts.comment;<br><br>        comment.author = ctx.accounts.user.key();<br>        comment.content = content;<br>        comment.post = ctx.accounts.post.key();<br><br>        ctx.accounts.post.comments += 1;<br><br>        Ok(())<br>    }<br><br><br>    // -------------------------------------------------<br>    // REPOST<br>    // -------------------------------------------------<br><br>    pub fn repost_post(ctx: Context&lt;RepostPost&gt;) -&gt; Result&lt;()&gt; {<br><br>        ctx.accounts.post.reposts += 1;<br><br>        Ok(())<br>    }<br><br>}<br><br><br>// =====================================================<br>// PROFILE ACCOUNT<br>// =====================================================<br><br>#[account]<br>#[derive(InitSpace)]<br>pub struct Profile {<br><br>    #[max_len(50)]<br>    pub username: String,<br><br>    #[max_len(200)]<br>    pub bio: String,<br><br>    pub followers: u64,<br><br>    pub following: u64,<br><br>    pub posts: u64,<br>}<br><br><br>// =====================================================<br>// POST ACCOUNT<br>// =====================================================<br><br>#[account]<br>#[derive(InitSpace)]<br>pub struct Post {<br><br>    pub author: Pubkey,<br><br>    #[max_len(280)]<br>    pub content: String,<br><br>    pub likes: u64,<br><br>    pub comments: u64,<br><br>    pub reposts: u64,<br>}<br><br><br>// =====================================================<br>// COMMENT ACCOUNT<br>// =====================================================<br><br>#[account]<br>#[derive(InitSpace)]<br>pub struct Comment {<br><br>    pub post: Pubkey,<br><br>    pub author: Pubkey,<br><br>    #[max_len(140)]<br>    pub content: String,<br>}<br><br><br>// =====================================================<br>// CONTEXT STRUCTS<br>// =====================================================<br><br>#[derive(Accounts)]<br>pub struct CreateProfile&lt;&#39;info&gt; {<br><br>    #[account(mut)]<br>    pub user: Signer&lt;&#39;info&gt;,<br><br>    #[account(<br>        init,<br>        payer = user,<br>        space = 8 + Profile::INIT_SPACE,<br>        seeds=[b&quot;profile&quot;,user.key().as_ref()],<br>        bump<br>    )]<br>    pub profile: Account&lt;&#39;info,Profile&gt;,<br><br>    pub system_program: Program&lt;&#39;info,System&gt;,<br>}<br><br><br><br>#[derive(Accounts)]<br>pub struct UpdateProfile&lt;&#39;info&gt;{<br><br>    #[account(mut)]<br>    pub profile:Account&lt;&#39;info,Profile&gt;<br>}<br><br><br><br>#[derive(Accounts)]<br>pub struct FollowUser&lt;&#39;info&gt;{<br><br>    #[account(mut)]<br>    pub follower_profile:Account&lt;&#39;info,Profile&gt;,<br><br>    #[account(mut)]<br>    pub target_profile:Account&lt;&#39;info,Profile&gt;<br>}<br><br><br><br>#[derive(Accounts)]<br>pub struct UnfollowUser&lt;&#39;info&gt;{<br><br>    #[account(mut)]<br>    pub follower_profile:Account&lt;&#39;info,Profile&gt;,<br><br>    #[account(mut)]<br>    pub target_profile:Account&lt;&#39;info,Profile&gt;<br>}<br><br><br><br>#[derive(Accounts)]<br>pub struct CreatePost&lt;&#39;info&gt;{<br><br>    #[account(mut)]<br>    pub user:Signer&lt;&#39;info&gt;,<br><br>    #[account(mut)]<br>    pub profile:Account&lt;&#39;info,Profile&gt;,<br><br>    #[account(<br>        init,<br>        payer=user,<br>        space = 8 + Post::INIT_SPACE,<br>        seeds=[<br>            b&quot;post&quot;,<br>            user.key().as_ref(),<br>            &amp;profile.posts.to_le_bytes()<br>        ],<br>        bump<br>    )]<br>    pub post:Account&lt;&#39;info,Post&gt;,<br><br>    pub system_program:Program&lt;&#39;info,System&gt;<br>}<br><br><br><br>#[derive(Accounts)]<br>pub struct DeletePost&lt;&#39;info&gt;{<br><br>    #[account(mut)]<br>    pub profile:Account&lt;&#39;info,Profile&gt;,<br><br>    #[account(mut,close=user)]<br>    pub post:Account&lt;&#39;info,Post&gt;,<br><br>    pub user:Signer&lt;&#39;info&gt;<br>}<br><br><br><br>#[derive(Accounts)]<br>pub struct LikePost&lt;&#39;info&gt;{<br><br>    pub user:Signer&lt;&#39;info&gt;,<br><br>    #[account(mut)]<br>    pub post:Account&lt;&#39;info,Post&gt;<br>}<br><br><br><br>#[derive(Accounts)]<br>pub struct CommentPost&lt;&#39;info&gt;{<br><br>    #[account(mut)]<br>    pub user:Signer&lt;&#39;info&gt;,<br><br>    #[account(mut)]<br>    pub post:Account&lt;&#39;info,Post&gt;,<br><br>    #[account(<br>        init,<br>        payer=user,<br>        space = 8 + Comment::INIT_SPACE,<br>        seeds=[b&quot;comment&quot;,post.key().as_ref()],<br>        bump<br>    )]<br>    pub comment:Account&lt;&#39;info,Comment&gt;,<br><br>    pub system_program:Program&lt;&#39;info,System&gt;<br>}<br><br><br><br>#[derive(Accounts)]<br>pub struct RepostPost&lt;&#39;info&gt;{<br><br>    pub user:Signer&lt;&#39;info&gt;,<br><br>    #[account(mut)]<br>    pub post:Account&lt;&#39;info,Post&gt;<br>}</pre><h4>🔍 Breaking Down the Architecture</h4><h4>1. Three Main Data Structures</h4><pre>// User Profile - One per user<br>pub struct Profile {<br>    pub username: String,    // Display name<br>    pub bio: String,         // About section<br>    pub followers: u64,      // Follower count<br>    pub following: u64,      // Following count<br>    pub posts: u64,          // Total posts made<br>}<br>// Post - Multiple per user<br>pub struct Post {<br>    pub author: Pubkey,      // Who created it<br>    pub content: String,     // Post text/caption<br>    pub likes: u64,          // Like count<br>    pub comments: u64,       // Comment count<br>    pub reposts: u64,        // Repost count<br>}<br>// Comment - Multiple per post<br>pub struct Comment {<br>    pub post: Pubkey,        // Which post<br>    pub author: Pubkey,      // Who commented<br>    pub content: String,     // Comment text<br>}</pre><h4>2. PDA Strategy: Smart Address Generation</h4><p><strong>Profile PDA:</strong></p><pre>seeds = [b&quot;profile&quot;, user.key().as_ref()]</pre><ul><li><strong>Result:</strong> Each user has ONE profile at a predictable address</li><li><strong>Address:</strong> hash([&quot;profile&quot;, user_pubkey])</li></ul><p><strong>Post PDA:</strong></p><pre>seeds = [<br>    b&quot;post&quot;,<br>    user.key().as_ref(),<br>    &amp;profile.posts.to_le_bytes()  // Post number<br>]</pre><ul><li><strong>Result:</strong> Each post has a unique address</li><li><strong>Address:</strong> hash([&quot;post&quot;, user_pubkey, post_number])</li><li><strong>Example:</strong></li><li>User’s 1st post: hash([&quot;post&quot;, user, 0])</li><li>User’s 2nd post: hash([&quot;post&quot;, user, 1])</li><li>User’s 3rd post: hash([&quot;post&quot;, user, 2])</li></ul><p><strong>Comment PDA:</strong></p><pre>seeds = [b&quot;comment&quot;, post.key().as_ref()]</pre><ul><li><strong>Result:</strong> Comments are linked to specific posts</li><li><strong>Address:</strong> hash([&quot;comment&quot;, post_address])</li></ul><h4>🔐 Security Analysis</h4><h4>Account Access Control</h4><p><strong>Profile Updates:</strong></p><pre>#[derive(Accounts)]<br>pub struct UpdateProfile&lt;&#39;info&gt;{<br>    #[account(mut)]<br>    pub profile: Account&lt;&#39;info, Profile&gt;<br>}</pre><p>⚠️ <strong>Security Issue:</strong> No Signer requirement!</p><ul><li>Anyone can update any profile</li><li><strong>Fix needed:</strong> Add owner validation</li></ul><p><strong>Better Implementation:</strong></p><pre>#[derive(Accounts)]<br>pub struct UpdateProfile&lt;&#39;info&gt;{<br>    pub user: Signer&lt;&#39;info&gt;,  // Add signer<br>    <br>    #[account(<br>        mut,<br>        seeds = [b&quot;profile&quot;, user.key().as_ref()],<br>        bump<br>    )]<br>    pub profile: Account&lt;&#39;info, Profile&gt;<br>}</pre><h4>Post Deletion: The close Constraint</h4><pre>#[account(mut, close=user)]<br>pub post: Account&lt;&#39;info, Post&gt;,</pre><p><strong>What </strong><strong>close does:</strong></p><ol><li>Transfers all lamports (rent) to user</li><li>Marks account for deletion</li><li>Refunds the storage cost</li></ol><p><strong>Security:</strong> Only the post author should be able to close!</p><p><strong>Better Implementation:</strong></p><pre>#[derive(Accounts)]<br>pub struct DeletePost&lt;&#39;info&gt;{<br>    #[account(mut)]<br>    pub profile: Account&lt;&#39;info, Profile&gt;,<br><br>    #[account(<br>        mut,<br>        close = user,<br>        seeds = [<br>            b&quot;post&quot;,<br>            user.key().as_ref(),<br>            &amp;(profile.posts - 1).to_le_bytes()<br>        ],<br>        bump<br>    )]<br>    pub post: Account&lt;&#39;info, Post&gt;,<br><br>    pub user: Signer&lt;&#39;info&gt;<br>}</pre><p>This ensures:</p><ul><li>✅ Seeds validate the post belongs to the user</li><li>✅ User must sign to delete</li><li>✅ Rent is refunded to the correct person</li></ul><pre>┌─────────────────────────────────────┐<br>│         Alice&#39;s Profile             │<br>│   PDA: [&quot;profile&quot;, alice]           │<br>│                                     │<br>│   username: &quot;alice_crypto&quot;          │<br>│   bio: &quot;Web3 enthusiast&quot;            │<br>│   followers: 10                     │<br>│   following: 5                      │<br>│   posts: 3                          │<br>└─────────────────┬───────────────────┘<br>                  │<br>                  │ owns<br>                  │<br>    ┌─────────────┼─────────────┐<br>    │             │             │<br>    ▼             ▼             ▼<br>┌────────┐   ┌────────┐   ┌────────┐<br>│ Post 0 │   │ Post 1 │   │ Post 2 │<br>│        │   │        │   │        │<br>│likes: 5│   │likes: 8│   │likes: 3│<br>└───┬────┘   └───┬────┘   └───┬────┘<br>    │            │            │<br>    │ has        │ has        │ has<br>    │            │            │<br>    ▼            ▼            ▼<br>┌─────────┐ ┌─────────┐ ┌─────────┐<br>│Comment 1│ │Comment 1│ │Comment 1│<br>│Comment 2│ │Comment 2│ │         │<br>└─────────┘ └─────────┘ └─────────┘</pre><h4>📚 Key Takeaways</h4><p><strong>Multi-Account Architecture:</strong></p><ul><li>Profile → Posts → Comments (hierarchical)</li><li>Each level has its own PDA strategy</li><li>Relationships maintained through Pubkeys</li></ul><p><strong>PDA Design Patterns:</strong></p><ul><li>Static seeds for unique entities ([&quot;profile&quot;, user])</li><li>Sequential seeds for multiple entities ([&quot;post&quot;, user, number])</li><li>Reference seeds for relationships ([&quot;comment&quot;, post])</li></ul><p><strong>The Power of PDAs:</strong></p><ul><li>Deterministic addresses</li><li>No private keys needed</li><li>Program-controlled accounts</li><li>Predictable and secure</li></ul><h4>🏆 What You’ve Accomplished</h4><p>Take a moment to appreciate what you’ve just built.</p><p>✅ <strong>Global Counter</strong> — Mastered the fundamentals of Solana programs</p><p>✅ <strong>User-Specific Counter</strong> — Conquered PDAs and deterministic addressing</p><p>✅ <strong>Decentralized Instagram</strong> — Built a smart contract of social media platform</p><p><em>Happy building on Solana! 🌊⚡</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=134ebbdb759d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating Your Own SPL Token on Solana: A Complete Walkthrough By Dhruv patel]]></title>
            <link>https://medium.com/@d7511162/creating-your-own-spl-token-on-solana-a-complete-walkthrough-by-dhruv-patel-3ed39f02a61d?source=rss-8de3c9502bfd------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ed39f02a61d</guid>
            <category><![CDATA[solana-network]]></category>
            <category><![CDATA[solana-blockchain]]></category>
            <category><![CDATA[solana-token-development]]></category>
            <category><![CDATA[solana-token-creation]]></category>
            <dc:creator><![CDATA[Dhruv Patel]]></dc:creator>
            <pubDate>Sun, 08 Mar 2026 08:37:01 GMT</pubDate>
            <atom:updated>2026-03-23T18:24:56.180Z</atom:updated>
            <content:encoded><![CDATA[<p>A practical guide showing how token creation works on Solana, from mint creation to transfers with Scripts.</p><blockquote><em>⚠️ </em><strong><em>Note for Readers</em></strong></blockquote><blockquote><em>This article is part of my Solana learning series.</em></blockquote><blockquote><em>👉 Before continuing, I highly recommend checking the complete series here:<br></em><a href="https://medium.com/@d7511162/the-solana-learning-ladder-by-dhruv-patel-da5044b6a671"><strong><em>View Full Solana Series</em></strong></a></blockquote><blockquote><em>Following the series in order will give you a much better understanding.</em></blockquote><blockquote><em>However, if you are already familiar with the basics, feel free to continue with this article.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/0*f9su4AFtQU4yJRkz" /></figure><blockquote>🏗️ Step 1: Creating Your Token Mint</blockquote><h4>Understanding the Concept</h4><p>The <strong>Mint Account</strong> is the blueprint for your token. Think of it as the factory that produces your tokens and defines all the rules.</p><p>The Code: create-token-mint.ts</p><pre>import { createMint } from &quot;@solana/spl-token&quot;;<br>import &quot;dotenv/config&quot;;<br>import {<br>  getKeypairFromEnvironment,<br>  getExplorerLink,<br>} from &quot;@solana-developers/helpers&quot;;<br>import { Connection, clusterApiUrl, LAMPORTS_PER_SOL } from &quot;@solana/web3.js&quot;;<br><br>/**<br> * STARTING THE TOKEN CREATION PROCESS<br> * <br> * This script is the very first step in creating your own SPL Token on Solana.<br> * It will create a &quot;Mint Account,&quot; which serves as the global blueprint for your token.<br> */<br><br>// Step 1: Connect to the Solana Network<br>// We use the &#39;devnet&#39; cluster, which is a playground for development where SOL has no real value.<br>const connection = new Connection(clusterApiUrl(&quot;devnet&quot;));<br><br>/**<br> * Step 2: Load the Payer&#39;s Keypair<br> * To interact with the blockchain, you need a wallet (KeyPair).<br> * This function securely loads your secret key from the .env file.<br> * The &#39;user&#39; will be both the payer for transaction fees and the &#39;Mint Authority&#39;.<br> */<br>const user = getKeypairFromEnvironment(&quot;SECRET_KEY&quot;);<br><br>console.log(<br>  `🔑 Loaded keypair. Public Key: ${user.publicKey.toBase58()}`<br>);<br><br>/**<br> * Step 3: Verify Wallet Funds<br> * Creating a Mint Account requires &#39;Rent&#39; (a small amount of SOL) to be stored on-chain.<br> * We check the balance to ensure there is enough SOL to cover these costs.<br> */<br>const balance = await connection.getBalance(user.publicKey);<br>console.log(`💰 Current Balance: ${balance / LAMPORTS_PER_SOL} SOL`);<br><br>if (balance &lt; 0.01 * LAMPORTS_PER_SOL) {<br>  console.log(&quot;⚠️ Warning: Your balance might be too low for transaction fees.&quot;);<br>}<br><br>/**<br> * Step 4: Create the Token Mint<br> * This is the core instruction that creates the token on the blockchain.<br> * <br> * Parameters explained:<br> * - connection: The network connection object.<br> * - user: The account that signs the transaction and pays the fees.<br> * - user.publicKey: The &#39;Mint Authority&#39; – the only address allowed to create new supply of this token.<br> * - null: The &#39;Freeze Authority&#39; – used if you want to be able to lock tokens in users&#39; wallets.<br> * - 2: The Decimals – 2 means your token can be divided into 100 parts (like USD cents).<br> */<br>console.log(&quot;🚀 Creating the token mint... (This may take a few seconds)&quot;);<br><br>const tokenMint = await createMint(<br>  connection,<br>  user,<br>  user.publicKey,<br>  null,<br>  2<br>);<br><br>/**<br> * Step 5: Output Success and Explorer Link<br> * Once the transaction is confirmed, we get a Mint Address.<br> * We generate a link to the Solana Explorer so you can verify the token on-chain.<br> */<br>const link = getExplorerLink(&quot;address&quot;, tokenMint.toString(), &quot;devnet&quot;);<br><br>console.log(`✅ Success! Your Token Mint Address is: ${tokenMint.toString()}`);<br>console.log(`🌐 View on Solana Explorer: ${link}`);<br><br>// ---------------------------------------------------------<br>// TO RUN THIS SCRIPT:<br>// npx esrun create-token-mint.ts<br>// ---------------------------------------------------------<br>```<br><br>### Expected Output<br>```<br>PS C:\Users\lenovo\OneDrive\Desktop\SOLANA_RELATED_FILES\ACTUAL_SOLANA_SPL_TOKEN\spl_token-main&gt; npx esrun create-token-mint.ts<br>bigint: Failed to load bindings, pure JS will be used (try npm run rebuild?)<br>🔑 Loaded keypair. Public Key: HYbmZrLu6ve9buQa7NkHNXmvgZeCfv8c5ryhwRV7JYEG<br>💰 Current Balance: 2.47295248 SOL<br>🚀 Creating the token mint... (This may take a few seconds)<br>✅ Success! Your Token Mint Address is: AEE6AfgXcsYbzWA1DckV1BeetfW5wMwbxeNbaAARU9fq<br>🌐 View on Solana Explorer: https://explorer.solana.com/address/AEE6AfgXcsYbzWA1DckV1BeetfW5wMwbxeNbaAARU9fq?cluster=devnet</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lk7bqyXpGES5yADv3BKcEw.png" /><figcaption>Your token’s factory (Mint Account) is now live on Solana blockchain! Currently, it shows “Unknown Token” because we haven’t added the name, symbol, or logo yet. The supply is zero since no tokens have been minted. Your wallet is set as the Mint Authority, meaning only you can create new tokens. The token supports 2 decimal places for precision. In the next coming step-3, we’ll add metadata to give it an identity.</figcaption></figure><h4>Understanding What Happened</h4><p><strong>Your Wallet:</strong> HYbmZrLu6ve9buQa7NkHNXmvgZeCfv8c5ryhwRV7JYEG</p><ul><li>Paid the transaction fee</li><li>Became the Mint Authority (can create new tokens)</li><li>Owns the mint account</li></ul><p><strong>Your Token Mint:</strong> AEE6AfgXcsYbzWA1DckV1BeetfW5wMwbxeNbaAARU9fq</p><ul><li>Unique identifier for your token</li><li>Has 2 decimals (0.01 is the smallest unit)</li><li>Currently has zero supply</li></ul><blockquote>🏦 Step 2: Creating Your Token Account (ATA)</blockquote><h4>Understanding the Problem</h4><p><strong>Solana wallets don’t hold tokens directly.</strong> You need a specialized <strong>Associated Token Account (ATA)</strong> for each token type you want to hold.</p><p>Think of it this way:</p><ul><li>Your Wallet = Your house 🏠</li><li>Token Account = A vault inside your house 🔐</li><li>Each token type needs its own vault</li></ul><p>The Code: create-token-account.ts</p><pre>import { getOrCreateAssociatedTokenAccount } from &quot;@solana/spl-token&quot;;<br>import &quot;dotenv/config&quot;;<br>import {<br>    getExplorerLink,<br>    getKeypairFromEnvironment,<br>} from &quot;@solana-developers/helpers&quot;;<br>import { Connection, PublicKey, clusterApiUrl } from &quot;@solana/web3.js&quot;;<br><br>/**<br> * CREATING AN ASSOCIATED TOKEN ACCOUNT (ATA)<br> * <br> * On Solana, tokens (like your TRUMP TOKEN) are NOT stored directly in your main wallet address.<br> * Instead, they are stored in a separate, specialized account called an &quot;Associated Token Account.&quot;<br> * <br> * Every unique token you own has its own ATA. This script creates that &quot;digital pocket&quot; for you.<br> */<br><br>// Step 1: Connect to the Solana Network<br>const connection = new Connection(clusterApiUrl(&quot;devnet&quot;));<br><br>// Step 2: Load your Keypair (The one paying for the account creation)<br>const user = getKeypairFromEnvironment(&quot;SECRET_KEY&quot;);<br><br>console.log(<br>    `🔑 Loaded Keypair. Public Key: ${user.publicKey.toBase58()}`<br>);<br><br>/**<br> * Step 3: Define the Token Mint Address<br> * This is the unique identifier for the token you want an account for.<br> * We are using the &quot;TRUMP TOKEN&quot; address you recently created.<br> */<br>const tokenMintAccount = new PublicKey(&quot;AEE6AfgXcsYbzWA1DckV1BeetfW5wMwbxeNbaAARU9fq&quot;);<br><br>/**<br> * Step 4: Define the Recipient (Owner of the new account)<br> * Usually, you create an account for yourself, but you could also create one <br> * for a friend&#39;s wallet address if you wanted to send them tokens later.<br> */<br>const recipient = user.publicKey;<br><br>/**<br> * Step 5: Get or Create the Associated Token Account (ATA)<br> * The function &#39;getOrCreateAssociatedTokenAccount&#39; does two things:<br> * 1. It checks if an account for this token already exists for the recipient.<br> * 2. If it doesn&#39;t exist, it creates it and pays the &#39;Rent&#39; using your SOL.<br> * <br> * Arguments:<br> * - connection: Network connection.<br> * - user: The one who signs the transaction and pays the SOL rent fee.<br> * - tokenMintAccount: Which token this account is for.<br> * - recipient: Who will own the tokens in this account.<br> */<br>console.log(&quot;🚀 Checking/Creating your Token Account...&quot;);<br><br>const tokenAccount = await getOrCreateAssociatedTokenAccount(<br>    connection,<br>    user,<br>    tokenMintAccount,<br>    recipient,<br>);<br><br>/**<br> * Step 6: Output the Final Account Address<br> * This is the address where your tokens will actually live.<br> * It is DIFFERENT from your main wallet address.<br> */<br>console.log(`✅ Success! Token Account Address: ${tokenAccount.address.toBase58()}`);<br><br>const link = getExplorerLink(<br>    &quot;address&quot;,<br>    tokenAccount.address.toBase58(),<br>    &quot;devnet&quot;,<br>);<br><br>console.log(`🌐 View on Solana Explorer: ${link}`);<br><br>// ---------------------------------------------------------<br>// TO RUN THIS SCRIPT:<br>// npx esrun create-token-account.ts<br>// ---------------------------------------------------------<br>```<br><br>### Expected Output<br>```<br>PS C:\Users\lenovo\OneDrive\Desktop\SOLANA_RELATED_FILES\ACTUAL_SOLANA_SPL_TOKEN\spl_token-main&gt; npx esrun create-token-account.ts    <br>bigint: Failed to load bindings, pure JS will be used (try npm run rebuild?)<br>🔑 Loaded Keypair. Public Key: HYbmZrLu6ve9buQa7NkHNXmvgZeCfv8c5ryhwRV7JYEG<br>🚀 Checking/Creating your Token Account...<br>✅ Success! Token Account Address: DpqY5bEAcRn3yqJL8UXzzrgMofQext1BdPPY7NyRihkc<br>🌐 View on Solana Explorer: https://explorer.solana.com/address/DpqY5bEAcRn3yqJL8UXzzrgMofQext1BdPPY7NyRihkc?cluster=devnet</pre><h4>Understanding What Happened</h4><p><strong>Token Account Address:</strong> DpqY5bEAcRn3yqJL8UXzzrgMofQext1BdPPY7NyRihkc</p><ul><li>This vault will hold your token balance</li><li>It’s linked to both your wallet AND your token mint</li><li>Current balance: 0 tokens (freshly created)</li></ul><blockquote>🎨 Step 3: Adding Metadata to Your Token</blockquote><h4>Understanding Metadata</h4><p>Right now your token is just a number on the blockchain. To make it recognizable, you need:</p><ul><li><strong>Name:</strong> “TRUMP TOKEN”</li><li><strong>Symbol:</strong> “TRUMP”</li><li><strong>Logo:</strong> An image stored on IPFS/Arweave</li></ul><p>This is what makes your token appear properly in wallets and exchanges.</p><p>The Code: create-token-metadata.ts</p><pre>// This script uses the Metaplex Foundation&#39;s MPL Token Metadata program to attach info to your token.<br>import &quot;dotenv/config&quot;;<br>import {<br>    getKeypairFromEnvironment,<br>    getExplorerLink,<br>} from &quot;@solana-developers/helpers&quot;;<br>import {<br>    Connection,<br>    clusterApiUrl,<br>    PublicKey,<br>    Transaction,<br>    sendAndConfirmTransaction,<br>} from &quot;@solana/web3.js&quot;;<br>import { createCreateMetadataAccountV3Instruction } from &quot;@metaplex-foundation/mpl-token-metadata&quot;;<br><br>/**<br> * ATTACHING METADATA TO YOUR TOKEN<br> * <br> * On Solana, a &quot;Token Mint&quot; only tracks the supply. <br> * To give your token a Name, Symbol, and Logo, we use the Metaplex Metadata Program.<br> */<br><br>// Step 1: Initialize User and Connection<br>const user = getKeypairFromEnvironment(&quot;SECRET_KEY&quot;);<br>const connection = new Connection(clusterApiUrl(&quot;devnet&quot;));<br><br>console.log(<br>    `🔑 Loaded Keypair. Public key: ${user.publicKey.toBase58()}`<br>);<br><br>/**<br> * Step 2: Metaplex Token Metadata Program ID<br> * This is a standard Program on Solana called &quot;Token Metadata&quot;.<br> * It is responsible for storing and managing information about tokens.<br> */<br>const TOKEN_METADATA_PROGRAM_ID = new PublicKey(<br>    &quot;metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s&quot;,<br>);<br><br>/**<br> * Step 3: Define the Token Mint Account<br> * This is the address of the token you created in the first step.<br> * Replace this with the Mint Address generated from &#39;create-token-mint.ts&#39;.<br> */<br>const tokenMintAccount = new PublicKey(&quot;AEE6AfgXcsYbzWA1DckV1BeetfW5wMwbxeNbaAARU9fq&quot;);<br><br>/**<br> * Step 4: Define Metadata Details<br> * - name: The full name of your token.<br> * - symbol: The short ticker (like BTC or SOL).<br> * - uri: A link to a JSON file (stored on Arweave/IPFS) containing the logo and description.<br> */<br>const metadataData = {<br>    name: &quot;TRUMP TOKEN&quot;,<br>    symbol: &quot;TRUMP&quot;,<br>    uri: &quot;https://copper-organic-whale-264.mypinata.cloud/ipfs/bafkreiawfc5lwnikyz6ttryp25z3yqb3kwakbimagak2vi4zqx7nuvtxam&quot;,<br>    sellerFeeBasisPoints: 0,<br>    creators: null,<br>    collection: null,<br>    uses: null,<br>};<br><br>/**<br> * Step 5: Find Metadata PDA (Program Derived Address)<br> * Metadata isn&#39;t stored inside the Mint account. It&#39;s stored in a separate account.<br> * The address of that account is calculated using the Mint Address and the Metadata Program ID.<br> * This ensures every token has exactly one unique metadata account.<br> */<br>const [metadataPDA] = PublicKey.findProgramAddressSync(<br>    [<br>        Buffer.from(&quot;metadata&quot;),<br>        TOKEN_METADATA_PROGRAM_ID.toBuffer(),<br>        tokenMintAccount.toBuffer(),<br>    ],<br>    TOKEN_METADATA_PROGRAM_ID,<br>);<br><br>/**<br> * Step 6: Create Instruction for Metadata Account<br> * We build the instruction that tells the Metaplex program to create the metadata account.<br> * We pass the Mint Authority (user) and the actual metadata values.<br> */<br>const createMetadataAccountInstruction =<br>    createCreateMetadataAccountV3Instruction(<br>        {<br>            metadata: metadataPDA,<br>            mint: tokenMintAccount,<br>            mintAuthority: user.publicKey,<br>            payer: user.publicKey,<br>            updateAuthority: user.publicKey,<br>        },<br>        {<br>            createMetadataAccountArgsV3: {<br>                collectionDetails: null,<br>                data: metadataData,<br>                isMutable: true,<br>            },<br>        },<br>    );<br><br>/**<br> * Step 7: Send and Confirm Transaction<br> * We bundle the instruction into a transaction and send it to the blockchain.<br> */<br>const transaction = new Transaction().add(createMetadataAccountInstruction);<br><br>console.log(&quot;🚀 Sending metadata transaction...&quot;);<br><br>const transactionSignature = await sendAndConfirmTransaction(<br>    connection,<br>    transaction,<br>    [user],<br>);<br><br>/**<br> * Step 8: Log Output Details<br> */<br>const transactionLink = getExplorerLink(<br>    &quot;transaction&quot;,<br>    transactionSignature,<br>    &quot;devnet&quot;,<br>);<br><br>console.log(`✅ Metadata created! Transaction: ${transactionLink}`);<br><br>const tokenMintLink = getExplorerLink(<br>    &quot;address&quot;,<br>    tokenMintAccount.toString(),<br>    &quot;devnet&quot;,<br>);<br><br>console.log(`🌐 Check your token on Explorer: ${tokenMintLink}`);<br><br>// ---------------------------------------------------------<br>// TO RUN THIS SCRIPT:<br>// npx esrun create-token-metadata.ts<br>// ---------------------------------------------------------<br>```<br><br>### Expected Output<br>```<br>PS C:\Users\lenovo\OneDrive\Desktop\SOLANA_RELATED_FILES\ACTUAL_SOLANA_SPL_TOKEN\spl_token-main&gt; npx esrun create-token-metadata.ts<br>bigint: Failed to load bindings, pure JS will be used (try npm run rebuild?)<br>🔑 Loaded Keypair. Public key: HYbmZrLu6ve9buQa7NkHNXmvgZeCfv8c5ryhwRV7JYEG<br>🚀 Sending metadata transaction...<br>✅ Metadata created! Transaction: https://explorer.solana.com/tx/66vP9szeht9a7A3SBDyKBpXGmaY7dB6TFMB8Z8U76wbp5iqVCjauPRj9qZMHK4PWWsRxUbAZ59hP27EdvpMRKrA5?cluster=devnet<br>🌐 Check your token on Explorer: https://explorer.solana.com/address/AEE6AfgXcsYbzWA1DckV1BeetfW5wMwbxeNbaAARU9fq?cluster=devnet</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4FwBJeXyyUZJ3V2pBAUIfw.png" /><figcaption>Your token now has a complete identity! It shows as “Spidey Token” with symbol “TRUMP” and has a logo displayed. The token is now recognizable in wallets and explorers. Notice the new “Metadata” tab appeared in the navigation, confirming metadata is linked to your mint. Current supply is still zero because we haven’t minted tokens yet, but your token now looks professional and ready for distribution. The transaction history shows the metadata creation transaction that just executed successfully.</figcaption></figure><h4>Understanding What Happened</h4><p>Your token now has:</p><ul><li><strong>Name:</strong> TRUMP TOKEN</li><li><strong>Symbol:</strong> TRUMP</li><li><strong>Logo:</strong> Stored on IPFS</li><li><strong>Metadata Account:</strong> A separate account linked to your mint</li></ul><p>When you check the Explorer link, you’ll see your token with full branding!</p><blockquote>💰 Step 4: Minting Tokens</blockquote><h4>Understanding Minting</h4><p>“Minting” is creating new supply of your token. It’s like a central bank printing money, but only the <strong>Mint Authority</strong> can do this.</p><p>The Code: mint-token.ts</p><pre>import { mintTo } from &quot;@solana/spl-token&quot;;<br>import &quot;dotenv/config&quot;;<br>import {<br>    getExplorerLink,<br>    getKeypairFromEnvironment,<br>} from &quot;@solana-developers/helpers&quot;;<br>import { Connection, PublicKey, clusterApiUrl } from &quot;@solana/web3.js&quot;;<br><br>/**<br> * MINTING (CREATING) NEW TOKENS<br> * <br> * &quot;Minting&quot; is the process of creating new digital supply for your token.<br> * It&#39;s like a central bank printing more money, but for your specific SPL Token.<br> * <br> * Note: Only the &#39;Mint Authority&#39; (the wallet that created the mint) can do this.<br> */<br><br>// Step 1: Connect to the Solana Network<br>const connection = new Connection(clusterApiUrl(&quot;devnet&quot;));<br><br>/**<br> * Step 2: Handle Token Decimals<br> * SPL tokens use &quot;minor units&quot; (like cents for dollars).<br> * Since we chose 2 decimals in &#39;create-token-mint.ts&#39;, <br> * we use 10 to the power of 2 (100) to calculate the multiplier.<br> */<br>const MINOR_UNITS_PER_MAJOR_UNITS = Math.pow(10, 2);<br><br>// Step 3: Load the Mint Authority&#39;s Keypair<br>const user = getKeypairFromEnvironment(&quot;SECRET_KEY&quot;);<br><br>/**<br> * Step 4: Define the Token Mint Address<br> * This is the unique identifier for your &quot;TRUMP TOKEN&quot;.<br> */<br>const tokenMintAccount = new PublicKey(&quot;AEE6AfgXcsYbzWA1DckV1BeetfW5wMwbxeNbaAARU9fq&quot;);<br><br>/**<br> * Step 5: Define the Recipient&#39;s Token Account (ATA)<br> * Tokens must be sent to an Associated Token Account, NOT the main wallet.<br> * We are using the ATA generated in &#39;create-token-account.ts&#39;.<br> */<br>const recipientAssociatedTokenAccount = new PublicKey(<br>    &quot;DpqY5bEAcRn3yqJL8UXzzrgMofQext1BdPPY7NyRihkc&quot;,<br>);<br><br>/**<br> * Step 6: Execute the Minting Process<br> * We use &#39;mintTo&#39; to generate the tokens and deposit them into the recipient&#39;s ATA.<br> * <br> * Parameters:<br> * - connection: Network connection.<br> * - user: The one paying the transaction fee.<br> * - tokenMintAccount: The token we are creating supply for.<br> * - recipientAssociatedTokenAccount: The destination account.<br> * - user: The Mint Authority (authorizer).<br> * - amount: Total tokens in minor units (e.g., 10 * 100 = 1000 units = 10 full tokens).<br> */<br>console.log(&quot;🚀 Minting 10 tokens to your account...&quot;);<br><br>const transactionSignature = await mintTo(<br>    connection,<br>    user,<br>    tokenMintAccount,<br>    recipientAssociatedTokenAccount,<br>    user,<br>    10 * MINOR_UNITS_PER_MAJOR_UNITS, // Minting 10 full tokens<br>);<br><br>/**<br> * Step 7: Output Success and Explorer Link<br> */<br>const link = getExplorerLink(&quot;transaction&quot;, transactionSignature, &quot;devnet&quot;);<br><br>console.log(`✅ Success! Tokens minted. Transaction: ${link}`);<br><br>// ---------------------------------------------------------<br>// TO RUN THIS SCRIPT:<br>// npx esrun mint-token.ts<br>// ---------------------------------------------------------<br>```<br><br>### Expected Output<br>```<br>PS C:\Users\lenovo\OneDrive\Desktop\SOLANA_RELATED_FILES\ACTUAL_SOLANA_SPL_TOKEN\spl_token-main&gt; npx esrun mint-token.ts<br>bigint: Failed to load bindings, pure JS will be used (try npm run rebuild?)<br>🚀 Minting 10 tokens to your account...<br>✅ Success! Tokens minted. Transaction: https://explorer.solana.com/tx/3L6LzBbJ8im5DtdFAVpwUiATmUtai5PoNzoNJ7rxDvwK7Bg4LnzAXsf5Y7Qo1s2Zbw8CKo7buC2Cfy8fG5P1ZmRa?cluster=devnet</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MUlw55rLlAUu8PXlgsiLAQ.png" /><figcaption>Your token account now holds 10 tokens! The minting process created new supply and deposited it directly into your account. Token balance changed from 0 to 10, confirming the mint transaction was successful. The account is initialized and active, ready for transfers. Transaction history shows the recent minting operation that added these tokens to your balance. You now have full control over these 10 tokens and can transfer them to other wallets whenever needed.</figcaption></figure><h4>Understanding What Happened</h4><p>You just created <strong>10 TRUMP tokens</strong> out of thin air!</p><p><strong>How Decimals Work:</strong></p><ul><li>You minted: 10 * 100 = 1000 minor units</li><li>With 2 decimals, this equals: 10.00 tokens</li><li>Your token account now has a balance of 10 TRUMP tokens</li></ul><blockquote>📤 Step 5: Transferring Tokens</blockquote><h4>Understanding Transfers</h4><p>Now you can send your tokens to other wallets. The tokens move from your token account to theirs.</p><p>The Code: token-transfer.ts</p><pre>import &quot;dotenv/config&quot;;<br>import {<br>  getExplorerLink,<br>  getKeypairFromEnvironment,<br>} from &quot;@solana-developers/helpers&quot;;<br>import { Connection, PublicKey, clusterApiUrl } from &quot;@solana/web3.js&quot;;<br>import { getOrCreateAssociatedTokenAccount, transfer } from &quot;@solana/spl-token&quot;;<br><br>/**<br> * TRANSFERRING SPL TOKENS<br> * <br> * This script sends your custom tokens from your wallet to another wallet.<br> * <br> * IMPORTANT CONCEPTS:<br> * 1. Source ATA: Your token account (the sender).<br> * 2. Destination ATA: The recipient&#39;s token account.<br> * 3. Transfer: The tokens move from your storage &quot;pocket&quot; to theirs.<br> */<br><br>// Step 1: Connect to the Solana Network<br>const connection = new Connection(clusterApiUrl(&quot;devnet&quot;));<br><br>// Step 2: Load the Sender&#39;s Keypair (Your wallet)<br>const sender = getKeypairFromEnvironment(&quot;SECRET_KEY&quot;);<br><br>console.log(<br>  `🔑 Loaded Sender Keypair. Public Key: ${sender.publicKey.toBase58()}`<br>);<br><br>/**<br> * Step 3: Define the Recipient&#39;s Wallet Address<br> * This is the public key of the person who will receive the tokens.<br> */<br>const recipient = new PublicKey(&quot;7tQ4st2Ctjv7KGH4CZ2CadQv6FJyNHwHyTxH4gBZCneG&quot;);<br><br>/**<br> * Step 4: Define the Token Mint Account<br> * This is the unique identifier for your &quot;TRUMP TOKEN&quot;.<br> */<br>const tokenMintAccount = new PublicKey(<br>  &quot;AEE6AfgXcsYbzWA1DckV1BeetfW5wMwbxeNbaAARU9fq&quot;<br>);<br><br>/**<br> * Step 5: Handle Token Decimals<br> * Since our token has 2 decimals, we use 10^2 (100) to calculate the multiplier.<br> */<br>const MINOR_UNITS_PER_MAJOR_UNITS = Math.pow(10, 2);<br><br>console.log(`💸 Attempting to send 5 tokens to ${recipient.toBase58()}...`);<br><br>/**<br> * Step 6: Get or Create the Source Associated Token Account (ATA)<br> * We must ensure your wallet has an account for this specific token.<br> */<br>const sourceTokenAccount = await getOrCreateAssociatedTokenAccount(<br>  connection,<br>  sender,<br>  tokenMintAccount,<br>  sender.publicKey<br>);<br><br>/**<br> * Step 7: Get or Create the Destination Associated Token Account (ATA)<br> * If the recipient doesn&#39;t have an account for this token yet, we create it for them.<br> * Note: You (the sender) will pay the small SOL fee to create their account.<br> */<br>const destinationTokenAccount = await getOrCreateAssociatedTokenAccount(<br>  connection,<br>  sender,<br>  tokenMintAccount,<br>  recipient<br>);<br><br>/**<br> * Step 8: Execute the Transfer<br> * This performs the actual movement of 5 tokens from the source to the destination.<br> * <br> * Parameters:<br> * - connection: Network connection.<br> * - sender: The one paying the transaction fees.<br> * - sourceTokenAccount.address: Where tokens are coming from.<br> * - destinationTokenAccount.address: Where tokens are going to.<br> * - sender: The owner authorizing the move.<br> * - amount: Total tokens in minor units (5 * 100 = 500 minor units = 5 full tokens).<br> */<br>const signature = await transfer(<br>  connection,<br>  sender,<br>  sourceTokenAccount.address,<br>  destinationTokenAccount.address,<br>  sender,<br>  5 * MINOR_UNITS_PER_MAJOR_UNITS<br>);<br><br>/**<br> * Step 9: Output Success and Explorer Link<br> */<br>const explorerLink = getExplorerLink(&quot;transaction&quot;, signature, &quot;devnet&quot;);<br><br>console.log(`✅ Transfer Successful! Transaction: ${explorerLink}`);<br><br>// ---------------------------------------------------------<br>// TO RUN THIS SCRIPT:<br>// npx esrun token-transfer.ts<br>// ---------------------------------------------------------<br>```<br><br>### Expected Output<br>```<br>PS C:\Users\lenovo\OneDrive\Desktop\SOLANA_RELATED_FILES\ACTUAL_SOLANA_SPL_TOKEN\spl_token-main&gt; npx esrun token-transfer.ts<br>bigint: Failed to load bindings, pure JS will be used (try npm run rebuild?)<br>🔑 Loaded Sender Keypair. Public Key: HYbmZrLu6ve9buQa7NkHNXmvgZeCfv8c5ryhwRV7JYEG<br>💸 Attempting to send 5 tokens to 7tQ4st2Ctjv7KGH4CZ2CadQv6FJyNHwHyTxH4gBZCneG...<br>✅ Transfer Successful! Transaction: https://explorer.solana.com/tx/hFWrgKvaG3JJmF8MzVvMMNJATh4ssfg2rZFwQsSdad5bCQz83xJPc49ugrCtsSg7rrienebBrTa2UwYrWKCue5T?cluster=devnet<br>```<br><br>### Understanding What Happened<br><br>You sent **5 TRUMP tokens** to another wallet!<br><br>**Your Balance:** 10 - 5 = **5 TRUMP tokens remaining**<br>**Recipient&#39;s Balance:** 0 + 5 = **5 TRUMP tokens received**<br><br>---<br><br>## 🔗 The Complete Picture<br>```<br>┌─────────────────────────────────────────────────┐<br>│         YOUR WALLET                             │<br>│     HYbmZrLu6ve9buQa7NkHNXmvgZeCfv8c5ryhwRV7JYEG│<br>│                                                 │<br>│  💰 Holds: SOL (for fees)                       │<br>│  🔑 Controls: Token accounts                    │<br>│  👑 Authorities: Mint &amp; Update                  │<br>└─────────────────┬───────────────────────────────┘<br>                  │<br>                  │ owns<br>                  ▼<br>┌─────────────────────────────────────────────────┐<br>│       YOUR TOKEN ACCOUNT (ATA)                  │<br>│     DpqY5bEAcRn3yqJL8UXzzrgMofQext1BdPPY7NyRihkc│<br>│                                                 │<br>│  🪙 Balance: 5.00 TRUMP (after transfer)        │<br>│  🔗 For Mint: AEE6AfgXcsYbzWA1DckV...           │<br>└─────────────────┬───────────────────────────────┘<br>                  │<br>                  │ references<br>                  ▼<br>┌─────────────────────────────────────────────────┐<br>│         TOKEN MINT                              │<br>│     AEE6AfgXcsYbzWA1DckV1BeetfW5wMwbxeNbaAARU9fq│<br>│                                                 │<br>│  🏭 Total Supply: 10.00 TRUMP                   │<br>│  📊 Decimals: 2                                 │<br>│  👑 Mint Authority: HYbmZrLu...                 │<br>└─────────────────┬───────────────────────────────┘<br>                  │<br>                  │ linked to<br>                  ▼<br>┌─────────────────────────────────────────────────┐<br>│         METADATA ACCOUNT                        │<br>│                                                 │<br>│  🎨 Name: TRUMP TOKEN                           │<br>│  🏷️ Symbol: TRUMP                               │<br>│  🖼️ Logo: IPFS URI                              │<br>└─────────────────────────────────────────────────┘</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2BZgQn6l31t2wAa5ewZzJw.png" /><figcaption>Your token balance decreased from 10 to 5, confirming the transfer was successful. You sent 5 tokens to another wallet, and now you have 5 tokens remaining in your account. The transaction history shows the recent transfer operation at the top. The recipient’s token account was automatically created during the transfer and now holds the 5 tokens you sent. Both accounts remain initialized and active for future transactions.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MqFHDMFaWjZpJ0E00WRrRw.png" /><figcaption>This is the recipient’s wallet view showing they received 5 TRUMP tokens. The “Tokens” tab displays their token holdings with your TRUMP token now visible. The balance shows exactly 5 TRUMP tokens, confirming the transfer completed successfully. This wallet address is different from yours, proving the tokens moved from your account to theirs. The recipient can now see the token with full metadata including logo and symbol in their wallet.</figcaption></figure><h4>🎯 What You’ve Accomplished</h4><p>✅ <strong>Created a Token Mint</strong> with custom decimals</p><p>✅ <strong>Created Token Accounts</strong> to hold your tokens</p><p>✅ <strong>Added Professional Metadata</strong> (name, symbol, logo)</p><p>✅ <strong>Minted 10 tokens</strong> into circulation</p><p>✅ <strong>Transferred 5 tokens</strong> to another wallet</p><p><strong>Your token is now:</strong></p><ul><li>Visible in Solana wallets</li><li>Transferable between users</li><li>Searchable on Solana Explorer</li></ul><h4>💡 Key Takeaways</h4><p><strong>Three Critical Addresses:</strong></p><ul><li><strong>Wallet Address:</strong> Your identity on Solana</li><li><strong>Mint Address:</strong> Your token’s unique identifier</li><li><strong>Token Account Address:</strong> Where your balance is stored</li></ul><p><strong>The Flow:</strong></p><ol><li>Create Mint → 2. Create Token Account → 3. Add Metadata → 4. Mint Tokens → 5. Transfer Tokens</li></ol><p><strong>Decimals Matter:</strong></p><ul><li>10 * (10^decimals) = actual on-chain value</li><li>Always multiply by the decimal factor when minting/transferring</li></ul><p><strong>🎉 Congratulations! You’ve successfully created a complete SPL token on Solana!</strong></p><p><strong>📦 GitHub Repository:</strong> <a href="https://github.com/Dhruv-0101/ACTUAL_SOLANA_SPL_TOKEN.git">https://github.com/Dhruv-0101/ACTUAL_SOLANA_SPL_TOKEN.git</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ed39f02a61d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>