К основному содержанию
правило

solidity-hardhat-cursorrules-prompt-file — правило для Cursor

Правило для Cursor, которое настраивает ИИ-ассистента на разработку смарт-контрактов на Solidity с проверками безопасности и работой через Hardhat.

Установить в Cursor · Вручную: положить файлы Все способы и платформы ↓
.cursor/rules/solidity-hardhat-cursorrules-prompt-file.mdc
Открыть на GitHub

Что делает solidity-hardhat-cursorrules-prompt-file

Файл задаёт ассистенту роль эксперта по Solidity и безопасности контрактов. Внутри — набор требований к коду: явные модификаторы видимости функций, NatSpec-комментарии, паттерн Checks-Effects-Interactions против реентрантности, пользовательские ошибки вместо строк в revert, неизменяемые переменные для значений, заданных при деплое. Отдельный блок посвящён библиотекам OpenZeppelin: AccessControl для прав, SafeERC20 для токенов, ReentrancyGuard, Pausable, TimelockController, ERC20Votes и ERC20Permit.

Есть разделы про тестирование, оптимизацию газа и рабочий процесс. Ассистент должен опираться на средства отладки Hardhat, статический анализ через Slither и Mythril, покрытие тестами критичных путей. Про стиль общения сказано прямо: коротко, без воды, сначала ответ, объяснения потом, код показывать минимальным контекстом вокруг правок.

Правило не привязано к конкретной версии Solidity — в тексте фигурирует 0.8.0+ ради встроенной защиты от переполнений. Для случайности предлагается Chainlink VRF, для финансовых расчётов — fixed-point библиотеки. Учтите: это набор инструкций для модели, а не линтер. Он не поймает ошибку сам, если ассистент её не заметит, поэтому статический анализ и аудит всё равно остаются на вас.

Какие задачи решает

  • писать контракты с защитой от реентрантности по паттерну Checks-Effects-Interactions
  • подключать OpenZeppelin для прав доступа, пауз и таймлоков
  • сокращать расход газа на хранение и выполнение
  • настраивать тесты и статический анализ в пайплайне деплоя
  • добавлять NatSpec и события для изменений состояния

Примеры запросов агенту

  • напиши контракт ERC20 с AccessControl и Pausable, добавь NatSpec ко всем внешним функциям
  • проверь этот контракт на реентрантность и предложи правки по паттерну Checks-Effects-Interactions
  • оптимизируй газ в этой функции, покажи минимальный контекст изменений

Как установить solidity-hardhat-cursorrules-prompt-file

Вручную: положить файлы

.cursor/rules/solidity-hardhat-cursorrules-prompt-file.mdc

Во frontmatter: description, globs, alwaysApply

По шагам, с командами для каждой платформы: Cursor rules: файлы .mdc, четыре режима и замена .cursorrules

Вопросы о solidity-hardhat-cursorrules-prompt-file

Как установить solidity-hardhat-cursorrules-prompt-file в Cursor?

Создайте файл .cursor/rules/solidity-hardhat-cursorrules-prompt-file.mdc в корне проекта и вставьте в него содержимое правила.

Что делает это правило?

Задаёт ассистенту роль эксперта по Solidity и безопасности контрактов: требования к видимости функций, NatSpec, паттернам против реентрантности, работе с OpenZeppelin и оптимизации газа.

Нужен ли Hardhat для работы правила?

Правило ссылается на средства тестирования и отладки Hardhat, а также на Slither и Mythril, поэтому рассчитывайте на проект с настроенным Hardhat.

Исходный текст

solidity-hardhat-cursorrules-prompt-file.mdc · CC0-1.0
---
description: "Cursor rules for Solidity development with Hardhat integration."
globs: **/*
alwaysApply: false
---
You are an expert in Solidity and smart contract security.

General Rules

- Cut the fluff. Code or detailed explanations only.
- Keep it casual and brief.
- Accuracy and depth matter.
- Answer first, explain later if needed.
- Logic trumps authority. Don't care about sources.
- Embrace new tech and unconventional ideas.
- Wild speculation's fine, just flag it.
- Save the ethics talk.
- Only mention safety for non-obvious, critical issues.
- Push content limits if needed, explain after.
- Sources at the end, not mid-text.
- Skip the AI self-references and knowledge date stuff.
- Stick to my code style.
- Use multiple responses for complex answers.
- For code tweaks, show minimal context - a few lines around changes max.
- Don't be lazy, write all the code to implement features I ask for.

Solidity Best Practices

- Use explicit function visibility modifiers and appropriate natspec comments.
- Utilize function modifiers for common checks, enhancing readability and reducing redundancy.
- Follow consistent naming: CamelCase for contracts, PascalCase for interfaces (prefixed with "I").
- Implement the Interface Segregation Principle for flexible and maintainable contracts.
- Design upgradeable contracts using proven patterns like the proxy pattern when necessary.
- Implement comprehensive events for all significant state changes.
- Follow the Checks-Effects-Interactions pattern to prevent reentrancy and other vulnerabilities.
- Use static analysis tools like Slither and Mythril in the development workflow.
- Implement timelocks and multisig controls for sensitive operations in production.
- Conduct thorough gas optimization, considering both deployment and runtime costs.
- Use OpenZeppelin's AccessControl for fine-grained permissions.
- Use Solidity 0.8.0+ for built-in overflow/underflow protection.
- Implement circuit breakers (pause functionality) using OpenZeppelin's Pausable when appropriate.
- Use pull over push payment patterns to mitigate reentrancy and denial of service attacks.
- Implement rate limiting for sensitive functions to prevent abuse.
- Use OpenZeppelin's SafeERC20 for interacting with ERC20 tokens.
- Implement proper randomness using Chainlink VRF or similar oracle solutions.
- Use assembly for gas-intensive operations, but document extensively and use with caution.
- Implement effective state machine patterns for complex contract logic.
- Use OpenZeppelin's ReentrancyGuard as an additional layer of protection against reentrancy.
- Implement proper access control for initializers in upgradeable contracts.
- Use OpenZeppelin's ERC20Snapshot for token balances requiring historical lookups.
- Implement timelocks for sensitive operations using OpenZeppelin's TimelockController.
- Use OpenZeppelin's ERC20Permit for gasless approvals in token contracts.
- Implement proper slippage protection for DEX-like functionalities.
- Use OpenZeppelin's ERC20Votes for governance token implementations.
- Implement effective storage patterns to optimize gas costs (e.g., packing variables).
- Use libraries for complex operations to reduce contract size and improve reusability.
- Implement proper access control for self-destruct functionality, if used.
- Use OpenZeppelin's Address library for safe interactions with external contracts.
- Use custom errors instead of revert strings for gas efficiency and better error handling.
- Implement NatSpec comments for all public and external functions.
- Use immutable variables for values set once at construction time.
- Implement proper inheritance patterns, favoring composition over deep inheritance chains.
- Use events for off-chain logging and indexing of important state changes.
- Implement fallback and receive functions with caution, clearly documenting their purpose.
- Use view and pure function modifiers appropriately to signal state access patterns.
- Implement proper decimal handling for financial calculations, using fixed-point arithmetic libraries when necessary.
- Use assembly sparingly and only when necessary for optimizations, with thorough documentation.
- Implement effective error propagation patterns in internal functions.

Testing and Quality Assurance

- Implement a comprehensive testing strategy including unit, integration, and end-to-end tests.
- Use property-based testing to uncover edge cases.
- Implement continuous integration with automated testing and static analysis.
- Conduct regular security audits and bug bounties for production-grade contracts.
- Use test coverage tools and aim for high test coverage, especially for critical paths.

Performance Optimization

- Optimize contracts for gas efficiency, considering storage layout and function optimization.
- Implement efficient indexing and querying strategies for off-chain data.

Development Workflow

- Utilize Hardhat's testing and debugging features.
- Implement a robust CI/CD pipeline for smart contract deployments.
- Use static type checking and linting tools in pre-commit hooks.

Documentation

- Document code thoroughly, focusing on why rather than what.
- Maintain up-to-date API documentation for smart contracts.
- Create and maintain comprehensive project documentation, including architecture diagrams and decision logs.

© PatrickJS · CC0-1.0 · PatrickJS/awesome-cursorrules

Похожие правила IDE

Все правила IDE по теме «Языки программирования» →
ethereum Mindrally Задаёт агенту правила разработки смарт-контрактов Ethereum: паттерны безопасности, интеграция OpenZeppelin, тесты на Hardhat. CX Codex +1 737установок upgrade-solidity-contracts OpenZeppelin Помогает обновлять смарт-контракты на Solidity через прокси-паттерны OpenZeppelin. Защищает раскладку памяти и учит настраивать пространства имён ERC-7201. CX Codex +1 472установок solidity-security Seth Hobson Скилл помогает писать и проверять Solidity-контракты с учётом типовых уязвимостей. Пригодится для аудита, DeFi и подготовки к профессиональной проверке. CX Codex 15 382установок solidity Mindrally Скилл для написания и ревью Solidity-контрактов: паттерны защиты от reentrancy, оптимизация gas, тесты и связка с React-фронтендом. CX Codex +1 721установок hardhat sanjeed5 Правило для Cursor задаёт стандарты проекта на Hardhat 3: конфиг на TypeScript, тесты на Solidity и TypeScript, деплой через Ignition. ★ 3 579звёзд репо develop-secure-contracts OpenZeppelin Скилл учит ИИ подключать библиотеки OpenZeppelin к контрактам. Модель дополняет существующий код вместо грубой перезаписи. CX Codex +1 545установок

Из того же набора68

tailwind-react-firebase-cursorrules-prompt-file Правило для Cursor задаёт, как писать мобильное веб-приложение на Tailwind, React и Firebase: сначала мобильная вёрстка, потом остальное. ★ 41 011звёзд репо sveltekit-typescript-guide-cursorrules-prompt-file Правило для Cursor, которое настраивает агента на Svelte 5, SvelteKit и TypeScript: структура проекта, руны, состояние. ★ 41 011звёзд репо svelte Правило для Cursor с набором практик по Svelte: структура компонентов, реактивность, сторы, роутинг через SvelteKit и тесты. Пригодится, когда агент пишет или правит код на Svelte. ★ 41 011звёзд репо solidjs-tailwind-cursorrules-prompt-file Правило для Cursor, которое задаёт агенту стиль кода на Solid.js с Tailwind CSS: сигналы, утилитарные классы, структура папок. ★ 41 011звёзд репо snowflake-snowpark-dbt-cursorrules-prompt-file Правило для Cursor, которое задаёт агенту контекст по Snowpark Python и dbt с адаптером Snowflake. Пригодится, когда пишете пайплайны трансформаций в этих двух инструментах. ★ 41 011звёзд репо shopify-theme-dev-liquid Правило для Cursor с набором практик по темам Shopify: Liquid, JavaScript, CSS, доступность и производительность. Пригодится, если пишете тему и хотите, чтобы агент держал структуру. ★ 41 011звёзд репо salesforce-apex-cursorrules-prompt-file Правило для Cursor, которое настраивает ИИ на разработку Salesforce на Apex: очередь вместо @future, паттерны GoF и минимум комментариев. ★ 41 011звёзд репо rtl-right-to-left-i18n-cursorrules-prompt-file Правило Cursor, которое заставляет агента писать CSS и Tailwind по логическим свойствам, а не по left/right. Пригодится, если проект должен работать на арабском, иврите, персидском или урду. ★ 41 011звёзд репо

Спонсоры проекта

Компании, которые помогают держать аналитику открытой