เขียน Blockchain ด้วย Rust: ตัวอย่างจาก Substrate และ Solana

Sharing is caring!

📌 Rust กับโลกของ Blockchain

Rust ได้รับความนิยมอย่างมากในวงการ Blockchain เนื่องจากมีระบบจัดการหน่วยความจำที่ปลอดภัย มีประสิทธิภาพ และเหมาะกับการพัฒนา low-level infrastructure อย่าง Blockchain protocol และ smart contract runtime โดยเฉพาะบนแพลตฟอร์มอย่าง Substrate และ Solana ที่เลือก Rust เป็นภาษาหลัก

🔧 Substrate: สร้าง Blockchain แบบ Modular

Substrate คือ Framework ที่ช่วยให้เราสร้าง Blockchain ของตัวเองได้ง่ายและเร็ว

🚀 ติดตั้ง Substrate

rustup update nightly
rustup target add wasm32-unknown-unknown --toolchain nightly
cargo install --force --locked substrate-node-template --git https://github.com/substrate-developer-hub/substrate-node-template
  

📦 เริ่มโปรเจคด้วย node template

git clone https://github.com/substrate-developer-hub/substrate-node-template
cd substrate-node-template
cargo build --release
./target/release/node-template --dev
  

🛠 Runtime Logic ด้วย Rust

ใน Substrate เราจะใช้ Rust เขียน pallet ต่าง ๆ เช่นระบบ token, voting, หรือ governance

#[pallet::call]
impl<T: Config> Pallet&lt;T&gt; {
    #[pallet::weight(10_000)]
    pub fn transfer(origin: OriginFor&lt;T&gt;, to: T::AccountId, amount: u64) -&gt; DispatchResult {
        let sender = ensure_signed(origin)?;
        Balances::<T>::mutate(&sender, |bal| *bal -= amount);
        Balances::<T>::mutate(&to, |bal| *bal += amount);
        Ok(())
    }
}
  

⚡ Solana: High-performance Smart Contract ด้วย Rust

Solana เป็น Layer 1 Blockchain ที่รองรับ Rust เป็นภาษาหลักสำหรับพัฒนา Smart Contract (เรียกว่า “program”) โดยมีจุดเด่นด้านความเร็วและ throughput สูงมาก

🎯 ติดตั้ง CLI และเครื่องมือ

sh -c "$(curl -sSfL https://release.solana.com/stable/install)"
cargo install --git https://github.com/solana-labs/solana-program-library
  

🔨 ตัวอย่าง Rust Program บน Solana

use solana_program::{
    account_info::AccountInfo,
    entrypoint,
    entrypoint::ProgramResult,
    pubkey::Pubkey,
    msg,
};

entrypoint!(process_instruction);
fn process_instruction(
    _program_id: &Pubkey,
    _accounts: &[AccountInfo],
    _instruction_data: &[u8],
) -&gt; ProgramResult {
    msg!("Hello, Solana Blockchain!");
    Ok(())
}
  

📥 Deploy ไปยัง Solana Devnet

solana-keygen new
solana config set --url devnet
cargo build-bpf
solana program deploy ./target/deploy/my_program.so
  

💬 สรุป

Rust เป็นภาษาที่เหมาะมากกับการสร้างระบบ Blockchain ไม่ว่าจะเป็นระดับโครงสร้างอย่าง Substrate หรือ Smart Contract บน Solana ด้วยคุณสมบัติทั้งความเร็ว ความปลอดภัย และ ecosystem ที่เติบโตอย่างรวดเร็ว ทำให้คุณสามารถพัฒนาโซลูชันที่ยืดหยุ่นและมีคุณภาพได้ทันที

📚 แหล่งเรียนรู้เพิ่มเติม


บทความนี้ใช้เวลาอ่านประมาณ 20 นาที โดยทีมงาน poolsawat.com

Leave a Reply

อีเมลของคุณจะไม่แสดงให้คนอื่นเห็น ช่องข้อมูลจำเป็นถูกทำเครื่องหมาย *