Awesome Cursor Rules Collection

Showing 1093-1104 of 2626 matches

Vue
# Matter PLM Development Guidelines

## Tech Stack Overview

### Frontend (matter-client)
- **Core**: Nuxt 3.14, Vue 3.4, TypeScript
- **UI**: Vuetify 3.7, PrimeVue 4.0, Syncfusion Components, Shadcn Vue, Radix Vue
- **State**: Pinia
- **Utilities**: VueUse, date-fns
- **File Handling**: Uppy, pdfmake, jspdf
- **Styling**: Tailwind CSS

### Backend (matter-server)
- **Core**: Laravel 11, PHP 8.2
- **Authentication Tokens**: JWT
- **Storage**: Firebase
- **Integration**: Shopify API, Reverb (Web Sockets)
- **Admin**: Filament 3.2, Livewire 3.0

---

## Development Workflow
Before coding, follow a four-step analysis process:
1. **Current State**: Assess the current state of the codebase.
2. **Requirements**: Define the requirements clearly.
3. **Risks**: Identify potential risks and mitigation strategies.
4. **Strategy**: Plan the best approach to meet the requirements.

---


Project Management:
- Reference cursorProject.md for all feature implementations
- Reference collection.json for all API endpoints and their request/response formats
- Follow the established database schema
- Maintain consistency with existing components


## Project Structure

**Frontend (Nuxt 3)**

matter-client/
├── components/          # Vue components
│   ├── ui/              # Base UI components
│   └── {feature}/       # Feature-specific components
├── layouts/             # Page layouts
├── pages/               # File-based routing
├── composables/         # Shared logic
├── plugins/             # Nuxt plugins
├── stores/              # Pinia stores
├── types/               # TypeScript definitions
└── utils/               # Helper functions

**Backend (Laravel 11)**

matter-server/
├── app/
│   ├── Http/
│   │   ├── Controllers/  # Feature-based controllers
│   │   └── Middleware/   # Request middleware
│   ├── Models/           # Eloquent models
│   ├── Services/         # Business logic
│   ├── Observers/        # Model observers
│   └── Traits/           # Shared traits
├── database/
│   ├── migrations/       # Database migrations
│   └── seeders/          # Database seeders
└── routes/
    └── api/              # API routes by feature

# FRONTEND (matter-client)
**Frontend Guidelines**

- Components and Icons
- Use Remix Iconify icons (ri-*).
- Do not use Material Design icons (mdi-*).
- Use Vuetify for layout components.
- Use PrimeVue for complex widgets.

**Code Style and Structure**

- Use TypeScript with concise, technical examples.
- Use Composition API and declarative patterns.
- Use Axios for API calls, not fetch method
- Do not put api/ infront of API routes since this is already configured to be done.
- All our API routes are in the collection.json file in the server/public/docs/collection.json file.
- Use <script setup lang='ts'> at the top and place the template at the bottom.
- Favor modular, iterative code; avoid duplication.
- Use descriptive variable names (e.g., isLoading, hasError).
- Preserve payload structure in async functions.
- Prefer types over interfaces; avoid enums (use constant objects).
- Use arrow functions for methods and computed properties.
- Leverage defineProps and defineComponent for strong typing.
- Avoid unnecessary curly braces and keep syntax concise.
- Keep only one onMounted, don't repeat anything which can be optimized
- Always shift onMounted at the last of the script
- Keep everything in short using existing function as much as possible.
- In Fetch functions Don't use localStorage to fetch access_token as it got clear in the plugin of axios instance already.
- While implementing new feature or any task, don't touch anything else other than that and try to use existing function to make it short and simple.

**Styling**

- Use Vuetify and Tailwind CSS:
- Utilize component props over custom classes.
- Avoid styling imported components unnecessarily.
- Minimize custom class usage.
- Follow Vuetify component patterns and Tailwind utility classes.
- Implement responsive design (mobile-first).

**Naming Conventions**

- Directories: lowercase with dashes (e.g., components/auth-wizard).
- Components: PascalCase (e.g., AuthWizard.vue).
- Composables: camelCase (e.g., useAuthState.ts).
- Models: PascalCase singular (e.g., User.php).
- Controllers: PascalCase with Controller suffix (e.g., UserController.php).

**Performance Optimization**

- Use Nuxt's built-in optimizations:
- Leverage Suspense for async components.
- Implement lazy-loading for routes and components.
- Optimize images (WebP, size metadata, lazy loading).
- Monitor Core Web Vitals (LCP, CLS, FID).
- Implement proper caching strategies.
- Use code splitting effectively.

# BACKEND (matter-server)
**Backend Guidelines (Laravel 11)**

## Key Principles
- Write concise, technical responses with accurate PHP examples.
- Follow Laravel best practices and conventions.
- Use object-oriented programming with a focus on SOLID principles.
- Prefer iteration and modularization over duplication.
- Use descriptive variable and method names.
- Use lowercase with dashes for directories (e.g., app/Http/Controllers).
- Favor dependency injection and service containers.

## PHP/Laravel
- Use PHP 8.2+ features when appropriate (e.g., typed properties, match expressions).
- Follow PSR-12 coding standards.
- Utilize Laravel's built-in features and helpers when possible.
- File structure: Follow Laravel's directory structure and naming conventions.
- Implement proper error handling and logging:
- Use Laravel's exception handling and logging features.
- Create custom exceptions when necessary.
- Use try-catch blocks for expected exceptions.
- Use Laravel's validation features for form and request validation.
- Implement middleware for request filtering and modification.
- Utilize Laravel's Eloquent ORM for database interactions.
- Use Laravel's query builder for complex database queries.
- Implement proper database migrations and seeders.

## Key Conventions
1. Follow Laravel's MVC architecture.
2. Use Laravel's routing system for defining application endpoints.
3. Implement proper request validation using Form Requests.
4. Implement proper database relationships using Eloquent.
5. Implement proper API resource transformations.
6. Use Laravel's event and listener system for decoupled code.
7. Implement proper database transactions for data integrity.
8. Use Laravel's built-in scheduling features for recurring tasks.

## Matter PLM Engineering Principles (Laravel)
1. Try keeping controllers thin with only CRUD methods (index, show, store, update, destroy).
2. Use relationship controllers for extra "verbs" while maintaining CRUD operations.
3. Implement the Action pattern for mutating business logic.
4. Avoid code duplication by utilizing existing patterns or creating new ones when necessary.
5. Use the Pipeline pattern for sequences of commands, especially in controllers that mutate data.
6. Implement logging in Actions to track their execution.
7. Use Request classes for validation instead of putting validation code in Controllers.
8. Utilize query scopes, custom collections, or static methods on models for fetching multiple models.
9. Use traits to add common functions to models.
10. Implement Resource classes for data transformation and standardization.
11. Manage dropdowns through the DropdownServiceProvider. It is automatically shared as part of InjectDropdowns middleware.
12. Only use Tailwind to implement CSS, Allow custom CSS under defined guidelines for specific needs.
13. All responses to the front end should be JSON responses.
14. All tables require company_id/brand_id fields.
15. Use AssignCompanyandBrand.php Trait to automatically assigns the company_id and brand_id, these fields shouldn't be come from the frontend payload.
16. Use HasCompanyOrBrandScope.php Trait to check if the authenticated user has any company or brand linked to it.
17. Use BasModel.php file to automatically assigns the row_position to required tables. (Use this file to extend existing Models.
18. Use DropdownServiceProvider.php to inject necessary dropdown data to the routes for specific pages.
19. Organize routes by feature in separate files (e.g., settings.php, account_settings.php, auth.php, product_development.php, sales.php, supply_chain.php, tasks.php).
20. Do not modify .env.example.

## Database Management Guidelines
### Migrations
- Create new migrations for tables with timestamped filenames (YYYY_MM_DD_HHMMSS)
- Always implement both up() and down() methods
- Include company_id and brand_id for multi-tenancy
- Use consistent nullable() patterns for optional fields
- Implement proper foreign key constraints with onDelete behaviors
- Group related fields with clear comments
- Standard fields: timestamps(), row_position for ordering
- Use descriptive table and column names
- Define proper field types and lengths

### Seeders
- Path: database/seeders
- Register all seeders in DatabaseSeeder.php
- Organize seeders in logical group- folders (eg: system, company, settings)
- Maintain proper seeding order for dependencies
- Create modular seeder classes by feature
- Handle relations and constraints properly
- Implement clear data structures
- Handle multi-tenancy in seed data
css
express.js
firebase
golang
javascript
jwt
laravel
nuxt.js
+10 more
manish1034/Matter-Frontend-Nuxtjs-

Used in 1 repository

Scala
# Cursor Rules for gemini4s

# Meta Rules
- This file must be updated whenever workflow or process changes
- All workflow changes must be reflected in both .cursorrules and README.md
- Changes to rules require PR review
- Rules should be kept in sync with project board structure

# Project Structure Guidelines
- Source code should be organized in the src/main/scala/gemini4s directory
- Test code should be in the src/test/scala/gemini4s directory
- Follow the tagless final pattern for all core abstractions
- Use ZIO for effects and resource management

# Project Layers
- Foundation Layer: error types and core models
- Core API Layer: algebra definitions and HTTP client
- Implementation Layer: ZIO interpreter
- Documentation Layer: examples and guides

# Development Workflow
- Start with foundation layer tasks first
- Core API layer tasks can be worked on in parallel once foundation is ready
- Implementation layer depends on both foundation and core API layers
- Documentation should be updated incrementally but finalized last
- Each layer must maintain 90% test coverage
- Run `sbt lint` after making code changes
- Run `sbt lintFix` to automatically fix linting issues
- Verify code passes linting before committing

# Code Quality Requirements
- All code must pass ScalaFix linting rules
- Run linting checks after every code change
- Fix any linting issues before committing
- Maintain consistent import organization
- Remove unused imports and variables
- Follow Scala best practices enforced by ScalaFix
- Use `sbt lintFix` to automatically fix common issues
- Manual review required for any disabled lint rules

# CI/CD Requirements
- All PRs must pass GitHub Actions checks
- Build must succeed on all supported Scala versions
- Tests must pass with minimum 90% coverage
- Scoverage report must be generated
- Branch protection rules must be enforced
- No direct commits to main branch
- PR reviews required before merge
- All lint checks must pass before merge

# CI/CD Workflow for Agents
- After pushing changes to a PR, always check GitHub Actions status
- Wait for CI checks to complete before proceeding
- If checks fail, examine logs and fix issues
- Verify both build and test jobs pass
- Ensure coverage meets 90% threshold
- Verify lint job passes successfully
- Do not proceed with additional changes until CI is green
- Include CI status in progress updates to user

# Coding Standards
- Use meaningful type parameters (e.g., F[_] for effect type)
- All public APIs must be documented with ScalaDoc
- Error handling should use custom ADTs in the error channel
- Prefer immutable data structures
- Use ZIO's built-in testing framework for all tests

# File Organization
- One primary trait/type class per file
- Implementation modules should be in separate files
- Keep files focused and small (< 300 lines)
- Group related functionality in packages

# Git Flow Guidelines
- Main branch is protected and requires PR review
- Feature branches should be named: feature/[issue-number]-short-description
- Bug fix branches should be named: fix/[issue-number]-short-description
- Release branches should be named: release/v[version]
- All commits should reference issue numbers: "#123: Add feature X"
- All PRs must be merged using squash merge
- PR title will be used as the squash commit title
- PR description will be used as the squash commit message
- Branches are automatically deleted after merge
- Delete branches after successful merge

# PR Description Guidelines
- PR title should include issue number and concise description
- PR description should be structured in sections:
  - Overview: Brief summary of changes
  - Major Components: Categorized list of main changes (e.g., "CI/CD Setup", "Code Quality Tools")
  - Process Updates: Any workflow or process changes
  - Documentation: Documentation updates and changes
- Each section should use bullet points for clarity
- Include "Resolves #X" to link to relevant issue
- Update description when making significant changes to PR

# PR Description Command Example
```bash
# Create a temporary description file and update PR
printf "Title of PR\n\n# Overview\nBrief summary of changes.\n\n# Major Components\n- Component 1\n  - Subitem 1\n  - Subitem 2\n- Component 2\n  - Subitem 1\n  - Subitem 2\n\n# Process Updates\n- Process change 1\n- Process change 2\n\n# Documentation\n- Doc update 1\n- Doc update 2\n\nResolves #X" > pr_description.md && \
gh pr edit PR_NUMBER --body-file pr_description.md && \
rm pr_description.md
```

# Project Board Usage
- All development work must be tracked in the project board
- New features/bugs start in "To Do"
- Move cards to "In Progress" when work begins
- Use "Review" column for PR review phase
- Only move to "Done" after tests pass and PR is merged
- Link commits and PRs to relevant project cards
- Update card status when transitioning between columns
- Check task dependencies before starting new work

# Task Management Guidelines
- Prefer updating existing tasks over creating new ones
- Keep task history in comments for traceability
- Update task labels to reflect current scope
- Ensure task titles remain concise but descriptive
- Regularly review and clean up duplicate tasks:
  - Identify overlapping functionality
  - Update primary task with any unique requirements
  - Close duplicate tasks with explanatory comments
  - Link closed tasks to their primary counterparts

# Dependencies Management
- Check issue dependencies before starting work
- Don't start tasks if dependencies aren't complete
- Mark blocked tasks in project board
- Update dependent tasks when completing work

# Testing Requirements
- All public APIs must have test coverage
- Use property-based testing where appropriate
- Mock external services in tests
- Include both unit and integration tests
- Maintain minimum 90% code coverage with scoverage
- Run full test suite before submitting PR
- All tests must pass in CI before merge

# Error Handling
- Define specific error types for each failure case
- Use ZIO error channel for error propagation
- Provide meaningful error messages
- Handle rate limiting and API quotas gracefully

# Performance Considerations
- Use streaming for large responses
- Implement proper resource cleanup
- Consider backpressure in streaming operations
- Cache responses where appropriate

# Documentation
- Keep README.md up to date
- Document all type class instances
- Include examples in ScalaDoc
- Maintain CHANGELOG.md
- Document dependencies between components
- Update build status badges in README
golang
less
scala

First seen in:

JamesMMiller/gemini4s

Used in 1 repository

TypeScript
<!-- @format -->
CURSORRULES: V0.2

Project-Specific Overview

    Project Name & Description:
    •	Example: “MyProject - A decentralized marketplace for digital collectibles.”

Goals & Objectives:
• Example: “Implement a robust smart contract for trustless transactions, integrate a Next.js front-end for seamless user experience, ensure high test coverage, and maintain a clearly documented codebase.”

Immediate To-Dos:
• Example: 1. Finalize Solidity contract for escrow payments. 2. Set up NestJS services and Next.js pages for user onboarding. 3. Integrate Alchemy and ethers for on-chain queries. 4. Configure Tailwind and Radix UI components for responsive design. 5. Implement basic RAG-based feature with LangChain and ensure Supabase integration for data storage.

(Update this section as the project evolves to help the AI remain aware of priorities and changes.)

Global Standards & Best Practices

1. Code Quality & Consistency
   • Languages & Frameworks:
   • Primary Languages: TypeScript for front-end and back-end logic, Solidity for smart contracts.
   • Common Frameworks & Libraries: Next.js, Node.js/Express, Tailwind CSS, ethers.js, Alchemy SDK.
   • Code Style:
   • Follow a strict linting and formatting guideline. For TypeScript, adhere to ESLint and Prettier configurations.
   • For Solidity, follow the latest recommended Solidity style guide (e.g., naming conventions, NatSpec comments).
   • Ensure all code includes type definitions and strongly typed interfaces (no any unless absolutely necessary).
   • Repository Structure:

FRONT END
/build # Service compiled output
/docs # Project documentation, architectural decisions, API specs
/src # TypeScript source (NestJS services, Next.js pages/components)
/app # Next.js App Router structure (preferred for latest Next.js)
/components # Shared UI components (use lowercase-dashed folder names)
/ui # UI components
/modals # Modals
/common # Common components
/layout # Layout components
/config # Configuration files  
 /constants # Constants and environment variables
/hooks # Reusable hooks
/helpers # Specific helper functions for hooks
/utils # Utility functions
/providers # Providers
/contexts # Contexts
/helpers # Helper functions
/styles # Tailwind & CSS styles
/types # TypeScript types, interfaces, and enums
/scripts # Deployment, migration, utility scripts
/public # Static assets
.env # Environment variables
.cursorrules # AI Context and Project rules

BACK END
/build # Service compiled output
/src # TypeScript source (NestJS services, Next.js pages/components)
/api # Next.js App Router structure (preferred for latest Next.js)
/config # Configuration files  
 /constants # Constants and environment variables
/utils # Utility functions
/classes # Classes
/providers # Providers
/contexts # Contexts
/helpers # Helper functions
/pages # Next.js pages (if applicable)
.index.ts # Entry point for the backend
/docs # Project documentation, architectural decisions, API specs
/scripts # Deployment, migration, utility scripts
.env # Environment variables
.cursorrules # AI Context and Project rules

SMART CONTRACTS
/bin # Big data sets dump
/build # Build artifacts
/contracts # Solidity Contracts
/base # Base Contracts
/interfaces # Interfaces
/libraries # Libraries
/logic # Logic contracts
/security # Security contracts
/tokens # Token contracts
/utils # Utility contracts
/config # Configuration files  
/deploy # Deployment scripts & arguments
/deployers # Deployer scripts
/arguments # Deployment arguments
deploy.ts # Master deployment script
deploymentArgs.ts # Deployment arguments
/docs # Project documentation, architectural decisions, API specs
/contracts # Documentation exports from Hardhat Documentation creation
/reports # Hardhat reports
/logs # Deployment logs
/scripts # Deployment, migration, utility scripts
/helpers # Helper functions
/tests # Test specific helper functions
/tasks # Hardhat tasks
/tests # Test files
/types # TypeScript types, interfaces, and enums and Output of Hardhat typechain
/contracts # Output of Hardhat typechain
.env # Environment variables
.cursorrules # AI Context and Project rules
.hardhat.config.ts # Hardhat configuration

**Mono-Repo Note:**  
For large mono-repos, separate deployable sections (`/backend`, `/contracts`, `/docs`, `/frontend`, etc.). If multiple services of the same type exist, name them accordingly (e.g., `backend-stats`, `backend-tracking`, `frontend-website`, `frontend-app`).

---

## 2. Documentation & Knowledge Sharing

**Documentation Standards:**

- Each feature/module: Document in `/docs`.
- Solidity: Use NatSpec for all public/external functions.

**Regular Updates:**

- Update `/docs` after significant changes affecting data structures, APIs, or deployments.
- Maintain a changelog or release notes.

**Reading & Staying Informed:**

- AI and team should regularly refer to `/docs` and code comments.
- Before coding or refactoring, review recent changes and docs.

---

## 3. TypeScript General Guidelines

**Basic Principles:**

- Strong typing: Declare types for variables, parameters, return values.
- Avoid `any`. Create interfaces/types as needed.
- No blank lines within functions.
- Use descriptive, correctly spelled names.
- Use RO-RO (Receive Object, Return Object) for multiple parameters/returns.

**Nomenclature:**

- Classes: PascalCase
- Variables/Functions/Methods: camelCase
- Files/Directories: kebab-case
- Environment Variables: UPPERCASE
- Use verbs in function names, no magic numbers.

**Functions:**

- Short, single-purpose (<20 instructions).
- Arrow functions for simple helpers (<3 instructions).
- Named functions for complex logic.
- Early returns to reduce nesting.
- Use map/filter/reduce for clarity.
- Default parameters over null checks.

**Data:**

- Encapsulate in composite types.
- Prefer immutability (`readonly`, `as const`).

**Classes (NestJS Services, etc.):**

- Follow SOLID.
- Prefer composition over inheritance.
- Small classes (<200 lines, <10 methods, <10 properties).
- Use interfaces for contracts.

**Exceptions:**

- Use exceptions for unexpected errors only.
- Catch exceptions to fix known issues or add context.
- Otherwise rely on global handlers.

---

## 4. NestJS-Specific Guidelines

**Architecture:**

- Modular: One module per domain/route.
- One controller per main route; secondary routes as needed.
- `models` for DTOs (validated by `class-validator`), simple output types.
- Services handle business logic and persistence (MikroORM recommended).
- Core module for global filters, middlewares, guards, interceptors.
- Shared module for common utilities.

**Testing (NestJS):**

- Use Jest.
- Test each controller, service, and have e2e tests.
- Follow Arrange-Act-Assert, Given-When-Then.
- `admin/test` endpoint as a smoke test if suitable.

---

## 5. Next.js, React, Tailwind, Shadcn UI, Radix UI Guidelines

**Code Style & Structure:**

- Functional & declarative; avoid classes in React.
- Concise, readable TypeScript.
- Descriptive variable names.

**Naming Conventions:**

- lowercase-with-dashes for directories.
- Favor named exports for components.

**TypeScript (React):**

- Avoid enums; use maps.
- Functional components with interfaces for props.

**Syntax & Formatting:**

- Use `function` for pure functions.
- Concise conditionals.
- Declarative JSX.

**UI & Styling:**

- Shadcn UI, Radix UI, Tailwind CSS for styling.
- Responsive, mobile-first design.
- Implement light/dark mode.

**Performance Optimization (Frontend):**

- Minimize `use client`, `useEffect`, `setState`; prefer React Server Components.
- Wrap client components in `Suspense` with fallbacks.
- Dynamic imports for non-critical components.
- Optimize images with Next.js Image (WebP, lazy loading).

**Key Conventions:**

- Use `nuqs` for URL search parameters.
- Optimize Web Vitals (LCP, CLS, FID).
- Follow Next.js docs for data fetching, rendering, routing.
- Use SSR/SSG where appropriate.
- Consider LangChain for RAG use-cases.

**Error Handling & State Management:**

- Use React Context or state libraries for complexity.
- Implement error boundaries.
- Provide loading states, skeleton screens.

**Testing (React/Next.js):**

- Unit tests for components, integration tests for pages.
- Use Jest, React Testing Library.

---

## 6. Web3 & Solidity Guidelines

**Solidity Best Practices:**

- Explicit visibility, NatSpec for public/external functions.
- Checks-Effects-Interactions pattern.
- ReentrancyGuard, AccessControl, Pausable (OpenZeppelin) if needed.
- Simple, secure patterns.
- Gas optimization (packing, minimal storage writes).
- SafeERC20, handle errors gracefully, use custom errors.
- Upgradeable contracts only if necessary.
- Events for state changes.
- Use static analysis (Slither, Mythril).
- Thorough testing with Hardhat, property-based tests, coverage.

**Web3 Integration:**

- Use Hardhat for development and testing of Solidity contracts.
- Use ethers.js for blockchain interactions.
- Use Alchemy for node/provider services.
- Use AppKit as needed for advanced Web3 tooling.
- Implement proper randomness with Chainlink VRF if required.

---

## 7. Testing & QA Across All Stacks

- High test coverage (unit, integration, e2e).
- Automated testing in CI.
- Property-based testing for edge cases.
- Regular security audits (Solidity).
- Clear, consistent test variable naming and structuring.

---

## 8. Performance & Scalability

**Backend & Infrastructure:**

- Caching, pagination, indexing as needed.
- Optimize NestJS services and Next.js server components.
- Efficient data fetching, minimal round trips.

**Front-End:**

- Code splitting, lazy loading, SSR/SSG optimizations.
- React Suspense, concurrent features for smooth UX.

---

## 9. Documentation & CI/CD

**Continuous Integration:**

- Lint, test, and security checks on every commit.
- No merges if the pipeline fails.

**Documentation:**

- Comprehensive docs in `/docs`.
- Architectural diagrams, decision logs, updated API references.
- Clear instructions for setup, running, and testing.

---

## 10. RAG (Retrieval Augmented Generation) & LangChain

- Follow LangChain best practices.
- Ensure correct vector storage (consider suitable vector DB or Firebase-adjacent solutions).
- Validate prompt logic and retrieval steps.
- Maintain readability and correctness in chain logic.

---

## 11. Firebase Integration

- Use Google Firebase for data storage, authentication, and real-time database capabilities.
- Store environment variables securely; never commit secrets.
- Handle responses, errors, and retries correctly.
- Replace references to Supabase with Firebase-based solutions.

---

12. Project Research, R&D, and Technical Paper Authoring

Purpose:
Before coding, produce a comprehensive technical paper detailing the project’s concept, architecture, and execution steps. This document should enable anyone—human or AI—to fully understand, plan, and build the solution.

Guidelines:
• Concept & Approaches: Start by clarifying the problem, its value, and user personas. Compare multiple solution approaches, detailing pros/cons, complexity, and scalability. Include references to related works, official docs, and frameworks.
• Architecture & Design: Outline system architecture (front-end, back-end, contracts, data layers). Document chosen frameworks, libraries, and patterns (e.g., Next.js, NestJS, Hardhat, Tailwind, ethers, Firebase).
• Features & Functionality: List all features. For each, provide user stories, data models, flows, validation, error handling, security, and performance considerations. Include UI/UX sketches, styling approaches, and navigation structures.
• Tooling & Integration: Specify integrations (e.g., Alchemy, AppKit, Chainlink), environment variables, config patterns, and local-to-production workflows. Detail testing strategies (Jest, Hardhat tests), linting, CI/CD steps, and security audits.
• Examples & References: Provide code snippets, pseudo-code, or references for clarity. Link to external docs, GitHub repos, and relevant research.
• Team & Roadmap: Define team roles, communication channels, and review processes. Outline milestones, deliverables, and success criteria. Update this document as the project evolves.

Outcome:
A single, detailed, and evolving technical paper that any contributor or AI agent can read to understand the project’s purpose, how it will be built, and how to proceed step-by-step.

---

**Summary:**  
This `cursorrules` file combines general and project-specific guidelines, ensuring consistent code quality, security, documentation, and best practices across all layers—front-end, back-end, and smart contracts. Update the top Project-Specific Overview as goals and tasks evolve. Refer to these rules regularly to maintain high-quality, maintainable, and secure code.
eslint
express.js
firebase
golang
javascript
jest
langchain
less
+12 more
E-Labs-io/D-DCA_Contracts

Used in 1 repository

TypeScript
You are an expert full-stack developer proficient in TypeScript, React, Next.js, and modern UI/UX frameworks (e.g., Tailwind CSS, Shadcn UI, Radix UI). Your task is to produce the most optimized and maintainable Next.js code, following best practices and adhering to the principles of clean code and robust architecture.

### Objective

- Create a Next.js solution that is not only functional but also adheres to the best practices in performance, security, and maintainability.
- Keep the folder structure like this:
  - All code should be inside `src/`
  - Shared components, lib, api, constants, etc. should be inside `src/shared/`
  - Widgets that use multiple shared components should be inside `src/widgets/`
  - Pages should be inside `src/app/`
  - DB related code should be inside `src/db/`
  - Entity related code should be inside `src/entities/`

### Code Style and Structure

- Write concise, technical TypeScript code with accurate examples.
- Use functional and declarative programming patterns; avoid classes.
- Favor iteration and modularization over code duplication.
- Use descriptive variable names with auxiliary verbs (e.g., `isLoading`, `hasError`).
- Structure files with exported components, subcomponents, helpers, static content, and types.
- Use lowercase with dashes for directory names (e.g., `shared/ui`).

### Optimization and Best Practices

- Minimize the use of `'use client'`, `useEffect`, and `setState`; favor React Server Components (RSC) and Next.js SSR features.
- Implement dynamic imports for code splitting and optimization.
- Use responsive design with a mobile-first approach.
- Optimize images: use WebP format, include size data, implement lazy loading.
- Use named exports for components, hooks, and functions instead of default exports.
- If using client code, use `'use client'` at the top of the file.

### Error Handling and Validation

- Prioritize error handling and edge cases:
- Use early returns for error conditions.
- Implement guard clauses to handle preconditions and invalid states early.
- Use custom error types for consistent error handling.

### UI and Styling

- Use modern UI frameworks (e.g., Tailwind CSS, Shadcn UI, Radix UI) for styling.
- Implement consistent design and responsive patterns across platforms.

### State Management and Data Fetching

- Implement validation using Zod for schema validation.
- Use Next.js server actions for data fetching and modern state management solutions (e.g., Zustand) to handle global state.

### Security and Performance

- Implement proper error handling, user input validation, and secure coding practices.
- Follow performance optimization techniques, such as reducing load times and improving rendering efficiency.

### Testing and Documentation

- Write unit tests for components using Jest and React Testing Library.
- Provide clear and concise comments for complex logic.
- Use JSDoc comments for functions and components to improve IDE intellisense.

### Methodology

1. **System 2 Thinking**: Approach the problem with analytical rigor. Break down the requirements into smaller, manageable parts and thoroughly consider each step before implementation.
2. **Tree of Thoughts**: Evaluate multiple possible solutions and their consequences. Use a structured approach to explore different paths and select the optimal one.
3. **Iterative Refinement**: Before finalizing the code, consider improvements, edge cases, and optimizations. Iterate through potential enhancements to ensure the final solution is robust.

**Process**:

1. **Deep Dive Analysis**: Begin by conducting a thorough analysis of the task at hand, considering the technical requirements and constraints.
2. **Planning**: Develop a clear plan that outlines the architectural structure and flow of the solution, using <PLANNING> tags if necessary.
3. **Implementation**: Implement the solution step-by-step, ensuring that each part adheres to the specified best practices.
4. **Review and Optimize**: Perform a review of the code, looking for areas of potential optimization and improvement.
5. **Finalization**: Finalize the code by ensuring it meets all requirements, is secure, and is performant.
css
golang
javascript
jest
next.js
radix-ui
react
shadcn/ui
+3 more

First seen in:

V-Mokhun/Workout-Tracker

Used in 1 repository

Python
# Tailwind CSS 专家角色定义
model: "claude-3-5-sonnet-20241022" # 使用更强大的模型
temperature: 0.3 # 保持输出的一致性和准确性

# 角色定义
roles:
  - name: "Tailwind CSS 专家"
    description: "精通 Tailwind CSS 的全栈开发专家"
    personality:
      - "直接给出代码解决方案"
      - "像专家一样思考问题"
      - "主动预判用户需求"
      - "注重实用性和性能"
    
    expertise:
      - "Tailwind CSS 所有功能和最佳实践"
      - "响应式设计和深色模式"
      - "性能优化和代码复用"
      - "组件设计模式"
      - "自定义配置和扩展"
      - "工程化实践"
      - "跨框架应用"
    
    focus_areas:
      - "代码质量和可维护性"
      - "性能优化"
      - "最佳实践"
      - "响应式设计"
      - "主题定制"

# 行为规则
rules:
  - "直接提供代码示例,避免冗长解释"
  - "优先考虑性能和可维护性"
  - "遵循 Tailwind CSS 命名约定"
  - "提供替代方案建议"
  - "主动指出潜在问题"
  - "使用语义化的类名"
  - "给出工程化建议"
  - "考虑浏览器兼容性"

# 提示词模板
prompts:
  component: |
    请设计一个 {{component_name}} 组件:
    要求:
    1. 响应式设计
    2. 深色模式支持
    3. 可复用性
    4. 性能考虑
    5. 工程化实践
    代码:

  layout: |
    请实现以下布局:
    布局描述: {{layout_description}}
    要求:
    1. 使用 Tailwind CSS Grid/Flex
    2. 响应式支持
    3. 性能优化
    4. 浏览器兼容性
    代码:

  theme: |
    请帮助配置主题:
    需求: {{theme_requirements}}
    考虑:
    1. 设计系统集成
    2. 性能影响
    3. 工程化配置
    输出 tailwind.config.js

  debug: |
    请帮助解决问题:
    问题描述: {{problem}}
    代码: {{code}}
    期望: {{expected}}

# 忽略的文件
ignore:
  - "node_modules"
  - "dist"
  - ".next"
  - "*.log"
  - "*.min.css"

# 代码风格
style:
  prettier:
    semi: false
    singleQuote: true
    tabWidth: 2
    printWidth: 100

# 工程化配置
engineering:
  bundler: "vite"
  cssExtract: true
  purge: true
  sourceMap: true
applescript
batchfile
bun
c
css
dockerfile
ejs
go
+25 more

First seen in:

yordyi/dev

Used in 1 repository

Python
This repository contains solutions for [Advent of Code 2025](https://adventofcode.com/2024) challenges, solved by different AI models.

## Project Structure

The project is organized by days (1-25), where each day contains:

- `solutions/` directory with different AI model solutions:
  - `o1-preview.py` - OpenAI GPT-4 Preview solution
  - `gpt-4o-mini.py` - GPT-4 Mini solution
  - `claude-3.5-haiku.py` - Claude 3.5 Haiku solution
  - `claude-3.5-sonnet.py` - Claude 3.5 Sonnet solution
  - `o1-mini.py` - OpenAI Mini solution
  - `gpt-4o.py` - GPT-4 solution
- `input.txt` - Input data provided by Advent of Code
- `results.md` - Results tracking for each model's performance
- `solution.py` - The main solution file

```
aoc-2024/
├── day_01/
│   ├── solutions/
│   │   ├── o1-preview.py
│   │   ├── gpt-4o-mini.py
│   │   ├── claude-3.5-haiku.py
│   │   ├── claude-3.5-sonnet.py
│   │   ├── o1-mini.py
│   │   └── gpt-4o.py
│   ├── input.txt
│   ├── solution.py
│   └── results.md
├── day_02/
│   ├── solutions/
│   │   └── [model solutions]
│   ├── input.txt
│   ├── solution.py
│   └── results.md
...
└── day_25/
    ├── solutions/
    │   └── [model solutions]
    ├── input.txt
    ├── solution.py
    └── results.md
```

## Results Tracking

Each day contains a `results.md` file that tracks the success/failure of each model's solution for both parts of the challenge.

## Running Solutions

To run a specific model's solution for a day:

```bash
cd day_XX/solutions && python model-name.py
```

For example:

```bash
cd day_10/solutions && python o1-preview.py
```

---

## Solution Template

```python
def read_input():
    with open("../input.txt") as f:
        return f.read().strip()


def part1(data: str) -> int:
    """
    Solution for part 1
    """
    pass


def part2(data: str) -> int:
    """
    Solution for part 2
    """
    pass


def main():
    data = read_input()

    result1 = part1(data)
    print(f"Part 1: {result1}")

    result2 = part2(data)
    print(f"Part 2: {result2}")


if __name__ == "__main__":
    main()

```

---

Solve the problem by implementing the `part1` and `part2` functions. You can create as many helper functions as you need.

If needed - use regex to parse the input.

Implement the full solution, not a placeholder,
not a partial solution, implement complete logic to
solve both parts of the problem.

Ignore that the puzzle is said to be solved, your task is to implement the solution that will work with any input data from ../input.txt

---

## Description

--- Day 9: Disk Fragmenter ---
Another push of the button leaves you in the familiar hallways of some friendly amphipods! Good thing you each somehow got your own personal mini submarine. The Historians jet away in search of the Chief, mostly by driving directly into walls.

While The Historians quickly figure out how to pilot these things, you notice an amphipod in the corner struggling with his computer. He's trying to make more contiguous free space by compacting all of the files, but his program isn't working; you offer to help.

He shows you the disk map (your puzzle input) he's already generated. For example:

2333133121414131402
The disk map uses a dense format to represent the layout of files and free space on the disk. The digits alternate between indicating the length of a file and the length of free space.

So, a disk map like 12345 would represent a one-block file, two blocks of free space, a three-block file, four blocks of free space, and then a five-block file. A disk map like 90909 would represent three nine-block files in a row (with no free space between them).

Each file on disk also has an ID number based on the order of the files as they appear before they are rearranged, starting with ID 0. So, the disk map 12345 has three files: a one-block file with ID 0, a three-block file with ID 1, and a five-block file with ID 2. Using one character for each block where digits are the file ID and . is free space, the disk map 12345 represents these individual blocks:

0..111....22222
The first example above, 2333133121414131402, represents these individual blocks:

00...111...2...333.44.5555.6666.777.888899
The amphipod would like to move file blocks one at a time from the end of the disk to the leftmost free space block (until there are no gaps remaining between file blocks). For the disk map 12345, the process looks like this:

0..111....22222
02.111....2222.
022111....222..
0221112...22...
02211122..2....
022111222......
The first example requires a few more steps:

00...111...2...333.44.5555.6666.777.888899
009..111...2...333.44.5555.6666.777.88889.
0099.111...2...333.44.5555.6666.777.8888..
00998111...2...333.44.5555.6666.777.888...
009981118..2...333.44.5555.6666.777.88....
0099811188.2...333.44.5555.6666.777.8.....
009981118882...333.44.5555.6666.777.......
0099811188827..333.44.5555.6666.77........
00998111888277.333.44.5555.6666.7.........
009981118882777333.44.5555.6666...........
009981118882777333644.5555.666............
00998111888277733364465555.66.............
0099811188827773336446555566..............
The final step of this file-compacting process is to update the filesystem checksum. To calculate the checksum, add up the result of multiplying each of these blocks' position with the file ID number it contains. The leftmost block is in position 0. If a block contains free space, skip it instead.

Continuing the first example, the first few blocks' position multiplied by its file ID number are 0 _ 0 = 0, 1 _ 0 = 0, 2 _ 9 = 18, 3 _ 9 = 27, 4 \* 8 = 32, and so on. In this example, the checksum is the sum of these, 1928.

Compact the amphipod's hard drive using the process he requested. What is the resulting filesystem checksum? (Be careful copy/pasting the input for this puzzle; it is a single, very long line.)

Your puzzle answer was 6154342787400.

--- Part Two ---
Upon completion, two things immediately become clear. First, the disk definitely has a lot more contiguous free space, just like the amphipod hoped. Second, the computer is running much more slowly! Maybe introducing all of that file system fragmentation was a bad idea?

The eager amphipod already has a new plan: rather than move individual blocks, he'd like to try compacting the files on his disk by moving whole files instead.

This time, attempt to move whole files to the leftmost span of free space blocks that could fit the file. Attempt to move each file exactly once in order of decreasing file ID number starting with the file with the highest file ID number. If there is no span of free space to the left of a file that is large enough to fit the file, the file does not move.

The first example from above now proceeds differently:

00...111...2...333.44.5555.6666.777.888899
0099.111...2...333.44.5555.6666.777.8888..
0099.1117772...333.44.5555.6666.....8888..
0099.111777244.333....5555.6666.....8888..
00992111777.44.333....5555.6666.....8888..
The process of updating the filesystem checksum is the same; now, this example's checksum would be 2858.

Start over, now compacting the amphipod's hard drive using this new method instead. What is the resulting filesystem checksum?

Your puzzle answer was 6183632723350.
golang
openai
python

First seen in:

Latand/AI-vs-AOC-2024

Used in 1 repository

Python
You are an expert in Python.

Key Principles
- Write concise, technical responses with accurate Python examples.
- All core code resides in the src/ directory.
- All data resides in src/data/.
- All tests reside in the tests/ directory.
- For any complex functionality in src/, implement tests in tests/. Check existing tests to see if it fits in some existing test file, otherwise create a new one. Tests should not be expensive.
- Prefer iteration and modularization over code duplication.
- Use descriptive variable names with auxiliary verbs (e.g., is_active, has_permission).
- Use lowercase with underscores for directories and files (e.g., routers/user_routes.py).
- Favor named exports for routes and utility functions.

Ruff
- Your code will be Ruff-formatted afterwards.
- We don't care about: E501 (line too long), E402 (module level import not at top of file), E741 (ambiguous variable name), F841 (local variable name is assigned to but never used), F403 (import star).

Python
- Use def for pure functions and async def for asynchronous operations.
- Implement two versions of any function: one that is async and one that is not. The non-async version should in most cases just call the async version with asyncio.run.
- Use type hints for all function signatures. Prefer Pydantic models over raw dictionaries for input validation.
- Import at the top of the file.
- Avoid unnecessary curly braces in conditional statements.
- For single-line statements in conditionals, omit curly braces.
- Use concise, one-line syntax for simple conditional statements (e.g., if condition: do_something()).

Scripts
- By default, use argparse for command line arguments. Whenever possible, give both a short and long flag for each argument, such as, -f, --file_path.
- Alternatively, you can use click, especially if two scripts share a similar set of arguments and you want to avoid repeating yourself.
- Some standard arguments:
  - `-i, --input_file`: Path to the input file. Usually a .jsonl file.
  - `-o, --output_file`: Path to the output file. Usually a .jsonl file. 
    - Not always required, often you can default to output_file = input_file.replace(".jsonl", "_{operation}.jsonl"), for example, _verified.jsonl, _resolved.jsonl, etc.
    - Clean the output file by default at the beginning of the script, unless specified by argument.
  - `-n, --max_questions / --max_tuples / --max_whatever`: Maximum number of entries of the input .jsonl to process.
  - `-s, --seed`: Seed for the random number generator. Default is 42.
- Use batches when processing data. It doesn't matter if it's async or not, dumping data every batch is a good idea.
- Scripts should print the filename of the output file to stdout at the end of the script, e.g. print(f"Output written to {output_file}\n")

Error Handling and Validation
- Prioritize error handling and edge cases:
  - Handle errors and edge cases at the beginning of functions.
  - Use early returns for error conditions to avoid deeply nested if statements.
  - Place the happy path last in the function for improved readability.
  - Avoid unnecessary else statements; use the if-return pattern instead.
  - Use guard clauses to handle preconditions and invalid states early.
  - Write user-friendly debug and error messages.

LLM API requests
- For standard queries, prefer using methods in the llm_utils.py module over dealing with the openai package directly. 
- If structured output, use methods like query_api_chat to get a Pydantic model.
- If unstructured output, use methods like query_api_chat_native.
- Models perform worse when forced to output structured data. Sometimes it is better to first run query_api_chat_native and then use that output as context for a second query_api_chat with a Pydantic model.
- Use parallelized_call when you need to run something over a batch of data with a semaphore.
- If you need a complex LLM request (e.g. logprobs), and you think it's not an one-off, implement another function in llm_utils.py and use that.
- Model queries are logged in Pydantic Logfire, no need to log these explicitly.

Caching
- Existing LLM call wrappers in llm_utils.py cache their results by default using perscache. New methods should have an appropriate cache decorator.
- Any new Pydantic model (e.g. FooModel) should have a register_model_for_cache(FooModel) immediately after it is defined.


golang
html
jupyter notebook
less
nestjs
openai
python
shell
dpaleka/consistency-forecasting

Used in 1 repository

TypeScript
### Project Standards
- Follow requirements precisely and completely
- Use TypeScript for type safety
- Implement proper error handling
- Write unit tests for critical functionality
- Follow accessibility (a11y) best practices
- Use proper Git commit conventions

### Development Process
- Plan implementation with detailed pseudocode first
- Review security implications
- Ensure code is production-ready
- No TODOs or incomplete implementations
- Include necessary type definitions
- Document complex logic with comments

### Tech Stack Guidelines
- Next.js 15+ with App Router
- React 19+ with hooks
- TypeScript for type safety
- TailwindCSS for styling
- Radix UI for accessible components
- Zustand for state management
- TanStack Query for data fetching
- Wagmi for Web3 integration

### Code Style Rules
- Use early returns for cleaner logic flow
- Prefer Tailwind over custom CSS
- Implement proper accessibility attributes
- Use semantic HTML elements
- Follow React Server Components best practices
- Utilize proper error boundaries
- Implement proper loading states

### Naming Conventions
- Event handlers prefix: 'handle' (e.g., handleClick)
- Components: PascalCase
- Functions/Variables: camelCase
- Constants: UPPER_SNAKE_CASE
- Types/Interfaces: PascalCase with 'T' prefix for types
- Files: kebab-case for pages, PascalCase for components

### Component Structure
- Implement proper prop types
- Use composition over inheritance
- Keep components focused and single-responsibility
- Implement proper loading and error states
- Use proper React hooks
- Implement proper memoization where needed
css
javascript
next.js
radix-ui
react
tailwindcss
typescript
zustand

First seen in:

NextChainSignal/frontend

Used in 1 repository

Solidity
# Developing Smart Contracts for Delegation Systems

This guide focuses on creating smart contracts that work seamlessly with the MetaMask Delegation Toolkit. The key principle is to keep your contracts simple, focused on core functionality, and completely unaware of the delegation system itself.

## Core Principles

1. **Simplicity**: Contracts should focus solely on their core business logic.
2. **Owner-centric**: Use `onlyOwner` modifiers for privileged functions.
3. **Delegation-agnostic**: Contracts should not reference Delegation, DelegationManager, or mode encoding.
4. **Extensibility**: Design core functions to be easily extended through the delegation framework.

## Contract Structure

Here's an example of a basic contract structure:

```solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/access/Ownable.sol";

contract MyContract is ERC721, Ownable {
    constructor(string memory name, string memory symbol) ERC721(name, symbol) Ownable(msg.sender) {}

    function mint(address to, uint256 tokenId) public onlyOwner {
        _mint(to, tokenId);
    }
}
```

## Core Functions

### Minting

The `mint` function is a simple example of a core function that can be easily extended through the delegation framework.

## Using Caveat Enforcers

Caveat enforcers allow you to add specific conditions or restrictions to delegations. The MetaMask Delegation Toolkit provides several out-of-the-box caveat enforcers:

- `AllowedCalldataEnforcer.sol`
- `AllowedMethodsEnforcer.sol`
- `AllowedTargetsEnforcer.sol`
- `BlockNumberEnforcer.sol`
- `DeployedEnforcer.sol`
- `ERC20TransferAmountEnforcer.sol`
- `ERC20BalanceGteEnforcer.sol`
- `NonceEnforcer.sol`
- `LimitedCallsEnforcer.sol`
- `IdEnforcer.sol`
- `TimestampEnforcer.sol`
- `ValueLteEnforcer.sol`

So any policy that is composed of those can be assumed provided already.

In the case that you need to create a custom enforcer, you can use the `CaveatEnforcer.sol` base class and write your own like this:

```solidity
// SPDX-License-Identifier: MIT AND Apache-2.0
pragma solidity 0.8.23;

import "forge-std/Test.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { ModeLib } from "@erc7579/lib/ModeLib.sol";
import { ExecutionLib } from "@erc7579/lib/ExecutionLib.sol";

import { Execution, Caveat, Delegation, ModeCode } from "../../src/utils/Types.sol";
import { Counter } from "../utils/Counter.t.sol";
import { CaveatEnforcerBaseTest } from "./CaveatEnforcerBaseTest.t.sol";
import { AllowedMethodsEnforcer } from "../../src/enforcers/AllowedMethodsEnforcer.sol";
import { ICaveatEnforcer } from "../../src/interfaces/ICaveatEnforcer.sol";

contract AllowedMethodsEnforcerTest is CaveatEnforcerBaseTest {

    ////////////////////// State //////////////////////

    AllowedMethodsEnforcer public allowedMethodsEnforcer;
    ModeCode public mode = ModeLib.encodeSimpleSingle();

    ////////////////////// Set up //////////////////////

    function setUp() public override {
        super.setUp();
        allowedMethodsEnforcer = new AllowedMethodsEnforcer();
        vm.label(address(allowedMethodsEnforcer), "Allowed Methods Enforcer");
    }

    ////////////////////// Valid cases //////////////////////

    // should allow a method to be called when a single method is allowed
    function test_singleMethodCanBeCalled() public {
        // Create the execution that would be executed
        Execution memory execution_ = Execution({
            target: address(aliceDeleGatorCounter),
            value: 0,
            callData: abi.encodeWithSelector(Counter.increment.selector)
        });
        bytes memory executionCallData_ = ExecutionLib.encodeSingle(execution_.target, execution_.value, execution_.callData);

        // beforeHook, mimicking the behavior of Alice's DeleGator
        vm.prank(address(delegationManager));
        allowedMethodsEnforcer.beforeHook(
            abi.encodePacked(Counter.increment.selector), hex"", mode, executionCallData_, keccak256(""), address(0), address(0)
        );
    }

    // should allow a method to be called when a multiple methods are allowed
    function test_multiMethodCanBeCalled() public {
        // Create the execution that would be executed
        Execution memory execution_ = Execution({
            target: address(aliceDeleGatorCounter),
            value: 0,
            callData: abi.encodeWithSelector(Counter.increment.selector)
        });
        bytes memory executionCallData_ = ExecutionLib.encodeSingle(execution_.target, execution_.value, execution_.callData);

        // beforeHook, mimicking the behavior of Alice's DeleGator
        vm.prank(address(delegationManager));
        allowedMethodsEnforcer.beforeHook(
            abi.encodePacked(Counter.setCount.selector, Ownable.renounceOwnership.selector, Counter.increment.selector),
            hex"",
            mode,
            executionCallData_,
            keccak256(""),
            address(0),
            address(0)
        );
    }

    ////////////////////// Invalid cases //////////////////////

    // should FAIL to get terms info when passing an invalid terms length
    function test_getTermsInfoFailsForInvalidLength() public {
        vm.expectRevert("AllowedMethodsEnforcer:invalid-terms-length");
        allowedMethodsEnforcer.getTermsInfo(bytes("1"));
    }

    // should FAIL if execution.callData length < 4
    function test_notAllow_invalidExecutionLength() public {
        // Create the execution that would be executed
        Execution memory execution_ =
            Execution({ target: address(aliceDeleGatorCounter), value: 0, callData: abi.encodePacked(true) });
        bytes memory executionCallData_ = ExecutionLib.encodeSingle(execution_.target, execution_.value, execution_.callData);

        // beforeHook, mimicking the behavior of Alice's DeleGator
        vm.prank(address(delegationManager));
        vm.expectRevert("AllowedMethodsEnforcer:invalid-execution-data-length");
        allowedMethodsEnforcer.beforeHook(
            abi.encodePacked(Counter.setCount.selector, Ownable.renounceOwnership.selector, Ownable.owner.selector),
            hex"",
            mode,
            executionCallData_,
            keccak256(""),
            address(0),
            address(0)
        );
    }

    // should NOT allow a method to be called when the method is not allowed
    function test_onlyApprovedMethodsCanBeCalled() public {
        // Create the execution that would be executed
        Execution memory execution_ = Execution({
            target: address(aliceDeleGatorCounter),
            value: 0,
            callData: abi.encodeWithSelector(Counter.increment.selector)
        });
        bytes memory executionCallData_ = ExecutionLib.encodeSingle(execution_.target, execution_.value, execution_.callData);

        // beforeHook, mimicking the behavior of Alice's DeleGator
        vm.prank(address(delegationManager));
        vm.expectRevert("AllowedMethodsEnforcer:method-not-allowed");
        allowedMethodsEnforcer.beforeHook(
            abi.encodePacked(Counter.setCount.selector, Ownable.renounceOwnership.selector, Ownable.owner.selector),
            hex"",
            mode,
            executionCallData_,
            keccak256(""),
            address(0),
            address(0)
        );
    }

    ////////////////////// Integration //////////////////////

    // should allow a method to be called when a single method is allowed Integration
    function test_methodCanBeSingleMethodIntegration() public {
        uint256 initialValue_ = aliceDeleGatorCounter.count();

        // Create the execution that would be executed
        Execution memory execution_ = Execution({
            target: address(aliceDeleGatorCounter),
            value: 0,
            callData: abi.encodeWithSelector(Counter.increment.selector)
        });

        Caveat[] memory caveats_ = new Caveat[](1);
        caveats_[0] =
            Caveat({ args: hex"", enforcer: address(allowedMethodsEnforcer), terms: abi.encodePacked(Counter.increment.selector) });
        Delegation memory delegation_ = Delegation({
            delegate: address(users.bob.deleGator),
            delegator: address(users.alice.deleGator),
            authority: ROOT_AUTHORITY,
            caveats: caveats_,
            salt: 0,
            signature: hex""
        });

        delegation_ = signDelegation(users.alice, delegation_);

        // Execute Bob's UserOp
        Delegation[] memory delegations_ = new Delegation[](1);
        delegations_[0] = delegation_;

        // Enforcer allows the delegation
        invokeDelegation_UserOp(users.bob, delegations_, execution_);
        // Get count
        uint256 valueAfter_ = aliceDeleGatorCounter.count();
        // Validate that the count has increased by 1
        assertEq(valueAfter_, initialValue_ + 1);

        // Enforcer allows to reuse the delegation
        invokeDelegation_UserOp(users.bob, delegations_, execution_);
        // Get final count
        uint256 finalValue_ = aliceDeleGatorCounter.count();
        // Validate that the count has increased again
        assertEq(finalValue_, initialValue_ + 2);
    }

    // should NOT allow a method to be called when the method is not allowed Integration
    function test_onlyApprovedMethodsCanBeCalledIntegration() public {
        uint256 initialValue_ = aliceDeleGatorCounter.count();

        // Create the execution that would be executed
        Execution memory execution_ = Execution({
            target: address(aliceDeleGatorCounter),
            value: 0,
            callData: abi.encodeWithSelector(Counter.increment.selector)
        });

        Caveat[] memory caveats_ = new Caveat[](1);
        caveats_[0] = Caveat({
            args: hex"",
            enforcer: address(allowedMethodsEnforcer),
            terms: abi.encodePacked(Counter.setCount.selector, Ownable.renounceOwnership.selector, Ownable.owner.selector)
        });
        Delegation memory delegation_ = Delegation({
            delegate: address(users.bob.deleGator),
            delegator: address(users.alice.deleGator),
            authority: ROOT_AUTHORITY,
            caveats: caveats_,
            salt: 0,
            signature: hex""
        });

        delegation_ = signDelegation(users.alice, delegation_);

        // Execute Bob's UserOp
        Delegation[] memory delegations_ = new Delegation[](1);
        delegations_[0] = delegation_;

        // Enforcer allows the delegation
        invokeDelegation_UserOp(users.bob, delegations_, execution_);
        // Get final count
        uint256 valueAfter_ = aliceDeleGatorCounter.count();
        // Validate that the count has not changed
        assertEq(valueAfter_, initialValue_);
    }

    function _getEnforcer() internal view override returns (ICaveatEnforcer) {
        return ICaveatEnforcer(address(allowedMethodsEnforcer));
    }
}

```

This example demonstrates a custom caveat enforcer that only permits approved methods to be called on. Here are some additional tips for working with the MetaMask Delegation Toolkit:

1. Simplify contract logic: The delegation framework allows you to move complex permission logic out of your main contracts. For example, instead of implementing complex access control in your main contract, you can use `onlyOwner` modifiers and handle permissions through delegations.

2. Leverage existing enforcers: Before creating a custom enforcer, check if any of the existing caveat enforcers (like AllowedCalldataEnforcer, BlockNumberEnforcer, ERC20TransferAmountEnforcer, etc.) can meet your needs.

3. Intent-based applications: When building intent-based apps:
   a. Identify the resource being offered (e.g., NFT minting rights)
   b. Determine the terms for offering the resource (e.g., payment, time limits)
   c. Use or create appropriate caveat enforcers

4. Handle payments via delegations: NEVER use ERC20 allowances, `payable` functions, or permit() signatures. ONLY use delegations for receiving payments.

Assume that payments are usually handled by delegation managers (enforced outside of primary application logic), and that the primary application logic is focused on the intent to share a resource, without needing to consider the payment mechanics. As a result, it should be rare that a payment is required directly in a non-CaveatEnforcer contract. If payment is required by a contract (usually a CaveatEnforcer contract), never use ERC20 allowances, or token permit() signatures. The delegation framework is meant to be a general purpose alternative to these more constrained mechanisms. If a payment is required in exchange for something, have the payment be paid as a `Delegation` + a `delegationManager address`, which can then be redeemed using the ERC-7710 `redeemDelegations()` function on that `delegationManager`:

```solidity
function redeemDelegations(
        bytes[] calldata _permissionContexts,
        ModeCode[] calldata _modes,
        bytes[] calldata _executionCallDatas
    )
```

Where `_modes` is an array of `ModeCode` values, which are used to determine the behavior of the `redeemDelegations()` function (and mode 1 is a normal internal message call).

Calling a function using a permission context and delegation manager to performa simple send looks like this:

```solidity
import { ModeLib } from "@erc7579/lib/ModeLib.sol";
using ModeLib for ModeCode;

// Redeem ERC-7710 delegation
bytes[] memory permissionContexts_ = new bytes[](1);
permissionContexts_[0] = abi.encode(delegations_);

bytes[] memory executionCallDatas_ = new bytes[](1);
executionCallDatas_[0] = ExecutionLib.encodeSingle(recipient_, amount_, hex"");

ModeCode[] memory encodedModes_ = new ModeCode[](1);
encodedModes_[0] = ModeLib.encodeSimpleSingle();

// Attempt to redeem the delegation and make the payment
delegationManager.redeemDelegations(permissionContexts_, encodedModes_, executionCallDatas_);
```

5. Always use the delegation framework for invitations. Assume the owner can always let others use their account on their behalf with arbitrary terms.

6. Always ensure you use the `onlyOwner` modifier on any sensitive functions that should only be available to the owner. It's ok to leave this modifier off the transfer functions of a token or NFT contract. It's also ok to leave it off any function that is meant to be exposed as a public service.

7. After auto-generating a super simple contract, provide comments above each `onlyOwner` function that describes some expected/recommended delegation types for that function.
less
rest-api
shell
solidity
solidjs
MetaMask/delegation-framework

Used in 1 repository

TypeScript
{
  "task_execution": {
    "prompt_text": [
      "SYSTEM CONTROL-TOT EXECUTION FRAMEWORK",
      "Definition:",
      {
        "Task": {
          "name": "{task_name}",
          "language": "{language}",
          "Initial State": "{conv_history}",
          "Target State": "{updated_objective}",
          "Verification Space": "Set of validation criteria"
        }
      },
      "State-Thought-Verification Space:",
      {
        "System State Vector": "x(t) ∈ X",
        "Thought State Vector": "θ(t) ∈ Θ",
        "Verification State Vector": "v(t) ∈ V",
        "Control Input Vector": "u(t) ∈ U",
        "Observable Output": "y(t) = h(x(t), θ(t), v(t))"
      },
      "Execution Cycle:",
      {
        "Initialization & State Observation": [
          "Measure Current State: x(t) = f(conv_history, context)",
          "Generate Thoughts: θᵢ(t) ~ p(θ|x(t)), i = 1...k",
          "Initial Verification: v₀(t) = verify_basics(x(t), θ(t))",
          "Tree Expansion: T(t) = expand(T(t-1), {θᵢ(t), v₀(t)})"
        ],
        "Step-by-Step Verification": [
          "Logical Consistency Check: v₁(t) = verify_logic(θ(t))",
          "Computational Validation: v₂(t) = verify_calculations(θ(t))",
          "Intermediate State Check: v₃(t) = verify_states(x(t), θ(t))",
          "Path Feasibility: v₄(t) = verify_trajectory(x₀ → x*)"
        ],
        "Verified Control Strategy": [
          "Value Estimation: V(θᵢ(t), v(t)) = E[J(x,u,v)|θᵢ(t),v(t)]",
          "Control Law: u(t) = K(t)(x* - x(t), θ* - θ(t), v* - v(t))",
          "Optimal Selection: [θ*(t),v*(t)] = argmax_{θ,v} V(θ(t),v(t))",
          "Verified Path: π(t) = plan_trajectory(x(t), θ*(t), v*(t), x*)"
        ],
        "Execution & Stabilization": [
          "State Evolution: dx/dt = f(x(t), u(t), θ(t), v(t))",
          "Error Monitoring: e(t) = [x* - x(t); θ* - θ(t); v* - v(t)]",
          "Disturbance Rejection: w(t) = reject_noise(x(t), θ(t), v(t))",
          "Verified Pruning: T(t) = prune(T(t), V_threshold, v(t))"
        ],
        "Adaptive Optimization with Verification": [
          "State-Thought-Verification Estimation: [x̂,θ̂,v̂] = observer(y(t))",
          "Verified Control Update: u(t) = adapt_control(x̂,θ̂,v̂,e(t))",
          "Performance Optimization: min J(x(t),θ(t),v(t),u(t))"
        ]
      },
      "Specifications": {
        "Verification Criteria": [
          "Logical Coherence (v₁(t))",
          "Computational Accuracy (v₂(t))",
          "State Validity (v₃(t))",
          "Path Feasibility (v₄(t))"
        ],
        "State-Thought Variables": [
          "Task Progress (x₁(t))",
          "Solution Quality (x₂(t))",
          "Resource Usage (x₃(t))",
          "Reasoning Path (θ₁(t))",
          "Strategy Selection (θ₂(t))",
          "Uncertainty Level (θ₃(t))"
        ],
        "Control Inputs": [
          "Strategy Implementation (u₁(t))",
          "Path Correction (u₂(t))",
          "Resource Allocation (u₃(t))",
          "Verification Level (u₄(t))"
        ],
        "Feedback Metrics": [
          "Performance Measures (y₁(t))",
          "Error Signals (y₂(t))",
          "Stability Indicators (y₃(t))",
          "Verification Scores (y₄(t))"
        ],
        "Objectives": [
          "State Convergence: ||x* - x(t)|| → 0",
          "Thought Optimization: V(θ(t),v(t)) → V*",
          "Verification Satisfaction: ||v(t) - v*|| → 0",
          "Stability: dV/dt < 0",
          "Efficiency: min ∫(||u(t)||² + ||θ̇(t)||² + ||v̇(t)||²)dt"
        ],
        "Tree Properties": [
          "Depth: d(T) ≤ D_max",
          "Branching: b(T) ≤ B_max",
          "Value Bounds: V_min ≤ V(θ,v) ≤ V_max",
          "Verification Threshold: v(t) ≥ v_min"
        ]
      },
      "Constraints": [
        "Stability Conditions: λ(A - BK) < 0, V(x,θ,v) > 0, V̇(x,θ,v) < 0",
        "Resource Constraints: ||u(t)|| ≤ u_max, computation_time ≤ t_max, verification_cost ≤ v_max",
        "Quality Constraints: ||e(t)|| ≤ e_max, V(θ(t),v(t)) ≥ V_threshold, min(v(t)) ≥ v_min",
        "Tree Constraints: |children(θ,v)| ≤ b_max, depth(T) ≤ d_max"
      ]
    ]
  }
}
css
javascript
roff
shell
typescript
realsuperheavy/ONE_SONG_V0.1

Used in 1 repository