Skip to main content
ClaudeWave
Skill5.3k repo starsupdated 17d ago

near-smart-contracts

NEAR Protocol smart contract development in Rust. Use when writing, reviewing, or deploying NEAR smart contracts. Covers contract structure, state management, cross-contract calls, testing, security, and optimization patterns. Based on near-sdk v5.x with modern macro syntax.

Install in Claude Code
Copy
git clone --depth 1 https://github.com/internet-court/internet-court-skill /tmp/near-smart-contracts && cp -r /tmp/near-smart-contracts/vendored/near/near-smart-contracts ~/.claude/skills/near-smart-contracts
Then start a new Claude Code session; the skill loads automatically.

SKILL.md

# NEAR Smart Contracts Development

Comprehensive guide for developing secure and efficient smart contracts on NEAR Protocol using Rust and the NEAR SDK (v5.x).

## When to Apply

Reference these guidelines when:

- Writing new NEAR smart contracts in Rust
- Reviewing existing contract code for security and optimization
- Implementing cross-contract calls and callbacks
- Managing contract state and storage
- Testing and deploying NEAR contracts
- Optimizing gas usage and performance

## Getting Started

### Prerequisites

Install the required tools before starting development:

```bash
# Install Rust (if not already installed)
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

# Add wasm32 target for compiling contracts
rustup target add wasm32-unknown-unknown

# Install cargo-near (build, deploy, and manage contracts)
curl --proto '=https' --tlsv1.2 -LsSf https://github.com/near/cargo-near/releases/latest/download/cargo-near-installer.sh | sh

# Install near-cli-rs (interact with NEAR network)
curl --proto '=https' --tlsv1.2 -LsSf https://github.com/near/near-cli-rs/releases/latest/download/near-cli-rs-installer.sh | sh
```

### Create a New Project

> **CRITICAL**: ALWAYS run `cargo near new` to create new projects. NEVER manually create Cargo.toml, lib.rs, or any project files. The command generates all required files with correct configurations.

```bash
# REQUIRED: Create a new contract project using the official template
cargo near new my-contract

# Navigate to project directory
cd my-contract

# Build the contract
cargo near build

# Run tests
cargo test
```

**Why `cargo near new` is mandatory:**
- Generates correct `Cargo.toml` with proper dependencies and build settings
- Creates proper project structure with `src/lib.rs` template
- Includes integration test setup in `tests/` directory
- Configures release profile with `overflow-checks = true`
- Sets up correct crate-type for WASM compilation
- Avoids common configuration mistakes that cause build failures

**DO NOT:**
- Manually create `Cargo.toml`
- Manually create `src/lib.rs`
- Copy-paste project structure from examples
- Skip this step and create files directly

### Project Structure

```
my-contract/
├── Cargo.toml          # Dependencies and project config
├── src/
│   └── lib.rs          # Main contract code
├── tests/              # Integration tests
│   └── test_basics.rs
└── README.md
```

### Deploy to Testnet

```bash
# Create a testnet account (if needed)
near account create-account sponsor-by-faucet-service my-contract.testnet autogenerate-new-keypair save-to-keychain network-config testnet create

# Build in release mode
cargo near build --release

# Deploy to testnet
cargo near deploy my-contract.testnet without-init-call network-config testnet sign-with-keychain send
```

## Rule Categories by Priority

| Priority | Category | Impact | Prefix |
| --------- | ---------- | -------- | --------- |
| 1 | Security & Safety | CRITICAL | `security-` |
| 2 | Contract Structure | HIGH | `structure-` |
| 3 | State Management | HIGH | `state-` |
| 4 | Cross-Contract Calls | MEDIUM-HIGH | `xcc-` |
| 5 | Contract Upgrades | MEDIUM-HIGH | `upgrade-` |
| 6 | Chain Signatures | MEDIUM-HIGH | `chain-` |
| 7 | Gas Optimization | MEDIUM | `gas-` |
| 8 | Yield & Resume | MEDIUM | `yield-` |
| 9 | Testing | MEDIUM | `testing-` |
| 10 | Best Practices | MEDIUM | `best-` |

### 1. Security & Safety (CRITICAL)

- `security-storage-checks` - Always validate storage operations and check deposits
- `security-access-control` - Implement proper access control using `predecessor_account_id`
- `security-reentrancy` - Protect against reentrancy attacks (update state before external calls)
- `security-overflow` - Use `overflow-checks = true` in Cargo.toml to prevent overflow
- `security-callback-validation` - Validate callback results and handle failures
- `security-private-callbacks` - Mark callbacks as `#[private]` to prevent external calls
- `security-yoctonear-validation` - Validate attached deposits with `#[payable]` functions
- `security-sybil-resistance` - Implement minimum deposit checks to prevent spam

### 2. Contract Structure (HIGH)

- `structure-near-bindgen` - Use `#[near(contract_state)]` macro for contract struct (replaces old `#[near_bindgen]`)
- `structure-initialization` - Implement proper initialization with `#[init]` patterns
- `structure-versioning` - Plan for contract upgrades with versioning mechanisms
- `structure-events` - Use `env::log_str()` and structured event logging (NEP-297)
- `structure-standards` - Follow NEAR Enhancement Proposals (NEPs) for standards
- `structure-serializers` - Use `#[near(serializers = [json, borsh])]` for data structs
- `structure-panic-default` - Use `#[derive(PanicOnDefault)]` to require initialization

### 3. State Management (HIGH)

- `state-collections` - Use SDK collections from `near_sdk::store`: `IterableMap`, `IterableSet`, `Vector`, `LookupMap`, `LookupSet`, `UnorderedMap`, `UnorderedSet`, `TreeMap`
- `state-serialization` - Use Borsh for state, JSON for external interfaces
- `state-lazy-loading` - Use SDK collections for lazy loading to save gas (loaded on-demand, not all at once)
- `state-pagination` - Implement pagination with `.skip()` and `.take()` for large datasets
- `state-migration` - Plan state migration strategies using versioning
- `state-storage-cost` - Remember: 1 NEAR ≈ 100kb storage, contracts pay for their storage
- `state-unique-prefixes` - Use unique byte prefixes for all collections (avoid collisions)
- `state-native-vs-sdk` - Native collections (Vec, HashMap) load all data; use only for <100 entries

### 4. Cross-Contract Calls (MEDIUM-HIGH)

- `xcc-promise-chaining` - Chain promises correctly
- `xcc-callback-handling` - Handle all callback scenarios (success, failure)
- `xcc-gas-management` - Allocate appropriate gas for cross-contract calls
- `xcc-error-handling` - Implement robust error handling
- `xcc-result-unwrap` - Never unwrap promise
internet-courtSkill

Entry point for Internet Court — the trust layer for agent-to-agent commerce. Use whenever an agent needs to transact with another agent or a paid service, or a user mentions agent payments, paid APIs (HTTP 402/x402), wallet custody or trust concerns, spending mandates, delegated permissions (ERC-7710/7715), escrow, agent identity or reputation (ERC-8004), negotiation between agents (A2A), agent jobs (ERC-8183), machine payments (MPP, AP2), supervision of agent behavior, revocation, verification, or dispute resolution (GenLayer) — even if they never say "Internet Court". Routes to the vendored protocol skills and connector skills in this package.

genlayer-erc7710-connectorSkill

Connect GenLayer Intelligent Contract decisions to ERC-7710-style delegated authority. Use when an agent needs to design the interface, message schema, relayer/bridge path, EVM revocation controller, constraint updates, proof/finality assumptions, and failure handling that turn a GenLayer agent-performance review into ERC-7710 revocation or policy changes.

genlayer-intelligent-contractsSkill

Internet Court adapter for GenLayer Intelligent Contract supervision. Use to specify agent-performance rubrics, evidence schemas, decision outputs, and ERC-7710 connector expectations, while delegating actual GenLayer contract writing, linting, testing, deployment, and CLI interaction to the official GenLayer skills at https://skills.genlayer.com/.

x402-erc7710Skill

Design and implement demos combining x402 HTTP payments with ERC-7710 smart contract delegations and ERC-7715 wallet permission requests for subscriptions, bounded agent budgets, recurring spend, pay-per-use APIs, and agentic commerce.

0g-computeSkill

0G Compute Network guide for decentralized AI inference, fine-tuning, and GPU services. Covers chatbots, image generation, speech-to-text, SDK integration (0g-serving-broker), processResponse API, broker.inference methods, CLI commands (0g-compute-cli), and account management. Use this skill for any 0G compute, 0G AI, or decentralized GPU question.

altllm-portal-api-keysSkill

Use this skill when the user asks to list, create, inspect, update, disable, re-enable, or revoke AltLLM Portal API keys for external agents or applications. Do NOT use for wallet login, billing history, or payment links.

altllm-portal-authSkill

Use this skill when the user asks to log in or out with a wallet session, fetch a wallet sign-in challenge, verify an externally signed challenge, or troubleshoot AltLLM Portal wallet login for the local altllm CLI. Do NOT use for API key management, billing history, or payment links.

altllm-portal-billingSkill

Use this skill when the user asks to inspect AltLLM Portal balance, redeem a promo code, review billing transactions, or view usage analytics by period, model, or API key using the local altllm CLI. Do NOT use for API key lifecycle management or payment-link execution.