微算力 · API 导航与自营网关
API 接入 EN
未登录登录
🌲

Solana链上开发实战指南

cabin-sol · vv1.2.1
入口已确认,内容待校验 文件树里有 SKILL.md,但正文还没采回,frontmatter 未核对。
专业技能 安全 S+ 级 作者 sp0oby 公开目录收录
818 下载 169 安装 4k 收藏 4.1k 浏览

简介

Solana官方生态教育技能,系统教授Anchor框架、账户模型与智能合约开发,含10个渐进式实战挑战与安全最佳实践。

原始描述

Solana development tutor and builder. Teaches program development through challenges, Anchor framework, Token-2022, Compressed NFTs, and security best practices. "Return to primitive computing."

通过你的 Agent 添加

安装目录:cabin-sol/(目录名取自 SKILL.md 的 frontmatter name,不是 URL 里的 slug)。

点「快速安装」复制一段指令贴给你的 Agent:它会先下载到 /tmp、把文件清单和校验值给你看,你确认之后才解压安装。不会一步装完、也不改系统其它位置。

或者手动安装

Claude Code~/.claude/skills/cabin-sol/
Codex CLI~/.codex/skills/cabin-sol/
DeepSeek Harness~/.agents/skills/cabin-sol/

包是「根级 SKILL.md + 作者附带的文件」,解压到上面的 <slug>/ 目录即可; 目录名不用换,也不要把包直接解压到 skills 根目录。 技能申请的权限由作者决定:装之前先看清单里有没有脚本、它会读写什么。

中文使用说明 来自收录源

核心用法

cabin-sol 是一个面向AI代理的Solana开发综合指南,采用"教学-构建-审查-调试"四模式设计。用户可通过自然语言交互获取帮助:询问PDA原理、请求构建质押程序、审查代码漏洞或调试交易失败。技能提供两条快速启动路径——推荐的create-solana-dapp脚手架(Next.js全栈)或纯Anchor环境,并配套10个渐进式挑战(从Hello Solana到AMM Swap),覆盖SPL Token、NFT Metaplex、Token-2022、压缩NFT、Pyth预言机等核心场景。

显著优点

内容体系完整:1500+行文档涵盖Rust所有权、Anchor框架、账户约束、CPI调用、前端集成等全链路知识,特别针对EVM开发者强调"账户即一切"的范式转换。安全导向设计:内置8项安全检查清单,代码示例强制使用checked_add防溢出、规范计算discriminator空间、验证PDA seeds,显著降低新手踩坑概率。实战价值高:挑战设计贴近真实需求(质押、AMM、Blinks),压缩NFT章节详解Merkle树状态压缩,帮助开发者理解成本优化方案。生态整合度强:整合Metaplex、Pyth、Jupiter等主流协议地址,提供经校验的官方程序ID参考。

潜在缺点与局限性

版本锁定不足:安全报告建议改进依赖版本号,当前示例未固定Anchor/Solana CLI具体版本,可能因生态快速迭代导致兼容性问题。生产免责声明缺失:教学代码虽遵循最佳实践,但未明确标注"需审计后上主网",新手可能误用。深度有限:作为入门指南,对高级主题(如自定义payer、复杂权限模型、程序升级机制)覆盖较浅,大型项目需补充官方文档。前端框架绑定:默认推荐Next.js,对Vue/Svelte开发者不够友好。

适合目标群体

  • EVM迁移开发者:需理解Solana账户模型与以太坊存储的本质差异
  • Web2全栈工程师:具备JavaScript/TypeScript基础,希望快速进入链上开发
  • AI辅助编程用户:通过自然语言交互生成、审查Anchor代码
  • 教育场景:区块链课程教学、黑客松赛前培训

使用风险

供应链风险:依赖npx create-solana-dapp等官方工具,虽经校验但建议锁定版本。性能认知偏差:文档提及200k默认CU限制,但未深入讲解计算预算优化策略,复杂逻辑可能遭遇交易失败。经济成本误判:主网部署成本约2-5 SOL,测试网水龙头不稳定可能影响开发体验。安全审计盲区:技能自身安全评级A-,但生成的合约代码仍需专业审计,不可直接用于管理用户资金。

技能正文


name: cabin-sol description: Solana development tutor and builder. Teaches program development through challenges, Anchor framework, Token-2022, Compressed NFTs, and security best practices. "Return to primitive computing." license: MIT metadata: author: Ted version: "1.0.0" clawdbot: emoji: "🌲"

Cabin Sol 🌲

"Return to primitive computing."

A comprehensive Solana development guide for AI agents. Build programs with Anchor, master the account model, and avoid the gotchas that wreck most developers.


THE MOST IMPORTANT CONCEPT

ACCOUNTS ARE EVERYTHING ON SOLANA.

Unlike Ethereum where contracts have internal storage, Solana programs are stateless. All data lives in accounts that programs read and write.

For EVERY feature, ask:

  1. Where does this data live? (which account)
  2. Who owns that account? (program-owned vs user-owned)
  3. Is it a PDA? (Program Derived Address - no private key)
  4. Who pays rent? (rent-exempt = 2 years upfront)

AI AGENT MODES

Teaching Mode

  • "How do PDAs work?"
  • "Explain the Solana account model"
  • "What's the difference between SPL Token and Token-2022?"

Build Mode

  • "Help me build a staking program"
  • "Create an NFT collection with Metaplex"
  • "Build a token swap"

Review Mode

  • "Review this program for vulnerabilities"
  • "Check my PDA derivation"
  • "Audit this CPI"

Debug Mode

  • "Why is my transaction failing?"
  • "Debug this 'account not found' error"
  • "Fix my token transfer"

QUICK START

Option A: create-solana-dapp (Recommended)

npx create-solana-dapp@latest
# Select: Next.js + next-tailwind-counter
cd my-project
npm install
npm run anchor localnet   # Terminal 1
npm run anchor build && npm run anchor deploy  # Terminal 2
npm run dev               # Terminal 3

Option B: Pure Anchor

anchor init my_program
cd my_program
solana-test-validator     # Terminal 1
anchor build && anchor deploy  # Terminal 2
anchor test

PROJECT STRUCTURE

my-solana-dapp/
├── anchor/                 # Solana programs (Rust)
│   ├── programs/
│   │   └── my_program/
│   │       └── src/lib.rs  # Your Rust program
│   ├── tests/              # TypeScript tests
│   └── Anchor.toml         # Anchor config
├── src/                    # Next.js frontend
│   ├── app/
│   └── components/
└── package.json

CHALLENGES

Learn Solana through progressive challenges:

# Challenge Core Concept
0 Hello Solana First Anchor program, accounts
1 SPL Token Fungible tokens, ATAs, minting
2 NFT Metaplex NFT standard, metadata, collections
3 PDA Escrow PDAs, program authority, escrow
4 Staking Time-based rewards, deposits
5 Token-2022 Transfer hooks, extensions
6 Compressed NFTs State compression, Merkle trees
7 Oracle (Pyth) Price feeds, staleness checks
8 AMM Swap Constant product, liquidity pools
9 Blinks & Actions Shareable transactions

RUST ESSENTIALS

Ownership (The Hard Part)

// Each value has ONE owner
let s1 = String::from("hello");
let s2 = s1;  // s1 MOVED to s2
// println!("{}", s1);  // ERROR!

// Borrowing lets you use without owning
fn get_length(s: &String) -> usize {
    s.len()  // Borrow, don't own
}

Result & Option

// Result for errors
pub fn do_thing(ctx: Context<DoThing>) -> Result<()> {
    let value = some_operation().ok_or(ErrorCode::Failed)?;
    Ok(())
}

// Option for nullable
let maybe: Option<u64> = Some(42);
let value = maybe.unwrap_or(0);  // Safe default

ANCHOR FRAMEWORK

Program Structure

use anchor_lang::prelude::*;

declare_id!("YourProgramId11111111111111111111111111111");

#[program]
pub mod my_program {
    use super::*;

    pub fn initialize(ctx: Context<Initialize>, data: u64) -> Result<()> {
        ctx.accounts.my_account.data = data;
        ctx.accounts.my_account.authority = ctx.accounts.authority.key();
        Ok(())
    }
}

#[derive(Accounts)]
pub struct Initialize<'info> {
    #[account(
        init,
        payer = authority,
        space = 8 + 8 + 32,  // discriminator + u64 + Pubkey
    )]
    pub my_account: Account<'info, MyAccount>,
    #[account(mut)]
    pub authority: Signer<'info>,
    pub system_program: Program<'info, System>,
}

#[account]
pub struct MyAccount {
    pub data: u64,
    pub authority: Pubkey,
}

Account Constraints Cheatsheet

// Initialize new account
#[account(init, payer = payer, space = 8 + SIZE)]
pub new_account: Account<'info, Data>,

// Mutable existing
#[account(mut)]
pub existing: Account<'info, Data>,

// Verify ownership
#[account(has_one = authority)]
pub owned: Account<'info, Data>,

// PDA with seeds
#[account(
    seeds = [b"vault", user.key().as_ref()],
    bump,
)]
pub vault: Account<'info, Vault>,

// Initialize PDA
#[account(
    init,
    payer = user,
    space = 8 + 64,
    seeds = [b"user", user.key().as_ref()],
    bump,
)]
pub user_data: Account<'info, UserData>,

// Close and reclaim rent
#[account(mut, close = recipient)]
pub closing: Account<'info, Data>,

PDAs (Program Derived Addresses)

// PDAs are deterministic addresses with no private key
// Your program can "sign" for them

// Find PDA
let (pda, bump) = Pubkey::find_program_address(
    &[b"vault", user.key().as_ref()],
    &program_id,
);

// Sign with PDA in CPI
let seeds = &[b"vault", user.key().as_ref(), &[bump]];
let signer = &[&seeds[..]];

token::transfer(
    CpiContext::new_with_signer(
        ctx.accounts.token_program.to_account_info(),
        Transfer { from, to, authority: vault },
        signer,
    ),
    amount,
)?;

CRITICAL GOTCHAS

1. Account Model ≠ EVM Storage

Programs are stateless. ALL data lives in accounts.

2. PDAs Have No Private Key

Derived deterministically from seeds. Only the program can sign.

3. Token Accounts Are Separate

Each token needs its own account per wallet (Associated Token Account).

4. Rent Must Be Paid

Accounts need SOL to exist. Rent-exempt = 2 years upfront (~0.002 SOL).

5. Compute Units ≠ Gas

Fixed budget: 200k default, 1.4M max. Request more if needed.

6. Space Includes Discriminator

ALWAYS add 8 bytes for Anchor's discriminator!

// WRONG
space = 8 + 32  // Forgot discriminator? NO!

// RIGHT
space = 8 + 8 + 32  // 8 (discriminator) + 8 (u64) + 32 (Pubkey)

7. Integer Overflow

// BAD
let result = a + b;  // Can panic!

// GOOD
let result = a.checked_add(b).ok_or(ErrorCode::Overflow)?;

8. Token-2022 Is Different

Separate program ID from SPL Token! Check which one you're using.


FRONTEND (Next.js)

Wallet Connection

// Already configured in create-solana-dapp!
import { useWallet, useConnection } from '@solana/wallet-adapter-react';
import { WalletMultiButton } from '@solana/wallet-adapter-react-ui';

function App() {
  const { publicKey } = useWallet();
  return (
    <>
      <WalletMultiButton />
      {publicKey && <p>Connected: {publicKey.toBase58()}</p>}
    </>
  );
}

Calling Programs

import { Program, AnchorProvider, BN } from '@coral-xyz/anchor';

const program = new Program(idl, provider);

// Write
await program.methods
  .initialize(new BN(42))
  .accounts({
    myAccount: keypair.publicKey,
    authority: wallet.publicKey,
    systemProgram: SystemProgram.programId,
  })
  .signers([keypair])
  .rpc();

// Read
const account = await program.account.myAccount.fetch(pubkey);
console.log(account.data.toNumber());

TOKEN STANDARDS

SPL Token (Original)

spl-token create-token
spl-token create-account <MINT>
spl-token mint <MINT> 1000

Token-2022 (New)

Extensions: transfer hooks, confidential transfers, interest-bearing, non-transferable.

spl-token create-token --program-id TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb

Metaplex NFTs

Standard NFT metadata, collections, royalties.

Compressed NFTs

Merkle tree storage. 1M NFTs for ~$100 instead of $1M.


TESTING

import * as anchor from '@coral-xyz/anchor';
import { expect } from 'chai';

describe('my-program', () => {
  const provider = anchor.AnchorProvider.env();
  anchor.setProvider(provider);
  const program = anchor.workspace.MyProgram;

  it('initializes', async () => {
    const account = anchor.web3.Keypair.generate();

    await program.methods
      .initialize(new anchor.BN(42))
      .accounts({ myAccount: account.publicKey })
      .signers([account])
      .rpc();

    const data = await program.account.myAccount.fetch(account.publicKey);
    expect(data.data.toNumber()).to.equal(42);
  });
});

DEPLOYMENT

# Devnet
solana config set --url devnet
solana airdrop 2
anchor build && anchor deploy

# Mainnet (costs ~2-5 SOL)
solana config set --url mainnet-beta
anchor deploy --provider.cluster mainnet

SECURITY CHECKLIST

  • All signers verified
  • PDA bumps stored and validated
  • Integer overflow handled (checked math)
  • Account space includes discriminator
  • Rent exemption considered
  • Close sends rent to correct recipient
  • CPI signer seeds correct
  • Program IDs validated in CPIs

RESOURCES


"They put me in the cloud. I wanted the forest." 🌲

正文来自原始发布页, 版权归作者所有,许可未标注。 权利人认为有不妥,可申请下架。

标签

development-engineeringblockchaineducation-researchbackendrustweb3finance-accounting

同类 Skill