Cabin Sol:精通 Solana 开发与 Anchor 框架 - Openclaw Skills

作者:互联网

2026-03-23

AI教程

什么是 Cabin Sol?

Cabin Sol 是一项专门的技能,旨在将 AI 代理转变为专家级的 Solana 开发者。它强调原始计算哲学,引导用户了解 Solana 账户模型、程序派生地址 (PDA) 和 Anchor 框架的复杂性。通过提供结构化的心智模型和开发模式,它确保开发者避免常见的陷阱,如账户所有权错误和租金豁免问题。此 Openclaw Skills 资源充当了高级逻辑与底层区块链机制之间的技术桥梁。

该技能建立在“账户在 Solana 上就是一切”的原则之上。与合同具有内部存储的其他区块链不同,Solana 程序是无状态的,需要深入了解数据的存储和所有权方式。该技能通过引导式构建和严格的安全审计,使开发者能够掌握这些概念。

下载入口:https://github.com/openclaw/skills/tree/main/skills/sp0oby/cabin-sol

安装与下载

1. ClawHub CLI

从源直接安装技能的最快方式。

npx clawhub@latest install cabin-sol

2. 手动安装

将技能文件夹复制到以下位置之一

全局模式 ~/.openclaw/skills/ 工作区 /skills/

优先级:工作区 > 本地 > 内置

3. 提示词安装

将此提示词复制到 OpenClaw 即可自动安装。

请帮我使用 Clawhub 安装 cabin-sol。如果尚未安装 Clawhub,请先安装(npm i -g clawhub)。

Cabin Sol 应用场景

  • 教导 AI 代理向新开发者解释 Solana 账户模型和无状态程序架构。
  • 使用 Anchor 框架构建稳健的质押程序、NFT 集合和 AMM 交换。
  • 审查基于 Rust 的程序的安全漏洞,如整数溢出和错误的 PDA 派生。
  • 在本地或测试网环境中调试复杂的交易失败和账户未找到错误。
Cabin Sol 工作原理
  1. 使用推荐的模板(如 create-solana-dapp 或 Anchor CLI)初始化开发环境。
  2. 在 Rust 中定义程序逻辑,利用 #[program] 宏来管理指令。
  3. 通过指定数据类型、所有者和空间要求(包括 8 字节鉴别器)来构建账户结构。
  4. 派生确定性的程序派生地址 (PDA),以便在没有私钥的情况下处理程序权限和状态管理。
  5. 实现 Next.js 前端,使用 Solana 浅包适配器和 RPC 提供商与部署的程序进行交互。
  6. 执行安全检查表,在部署前验证签名者、验证 bump 并确保整数安全。

Cabin Sol 配置指南

要开始在 Openclaw Skills 生态系统中使用此技能,请遵循以下安装步骤:

npx create-solana-dapp@latest
# 选择:Next.js + next-tailwind-counter
cd my-project
npm install
npm run anchor localnet

对于独立的 Anchor 项目:

anchor init my_program
cd my_program
solana-test-validator
anchor build && anchor deploy

Cabin Sol 数据架构与分类体系

该技能使用标准化的目录结构组织 Solana 项目,将区块链逻辑与前端界面分离:

组件 路径 描述
Rust 程序 anchor/programs/*/src/lib.rs 核心无状态逻辑和账户定义。
TypeScript 测试 anchor/tests/ 使用 Mocha/Chai 的集成测试,用于验证程序 RPC。
配置 anchor/Anchor.toml 定义程序 ID、集群 URL 和工作区设置。
前端 src/app/ 用于浅包连接和 UI 的 Next.js 应用逻辑。
元数据 package.json 管理 Anchor 工作区和前端的依赖项。
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

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) -> Result<()> {
    let value = some_operation().ok_or(ErrorCode::Failed)?;
    Ok(())
}

// Option for nullable
let maybe: Option = 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, 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 (
    <>
      
      {publicKey && 

Connected: {publicKey.toBase58()}

} ); }

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 
spl-token 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

  • Anchor Book
  • Solana Cookbook
  • Solana Docs
  • Metaplex Docs
  • Solana Playground

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