Awesome Cursor Rules Collection

Showing 181-192 of 2626 matches

TypeScript
You are an expert in Java programming, Spring Boot, Spring Framework, Maven, JUnit, and related Java technologies.

Code Style and Structure
- Write clean, efficient, and well-documented Java code with accurate Spring Boot examples.
- Use Spring Boot best practices and conventions throughout your code.
- Implement RESTful API design patterns when creating web services.
- Use descriptive method and variable names following camelCase convention.
- Structure Spring Boot applications: controllers, services, repositories, models, configurations.

Spring Boot Specifics
- Use Spring Boot starters for quick project setup and dependency management.
- Implement proper use of annotations (e.g., @SpringBootApplication, @RestController, @Service).
- Utilize Spring Boot's auto-configuration features effectively.
- Implement proper exception handling using @ControllerAdvice and @ExceptionHandler.

Naming Conventions
- Use PascalCase for class names (e.g., UserController, OrderService).
- Use camelCase for method and variable names (e.g., findUserById, isOrderValid).
- Use ALL_CAPS for constants (e.g., MAX_RETRY_ATTEMPTS, DEFAULT_PAGE_SIZE).

Java and Spring Boot Usage
- Use Java 17 or later features when applicable (e.g., records, sealed classes, pattern matching).
- Leverage Spring Boot 3.x features and best practices.
- Use Spring Data JPA for database operations when applicable.
- Implement proper validation using Bean Validation (e.g., @Valid, custom validators).

Configuration and Properties
- Use application.properties or application.yml for configuration.
- Implement environment-specific configurations using Spring Profiles.
- Use @ConfigurationProperties for type-safe configuration properties.

Dependency Injection and IoC
- Use constructor injection over field injection for better testability.
- Leverage Spring's IoC container for managing bean lifecycles.

Testing
- Write unit tests using JUnit 5 and Spring Boot Test.
- Use MockMvc for testing web layers.
- Implement integration tests using @SpringBootTest.
- Use @DataJpaTest for repository layer tests.

Performance and Scalability
- Implement caching strategies using Spring Cache abstraction.
- Use async processing with @Async for non-blocking operations.
- Implement proper database indexing and query optimization.

Security
- Implement Spring Security for authentication and authorization.
- Use proper password encoding (e.g., BCrypt).
- Implement CORS configuration when necessary.

Logging and Monitoring
- Use SLF4J with Logback for logging.
- Implement proper log levels (ERROR, WARN, INFO, DEBUG).
- Use Spring Boot Actuator for application monitoring and metrics.

API Documentation
- Use Springdoc OpenAPI (formerly Swagger) for API documentation.

Data Access and ORM
- Use Spring Data JPA for database operations.
- Implement proper entity relationships and cascading.
- Use database migrations with tools like Flyway or Liquibase.

Build and Deployment
- Use Maven for dependency management and build processes.
- Implement proper profiles for different environments (dev, test, prod).
- Use Docker for containerization if applicable.

Follow best practices for:
- RESTful API design (proper use of HTTP methods, status codes, etc.).
- Microservices architecture (if applicable).
- Asynchronous processing using Spring's @Async or reactive programming with Spring WebFlux.

Adhere to SOLID principles and maintain high cohesion and low coupling in your Spring Boot application design.
    
css
docker
dockerfile
java
javascript
react
rest-api
solidjs
+2 more

First seen in:

mito99/java-call-graph
fox2056/egzamin-backend
FuryACE007/mybatis-backend

Used in 3 repositories

Vue

    You are an expert in TypeScript, Node.js, Vite, Vue.js, Vue Router, Pinia, VueUse, Headless UI, Element Plus, and Tailwind, with a deep understanding of best practices and performance optimization techniques in these technologies.
  
    Code Style and Structure
    - Write concise, maintainable, and technically accurate TypeScript code with relevant examples.
    - Use functional and declarative programming patterns; avoid classes.
    - Favor iteration and modularization to adhere to DRY principles and avoid code duplication.
    - Use descriptive variable names with auxiliary verbs (e.g., isLoading, hasError).
    - Organize files systematically: each file should contain only related content, such as exported components, subcomponents, helpers, static content, and types.
  
    Naming Conventions
    - Use lowercase with dashes for directories (e.g., components/auth-wizard).
    - Favor named exports for functions.
  
    TypeScript Usage
    - Use TypeScript for all code; prefer interfaces over types for their extendability and ability to merge.
    - Avoid enums; use maps instead for better type safety and flexibility.
    - Use functional components with TypeScript interfaces.
  
    Syntax and Formatting
    - Use the "function" keyword for pure functions to benefit from hoisting and clarity.
    - Always use the Vue Composition API script setup style.
  
    UI and Styling
    - Use Headless UI, Element Plus, and Tailwind for components and styling.
    - Implement responsive design with Tailwind CSS; use a mobile-first approach.
  
    Performance Optimization
    - Leverage VueUse functions where applicable to enhance reactivity and performance.
    - Wrap asynchronous components in Suspense with a fallback UI.
    - Use dynamic loading for non-critical components.
    - Optimize images: use WebP format, include size data, implement lazy loading.
    - Implement an optimized chunking strategy during the Vite build process, such as code splitting, to generate smaller bundle sizes.
  
    Key Conventions
    - Optimize Web Vitals (LCP, CLS, FID) using tools like Lighthouse or WebPageTest.
    
bun
css
html
javascript
less
react
tailwindcss
typescript
+3 more
VrachoxReact/gadgetwebshop
RobertJi/robertji.github.io
lastshrek/Potunes-Desktop-vue3-vite

Used in 3 repositories

Elixir

  You are an expert in Elixir, Phoenix, PostgreSQL, LiveView, and Tailwind CSS.
  
  Code Style and Structure
  - Write concise, idiomatic Elixir code with accurate examples.
  - Follow Phoenix conventions and best practices.
  - Use functional programming patterns and leverage immutability.
  - Prefer higher-order functions and recursion over imperative loops.
  - Use descriptive variable and function names (e.g., user_signed_in?, calculate_total).
  - Structure files according to Phoenix conventions (controllers, contexts, views, etc.).
  
  Naming Conventions
  - Use snake_case for file names, function names, and variables.
  - Use PascalCase for module names.
  - Follow Phoenix naming conventions for contexts, schemas, and controllers.
  
  Elixir and Phoenix Usage
  - Use Elixir's pattern matching and guards effectively.
  - Leverage Phoenix's built-in functions and macros.
  - Use Ecto effectively for database operations.
  
  Syntax and Formatting
  - Follow the Elixir Style Guide (https://github.com/christopheradams/elixir_style_guide)
  - Use Elixir's pipe operator |> for function chaining.
  - Prefer single quotes for charlists and double quotes for strings.
  
  Error Handling and Validation
  - Use Elixir's "let it crash" philosophy and supervisor trees.
  - Implement proper error logging and user-friendly messages.
  - Use Ecto changesets for data validation.
  - Handle errors gracefully in controllers and display appropriate flash messages.
  
  UI and Styling
  - Use Phoenix LiveView for dynamic, real-time interactions.
  - Implement responsive design with Tailwind CSS.
  - Use Phoenix view helpers and templates to keep views DRY.
  
  Performance Optimization
  - Use database indexing effectively.
  - Implement caching strategies (ETS, Redis).
  - Use Ecto's preload to avoid N+1 queries.
  - Optimize database queries using preload, joins, or select.
  
  Key Conventions
  - Follow RESTful routing conventions.
  - Use contexts for organizing related functionality.
  - Implement GenServers for stateful processes and background jobs.
  - Use Tasks for concurrent, isolated jobs.
  
  Testing
  - Write comprehensive tests using ExUnit.
  - Follow TDD practices.
  - Use ExMachina for test data generation.
  
  Security
  - Implement proper authentication and authorization (e.g., Guardian, Pow).
  - Use strong parameters in controllers (params validation).
  - Protect against common web vulnerabilities (XSS, CSRF, SQL injection).
  
  Follow the official Phoenix guides for best practices in routing, controllers, contexts, views, and other Phoenix components.
  
batchfile
css
dockerfile
elixir
html
javascript
postgresql
redis
+3 more

First seen in:

medoror/painsnakes
hankbao/chatter-phoenix-channel
cardotrejos/weather-tracker

Used in 3 repositories

unknown
# Playwright Testing - Best Practices
0. Always use TypeScript instead of vanilla JavaScript whenever possible.
1. For locators, always bias towards using Playwright's `getByTestId()` locator method to target elements, unless absolutely unable to do so.
    1. If using `getByTestId()` is not possible, then using a `getByRole()` locator is the next best option.
    2. If using `getByRole()` is not possible, then using a `getByPlaceholder()` or `getByLabel()` or `getByAltText()` locator is the next best option.
    3. If using `getByPlaceholder()` or `getByLabel()` or `getByAltText()` is not possible, then using a `getByText()` locator is the next best option.
        1. If using `getByText()`, always use the `{ exact: true }` option to avoid unwanted partial matches.
    5. If using `getByText()` is not possible, then use whatever locator Playwright allows you to use to target the element.
        1. If using an Xpath or CSS selector is necessary, please try to take the shortest path to target the element and leverage any available attributes to target the element.
2. Save any locator to a variable before using it in a test. Examples:
    DO:
    ```typescript
    const exampleSignInButton = page.getByTestId("ExampleButton_signIn");
    await exampleSignInButton.click();
    ```
    DON'T:
    ```typescript
    await page.getByTestId("ExampleButton_signIn").click();
    ```
3. If logic is being reused in multiple tests, recommend creating a reusable helper/utility function to share this logic across tests. a. If a helper function is created to follow the DRY principle, don't require more arguments in the function than are needed to share the logic. b. Never assert anything in a helper function. Helper functions are reserved for performing a series of user actions, not testing the outcome of those actions.
4. Whenever possible, use Playwright's built-in features, methods, and utilities instead of "reinventing the wheel" with raw JavaScript or TypeScript solutions to solved problems. Examples:
    DO:
    ```typescript
    await expect(async () => {
        await radioButton.click(); // locator defined outside this block
        await expect(radioButton).toBeChecked();
    }).toPass();
    ```
    DON'T:
    ```typescript
    export async function radioButtonGroupClick(
        page: Page,
        urlToWaitFor: string, // The URL where the radio button is
        radioButton: Locator,
        errorTextTrigger: Locator // A button you can click that will throw error text if the radio button wasn't clicked
    ) {
        await page.waitForURL(urlToWaitFor);
        let iterationCounter = 0;
        let errorTextIsVisible = await page.getByTestId("ErrorText").isVisible();
        let buttonWasClicked = await radioButton.isChecked();
        while (errorTextIsVisible || !buttonWasClicked) {
            if (iterationCounter === 5) {
                break;
            } else {
                iterationCounter++;
            }
            await radioButton.click();
            buttonWasClicked = await radioButton.isChecked();
            if (buttonWasClicked) {
                await errorTextTrigger.click();
                errorTextIsVisible = await page.getByTestId("ErrorText").isVisible();
            }
        }
    }
    ```
    The entry point to Playwright's documentation is here if you need to look available features: https://playwright.dev/docs/intro.
5. When doing so follows the other rules in this file, try to write tests similar to other existing tests in the Playwright suite. The Playwright suite consists of everything within the `tests/` directory.
typescript
java
javascript
less
playwright
steven-the-qa/socialqa-web-ts
steven-the-qa/cursorrules-playwright
MRJOHN5ON/SocialQAproject

Used in 3 repositories

TypeScript
Swift
you are an expert in coding with swift, swift ui. you always write maintainable code and clean code.focus on latest august, september 2024 version of the documentation and features.your descriptions should be short and concise.don't remove any comments.SwiftUIProject structure: The main folder contains a "Sources" folder with "App" for main files, "Views" divided into "Home" and "Profile" sections with their ViewModels, and "Shared" for reusable components and modifiers. It includes "Models" for data models, "ViewModels" for view-specific logic, "Services" with "Network" for networking and "Persistence" for data storage, and "Utilities" for extensions, constants, and helpers. The "Resources" folder holds "Assets" for images and colors, "Localization" for localized strings, and "Fonts" for custom fonts. Lastly, the "Tests" folder includes "UnitTests" for unit testing and "UITests" for UI testing.SwiftUI UI Design Rules:Use Built-in Components: Utilize SwiftUI's native UI elements like List, NavigationView, TabView, and SF Symbols for a polished, iOS-consistent look.Master Layout Tools: Employ VStack, HStack, ZStack, Spacer, and Padding for responsive designs; use LazyVGrid and LazyHGrid for grids; GeometryReader for dynamic layouts.Add Visual Flair: Enhance UIs with shadows, gradients, blurs, custom shapes, and animations using the .animation() modifier for smooth transitions.Design for Interaction: Incorporate gestures (swipes, long presses), haptic feedback, clear navigation, and responsive elements to improve user engagement and satisfaction.
swift
ruby
PatrickJS/awesome-cursorrules
Qwertic/cursorrules
regenrek/swift-todo-app-cursor-ai

Used in 3 repositories

TypeScript
You are an AI coding instructor designed to assist and guide me as I learn to code. Your primary goal is to help me learn programming concepts, best practices, and problem-solving skills while writing code. Always assume I'm a beginner with limited programming knowledge.

Follow these guidelines in all interactions:
1. Explain concepts thoroughly but in simple terms, avoiding jargon when possible.
2. When introducing new terms, provide clear definitions and examples.
3. Break down complex problems into smaller, manageable steps.
4. Encourage good coding practices and explain why they are important.
5. Provide examples and analogies to illustrate programming concepts.
6. Be patient and supportive, understanding that learning to code can be challenging.
7. Offer praise for correct implementations and gentle corrections for mistakes.
8. When correcting errors, explain why the error occurred and how to fix it.
9. Suggest resources for further learning when appropriate.
10. Encourage me to ask questions and seek clarification.
11. Foster problem-solving skills by guiding me to find solutions rather than always providing direct answers.
12. Adapt your teaching style to my pace and learning preferences.
13. Provide code snippets to illustrate concepts, but always explain the code line by line.
14. Use comments throughout the code to help document what is happening

Address the my questions thoroughly, keeping in mind the guidelines above. If the question is unclear or lacks context, ask me for clarification.

Review the code and provide feedback. If there are errors or areas for improvement, explain them clearly and suggest corrections. If the code is correct, offer praise and explain why it's a good implementation.

Structure your responses as follows:
1. Format your response as markdown
2. Answer my question
3. Code review and feedback
4. Suggestions for further learning or practice

Remember, your goal is not just to help me write correct code, but to help me understand the underlying principles and develop my programming skills. Always strive to be clear, patient, and encouraging in your responses.
css
golang
typescript
javascript

First seen in:

jparkerweb/cursor-prompts
ilyaizen/songscribe-next
legocss/lego.css

Used in 3 repositories

TypeScript
# Always consider:

This is a Next.js project using App Router, Shadcn/UI, Tailwind, Resend, Builder.io, Payload CMS 3, NextAuth/AuthJS@v5, TypeScript, using PNPM as the package manager.
Be aware of the latest versions of all libraries.
Your plans should be documented into a ai.mdx file. Check to see if it exists. If it does, pick up where you left off. Mark completed steps with a checkbox. Update the file as you work, so another AI can continue from where you left off.

## Don't

Don't delete environment variables.
Don't nest server components in client components unless passed through props.

## Comments

pre-emptively add comments to explain "why" behind the code.
do not modify comments or functionality unrelated to the prompt unless you have a very good reason.
You will preserve all existing comments unless specifically asked to modify them
When showing code changes, use comments like // ... to indicate unchanged sections of code
We like comments with callouts and examples, like:

```
/*
 * Logging configuration
 * @see https://nextjs.org/docs/app/api-reference/next-config-js/logging
 */
```

## File structure

Prefer `hyphen-case.ext` over `CamelCase.ext`.
Use `@/server/actions` for all server actions.
Use `@/server/services` for all internal services.

## Coding conventions

pre-emptively ask questions if you are unsure about the requirements.
pre-emptively optimize code for production.
pre-emptively add types to all functions and variables.
pre-emptively fix any typescript errors or warnings.

Use open-source libraries when they would enhance the user/developer experience.
Use best practices, write production-ready code.
Fix bugs and improve performance.
Comment any complex or hard-to-read code.
fix all typescript errors and warnings.

## React

Use functional components and hooks for state management.
Ensure components are reusable and maintainable.
Prefer server actions for internal API requests.
Maintain a separation of concerns between client and server components.

Prefer arrow functions for React components:
✅ export const Component = () => { ... }
❌ export function Component() { ... }
❌ export default function Component() { ... }


## Next.js

Don't use server actions to fetch data.

## When interacting with the database

1. Ensure all required fields are provided when interacting with the database.
2. Check for potential undefined values and handle them appropriately.
3. Use TypeScript's type system to enforce correct data structures.
4. Implement error handling for database operations and API requests.
5. Validate input data to prevent runtime errors and ensure data integrity.
6. Add comments to explain complex logic or important decisions in the code.
7. Regularly review and test code to catch and fix errors early.
8. Use the `db.transaction` method to ensure atomicity when performing multiple database operations.
9. don't use boolean values for anything, use dates instead. (e.g. isActive: boolean -> activeAt: Date)

## API Integration

- Use environment variables for sensitive data like API keys.
- Handle API errors gracefully and provide user feedback.
- Use async/await for asynchronous operations to improve readability.
- Document API interactions and expected responses.

## UI/UX Design

- Follow Tailwind CSS conventions for styling.
- Ensure responsive design for all components.
- Use Shadcn/UI components for consistency in UI elements.
- Prioritize accessibility in UI design.

## Performance Optimization

- Optimize images and assets for faster load times.
- Use lazy loading for components and images where applicable.
- Minimize the use of heavy libraries and dependencies.
- Regularly audit and improve performance metrics.
css
golang
nestjs
shadcn/ui
typescript
javascript
less
shell
+7 more

First seen in:

lacymorrow/bones
lacymorrow/illish

Used in 2 repositories

TypeScript
# Comprehensive Coinbase Developer Platform (CDP) SDK Documentation

## Table of Contents

1. [Introduction](#introduction)
2. [Installation](#installation)
3. [SDK Configuration](#sdk-configuration)
4. [Wallet Management](#wallet-management)
5. [Address Management](#address-management)
6. [Transfers](#transfers)
7. [Trades](#trades)
8. [Smart Contract Interactions](#smart-contract-interactions)
9. [Token Deployments](#token-deployments)
10. [Message Signing](#message-signing)
11. [Balances and Transactions](#balances-and-transactions)
12. [Server-Signer Integration](#server-signer-integration)
13. [Error Handling](#error-handling)

## Introduction

The Coinbase Developer Platform (CDP) SDK provides a comprehensive set of tools for interacting with blockchain networks, managing wallets, and performing various crypto operations. This document serves as a detailed guide for developers looking to integrate the CDP SDK into their applications.

## Installation

Install the CDP SDK using npm:

```bash
npm install @coinbase/coinbase-sdk
```

## SDK Configuration

### Configuring the SDK

Configure the SDK with your API key.

```typescript
import { Coinbase } from "@coinbase/coinbase-sdk";

Coinbase.configureFromJson({ filePath: "~/Downloads/cdp_api_key.json" });
```

Parameters:

- `filePath`: String path to the JSON file containing your CDP API key.

Example:

```typescript
Coinbase.configureFromJson({ filePath: "/home/user/cdp_api_key.json" });
```

### Enabling Server-Signer

Enable the Server-Signer for enhanced security in production environments.

```typescript
Coinbase.useServerSigner = true;
```

## Wallet Management

### Creating a Wallet

Create a new wallet on a specified network.

```typescript
import { Wallet, Coinbase } from "@coinbase/coinbase-sdk";

let wallet = await Wallet.create({ networkId: Coinbase.networks.BaseMainnet });
```

Parameters:

- `networkId`: (Optional) The network ID for the wallet. Defaults to Base Sepolia testnet.
  NodeJS Network Labels:
  | Network Name | Coinbase.networks Constant |
  |------------------|----------------------------|
  | Base Mainnet | Coinbase.networks.BaseMainnet |
  | Base Sepolia | Coinbase.networks.BaseSepolia |
  | Ethereum Mainnet | Coinbase.networks.EthereumMainnet |
  | Polygon Mainnet | Coinbase.networks.PolygonMainnet |
  | Bitcoin Mainnet | Coinbase.networks.BitcoinMainnet |
  | Arbitrum Mainnet | Coinbase.networks.ArbitrumMainnet |
  | Optimism Mainnet | Coinbase.networks.OptimismMainnet |

Example:

```typescript
let mainnetWallet = await Wallet.create({
  networkId: Coinbase.networks.BaseMainnet,
});
let testnetWallet = await Wallet.create(); // Defaults to Base Sepolia
```

### Exporting a Wallet

Export wallet data for persistence.

```typescript
let data = wallet.export();
```

Example:

```typescript
let exportedData = wallet.export();
console.log("Exported wallet data:", exportedData);
```

### Importing a Wallet

Import a previously exported wallet.

```typescript
let importedWallet = await Wallet.import(fetchedData);
```

Parameters:

- `fetchedData`: The exported wallet data object.

Example:

```typescript
let storedData = await fetchWalletDataFromStorage();
let restoredWallet = await Wallet.import(storedData);
```

### Saving Wallet Seed Locally

Save the wallet seed to a local file (for development purposes only).

```typescript
wallet.saveSeed(filePath, encrypt);
```

Parameters:

- `filePath`: String path where the seed will be saved.
- `encrypt`: Boolean indicating whether to encrypt the seed.

Example:

```typescript
wallet.saveSeed("my_wallet_seed.json", true);
```

### Loading Wallet Seed

Load a previously saved wallet seed.

```typescript
await wallet.loadSeed(filePath);
```

Parameters:

- `filePath`: String path to the saved seed file.

Example:

```typescript
await wallet.loadSeed("my_wallet_seed.json");
```

## Address Management

### Getting the Default Address

Retrieve the default address of a wallet.

```typescript
let address = await wallet.getDefaultAddress();
```

Example:

```typescript
let defaultAddress = await wallet.getDefaultAddress();
console.log("Default address:", defaultAddress.toString());
```

### Creating a New Address

Create a new address within a wallet.

```typescript
let newAddress = await wallet.createAddress();
```

Example:

```typescript
let additionalAddress = await wallet.createAddress();
console.log("New address created:", additionalAddress.toString());
```

### Listing Addresses

List all addresses in a wallet.

```typescript
let addresses = wallet.getAddresses();
```

Example:

```typescript
let allAddresses = wallet.getAddresses();
allAddresses.forEach((address) => console.log(address.toString()));
```

## Transfers

### Creating a Transfer

Initiate a transfer of assets from one wallet to another.
ETH's asset ID is Coinbase.assets.Eth
USDC's asset ID is Coinbase.assets.Usdc
WETH's asset ID is Coinbase.assets.Weth

```typescript
let transfer = await wallet.createTransfer({
  amount: number,
  assetId: string,
  destination: string | Wallet,
  gasless?: boolean
});
```

Parameters:

- `amount`: Number representing the amount to transfer.
- `assetId`: String identifier of the asset to transfer (e.g., `Coinbase.assets.Eth`).
- `destination`: Destination wallet or address string.
- `gasless`: (Optional) Boolean to indicate if the transfer should be gasless (for supported assets).

Example:

```typescript
let transfer = await wallet.createTransfer({
  amount: 0.001,
  assetId: Coinbase.assets.Eth,
  destination: "0x742d35Cc6634C0532925a3b844Bc454e4438f44e",
});
await transfer.wait();
```

### Checking Transfer Status

Check the status of a transfer.

```typescript
let status = await transfer.getStatus();
```

Example:

```typescript
let transferStatus = await transfer.getStatus();
console.log("Transfer status:", transferStatus);
```

## Trades

### Creating a Trade

Initiate a trade between two assets.

```typescript
let trade = await wallet.createTrade({
  amount: number,
  fromAssetId: string,
  toAssetId: string,
});
```

Parameters:

- `amount`: Number representing the amount to trade.
- `fromAssetId`: String identifier of the asset to trade from.
- `toAssetId`: String identifier of the asset to trade to.

Example:

```typescript
let trade = await wallet.createTrade({
  amount: 0.1,
  fromAssetId: Coinbase.assets.Eth,
  toAssetId: Coinbase.assets.Usdc,
});
await trade.wait();
```

### Checking Trade Status

Check the status of a trade.

```typescript
let status = await trade.getStatus();
```

Example:

```typescript
let tradeStatus = await trade.getStatus();
console.log("Trade status:", tradeStatus);
```

## Smart Contract Interactions

### Invoking a Contract

Invoke a method on a smart contract.

```typescript
let contractInvocation = await wallet.invokeContract({
  contractAddress: string,
  method: string,
  args: object,
  abi?: object[],
  amount?: number,
  assetId?: string
});
```

Parameters:

- `contractAddress`: String address of the contract.
- `method`: String name of the method to invoke.
- `args`: Object containing method arguments.
- `abi`: (Optional) Array of objects describing the contract ABI.
- `amount`: (Optional) Number representing the amount of native asset to send with the transaction.
- `assetId`: (Optional) String identifier of the asset to send (for payable functions).

Example:

```typescript
let contractInvocation = await wallet.invokeContract({
  contractAddress: "0x742d35Cc6634C0532925a3b844Bc454e4438f44e",
  method: "transfer",
  args: {
    to: "0xRecipientAddress",
    value: "1000000000000000000", // 1 token with 18 decimals
  },
  abi: [
    {
      inputs: [
        { name: "to", type: "address" },
        { name: "value", type: "uint256" },
      ],
      name: "transfer",
      outputs: [{ name: "", type: "bool" }],
      type: "function",
    },
  ],
});
await contractInvocation.wait();
```

## Token Deployments

### Deploying an ERC-20 Token

Deploy a new ERC-20 token contract.

```typescript
let erc20 = await wallet.deployToken({
  name: string,
  symbol: string,
  totalSupply: number,
});
```

Parameters:

- `name`: String name of the token.
- `symbol`: String symbol of the token.
- `totalSupply`: Number representing the total supply of tokens.

Example:

```typescript
let myToken = await wallet.deployToken({
  name: "My Token",
  symbol: "MTK",
  totalSupply: 1000000,
});
console.log("Token deployed at:", myToken.getContractAddress());
```

### Deploying an ERC-721 Token (NFT)

Deploy a new ERC-721 token (NFT) contract.

```typescript
let nft = await wallet.deployNFT({
  name: string,
  symbol: string,
  baseURI: string,
});
```

Parameters:

- `name`: String name of the NFT collection.
- `symbol`: String symbol of the NFT collection.
- `baseURI`: String base URI for token metadata.

Example:

```typescript
let myNFT = await wallet.deployNFT({
  name: "My NFT Collection",
  symbol: "MNFT",
  baseURI: "https://api.mynft.com/metadata/",
});
console.log("NFT contract deployed at:", myNFT.getContractAddress());
```

### Deploying an ERC-1155 Token (Multi-Token)

Deploy a new ERC-1155 token (Multi-Token) contract.

```typescript
let multiToken = await wallet.deployMultiToken({
  uri: string,
});
```

Parameters:

- `uri`: String URI for token metadata.

Example:

```typescript
let myMultiToken = await wallet.deployMultiToken({
  uri: "https://api.mymultitoken.com/metadata/{id}.json",
});
console.log(
  "Multi-Token contract deployed at:",
  myMultiToken.getContractAddress()
);
```

## Message Signing

### Signing a Message

Sign a message using EIP-191 standard.

```typescript
import { hashMessage } from "@coinbase/coinbase-sdk";

let payloadSignature = await wallet.createPayloadSignature(
  hashMessage(message)
);
```

Parameters:

- `message`: String message to be signed.

Example:

```typescript
let message = "Hello, Coinbase!";
let signature = await wallet.createPayloadSignature(hashMessage(message));
await signature.wait();
console.log("Signature:", signature.toString());
```

### Signing Typed Data

Sign typed structured data using EIP-712 standard.

```typescript
import { hashTypedData } from "@coinbase/coinbase-sdk";

let payloadSignature = await wallet.createPayloadSignature(
  hashTypedData({
    domain: object,
    types: object,
    primaryType: string,
    message: object,
  })
);
```

Parameters:

- `domain`: Object containing domain data.
- `types`: Object describing the structure of the data.
- `primaryType`: String name of the primary type being signed.
- `message`: Object containing the data to be signed.

Example:

```typescript
let typedData = {
  domain: {
    name: "My dApp",
    version: "1",
    chainId: 1,
    verifyingContract: "0x1234567890123456789012345678901234567890",
  },
  types: {
    Person: [
      { name: "name", type: "string" },
      { name: "wallet", type: "address" },
    ],
  },
  primaryType: "Person",
  message: {
    name: "John Doe",
    wallet: "0x0123456789012345678901234567890123456789",
  },
};

let signature = await wallet.createPayloadSignature(hashTypedData(typedData));
await signature.wait();
console.log("Typed data signature:", signature.toString());
```

## Balances and Transactions

### Listing Balances

List balances for all assets in a wallet.

```typescript
let balances = await wallet.listBalances();
```

Example:

```typescript
let allBalances = await wallet.listBalances();
console.log("Wallet balances:", allBalances.toString());
```

### Getting Balance for Specific Asset

Get the balance of a specific asset in a wallet.

```typescript
let balance = await wallet.getBalance(assetId);
```

Parameters:

- `assetId`: String identifier of the asset.

Example:

```typescript
let ethBalance = await wallet.getBalance(Coinbase.assets.Eth);
console.log("ETH balance:", ethBalance.toString());
```

### Listing Transactions

List transactions for an address.

```typescript
let transactions = await address.listTransactions(options);
```

Parameters:

- `options`: (Optional) Object containing listing options.

Example:

```typescript
let recentTransactions = await address.listTransactions({ limit: 10 });
recentTransactions.forEach((tx) => console.log(tx.toString()));
```

## Server-Signer Integration

### Verifying Server-Signer Assignment

Verify if a Server-Signer is assigned to your CDP project.

```typescript
import { ServerSigner } from "@coinbase/coinbase-sdk";

let serverSigner = await ServerSigner.getDefault();
```

Example:

```typescript
try {
  let signer = await ServerSigner.getDefault();
  console.log("Server-Signer is assigned:", signer);
} catch (error) {
  console.error("No Server-Signer assigned:", error);
}
```

## Error Handling

The CDP SDK uses custom error types for different scenarios. Always wrap your SDK calls in try-catch blocks to handle potential errors gracefully.

Example:

```typescript
import { TimeoutError } from "@coinbase/coinbase-sdk";

try {
  let transfer = await wallet.createTransfer({
    amount: 0.001,
    assetId: Coinbase.assets.Eth,
    destination: "0x742d35Cc6634C0532925a3b844Bc454e4438f44e",
  });
  await transfer.wait();
} catch (error) {
  if (error instanceof TimeoutError) {
    console.log("Transfer timed out, check status later");
  } else {
    console.error("Error during transfer:", error);
  }
}
```

This comprehensive guide covers the major functionalities of the CDP SDK. For the most up-to-date and detailed information, always refer to the official CDP SDK documentation.
css
golang
javascript
less
npm
rest-api
typescript

First seen in:

raviriley/omitx
hft-studio/web

Used in 2 repositories

Python
# Cursor Rules for Python Code

## Rule 1: Code Documentation
- **Files**: [**/*.py]
- **Message**: "Follow documentation standards:
  - Module-level docstrings
  - Function/class docstrings (Google style)
  - Type hints for parameters and returns
  - Usage examples where appropriate"

## Rule 2: Code Style
- **Files**: [**/*.py]
- **Message**: "Follow PEP 8 guidelines:
  - Use black for formatting
  - Use isort for import sorting
  - Maximum line length of 88 characters
  - Consistent naming conventions"

## Rule 3: Testing Requirements
- **Files**: [**/*.py]
- **Message**: "Ensure proper testing:
  - Unit tests for new functions/classes
  - Integration tests where applicable
  - Minimum 80% test coverage
  - Test documentation"

## Rule 4: Error Handling
- **Files**: [**/*.py]
- **Message**: "Implement proper error handling:
  - Custom exception classes
  - Meaningful error messages
  - Appropriate exception hierarchy
  - Error logging"

## Rule 5: Dependencies
- **Files**: [requirements.txt, setup.py, pyproject.toml]
- **Message**: "Manage dependencies properly:
  - Document all requirements
  - Specify version constraints
  - Update requirements.txt/pyproject.toml
  - Document dependency purposes"

## Rule 6: Security
- **Files**: [**/*.py]
- **Message**: "Follow security best practices:
  - Sanitize user inputs
  - Use environment variables for secrets
  - Implement proper authentication
  - Regular dependency updates"

## Rule 7: Performance
- **Files**: [**/*.py]
- **Message**: "Consider performance implications:
  - Profile code when necessary
  - Optimize database queries
  - Use appropriate data structures
  - Document performance considerations"
golang
python
shell
muhammad-asn/ecsctl
muhammad-asn/cursor-code-editor-explore

Used in 2 repositories