본문으로 건너뛰기
cccskills
무료GitHub에 공개

near-smart-contracts

Write, review, test, and deploy Rust smart contracts on NEAR Protocol using near-sdk v5.x. Covers stored data, calls between contracts, security checks, upgrades, and gas optimization to reduce the computation costs of contract operations.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

원문원문 설명 보기

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.

실행 점수 미검증

설치 방법 보기

이럴 때 유용합니다

  • Creating a NEAR contract in Rust
  • Reviewing access control and storage handling
  • Testing calls between contracts
  • Planning contract upgrades and data migration

포함된 파일(11)

  • SKILL.md13.9 KB
  • LICENSE329 B
  • rules/best-contract-tools.md11.4 KB
  • rules/chain-signatures.md12.5 KB
  • rules/security-storage-checks.md3.5 KB
  • rules/state-collections.md4.0 KB
  • rules/structure-near-bindgen.md2.9 KB
  • rules/testing-integration-tests.md5.7 KB
  • rules/upgrade-migration.md4.9 KB
  • rules/xcc-promise-chaining.md4.7 KB
  • rules/yield-resume.md8.3 KB

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:

# 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.

# 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

# 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

PriorityCategoryImpactPrefix
1Security & SafetyCRITICALsecurity-
2Contract StructureHIGHstructure-
3State ManagementHIGHstate-
4Cross-Contract CallsMEDIUM-HIGHxcc-
5Contract UpgradesMEDIUM-HIGHupgrade-
6Chain SignaturesMEDIUM-HIGHchain-
7Gas OptimizationMEDIUMgas-
8Yield & ResumeMEDIUMyield-
9TestingMEDIUMtesting-
10Best PracticesMEDIUMbest-

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 results without checks

5. Contract Upgrades & Migration (MEDIUM-HIGH)

  • upgrade-migration - Use enums for state versioning and implement migrate method with #[init(ignore_state)]
  • upgrade-self-update - Pattern for contracts that can update themselves programmatically
  • upgrade-cleanup-old-state - Always remove old state structures to free storage
  • upgrade-dao-controlled - Use multisig or DAO for production upgrade governance

6. Chain Signatures (MEDIUM-HIGH)

  • chain-signatures - Derive foreign blockchain addresses, request MPC signatures, and build multichain transactions
  • chain-callback-handling - Handle MPC signature callbacks properly
  • chain-gas-allocation - Allocate sufficient gas for MPC calls (yield/resume pattern)

7. Gas Optimization (MEDIUM)

  • gas-batch-operations - Batch operations to reduce transaction costs
  • gas-minimal-state-reads - Minimize state reads and writes (cache in memory)
  • gas-efficient-collections - Choose appropriate collection types (LookupMap vs IterableMap)
  • gas-view-functions - Mark read-only functions as view (&self in Rust)
  • gas-avoid-cloning - Avoid unnecessary cloning of large data structures
  • gas-early-validation - Use require! early to save gas on invalid inputs
  • gas-prepaid-gas - Attach appropriate gas for cross-contract calls (recommended: 30 TGas)

8. Yield & Resume (MEDIUM)

  • yield-resume - Create yielded promises, signal resume, handle timeouts, and manage state between yield/resume
  • yield-gatekeeping - Protect resume methods from unauthorized callers

9. Testing (MEDIUM)

  • testing-integration-tests - Use near-sandbox + near-api for integration tests
  • testing-unit-tests - Write comprehensive unit tests with mock contexts
  • testing-sandbox - Test with local sandbox environment before testnet/mainnet
  • testing-edge-cases - Test boundary conditions, overflow, and empty states
  • testing-gas-profiling - Profile gas usage in integration tests
  • testing-cross-contract - Test cross-contract calls and callbacks thoroughly
  • testing-failure-scenarios - Test promise failures and timeout scenarios
  • testing-time-travel - Use sandbox.fast_forward() for time-sensitive tests

10. Best Practices (MEDIUM)

  • best-contract-tools - Use near-sdk-contract-tools for NEP standards (FT, NFT, etc.) and NEP-297 structured events
  • best-panic-messages - Provide clear, actionable panic messages
  • best-logging - Use env::log_str() for debugging and event emission
  • best-documentation - Document public methods, parameters, and complex logic
  • best-error-types - Define custom error types or use descriptive strings
  • best-constants - Use constants for magic numbers and configuration
  • best-require-macro - Use require! instead of assert! for better error messages
  • best-promise-return - Return promises from cross-contract calls for proper tracking
  • best-sdk-crates - Reuse SDK-exported crates (borsh, serde, base64, etc.)
  • best-account-id-encoding - Encode AccountIds in base32 for 40% storage savings

How to Use

Read individual rule files for detailed explanations and code examples:

rules/security-storage-checks.md
rules/structure-near-bindgen.md
rules/state-collections.md
rules/xcc-promise-chaining.md
rules/upgrade-migration.md
rules/chain-signatures.md
rules/yield-resume.md
rules/best-contract-tools.md
rules/testing-integration-tests.md

Each rule file contains:

  • Brief explanation of why it matters
  • Incorrect code example with explanation
  • Correct code example with explanation
  • Additional context and NEAR-specific considerations

Latest Tools & Versions

Development Tools

  • cargo-near: Latest - Build, deploy, and manage contracts (cargo near build, cargo near deploy)
  • near-cli-rs: Latest - Command-line interface for NEAR (near contract call, near contract view)
  • rustc: Latest stable - Rust compiler
  • near-sandbox: Latest - Local sandbox environment for integration testing
  • near-api-rs: Latest - Rust API client for interacting with NEAR (replaces near-workspaces-rs for tests)
  • omni-transaction-rs: Latest - Build transactions for multiple blockchains (Bitcoin, Ethereum, etc.)

SDK Versions

  • near-sdk-rs: v5.x (v6.x coming with structured errors support)
  • near-sdk-contract-tools: Latest - Derive macros for NEP standards (FT, NFT, Storage Management)

Key Features

  • Unified macro syntax: #[near(contract_state)] replaces #[near_bindgen] + derives
  • Flexible serialization: #[near(serializers = [json, borsh])] for data structs
  • Store collections: near_sdk::store::IterableMap, IterableSet, LookupMap, LookupSet, Vector, UnorderedMap, UnorderedSet, TreeMap
  • Simplified cross-contract calls: High-level promise API with Promise::new() and .then()
  • Built-in NEP support: FT (NEP-141), NFT (NEP-171), and other standards
  • Result handling: #[handle_result] for methods returning Result<T, E> without panicking
  • Yield/Resume: Contracts can yield execution and wait for external services to resume
  • Chain Signatures: Sign transactions for other blockchains (Bitcoin, Ethereum, Solana, etc.)
  • Contract Tools: Derive macros for Owner, Pause, Role-based access control patterns

Resources

Storage Costs Reference

StorageCostNotes
1 byte0.00001 NEAR~10kb per 0.1 NEAR
100 KB~1 NEARApproximate reference
AccountId64+ bytesCan save 40% with base32 encoding
Contract codeVariablePaid by contract account

SDK Collections Reference

CollectionIterableClearOrderedRangeUse Case
VectorYesYesYesYesOrdered list with index access
LookupMapNoNoNoNoFast key-value, no iteration needed
LookupSetNoNoNoNoFast membership checks
IterableMapYesYesYesNoKey-value with iteration
IterableSetYesYesYesNoSet with iteration
UnorderedMapYesYesNoNoKey-value, unordered iteration
UnorderedSetYesYesNoNoSet, unordered iteration
TreeMapYesYesYesYesSorted key-value with range queries

리뷰

아직 리뷰가 없습니다. 사용해 본 소감을 남겨 주세요.

댓글

로그인 없이 쓸 수 있습니다. 사용 후기, 질문, 작동하지 않은 환경 등을 편하게 남겨 주세요.

아직 댓글이 없습니다. 첫 댓글을 남겨 보세요.

보내면 바로 공개됩니다. 이메일 주소나 전화번호 같은 개인 정보는 쓰지 마세요. URL은 2개까지입니다.

0 / 1,000자

이 양식은 reCAPTCHA로 보호되며 Google 개인정보처리방침 및 서비스 약관이 적용됩니다.

같은 저장소의 스킬

Build chat, image generation, and speech transcription features on 0G Compute Network, a distributed GPU marketplace. This skill guides SDK integration, model fine-tuning, response processing for billing, and account funding through code patterns and CLI commands.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

  • Integrating chat and image generation into an application
  • Preparing model fine-tuning jobs
  • Checking balances and funding provider accounts
internet-court/internet-court-skill7천2026년 8월 20일 업데이트

Build servers and clients for A2A, an open protocol that lets AI agents communicate across frameworks. Publish agent capabilities, exchange tasks and results, stream progress, and add notifications for workflows involving multiple agents.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

  • Connect agents built with different frameworks
  • Publish agent capabilities through an Agent Card
  • Build a research, writing, and review workflow
internet-court/internet-court-skill7천2026년 8월 20일 업데이트

Give an AI agent a wallet with administrator-defined transaction limits. The skill covers encrypted key storage, balance checks, and sending funds through code-enforced rules for destinations, amounts, transaction frequency, and emergency shutdown.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

  • Give an agent a wallet with transaction limits
  • Restrict transfers to approved chains and addresses
  • Check balances and active rules before sending
internet-court/internet-court-skill7천2026년 8월 20일 업데이트

Manage a crypto wallet with the awal CLI, including sign-in, balance checks, transfers, swaps, and funding. Also find and pay for APIs through x402, a payment protocol, set up paid endpoints, and query blockchain data on Base.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

  • Check wallet balances across supported networks
  • Send tokens to an address or ENS name
  • Swap tokens or add wallet funds
internet-court/internet-court-skill7천2026년 8월 20일 업데이트

Write TypeScript, Rust, or Python code for Alkahest escrow contracts, which hold assets until conditions are met. Covers creating escrows, submitting fulfillment, collecting payments, and building custom contracts that decide whether requirements have been satisfied.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

  • Integrate Alkahest escrow into an application
  • Build a bot that creates escrows and submits fulfillment
  • Implement payment collection and fulfillment monitoring
internet-court/internet-court-skill7천2026년 8월 20일 업데이트

Use the Alkahest CLI to manage escrow, where assets are held until agreed conditions are met. It covers buyer deposits, seller fulfillment and collection, third-party decisions, token swaps, and reclaiming expired, unfulfilled deposits.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

  • Creating escrow with release conditions
  • Submitting work and collecting escrowed assets
  • Approving or rejecting fulfillment as an oracle
internet-court/internet-court-skill7천2026년 8월 20일 업데이트

internet-court의 스킬 모두 보기

이 스킬의 문제 신고