<?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 Het Dagli on Medium]]></title>
        <description><![CDATA[Stories by Het Dagli on Medium]]></description>
        <link>https://medium.com/@het2341999?source=rss-389abb49c536------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*aL-hvUzm70cxaUO35yqTUg.jpeg</url>
            <title>Stories by Het Dagli on Medium</title>
            <link>https://medium.com/@het2341999?source=rss-389abb49c536------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 22:09:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@het2341999/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[Optimizing Solana Programs]]></title>
            <link>https://medium.com/@het2341999/optimizing-solana-programs-26c7ddd0299c?source=rss-389abb49c536------2</link>
            <guid isPermaLink="false">https://medium.com/p/26c7ddd0299c</guid>
            <category><![CDATA[solana-network]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[crypto]]></category>
            <dc:creator><![CDATA[Het Dagli]]></dc:creator>
            <pubDate>Sat, 28 Sep 2024 20:35:39 GMT</pubDate>
            <atom:updated>2024-09-29T07:32:05.634Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NGmmgR2OY3rVxbRd.jpg" /><figcaption>Average Solano Optimizoooor</figcaption></figure><h3>Actionable insights</h3><ul><li>Use zero-copy deserialization for large data structures and high-frequency operations.</li><li>Implement custom serialization/deserialization to avoid Borsh overhead.</li><li>Use nostd_entrypoint instead of solana_program’s bloated entrypoint.</li><li>Mark critical functions with #[inline(always)] for potential performance gains.</li><li>Use bit manipulation for efficient instruction parsing.</li><li>Minimize dynamic allocations, favouring stack-based data structures.</li><li>Use Solana-specific C syscalls.</li><li>Measure compute unit usage to guide optimization efforts.</li></ul><p>Solana devs have a spectrum of choices for writing programs, each with its own trade-offs between ease of use, performance, and safety. At one end, we have the Anchor framework, providing a high-level abstraction that simplifies development but may introduce some overhead. At the other extreme, we find low-level approaches using unsafe Rust and direct syscalls, offering maximum performance at the cost of increased complexity and potential security risks.</p><p>Between these extremes lie options like Anchor with zero-copy deserialization and native Rust programming. Each approach represents a different balance of development speed, runtime efficiency, and safety guarantees. The key question for devs is not just how to optimize, but when and to what degree optimization is necessary.</p><p>This blog post explores these options in-depth, providing a roadmap for devs to navigate the optimization landscape. We’ll examine:</p><p>1. Anchor: The standard high-level framework<br>2. Anchor with zero-copy: Optimizing for large data structures<br>3. Native Rust: Balancing control and ease of use<br>4. Unsafe Rust with direct syscalls: Pushing the limits of performance</p><p>The goal is not to prescribe a one-size-fits-all solution but to equip developers with the knowledge to make informed decisions based on their specific use cases.</p><p>By the end of this post, you’ll have a clearer picture of how to think about these different levels of abstraction and when to consider moving down the optimization path. Remember, the most optimized code isn’t always the best solution — it’s about finding the right balance for your project’s needs.</p><p>For the impatient:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*HgtlPzJixgz832xzcZtj7A.png" /><figcaption>TL;DR</figcaption></figure><h4>Compute Units</h4><p>Solana’s high-performance architecture relies on efficient resource management. At the heart of this system are compute units (CUs) — a measure of computational resources consumed by a transaction.</p><h4>Why Care About Compute Units?</h4><p><strong>1. Transaction Success:</strong> Each transaction has a CU budget. Exceeding it leads to failure.<br><strong>2. Cost Efficiency: </strong>Lower CU usage means lower transaction fees.<br><strong>3. User Experience:</strong> Optimized programs execute faster, enhancing overall UX.<br><strong>4. Scalability:</strong> Efficient programs allow more transactions per block, improving network throughput.</p><h4>Measuring Compute Units</h4><p>solana_program::log::sol_log_compute_units()syscall logs the number of compute units consumed by a program at a specific point in its execution.</p><p>Here is a simple compute_fn! macro implementation using the syscall.</p><pre>#[macro_export]<br>macro_rules! compute_fn {<br>    ($msg:expr=&gt; $($tt:tt)*) =&gt; {<br>        ::solana_program::msg!(concat!($msg, &quot; {&quot;));<br>        ::solana_program::log::sol_log_compute_units();<br>        let res = { $($tt)* };<br>        ::solana_program::log::sol_log_compute_units();<br>        ::solana_program::msg!(concat!(&quot; } // &quot;, $msg));<br>        res<br>    };<br>}</pre><p>This is taken from <a href="https://github.com/solana-developers/cu_optimizations/blob/main/anchor/counter/anchor/programs/counter/src/lib.rs#L18">source code</a> where the macro is used to log the CU consumed by various code blocks.</p><p>The above code snippet implements a counter program with 2 instructions initialize and increment</p><p>We will write the same counter program with the same 2 instructions initialize and increment in 4 different ways anchor, anchor(zero_copy), native rust and unsafe rust and compare the CU usage for all of them.</p><p>Initializing an account and making a minor change to that account(incrementing) is a decent benchmark to compare different approaches. We are not using PDAs for now.</p><p>For the impatient here are the CU comparisons for the 4 approaches:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*hUrsp8EY3kutZLqp7GgLuQ.png" /><figcaption>CU comparisons</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EEbnG4mBMkZ09Ncr2k9nFQ.png" /><figcaption>Initialize Instruction</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3BZwk4VAIkVH-QdaVd3fBg.png" /><figcaption>Increment Instruction</figcaption></figure><p>Let’s get going…</p><h4>Zero-Copy Deserialization</h4><p>Zero-copy deserialization allows us to interpret account data directly, without allocating new memory or copying data. This technique can reduce CPU usage, lower memory consumption, and potentially lead to more efficient instructions.</p><p>Let us start with a basic Anchor counter program:</p><pre>use anchor_lang::prelude::*;<br> <br>declare_id!(&quot;37oUa3WkeqwnFxSCqyMnpC3CfTSwtvyJxnwYQc3u6U7C&quot;);<br><br>#[program]<br>pub mod counter {<br>    use super::*;<br> <br>    pub fn initialize(ctx: Context&lt;Initialize&gt;) -&gt; Result&lt;()&gt; {<br>        let counter = &amp;mut ctx.accounts.counter;<br>        counter.count = 0;<br>        Ok(())<br>    }<br> <br>    pub fn increment(ctx: Context&lt;Update&gt;) -&gt; Result&lt;()&gt; {<br>        let counter = &amp;mut ctx.accounts.counter;<br>        //Not doing checked_add, wrapping add or any overflow checks<br>        //to keep it simple<br>        counter.count += 1;<br>        Ok(())<br>    }<br>}<br> <br>#[derive(Accounts)]<br>pub struct Initialize&lt;&#39;info&gt; {<br>    #[account(init, payer = user, space = 8 + 8)]<br>    pub counter: Account&lt;&#39;info, Counter&gt;,<br>    #[account(mut)]<br>    pub user: Signer&lt;&#39;info&gt;,<br>    pub system_program: Program&lt;&#39;info, System&gt;,<br>}<br> <br>#[derive(Accounts)]<br>pub struct Update&lt;&#39;info&gt; {<br>    #[account(mut)]<br>    pub counter: Account&lt;&#39;info, Counter&gt;,<br>    pub user: Signer&lt;&#39;info&gt;,<br>}<br> <br>#[account]<br>pub struct Counter {<br>    pub count: u64,<br>}</pre><p>Nothing fancy above now let’s make it fancy with zero_copy</p><pre>use anchor_lang::prelude::*;<br><br><br>declare_id!(&quot;7YkAh5yHbLK4uZSxjGYPsG14VUuDD6RQbK6k4k3Ji62g&quot;);<br><br><br>#[program]<br>pub mod counter {<br> use super::*;<br><br>pub fn initialize(ctx: Context&lt;Initialize&gt;) -&gt; Result&lt;()&gt; {<br> let mut counter = ctx.accounts.counter.load_init()?;<br> counter.count = 0;<br> Ok(())<br> }<br><br>pub fn increment(ctx: Context&lt;Update&gt;) -&gt; Result&lt;()&gt; {<br> let mut counter = ctx.accounts.counter.load_mut()?;<br> counter.count += 1;<br> Ok(())<br> }<br>}<br><br>#[derive(Accounts)]<br>pub struct Initialize&lt;&#39;info&gt; {<br> #[account(init, payer = user, space = 8 + std::mem::size_of::&lt;CounterData&gt;())]<br> pub counter: AccountLoader&lt;&#39;info, CounterData&gt;,<br> #[account(mut)]<br> pub user: Signer&lt;&#39;info&gt;,<br> pub system_program: Program&lt;&#39;info, System&gt;,<br>}<br><br>#[derive(Accounts)]<br>pub struct Update&lt;&#39;info&gt; {<br> #[account(mut)]<br> pub counter: AccountLoader&lt;&#39;info, CounterData&gt;,<br> pub user: Signer&lt;&#39;info&gt;,<br>}<br><br>#[account(zero_copy)]<br>pub struct CounterData {<br> pub count: u64,<br>}</pre><p><strong>Key Changes:</strong></p><p><strong>1. AccountLoader Instead of Account:<br></strong> We now use AccountLoader&lt;’info, CounterData&gt; instead of Account&lt;’info, Counter&gt;. This allows for zero-copy access to the account’s data.</p><p><strong>2. Zero-Copy Attribute:<br></strong> The #[account(zero_copy)] attribute on CounterData indicates that this struct can be directly interpreted from raw bytes in memory.</p><p><strong>3. Direct Data Access:<br></strong> In the initialize and increment functions, we use load_init() and load_mut() respectively to get mutable access to the account data without copying it.</p><p><strong>4. Memory Layout Guarantees:<br></strong> The zero_copy attribute ensures that CounterData has a consistent memory layout, allowing safe reinterpretation from raw bytes.</p><p>This implementation reduced CU usage of initialize instruction from 5095 to 5022 and for increment instruction from 1162 to 1124.</p><p>Zero copy leads to minimal largely insignificant improvements for our case.</p><p>However zero-copy deserialization might come in handy for:</p><p><strong>1. Large Data Structures:</strong> When dealing with accounts storing complex or extensive data, zero-copy can substantially reduce CPU and memory usage.</p><p><strong>2. High-Frequency Operations:</strong> Programs that frequently read or write to accounts benefit from the reduced overhead of zero-copy deserialization.</p><h4>Trade-offs and Considerations</h4><p>Zero-copy isn’t without its challenges:</p><p><strong>1. Increased Complexity:</strong> The code becomes slightly more complex, requiring careful handling of raw data.</p><p><strong>2. Safety Considerations: </strong>Direct memory access requires extra attention to ensure data integrity and prevent errors.</p><p><strong>3. Compatibility: </strong>Not all data structures are suitable for zero-copy deserialization. They must have a predictable memory layout.</p><p>In practice, the decision to use zero-copy should be based on your specific use case. For simple programs like our counter, the benefits might be minimal. However, as your programs grow in complexity and handle larger data structures, zero-copy can become a powerful tool for optimization.</p><p>While zero-copy optimization didn’t yield significant improvements for our simple counter program, the quest for efficiency doesn’t end here. Let’s explore another avenue: writing native Solana programs in Rust without the Anchor framework. This approach offers more control and potential for optimization, albeit with increased complexity.</p><h4>Going Native</h4><p>Native Rust programs on Solana provide a lower-level interface, requiring developers to handle many tasks that Anchor automates. This includes account deserialization, serialization, and various security checks. While this demands more from the developer, it also opens up opportunities for fine-tuned optimizations.</p><p>Let’s examine the native Rust implementation of our counter program:</p><pre>use solana_program::{<br>    account_info::{next_account_info, AccountInfo},<br>    entrypoint,<br>    entrypoint::ProgramResult,<br>    program_error::ProgramError,<br>    pubkey::Pubkey,<br>    rent::Rent,<br>    system_instruction,<br>    program::invoke,<br>    sysvar::Sysvar,<br>};<br>use std::mem::size_of;<br><br>// Define the state struct<br>struct Counter {<br>    count: u64,<br>}<br><br>// Declare and export the program&#39;s entrypoint<br>entrypoint!(process_instruction);<br><br>// Program entrypoint&#39;s implementation<br>pub fn process_instruction(<br>    program_id: &amp;Pubkey,<br>    accounts: &amp;[AccountInfo],<br>    instruction_data: &amp;[u8],<br>) -&gt; ProgramResult {<br>    let instruction = instruction_data<br>        .get(0)<br>        .ok_or(ProgramError::InvalidInstructionData)?;<br><br>    match instruction {<br>        0 =&gt; initialize(program_id, accounts),<br>        1 =&gt; increment(accounts),<br>        _ =&gt; Err(ProgramError::InvalidInstructionData),<br>    }<br>}<br><br>fn initialize(program_id: &amp;Pubkey, accounts: &amp;[AccountInfo]) -&gt; ProgramResult {<br>    let account_info_iter = &amp;mut accounts.iter();<br>    let counter_account = next_account_info(account_info_iter)?;<br>    let user = next_account_info(account_info_iter)?;<br>    let system_program = next_account_info(account_info_iter)?;<br><br>    if !user.is_signer {<br>        return Err(ProgramError::MissingRequiredSignature);<br>    }<br><br>    if counter_account.owner != program_id {<br>        let rent = Rent::get()?;<br>        let space = size_of::&lt;Counter&gt;();<br>        let rent_lamports = rent.minimum_balance(space);<br><br>        invoke(<br>            &amp;system_instruction::create_account(<br>                user.key,<br>                counter_account.key,<br>                rent_lamports,<br>                space as u64,<br>                program_id,<br>            ),<br>            &amp;[user.clone(), counter_account.clone(), system_program.clone()],<br>        )?;<br>    }<br><br>    let mut counter_data = Counter { count: 0 };<br>    counter_data.serialize(&amp;mut &amp;mut counter_account.data.borrow_mut()[..])?;<br><br>    Ok(())<br>}<br><br>fn increment(accounts: &amp;[AccountInfo]) -&gt; ProgramResult {<br>    let account_info_iter = &amp;mut accounts.iter();<br>    let counter_account = next_account_info(account_info_iter)?;<br>    let user = next_account_info(account_info_iter)?;<br><br>    if !user.is_signer {<br>        return Err(ProgramError::MissingRequiredSignature);<br>    }<br><br>    let mut counter_data = Counter::deserialize(&amp;counter_account.data.borrow())?;<br><br>    //Not doing checked_add, wrapping add or any overflow checks to keep it simple<br>    counter_data.count += 1;<br>    counter_data.serialize(&amp;mut &amp;mut counter_account.data.borrow_mut()[..])?;<br><br>    Ok(())<br>}<br><br>impl Counter {<br>    fn serialize(&amp;self, data: &amp;mut [u8]) -&gt; ProgramResult {<br>        if data.len() &lt; size_of::&lt;Self&gt;() {<br>            return Err(ProgramError::AccountDataTooSmall);<br>        }<br>        <br>        //First 8 bytes is the count<br>        data[..8].copy_from_slice(&amp;self.count.to_le_bytes());<br>        Ok(())<br>    }<br><br>    fn deserialize(data: &amp;[u8]) -&gt; Result&lt;Self, ProgramError&gt; {<br>        if data.len() &lt; size_of::&lt;Self&gt;() {<br>            return Err(ProgramError::AccountDataTooSmall);<br>        }<br><br>        //First 8 bytes is the count<br>        let count = u64::from_le_bytes(data[..8].try_into().unwrap());<br>        Ok(Self { count })<br>    }<br>}<br> </pre><p><strong>Key Differences and Considerations:</strong></p><ol><li><strong>Manual Instruction Parsing:<br></strong> Unlike Anchor, which automatically routes instructions, we manually parse the instruction data and route it to the appropriate function.</li></ol><pre>let instruction = instruction_data<br>        .get(0)<br>        .ok_or(ProgramError::InvalidInstructionData)?;<br><br>    match instruction {<br>        0 =&gt; initialize(program_id, accounts),<br>        1 =&gt; increment(accounts),<br>        _ =&gt; Err(ProgramError::InvalidInstructionData),<br>    }</pre><p><strong>2. Account Management:<br></strong> We use next_account_info to iterate through accounts, manually checking for signers and owners. Anchor handles this automatically with its #[derive(Accounts)] macro.</p><pre>let account_info_iter = &amp;mut accounts.iter();<br>    let counter_account = next_account_info(account_info_iter)?;<br>    let user = next_account_info(account_info_iter)?;<br><br>    if !user.is_signer {<br>        return Err(ProgramError::MissingRequiredSignature);<br>    }</pre><p><strong>3. Custom Serialization:<br></strong> We implement custom serialize and deserialize methods for our Counter struct. Anchor uses borsh serialization by default, abstracting this away.</p><pre>impl Counter {<br>    fn serialize(&amp;self, data: &amp;mut [u8]) -&gt; ProgramResult {<br>        if data.len() &lt; size_of::&lt;Self&gt;() {<br>            return Err(ProgramError::AccountDataTooSmall);<br>        }<br>        <br>        //First 8 bytes is the count<br>        data[..8].copy_from_slice(&amp;self.count.to_le_bytes());<br>        Ok(())<br>    }<br><br>    fn deserialize(data: &amp;[u8]) -&gt; Result&lt;Self, ProgramError&gt; {<br>        if data.len() &lt; size_of::&lt;Self&gt;() {<br>            return Err(ProgramError::AccountDataTooSmall);<br>        }<br><br>        //First 8 bytes is the count<br>        let count = u64::from_le_bytes(data[..8].try_into().unwrap());<br>        Ok(Self { count })<br>    }<br>}</pre><p><strong>4. System Program Interactions:<br></strong> Creating accounts involves direct interaction with the System Program using invoke and doing a CPI, which Anchor simplifies with its init constraint.</p><pre>invoke(<br>      &amp;system_instruction::create_account(<br>          user.key,<br>          counter_account.key,<br>          rent_lamports,<br>          space as u64,<br>          program_id,<br>      ),<br>      &amp;[user.clone(), counter_account.clone(), system_program.clone()],<br>  )?;</pre><p><strong>5. Fine-grained Control:<br></strong>In general, native programs offer more control over data layout and processing, potentially allowing for more optimized code.</p><h4>How to think about Anchor v/s Native?</h4><p><strong>1. Explicit vs. Implicit:<br></strong> Native programs require explicit handling of many aspects that Anchor manages implicitly. This includes account validation, serialization, and instruction routing.</p><p><strong>2. Security Considerations:<br></strong> Without Anchor’s built-in checks, you must be vigilant about implementing proper security measures, such as checking account ownership and signer status.</p><p><strong>3. Performance Tuning:<br></strong> Native programs allow for more fine-grained performance optimizations but require a deeper understanding of Solana’s runtime behaviour.</p><p><strong>4. Boilerplate Code:<br></strong> Expect to write more boilerplate code for common operations that Anchor abstracts away.</p><p><strong>5. Learning Curve:<br></strong> While potentially more efficient, native programming has a steeper learning curve and requires more in-depth knowledge of Solana’s architecture.</p><h4>TL;DR</h4><p>The biggest limiting factor going from Anchor to native is to handle serialisation and deserialization. In our case, it was relatively simple but it would get complicated as state management gets complex.</p><p>However, it is also true that Borsh used by Anchor is computationally very costly, so the effort is worth it.</p><p>Our optimization journey doesn’t end here. In the next section, we’ll push the boundaries even further by leveraging direct syscalls and avoiding the Rust standard library.</p><p>This approach is challenging but I promise it would provide some interesting insights into the inner workings of Solana’s runtime.</p><h4>Pushing the Limits with Unsafe Rust and Direct Syscalls</h4><p>We’ll now examine how to leverage unsafe Rust and direct syscalls to squeeze out even more performance from our counter program. This approach, while more complex and requiring careful handling, can lead to significant CU savings.</p><p>Let’s look at a highly optimized version of our counter program:</p><pre>use solana_nostd_entrypoint::{<br>    basic_panic_impl, entrypoint_nostd, noalloc_allocator,<br>    solana_program::{<br>        entrypoint::ProgramResult, log, program_error::ProgramError, pubkey::Pubkey, system_program,<br>    },<br>    InstructionC, NoStdAccountInfo,<br>};<br><br>entrypoint_nostd!(process_instruction, 32);<br><br>pub const ID: Pubkey = solana_nostd_entrypoint::solana_program::pubkey!(<br>    &quot;EgB1zom79Ek4LkvJjafbkUMTwDK9sZQKEzNnrNFHpHHz&quot;<br>);<br><br>noalloc_allocator!();<br>basic_panic_impl!();<br><br>const ACCOUNT_DATA_LEN: usize = 8; // 8 bytes for u64 counter<br><br>/*<br> * Program Entrypoint<br> * ------------------<br> * Entrypoint receives:<br> * - program_id: The public key of the program&#39;s account<br> * - accounts: An array of accounts required for the instruction<br> * - instruction_data: A byte array containing the instruction data<br> *<br> * Instruction data format:<br> * ------------------------<br> * | Bit 0 | Bits 1-7 |<br> * |-------|----------|<br> * |  0/1  |  Unused  |<br> * <br> * 0: Initialize<br> * 1: Increment<br> */<br>#[inline(always)]<br>pub fn process_instruction(<br>    _program_id: &amp;Pubkey,<br>    accounts: &amp;[NoStdAccountInfo],<br>    instruction_data: &amp;[u8],<br>) -&gt; ProgramResult {<br><br>    if instruction_data.is_empty() {<br>        return Err(ProgramError::InvalidInstructionData);<br>    }<br><br>    // Use the least significant bit to determine the instruction<br>    match instruction_data[0] &amp; 1 {<br>        0 =&gt; initialize(accounts),<br>        1 =&gt; increment(accounts),<br>        _ =&gt; unreachable!(),<br>    }<br>}<br><br>/*<br> * Initialize Function<br> * -------------------<br> * This function initializes a new counter account.<br> * <br> * Account structure:<br> * ------------------<br> * 1. Payer account (signer, writable)<br> * 2. Counter account (writable)<br> * 3. System program<br> *<br> * Memory layout of instruction_data:<br> * -----------------------------------------<br> * | Bytes    | Content                     |<br> * |----------|----------------------------|<br> * | 0-3      | Instruction discriminator  |<br> * | 4-11     | Required lamports (u64)    |<br> * | 12-19    | Space (u64)                |<br> * | 20-51    | Program ID                 |<br> * | 52-55    | Unused                     |<br> */<br>#[inline(always)]<br>fn initialize(accounts: &amp;[NoStdAccountInfo]) -&gt; ProgramResult {<br><br>    let [payer, counter, system_program] = match accounts {<br>        [payer, counter, system_program, ..] =&gt; [payer, counter, system_program],<br>        _ =&gt; return Err(ProgramError::NotEnoughAccountKeys),<br>    };<br><br>    if counter.key() == &amp;system_program::ID {<br>        return Err(ProgramError::InvalidAccountData);<br>    }<br>    <br>    let rent = solana_program::rent::Rent::default();<br>    let required_lamports = rent.minimum_balance(ACCOUNT_DATA_LEN);<br><br>    let mut instruction_data = [0u8; 56];<br>    instruction_data[4..12].copy_from_slice(&amp;required_lamports.to_le_bytes());<br>    instruction_data[12..20].copy_from_slice(&amp;(ACCOUNT_DATA_LEN as u64).to_le_bytes());<br>    instruction_data[20..52].copy_from_slice(ID.as_ref());<br><br>    let instruction_accounts = [<br>        payer.to_meta_c(),<br>        counter.to_meta_c(),<br>    ];<br><br>    let instruction = InstructionC {<br>        program_id: &amp;system_program::ID,<br>        accounts: instruction_accounts.as_ptr(),<br>        accounts_len: instruction_accounts.len() as u64,<br>        data: instruction_data.as_ptr(),<br>        data_len: instruction_data.len() as u64,<br>    };<br><br>    let infos = [payer.to_info_c(), counter.to_info_c()];<br><br>    // Invoke system program to create account<br>    #[cfg(target_os = &quot;solana&quot;)]<br>    unsafe {<br>        solana_program::syscalls::sol_invoke_signed_c(<br>            &amp;instruction as *const InstructionC as *const u8,<br>            infos.as_ptr() as *const u8,<br>            infos.len() as u64,<br>            std::ptr::null(),<br>            0,<br>        );<br>    }<br><br>    // Initialize counter to 0<br>    let mut counter_data = counter.try_borrow_mut_data().ok_or(ProgramError::AccountBorrowFailed)?;<br>    counter_data[..8].copy_from_slice(&amp;0u64.to_le_bytes());<br><br>    Ok(())<br>}<br><br>/*<br> * Increment Function<br> * ------------------<br> * This function increments the counter in the counter account.<br> *<br> * Account structure:<br> * ------------------<br> * 1. Counter account (writable)<br> * 2. Payer account (signer)<br> *<br> * Counter account data layout:<br> * ----------------------------<br> * | Bytes | Content        |<br> * |-------|----------------|<br> * | 0-7   | Counter (u64)  |<br> */<br>#[inline(always)]<br>fn increment(accounts: &amp;[NoStdAccountInfo]) -&gt; ProgramResult {<br><br>    let [counter, payer] = match accounts {<br>        [counter, payer, ..] =&gt; [counter, payer],<br>        _ =&gt; return Err(ProgramError::NotEnoughAccountKeys),<br>    };<br><br>    if !payer.is_signer() || counter.owner() != &amp;ID {<br>        return Err(ProgramError::IllegalOwner);<br>    }<br><br>    let mut counter_data = counter.try_borrow_mut_data().ok_or(ProgramError::AccountBorrowFailed)?;<br><br>    if counter_data.len() != 8 {<br>        return Err(ProgramError::UninitializedAccount);<br>    }<br><br>    let mut value = u64::from_le_bytes(counter_data[..8].try_into().unwrap());<br>    value += 1;<br>    counter_data[..8].copy_from_slice(&amp;value.to_le_bytes());<br><br>    Ok(())<br>}</pre><h4>Key Differences and Optimizations:</h4><ol><li><strong>No-std Environment:</strong></li></ol><p>We’re using solana_nostd_entrypoint, which provides a no-std environment. This eliminates the overhead of the Rust standard library, reducing program size and potentially improving performance. Credits to <a href="https://x.com/cavemanloverboy">cavemanloverboy</a>, here is the repo to deep dive: <a href="https://github.com/cavemanloverboy/solana-nostd-entrypoint">https://github.com/cavemanloverboy/solana-nostd-entrypoint</a></p><p><strong>2. Inline Functions:<br></strong> Critical functions are marked with #[inline(always)], inlining gives potential performance gains.</p><p><strong>3. Bit Manipulation for Instruction Parsing:<br></strong> We use bit manipulation instruction_data[0] &amp; 1 to determine the instruction type, which can be more efficient than other parsing methods.</p><pre>// Use the least significant bit to determine the instruction<br>    match instruction_data[0] &amp; 1 {<br>        0 =&gt; initialize(accounts),<br>        1 =&gt; increment(accounts),<br>        _ =&gt; unreachable!(),<br>    }</pre><p><strong>4. Zero-Cost Memory Management and Minimal Panic Handling:</strong></p><p>The noalloc_allocator! and basic_panic_impl! macros implement minimal, zero-overhead memory management and panic handling:</p><p>noalloc_allocator!: Defines a custom allocator that panics on any allocation attempt and does nothing on deallocation. By setting this as the global allocator for Solana programs, it effectively prevents any dynamic memory allocation during runtime.</p><pre>#[macro_export]<br>macro_rules! noalloc_allocator {<br>    () =&gt; {<br>        pub mod allocator {<br>            pub struct NoAlloc;<br>            extern crate alloc;<br>            unsafe impl alloc::alloc::GlobalAlloc for NoAlloc {<br>                #[inline]<br>                unsafe fn alloc(&amp;self, _: core::alloc::Layout) -&gt; *mut u8 {<br>                    panic!(&quot;no_alloc :)&quot;);<br>                }<br>                #[inline]<br>                unsafe fn dealloc(&amp;self, _: *mut u8, _: core::alloc::Layout) {}<br>            }<br><br>            #[cfg(target_os = &quot;solana&quot;)]<br>            #[global_allocator]<br>            static A: NoAlloc = NoAlloc;<br>        }<br>    };<br>}</pre><p>This is crucial because:</p><p>a) It eliminates the overhead of memory allocation and deallocation operations.</p><p>b) It forces developers to use stack-based or static memory, which is generally faster and more predictable in terms of performance.</p><p>c) It reduces the program’s memory footprint.</p><p>basic_panic_impl! This macro provides a minimal panic handler that simply logs a “panicked!” message.</p><pre>#[macro_export]<br>macro_rules! basic_panic_impl {<br>    () =&gt; {<br>        #[cfg(target_os = &quot;solana&quot;)]<br>        #[no_mangle]<br>        fn custom_panic(_info: &amp;core::panic::PanicInfo&lt;&#39;_&gt;) {<br>            log::sol_log(&quot;panicked!&quot;);<br>        }<br>    };<br>}</pre><p><strong>5. Efficient CPI Preparation</strong></p><p>The InstructionC struct andto_meta_c, and to_info_c functions provide a low-level, efficient way to prepare data for CPIs.</p><pre>let instruction_accounts = [<br>        payer.to_meta_c(),<br>        counter.to_meta_c(),<br>    ];<br><br>    let instruction = InstructionC {<br>        program_id: &amp;system_program::ID,<br>        accounts: instruction_accounts.as_ptr(),<br>        accounts_len: instruction_accounts.len() as u64,<br>        data: instruction_data.as_ptr(),<br>        data_len: instruction_data.len() as u64,<br>    };<br><br>    let infos = [payer.to_info_c(), counter.to_info_c()];</pre><p>These functions create C-compatible structures that can be directly passed to the sol_invoke_signed_c syscall. By avoiding the overhead of Rust’s higher-level abstractions and working directly with raw pointers and C-compatible structures, these functions minimize the computational cost of preparing for CPIs. This approach saves CUs by reducing memory allocations, copies, and conversions that would typically occur when using more abstract Rust types.</p><p>For example, the to_info_c the method efficiently constructs an AccountInfoC struct using direct pointer arithmetic:</p><pre>pub fn to_info_c(&amp;self) -&gt; AccountInfoC {<br>AccountInfoC {<br>key: offset(self.inner, 8),<br>lamports: offset(self.inner, 72),<br>data_len: self.data_len() as u64,<br>data: offset(self.inner, 88),<br>owner: offset(self.inner, 40),<br>// … other fields …<br>}<br>}</pre><p>This direct manipulation of memory layouts allows for extremely efficient creation of the necessary structures for CPIs, thereby reducing the CU cost of these operations.</p><p><strong>6. Direct Syscalls and Unsafe Rust</strong></p><p>This approach bypasses the usual Rust abstractions and directly interacts with the Solana’s runtime, offering significant performance benefits. However, it also introduces complexity and requires careful handling of unsafe Rust.</p><pre>// Invoke system program to create account<br>#[cfg(target_os = &quot;solana&quot;)]<br>unsafe {<br>    solana_program::syscalls::sol_invoke_signed_c(<br>        &amp;instruction as *const InstructionC as *const u8,<br>        infos.as_ptr() as *const u8,<br>        infos.len() as u64,<br>        std::ptr::null(),<br>        0,<br>    );<br>}</pre><p><strong>7. Conditional Compilation:</strong></p><p>The #[cfg(target_os = “solana”)] attribute ensures this code only compiles when targeting the Solana runtime, which is necessary because these syscalls are only available in that environment.</p><h4>TL;DR</h4><p>While all this is fascinating I do think that using this in a production-ready program to secure real money might be a difficult sell. Further, making a memory map to decode the inputs in the right way might be complex for complex states. Using this you are most likely going to fall into the trap of premature optimizations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/0*rF0QiN4rElBuwEnr" /></figure><p>However, some things are easily replicable:</p><ol><li>Using nostd_entrypoint instead of bloatedentrypoint by solana_program.</li><li>Using inline functions wherever possible.</li><li>Minimizing dynamic allocations and favouring stack-based data structures.</li></ol><h4>Conclusion</h4><p>For a more detailed look at the programs and the tests, go <a href="https://github.com/hetdagli234/optimising-solana-programs">here</a>. I have made the programs as readable and easily approachable as possible sometimes at the cost of further optimizations ;)</p><p>If you have any queries hit me up at <a href="https://x.com/daglihet">@daglihet</a>. Although opening a PR in the repo above would make me reply faster ;)</p><p>Glass chewing should not stop!!! ;)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=26c7ddd0299c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Solana from First Principles: Part 3]]></title>
            <link>https://medium.com/@het2341999/solana-from-first-principles-part-3-88be76611e27?source=rss-389abb49c536------2</link>
            <guid isPermaLink="false">https://medium.com/p/88be76611e27</guid>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[solana-blockchain]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[crypto]]></category>
            <dc:creator><![CDATA[Het Dagli]]></dc:creator>
            <pubDate>Thu, 06 Jun 2024 11:17:28 GMT</pubDate>
            <atom:updated>2024-06-06T11:17:28.330Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*3ogjRgPZcnH1Uk6v.jpg" /></figure><p>As we discussed in <a href="https://medium.com/@het2341999/solana-from-first-principles-part-2-52189b26e5c9">Part 2</a>, PDAs are addresses that are deterministically derived from a set of seeds and a program ID. Unlike regular accounts, PDAs don’t have private keys associated with them.</p><p>PDAs provide a way to deterministically derive accounts that are owned by a program, allowing the program to sign transactions on behalf of those accounts.</p><p>Building upon the concept of PDAs, Solana introduces another powerful feature called Cross Program Invocations (CPIs). CPIs allow programs to interact with each other seamlessly, enabling composability and modularity in Solana’s ecosystem.</p><h3>Understanding Cross-Program Invocations (CPIs)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*yLNhgcz33MO-vQWl.jpg" /><figcaption>CPI in a nutshell</figcaption></figure><p>CPIs allow one program to call functions of another program directly as if they were part of the same codebase. This opens up a world of opportunities for developers to create dApps that interact with each other and build upon existing programs.</p><p>To understand the significance of CPIs in the world of Web3, let’s first take a step back and examine how traditional Web2 applications operate.</p><p>In Web2, each application typically has its own siloed database, where it stores and manages its data. While this approach provides a level of control and security, it also creates barriers to innovation and interoperability.</p><p>Imagine a scenario where a ride-sharing app wants to integrate a payment processing service. In the Web2 world, this would require the ride-sharing app to establish a partnership with the payment provider, negotiate terms, and implement a custom integration. The process is often complicated by legal contracts, data-sharing agreements, and technical challenges in connecting disparate systems.</p><p>Now, let’s consider the same scenario in the context of Web3. With CPIs, the ride-sharing dApp can simply call the functions of a payment processing program directly, without the need for complex integrations or legal agreements.</p><p>This is possible because, on Solana, programs can be composed and extended by other programs, just like Lego bricks. Each program provides a specific set of functionalities, and other programs can leverage those functionalities through CPIs.</p><p>In essence, CPIs enable programs to “talk” to each other and build upon each other’s capabilities. This composability is a fundamental principle of Web3 and is key to unlocking innovation in the decentralized ecosystem.</p><h3>So, how do CPIs work under the hood?</h3><p>When a program wants to invoke an instruction from another program, it needs to provide three pieces of information:</p><ol><li>The program ID of the called program.</li><li>The accounts required by the instruction.</li><li>The instruction data itself.</li></ol><p>There are two primary methods to invoke another program’s instruction: invoke and invoke_signed.</p><p>The invoke function is used to call another program&#39;s instruction without any additional signing. It requires the instruction and the accounts involved.</p><pre>use solana_program::program::invoke;<br>use solana_program::instruction::Instruction;<br><br>let instruction = Instruction {<br>    program_id: called_program_id,<br>    accounts: vec![AccountMeta::new(account_pubkey, false)],<br>    data: instruction_data,<br>};<br>invoke(&amp;instruction, &amp;[account_info])?;</pre><p>The invoke_signed the function is similar to invoke, but it allows the calling program to sign the instruction on behalf of a PDA.</p><pre>use solana_program::program::invoke_signed;<br><br>let seeds: &amp;[&amp;[u8]] = &amp;[b&quot;seed&quot;];<br>invoke_signed(&amp;instruction, &amp;[account_info], &amp;[seeds])?;</pre><h3>Using Anchor for CPIs</h3><p>Anchor simplifies the process of performing CPIs by abstracting away much of the boilerplate code. It provides a CpiContext struct that encapsulates the necessary information for a CPI, making it easier to manage and execute.</p><p>The CpiContext struct in Anchor is used to create a context for a CPI. It includes the program ID of the called program, the accounts required by the instruction, and any additional data.</p><pre>use anchor_lang::prelude::*;<br>use anchor_lang::solana_program::program::invoke;<br>use anchor_lang::solana_program::instruction::Instruction;<br><br>let cpi_program = ctx.accounts.called_program.to_account_info();<br>let cpi_accounts = Increment {<br>    counter: ctx.accounts.counter.to_account_info(),<br>};<br>let cpi_context = CpiContext::new(cpi_program, cpi_accounts);<br>called_program::cpi::increment(cpi_context)?;</pre><h3>Code Walkthrough</h3><p>We’ll understand how CPI works by invoking an instruction of the System Program. But first a short primer on the System Program.</p><p>The System Program is a core program in Solana that provides essential functionality for account management and SOL transfers. It allows you to create new accounts, allocate space for accounts, assign account ownership, and transfer SOL between accounts.</p><p>Whenever you create an account using #[account(init)] in anchor, you are essentially CPIing into System Program’s <a href="https://docs.rs/solana-program/1.18.4/solana_program/system_instruction/fn.create_account.html">create_account</a> instruction.</p><p>We’ll be invoking another instruction of the system program.</p><p>It is important to understand the instruction we are invoking before writing the logic.</p><p>The <a href="https://docs.rs/solana-program/1.18.4/solana_program/system_instruction/fn.transfer.html">transfer</a> instruction of the System Program looks something like this:</p><pre>pub fn transfer(<br>    from_pubkey: &amp;Pubkey,<br>    to_pubkey: &amp;Pubkey,<br>    lamports: u64<br>) -&gt; Instruction</pre><p>Now let’s write the logic to invoke this <a href="https://docs.rs/solana-program/1.18.4/solana_program/system_instruction/fn.transfer.html">transfer</a> instruction.</p><pre>use anchor_lang::prelude::*;<br>use anchor_lang::system_program;<br><br>declare_id!(&quot;3rbuZQnnuXbb7Pn7JmT7eppzWCCs4iPtQMhfkpbu9Hjp&quot;);<br><br>#[program]<br>pub mod cpi_example {<br>    use super::*;<br><br>    pub fn transfer_cpi(ctx: Context&lt;Transfer&gt;, amount: u64) -&gt; Result&lt;()&gt; {<br>        let cpi_program = ctx.accounts.system_program.to_account_info();<br>        let cpi_accounts = system_program::Transfer {<br>            from: ctx.accounts.from.to_account_info(),<br>            to: ctx.accounts.to.to_account_info(),<br>        };<br>        let cpi_context = CpiContext::new(cpi_program, cpi_accounts);<br>        system_program::transfer(cpi_context, amount)?;<br>        Ok(())<br>    }<br>}<br><br>#[derive(Accounts)]<br>pub struct Transfer&lt;&#39;info&gt; {<br>    #[account(mut)]<br>    pub from: Signer&lt;&#39;info&gt;,<br>    #[account(mut)]<br>    /// CHECK: This is not dangerous because we don&#39;t have to close the account<br>    pub to: AccountInfo&lt;&#39;info&gt;,<br>    pub system_program: Program&lt;&#39;info, System&gt;,<br></pre><p>Do: anchor build &amp;&amp; anchor deploy</p><p>The transfer_cpi instruction transfers SOL from one account to another. It takes a Context&lt;Transfer&gt; and an amount as parameters. Inside the transfer function:</p><ul><li>cpi_program represents the System Program&#39;s account info. Remember we need the called programs account for CPI.</li><li>cpi_accounts is a system_program::Transfer struct that specifies the from and to accounts for the transfer. Recall we need the accounts required by the called program.</li><li>It is important to note that the accounts passed here should be of the type expected by the program we are calling, in our case it is Transfer type of the System Program. For other programs, there should be a crate to help you get the required type.</li><li>cpi_context is a CpiContext created using the cpi_program and cpi_accounts. Constructing the cpi.</li><li>The system_program::transfer function is invoked with the cpi_context and amount to perform the actual SOL transfer. Here the amount is the data being passed through CPI.</li><li>In summary, we provided 3 things required for CPI; program: cpi_program , accounts: cpi_accounts and the data: amount</li></ul><p>The Transfer struct represents the accounts required for the transfer operation:</p><ul><li>from is the signer account that sends the SOL. It must be mutable.</li><li>to is the account that receives the SOL. It must also be mutable.</li><li>system_program is the System Program itself, which is required to perform the transfer.</li></ul><p>To test the program:</p><pre>import * as anchor from &quot;@coral-xyz/anchor&quot;;<br>import { Program } from &quot;@coral-xyz/anchor&quot;;<br>import { CpiExample } from &quot;../target/types/cpi_example&quot;;<br>import { PublicKey, SystemProgram } from &quot;@solana/web3.js&quot;;<br>import { expect } from &quot;chai&quot;;<br><br>describe(&quot;cpi-example&quot;, () =&gt; {<br>  const provider = anchor.AnchorProvider.env();<br>  anchor.setProvider(provider);<br><br>  const program = anchor.workspace.CpiExample as Program&lt;CpiExample&gt;;<br><br>  it(&quot;Transfers SOL using CPI&quot;, async () =&gt; {<br>    const from = anchor.web3.Keypair.generate();<br>    const to = anchor.web3.Keypair.generate();<br>    const amount = new anchor.BN(1_000_000_000); // 1 SOL<br><br>    // Airdrop SOL to the &#39;from&#39; account<br>    await provider.connection.confirmTransaction(<br>      await provider.connection.requestAirdrop(from.publicKey, amount.toNumber()),<br>      &quot;confirmed&quot;<br>    );<br><br>    // Perform the transfer using CPI<br>    await program.methods<br>      .transfer_cpi(amount)<br>      .accounts({<br>        from: from.publicKey,<br>        to: to.publicKey,<br>        systemProgram: SystemProgram.programId,<br>      })<br>      .signers([from])<br>      .rpc();<br><br>    // Check the balance of the &#39;to&#39; account<br>    const toBalance = await provider.connection.getBalance(to.publicKey);<br>    expect(toBalance).to.equal(amount.toNumber());<br>  });<br>});</pre><p>anchor test and we are done</p><h3>Conclusion</h3><p>Phew…</p><p>I hope I have tickled your curiosity enough to explore Solana further. This is just a starting point there are a lot of things to explore further like native Solana programming, Solana runtime, Token Extensions, etc.</p><p>Here is a comprehensive list of resources to get started: <a href="https://docs.google.com/document/d/1-8EUL-vxJw-0_pM6XtLZCk4WPTZrTcmcSea6cC2VnbQ/edit?usp=sharing">Solana</a>.</p><p>You can DM me on TG @daglihet with any questions or feedback.</p><p>Happy building!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88be76611e27" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Solana from First Principles: Part 2]]></title>
            <link>https://medium.com/@het2341999/solana-from-first-principles-part-2-52189b26e5c9?source=rss-389abb49c536------2</link>
            <guid isPermaLink="false">https://medium.com/p/52189b26e5c9</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[cryptocurrency]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[solanas]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <dc:creator><![CDATA[Het Dagli]]></dc:creator>
            <pubDate>Fri, 26 Apr 2024 19:32:18 GMT</pubDate>
            <atom:updated>2024-06-06T11:32:57.940Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*9iJBTycURd2HKBwJ.jpg" /></figure><p>In the <a href="https://medium.com/@het2341999/solana-from-first-principles-part-1-08525c7e1ccc">first part</a>, we learned that Solana uses public-private key pairs to manage ownership and access control. A wallet generates a key pair, with the public key used as the address for receiving tokens and the private key used to sign transactions and authorize changes.</p><p>Now that we understand how key pairs provide the foundation for ownership and control, let’s take a closer look at how Solana organizes and stores data using accounts.</p><h3><strong>Solana’s Account Model</strong></h3><p>Imagine you’re using a traditional bank. When you open an account, the bank assigns you an account number (like a public key) that you can share with anyone who wants to send you money. However, to access the funds in your account, you need to prove your identity using a password or PIN (like a private key). The bank maintains a ledger of all the accounts and their balances.</p><p>In Solana, the blockchain itself acts as the bank ledger. Instead of bank accounts, Solana has programmable accounts. Each account is like a safety deposit box holding data or executable code.</p><p>Just like a bank account, each Solana account has a unique address derived from a public key. Anyone can send tokens to this address, but only the person with the corresponding private key can access the contents of the account.</p><p>There are two main types of accounts in Solana:</p><ol><li><strong><em>Data Accounts:</em></strong> These are like standard bank accounts that store your data or tokens. They’re controlled by programs and can only be modified according to the program’s rules.</li><li><strong><em>Program Accounts:</em></strong> These special accounts hold the code that defines the rules for how the associated Data Accounts can be modified. You can think of them as the bank’s software that controls how funds can be transferred or withdrawn.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*K9E3HgCYNdSZisJy.jpg" /><figcaption>Program account and Data account</figcaption></figure><h3>Data Storage and the Concept of State</h3><p>Imagine you’re playing a game of chess. Each move changes the position of the pieces on the board. The “state” of your chess game is the arrangement of all the pieces at any given time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/244/0*chiA7n-lDjmrhkvn.gif" /></figure><p>Similarly, the state of an account is the current information it holds, such as the balance of tokens, ownership details, or data specific to a decentralized application (dApp).</p><p>The state of a blockchain refers to the current status or condition of all the accounts in the system at any given moment. It’s like a snapshot that captures all the transactions and decisions that have happened up to that point.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VLD0bc70wLUVy9ileTTpIA.png" /><figcaption>Ethereum State visualised</figcaption></figure><p>In Solana, the data is stored in Data accounts. Interestingly the program accounts don’t store any data and hence are stateless.</p><h3>How Stateless Programs Work?</h3><p>As we have seen before programs are essentially executable accounts that contain the logic or the code necessary to perform operations.</p><p>When a transaction occurs, the necessary data is passed to these programs via references to accounts or in simpler terms accounts are passed as an argument to the function.</p><p>This data and logic separation allows Solana to optimize transaction throughput by parallelizing the execution of transactions that do not operate on overlapping data, thereby preventing conflicts and ensuring efficient use of network resources.</p><h3>Rent and Resource Management</h3><p>Since storing data on the blockchain takes up space, Solana uses a rent mechanism to manage resource allocation.</p><p>Accounts holding data need to maintain a minimum balance, proportional to their size, to remain active. However, accounts can become “rent-exempt” by holding a balance sufficient to cover rent for an extended period, typically two years&#39; worth of rent payments, ensuring they are not purged from the system.</p><p>Recent updates to Solana have mandated that all new accounts must be initialized with enough lamports (the smallest unit of SOL) to be rent-exempt, ensuring that they are not subject to rent payments and are not at risk of being purged.</p><h3>Understanding Program Derived Addresses (PDAs)</h3><p>This is by far the most complicated concept of Solana so bear with me.</p><p>Data accounts have some limitations:</p><ol><li>They are controlled by private keys. If these keys are compromised, the security of the account and its assets are at risk.</li><li>They are typically passive and require external instructions signed by private keys to make changes. This means that every operation needs to be explicitly authorized by an external signer, which can complicate or slow down automated processes within dApps.</li><li>While data accounts can interact with multiple programs, managing these interactions securely and efficiently can be cumbersome. Each interaction would typically require permissions and signatures, complicating the development and execution of complex dApps that require seamless interactions between different programs.</li></ol><p>Imagine you’re using a highly secure app that needs to perform actions on your behalf without constantly asking for your password. In Solana, PDAs serve a similar function for programs. They allow programs to perform specific actions or control certain accounts without needing a traditional private key. This setup enhances security and efficiency.</p><p>PDAs are special types of addresses which do not have a corresponding private key.</p><h3>How PDAs are Created?</h3><p>Creating a PDA is somewhat like making a custom ID tag that doesn’t need a key to open but can be recognized and used by a specific program. Here’s how it works:</p><ol><li><strong>Combination of Ingredients (Seeds and Program ID):</strong> To create a PDA, a program combines several pieces of data, known as “seeds” (these could be numbers, strings, or other public keys), with its own unique identifier (Program ID). This combination is unique to each PDA.</li><li><strong>Hashing Function:</strong> The program uses <em>findProgramAddressSync </em>function which takes in seeds and the program ID and passes it through a cryptographic function (SHA-512), which mixes them to produce a new, unique address.</li><li><strong>Bump Seed:</strong> Sometimes, the result of the hashing might accidentally create an address that could theoretically have a corresponding private key (even though it’s highly unlikely). To prevent this and ensure the address is truly “off-curve” (meaning it can’t have a private key), a small adjustment called a “bump seed” is used.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*r0SM0fJzQNd30AeU.png" /><figcaption>PDAs are off-curve(no private key)</figcaption></figure><p>Only the program that generated the PDA can use it. This means the program can perform operations involving the PDA, like updating data stored at the address or transferring assets, without any other user or program being able to do so.</p><h3>Why PDAs Are Necessary?</h3><p>PDAs address the limitations of regular data accounts which we talked about earlier:</p><ol><li><strong>No Private Keys:</strong> PDAs do not have private keys. They are derived programmatically using a combination of seeds and a program ID, which inherently makes them more secure against certain types of attacks, such as key theft or leakage.</li><li><strong>Exclusive Program Control:</strong> Only the program that created a PDA can control it. This exclusive control allows for secure and predictable interactions within and across programs without needing external signatures. For example, a program can autonomously update state or manage assets within its PDAs without any external intervention, streamlining operations and enhancing security.</li><li><strong>Efficient Cross-Program Invocations:</strong> PDAs facilitate smoother and more secure interactions between different programs. Since a PDA can be controlled directly by the program that created it, it simplifies the architecture of cross-program operations. This is particularly important in complex dApps involving multiple smart contracts that need to interact seamlessly and securely.</li><li><strong>Specific Use Cases: </strong>Certain functionalities, like managing user-specific states or creating unique identifiers for transactions within a program, are more efficiently handled using PDAs. For instance, a PDA can be used to uniquely identify and manage user sessions or specific tasks within a program, which would be cumbersome and less secure with a regular data account.</li></ol><p>Next is my favourite part, let’s get our hands dirty.</p><h3>Deploying Your First Program on Solana</h3><p>We’ll create a simple program that integrates the concepts we’ve discussed: accounts, state management, and Program Derived Addresses (PDAs).</p><p>Our goal is to build a Solana program using Anchor, a framework that simplifies Solana development.</p><p>You can use Solana’s Web-Based IDE for this task here: <a href="http://beta.solpg.io/">SolPg</a>. Here I will talk about how you can run a solana program locally.</p><h3>Part 1: Setting Up Your Development Environment</h3><p>Follow the steps here to set up locally: <a href="https://solana.com/developers/guides/getstarted/setup-local-development">https://solana.com/developers/guides/getstarted/setup-local-development</a></p><h4>Step 1: Install Rust</h4><p>Solana programs are primarily written in Rust, so the first step is to install Rust on your machine. Open your terminal and run the following command:</p><pre>curl - proto &#39;=https&#39; - tlsv1.2 -sSf https://sh.rustup.rs | sh</pre><p>This script will install rustup, the Rust toolchain manager, along with the default compiler and Cargo, Rust’s package manager and build system.</p><h4>Step 2: Install Solana Tools</h4><p>Next, you’ll need the Solana command-line tools. Install them by running:</p><pre>sh -c &quot;$(curl -sSfL https://release.solana.com/stable/install)&quot;</pre><p>To check if your installation was successful, check the Solana CLI version:</p><pre>solana --version</pre><h4>Step 3: Install Anchor using AVM</h4><pre>cargo install --git https://github.com/coral-xyz/anchor avm --locked --force<br>avm install latest<br>avm use latest</pre><p>Verify if the installation was correct as of now, latest Anchor version is 0.3.0</p><pre>anchor --version</pre><h4>Step 4: Using Devnet</h4><p>Solana runs on 3 environments mainnet-beta, testnet, and devnet.</p><p>We’ll use Devnet.</p><pre>solana config set --url devnet</pre><p>You can verify your configuration anytime using</p><pre>solana config get</pre><h4>Step 5: Setting Up Solana Wallet</h4><p>You’ll need a Solana wallet. Create one by running:</p><pre>solana-keygen new</pre><p>This command will generate a new key pair and show you the path to your wallet file.</p><p>We would use this account to deploy programs on-chain.</p><p>Airdrop some tokens to pay for rent and deployment costs.</p><pre>solana airdrop 2</pre><p>You can get more tokens by using this faucet: <a href="https://faucet.solana.com/">https://faucet.solana.com/</a></p><p>Check Balance</p><pre>solana balance</pre><p>You should see 2 SOL as your balance.</p><h3>Part 2: Writing Your First Solana Program</h3><h4>Step 1: Initialize a New Anchor Project</h4><p>Create a new directory for your project and navigate into it:</p><pre>mkdir my-solana-project<br>cd my-solana-project</pre><p>Initialize a new Anchor project:</p><pre>anchor init counter</pre><p>This command creates a new project named counter.</p><h4>Step 2: Understanding the Project Structure</h4><p>Your new Anchor project has several key components:</p><ul><li>programs/: Contains your Rust programs.</li><li>tests/: Where your JavaScript (or TypeScript) tests will reside.</li><li>Anchor.toml: Configuration file for Anchor.</li><li>app/: A simple frontend application (if you chose to generate it).</li></ul><p>In Anchor.toml, change the configuration to devnet.</p><p>Change programs.localnet to programs.devnet and change the cluster value from “localnet” to “devnet”.</p><h4>Step 3: Write the Program</h4><p>Navigate to programs/counter/src/lib.rs. This is where you’ll write your Rust code for the program.</p><p>Here’s a simple counter program:</p><pre>use anchor_lang::prelude::*;<br><br>declare_id!(&quot;4gdRvoPjjwbkMtDfWzUcrDghfQTxoV4oU6L2ELz88qUW&quot;);<br><br>#[program]<br>pub mod counter {<br>    use super::*;<br>    pub fn initialize(ctx: Context&lt;Initialize&gt;, counter: u8) -&gt; Result&lt;()&gt; {<br>        let counter_account = &amp;mut ctx.accounts.counter_account;<br>        counter_account.counter = counter;<br>        Ok(())<br>    }<br><br>    pub fn increment(ctx: Context&lt;Increment&gt;) -&gt; Result&lt;()&gt; {<br>        let counter_account = &amp;mut ctx.accounts.counter_account;<br>        counter_account.counter += 1;<br>        Ok(())<br>    }<br>}<br><br>#[derive(Accounts)]<br>pub struct Initialize&lt;&#39;info&gt; {<br>    #[account(init, payer = user, space = 8 + 8, seeds = [b&quot;counter&quot;, user.key().as_ref()], bump)]<br>    pub counter_account: Account&lt;&#39;info, CounterAccount&gt;,<br>    #[account(mut)]<br>    pub user: Signer&lt;&#39;info&gt;,<br>    pub system_program: Program&lt;&#39;info, System&gt;,<br>}<br><br>#[derive(Accounts)]<br>pub struct Increment&lt;&#39;info&gt; {<br>    #[account(mut, seeds = [b&quot;counter&quot;, user.key().as_ref()], bump)]<br>    pub counter_account: Account&lt;&#39;info, CounterAccount&gt;,<br>    pub user: Signer&lt;&#39;info&gt;,<br>}<br><br>#[account]<br>pub struct CounterAccount {<br>    pub counter: u8,<br>}</pre><p>Anchor programs are generally divided into two main parts: <strong>instructions</strong> and <strong>accounts</strong>.</p><p>Instructions define the actions our program can perform. In this case, we have two instructions:</p><ol><li><em>initialize</em>: initializes a new data account with a counter set by the input given by the user.</li><li><em>increment</em>: increments the counter in the data account.</li></ol><p>Accounts define the data structures used by our program. We have two account structs:</p><ol><li>Initialize: defines the accounts required for the <em>initialize</em> instruction.</li><li><em>Increment</em>: defines the accounts required for the <em>increment</em> instruction.</li><li>CounterAccount : defines the counter variable which would be manipulated.</li></ol><p>Code Walkthrough</p><pre>use anchor_lang::prelude::*;</pre><p>This line brings in all the necessary types and macros from the anchor_lang crate. You can think of crates as the npm equivalent of Rust.</p><pre>declare_id!(&quot;Fg6PaFyL1JpZsh2sfyZ1LWQVnJDs9ub6QUT7QXeDx4e&quot;);</pre><p>The declare_id! macro is used to define the unique identifier for our program. This would be the Program ID of your Program. Ignore this for now, we will change this later.</p><pre>#[program]<br>pub mod first_solana_app {<br> use super::*;<br> // …<br>}</pre><p>The #[program] attribute indicates that the following module contains our Solana program’s logic. Inside this module, we define our instructions: initialize and increment.</p><pre>pub fn initialize(ctx: Context&lt;Initialize&gt;, counter: u8) -&gt; Result&lt;()&gt; {<br> let counter_account = &amp;mut ctx.accounts.counter_account;<br> counter_account.counter = counter;<br> Ok(())<br> }</pre><p>The initialize instruction takesContext&lt;Initialize&gt; and counter integer as inputs. We extract the counter_account from the context and set its counter field to the integer passed on by the client. The Ok(()) at the end indicates that the instruction was executed successfully.</p><pre>pub fn increment(ctx: Context&lt;Increment&gt;) -&gt; Result&lt;()&gt; {<br> let counter_account = &amp;mut ctx.accounts.counter_account;<br> counter_account.counter += 1;<br> Ok(())<br>}</pre><p>Similarly, the increment instruction takes Context&lt;Increment&gt; and extracts the counter_account. It then increments the counter field by 1.</p><pre>#[derive(Accounts)]<br>pub struct Initialize&lt;&#39;info&gt; {<br> #[account(init, payer = user, space = 8 + 8, seeds = [b&quot;counter&quot;, user.key().as_ref()], bump)]<br> pub counter_account: Account&lt;&#39;info, CounterAccount&gt;,<br> #[account(mut)]<br> pub user: Signer&lt;&#39;info&gt;,<br> pub system_program: Program&lt;&#39;info, System&gt;,<br>}</pre><p>TheInitialize struct defines the accounts required for the initialize instruction. It has three fields:<br>1. counter_account: This is the account where we’ll store our counter. #[account(…)] attribute specifies that this account should be initialized with the given constraints (payer, space, seeds, bump). This account is our PDA.<br>2. user: This is the account of the user initializing the program. It must be a signer.<br>3. system_program: This is the Solana System Program, which is required for account creation.</p><pre>#[derive(Accounts)]<br>pub struct Increment&lt;&#39;info&gt; {<br> #[account(mut, seeds = [b&quot;counter&quot;, user.key().as_ref()], bump)]<br> pub counter_account: Account&lt;&#39;info, CounterAccount&gt;,<br> pub user: Signer&lt;&#39;info&gt;,<br>}</pre><p>The Increment struct defines the accounts for the increment instruction. It has two fields:<br>1. counter_account: This is the same account used in Initialize, but now it’s mutable so we can increment the counter.<br>2. user: The user account, which must be a signer.</p><pre>#[account]<br>pub struct CounterAccount {<br> pub counter: u64,<br>}</pre><p>Finally, the CounterAccount struct defines the structure of our data account. It has a single field, counter which is an unsigned 64-bit integer.</p><h4>Step 4: Build and Deploy</h4><p>Run the following commands to build and deploy, make sure you are at the root where you initialized your program.</p><pre>anchor build<br>anchor deploy</pre><p>If everything goes as planned, the program should build and deploy successfully.</p><p>You may not have enough SOL to deploy, use solana airdrop 2 to get more SOL in your account.</p><p>Once deployed you would get a Program ID, replace the declare_id! macro at the top of the program with your program ID.</p><p>You’ll see a counter.json file in target/idl folder. This is the IDL of your program. An IDL (Interface Definition Language) is a JSON file that defines the public interface of a Solana program. It specifies the program’s instructions, account structures, and error codes, making it easier for client applications to interact with the program</p><p>In target/deploy folder you will see the counter.so and counter-keypair.json files. counter.so is the compiled code which lives on the chain and counter-keypair.json is the keypair of your program.</p><h3>Part 3: Testing Your Solana Program</h3><h4>Step 1: Write Tests</h4><p>Navigate to the tests/ directory. Here, you’ll find a TypeScript file where you can write tests for your program.</p><p>Here’s how you might write tests for the initialize and increment functions:</p><pre>import * as anchor from &#39;@project-serum/anchor&#39;;<br>import { Program } from &#39;@project-serum/anchor&#39;;<br>import { Counter } from &#39;../target/types/counter&#39;;<br><br>describe(&#39;counter&#39;, () =&gt; {<br>  // Configure the client to use the local cluster.<br>  anchor.setProvider(anchor.Provider.env());<br><br>  const program = anchor.workspace.Counter as Program&lt;Counter&gt;;<br><br>  it(&#39;Initializes the counter&#39;, async () =&gt; {<br>    // Call the initialize function<br>    const counter = anchor.web3.Keypair.generate();<br>    await program.rpc.initialize(new anchor.BN(0), {<br>      accounts: {<br>        counter: counter.publicKey,<br>        user: program.provider.wallet.publicKey,<br>        systemProgram: anchor.web3.SystemProgram.programId,<br>      },<br>      signers: [counter],<br>    });<br><br>    // Fetch the account and check the value<br>    const account = await program.account.counter.fetch(counter.publicKey);<br>    assert.equal(account.count.toNumber(), 0);<br>  });<br><br>  it(&#39;Increments the counter&#39;, async () =&gt; {<br>    const counter = anchor.web3.Keypair.generate();<br>    await program.rpc.initialize(new anchor.BN(0), {<br>      accounts: {<br>        counter: counter.publicKey,<br>        user: program.provider.wallet.publicKey,<br>        systemProgram: anchor.web3.SystemProgram.programId,<br>      },<br>      signers: [counter],<br>    });<br><br>    // Increment the counter<br>    await program.rpc.increment({<br>      accounts: {<br>        counter: counter.publicKey,<br>      },<br>    });<br><br>    // Fetch the account and check the value<br>    const account = await program.account.counter.fetch(counter.publicKey);<br>    assert.equal(account.count.toNumber(), 1);<br>  });<br>});</pre><p>Make sure Mocha is installed: npm i mocha</p><p>This code is semi-broken purposefully.</p><p>Run anchor test and the tests should pass for the first time, but if you run it again, it will show an error.</p><h4>Code Walkthrough</h4><pre>import * as anchor from &quot;@coral-xyz/anchor&quot;;<br>import { Program, web3 } from &quot;@coral-xyz/anchor&quot;;<br>import { Counter } from &quot;../target/types/counter&quot;;<br>import * as assert from &quot;assert&quot;;</pre><p>We import the necessary dependencies</p><pre>describe(&#39;counter&#39;, () =&gt; {<br> // …<br>});</pre><p>The describe block is a way to group related test cases together. In this case, we’re grouping all the tests related to the counter program.</p><pre>const provider = anchor.AnchorProvider.env()<br>anchor.setProvider(provider)<br>const program = anchor.workspace.counter as Program&lt;Counter&gt;</pre><p>Here, we set up the Anchor provider and the program instance:<br>- anchor.AnchorProvider.env() creates a provider using the environment configuration (e.g., the Solana cluster and wallet specified in the Anchor.toml file).<br>- anchor.setProvider(provider) sets the provider for the Anchor framework.<br>- anchor.workspace.counter retrieves the counter program from the Anchor workspace, and we cast it to the Program&lt;Counter&gt; type.</p><pre>it(&#39;Initializes the counter&#39;, async () =&gt; {<br> // …<br>});</pre><p>The it block defines an individual test case. This test case checks if the initialize function correctly initializes the counter.</p><pre>const [counterAccountPda, _] = web3.PublicKey.findProgramAddressSync(<br> [Buffer.from(&#39;counter&#39;), provider.wallet.publicKey.toBuffer()],<br> program.programId<br>);</pre><p>Here, we find the Program Derived Address (PDA) for the counter account using web3.PublicKey.findProgramAddressSync:<br>- We pass the seeds (string ‘counter’ and the provider’s wallet public key) and the program ID to generate the PDA.<br>- The PDA will be used to interact with the counter account.</p><p>If you look closely this PDA is the reason why our tests are broken.</p><p>Give yourself a few minutes and think why…</p><p>Remember every PDA is unique for the seeds being passed on, in our case the seeds are the string ‘counter’ and the user&#39;s public key. Given these inputs, the findProgramAddressSync function would generate the same public key every time it runs.</p><p>When we run our tests for the first time, there is a PDA generated, but when we run it again, the same PDA is generated which causes the conflict and the program fails.</p><p>Now in real-life situations, your dapp would interact with multiple wallets, so every time someone interacts with the program one of the seeds i.e. the wallet address would change. Generating a new PDA for every unique wallet.</p><p>As a dev, this provides a powerful tool to store user-specific information on-chain through PDAs. Changing the static string allows you to have multiple PDAs for a single-user wallet.</p><p>As homework, you can try changing the public key to make the tests work.</p><pre>const tx = await program.methods<br> .initialize(69)<br> .rpc()</pre><p>In this block, we call the initialize function of our program:<br>- program.methods.initialize(69) prepares the initialize method with the argument 69.<br>- .rpc() sends the transaction to the Solana cluster using RPC (Remote Procedure Call).</p><pre>const account = await program.account.counterAccount.fetch(counterAccountPda);<br>console.log(account.counter)<br>assert.ok(account.counter === 69);<br>console.log(&#39;Counter is initialized to&#39;, account.counter.toString());</pre><p>After initializing the counter, we fetch the counter account using program.account.counterAccount.fetch the counterAccountPda.<br>- We use assert.ok to check if the counter value is equal to 69, ensuring that the initialization was successful.</p><p>The second test case, Increments the counter, follows a similar structure:<br>- We find the PDA for the counter account.<br>- We call the increment method using program.methods.increment().rpc().<br>- We fetch the updated counter account and assert that the counter value has been incremented to 70.</p><p>I hope I have tickled your curiosity enough to explore Solana further.</p><p>Further, I have prepared a doc for you to get started on Solana: <a href="https://docs.google.com/document/d/1-8EUL-vxJw-0_pM6XtLZCk4WPTZrTcmcSea6cC2VnbQ/edit#heading=h.8k9e7o6fehdb">Everything about Solana</a></p><p>If you have any doubts, feel free to dm me on Twitter: <a href="https://twitter.com/daglihet">@daglihet</a></p><p>See you in Part 3…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52189b26e5c9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Solana from First Principles: Part 1]]></title>
            <link>https://medium.com/@het2341999/solana-from-first-principles-part-1-08525c7e1ccc?source=rss-389abb49c536------2</link>
            <guid isPermaLink="false">https://medium.com/p/08525c7e1ccc</guid>
            <category><![CDATA[solana-network]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Het Dagli]]></dc:creator>
            <pubDate>Thu, 18 Apr 2024 16:06:52 GMT</pubDate>
            <atom:updated>2024-05-08T10:17:15.151Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*D1vf_idUlWIar8gF.jpg" /></figure><p>Solana can seem intimidating at first glance, especially for developers new to the world of blockchain.</p><p>With its unique architecture, parallel transaction processing, and unfamiliar terminology, it’s easy to feel overwhelmed. But what if I told you that understanding Solana is simpler than you think? That by breaking it down to its core components and reasoning from first principles, the elegance and power of Solana becomes clear?</p><p>In this series, my aim is to guide you on a journey to develop strong mental models and intuition about Solana development. We’ll peel back the layers of complexity and discover that, at its heart, Solana shares many similarities with concepts you may already be familiar with, like databases.</p><p>You don’t need any prior knowledge of Solana, Rust, or other blockchains to follow along. All that’s required is an open mind, curiosity, and some programming experience in any domain.</p><p>Let’s get started…</p><h4>From Databases to Blockchains</h4><p>At its core, Solana can be thought of as a massive key-value database. If you’re familiar with traditional databases like Redis or MongoDB, you’re already halfway there!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QRToTp7SFWr_R2sP.png" /><figcaption>Key-Value on Solana(<a href="https://www.bonfida.org/blog/everything-is-a-domain">source</a>)</figcaption></figure><p>We as devs write code to manipulate this database, similar to how you would write queries to interact with a conventional database.</p><p>In Solana, we refer to the logic to manipulate this database as <strong><em>Programs</em></strong>. In other blockchains, this logic is referred to as <strong><em>Smart Contracts</em></strong>.</p><p>The main distinction between blockchains like Solana and normal databases lies in who controls the database.</p><p>In the <strong><em>Web2</em></strong> world, the owner of the database server has complete control over it. Take Facebook, for example, they have databases that store all user data, and they have full control over this data. Similarly, YouTube controls all the videos uploaded on its platform.</p><p>But in the world of blockchains, the database is community-owned. Instead of a single entity having control, it’s distributed among many individuals and organizations.</p><p>This is the main distinction between Web2 and <strong><em>Web3</em></strong>, in Web2 data is owned by the platform but in Web3 data is owned by the user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/0*yNgSO3hAEmRW96wK.png" /><figcaption>Web1 v/s Web2 v/s Web3</figcaption></figure><p>The obvious next question is…</p><h4>How does community ownership work practically?</h4><p>The control each participant has is determined by the <strong><em>private keys</em></strong> they hold.</p><p>This is where the concept of <strong><em>public</em></strong> and <strong><em>private </em></strong>key pairs comes into play.</p><p>Your public key is like your account number, and your private key is like your password. If you have the private key associated with certain data (like token balances), you control that data. You can think of it as having the password to your account in Solana.</p><p>The actual derivation method for creating a public-private keypair is a little bit complex but it would mostly be abstracted away through wallets for end users and through JS libraries for devs.</p><p>So in summary, as a developer, you’re still interacting with a database, but the ownership model is decentralized. You write Programs to define the rules for how the database can be updated, and users interact with these Programs using their public and private keys.</p><p>This decentralized control is one of the key innovations of blockchains. It enables trustless, permissionless interaction and eliminates the need for intermediaries. As a developer, understanding this model is crucial for designing effective Programs and building decentralized applications.</p><p>Now that we understand the role of public and private keys, let’s…</p><h4><strong>Get our Hands Dirty</strong></h4><p>We’ll put this knowledge into practice by creating a simple JavaScript project that interacts with Solana.</p><p>We’ll use the `@solana/web3.js` library to create a wallet, airdrop some SOL tokens, and then transfer those tokens to a different wallet.</p><p>Here is the Replit link for the code: <a href="https://replit.com/@HetDagli/UnwillingBarrenQuadrilateral#index.js">https://replit.com/@HetDagli/UnwillingBarrenQuadrilateral#index.js</a></p><p>Hit fork and run, you may get an ‘internal<em> </em>error<em>’, </em>this is due to Devnet RPC issues, if so, follow the next steps to run locally.</p><p>First, make sure you have Node.js installed. Then create a new directory for your project and initialize a new Node.js project:</p><pre><br>mkdir solana-wallet-example<br>cd solana-wallet-example<br>npm init -y</pre><p>Next, install the `@solana/web3.js` library:</p><pre>npm install @solana/web3.js</pre><p>Now, create a new file named `index.js` and add the following code:</p><pre><br>const {<br> Connection,<br> PublicKey,<br> Keypair,<br> LAMPORTS_PER_SOL,<br> Transaction,<br> sendAndConfirmTransaction,<br> SystemProgram,<br>} = require(&quot;@solana/web3.js&quot;);<br><br><br>// Connect to the Solana devnet<br>const connection = new Connection(&quot;https://api.devnet.solana.com&quot;);<br><br><br>// Create a new wallet keypair<br>const wallet = Keypair.generate();<br><br><br>// Get the public key (address) of the wallet<br>const publicKey = wallet.publicKey;<br>console.log(&quot;Public Key:&quot;, publicKey.toBase58());<br><br><br>// Request an airdrop of 1 SOL<br>(async () =&gt; {<br> const airdropSignature = await connection.requestAirdrop(<br> publicKey,<br> LAMPORTS_PER_SOL<br> );<br> await connection.confirmTransaction(airdropSignature);<br> console.log(&quot;Airdrop completed!&quot;);<br><br><br>// Check the balance of the wallet<br> const balance = await connection.getBalance(publicKey);<br> console.log(`Wallet balance: ${balance / LAMPORTS_PER_SOL} SOL`);<br><br><br>// Create a new wallet to transfer tokens to<br> const recipientWallet = Keypair.generate();<br> const recipientPublicKey = recipientWallet.publicKey;<br><br><br>// Transfer 0.5 SOL to the recipient wallet<br> const transaction = new Transaction().add(<br> SystemProgram.transfer({<br> fromPubkey: publicKey,<br> toPubkey: recipientPublicKey,<br> lamports: 0.5 * LAMPORTS_PER_SOL,<br> })<br> );<br><br><br>// Sign the transaction with the sender&#39;s private key<br> const signature = await sendAndConfirmTransaction(connection, transaction, [<br> wallet,<br> ]);<br> console.log(&quot;Transfer completed. Transaction signature:&quot;, signature);<br><br><br>// Check the balance of both wallets<br> const senderBalance = await connection.getBalance(publicKey);<br> const recipientBalance = await connection.getBalance(recipientPublicKey);<br> console.log(`Sender balance: ${senderBalance / LAMPORTS_PER_SOL} SOL`);<br> console.log(`Recipient balance: ${recipientBalance / LAMPORTS_PER_SOL} SOL`);<br>})();</pre><p>Run the logic using:</p><pre>node index.js</pre><p>Let’s break down the code:</p><p><strong>Creating a Wallet</strong></p><p>We created a new wallet keypair using the `Keypair.generate()` function provided by the `@solana/web3.js` library.</p><pre>// Create a new wallet keypair<br>const wallet = Keypair.generate();<br>// Get the public key (address) of the wallet<br>const publicKey = wallet.publicKey;<br>console.log(&quot;Public Key:&quot;, publicKey.toBase58());</pre><p>As we learned earlier, a keypair consists of a public key and a private key. The public key serves as the wallet’s address, which can be shared with others to receive SOL tokens. The private key would be later used to sign transactions and should be kept secret.</p><p><strong>Interacting with Solana Devnet RPC</strong></p><p>To interact with the Solana blockchain, we need to connect to a cluster. In this example, we connect to the Solana devnet, which is a test network that allows developers to experiment with Solana’s features without risking real funds.</p><pre>// Connect to the Solana devnet<br>const connection = new Connection(&quot;https://api.devnet.solana.com&quot;);</pre><p>The `Connection` object establishes a connection to the Solana devnet RPC (Remote Procedure Call) endpoint. RPC is a protocol that allows a program to request services from another program located on a different computer.</p><p><strong>Requesting an Airdrop</strong></p><p>To get some SOL tokens for testing purposes, we can request an airdrop from the Solana devnet faucet.</p><pre>// Request an airdrop of 1 SOL<br>const airdropSignature = await connection.requestAirdrop(<br> publicKey,<br> LAMPORTS_PER_SOL<br>);<br>await connection.confirmTransaction(airdropSignature);<br>console.log(&quot;Airdrop completed!&quot;);</pre><p>The `requestAirdrop` function sends a request to the Solana devnet to transfer 1 SOL (1 billion lamports) to our wallet’s public key. We then wait for the transaction to be confirmed using `confirmTransaction`.</p><p>SOL is the native token of the Solana blockchain, and it is used to pay for transaction fees and interact with Solana programs.</p><p>You can think of these steps as if we have added a new row in the Solana key-value database, the key is the account number and the value is the data which in our case is the 1 SOL that we airdropped.</p><p><strong>Transferring SOL Tokens</strong></p><p>To demonstrate transferring SOL tokens, we create another wallet keypair to serve as the recipient.</p><pre>// Create a new wallet to transfer tokens to<br>const recipientWallet = Keypair.generate();<br>const recipientPublicKey = recipientWallet.publicKey;</pre><p><strong>Using the System Program</strong></p><p>Solana provides a set of native programs like System Program out of the box, which allows us to perform basic operations like creating accounts and transferring tokens.</p><pre>// Transfer 0.5 SOL to the recipient wallet<br>const transaction = new Transaction().add(<br> SystemProgram.transfer({<br> fromPubkey: publicKey,<br> toPubkey: recipientPublicKey,<br> lamports: 0.5 * LAMPORTS_PER_SOL,<br> })<br>);</pre><p>Here, we create a new <strong><em>transaction</em></strong> and add an <strong><em>instruction</em></strong> to transfer 0.5 SOL from our wallet to the recipient wallet using the `<a href="https://docs.rs/solana-program/1.18.4/solana_program/system_instruction/fn.transfer.html">SystemProgram.transfer</a>` function.</p><p>An <strong><em>instruction </em></strong>is the most basic unit of operation in Solana. It specifies a single action to be performed, such as transferring tokens, interacting with a program, or modifying account data.</p><p>A <strong><em>transaction</em></strong> is a collection of one or more instructions that are executed atomically. If any of the instructions within a transaction fail, the entire transaction is rolled back as if no changes were made.</p><p>In our case, we are constructing a transaction with 1 transfer instruction.</p><p>The `SystemProgram.transfer` function is defined as follows:</p><pre>transfer(<br> from: PublicKey,<br> to: PublicKey, <br> amount: number | bigint, <br>): TransactionInstruction;</pre><p>It takes the source and destination public keys, along with the amount of lamports to transfer, and returns a `TransactionInstruction` object that can be added to a transaction.</p><p><strong>Signing and Sending the Transaction</strong></p><p>After creating the transaction, we need to sign it with our wallet’s private key to prove that we have the authority to transfer the tokens.</p><pre>// Sign the transaction with the sender&#39;s private key<br>const signature = await sendAndConfirmTransaction(connection, transaction, [<br> wallet,<br>]);<br>console.log(&quot;Transfer completed. Transaction signature:&quot;, signature);</pre><p>The `sendAndConfirmTransaction` function sends the signed transaction to the Solana cluster and waits for confirmation. It returns the transaction signature, which can be used to track the transaction on the blockchain.</p><p>The transaction signature can be searched on a block explorer like <a href="http://solscan.io/">solscan.io</a>, select devnet from the top right corner; the final <a href="https://solscan.io/tx/2bjyrjEgUHccFXaU8o8srC3BDGBjfKuCoULgdTbzChMhFKAne7e6e5pySUBmyVp9FMBARFMqZZ7c3kVXV9KtfcWc?cluster=devnet">transaction</a> would look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rxd03NCid2-wcFB0FgDS8g.png" /></figure><p>We have now covered the basic concepts of creating wallets, requesting airdrops, and transferring SOL tokens on Solana using JS. The `@solana/web3.js` library provides a convenient way to interact with the Solana blockchain, abstracting away many of the low-level details.</p><p>In <a href="https://medium.com/@het2341999/solana-from-first-principles-part-2-52189b26e5c9">Part 2</a>, we will deep dive into Solana Accounts, and PDAs and write our first-ever program on Solana.</p><p>You can also look at additional resources to learn about Solana <a href="https://docs.google.com/document/d/1-8EUL-vxJw-0_pM6XtLZCk4WPTZrTcmcSea6cC2VnbQ/edit#heading=h.8k9e7o6fehdb">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=08525c7e1ccc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An introduction to writing applications on Solana with Anchor and Seahorse lang.]]></title>
            <link>https://medium.com/@het2341999/an-introduction-to-writing-application-on-solana-with-anchor-and-seahorse-lang-289a9439e175?source=rss-389abb49c536------2</link>
            <guid isPermaLink="false">https://medium.com/p/289a9439e175</guid>
            <category><![CDATA[solana-network]]></category>
            <category><![CDATA[anchor]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Het Dagli]]></dc:creator>
            <pubDate>Mon, 19 Sep 2022 18:10:34 GMT</pubDate>
            <atom:updated>2022-09-20T07:54:51.464Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uPn7jmIuO2ZOX28xYc8JCQ.png" /></figure><p><em>Check out the original app by</em><a href="https://twitter.com/bfriel_"><em> bfriel</em></a><em> written in Rust live</em><a href="https://www.pbvote.com/"><em> here</em></a><em> and its code</em><a href="https://github.com/bfriel/crunchy-vs-smooth"><em> here</em></a><em>. In this tutorial we will try to recreate the program in Seahorse lang.</em></p><h3>Introduction</h3><p>Developing on Solana is notoriously difficult with a significant roadblock being learning Rust. Anchor framework abstracted away a lot of complexities involved in building on Solana, however, learning Rust still remains a barrier for new devs looking to explore the Solana ecosystem. Enter seahorse lang, a framework for developing Solana programs in python, built using Anchor.</p><p>This is a simple guide to build a Solana application using seahorse lang. This guide is perfect for new devs aiming to learn Solana development.</p><h3>Overview</h3><p>Every new technology should be used to solve humanity’s toughest problems. Hence we will use the Solana blockchain to build a program to find out which is the best flavour of peanut butter by letting users vote on their favourite flavour, crunchy or smooth.</p><h3>Prerequisites</h3><p>First let us install the command line tools required to build. We need<a href="https://docs.solana.com/cli/install-solana-cli-tools"> Solana</a>,<a href="https://project-serum.github.io/anchor/getting-started/installation.html#install-rust"> Anchor</a>,<a href="https://nodejs.org/en/"> NodeJS</a> and<a href="https://seahorse-lang.org/docs/installation"> Seahorse</a>. The links provided contain the step-by-step guide on installing these tools and the dependencies required for them like Rust.</p><p>Once done, you should be able to run the following commands successfully:</p><ul><li>solana -V</li><li>anchor -V</li><li>node -v</li><li>seahorse -V</li></ul><p>I am using:</p><ul><li>solana 1.9.2</li><li>anchor 0.25.0</li><li>node 16.8.0</li><li>seahorse 0.1.6</li></ul><h3>Getting started with Seahorse</h3><p>Now we can initialize the project using seahorse init:</p><p>seahorse init crunchy_vs_smooth</p><p>This will create multiple files, you may be familiar with the structure of the project if you have used anchor, seahorse just adds a new folder to write python programs, we will be writing our seahorse program here:</p><p>crunchy_vs_smooth/programs_py/crunchy_vs_smooth.py</p><p>We will write our tests in typescript here:</p><p>crunchy_vs_smooth/tests/crunchy_vs_smooth.ts</p><h3>A Brief Introduction to Solana’s account model</h3><p>Before starting out I want to talk a little bit about Solana’s unique way of storing and handling data on-chain which will further help us understand how Solana programs are structured, you can safely skip this part if you already know this.</p><p>Everything on the Solana blockchain is stored in an account. There are 3 types of accounts on Solana:</p><ul><li>Data accounts to store data.</li><li>Program accounts to store executable programs.</li><li>Native accounts that indicate native programs on Solana such as System, Stake, and Vote.</li></ul><p>Each account is mapped to an address(public key) and an owner(address of a program account).</p><p>In Solana programs state and the code live separately, programs do not store any data, while executing all the data should be passed on to them as an argument.</p><p>So to simplify, everything on Solana is stored on an account, and programs are stored in a special type of account which are marked as executable and do not store any data, for storing data we need to create another account which is owned by a program which can modify the data.</p><p>You can read more about Solana’s account model<a href="https://solanacookbook.com/core-concepts/accounts.html"> here</a>.</p><h3>PDAs and enforced uniqueness</h3><p>I will like to take a tangent here to explain the concept of PDAs(Program Derived Addresses) and one of its uses case in Solana programs. You can skip this if you already know.</p><p>Let us take an example, whenever you log in to FaceBook at the backend FB decides on your access level based on your credentials, basically, you can edit and view data of your own account but can only view not modify other users’ accounts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nMiiy__KtQT5CWIg" /><figcaption>Facebook enforced uniqueness</figcaption></figure><p>From Facebook’s perspective, they can logically separate the data stored in their database by mapping your credentials to a unique account space modifiable only by you.</p><p>Same way to store data on-chain we generate a unique public key without a corresponding private key based on some user input(often the owner’s public key), seeds and the owning program’s address. The generated unique address is called a PDA or Program Derived Address.</p><p>Essentially we are building hashmap-like structures mentioned below to store data on-chain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QGU7fg2kxPLDu5L3" /><figcaption>PDAs on Solana</figcaption></figure><p>Since these addresses do not have a private key no one can sign and modify the data stored in the corresponding account. However, the program owning that account can modify the data when it receives the right bump generated by valid seeds.</p><p>PDAs are generated using<a href="https://coral-xyz.github.io/anchor/ts/classes/web3.PublicKey.html#findProgramAddress"> findProgramAddress</a> method provided by Anchor, it takes in seeds(<em>Uint8Array</em> | <em>Buffer</em>) and programId(<em>PublicKey) </em>as input<em>. </em>This function iterates through various addresses until it finds one that when combined with the seeds generates a valid Public Key which does not lie on the ed25519 curve(not having a private key). Finally, it returns a PDA(<em>PublicKey) </em>and a bump<em>(number).</em></p><p>We will look into the process of generating PDAs when we write tests later. Apart from helping to store data on-chain, PDAs also allow programs to sign instructions. You can read more about PDAs<a href="https://book.anchor-lang.com/anchor_in_depth/PDAs.html"> here</a>.</p><h3>Writing our Seahorse program</h3><p>We are finally ready to write our program. First, let us go through the final program to get an intuitive understanding of the structure of a typical Solana program.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc417d72ca222132821bfa655a9627b8/href">https://medium.com/media/bc417d72ca222132821bfa655a9627b8/href</a></iframe><p>In anchor Rust programs you will often find two things separating the code in its logical form:</p><ol><li><em>#[program] </em>macro on a modifier which contains all the methods which are also called instructions, they contain all the logic and act as an RPC endpoint for clients to call.</li><li><em>#[account} </em>macro on structs which creates new accounts on-chain for us to store data.</li></ol><p>This structure more or less remains the same for every Anchor program.</p><p>In our Seahorse program, you will find the same logical separation between instruction methods and account classes inheriting from a parent Account.</p><p>For us init, vote_crunchy, and vote_smooth are the three instructions which act as an RPC endpoint for clients to call, we will use them when we write tests.</p><p>In the end, we define an account to store data VoteAccount for every user connecting to interact with our dapp we will create a new VoteAccount.</p><p>As a new user connects we will initialize his/her account on-chain by calling the init instruction.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8d8fbb0bfb017e6156ef8bb3fec2f65b/href">https://medium.com/media/8d8fbb0bfb017e6156ef8bb3fec2f65b/href</a></iframe><p>The init instruction takes in the owner who is the one paying for the account, along with the voter a PDA and the corresponding bump</p><p>The first line then creates a new VoteAccount account, verifying that the PDA passed in as voter is generated from the right seeds which in our case is the string “Voter” and the owner account. It also assigns the payer as the owner.</p><p>It then creates an empty VoteAccount assigning owner and bump as passed on and crunchy, smooth being initialized as 0. VoteAccount looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/adc0e18042ac6674665619ea028bed61/href">https://medium.com/media/adc0e18042ac6674665619ea028bed61/href</a></iframe><p>This account will be used to store unique user credentials and their voting state on-chain.</p><p>Finally, we create separate instructions to vote for your favourite peanut butter flavour.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cc576a18b673f817a57813c0c7b5f386/href">https://medium.com/media/cc576a18b673f817a57813c0c7b5f386/href</a></iframe><p>The above two instruction takes in owner and the vote PDA as input and verifies if the owner who called the instructions matches with the owner in the PDA account. Hence, it is important to call the init instruction before calling any of the voting instructions. If the VoteAccount is not initialized then the instruction will fail since VoteAccount.owner would be empty.</p><p>Finally, we can run seahorse build from the root of the project. If the command succeeds then boo-yaa we have successfully built our first Seahorse project.</p><h3>Deploying the program</h3><p>Once the program is built successfully. It will populate programs/crunchy_vs_smooth/src/lib.rs the anchor equivalent Rust program.</p><p>Next check if the solana configuration is set to localhost by running</p><p>solana config get</p><p>If it is not on localhost then set it like this:</p><p>solana config set — url localhost</p><p>Once done open a new terminal and run solana-test-validator this should start the solana validator on localhost. Airdrop yourself a few tokens to deploy the program locally: solana airdrop 1000</p><p>Now we are all set to deploy the program, run anchor deploy .</p><p>If the deployment is successful the second last line before deployment success will have your unique programId.</p><p>We need to modify the programId mentioned [programs.localnet] in anchor.toml and in the declare_id macro in both rust and python programs.</p><p>We are now ready to write the tests.</p><h3>Writing tests</h3><p>We have created three instructions hence we will write three tests for our program.</p><p>Before that, we need to initialize our accounts.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/55c578242c1e36ff6a17d78e49c465cf/href">https://medium.com/media/55c578242c1e36ff6a17d78e49c465cf/href</a></iframe><p>Anchor conveniently mocks a user wallet for us using anchor.AnchorProvider.env() we will use this as our provider wallet for testing.</p><p>Next, we import our program using anchor.workspace this is also relatively straightforward thanks to anchor.</p><p>The next step is important, here we find a PDA using the same seeds as mentioned in our program here in the init instruction:</p><p>init_voter = <em>voter</em>.init(<em>payer</em>=<em>owner</em>, <em>seeds</em>=[“Voter”, <em>owner</em>])</p><p>We use the “Voter” string with the owner as the public key of the provider wallet, along with the seeds array we also pass the programId. A combination of these inputs will give as the voter(PDA) and a bump used to find that address.</p><p>Now we move on to actual tests. First, we test the init instruction:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5529c02e6fa4490968defec617fe1fd4/href">https://medium.com/media/5529c02e6fa4490968defec617fe1fd4/href</a></iframe><p>Here we pass bump and the accounts required by the instruction.</p><p>def init(<em>owner</em>: Signer, <em>voter</em>: Empty[VoteAccount], <em>vote_account_bump</em>: u8):</p><p>bump would be the one we generated before while creating the PDA..</p><p>owner would be the provider wallet publickey.</p><p>voter account would be the PDA we generated before.</p><p>We also need to pass the systemProgram along with this.</p><p>On running .rpc() it will create a transaction for us on our localnet, calling the init instruction on our deployed program.</p><p>Once done we will check the state of our program by passing our PDA address voter to the voteAccount</p><p>Finally, we will assert that both crunchy and smooth is 0 in our voteAccount . Confirming the successful creation of our account.</p><p>Next, we will test vote_crunchy and vote_smooth instructions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9bdb48719b2b3d30220e664a4b1815c9/href">https://medium.com/media/9bdb48719b2b3d30220e664a4b1815c9/href</a></iframe><p>Both these instructions expect the owner publicKey and vote PDA account as input.</p><p>def vote_smooth(<em>owner</em>: Signer, <em>vote</em>: VoteAccount):</p><p>def vote_crunchy(<em>owner</em>: Signer, <em>vote</em>: VoteAccount):</p><p>We pass the owner and voter accounts initialized before and then fetch the state of the account same as before.</p><p>After the first instruction vote_smooth smooth should be incremented to 1 while crunchy should remain zero and after the second instruction vote_crunchy both crunchy and smooth should be 1.</p><p>Here is how the final test file should look like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/742c5ec249116646f9535ab6335104e5/href">https://medium.com/media/742c5ec249116646f9535ab6335104e5/href</a></iframe><p>Once done, run anchor test from the root and all 3 tests should pass.</p><blockquote>You may face some errors while running test, it is due to a #[derive(Debug)] above one of the structs in the rust program, please remove it and run anchor test again. Other warnings can be ignored.</blockquote><h3>Conclusion</h3><p>Seahorse vastly simplifies developing programs on Solana at the same time it acts as a gateway for python programmers to get familiar with Rust programs as Seahorse automatically generated the Anchor Rust program for you.</p><p>Original code can be found out <a href="https://github.com/hetdagli234/crunch-vs-smooth">here</a>. If you have any queries feel free to reach out on my<a href="https://twitter.com/daglihet"> Twitter</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=289a9439e175" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Designing a trading algorithm]]></title>
            <link>https://medium.com/@het2341999/designing-a-trading-algorithm-fedf73d7835c?source=rss-389abb49c536------2</link>
            <guid isPermaLink="false">https://medium.com/p/fedf73d7835c</guid>
            <dc:creator><![CDATA[Het Dagli]]></dc:creator>
            <pubDate>Fri, 01 Nov 2019 10:00:14 GMT</pubDate>
            <atom:updated>2019-11-01T10:00:14.932Z</atom:updated>
            <content:encoded><![CDATA[<p>It is assumed that trading in markets like Nifty, Sensex, etc, is carried out by individuals(human beings) with knowledge and required qualification. But with the advent of computers things have changed drastically.</p><p>Algorithmic trading is automated trading by computers that are programmed to take certain actions in response to varying market data.</p><p>Every day my algorithm will produce a trade sheet to decide on the stocks to buy and sell on that particular trading day. The trading strategy will generate the trade sheet based on the algorithm coded in python.</p><p>Each and every individual at some point in time will start earning money. The question of what to do with extra money i.e savings will surely come to their mind. Many will go for a fixed deposit or mutual fund etc. But the returns given by the above methods are not attractive enough and also the fact remains that in the above methods you are not in control of your own money. Algorithm trading may be a solution to the above problem. It is a better way to handle the savings and also more profitable if done right with extensive research.</p><p>Algorithm trading is generally done by HFTs and hedge funds. There are very few retail investors who do it.</p><p>Most of the algorithms which are open source are not profitable enough to invest upon. If I am able to minimize risk and maximize profit then I can open-source my algorithm for further improvement.</p><p>Even if I am not able to complete and test my algorithm in a given time period, the insights generated by me by analyzing historical data may prove to be valuable. It is difficult to innovate in this field as it requires a combination of logical decision making with a little bit of luck as part of the trial and error method. I need to generate multiple hypotheses based on a mathematical or a statistical model and work upon to prove my hypothesis right or wrong. Based on the results of the hypothesis testing I will make an informed decision of whether to use the given hypothesis in my algorithm.</p><p>I divide my approach into two phases:</p><ol><li>Researching and applying various machine learning models:</li></ol><p>The first model I applied was the LSTM model on Nifty data. Firstly, I started out by importing all the libraries and also the data in an IPython notebook. The data used was nifty data from the year 1997 to 2019. The format of the data was OHCLV. The frequency of the data was daily. The next thing I did was to divide the data into train and test data and perform scaling to make all the values between 0 to 1.Next is just running the model and getting the results. I used matplotlib to visualize the predictions. Here is the result of the LSTM model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OJiPvvVcrmRXzhpVoxa_1w.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nLE_taK7obW3EuYbFXPzzQ.jpeg" /></figure><p>The second model I applied was the HMM model to detect a regime change. The main hypothesis is that the hidden state of the hidden Markov model will change its state whenever regime change is detected.</p><p>The process started in a similar way as the previous model, where I imported the data. The data used was again the Nifty index’s day to day price.</p><p>I used different input variables to get better results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kzqeEYh2-XRY9hZlmcu6oA.png" /></figure><p>Finally, I used the previous two models to construct a trading algorithm.</p><p>2. Constructing a trading algorithm</p><p>Pseudocode for the trading algorithm:</p><p>The function which carries out transaction:</p><p>Transaction_on_market_data(tick1,tick2)</p><p>{</p><p>buy_price=tick2.bid-s</p><p>If buy_signal is True</p><p>Replace it to buy_price</p><p>else</p><p>send another order at the buy_price</p><p>sell_price=ticks2.ask+s</p><p>if sell_order is True</p><p>replace it to sell_price</p><p>else</p><p>send new order at sellPrice</p><p>}</p><p>afterexecution</p><p>{</p><p>if buy execution happened in instr1</p><p>send sell order on instr2</p><p>else if sell execution happened on instr1</p><p>send buy order in instr2</p><p>}</p><p>The remaining work in the project is to take the algorithm live.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fedf73d7835c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>