<?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 Ritamacharya on Medium]]></title>
        <description><![CDATA[Stories by Ritamacharya on Medium]]></description>
        <link>https://medium.com/@ritamacharya2004?source=rss-f408f72e733d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*emcN-tdfUKJDMig6</url>
            <title>Stories by Ritamacharya on Medium</title>
            <link>https://medium.com/@ritamacharya2004?source=rss-f408f72e733d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 11:05:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ritamacharya2004/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[Building Vault and Escrow Programs on Solana: From Basic Asset Management to Timed Escrow and…]]></title>
            <link>https://medium.com/@ritamacharya2004/building-vault-and-escrow-programs-on-solana-from-basic-asset-management-to-timed-escrow-and-fc20ba5c2ec6?source=rss-f408f72e733d------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc20ba5c2ec6</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[solana-network]]></category>
            <category><![CDATA[vault]]></category>
            <category><![CDATA[escrow]]></category>
            <category><![CDATA[rust]]></category>
            <dc:creator><![CDATA[Ritamacharya]]></dc:creator>
            <pubDate>Wed, 11 Nov 2026 20:58:41 GMT</pubDate>
            <atom:updated>2026-11-11T20:58:41.915Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building Vault and Escrow Programs on Solana: From Basic Asset Management to Timed Escrow and Non-Custodial DeFi Vaults</h3><p><em>Understanding PDA-based asset custody, conditional settlements, time-dependent execution, LiteSVM testing, and in-kind redemption on Solana.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5QoBpiWOwaxjl6ueqMHqbw.png" /></figure><p>Solana’s account model provides a powerful foundation for building financial applications where ownership, asset custody, and transaction execution must be transparent and verifiable. Two particularly important building blocks in this ecosystem are <strong>Vault Programs</strong> and <strong>Escrow Programs</strong>.</p><p>Although both involve managing digital assets, they address fundamentally different problems.</p><p>A vault provides a controlled environment for depositing, holding, and withdrawing assets. An escrow facilitates conditional transactions between two or more parties, ensuring that assets are transferred only when predefined conditions are satisfied.</p><p>These concepts become considerably more interesting when extended beyond their basic implementations. A vault can evolve into a non-custodial financial primitive that represents users’ proportional ownership of underlying assets. Similarly, an escrow can incorporate deadlines, delivery confirmations, dispute mechanisms, and automated settlement conditions.</p><p>This article explores these concepts from an implementation and architectural perspective, using the Anchor framework and Rust for Solana program development, with LiteSVM for testing.</p><p>The discussion is organized around five engineering objectives:</p><ol><li>Implementing a vault with deposit, withdrawal, and account-closing functionality.</li><li>Implementing an escrow with make, take, refund, and update instructions.</li><li>Testing every instruction using LiteSVM.</li><li>Extending escrow into a timed mechanism using the Clock sysvar.</li><li>Designing a non-custodial vault that supports in-kind redemption and does not force users to wait for available liquidity.</li></ol><p>The final objective is particularly important because it introduces a distinction between simply withdrawing deposited assets and redeeming an underlying financial position.</p><h3>1. Understanding Vault Programs on Solana</h3><h3>1.1 What is a vault?</h3><p>A vault is an on-chain account or collection of accounts designed to hold assets under the control of a Solana program.</p><p>Instead of transferring assets directly between users, a program establishes an account structure through which deposits, withdrawals, and other asset-management operations are executed.</p><p>Consider a simple application where Alice wants to deposit SOL into a vault.</p><p>The interaction looks like this:</p><ol><li>Alice connects her wallet to the application.</li><li>The frontend derives the vault’s Program Derived Address (PDA).</li><li>Alice signs a deposit transaction.</li><li>The vault program validates the supplied accounts.</li><li>SOL is transferred into the vault.</li><li>The program updates the user’s deposited balance.</li></ol><p>When Alice wants to withdraw, she submits another transaction. The program verifies her authority and available balance before transferring the SOL back to her wallet.</p><p>The important distinction is that Alice does not directly control the vault account. The program controls the rules governing access to the assets.</p><h3>1.2 Understanding PDAs in vault architecture</h3><p>Program Derived Addresses are fundamental to Solana vault implementations.</p><p>A PDA is a deterministic address derived from:</p><ul><li>A collection of seeds.</li><li>A bump value.</li><li>The program ID.</li></ul><p>Unlike a normal wallet address, a PDA does not have an associated private key. Its deriving program can authorize operations on its behalf through invoke_signed.</p><p>This makes PDAs particularly useful for managing program-controlled assets.</p><p>For example, consider the following vault architecture:</p><pre>User Wallet<br>                         |<br>                         |<br>                    Deposit SOL<br>                         |<br>                         v<br>              +----------------------+<br>              |     Vault Program    |<br>              +----------------------+<br>                         |<br>              +----------+-----------+<br>              |                      |<br>              v                      v<br>       vault_state PDA           vault PDA<br>       (Program-owned)           (SOL storage)<br>              |                      |<br>              |                      |<br>       Owner / Balance           SOL Balance<br>       Bump / Metadata           Controlled by<br>                                PDA authority</pre><p>We can derive these accounts using the following seeds:</p><pre>seeds = [b&quot;state&quot;, user.key().as_ref()]</pre><p>For the vault:</p><pre>seeds = [b&quot;vault&quot;, vault_state.key().as_ref()]</pre><p>The two accounts serve different purposes:</p><p><strong>vault_state</strong></p><p>Stores application-specific information, including:</p><ul><li>Vault authority.</li><li>User information.</li><li>Bump seeds.</li><li>Deposited balances or share information.</li><li>Additional configuration.</li></ul><p><strong>vault</strong></p><p>Holds the actual SOL balance.</p><p>A useful architectural distinction is that deriving a PDA and creating an account at that address are separate operations. The System Program creates accounts, while Anchor’s init constraint can automate the process.</p><p>For a SOL vault, one possible design uses a program-owned state PDA and a system-owned, zero-data vault PDA. The program then invokes the System Program with the vault PDA’s signer seeds to transfer SOL out.</p><p>For an SPL Token vault, a common alternative is a token account controlled by a PDA authority.</p><p>These distinctions matter because Solana account ownership determines which program can modify account data and debit its lamports.</p><p>References: <a href="https://solana.com/docs/core/pda/pda-accounts">Solana PDA documentation</a> and <a href="https://solana.com/docs/core/accounts/account-structure">Solana account structure</a>.</p><h3>1.3 The vault initialization process</h3><p>Before a user can deposit SOL, the program must establish the necessary accounts.</p><p>An Anchor initialization instruction generally requires:</p><ul><li>A signer who pays for account creation.</li><li>A state PDA.</li><li>A vault PDA.</li><li>The System Program.</li></ul><p>An illustrative account context looks like this:</p><pre>#[derive(Accounts)]<br>pub struct Initialize&lt;&#39;info&gt; {<br>    #[account(mut)]<br>    pub user: Signer&lt;&#39;info&gt;,<br>    #[account(<br>        init,<br>        payer = user,<br>        space = 8 + VaultState::INIT_SPACE,<br>        seeds = [<br>            b&quot;state&quot;,<br>            user.key().as_ref()<br>        ],<br>        bump<br>    )]<br>    pub vault_state: Account&lt;&#39;info, VaultState&gt;,<br>    /// CHECK: PDA validated using its seeds.<br>    #[account(<br>        seeds = [<br>            b&quot;vault&quot;,<br>            vault_state.key().as_ref()<br>        ],<br>        bump<br>    )]<br>    pub vault: SystemAccount&lt;&#39;info&gt;,<br>    pub system_program: Program&lt;&#39;info, System&gt;,<br>}</pre><p>This example validates the vault PDA but does not create it. If the application requires an explicitly initialized vault account, the implementation must create it through an appropriate account-creation mechanism.</p><p>The distinction is important when designing the initialization flow.</p><p>The frontend derives the addresses and supplies them in the transaction. Anchor then validates the signer, account mutability, seeds, bumps, ownership, and account allocation requirements before executing the instruction handler.</p><p>If validation or execution fails, the transaction’s state changes are rolled back.</p><h3>1.4 Deposit instruction</h3><p>A deposit instruction transfers SOL from the user’s wallet into the vault.</p><p>For a basic SOL implementation, the System Program performs the transfer.</p><pre>pub fn deposit(<br>    ctx: Context&lt;Deposit&gt;,<br>    amount: u64<br>) -&gt; Result&lt;()&gt; {<br>    require!(amount &gt; 0, VaultError::InvalidAmount);<br>    let transfer_instruction =<br>        anchor_lang::system_program::Transfer {<br>            from: ctx.accounts.user.to_account_info(),<br>            to: ctx.accounts.vault.to_account_info(),<br>        };<br>    anchor_lang::system_program::transfer(<br>        CpiContext::new(<br>            ctx.accounts.system_program.to_account_info(),<br>            transfer_instruction<br>        ),<br>        amount<br>    )?;<br>    Ok(())<br>}</pre><p>The deposit instruction must validate that:</p><ul><li>The user is a transaction signer.</li><li>The vault is the expected PDA.</li><li>The amount is greater than zero.</li><li>The receiving account is the intended vault.</li><li>The System Program is correctly supplied.</li></ul><p>For a production application, the program must also update its accounting state.</p><p>A critical implementation detail is that the program should not treat the entire vault balance as a user’s withdrawable deposit. Rent-exempt reserves, protocol-owned funds, and other users’ deposits must be accounted for separately.</p><h3>1.5 Withdrawal instruction</h3><p>A withdrawal instruction reverses the deposit operation.</p><p>However, unlike deposits, withdrawals require the program to authorize the vault as the source of funds.</p><p>The program must establish that the requesting user has sufficient entitlement to the amount being withdrawn.</p><p>For a basic one-user SOL vault, the instruction can use PDA signer seeds to authorize a System Program transfer.</p><pre>pub fn withdraw(<br>    ctx: Context&lt;Withdraw&gt;,<br>    amount: u64<br>) -&gt; Result&lt;()&gt; {<br>    require!(amount &gt; 0, VaultError::InvalidAmount);<br>    let vault_balance =<br>        ctx.accounts.vault.lamports();<br>    require!(<br>        vault_balance &gt;= amount,<br>        VaultError::InsufficientFunds<br>    );<br>    let state_key = ctx.accounts.vault_state.key();<br>    let bump = [ctx.bumps.vault];<br>    let signer_seeds: &amp;[&amp;[u8]] = &amp;[<br>        b&quot;vault&quot;,<br>        state_key.as_ref(),<br>        &amp;bump<br>    ];<br>    let transfer_instruction =<br>        anchor_lang::system_program::Transfer {<br>            from: ctx.accounts.vault.to_account_info(),<br>            to: ctx.accounts.user.to_account_info(),<br>        };<br>    anchor_lang::system_program::transfer(<br>        CpiContext::new_with_signer(<br>            ctx.accounts.system_program.to_account_info(),<br>            transfer_instruction,<br>            &amp;[signer_seeds]<br>        ),<br>        amount<br>    )?;<br>    Ok(())<br>}</pre><p>The withdrawal account context should enforce that:</p><ul><li>The user signs the transaction.</li><li>The user is the recorded authority.</li><li>The vault state belongs to the correct user.</li><li>The vault PDA matches the expected seeds.</li><li>The vault has sufficient withdrawable funds.</li></ul><p>For this example, the balance check is deliberately simplified. A production implementation must preserve any required rent reserve and ensure that the withdrawal does not exceed the user’s actual accounting entitlement.</p><p>For SPL Token vaults, the equivalent operation would use a Token Program CPI, with the PDA authority signing through invoke_signed.</p><h3>1.6 Close instruction</h3><p>Closing a vault is not the same as withdrawing funds.</p><p>A withdrawal transfers a specified amount while keeping the vault operational. Closing is a lifecycle operation that terminates the vault’s state account once its remaining obligations have been settled.</p><p>A close instruction should generally enforce the following conditions:</p><ol><li>The caller is the authorized owner.</li><li>The vault has no outstanding user liabilities.</li><li>No funds remain that must be distributed.</li><li>The account is eligible for closure.</li></ol><p>Anchor provides a convenient close constraint.</p><pre>#[derive(Accounts)]<br>pub struct CloseVault&lt;&#39;info&gt; {<br>    #[account(<br>        mut,<br>        has_one = authority,<br>        close = authority,<br>        seeds = [<br>            b&quot;state&quot;,<br>            authority.key().as_ref()<br>        ],<br>        bump = vault_state.bump<br>    )]<br>    pub vault_state: Account&lt;&#39;info, VaultState&gt;,<br>    #[account(mut)]<br>    pub authority: Signer&lt;&#39;info&gt;,<br>}</pre><p>The handler can be minimal:</p><pre>pub fn close_vault(<br>    _ctx: Context&lt;CloseVault&gt;<br>) -&gt; Result&lt;()&gt; {<br>    Ok(())<br>}</pre><p>Anchor closes the state account and transfers its remaining lamports to the designated recipient.</p><p>However, this does not automatically close a separate SOL vault PDA. If the vault is a system-owned account, its remaining balance must be transferred through a signed System Program CPI before its lifecycle can be considered complete.</p><p>A robust close operation must therefore handle both accounts appropriately.</p><p><strong>An important security principle:</strong> Never allow a user to close a vault while other users’ assets, unsettled claims, or protocol liabilities remain inside it.</p><h3>2. Understanding Escrow Programs on Solana</h3><h3>2.1 What is escrow?</h3><p>Escrow is a mechanism in which assets are held by a neutral, predefined arrangement until specific conditions are satisfied.</p><p>It solves a fundamental problem in peer-to-peer transactions: two parties may not trust each other enough to exchange assets directly.</p><p>Consider a freelance transaction.</p><ul><li>Alice is a client.</li><li>Bob is a freelancer.</li><li>Alice agrees to pay Bob 5 SOL for a completed project.</li></ul><p>If Alice pays before receiving the deliverable, she assumes the risk that Bob may never complete the work.</p><p>If Bob delivers the work before receiving payment, he assumes the risk that Alice may refuse to pay.</p><p>Escrow addresses this problem by separating the funding and settlement stages.</p><p>The client deposits the agreed amount into an escrow account. The funds remain locked until the program receives the required authorization or satisfies the settlement conditions.</p><pre>CLIENT (Alice)<br>                       |<br>                       |<br>                  Deposits SOL<br>                       |<br>                       v<br>              +-------------------+<br>              |   Escrow Program  |<br>              +-------------------+<br>                       |<br>                  Locked Funds<br>                       |<br>             +---------+----------+<br>             |                    |<br>             v                    v<br>      Delivery Accepted       Refund Approved<br>             |                    |<br>             v                    v<br>       Freelancer Bob         Client Alice<br>         Receives SOL         Receives SOL</pre><p>The escrow program acts as the enforcement mechanism.</p><p>Neither party should be able to arbitrarily withdraw the locked assets.</p><h3>2.2 Escrow account architecture</h3><p>A typical escrow implementation uses a PDA to store the agreement and another PDA or token account to hold the funds.</p><p>An escrow state might contain:</p><pre>#[account]<br>#[derive(InitSpace)]<br>pub struct EscrowState {<br>    pub maker: Pubkey,<br>    pub taker: Pubkey,<br>    pub mint: Pubkey,<br>    pub amount: u64,<br>    pub bump: u8,<br>    pub status: EscrowStatus,<br>}</pre><p>The status can be represented as:</p><pre>#[derive(<br>    AnchorSerialize,<br>    AnchorDeserialize,<br>    Clone,<br>    PartialEq,<br>    Eq,<br>    InitSpace<br>)]<br>pub enum EscrowStatus {<br>    Funded,<br>    Submitted,<br>    Disputed,<br>    Released,<br>    Refunded,<br>}</pre><p>The fields represent the parties, asset, agreed amount, account derivation information, and current lifecycle state.</p><p>For a token-based escrow, the actual funds are held in an SPL Token account whose authority is controlled by the escrow PDA.</p><p>This distinction is important: the escrow state records the agreement, while the token account holds the assets.</p><h3>2.3 The four fundamental escrow instructions</h3><p>A conventional escrow program can be organized around four primary instructions:</p><p>InstructionResponsibilitymakeCreate and fund an escrowtakeAccept the agreement and settle the paymentrefundReturn funds to the original depositorupdateModify permitted escrow parameters</p><p>Each instruction represents a different transition in the escrow lifecycle.</p><h3>A. Make instruction</h3><p>The make instruction creates a new escrow agreement.</p><p>The maker specifies:</p><ul><li>The intended recipient.</li><li>The asset to be deposited.</li><li>The agreed amount.</li><li>Any additional terms supported by the application.</li></ul><p>The program then initializes the escrow state and transfers the agreed assets into the escrow-controlled token account.</p><p>An illustrative implementation:</p><pre>pub fn make(<br>    ctx: Context&lt;Make&gt;,<br>    amount: u64<br>) -&gt; Result&lt;()&gt; {<br>    require!(<br>        amount &gt; 0,<br>        EscrowError::InvalidAmount<br>    );<br>    let escrow = &amp;mut ctx.accounts.escrow;<br>    escrow.maker = ctx.accounts.maker.key();<br>    escrow.taker = ctx.accounts.taker.key();<br>    escrow.mint = ctx.accounts.mint.key();<br>    escrow.amount = amount;<br>    escrow.status = EscrowStatus::Funded;<br>    escrow.bump = ctx.bumps.escrow;<br>    // Transfer tokens from maker<br>    // into the escrow-controlled token account.<br>    Ok(())<br>}</pre><p>The token transfer should be implemented using the SPL Token Program or Token-2022 Program, depending on the supported asset.</p><p>The program must validate:</p><ul><li>The maker’s signature.</li><li>The expected escrow PDA.</li><li>The correct token mint.</li><li>The maker’s source token account.</li><li>The escrow’s destination token account.</li><li>The amount and token-account authorities.</li></ul><p>The escrow should not become active unless the funding transfer succeeds.</p><h3>B. Take instruction</h3><p>The take instruction allows the designated taker to accept the escrow and receive the funds.</p><p>In the simplest exchange model, the taker accepts the agreement and the program transfers the locked assets to the taker’s token account.</p><pre>pub fn take(<br>    ctx: Context&lt;Take&gt;<br>) -&gt; Result&lt;()&gt; {<br>    let escrow = &amp;mut ctx.accounts.escrow;<br>    require!(<br>        escrow.status == EscrowStatus::Funded,<br>        EscrowError::InvalidStatus<br>    );<br>    require!(<br>        escrow.taker == ctx.accounts.taker.key(),<br>        EscrowError::Unauthorized<br>    );<br>    // Transfer escrow tokens to taker&#39;s<br>    // destination token account using<br>    // the escrow PDA as token authority.<br>    escrow.status = EscrowStatus::Released;<br>    Ok(())<br>}</pre><p>The actual token transfer must use PDA signer seeds through a Token Program CPI.</p><p>The instruction should also verify the destination token account’s mint and owner.</p><p>Once the transfer succeeds, the escrow can be marked as released.</p><p>The important property is that the taker cannot simply call the instruction with an arbitrary destination account. The program must validate the intended recipient.</p><h3>C. Refund instruction</h3><p>The refund instruction returns the deposited funds to the maker.</p><p>This operation is useful when:</p><ul><li>The escrow is cancelled.</li><li>The agreed conditions are not satisfied.</li><li>The parties mutually agree to terminate the agreement.</li><li>A deadline expires without the required delivery.</li></ul><p>For a simple escrow, the maker may be permitted to refund an escrow that has not been accepted.</p><pre>pub fn refund(<br>    ctx: Context&lt;Refund&gt;<br>) -&gt; Result&lt;()&gt; {<br>    let escrow = &amp;mut ctx.accounts.escrow;<br>    require!(<br>        escrow.status == EscrowStatus::Funded,<br>        EscrowError::InvalidStatus<br>    );<br>    require!(<br>        escrow.maker == ctx.accounts.maker.key(),<br>        EscrowError::Unauthorized<br>    );<br>    // Transfer escrow funds back to maker.<br>    escrow.status = EscrowStatus::Refunded;<br>    Ok(())<br>}</pre><p>In a production application, refund authorization must be defined carefully.</p><p>For example, allowing the maker to refund at any moment could undermine the freelancer’s ability to rely on the agreement.</p><p>A better design distinguishes between:</p><ul><li>Unconditional cancellation before work begins.</li><li>Refund after an agreed deadline.</li><li>Refund following an approved dispute.</li><li>Refund resulting from a mutually authorized cancellation.</li></ul><p>The state machine should make these conditions explicit.</p><h3>D. Update instruction</h3><p>The update instruction allows permitted escrow parameters to be modified.</p><p>For example, a client and freelancer might want to change:</p><ul><li>The payment amount.</li><li>The delivery deadline.</li><li>The delivery requirements.</li><li>The designated recipient.</li></ul><p>However, unrestricted updates introduce serious security risks.</p><p>Imagine Alice creates an escrow for 5 SOL. After Bob accepts the agreement and starts working, Alice changes the amount to 1 SOL.</p><p>The program should prevent this.</p><p>One possible design is to permit updates only while the escrow is funded but not yet accepted or submitted.</p><pre>pub fn update(<br>    ctx: Context&lt;Update&gt;,<br>    new_amount: u64,<br>    new_deadline: i64<br>) -&gt; Result&lt;()&gt; {<br>    let escrow = &amp;mut ctx.accounts.escrow;<br>    require!(<br>        escrow.status == EscrowStatus::Funded,<br>        EscrowError::InvalidStatus<br>    );<br>    require!(<br>        escrow.maker == ctx.accounts.maker.key(),<br>        EscrowError::Unauthorized<br>    );<br>    require!(<br>        new_amount &gt; 0,<br>        EscrowError::InvalidAmount<br>    );<br>    escrow.amount = new_amount;<br>    escrow.deadline = new_deadline;<br>    Ok(())<br>}</pre><p>If the amount changes, the actual escrowed token balance must also be adjusted. Updating a number in account data does not transfer additional tokens or return excess tokens.</p><p>For stronger agreement integrity, changes to material terms should require both parties’ signatures.</p><p>A useful production design is to store an agreement version and require the parties to explicitly approve changes before that version becomes active.</p><h3>3. Testing Solana Programs with LiteSVM</h3><p>Writing instructions is only one part of building a reliable Solana program.</p><p>A program that compiles successfully may still contain authorization bugs, incorrect PDA derivations, account-validation mistakes, or settlement errors.</p><p>Testing must therefore cover both successful operations and invalid transactions.</p><h3>3.1 What is LiteSVM?</h3><p>LiteSVM is a lightweight Solana virtual machine designed specifically for program testing.</p><p>Traditional testing approaches often use a local validator process. LiteSVM takes a different approach by embedding the Solana execution environment directly into the test process.</p><p>This allows developers to:</p><ul><li>Load compiled Solana programs.</li><li>Create accounts and fund wallets.</li><li>Execute transactions.</li><li>Inspect account state.</li><li>Test cross-program invocations.</li><li>Manipulate the Clock sysvar.</li><li>Verify program behavior without connecting to a live cluster.</li></ul><p>LiteSVM supports both Rust and TypeScript testing workflows.</p><p>For this implementation, TypeScript with LiteSVM is a practical choice because it allows the same language ecosystem to be used for program testing and frontend integration.</p><p>Official documentation: <a href="https://solana.com/docs/tools/litesvm">https://solana.com/docs/tools/litesvm</a></p><h3>3.2 Testing architecture</h3><p>A typical testing environment looks like this:</p><pre>TypeScript Test Suite<br>                        |<br>                        v<br>                  LiteSVM Instance<br>                        |<br>              +---------+---------+<br>              |                   |<br>              v                   v<br>         Vault Program       Escrow Program<br>              |                   |<br>              v                   v<br>        Vault Accounts       Escrow Accounts<br>              |                   |<br>              +---------+---------+<br>                        |<br>                        v<br>                 Assertions<br>              Balances / State /<br>              Authorization / Time</pre><p>The test suite loads the compiled program binaries and executes transactions against an in-memory Solana runtime.</p><p>The key benefit is that tests exercise actual program execution rather than merely mocking instruction handlers.</p><h3>3.3 Setting up the test environment</h3><p>The TypeScript LiteSVM integration uses the Solana Kit ecosystem.</p><p>A starting installation is:</p><pre>pnpm add -D \<br>  @solana/kit \<br>  @solana/kit-plugin-litesvm \<br>  @solana/kit-plugin-signer</pre><p>The exact dependencies and versions should be aligned with the current LiteSVM examples and the project’s Solana Kit version.</p><p>A simplified client setup looks like:</p><pre>import {<br>  createClient,<br>  generateKeyPairSigner,<br>} from &quot;@solana/kit&quot;;<br><br>import { litesvm } from &quot;@solana/kit-plugin-litesvm&quot;;<br>import { signer } from &quot;@solana/kit-plugin-signer&quot;;<br><br>async function setup() {<br>  const payer = await generateKeyPairSigner();<br>  const client = createClient()<br>    .use(signer(payer))<br>    .use(litesvm());<br>  client.svm.withSysvars();<br>  client.svm.withBuiltins();<br>  return {<br>    client,<br>    payer,<br>  };<br>}</pre><p>The compiled program must then be loaded into the LiteSVM instance, and the required test accounts must be funded and initialized.</p><p>The program-loading and transaction-building helpers should be implemented using the APIs corresponding to the versions installed in the project.</p><h3>3.4 Vault test cases</h3><p>The vault tests should verify every important state transition.</p><p>TestExpected resultInitialize vaultState PDA is createdDeposit SOLVault balance increasesWithdraw SOLVault balance decreasesWithdraw zeroTransaction failsWithdraw excessive amountTransaction failsWithdraw as unauthorized userTransaction failsClose empty vaultState account is closedClose with outstanding liabilitiesTransaction fails</p><p>An example test structure:</p><pre>describe(&quot;Vault Program&quot;, () =&gt; {<br>    it(&quot;initializes a vault&quot;, async () =&gt; {<br>    // Derive state and vault PDAs.<br>    // Execute initialize instruction.<br>    // Verify state account exists.<br>  });<br>  it(&quot;deposits SOL&quot;, async () =&gt; {<br>    // Record initial balances.<br>    // Execute deposit.<br>    // Verify vault balance increased.<br>  });<br>  it(&quot;withdraws SOL&quot;, async () =&gt; {<br>    // Deposit first.<br>    // Execute withdrawal.<br>    // Verify vault balance decreased.<br>  });<br>  it(&quot;rejects unauthorized withdrawal&quot;, async () =&gt; {<br>    // Attempt withdrawal with another signer.<br>    // Assert transaction failure.<br>  });<br>  it(&quot;closes an empty vault&quot;, async () =&gt; {<br>    // Execute close.<br>    // Verify state account is no longer initialized.<br>  });<br>});</pre><p>The assertions should account for transaction fees and any rent-exempt balance retained by the accounts.</p><p>A particularly important test is the unauthorized withdrawal test. A vault that allows deposits but fails to enforce withdrawal authority is not a secure vault.</p><h3>3.5 Escrow test cases</h3><p>Escrow testing should cover both individual instructions and complete transaction lifecycles.</p><p>TestExpected resultMake escrowState and token vault are initializedFund escrowCorrect amount is transferredTake escrowTaker receives the agreed amountRefund escrowMaker receives the deposited amountUpdate escrowPermitted terms are modifiedUnauthorized takeTransaction failsUnauthorized refundTransaction failsDouble settlementTransaction failsTake after refundTransaction failsRefund after releaseTransaction failsWrong token mintTransaction failsIncorrect destinationTransaction fails</p><p>For example, the following test represents the expected behavior of a complete escrow transaction:</p><pre>describe(&quot;Escrow Program&quot;, () =&gt; {<br>    it(&quot;creates and funds an escrow&quot;, async () =&gt; {<br>    // Maker creates escrow.<br>    // Verify escrow state.<br>    // Verify token vault balance.<br>  });<br>  it(&quot;allows the designated taker to settle&quot;, async () =&gt; {<br>    // Create escrow.<br>    // Execute take.<br>    // Verify taker token balance.<br>    // Verify status is Released.<br>  });<br>  it(&quot;allows an authorized refund&quot;, async () =&gt; {<br>    // Create escrow.<br>    // Execute refund.<br>    // Verify maker receives funds.<br>    // Verify status is Refunded.<br>  });<br>  it(&quot;updates permitted escrow terms&quot;, async () =&gt; {<br>    // Create escrow.<br>    // Execute update.<br>    // Verify updated values.<br>  });<br>  it(&quot;prevents double settlement&quot;, async () =&gt; {<br>    // Settle escrow once.<br>    // Attempt settlement again.<br>    // Assert transaction failure.<br>  });<br>});</pre><p>The most valuable tests are not necessarily the successful ones.</p><p>Security-sensitive programs must explicitly test what users are not allowed to do.</p><p>For example, an escrow must never allow the maker to withdraw funds after they have already been released to the taker.</p><p>Similarly, the taker must not be able to claim funds from an escrow that has already been refunded.</p><h3>3.6 Why testing complete lifecycles matters</h3><p>Testing individual instructions is necessary, but it is not sufficient.</p><p>Consider this sequence:</p><pre>make()<br>  |<br>  v<br>update()<br>  |<br>  v<br>take()<br>  |<br>  v<br>refund()</pre><p>The final refund must fail because the escrow has already been settled.</p><p>These tests help identify state-transition vulnerabilities that may not appear when instructions are tested independently.</p><p>The same principle applies to vaults.</p><p>For example:</p><pre>initialize()<br>  |<br>  v<br>deposit()<br>  |<br>  v<br>withdraw()<br>  |<br>  v<br>close()</pre><p>The program should correctly handle account balances and lifecycle transitions throughout the entire sequence.</p><h3>4. Upgrading Escrow into a Timed Escrow Mechanism</h3><p>A conventional escrow relies on explicit instructions to settle an agreement.</p><p>However, real-world transactions often involve deadlines.</p><p>A freelancer may agree to deliver a project by a particular date. A buyer may have a fixed period to confirm delivery. A dispute may need to be raised within a specified window.</p><p>This introduces the need for time-dependent conditions.</p><h3>4.1 Understanding the Clock sysvar</h3><p>Solana provides a special account called the Clock sysvar.</p><p>It exposes information about the current state of the network, including:</p><ul><li>Current slot.</li><li>Current epoch.</li><li>Unix timestamp.</li><li>Epoch start timestamp.</li></ul><p>Programs can read this information to enforce time-based rules.</p><p>In Anchor, the Clock sysvar can be accessed through:</p><pre>let clock = Clock::get()?;</pre><pre>let current_timestamp = clock.unix_timestamp;</pre><p>The Unix timestamp is expressed in seconds.</p><p>This is particularly useful for deadlines because the program can compare the current timestamp against a deadline stored in escrow state.</p><p>One important distinction: the Clock sysvar does not execute instructions automatically.</p><p>A program cannot wake itself up when a deadline expires. Someone must submit a transaction that invokes the appropriate instruction. The program then evaluates the current Clock value and decides whether settlement is permitted.</p><p>Reference: <a href="https://solana.com/docs/core/accounts/account-types">https://solana.com/docs/core/accounts/account-types</a></p><h3>4.2 Designing a timed freelance escrow</h3><p>For FreelanceFi, a useful timed escrow design can combine delivery confirmation with an automatic-release eligibility period.</p><p>Consider the following agreement:</p><ul><li>Alice is the client.</li><li>Bob is the freelancer.</li><li>Alice deposits 5 SOL.</li><li>Bob must submit the deliverable before the agreed deadline.</li><li>Alice receives a 48-hour review period after submission.</li><li>Alice can approve the work immediately.</li><li>Alice can raise a dispute during the review period.</li><li>If Alice neither approves nor disputes the submission within 48 hours, the freelancer becomes eligible to claim the payment.</li></ul><p>This design balances the interests of both parties.</p><p>The freelancer is protected against indefinite payment delays, while the client retains an opportunity to inspect the deliverable and raise a dispute.</p><p>The important distinction is that the deadline and review period are separate concepts.</p><p><strong>Delivery deadline:</strong> The latest permitted submission time.</p><p><strong>Review deadline:</strong> The end of the client’s review window.</p><h3>4.3 Timed escrow state</h3><p>We can extend the escrow state:</p><pre>#[account]<br>#[derive(InitSpace)]<br>pub struct TimedEscrow {<br>    pub maker: Pubkey,<br>    pub freelancer: Pubkey,<br>    pub amount: u64,<br>    pub delivery_deadline: i64,<br>    pub submitted_at: i64,<br>    pub review_deadline: i64,<br>    pub delivery_hash: [u8; 32],<br>    pub status: TimedEscrowStatus,<br>    pub bump: u8,<br>}</pre><p>The state machine becomes:</p><pre>#[derive(<br>    AnchorSerialize,<br>    AnchorDeserialize,<br>    Clone,<br>    PartialEq,<br>    Eq,<br>    InitSpace<br>)]<br>pub enum TimedEscrowStatus {<br>    Funded,<br>    Submitted,<br>    Disputed,<br>    Released,<br>    Refunded,<br>}</pre><p>Each state represents a specific stage of the agreement.</p><p>StateMeaningFundedClient has deposited the fundsSubmittedFreelancer has submitted the deliverableDisputedClient has raised a disputeReleasedPayment has been transferredRefundedFunds have been returned to the client</p><p>A terminal state such as Released or Refunded must never transition back into an active state.</p><h3>4.4 Instruction: Submit delivery</h3><p>The freelancer submits the deliverable before the delivery deadline.</p><p>Instead of storing the entire project file on-chain, the program can store a cryptographic hash of the deliverable or a reference to off-chain storage.</p><p>For example, the file can be stored using IPFS or another appropriate storage system, while the hash is recorded on-chain.</p><pre>pub fn submit_delivery(<br>    ctx: Context&lt;SubmitDelivery&gt;,<br>    delivery_hash: [u8; 32]<br>) -&gt; Result&lt;()&gt; {<br>    let escrow = &amp;mut ctx.accounts.escrow;<br>    let clock = Clock::get()?;<br>    require!(<br>        escrow.status == TimedEscrowStatus::Funded,<br>        EscrowError::InvalidStatus<br>    );<br>    require!(<br>        escrow.freelancer == ctx.accounts.freelancer.key(),<br>        EscrowError::Unauthorized<br>    );<br>    require!(<br>        clock.unix_timestamp &lt;= escrow.delivery_deadline,<br>        EscrowError::DeliveryDeadlinePassed<br>    );<br>    escrow.delivery_hash = delivery_hash;<br>    escrow.submitted_at = clock.unix_timestamp;<br>    escrow.review_deadline =<br>        clock.unix_timestamp + 48 * 60 * 60;<br>    escrow.status = TimedEscrowStatus::Submitted;<br>    Ok(())<br>}</pre><p>This instruction establishes the submission timestamp using the on-chain Clock rather than trusting a timestamp supplied by the frontend.</p><p>The frontend can display a countdown, but the on-chain program remains the authority for deadline enforcement.</p><h3>4.5 Instruction: Confirm delivery</h3><p>Once the client reviews the deliverable, they can approve it.</p><p>The approval triggers immediate settlement.</p><pre>pub fn confirm_delivery(<br>    ctx: Context&lt;ConfirmDelivery&gt;<br>) -&gt; Result&lt;()&gt; {<br>    let escrow = &amp;mut ctx.accounts.escrow;<br>    require!(<br>        escrow.status == TimedEscrowStatus::Submitted,<br>        EscrowError::InvalidStatus<br>    );<br>    require!(<br>        escrow.maker == ctx.accounts.client.key(),<br>        EscrowError::Unauthorized<br>    );<br>    // Transfer escrow funds to freelancer.<br>    escrow.status = TimedEscrowStatus::Released;<br>    Ok(())<br>}</pre><p>The token transfer should occur in the same transaction as the state transition.</p><p>This prevents the escrow from being marked as released without the actual funds being transferred.</p><h3>4.6 Instruction: Raise dispute</h3><p>The client must be able to dispute the submitted work within the review window.</p><pre>pub fn raise_dispute(<br>    ctx: Context&lt;RaiseDispute&gt;<br>) -&gt; Result&lt;()&gt; {<br>    let escrow = &amp;mut ctx.accounts.escrow;<br>    let clock = Clock::get()?;<br>    require!(<br>        escrow.status == TimedEscrowStatus::Submitted,<br>        EscrowError::InvalidStatus<br>    );<br>    require!(<br>        escrow.maker == ctx.accounts.client.key(),<br>        EscrowError::Unauthorized<br>    );<br>    require!(<br>        clock.unix_timestamp &lt;= escrow.review_deadline,<br>        EscrowError::ReviewPeriodExpired<br>    );<br>    escrow.status = TimedEscrowStatus::Disputed;<br>    Ok(())<br>}</pre><p>Once disputed, the escrow must not be automatically released.</p><p>The application can then introduce an arbitrator, a multisignature resolution mechanism, or a mutually authorized settlement process.</p><p>For a production freelance marketplace, the dispute resolution policy should be established before the agreement is funded.</p><h3>4.7 Instruction: Claim after review deadline</h3><p>This is where the timed mechanism becomes particularly interesting.</p><p>If the freelancer has submitted the deliverable and the client has not approved or disputed it within the review period, the freelancer should be able to claim the payment.</p><p>The claim can be permissionless in the sense that anyone may submit the settlement transaction, but the recipient must remain the freelancer.</p><pre>pub fn claim_after_review(<br>    ctx: Context&lt;ClaimAfterReview&gt;<br>) -&gt; Result&lt;()&gt; {<br>    let escrow = &amp;mut ctx.accounts.escrow;<br>    let clock = Clock::get()?;<br>    require!(<br>        escrow.status == TimedEscrowStatus::Submitted,<br>        EscrowError::InvalidStatus<br>    );<br>    require!(<br>        clock.unix_timestamp &gt; escrow.review_deadline,<br>        EscrowError::ReviewPeriodActive<br>    );<br>    // Transfer escrow funds to freelancer.<br>    escrow.status = TimedEscrowStatus::Released;<br>    Ok(())<br>}</pre><p>Notice that the instruction does not require the freelancer to be the transaction signer.</p><p>That is intentional.</p><p>Anyone can trigger the settlement after the review period expires, but the program always transfers the funds to the predetermined freelancer account.</p><p>This distinction separates permission to execute an instruction from permission to receive its financial benefits.</p><p>It is a useful pattern for permissionless settlement mechanisms.</p><h3>4.8 Handling missed delivery deadlines</h3><p>The other side of the timed escrow is what happens when the freelancer never submits the deliverable.</p><p>If the delivery deadline expires while the escrow is still in the Funded state, the client should be able to request a refund.</p><pre>pub fn refund_after_deadline(<br>    ctx: Context&lt;RefundAfterDeadline&gt;<br>) -&gt; Result&lt;()&gt; {<br>    let escrow = &amp;mut ctx.accounts.escrow;<br>    let clock = Clock::get()?;<br>    require!(<br>        escrow.status == TimedEscrowStatus::Funded,<br>        EscrowError::InvalidStatus<br>    );<br>    require!(<br>        clock.unix_timestamp &gt; escrow.delivery_deadline,<br>        EscrowError::DeadlineNotReached<br>    );<br>    // Transfer escrow funds back to client.<br>    escrow.status = TimedEscrowStatus::Refunded;<br>    Ok(())<br>}</pre><p>This creates two independent time-dependent settlement paths:</p><pre>ESCROW FUNDED<br>                         |<br>             +-----------+-----------+<br>             |                       |<br>             v                       v<br>       Work submitted           Deadline passes<br>             |                       |<br>             v                       v<br>         SUBMITTED                REFUNDED<br>             |<br>       +-----+------+<br>       |            |<br>       v            v<br>    Approved     Disputed<br>       |            |<br>       v            v<br>    RELEASED    Resolution<br>                    |<br>             +------+------+<br>             |             |<br>             v             v<br>          RELEASED      REFUNDED</pre><p>The exact dispute resolution process can be expanded according to the marketplace’s requirements.</p><h3>5. Testing Timed Escrow with LiteSVM</h3><p>Time-based programs introduce an additional testing requirement.</p><p>Testing only the successful execution path is insufficient. We must verify how the program behaves before, at, and after the deadline.</p><p>LiteSVM provides Clock manipulation functionality, making it possible to simulate these scenarios without waiting for real-world time to pass.</p><h3>5.1 Reading the Clock</h3><p>In the TypeScript LiteSVM integration, the Clock can be accessed through:</p><pre>const clock = client.svm.getClock();<br>console.log(clock.slot);<br>console.log(clock.unixTimestamp);</pre><p>The Clock sysvar can also be manipulated for testing.</p><p>The current TypeScript API exposes:</p><pre>client.svm.setClock(clock);</pre><p>and:</p><pre>client.svm.warpToSlot(targetSlot);</pre><p>An important implementation detail is that warpToSlot changes the slot, whereas setClock allows precise control over the Unix timestamp as well.</p><p>This makes setClock particularly useful for testing exact deadline boundaries.</p><p>Official reference: <a href="https://www.litesvm.com/docs/typescript/api-reference/time-and-sysvars">https://www.litesvm.com/docs/typescript/api-reference/time-and-sysvars</a></p><h3>5.2 Testing before the deadline</h3><p>Suppose the delivery deadline is:</p><pre>const deliveryDeadline = BigInt(<br>  initialTimestamp + 3600<br>);</pre><p>This represents one hour after the initial timestamp.</p><p>The test should attempt to refund before the deadline.</p><p>Expected behavior:</p><pre>Current timestamp: 10:00<br>Deadline:          11:00</pre><pre>Attempt refund<br>       |<br>       v<br>Transaction rejected</pre><p>The refund must fail because the deadline has not expired.</p><h3>5.3 Testing after the deadline</h3><p>The test can advance the Clock beyond the deadline.</p><p>Conceptually:</p><pre>const clock = client.svm.getClock();</pre><pre>client.svm.setClock({<br>  ...clock,<br>  unixTimestamp: deliveryDeadline + 1n,<br>});</pre><p>The program can then execute the refund instruction.</p><p>Expected behavior:</p><pre>Current timestamp: 11:01<br>Deadline:          11:00</pre><pre>Attempt refund<br>       |<br>       v<br>Transaction succeeds<br>       |<br>       v<br>Client receives SOL/tokens</pre><h3>5.4 Timed escrow test matrix</h3><p>A complete test suite should include:</p><p>ScenarioExpected behaviorSubmit before delivery deadlineSuccessSubmit after delivery deadlineFailureConfirm submitted workPayment releasedDispute during review windowSuccessDispute after review windowFailureClaim before review deadlineFailureClaim after review deadlineSuccessRefund before delivery deadlineFailureRefund after delivery deadline without submissionSuccessClaim after disputeFailureDouble settlementFailure</p><p>The boundary conditions deserve special attention.</p><p>For example, if the program uses:</p><pre>clock.unix_timestamp &gt; escrow.review_deadline</pre><p>then a claim at the exact review deadline must fail.</p><p>If the business logic requires settlement to become available at the deadline itself, the comparison should instead use &gt;=.</p><p>These seemingly small decisions can have significant financial consequences.</p><h3>6. Designing a Non-Custodial Vault with In-Kind Redemption</h3><p>The previous vault implementation provides basic deposit and withdrawal functionality.</p><p>However, it has a limitation.</p><p>A conventional vault usually assumes that when a user requests a withdrawal, the vault has enough liquid assets to fulfill that request.</p><p>This assumption becomes problematic when the vault deploys deposited assets into other financial positions.</p><p>Consider a DeFi vault that deposits users’ assets into a lending market, liquidity pool, or another investment strategy.</p><p>The assets may no longer be immediately available in the vault’s token account.</p><p>The vault may have a significant amount of underlying value but insufficient liquid balance to satisfy every withdrawal request.</p><p>This introduces an important design question:</p><p><strong>Should a user be forced to wait until the vault has sufficient liquidity before exiting?</strong></p><p>A more flexible design is to allow users to redeem their proportional underlying position rather than requiring the vault to convert everything back into immediately transferable liquid assets.</p><p>This is the idea behind in-kind redemption.</p><h3>6.1 What does non-custodial mean in this context?</h3><p>A non-custodial vault should not give an operator unrestricted control over users’ financial positions.</p><p>Instead, the program defines verifiable ownership and redemption rules.</p><p>The user should be able to:</p><ul><li>Deposit assets.</li><li>Receive a representation of their ownership.</li><li>Track the value of their position.</li><li>Redeem their ownership claim.</li><li>Exit without depending on an operator’s discretionary approval.</li></ul><p>However, there is an important distinction between non-custodial architecture and complete absence of asset custody.</p><p>Assets deposited into a Solana vault are still held by program-controlled accounts or authorities.</p><p>Non-custodial here refers to users retaining enforceable ownership and redemption rights under transparent on-chain rules, rather than trusting a centralized administrator to release their funds.</p><h3>6.2 Introducing shares</h3><p>Instead of tracking only deposited SOL or tokens, the vault can issue shares representing proportional ownership of its underlying assets.</p><p>For example:</p><p>Alice deposits 10 SOL.</p><p>Bob deposits 20 SOL.</p><p>The vault has received 30 SOL and issues 30 shares.</p><pre>VAULT<br>                   |<br>          Total Assets: 30 SOL<br>          Total Shares: 30<br>                   |<br>          +--------+--------+<br>          |                 |<br>          v                 v<br>        Alice               Bob<br>       10 Shares          20 Shares<br>       33.33%             66.67%</pre><p>The share represents an ownership claim over the vault’s assets and underlying positions.</p><p>If the vault generates returns, the value represented by each share increases.</p><p>If the strategy experiences losses, the value of each share decreases.</p><p>A simplified share-price formula is:</p><p>[ SharePrice = \frac{TotalAssets}{TotalShares} ]</p><p>The number of shares issued for a deposit is:</p><p>[<br>SharesMinted =<br>\frac{DepositAmount \times TotalShares}<br>{TotalAssets}<br>]</p><p>An initial deposit can use a one-to-one share ratio.</p><p>In production, the implementation must handle rounding, initial liquidity, zero-share conditions, and donation or inflation attacks. Virtual shares and virtual asset accounting can help mitigate some of these issues.</p><h3>6.3 The liquidity problem</h3><p>Consider a vault with the following financial position:</p><p>ComponentValueLiquid SOL10 SOLLending position40 SOLLiquidity pool position50 SOLTotal underlying value100 SOL</p><p>Suppose Alice owns 30% of the vault.</p><p>Her position is worth:</p><p>[ 100 \times 0.30 = 30\ SOL ]</p><p>However, the vault only has 10 SOL immediately available.</p><p>If Alice requests to withdraw her entire position as liquid SOL, the vault cannot fulfill the request.</p><p>A conventional withdrawal mechanism might reject the transaction or force Alice to wait for liquidity.</p><p>An in-kind redemption mechanism provides another option.</p><p>Instead of requiring the vault to convert the underlying positions into SOL, it transfers Alice’s proportional ownership of those positions.</p><p>For example:</p><p>AssetAlice’s 30% shareLiquid SOL3 SOLLending position12 SOLLP position15 SOLTotal position value30 SOL</p><p>Alice receives the corresponding assets or transferable position tokens representing those claims.</p><p>The vault no longer needs 30 SOL in immediately available liquidity.</p><p>It only needs to calculate and transfer the user’s proportional claim.</p><h3>6.4 Representing underlying positions</h3><p>The vault must track more than its liquid balance.</p><p>A possible state structure is:</p><pre>#[account]<br>pub struct VaultState {<br>    pub authority: Pubkey,<br>    pub total_shares: u128,<br>    pub total_assets: u128,<br>    pub liquid_assets: u64,<br>    pub strategy_assets: u128,<br>    pub bump: u8,<br>}</pre><p>In a real implementation, this state may also track:</p><ul><li>Supported asset mints.</li><li>Strategy identifiers.</li><li>External position accounts.</li><li>Outstanding liabilities.</li><li>Fee accounting.</li><li>Emergency configuration.</li></ul><p>The strategy positions themselves may be represented by SPL tokens, LP tokens, lending receipts, or other transferable on-chain claims.</p><p>The key requirement is that the vault can identify the underlying position associated with each share.</p><h3>6.5 In-kind redemption flow</h3><p>The redemption instruction should burn or otherwise invalidate the user’s vault shares and distribute the corresponding underlying assets.</p><p>The high-level flow is:</p><pre>USER<br>                  |<br>             Owns Shares<br>                  |<br>                  v<br>           Request Redemption<br>                  |<br>                  v<br>            VAULT PROGRAM<br>                  |<br>         Calculate Ownership %<br>                  |<br>                  v<br>          Calculate Asset Claims<br>                  |<br>          +-------+-------+<br>          |               |<br>          v               v<br>      Liquid Assets   Strategy Positions<br>          |               |<br>          v               v<br>       Transfer         Transfer<br>          |               |<br>          +-------+-------+<br>                  |<br>                  v<br>          Burn User Shares<br>                  |<br>                  v<br>          Redemption Complete</pre><p>An illustrative calculation is:</p><p>[<br>UserClaim_i =<br>\frac{UserShares}{TotalShares}<br>\times<br>VaultPosition_i<br>]</p><p>This calculation is performed separately for each supported asset or strategy position.</p><p>For example, if Alice owns 30% of the vault, the program calculates 30% of each eligible underlying position.</p><p>A redemption instruction might follow this structure:</p><pre>pub fn redeem_in_kind(<br>    ctx: Context&lt;RedeemInKind&gt;,<br>    shares: u64<br>) -&gt; Result&lt;()&gt; {<br>    require!(shares &gt; 0, VaultError::InvalidAmount);<br>    let vault = &amp;ctx.accounts.vault_state;<br>    require!(<br>        shares &lt;= ctx.accounts.user_position.shares,<br>        VaultError::InsufficientShares<br>    );<br>    let total_shares = vault.total_shares;<br>    let user_share = shares as u128;<br>    // Calculate proportional claims<br>    // for every supported underlying asset.<br>    // Transfer liquid assets.<br>    // Transfer underlying strategy positions.<br>    // Burn or reduce the user&#39;s shares.<br>    Ok(())<br>}</pre><p>The complete implementation must use safe integer arithmetic and handle rounding carefully.</p><p>The state changes, position transfers, and share reduction should occur atomically.</p><h3>6.6 Why in-kind redemption is important</h3><p>In-kind redemption separates two concepts that are often treated as identical:</p><ol><li>The user’s right to exit a position.</li><li>The vault’s ability to provide immediate liquidity.</li></ol><p>These are not the same thing.</p><p>A user can own a valuable financial position even when that position cannot be immediately converted into SOL.</p><p>The vault should not necessarily prevent the user from exercising their ownership rights merely because the underlying strategy has limited liquidity.</p><p>This design is particularly relevant for:</p><ul><li>Lending-market positions.</li><li>Automated market maker positions.</li><li>Yield-generating vaults.</li><li>Tokenized portfolio strategies.</li><li>Multi-asset investment vaults.</li></ul><h3>6.7 Making the vault exit-anytime</h3><p>Supporting in-kind redemption is one part of the design.</p><p>The second requirement is to ensure that users can initiate an exit at any time.</p><p>This means the vault should avoid:</p><ul><li>Arbitrary administrator-controlled withdrawal restrictions.</li><li>Mandatory waiting periods.</li><li>Unnecessary withdrawal queues.</li><li>Discretionary approval requirements.</li><li>Strategies that make user redemption entirely dependent on immediate liquidity.</li></ul><p>However, the phrase <em>exit anytime</em> needs a precise technical definition.</p><p>It should mean that users can initiate a permissionless, rule-based redemption whenever the program’s defined safety conditions are satisfied, without needing an operator’s approval.</p><p>It cannot guarantee that every external protocol will permit immediate withdrawal or that every underlying position will always be transferable.</p><p>For example, a lending position might be transferable through a receipt token, while another protocol might impose withdrawal restrictions.</p><p>The vault must account for these protocol-specific limitations.</p><p>A sensible design therefore supports multiple redemption paths:</p><p><strong>Liquid redemption:</strong> Transfer immediately available assets to the user.</p><p><strong>In-kind redemption:</strong> Transfer the user’s proportional underlying positions.</p><p>Both paths should be governed by the same ownership accounting.</p><h3>6.8 Important accounting and security considerations</h3><p>A non-custodial vault is significantly more complex than a basic SOL deposit account.</p><p>Several security considerations deserve attention.</p><p><strong>Share-price manipulation</strong></p><p>An attacker may attempt to manipulate the relationship between total assets and total shares through direct donations or unusual deposit sequences.</p><p>Use robust initial-share accounting and virtual offsets where appropriate.</p><p><strong>Strategy valuation</strong></p><p>The vault needs a reliable method of determining the value of external positions.</p><p>Stale or manipulated valuations can lead to unfair share issuance and redemption.</p><p><strong>Rounding</strong></p><p>Integer arithmetic can produce rounding differences during proportional distribution.</p><p>The program must define how residual units are handled and ensure that users cannot repeatedly exploit rounding.</p><p><strong>External protocol failures</strong></p><p>If an external lending or liquidity protocol becomes unavailable, the vault should not silently report an inaccurate position.</p><p><strong>Atomic settlement</strong></p><p>Share reduction and asset distribution must occur in the same transaction whenever possible.</p><p><strong>Strategy isolation</strong></p><p>A failure in one strategy should not automatically compromise the accounting of every other position.</p><p><strong>No discretionary confiscation</strong></p><p>An administrator should not be able to arbitrarily seize or invalidate a user’s shares.</p><p>The vault’s ownership and redemption rules should be enforced by the program itself.</p><h3>7. Integrating Vault and Escrow into a Real Application: FreelanceFi</h3><p>The individual programs become considerably more useful when combined into an application.</p><p>FreelanceFi is a decentralized freelance marketplace built around milestone-based payments.</p><p>The application uses escrow to secure individual client-freelancer agreements and a vault architecture to support more advanced asset-management functionality.</p><h3>7.1 Application architecture</h3><pre>FreelanceFi Frontend<br>                       Next.js<br>                          |<br>                          v<br>                  Solana Wallet Adapter<br>                          |<br>                          v<br>                Anchor Client / IDL<br>                          |<br>             +------------+------------+<br>             |                         |<br>             v                         v<br>        Escrow Program             Vault Program<br>             |                         |<br>             v                         v<br>        Escrow State              Vault State<br>             |                         |<br>             v                         v<br>       Token Vault PDA           Asset Vault<br>             |                         |<br>             v                         v<br>       Client Payments          Strategy Positions<br>             |<br>       +-----+------+<br>       |            |<br>       v            v<br>    Freelancer   Client<br>    Receives     Receives<br>    Payment      Refund</pre><p>The two programs have separate responsibilities.</p><p>The escrow program manages payment agreements, delivery conditions, deadlines, and dispute settlement.</p><p>The vault program manages deposits, shares, ownership accounting, and redemption.</p><p>This separation improves modularity and makes it easier to test each component independently.</p><h3>7.2 Example freelance transaction</h3><p>Suppose Alice hires Bob for a project worth 10 SOL.</p><p>The agreement is divided into two milestones:</p><ul><li>Milestone 1: 4 SOL.</li><li>Milestone 2: 6 SOL.</li></ul><p>Alice funds the first milestone through the escrow program.</p><p>Bob submits the first deliverable.</p><p>Alice reviews and approves it.</p><p>The program releases 4 SOL to Bob.</p><p>The second milestone follows the same process.</p><p>If Bob fails to submit the second deliverable before the deadline, Alice can request a refund according to the agreement’s predefined conditions.</p><p>If Bob submits the deliverable but Alice does not respond within the review period, Bob can trigger the permissionless timeout settlement.</p><p>This creates a transparent and verifiable agreement without requiring either party to trust the other with direct custody of the payment.</p><h3>7.3 Why separating vault and escrow matters</h3><p>Although both programs involve holding assets, combining every responsibility into a single program would introduce unnecessary coupling.</p><p>The escrow program should not need to understand how the vault values its underlying investment positions.</p><p>Similarly, the vault should not need to understand the details of every freelance agreement.</p><p>Each program should expose a clearly defined interface.</p><p>For example:</p><p>Vault responsibilities, Escrow responsibilities, Deposit, Create agreement, Withdraw Fund, agreement Redeem, shares Submit, delivery Close, vault Confirm, deliveryManage, positions Raise, dispute Calculate, ownership Release or refund.</p><p>This separation also creates opportunities for future integrations.</p><p>Other applications could use the vault without using the freelance escrow, while other escrow-based applications could reuse the settlement logic independently.</p><h3>8. Complete Security Checklist</h3><p>Before considering either program production-ready, it is important to validate its security assumptions.</p><h3>Vault security</h3><ul><li>Verify all PDA seeds and bumps.</li><li>Validate the user’s ownership of shares.</li><li>Prevent unauthorized withdrawals.</li><li>Prevent withdrawal amounts from exceeding user entitlement.</li><li>Account for rent reserves.</li><li>Prevent closing accounts with outstanding liabilities.</li><li>Use safe integer arithmetic.</li><li>Validate all token mints and token-account authorities.</li><li>Ensure that share accounting remains consistent.</li><li>Validate the transferability and valuation of underlying positions.</li></ul><h3>Escrow security</h3><ul><li>Validate maker and taker identities.</li><li>Verify escrow PDA derivation.</li><li>Validate token mint and token-account ownership.</li><li>Prevent double settlement.</li><li>Restrict unauthorized updates.</li><li>Validate deadlines using the Clock sysvar.</li><li>Prevent settlement after a terminal state.</li><li>Ensure funds and state transitions remain atomic.</li><li>Ensure dispute handling cannot be bypassed.</li><li>Ensure permissionless settlement always sends funds to the predetermined recipient.</li></ul><h3>Timed escrow security</h3><ul><li>Store deadlines on-chain.</li><li>Never trust client-provided timestamps.</li><li>Validate exact deadline boundaries.</li><li>Separate delivery deadlines from review deadlines.</li><li>Prevent disputes from being automatically released.</li><li>Ensure expired agreements cannot be modified to bypass settlement rules.</li><li>Ensure timeout instructions are safe for any caller.</li></ul><h3>9. Conclusion</h3><p>Vault and escrow programs represent two important primitives for building financial applications on Solana.</p><p>A vault establishes a controlled asset-management environment. An escrow establishes a conditional settlement mechanism between parties.</p><p>However, the real engineering challenge begins when these primitives are extended beyond their simplest implementations.</p><p>Adding withdrawal and closing functionality introduces account-lifecycle and authorization considerations.</p><p>Implementing make, take, refund, and update introduces state-transition and settlement-security requirements.</p><p>Introducing the Clock sysvar makes it possible to build time-dependent agreements, allowing applications to enforce delivery deadlines, review periods, and permissionless settlement conditions.</p><p>LiteSVM provides a practical environment for testing these mechanisms, including account validation, token transfers, failure scenarios, and time-dependent behavior.</p><p>Finally, extending a vault with share-based accounting and in-kind redemption introduces a more sophisticated model of ownership. Instead of making users entirely dependent on the vault’s immediate liquidity, the program can allow them to redeem their proportional underlying financial positions.</p><p>This distinction is particularly important for applications that interact with lending markets, liquidity pools, and other DeFi protocols.</p><p>Ultimately, the goal is not simply to create accounts that hold tokens. It is to build financial infrastructure in which ownership is transparent, settlement is deterministic, permissions are enforced on-chain, and users retain meaningful control over their assets.</p><p><strong>The strongest Solana financial applications are built around these principles: verifiable ownership, explicit state transitions, secure asset movement, and predictable exit mechanisms.</strong></p><p><em>Technical note: The Rust snippets in this article illustrate the core instruction logic and are architectural examples, not a complete drop-in Anchor repository. Account contexts, token CPIs, state initialization, error definitions, and program-specific constraints must be implemented consistently before deployment. The TypeScript testing snippets similarly illustrate the LiteSVM testing workflow; instruction builders and program-loading helpers depend on the versions used in the project.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc20ba5c2ec6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding SPL Tokens and NFTs on Solana: A Deep Dive into Token Creation, Metaplex Core, and…]]></title>
            <link>https://medium.com/@ritamacharya2004/understanding-spl-tokens-and-nfts-on-solana-a-deep-dive-into-token-creation-metaplex-core-and-46686ad59af9?source=rss-f408f72e733d------2</link>
            <guid isPermaLink="false">https://medium.com/p/46686ad59af9</guid>
            <category><![CDATA[solana-network]]></category>
            <category><![CDATA[nft]]></category>
            <category><![CDATA[metaplex]]></category>
            <category><![CDATA[non-fungible-tokens]]></category>
            <category><![CDATA[spls]]></category>
            <dc:creator><![CDATA[Ritamacharya]]></dc:creator>
            <pubDate>Wed, 04 Nov 2026 21:53:20 GMT</pubDate>
            <atom:updated>2026-11-04T21:53:20.581Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding SPL Tokens and NFTs on Solana: A Deep Dive into Token Creation, Metaplex Core, and the NFT Lifecycle</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QlvWkxZGU7CTYfAPlyNhQQ.png" /></figure><h3>Introduction</h3><p>Tokens and NFTs are fundamental building blocks of applications built on Solana. They enable users to create digital currencies, represent ownership of digital assets, build marketplaces, issue memberships, and develop on-chain economies.</p><p>However, creating a token or NFT on Solana involves more than simply calling a mint function. It requires understanding Solana’s account model, the programs responsible for managing tokens, the relationship between token mints and token accounts, and how metadata is associated with digital assets.</p><p>The Solana ecosystem provides established standards and protocols for these operations:</p><ul><li><strong>SPL Token Program:</strong> The standard program for creating and managing fungible tokens.</li><li><strong>Associated Token Account Program:</strong> Creates deterministic token accounts for wallet owners.</li><li><strong>Metaplex Token Metadata:</strong> The traditional standard for attaching metadata to SPL tokens and NFTs.</li><li><strong>Metaplex Core:</strong> A modern, asset-oriented standard for creating and managing NFTs on Solana.</li></ul><p>This article explores these components from an architectural and implementation perspective. It also demonstrates how to create a fungible token, mint and transfer tokens, upload NFT metadata, and perform common NFT lifecycle operations using TypeScript.</p><h3>1. Understanding Solana’s Account Model</h3><p>Before working with tokens and NFTs, it is important to understand how Solana stores data.</p><p>Unlike systems where smart contracts maintain their own internal storage, Solana uses an account-based architecture. Every piece of on-chain data exists inside an account.</p><p>An account generally contains:</p><p>Lamports: The account’s SOL balance, Data: The account’s stored bytes, Owner: The program allowed to modify the account’s data, Executable: Indicates whether the account contains an executable program, Rent epoch: Legacy rent-related field.</p><p>An account’s owner field identifies the program that controls its data. This is different from the wallet or authority that may be authorized to perform operations on that account.</p><p>For example:</p><ul><li>A wallet account is generally owned by the System Program.</li><li>A token mint account is owned by the SPL Token Program.</li><li>A token account is also owned by the SPL Token Program.</li><li>An NFT asset created using Metaplex Core is owned by the Metaplex Core program.</li></ul><p>This distinction is important because Solana programs cannot arbitrarily modify accounts owned by other programs. They must follow the rules of the program that owns the account.</p><h3>1.1 Programs and instructions</h3><p>Solana programs contain the logic that processes transactions.</p><p>A transaction can contain one or more instructions. Each instruction specifies:</p><ul><li>The program to execute.</li><li>The accounts required by that program.</li><li>The instruction data describing the operation.</li></ul><p>For example, creating a token involves instructions handled by the System Program and SPL Token Program. Creating an associated token account involves the Associated Token Account Program.</p><p>The TypeScript SDKs provide convenient interfaces for constructing these instructions, but the underlying operations are still executed by on-chain programs.</p><h3>2. Understanding SPL Tokens</h3><p>SPL stands for <strong>Solana Program Library</strong>. It refers to a collection of programs and standards used throughout the Solana ecosystem.</p><p>The SPL Token Program provides the standard functionality required to create and manage fungible tokens.</p><p>A fungible token is interchangeable with another unit of the same token. For example, one unit of a token is equivalent to another unit of that token, assuming they belong to the same mint.</p><p>Examples include:</p><ul><li>Stablecoins.</li><li>Governance tokens.</li><li>Utility tokens.</li><li>Application-specific currencies.</li></ul><p>The SPL Token Program supports operations such as:</p><ul><li>Creating token mints.</li><li>Creating token accounts.</li><li>Minting tokens.</li><li>Transferring tokens.</li><li>Burning tokens.</li><li>Freezing and thawing token accounts.</li><li>Managing authorities.</li></ul><h3>2.1 What is a Mint Account?</h3><p>A mint account represents a particular token on Solana.</p><p>It stores information about the token itself, rather than the balance held by individual wallets.</p><p>A mint account contains important fields such as:</p><p>Mint Authority: The authority allowed to create additional tokens, Total Supply: number of base units currently in circulation, Decimals: Number of decimal places supported by the token, Freeze Authority: Authority allowed to freeze or thaw token accounts, Is Initialized: Indicates whether the mint has been initialized.</p><p>Consider a token with the following configuration:</p><ul><li>Name: Example Token</li><li>Symbol: EXT</li><li>Decimals: 2</li><li>Initial supply: 100 tokens</li></ul><p>The mint account stores the token’s supply and configuration. It does not store each wallet’s individual balance. That information belongs in token accounts.</p><h3>2.2 What are Decimals?</h3><p>The SPL Token Program stores token amounts as integers. It does not store floating-point values.</p><p>The decimals field determines how those integer units are interpreted.</p><p>For a token with six decimals, minting 1,000,000 base units creates one whole token.</p><p>This distinction is important when writing token-related code. Token amounts should generally be handled as integers or appropriate big-number types instead of JavaScript floating-point values.</p><h3>2.3 Mint Authority and Freeze Authority</h3><p>Two important authorities are associated with an SPL mint.</p><p><strong>Mint Authority</strong></p><p>The mint authority controls the creation of additional tokens.</p><p>For example, if a token has a supply of 1,000 units and its mint authority remains active, that authority can mint additional units.</p><p>The mint authority can also be revoked by setting it to null. Once revoked, additional tokens cannot be minted through that mint authority.</p><p><strong>Freeze Authority</strong></p><p>The freeze authority can freeze or thaw token accounts associated with the mint.</p><p>A frozen token account cannot perform normal token operations such as transferring or burning tokens until it is thawed.</p><p>The mint authority and freeze authority are independent. Revoking one does not automatically revoke the other.</p><h3>3. Token Accounts and Associated Token Accounts</h3><p>A mint account defines a token, but it does not hold the balance of every wallet.</p><p>For that purpose, Solana uses <strong>token accounts</strong>.</p><p>A token account stores information such as:</p><ul><li>The mint it belongs to.</li><li>The token owner.</li><li>The token balance.</li><li>The delegate, if one exists.</li><li>The account’s frozen or initialized state.</li></ul><p>A wallet can own token accounts for multiple different mints.</p><h3>3.1 Why does a wallet need a separate token account?</h3><p>A wallet’s public key and its token account address are not the same thing.</p><p>A wallet can own many token accounts, each associated with a different mint.</p><p>The token account is where the SPL Token Program records the wallet’s balance for a particular token.</p><p>This separation allows the same wallet to hold thousands of different tokens without storing every token balance directly inside the wallet account.</p><h3>3.2 What is an Associated Token Account (ATA)?</h3><p>An Associated Token Account is a deterministic token account derived from three pieces of information:</p><ol><li>Wallet owner’s public key.</li><li>Token mint address.</li><li>Token program ID.</li></ol><p>The Associated Token Account Program uses these inputs to derive a predictable address.</p><p>Conceptually:</p><p>ATA = PDA(wallet, token_program, mint)</p><p>The actual derivation uses the associated token account program’s seeds and program ID.</p><p>Because the address is deterministic, the same wallet and mint combination will produce the same associated token account address.</p><p>This makes it easy for applications to locate a wallet’s standard token account without storing that address separately.</p><p>An important distinction:</p><p><strong>An ATA is still a token account.</strong> It is simply the conventional, deterministically derived token account for a particular wallet and mint.</p><p>A wallet may have other token accounts for the same mint, but the ATA is the standard account most applications use.</p><h3>4. Creating an SPL Token Using TypeScript</h3><p>The following implementation demonstrates the creation of a token mint, associated token accounts, minting, and transferring tokens on Solana Devnet.</p><h3>4.1 Required packages</h3><p>Install the required dependencies:</p><pre>bun add @solana/web3.js @solana/spl-token</pre><p>The implementation uses:</p><ul><li>@solana/web3.js for connecting to Solana and managing keypairs, transactions, and public keys.</li><li>@solana/spl-token for SPL Token Program instructions and associated token account operations.</li></ul><h3>4.2 Connecting to Devnet</h3><p>Solana provides multiple clusters, including:</p><ul><li>Mainnet Beta: Production network.</li><li>Devnet: Development and testing network.</li><li>Testnet: Primarily used for validator and network testing.</li></ul><p>For development, Devnet is generally the appropriate environment.</p><pre>import {<br>  Connection,<br>  Keypair,<br>  LAMPORTS_PER_SOL,<br>  SystemProgram,<br>  Transaction,<br>  sendAndConfirmTransaction,<br>} from &quot;@solana/web3.js&quot;;</pre><pre>import {<br>  TOKEN_PROGRAM_ID,<br>  MINT_SIZE,<br>  createInitializeMintInstruction,<br>  getAssociatedTokenAddress,<br>  createAssociatedTokenAccountInstruction,<br>  createMintToInstruction,<br>  createTransferInstruction,<br>} from &quot;@solana/spl-token&quot;;</pre><pre>const connection = new Connection(<br>  &quot;https://api.devnet.solana.com&quot;,<br>  &quot;confirmed&quot;<br>);</pre><p>A connection object provides access to the Solana RPC endpoint. It is used to fetch account information, submit transactions, and confirm transaction execution.</p><h3>4.3 Loading the payer keypair</h3><p>Transactions often require SOL to pay for transaction fees and account creation.</p><p>The account responsible for paying these costs is commonly called the <strong>payer</strong>.</p><pre>const payer = Keypair.fromSecretKey(<br>  Uint8Array.from(JSON.parse(process.env.PAYER_SECRET_KEY!))<br>);</pre><p>The secret key should be loaded securely from an environment variable. It should never be committed to a public repository.</p><p>The payer can also act as the mint authority and freeze authority, depending on the configuration.</p><h3>4.4 Creating the mint account</h3><p>Creating an SPL token involves creating an account owned by the Token Program and initializing it as a mint.</p><p>The mint account requires enough space for the mint’s data structure.</p><p>The standard SPL Token mint account size is 82 bytes.</p><p>It must also be funded with enough lamports to satisfy the rent-exemption requirement.</p><pre>const mint = Keypair.generate();</pre><pre>const lamports = await connection.getMinimumBalanceForRentExemption(<br>  MINT_SIZE<br>);</pre><pre>const createMintAccountInstruction =<br>  SystemProgram.createAccount({<br>    fromPubkey: payer.publicKey,<br>    newAccountPubkey: mint.publicKey,<br>    space: MINT_SIZE,<br>    lamports,<br>    programId: TOKEN_PROGRAM_ID,<br>  });</pre><p>This instruction creates a new account with the SPL Token Program as its owner.</p><p>However, the account is not yet an initialized mint.</p><p>That requires a separate instruction.</p><pre>const initializeMintInstruction =<br>  createInitializeMintInstruction(<br>    mint.publicKey,<br>    0,<br>    payer.publicKey,<br>    payer.publicKey,<br>    TOKEN_PROGRAM_ID<br>  );</pre><p>The arguments specify:</p><ol><li>Mint address.</li><li>Decimal precision.</li><li>Mint authority.</li><li>Freeze authority.</li><li>Token Program ID.</li></ol><p>The decimal precision is set to 0, meaning this token does not support fractional units.</p><p>Both authorities are assigned to the payer in this example.</p><p>Finally, both instructions are submitted in one transaction:</p><pre>const transaction = new Transaction().add(<br>  createMintAccountInstruction,<br>  initializeMintInstruction<br>);</pre><pre>const signature = await sendAndConfirmTransaction(<br>  connection,<br>  transaction,<br>  [payer, mint]<br>);</pre><pre>console.log(&quot;Mint Address:&quot;, mint.publicKey.toBase58());<br>console.log(&quot;Transaction:&quot;, signature);</pre><p>The payer signs the transaction because it funds the new account. The newly generated mint keypair signs because it is the account being created.</p><p>After successful execution, the mint account exists and is initialized.</p><h3>5. Creating Associated Token Accounts</h3><p>Once the mint exists, token accounts must be created to hold balances.</p><p>For this implementation, there are two wallets:</p><ul><li>Payer: The wallet creating and minting the token.</li><li>Receiver: A separate wallet that will receive tokens.</li></ul><p>First, derive their associated token account addresses.</p><pre>const payerATA = await getAssociatedTokenAddress(<br>  mint.publicKey,<br>  payer.publicKey<br>);</pre><pre>const receiverATA = await getAssociatedTokenAddress(<br>  mint.publicKey,<br>  receiver.publicKey<br>);</pre><p>Notice that both addresses are derived using the same mint address but different wallet public keys.</p><p>This produces two distinct associated token accounts.</p><p>Next, create the accounts:</p><pre>const createPayerATA =<br>  createAssociatedTokenAccountInstruction(<br>    payer.publicKey,<br>    payerATA,<br>    payer.publicKey,<br>    mint.publicKey<br>  );</pre><pre>const createReceiverATA =<br>  createAssociatedTokenAccountInstruction(<br>    payer.publicKey,<br>    receiverATA,<br>    receiver.publicKey,<br>    mint.publicKey<br>  );</pre><p>The arguments specify:</p><ol><li>Payer: The wallet paying for account creation.</li><li>Associated token account address.</li><li>Token account owner.</li><li>Mint address.</li></ol><p>An important detail is that the payer creating an ATA does not necessarily need to be the owner of that ATA.</p><p>In this example, the payer funds both accounts, but the receiver’s ATA belongs to the receiver.</p><p>This is useful when applications need to initialize token accounts for users before transferring tokens to them.</p><p>The two instructions can be submitted together:</p><pre>const transaction = new Transaction().add(<br>  createPayerATA,<br>  createReceiverATA<br>);</pre><pre>await sendAndConfirmTransaction(<br>  connection,<br>  transaction,<br>  [payer]<br>);</pre><p>After confirmation, both wallets have an associated token account for the newly created mint.</p><h3>6. Minting Tokens</h3><p>Minting is the process of creating additional units of a token and assigning them to a token account.</p><p>The SPL Token Program validates that the transaction is authorized by the mint authority.</p><p>For example, to mint 10 units:</p><pre>const mintInstruction = createMintToInstruction(<br>  mint.publicKey,<br>  payerATA,<br>  payer.publicKey,<br>  10<br>);</pre><p>The instruction contains:</p><ol><li>Mint address.</li><li>Destination token account.</li><li>Mint authority.</li><li>Amount in base units.</li></ol><p>Because the mint has zero decimals, 10 base units represent 10 whole tokens.</p><p>Submit the instruction:</p><pre>const transaction = new Transaction().add(<br>  mintInstruction<br>);</pre><pre>const signature = await sendAndConfirmTransaction(<br>  connection,<br>  transaction,<br>  [payer]<br>);</pre><pre>console.log(&quot;Mint transaction:&quot;, signature);</pre><p>The payer signs because it is the mint authority.</p><p>After successful execution, the payer’s token account contains 10 units.</p><p>The mint account’s total supply also increases by 10.</p><p><strong>Important:</strong> Minting does not create a new token mint. It increases the supply of an existing token and credits the specified token account.</p><h3>7. Transferring SPL Tokens</h3><p>A token transfer moves units from one token account to another.</p><p>It does not create a new mint, and it does not change the token’s total supply.</p><p>Suppose the payer owns 10 units and wants to transfer 5 units to the receiver.</p><p>The transfer instruction is:</p><pre>const transferInstruction = createTransferInstruction(<br>  payerATA,<br>  receiverATA,<br>  payer.publicKey,<br>  5<br>);</pre><p>The arguments specify:</p><ol><li>Source token account.</li><li>Destination token account.</li><li>Authority authorized to transfer from the source.</li><li>Amount in base units.</li></ol><p>The payer signs the transaction because it owns the source token account.</p><pre>const transaction = new Transaction().add(<br>  transferInstruction<br>);</pre><pre>const signature = await sendAndConfirmTransaction(<br>  connection,<br>  transaction,<br>  [payer]<br>);</pre><pre>console.log(&quot;Transfer transaction:&quot;, signature);</pre><p>After successful execution:</p><p>payer has 5 tokens in it’s ATA, and receiver has 5 tokens in it’s ATA.</p><p>The total supply remains unchanged because a transfer only changes the distribution of existing tokens.</p><h3>What actually happens during a transfer?</h3><p>The SPL Token Program validates the source account, destination account, mint, authority, and available balance.</p><p>If the instruction is valid, the program decreases the source token account’s balance and increases the destination token account’s balance.</p><p>The token mint itself remains unchanged.</p><p>The destination ATA also does not need to be recreated if it already exists. The existing account’s balance is updated.</p><p>This is an important distinction: transferring tokens does not create a new token account every time a transfer occurs.</p><h3>8. Understanding NFTs</h3><p>An NFT, or Non-Fungible Token, is a digital asset designed to represent something unique.</p><p>Unlike fungible tokens, NFTs are not interchangeable on a one-to-one basis.</p><p>For example:</p><ul><li>One unit of a fungible token is equivalent to another unit of the same token.</li><li>An individual NFT can represent a distinct digital artwork, membership, ticket, game item, or collectible.</li></ul><p>NFTs can provide verifiable ownership and a persistent identity for digital assets.</p><p>However, an NFT is not necessarily the image or file associated with it.</p><p>An NFT generally consists of:</p><ol><li>An on-chain identity.</li><li>Ownership information.</li><li>Metadata describing the asset.</li><li>A reference to associated media or other resources.</li></ol><p>Understanding the difference between an NFT’s on-chain representation and its off-chain metadata is essential.</p><h3>8.1 How were NFTs traditionally represented on Solana?</h3><p>The traditional NFT architecture on Solana was built using the SPL Token Program and Metaplex Token Metadata.</p><p>A traditional Metaplex NFT generally involves:</p><ul><li>An SPL mint account.</li><li>A token account holding the NFT.</li><li>A Metaplex metadata account.</li><li>A master edition account for the traditional NFT model.</li></ul><p>In the common traditional NFT model, the mint has zero decimals and a supply of one.</p><p>The associated token account holds the NFT token.</p><p>The metadata account stores information such as the NFT’s name, symbol, URI, creators, and other configuration.</p><p>This architecture works, but it involves multiple accounts and programs to represent a single NFT.</p><p>Metaplex Core provides an alternative architecture that simplifies NFT representation.</p><h3>9. Understanding Metaplex</h3><p>Metaplex is an ecosystem of protocols, programs, and developer tools for creating and managing digital assets on Solana.</p><p>It provides infrastructure for NFTs, digital collectibles, metadata, marketplaces, and other asset-related use cases.</p><p>Some important components in the Metaplex ecosystem include:</p><ul><li><strong>Token Metadata:</strong> The established metadata standard for traditional Solana NFTs.</li><li><strong>Candy Machine:</strong> A program for configuring and distributing collections of digital assets.</li><li><strong>Bubblegum:</strong> Infrastructure for compressed NFTs.</li><li><strong>Core:</strong> A modern standard for creating and managing digital assets using a dedicated asset account.</li></ul><p>These components address different use cases. They should not be treated as interchangeable implementations.</p><h3>9.1 Why was Metaplex Core introduced?</h3><p>Traditional NFT implementations often require multiple accounts to represent a single asset.</p><p>For example, a traditional NFT can involve a mint account, token account, metadata account, and master edition account.</p><p>This creates additional account-management complexity and can increase the amount of on-chain data and rent required.</p><p>Metaplex Core introduces an asset-centric architecture.</p><p>Instead of representing an NFT through the traditional SPL mint and token account structure, Core represents it through a dedicated <strong>Asset account</strong>.</p><p>This simplifies the account model and makes it easier to extend assets through plugins.</p><h3>Traditional NFT vs. Metaplex Core</h3><p>FeatureTraditional Token Metadata NFTMetaplex CoreAsset representationSPL mint and related accountsDedicated Asset accountOwnershipSPL token accountOwner field in Asset accountMetadataSeparate metadata accountData associated with Core AssetTransferSPL Token ProgramCore programExtensionsTraditional metadata configurationPlugin architectureSPL mint requiredYesNoATA required for ownershipYes, in the standard modelNo</p><p>Core does not replace every NFT standard or use case. It provides a different architecture for applications that want the Core asset model.</p><h3>10. Understanding Metaplex Core Architecture</h3><p>Metaplex Core uses a dedicated on-chain account to represent each asset.</p><p>The Core program manages the asset’s creation, ownership, metadata, and supported operations.</p><p>A Core Asset contains information such as:</p><ul><li>Asset public key.</li><li>Owner.</li><li>Update authority.</li><li>Name.</li><li>URI.</li><li>Plugin-related data.</li></ul><p>The exact account data and supported features depend on the Core program’s version and configuration.</p><h3>10.1 What is an Asset Account?</h3><p>An Asset account is the on-chain identity of a Core NFT.</p><p>It is owned by the Metaplex Core program.</p><p>Unlike the traditional SPL NFT model, a Core Asset does not require a separate SPL mint account and ATA to represent ownership.</p><p>This means that the asset’s public key acts as its persistent identifier.</p><p>For example:</p><pre>Asset Address:<br>7x...ExampleAssetAddress</pre><p>The address remains the identity of the asset even when ownership changes.</p><p>This is similar to how a database record can retain its primary key while its owner field changes.</p><h3>10.2 Owner vs. Update Authority</h3><p>Two important concepts in Core are the owner and the update authority.</p><p>They serve different purposes.</p><p><strong>Owner</strong></p><p>The owner is the wallet that currently owns the asset.</p><p>The owner can perform operations permitted by the Core program, including transferring the asset.</p><p><strong>Update Authority</strong></p><p>The update authority controls changes to the asset’s updateable data, subject to the asset’s configuration and plugin rules.</p><p>For example, an update authority may be able to change the asset’s name or URI if the asset is configured to permit those updates.</p><p>The owner and update authority do not have to be the same wallet.</p><p>Consider the following example:</p><pre>Asset:<br>  Owner: Wallet A<br>  Update Authority: Wallet B</pre><p>Wallet A owns the asset, while Wallet B controls permitted metadata updates.</p><p>Transferring the asset to another wallet does not automatically transfer the update authority.</p><p>This separation is useful for applications where an organization retains metadata-management rights while users own the assets.</p><h3>11. Understanding NFT Metadata</h3><p>An NFT’s metadata describes the asset and provides information that applications can display.</p><p>Metadata commonly includes:</p><ul><li>Name.</li><li>Symbol.</li><li>Description.</li><li>Image URI.</li><li>External URL.</li><li>Attributes.</li><li>Properties.</li></ul><p>For example, an NFT metadata JSON document could look like this:</p><pre>{<br>  &quot;name&quot;: &quot;Solana Developer #001&quot;,<br>  &quot;symbol&quot;: &quot;DEV&quot;,<br>  &quot;description&quot;: &quot;A digital collectible representing a Solana developer.&quot;,<br>  &quot;image&quot;: &quot;https://example.com/assets/developer.png&quot;,<br>  &quot;external_url&quot;: &quot;https://example.com&quot;,<br>  &quot;attributes&quot;: [<br>    {<br>      &quot;trait_type&quot;: &quot;Category&quot;,<br>      &quot;value&quot;: &quot;Developer&quot;<br>    },<br>    {<br>      &quot;trait_type&quot;: &quot;Network&quot;,<br>      &quot;value&quot;: &quot;Solana&quot;<br>    }<br>  ]<br>}</pre><p>This JSON document describes the NFT, but it is not itself the NFT’s on-chain identity.</p><p>The Core Asset stores a URI pointing to the metadata document.</p><p>Applications can retrieve the JSON document using that URI and use its contents to display the NFT.</p><h3>11.1 Why is metadata usually stored off-chain?</h3><p>Storing large images, videos, and JSON documents directly on-chain can be expensive.</p><p>Solana accounts have storage costs, and large amounts of data are generally better suited to off-chain storage systems.</p><p>A common architecture is:</p><pre>Solana Blockchain<br>                     |<br>                     |<br>               Core Asset<br>                     |<br>                Metadata URI<br>                     |<br>                     v<br>             Off-chain Storage<br>                     |<br>              Metadata JSON<br>                     |<br>                 Image URI<br>                     |<br>                     v<br>                Image File</pre><p>The blockchain stores the asset identity and metadata reference, while the actual metadata document and media are stored separately.</p><p>This separation reduces on-chain storage requirements.</p><p>However, it also introduces a dependency on the external storage system.</p><p>If a metadata URI points to a centralized server, the content may become unavailable if that server goes offline or changes its response.</p><p>For long-term NFT storage, content-addressed and decentralized storage systems are commonly preferred.</p><h3>12. Uploading NFT Assets and Metadata</h3><p>Before creating a Core NFT, the image and metadata JSON must be uploaded to storage.</p><p>One option is Arweave, a decentralized storage network designed for persistent data storage.</p><p>The Turbo SDK provides an interface for uploading data to Arweave through its infrastructure.</p><p>The implementation can use:</p><pre>bun add @ardrive/turbo-sdk</pre><p>The general upload workflow is:</p><ol><li>Prepare the NFT image.</li><li>Upload the image.</li><li>Obtain the image URI.</li><li>Create the metadata JSON using the image URI.</li><li>Upload the metadata JSON.</li><li>Obtain the metadata URI.</li><li>Use the metadata URI when creating the Core Asset.</li></ol><p>The resulting structure looks like:</p><pre>NFT Image<br>   |<br>   v<br>Upload Image<br>   |<br>   v<br>Image URI<br>   |<br>   v<br>Metadata JSON<br>   |<br>   v<br>Upload Metadata<br>   |<br>   v<br>Metadata URI<br>   |<br>   v<br>Create Metaplex Core Asset</pre><h3>12.1 Understanding the Turbo upload process</h3><p>A typical Turbo upload flow involves:</p><ul><li>Connecting using the required signer or wallet configuration.</li><li>Checking the available upload balance.</li><li>Calculating the upload cost.</li><li>Funding the upload balance when necessary.</li><li>Uploading the image or metadata.</li><li>Retrieving the resulting URI.</li></ul><p>The upload process is separate from creating the NFT on Solana.</p><p>Uploading an image does not create an NFT. It only makes the media available through a storage URI.</p><p>Similarly, uploading a metadata JSON document does not automatically create an on-chain asset.</p><p>The Core Asset must still be created through the Metaplex Core program.</p><p><strong>Important:</strong> The storage transaction and the Solana asset-creation transaction are separate operations. A successful upload does not guarantee that the later on-chain transaction will succeed.</p><h3>13. Creating an NFT Using Metaplex Core</h3><p>Once the metadata URI is available, the next step is to create the Core Asset.</p><p>Metaplex provides developer tooling through Umi and the Core SDK.</p><p>Install the relevant packages:</p><pre>bun add @metaplex-foundation/umi<br>bun add @metaplex-foundation/umi-bundle-defaults<br>bun add @metaplex-foundation/mpl-core</pre><h3>13.1 Understanding Umi</h3><p>Umi is a modular JavaScript framework used throughout the Metaplex ecosystem.</p><p>It provides abstractions for:</p><ul><li>Signers and identities.</li><li>Public keys.</li><li>Transactions.</li><li>RPC connections.</li><li>Program clients.</li><li>Transaction sending and confirmation.</li></ul><p>Instead of manually constructing every instruction and account structure, developers can use Umi-compatible SDK functions.</p><p>For example, a Umi instance can be configured with a Devnet RPC endpoint and a signer.</p><p>The exact signer setup depends on the keypair format and SDK version being used.</p><p>A simplified setup looks like:</p><pre>import { createUmi } from &quot;@metaplex-foundation/umi-bundle-defaults&quot;;<br>import { keypairIdentity } from &quot;@metaplex-foundation/umi&quot;;</pre><pre>const umi = createUmi(&quot;https://api.devnet.solana.com&quot;);</pre><pre>// Configure the signer using a Umi-compatible keypair.<br>umi.use(keypairIdentity(umiKeypair));</pre><p>Here, umiKeypair represents a keypair converted into the format expected by Umi.</p><h3>13.2 Creating a Core Asset</h3><p>The Core SDK provides a create operation for creating a new asset.</p><p>A simplified example is:</p><pre>import {<br>  create,<br>  mplCore,<br>} from &quot;@metaplex-foundation/mpl-core&quot;;</pre><pre>import { generateSigner } from &quot;@metaplex-foundation/umi&quot;;</pre><pre>umi.use(mplCore());</pre><pre>const asset = generateSigner(umi);</pre><pre>const result = await create(umi, {<br>  asset,<br>  name: &quot;Solana Developer #001&quot;,<br>  uri: metadataUri,<br>}).sendAndConfirm(umi);</pre><pre>console.log(&quot;Asset Address:&quot;, asset.publicKey);</pre><p>The example assumes that metadataUri contains the URI returned after uploading the metadata JSON document.</p><p>The creation operation:</p><ol><li>Generates an asset signer.</li><li>Constructs the Core Asset creation instruction.</li><li>Supplies the asset name and metadata URI.</li><li>Signs and submits the transaction.</li><li>Creates the asset account through the Metaplex Core program.</li></ol><p>The resulting asset public key is the NFT’s on-chain identity.</p><p>Unlike the traditional Token Metadata NFT model, this Core Asset does not require creating an SPL mint and associated token account to represent ownership.</p><p>The exact options available to the create instruction depend on the Core SDK version. Additional configuration, such as plugins or a different owner or update authority, can be supplied when supported by the SDK.</p><h3>14. Updating an NFT</h3><p>NFT metadata sometimes needs to change after creation.</p><p>For example:</p><ul><li>Correcting an asset’s name.</li><li>Updating its metadata URI.</li><li>Replacing an image reference.</li><li>Changing other updateable metadata fields.</li></ul><p>Metaplex Core supports updating assets through its update operation.</p><p>A simplified example:</p><pre>import {<br>  update,<br>} from &quot;@metaplex-foundation/mpl-core&quot;;</pre><pre>const result = await update(umi, {<br>  asset: assetAddress,<br>  name: &quot;Solana Developer #001 - Updated&quot;,<br>  uri: updatedMetadataUri,<br>}).sendAndConfirm(umi);</pre><p>The update operation is authorized according to the asset’s update authority and its configuration.</p><p>It is important to distinguish between updating an asset’s on-chain fields and updating the contents of the external metadata document.</p><p>For example:</p><p><strong>Updating the URI</strong></p><p>The asset’s on-chain URI is changed to point to a different metadata document.</p><p><strong>Updating the JSON at the existing URI</strong></p><p>The metadata document itself changes while the on-chain URI remains the same.</p><p>These are different operations.</p><p>If the metadata is stored using immutable, content-addressed storage, changing its contents generally produces a different URI. In that case, the asset’s URI must be updated if the new metadata is to be referenced.</p><h3>14.1 What is an immutable NFT?</h3><p>An immutable asset is one whose relevant update permissions have been permanently restricted or revoked.</p><p>Immutability is important because it provides stronger guarantees that asset information cannot be arbitrarily changed after creation.</p><p>However, immutability should be understood in terms of the actual asset configuration.</p><p>An immutable metadata document does not automatically make the on-chain asset immutable.</p><p>Likewise, revoking an asset’s update authority does not make an externally hosted image or metadata document immutable.</p><p>Both on-chain configuration and off-chain storage characteristics matter.</p><h3>15. Transferring an NFT</h3><p>Transferring an NFT changes the wallet that owns the asset.</p><p>For a traditional SPL NFT, ownership is represented through the balance in the associated token account.</p><p>For Metaplex Core, ownership is represented directly in the Core Asset account.</p><p>This is one of the key architectural differences between the two models.</p><h3>15.1 How does a Core NFT transfer work?</h3><p>Suppose:</p><pre>Asset:<br>  Owner: Wallet A</pre><p>Wallet A wants to transfer the asset to Wallet B.</p><p>After a successful transfer:</p><pre>Asset:<br>  Owner: Wallet B</pre><p>The asset address remains unchanged.</p><p>Only the ownership information is updated.</p><p>A simplified Core transfer example:</p><pre>import {<br>  transfer,<br>} from &quot;@metaplex-foundation/mpl-core&quot;;</pre><pre>const result = await transfer(umi, {<br>  asset: assetAddress,<br>  newOwner: receiverPublicKey,<br>}).sendAndConfirm(umi);</pre><p>The current owner or an appropriately authorized delegate must authorize the transfer according to the Core program’s rules.</p><p>The transfer does not create a second NFT. It does not generate a new asset address. It changes the owner of the existing asset.</p><p>The update authority is also a separate concept and is not automatically transferred just because ownership changes.</p><h3>15.2 Does transferring an NFT create a new account?</h3><p>For a Core Asset, the asset account remains the same.</p><p>The ownership field is updated by the Core program.</p><p>This differs from the mental model of creating a new token account for every NFT transfer.</p><p>In the traditional SPL NFT model, the source and destination token accounts already exist or may need to be created. The SPL Token Program updates their balances.</p><p>In the Core model, the asset’s ownership is managed directly by the Core program.</p><h3>16. Burning an NFT</h3><p>Burning is the process of permanently removing an asset from normal circulation.</p><p>For a traditional SPL token, burning reduces the token mint’s supply and the balance of the source token account.</p><p>For a Metaplex Core Asset, burning removes the asset according to the Core program’s burn operation.</p><p>A simplified example:</p><pre>import {<br>  burn,<br>} from &quot;@metaplex-foundation/mpl-core&quot;;</pre><pre>const result = await burn(umi, {<br>  asset: assetAddress,<br>}).sendAndConfirm(umi);</pre><p>The operation must be authorized by the current owner or an appropriately authorized Burn Delegate, depending on the asset’s configuration and plugin permissions.</p><p>An important distinction is that the update authority does not automatically have permission to burn an asset merely because it can update metadata.</p><p>Different operations have different authorization rules.</p><p>After a successful Core burn, the asset is no longer an active, normally usable asset under the Core program.</p><p>Burning should be treated as an irreversible operation. The asset’s address should not be assumed to remain usable as an active NFT after the burn.</p><h3>17. Understanding Metaplex Core Plugins</h3><p>One of the important features of Metaplex Core is its plugin architecture.</p><p>Plugins allow additional functionality and rules to be attached to an asset.</p><p>Instead of requiring every possible asset feature to be implemented directly in the base account structure, Core provides an extensible system.</p><p>Depending on the plugin, an asset can support additional capabilities such as:</p><ul><li>Royalties and creator configuration.</li><li>Transfer restrictions.</li><li>Freeze behavior.</li><li>Permanent attributes.</li><li>Delegated permissions.</li><li>Additional asset-management rules.</li></ul><p>Plugins can also define specific authorities and permissions.</p><p>For example, a transfer-related plugin can impose additional rules on how an asset may be transferred.</p><p>A royalties-related plugin can define creator royalty configuration.</p><p>A freeze-related plugin can control whether an asset can be frozen or thawed.</p><p>The exact behavior depends on the plugin type and its configuration.</p><p>This architecture makes Core suitable for applications that need more than basic NFT ownership and metadata.</p><h3>18. Common Misconceptions</h3><p>Understanding the following distinctions helps avoid common implementation mistakes.</p><h3>1. A wallet address is not a token account address</h3><p>A wallet can own multiple token accounts. Each token account is associated with a specific mint.</p><h3>2. A mint account does not store every wallet’s token balance</h3><p>The mint stores token-level information, including total supply and authorities. Individual balances are stored in token accounts.</p><h3>3. An ATA is not a new wallet</h3><p>An ATA is a token account derived from a wallet, mint, and token program. It does not represent a separate wallet identity.</p><h3>4. Transferring tokens does not create a new mint</h3><p>A token transfer changes the balances of existing token accounts. The mint and total supply remain unchanged.</p><h3>5. An NFT image is not the NFT itself</h3><p>The image is media associated with the asset. The on-chain asset and its metadata reference provide the asset’s identity and description.</p><h3>6. Uploading metadata does not create an NFT</h3><p>The metadata must be uploaded first, but an on-chain creation instruction is still required to create the Core Asset.</p><h3>7. Core NFTs do not require SPL mint and ATA accounts</h3><p>Metaplex Core uses a dedicated Asset account to represent ownership. It does not use the traditional SPL mint and token-account structure for Core asset ownership.</p><h3>8. The owner and update authority are different</h3><p>The owner controls ownership-related operations. The update authority controls permitted asset updates. These roles can belong to different wallets.</p><h3>9. Transferring a Core NFT does not change its asset address</h3><p>The same asset account remains the NFT’s identity. The Core program updates its owner.</p><h3>10. Immutability has multiple layers</h3><p>An immutable metadata file does not automatically make an on-chain asset immutable. On-chain permissions and off-chain storage must be considered separately.</p><h3>19. Putting the Complete Workflow Together</h3><p>The token and NFT implementations can be understood as two related but distinct workflows.</p><h3>SPL Token Workflow</h3><pre>Generate Mint Keypair<br>        |<br>        v<br>Create Mint Account<br>        |<br>        v<br>Initialize Mint<br>        |<br>        v<br>Derive Associated Token Accounts<br>        |<br>        v<br>Create Associated Token Accounts<br>        |<br>        v<br>Mint Tokens<br>        |<br>        v<br>Transfer Tokens<br>        |<br>        v<br>Verify Token Balances</pre><p>The mint defines the token, token accounts hold wallet balances, and the SPL Token Program validates operations such as minting and transferring.</p><h3>Metaplex Core NFT Workflow</h3><pre>Prepare NFT Image<br>        |<br>        v<br>Upload Image<br>        |<br>        v<br>Obtain Image URI<br>        |<br>        v<br>Create Metadata JSON<br>        |<br>        v<br>Upload Metadata<br>        |<br>        v<br>Obtain Metadata URI<br>        |<br>        v<br>Create Core Asset<br>        |<br>        v<br>Update / Transfer / Burn</pre><p>The Core program manages the asset’s on-chain identity and ownership, while the metadata URI connects it to the external description and media.</p><h3>20. Development Considerations</h3><p>When implementing these workflows, a few practical details are important.</p><h3>Use the correct cluster</h3><p>Ensure that the RPC endpoint, wallet funding, and transaction explorer all correspond to the intended cluster.</p><p>A Devnet transaction will not create an asset on Mainnet.</p><h3>Protect secret keys</h3><p>Never expose secret keys in source code, public repositories, screenshots, or logs.</p><p>Use environment variables or a secure wallet integration.</p><h3>Verify transaction confirmation</h3><p>Submitting a transaction and confirming its execution are separate steps.</p><p>Use the transaction signature to inspect the result on an explorer and verify that the expected account changes occurred.</p><h3>Handle account creation carefully</h3><p>Creating an account requires rent-exempt funding and transaction fees.</p><p>When an ATA already exists, attempting to create it again using a non-idempotent instruction may fail. Use an existence check or an idempotent ATA creation instruction where appropriate.</p><h3>Understand authorities before changing them</h3><p>Mint authority, freeze authority, asset owner, update authority, and plugin delegates control different capabilities.</p><p>Revoking or transferring an authority can have long-term consequences.</p><h3>Keep SDK versions consistent</h3><p>Solana and Metaplex SDKs evolve. Confirm that the APIs and package versions used in the implementation are compatible with one another.</p><p>For example, Umi public keys and signers should be converted using the appropriate Umi helpers rather than mixing incompatible types from unrelated SDK interfaces.</p><h3>21. Conclusion</h3><p>Solana’s token and NFT ecosystem is built around programs, accounts, authorities, and well-defined standards.</p><p>The SPL Token Program provides the foundation for fungible tokens. Mint accounts define token properties and supply, while token accounts maintain individual wallet balances. Associated Token Accounts provide a predictable way to locate a wallet’s standard token account for a particular mint.</p><p>Metaplex extends the ecosystem with tools and standards for digital assets. Its traditional Token Metadata approach represents NFTs through SPL token infrastructure and associated metadata accounts.</p><p>Metaplex Core takes a different approach by introducing a dedicated Asset account. This asset-centric architecture simplifies ownership representation and provides an extensible plugin system for additional functionality.</p><p>The distinction between on-chain identity, ownership, authority, and off-chain metadata is central to building reliable NFT applications.</p><p>Once these concepts are understood, operations such as creating tokens, minting, transferring, uploading metadata, creating NFTs, updating assets, and burning assets become easier to reason about — not just as SDK function calls, but as interactions between Solana programs and accounts.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46686ad59af9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Solana Deep Dive: Understanding Accounts, PDAs, and Runtime Rules]]></title>
            <link>https://medium.com/@ritamacharya2004/the-solana-deep-dive-understanding-accounts-pdas-and-runtime-rules-4feb93384e87?source=rss-f408f72e733d------2</link>
            <guid isPermaLink="false">https://medium.com/p/4feb93384e87</guid>
            <category><![CDATA[account]]></category>
            <category><![CDATA[instruction]]></category>
            <category><![CDATA[cpi]]></category>
            <category><![CDATA[solana-blockchain]]></category>
            <category><![CDATA[programs-in-solana]]></category>
            <dc:creator><![CDATA[Ritamacharya]]></dc:creator>
            <pubDate>Wed, 28 Oct 2026 14:18:16 GMT</pubDate>
            <atom:updated>2026-10-28T14:18:16.472Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/617/1*WqgprCqMu3zBaLAST_HCvg.jpeg" /></figure><h3><strong>What is Solana?</strong></h3><p>Solana is a high-speed, layer-1 blockchain launched in 2020. It can handle thousands of transactions per second (TPS) with average fees around <strong>$0.00025</strong>, making it far faster and cheaper than traditional networks.</p><h3><strong>Why use it</strong></h3><ul><li><strong>Microtransactions &amp; Trading:</strong> Ideal for high-frequency trading, fast token swaps, gaming, and NFT marketplaces where speed matters.</li><li><strong>User Experience:</strong> Transactions settle in under a second, removing long wait times.</li><li><strong>Staking:</strong> You can stake your native SOL tokens to help secure the network and earn passive yields.</li></ul><h3><strong>Bitcoin vs Ethereum vs Solana</strong></h3><p><strong>Bitcoin:</strong> Bitcoin was introduced for decentralized transactions. It follows Proof-of-work consensus. It can processes ~7 transactions per second and involve higher transaction fee.</p><p><strong>Etereum:</strong> Ethereum was introduced to Ethereum was introduced to expand blockchain technology beyond simple peer-to-peer financial payments by creating a programmable, decentralized “world computer”. It follows Proof-of-stake consensus. It can process 15–30 transactions per second and involve moderate to hightransaction fee.</p><p><strong>Solana:</strong> Solana was introduced to solve the scalability and speed limitations of earlier blockchains like Bitcoin and Ethereum. It follows Alpenglow consensus protocol on mainnet at epoc 1064. It can process thousands of transactions per second at an ultra-low($0.00025 per transaction) fee.</p><p>So, Now let’s try to unserstand the major terms related to Solana blockchain.</p><h3><strong>Accounts</strong></h3><p>An account is Solana’s fundamental data unit for storing state. The network stores all state in a key-value store where each key is a 32-byte address(either an Ed25519 public key or a PDA, which is base58 encoded string) and each value is an account.</p><p>Every account has the same five fields.</p><ol><li><strong>Lamports:</strong> It holds the account balance in lamports. It is the smallest unit of SOL. 1SOL = 10⁹ lamports. Every account must maintain a minimum lamport balance to keep its data stored onchain. This refundable storage balance is proportional to the account’s data size.</li><li><strong>Data: </strong>The data field stores an arbitrary byte array. Its contents depend on the account type.</li><li><strong>Owner: </strong>The owner field contains the program ID (public key) of the program that owns this account. The owner program is the only program that can — Modify the account’s data field, Deduct lamports from the account’s lamports field. Any program can add lamports to another account, but only the owner can deduct lamports from it.</li><li><strong>Rent epoch: </strong>The rent_epoch field is deprecated. Previously tracked when an account would automatically have lamports deducted to pay for maintaining its data onchain. Since ongoing rent collection is disabled, rent_epoch is set to u64::MAX for all new accounts that meet the minimum storage balance.</li><li><strong>Executable: </strong>The executable field is a boolean that determines whether the account is a program account(true) or a data account(false).</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/337/1*hhaa-ruFWJ_1axzfPzkF7w.png" /></figure><p><strong>Types of Accounts</strong></p><ol><li><strong>Program accounts: </strong>A program account stores executable code. Every program account is owned by a BPF loader Program. When a program is deployed, the runtime creates a program account to hold its bytecode. A program account has executable set to true.</li><li><strong>Program Data accounts:</strong> Programs deployed using loader-v3 do not store executable bytecode in their own data field. Instead, their data points to a separate program data account that contains the program code. Those accounts are called <strong>Program Data account</strong>. It has executable set to false and owner is the BPF loader program.</li><li><strong>Data accounts: </strong>Data accounts do not contain executable code. They store program-defined state. It has executable set to false and the owner is the program. It stores the account state as a binary in the data field.</li><li><strong>System accounts: </strong>Accounts that remain owned by the System Program after creation are called system accounts. Sending SOL to a new address for the first time creates a new account at that address owned by the System Program. All wallet accounts are system accounts. The fee payer on a transaction must be a system account, because only System Program-owned accounts can pay transaction fees.</li><li><strong>Sysvar accounts: </strong>Sysvar accounts are special accounts at predefined addresses that provide read-only access to cluster state data. They update dynamically each slot. Ex: Clock, Rent, Instructions etc.</li><li><strong>Program Derived Address(PDA) accounts: </strong>Program Derived Addresses (PDAs) are 32-byte account addresses that are deterministically derived from a program ID and a set of seeds. They are guaranteed to not lie on the Ed25519 curve, which means no private key exists for them. Only the program whose ID was used in the derivation can “sign” for a PDA, and it does so through invoke_signed during cross-program invocations (CPIs). These are the accounts owned by the program(whose program Id is used to derive it) and it stores the program state data. It has executable set to false.</li></ol><h4><strong>Modification Rules</strong></h4><p>The Solana runtime enforces these rules after each instruction executes via BorrowedInstructionAccount methods. Each rule is checked at the point of modification, and the transaction is rolled back if any check fails. Some important rules to remember are</p><ol><li>Only the owner can debit lamports.</li><li>Any program can credit lamports to a writable account.</li><li>Only the owner can modify data if the account is writable.</li><li>Only the current owner can reassign the owner if the account is writable and data is zero-initialized.</li></ol><p>Before execution, the runtime loads accounts, validates the fee payer, checks rent-exemption, and serializes account data into a memory layout that programs can access.</p><h3>Programs</h3><p>A Solana program is an account that contains executable sBPF bytecode and has its executable flag set to true. Programs are stateless. All mutable state lives in separate data accounts passed via instructions. We can write Solana programs in — 1. Anchor, 2. Pinocchio, 3. Native Rust.</p><p><strong>Loader Program</strong></p><p>Programs deployed via loader-v3 can be upgraded when an upgrade authority is set. Revoking the authority makes the program immutable.</p><p>There are 4 types of Loader programs.</p><ol><li><strong>Native Loader: </strong>Only upgradeable via validator software upgrade.</li><li><strong>BPF Loader(V1): </strong>Can’t upgrade the program once deployed.</li><li><strong>BPF Loader(V2): </strong>Can’t upgrade the program once deployed.</li><li><strong>BPF Loader Upgradeable(V3): </strong>Can upgrade the program if upgrade authority is set.</li></ol><p>All of our Solana program accounts are owned by these Loader programs.</p><p><strong>System Program</strong></p><p>The System Program (11111111111111111111111111111111) is the only program that can create new accounts. All new accounts are initially owned by the System Program, though ownership is typically reassigned upon creation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2F-t6eL4vvdQnJaHqUV_zQ.png" /></figure><p>Programs interact with the runtime through Syscalls. They cover things such as logging, hashing, CPI, cryptography, mem ops, etc.</p><h3>Instruction</h3><p>An instruction is a request to execute a specific function on a Solana program. Instructions are the fundamental building block for onchain operations. Each instruction specifies exactly one program to call, the accounts it needs, and a byte array of data that the program interprets (typically a discriminator to identify which instruction handler to run, followed by serialized arguments). Execution logic for each instruction is stored on a program, where each program defines its own set of instructions. To interact with the Solana network, one or more instructions are added to a transaction and sent to the network to be processed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6tEeNK_1cqzffaNi3jY4NQ.png" /></figure><p><strong>Instruction Structure</strong></p><p>An Instruction consists of three fields:</p><ol><li>Program Id: The instruction’s program_id is the public key address of the program that contains the instruction&#39;s execution logic. The runtime uses this field to route the instruction to the correct program for processing.</li><li>accounts: An array of account metadata. Metadata must be provided for each account the instruction interacts with. The validator uses this metadata to determine which transactions can run in parallel. Transactions that write to different accounts can execute in parallel. Each AccountMeta has three fields:</li></ol><ul><li>pubkey: The account’s public key address</li><li>is_signer: Set to true if the account must sign the transaction</li><li>is_writable: Set to true if the instruction modifies the account&#39;s data</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/1*XZ7pgPFLdpPa5tupLd6jEA.png" /></figure><p>3. data: The instruction’s data field is a byte array that tells the program which function to invoke and supplies the arguments for that function. The data typically begins with a discriminator or index byte(s) that identifies the target function, followed by the serialized arguments.</p><h3><strong>Transaction</strong></h3><p>A transaction includes one or more instructions, the signatures of accounts that authorize the changes, and a recent blockhash. The network processes all instructions in a transaction together. If any instruction fails, the entire transaction fails and all state changes are reverted. Fees are still charged on failure.</p><p>A Transaction has two top-level fields:</p><ul><li><strong>signatures:</strong> An array of signatures. The first signature in the array belongs to the fee payer, the account that pays the transaction basefee and prioritization fee. This first signature also serves as the transaction ID, used to look up the transaction on the network. The transaction ID is commonly referred to as the transaction signature.</li><li><strong>message:</strong> The message field is a Message struct containing the transaction&#39;s payload. These payloads are</li></ul><ol><li>header: The header field is a MessageHeader struct with three u8 fields that partition the account_keys array into permission groups:- i.num_required_signatures: Total number of signatures required by the transaction. ii.num_readonly_signed_accounts: Number of signed accounts that are read-only. iii. num_readonly_unsigned_accounts: Number of unsigned accounts that are read-only.</li><li>account_keys: The account_keys field is a compact-encoded array of public keys. Each entry identifies an account used by at least one of the transaction&#39;s instructions. The array must include every account and must follow this strict ordering: Signer + Writable, Signer + Read-only, Non-signer + Writable, Non-signer + Read-only. This strict ordering allows the account_keys array to be combined with the three counts in the message&#39;s header to determine the permissions for each account without storing per-account metadata flags. The header counts partition the array into the four permission groups listed above.</li><li>recent_blockhash: The recent_blockhash field is a 32-byte hash that serves two purposes: — 1. Timestamp: proves the transaction was created recently. 2. Deduplication: prevents the same transaction from being processed twice. A blockhash expires after 150 slots. If the blockhash is no longer valid when the transaction arrives, it is rejected with BlockhashNotFound, unless it is a valid durable nonce transaction.</li><li>instructions: The instructions field is a compact-encoded array of CompiledInstruction structs. Each CompiledInstruction references accounts by index into the account_keys array rather than by full public key. It contains: — <strong>program_id_index:</strong> Index into account_keys identifying the program to invoke. <strong>Accounts:</strong> Array of indices into account_keys specifying the accounts to pass to the program. <strong>Data:</strong> Byte array containing the instruction discriminator and serialized arguments.</li></ol><p>The total serialized size of a transaction must not exceed PACKET_DATA_SIZE(1,232 bytes) according to the v0 format. The 1,232 bytes include both the signatures array and the message struct. The v1 format raises the size limit to 4,096 bytes and uses a different wire layout.</p><h3><strong>Fees</strong></h3><p>Every Solana transaction requires a fee paid in SOL. The fee has two components: a base fee and an optional prioritization fee. The base fee compensates validators for the cryptographic work of verifying signatures. The prioritization fee increases the likelihood that the current leader schedules your transaction ahead of competing ones.</p><h3>Program Derived Addresses(PDA)</h3><p>Program derived addresses (PDAs) are 32-byte account address that are deterministically derived from a program ID and a set of seeds. A PDA is intentionally derived to fall off the Ed25519 curve. Because it is not a valid curve point, no secret key exists, and no external party can produce a signature. Only the deriving program can authorize operations on the PDA through invoke_signed.</p><p><strong>PDA vs Keypair account</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PBpDKhDxNTQtqg9SvOG-Yw.png" /></figure><p>PDAs are derived by hashing seeds and program ID and a bump via SHA-256 until the result is off the Ed25519 curve.</p><ol><li><strong>Program Id: </strong>Account address of your program.</li><li><strong>Optional seed: </strong>The optional seeds are user-defined byte strings that serve as inputs to the PDA derivation. They create unique, deterministic addresses scoped to a program. For example, using [“user”, user_pubkey] as seeds derives a different PDA for each user.</li><li><strong>Bump:</strong> The bump seed is a single byte (u8) appended to the optional seeds during derivation. find_program_address searches from 255 down to 1, calling create_program_address with each value until the result falls off the Ed25519 curve. The first value that succeeds is the canonical bump.</li></ol><p>Always use the canonical bump when deriving PDAs. Using a non-canonical bump creates a second valid address for the same seeds, which can lead to vulnerabilities where an attacker substitutes a different account than expected.</p><p>If all bump seed values from 255 down to 0 are exhausted without finding an address that falls off the Ed25519 elliptic curve, the find_program_address function will fail to return a valid PDA and throw a runtime or derivation error (such as a panic or NoValidBump error depending on the SDK/framework).</p><p>Deriving a PDA and creating an account at a PDA are two separate operations. You must explicitly create the account after deriving the address. To create an account at a PDA, the deriving program invokes the System Program create_account instruction via CPI, passes the PDA’s seeds so the runtime can verify the program authority over that address.</p><h3>Cross Program Invocation(CPI)</h3><p>A Cross-Program Invocation (CPI) is when one program calls an instruction on another program during execution. CPIs enable <strong>composability</strong>: any program’s instructions can be invoked by any other program on the network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MqQzwEFz6yQTIhpKJQ76ZQ.png" /></figure><p><strong>CPIs without PDA signers</strong></p><p>When a CPI doesn’t require PDA signers, the invoke function is used. The <strong>invoke</strong> function calls the <strong>invoke_signed</strong> function with an empty signers_seed array. The empty signers array indicates that no PDAs are required for signing.</p><p><strong>CPIs with PDA signers</strong></p><p>When a CPI requires a PDA signer, use <strong>invoke_signed </strong>with the signer seeds used to derive the PDA.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4feb93384e87" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understand SurfPool and set it up on your Linux-based system]]></title>
            <link>https://medium.com/@ritamacharya2004/understand-surfpool-and-set-it-up-on-your-linux-based-system-6f06220f1568?source=rss-f408f72e733d------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f06220f1568</guid>
            <category><![CDATA[setup]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[surfpool]]></category>
            <category><![CDATA[solana-blockchain]]></category>
            <dc:creator><![CDATA[Ritamacharya]]></dc:creator>
            <pubDate>Mon, 26 Oct 2026 13:44:20 GMT</pubDate>
            <atom:updated>2026-10-26T13:44:20.519Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Surfpool</strong> is a high-performance local development tool and network simulator for Solana, designed as a modern, drop-in replacement for solana-test-validator. In the Solana ecosystem, developers describe it as the equivalent of Ethereum&#39;s <strong>Anvil</strong> (from the Foundry suite).</p><p>Its core purpose is to make testing blockchain applications fast, realistic, and cost-effective by bridging the gap between a blank local machine and the live mainnet.</p><h3><strong>Why should I use Surfpool ?</strong></h3><ol><li><strong>Lazy Mainnet Forking (Copy-on-Read):</strong> Instead of downloading massive blockchain snapshots or manually cloning accounts, Surfpool dynamically fetches data from the actual Solana Mainnet the first time your local transaction interacts with a specific account, token balance, or program — caching it locally.</li><li><strong>Sub-Second Boot Times:</strong> Built on top of LiteSVM (a lightweight Solana Virtual Machine), it starts up in milliseconds and can even run smoothly on low-power devices like a Raspberry Pi.</li><li><strong>Built-in Studio &amp; Visual Dashboards:</strong> Running it launches <strong>Surfpool Studio</strong> — a web-based UI and interactive Terminal UI (TUI) to inspect transactions, debug programs, and watch block production in real time.</li></ol><h3><strong>Where It Fits Your Workflow ?</strong></h3><ol><li>Use <strong>LiteSVM</strong> or <strong>Mollusk</strong> for fast, isolated unit tests of pure program logic.</li><li>Use <strong>Surfpool</strong> when you need a full JSON-RPC server endpoint, want to test complex multi-program interactions against real Mainnet state, or want to run tests natively inside Anchor frameworks (where it is deeply integrated).</li></ol><h3><strong>How to setup Surfpool Locally</strong></h3><p><strong>Using the Installer Script (Recommended)</strong></p><p>Run this command</p><pre>curl -sL https://run.surfpool.run/ | bash</pre><p>Reload your terminal</p><pre> source ~/.bashrc</pre><p>Start a completely fresh, local Solana node</p><pre>surfpool start</pre><p>Verify the installation</p><pre>surfpool --version</pre><p>With these steps completed, <strong>SurfPool</strong> is now successfully set up and running on your system.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f06220f1568" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>