Skip to content

Latest commit

 

History

History
261 lines (209 loc) · 8.82 KB

File metadata and controls

261 lines (209 loc) · 8.82 KB

CLAUDE.md - AI Assistant Guide for ckb-script-app

This file provides guidance for AI assistants (Claude, GPT, Copilot, etc.) to help users work with this CKB JavaScript smart contract template.

Project Overview

ckb-script-app is a boilerplate for building smart contracts on the CKB (Nervos Common Knowledge Base) blockchain using TypeScript/JavaScript. It uses ckb-js-vm - a JavaScript virtual machine that runs on CKB.

Key Concept: ckb-js-vm

Unlike Ethereum where smart contracts are written in Solidity, CKB allows smart contracts in any language that compiles to RISC-V. The ckb-js-vm is a QuickJS-based JavaScript runtime compiled to RISC-V, enabling developers to write contracts in TypeScript/JavaScript.

Project Structure

ckb-script-app/
├── contracts/              # Smart contract source code (TypeScript)
│   └── <contract-name>/
│       └── src/
│           └── index.ts    # Contract entry point
├── tests/                  # Jest tests for contracts
│   ├── *.mock.test.ts      # Mock tests (no network, uses ckb-testtool)
│   ├── *.devnet.test.ts    # Devnet tests (requires local node)
│   └── helper.ts           # Test utilities
├── scripts/                # Build tooling
│   ├── build-all.js        # Build all contracts
│   ├── build-contract.js   # Build single contract
│   ├── add-contract.js     # Scaffold new contract
│   └── deploy.js           # Deploy to CKB networks
├── dist/                   # Build output (generated)
│   ├── <name>.js           # Bundled JavaScript
│   └── <name>.bc           # Compiled bytecode for CKB
├── deployment/             # Deployment artifacts
│   ├── scripts.json        # Deployed contract info
│   └── system-scripts.json # CKB system scripts info
├── app/                    # Next.js frontend (optional)
│   ├── app/                # App router pages
│   ├── components/         # React components
│   └── utils/              # CKB client utilities
├── .skills/                # AI skill patterns (Agent Skills format)
│   ├── ckb-contract-patterns/  # Contract writing patterns
│   └── ckb-ccc-frontend/       # Frontend integration patterns
└── Configuration files...

Essential Commands

Task Command
Install dependencies pnpm install
Build all contracts pnpm run build
Build one contract pnpm run build:contract <name>
Run all tests pnpm test
Add new contract pnpm run add-contract <name>
Deploy to devnet pnpm run deploy
Deploy to testnet pnpm run deploy -- --network testnet
Start frontend cd app && pnpm dev

Writing Smart Contracts

Contract Template Structure

Every contract must export a main() function that returns an exit code (0 = success):

import * as bindings from '@ckb-js-std/bindings';
import { Script, HighLevel, log } from '@ckb-js-std/core';

function main(): number {
  log.setLevel(log.LogLevel.Debug);
  
  // Load current script info
  let script = bindings.loadScript();
  log.debug(`Script loaded: ${JSON.stringify(script)}`);
  
  // Your validation logic here
  // Return 0 for success, non-zero for failure
  
  return 0;
}

bindings.exit(main());

Available APIs (@ckb-js-std/bindings)

  • loadScript() - Get current script info
  • loadCell(index, source) - Load cell data
  • loadCellData(index, source) - Load cell data field
  • loadInput(index, source) - Load input
  • loadWitness(index, source) - Load witness
  • loadHeader(index, source) - Load header
  • exit(code) - Exit with code

Cell Sources

  • SOURCE_INPUT (1) - Input cells
  • SOURCE_OUTPUT (2) - Output cells
  • SOURCE_CELL_DEP (3) - Cell dependencies
  • SOURCE_GROUP_INPUT (0x0100000001) - Input cells in same group
  • SOURCE_GROUP_OUTPUT (0x0100000002) - Output cells in same group

Testing Contracts

Mock Tests (Recommended for Development)

Uses ckb-testtool to simulate CKB environment without a real node:

import { Resource, Verifier, DEFAULT_SCRIPT_CKB_JS_VM } from 'ckb-testtool';

describe('my-contract', () => {
  test('should work', async () => {
    const resource = Resource.default();
    const tx = Transaction.default();
    
    // Deploy scripts and set up transaction
    const mainScript = resource.deployCell(hexFrom(readFileSync(DEFAULT_SCRIPT_CKB_JS_VM)), tx, false);
    // ... setup cells and verify
    
    const verifier = Verifier.from(resource, tx);
    await verifier.verifySuccess(true);
  });
});

Devnet Tests (Integration Testing)

Requires running local devnet via offckb:

offckb node  # Start local devnet
pnpm test -- devnet  # Run devnet tests

Deployment

Networks

  • devnet: Local development (default, via offckb)
  • testnet: Public test network
  • mainnet: Production network

Deploy Command Options

pnpm run deploy -- --network <network> [--type-id] [--privkey 0x...]
  • --type-id: Enable upgradable contracts via Type ID pattern
  • --privkey: Custom private key (defaults to offckb deployer)

Deployment Output

After deployment, deployment/scripts.json contains:

{
  "devnet": {
    "hello-world.bc": {
      "codeHash": "0x...",
      "hashType": "type",
      "cellDeps": [...]
    }
  }
}

Frontend Integration (app/)

The Next.js app uses CCC (Common Chain Connector) for wallet integration:

Key Files

  • app/utils/ckbClient.ts - CKB client setup
  • app/utils/contract.ts - Contract interaction helpers
  • app/components/ConnectWallet.tsx - Wallet connection UI

Using Deployed Contracts in Frontend

import scripts from "@/deployment/scripts.json";
import systemScripts from "@/deployment/system-scripts.json";

// Build script args for ckb-js-vm
const mainScript = {
  codeHash: systemScripts.devnet["ckb_js_vm"].script.codeHash,
  hashType: systemScripts.devnet["ckb_js_vm"].script.hashType,
  args: hexFrom(
    "0x0000" +
    scripts.devnet["hello-world.bc"].codeHash.slice(2) +
    hashTypeToBytes(scripts.devnet["hello-world.bc"].hashType).slice(2) +
    "your_custom_args"
  ),
};

Common Tasks for AI Assistants

1. Create a New Contract

pnpm run add-contract token-transfer

Then implement logic in contracts/token-transfer/src/index.ts

2. Add Contract Validation Logic

Common patterns:

  • Type Script: Validates cell creation/destruction rules
  • Lock Script: Validates who can spend a cell

3. Integrate Contract with Frontend

  1. Deploy contract: pnpm run deploy -- --network devnet
  2. Import in frontend: import scripts from "@/deployment/scripts.json"
  3. Build transaction using CCC library

4. Debug Contract

pnpm run build:debug           # Build with debug symbols
pnpm run deploy:debug          # Deploy debug version

CKB Concepts Quick Reference

Concept Description
Cell Basic data unit (like UTXO with data)
Lock Script Defines who can spend the cell
Type Script Defines rules for cell creation/destruction
Capacity CKB tokens, also determines cell storage size
Cell Dep Reference to code/data cells
Witness Signature/proof data

AI Skills (.skills/)

The .skills/ folder contains structured patterns following the Agent Skills Open Standard. These provide detailed, reusable patterns for AI assistants.

Available Skills

Skill Description Use When
ckb-contract-patterns Smart contract patterns Writing/reviewing contracts
ckb-ccc-frontend Frontend integration Building dApp frontends

Skill Structure

.skills/{skill-name}/
├── SKILL.md           # Main skill definition
├── rules/             # Individual pattern files
│   ├── _sections.md   # Section metadata
│   └── *.md           # Pattern rules
├── metadata.json      # Version info
└── README.md          # Documentation

Key Patterns

Contract Patterns (ckb-contract-patterns):

  • Cell iteration with try/catch loops
  • Token sum validation for UDT
  • Contract structure with main() and exit()

Frontend Patterns (ckb-ccc-frontend):

  • Network switching via .env (devnet/testnet/mainnet)
  • CCC Provider setup in React/Next.js
  • Wallet connection with ccc.useCcc() and ccc.useSigner()
  • Transaction composition with ckb-js-vm args format
  • RPC calls to fetch cells and send transactions

Resources