Skip to content

Commit 15bc1a3

Browse files
authored
Feat/llm instructions (#321)
* feat (llm): add CLAUDE.md and copilot-instructions to codebase * fix (llm instructions): remove string escaping * fix (claude.md): cleanup * fix (copilot instructions): adjust JSDoc Patterns * fix (copilot instructions): adjust jsdoc sections * fix (copilot instructions): adjust jsdoc sections * fix (copilot instructions): syslink to CLAUDE.md * fix (prettier): ignore .md doc files * fix (agent instructions): adjust linking, extract style guide, adjust readme * fix (git ignore): adjust for other agent instructions * fix (agent instructions): adjust agent.md * fix (apps): adjust agent instructions * fix (package json): adjust lint target * fix (docs): adjust agent instructions * fix (agent): adjust test and verification sequence * fix (agent md): adjust testing section * fix (agent md): cleanup * fix (agent md): adjust to basic sanity E2E * fix (agent.md, styleguide.md): adjust per comments * fix (agent.md): adjust verification * fix (agent.md): minor adjustments
1 parent 68ae79f commit 15bc1a3

21 files changed

Lines changed: 416 additions & 35 deletions

File tree

.github/copilot-instructions.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
../AGENT.md

.gitignore

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,3 +53,12 @@ jspm_packages
5353

5454
# eslint
5555
.eslintcache
56+
57+
# agent instructions
58+
AGENTS.md
59+
QWEN.md
60+
GEMINI.md
61+
GPT.md
62+
LLAMA.md
63+
MISTRAL.md
64+
VICUNA.md

.lintstagedrc.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ const config = {
1616
},
1717

1818
// Prettify
19-
'**/*.(md|json)': (filenames) => {
19+
'**/*.(json)': (filenames) => {
2020
const relativeFiles = filenames.map((f) => path.relative(path.resolve('.'), f));
2121
return [
2222
`yarn prettier --write ${relativeFiles.join(' ')}`

.prettierignore

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,11 @@ yarn-error.log*
3535
.env.test.local
3636
.env.production.local
3737

38+
# docs
39+
# Exclude .md files from formatting because Prettier adds unnecessary escaping
40+
# (e.g., turns `*` into `\*` where no escaping is needed).
41+
*.md
42+
3843
# vercel
3944
.vercel
4045

AGENT.md

Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
# Agent Instructions for Vertex SDK
2+
3+
This file provides guidance to LLMs when working with code in this repository.
4+
5+
## Repository Overview
6+
7+
The Vertex TypeScript SDK is a monorepo containing utilities for interacting with the Vertex Protocol API and contracts. The project uses Lerna for workspace management and provides a comprehensive SDK for trading on Vertex.
8+
9+
## Key Commands
10+
11+
### Development
12+
13+
- `yarn build` - Build all packages in the monorepo using Lerna
14+
- `yarn clean` - Clean all packages
15+
- `yarn dev` - Run development mode for all packages
16+
- `yarn test` - Run Jest tests across the entire codebase
17+
- `yarn lint` - Run ESLint with auto-fix and Prettier formatting
18+
- `yarn typecheck` - Run TypeScript type checking for all packages
19+
- `yarn gen-typedoc` - Generate TypeDoc documentation for all packages
20+
21+
### Testing
22+
23+
- **IMPORTANT**: Run `yarn build` before running any E2E tests to ensure all packages are built
24+
- `yarn --cwd apps/e2e e2e` - Run all E2E tests
25+
- `yarn --cwd apps/e2e e2e:client` - Run client-specific E2E tests
26+
- `yarn --cwd apps/e2e e2e:engine` - Run engine-client E2E tests
27+
- `yarn --cwd apps/e2e e2e:indexer` - Run indexer-client E2E tests
28+
- `yarn --cwd apps/e2e e2e:trigger` - Run trigger-client E2E tests
29+
30+
### Package Management
31+
32+
- `yarn link-local` / `yarn unlink-local` - Link/unlink packages for local development
33+
- `yarn publish-all` - Clean, build, and publish all packages via Lerna
34+
- `yarn depcruise:all` - Analyze package dependencies and detect circular dependencies
35+
36+
### Individual Package Scripts
37+
38+
Each package in `packages/` has these common scripts:
39+
- `yarn build` - Build the specific package
40+
- `yarn clean` - Clean build artifacts
41+
- `yarn dev` - Watch mode for development
42+
- `yarn lint` - Check linting rules only
43+
- `yarn lint:fix` - Fix linting issues automatically
44+
- `yarn typecheck` - Type check without emitting files
45+
46+
## Architecture
47+
48+
### Monorepo Structure
49+
50+
The project follows a monorepo pattern with these core packages:
51+
52+
1. **`@vertex-protocol/client`** - Main entry point that composes all other packages into a unified `VertexClient`
53+
2. **`@vertex-protocol/engine-client`** - Handles off-chain matching engine communication
54+
3. **`@vertex-protocol/indexer-client`** - Provides indexer queries for historical data
55+
4. **`@vertex-protocol/trigger-client`** - Manages trigger service for stop orders
56+
5. **`@vertex-protocol/contracts`** - Contract utilities, ABIs, and on-chain interactions
57+
6. **`@vertex-protocol/utils`** - Common utilities including bignumber.js for decimal math
58+
59+
### Client Architecture
60+
61+
- `VertexClient` is the main class that orchestrates all API interactions
62+
- Uses `viem` for Ethereum wallet/provider functionality
63+
- Supports both chain signers and linked signers for trading
64+
- Modular API design with separate classes for Market, Spot, Perp, Subaccount, and WebSocket operations
65+
66+
### Key Patterns
67+
68+
- All packages use TypeScript with strict type checking
69+
- Use bignumber.js (renamed to BigDecimal) for precise decimal calculations
70+
- EIP-712 signing for off-chain order execution
71+
- Comprehensive type definitions for all API responses
72+
- Consistent error handling with custom error classes
73+
- Viem as the primary Ethereum library dependency
74+
75+
## Test and Verification Sequence
76+
77+
After making edits, **ALWAYS** run the following verification sequence:
78+
79+
1. **Type Check**
80+
- Run `yarn typecheck` to verify all TypeScript types are correct across all packages
81+
2. **Lint Check**
82+
- Run `yarn lint` to run ESLint with auto-fix and Prettier formatting
83+
3. **Build**
84+
- Run `yarn build` to build all packages before running any tests
85+
4. **Tests**
86+
- Run `yarn test` to run all tests across the codebase
87+
### Requirements
88+
- **All commands must pass** before considering a task complete
89+
- **Fix errors immediately** - If any command fails, address issues and re-run the full sequence
90+
- **Build before adding E2E tests** - Always run `yarn build` before E2E testing to ensure packages are properly built
91+
- **Add basic sanity E2E tests** - Never skip writing E2E tests for new features, client APIs, or user flows
92+
- **Do NOT write unit tests** - any unit tests should be written manually
93+
94+
95+
## TypeScript SDK Style Guide
96+
97+
For detailed coding standards and conventions, see [Style Guide](./docs/STYLEGUIDE.md).
98+
99+
### Key areas covered in the style guide:
100+
101+
- JSDoc documentation standards
102+
- TypeScript conventions and type safety
103+
- Client class patterns and architecture
104+
- Error handling and custom exceptions
105+
- Naming conventions and file structure
106+
- Constants and configuration management
107+
- Utility function patterns and validation
108+

CLAUDE.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
AGENT.md

README.md

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,3 +60,21 @@ to enable other local repos to consume Vertex packages without having to publish
6060
We're using [Tsup](https://tsup.egoist.dev/) for building the packages in CJS and ESM formats.
6161
Each package has its own `tsup.config.ts` file importing `tsup.base.config.ts` at the root of the monorepo.
6262
`apps/node-compat-test` tests the compatibility of the SDK in a pure, bundler-less, Node.js environment.
63+
64+
## Agent Instructions
65+
66+
This repository includes agent instruction files for LLM-based development tools:
67+
68+
- `AGENT.md` - Master instructions file
69+
- `CLAUDE.md` - Automatically symlinked to `AGENT.md` (managed by the repository)
70+
- `.github/copilot-instructions.md` - Automatically symlinked to `AGENT.md` for GitHub Copilot
71+
72+
For other LLM agents (Qwen, Gemini, etc.), you can manually create symlinks:
73+
74+
```bash
75+
# For Qwen
76+
ln -sf AGENT.md QWEN.md
77+
78+
# For Gemini
79+
ln -sf AGENT.md GEMINI.md
80+
```

docs/STYLEGUIDE.md

Lines changed: 212 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,212 @@
1+
# TypeScript SDK Style Guide
2+
3+
## JSDoc Documentation Standards
4+
5+
**🚨 ALWAYS use JSDoc format (`/** ... */`) for:**
6+
7+
- **ALL exported functions** - Every function with `export` keyword must have JSDoc docstring describing its purpose, parameters, and return value
8+
- **ALL exported variables/constants** - Any constant or variable with `export` keyword used outside the current file
9+
- **ALL exported types and interfaces** - Including their properties and purpose
10+
- **ALL interface/type properties** - Individual property descriptions
11+
12+
**⚠️ When you see `export function`, `export const`, `export type`, or `export interface`, automatically add JSDoc format.**
13+
14+
### When NOT to Use JSDoc Format
15+
16+
- **Implementation comments** - Comments inside function bodies explaining logic flow
17+
- **Inline comments** - Comments on the same line as code
18+
- **Temporary/debugging comments** - Comments meant for development purposes only
19+
- **Non-exported private utilities** - Internal helper functions not used elsewhere
20+
21+
### JSDoc Formatting Requirements
22+
23+
#### Basic Structure
24+
25+
```typescript
26+
/**
27+
* Brief description of the function/variable/type
28+
* @param {type} paramName - Description of parameter
29+
* @returns {type} Description of return value
30+
* @type {type} - For variable type annotations
31+
*/
32+
```
33+
34+
#### Quality Guidelines
35+
36+
- **Be Concise** - Keep descriptions clear and to the point
37+
- **Be Specific** - Explain what the function/variable does, not how it works
38+
- **Use Proper Grammar** - Start with capital letters, end with periods
39+
- **Avoid Redundancy** - Don't repeat information already clear from the code
40+
- **Include Edge Cases** - Document important limitations or special behaviors
41+
42+
### Code Enforcement Rules
43+
44+
**When generating or reviewing code, LLM should:**
45+
46+
1. **Detect export keywords** - Scan for `export function`, `export const`, `export type`, `export interface`
47+
2. **Check for JSDoc** - Verify each export has proper `/** ... */` documentation
48+
3. **Suggest JSDoc format** - Auto-complete JSDoc blocks for any missing documentation
49+
4. **Flag regular comments** - Convert `//` comments above exports to JSDoc format
50+
5. **Apply to all files** - Enforce in `apps/`, `packages/`, and all TypeScript files
51+
52+
### Detection Patterns for Regular Comments Above Exports
53+
54+
**🚨 CRITICAL: Always detect and flag these patterns for JSDoc conversion:**
55+
56+
- `// comment\nexport function` → Convert to JSDoc
57+
- `/* comment */\nexport function` → Convert to JSDoc
58+
- `// comment\nexport const` → Convert to JSDoc
59+
- `// comment\nexport interface` → Convert to JSDoc
60+
- `// comment\nexport type` → Convert to JSDoc
61+
- `// comment\nexport class` → Convert to JSDoc
62+
63+
**Example:**
64+
65+
**Avoid - Regular comment above export:**
66+
67+
```typescript
68+
// calculates position notional value
69+
export function calculateNotional(size: BigDecimal, price: BigDecimal) {
70+
// Should be converted to JSDoc format
71+
}
72+
```
73+
74+
**Good - Proper JSDoc:**
75+
76+
```typescript
77+
/**
78+
* Calculates the notional value of a position
79+
* @param size - Position size in base units (BigDecimal)
80+
* @param price - Current price per unit (BigDecimal, precision 18)
81+
* @returns Notional value in quote currency (USDC), rounded to 6 decimal places
82+
* @throws {InvalidPositionError} When size is zero or negative
83+
*/
84+
export function calculateNotional(
85+
size: BigDecimal,
86+
price: BigDecimal,
87+
): BigDecimal {
88+
// Implementation
89+
}
90+
```
91+
92+
## TypeScript Conventions
93+
94+
- Use `interface` for object shapes that might be extended or implemented
95+
- Use `type` for unions, primitives, computed types, and utility types
96+
- **Never use `any` type** - Prefer `unknown` for truly unknown types, or create proper type definitions
97+
- Use descriptive generic constraints: `<T extends Record<string, unknown>>`
98+
99+
## Error Handling Patterns
100+
101+
- Create custom error classes extending base `Error`
102+
- Use `@throws` JSDoc tags to document all possible errors
103+
- Provide detailed error context and recovery suggestions
104+
105+
**Good error class patterns:**
106+
107+
```typescript
108+
/**
109+
* Error thrown when wallet client is not provided for operations requiring it
110+
*/
111+
export class WalletNotProvidedError extends Error {
112+
constructor() {
113+
// Set descriptive message and proper error name
114+
super('Wallet client not provided');
115+
this.name = 'WalletNotProvidedError';
116+
}
117+
}
118+
119+
/**
120+
* Error thrown when engine server returns a failure response
121+
*/
122+
export class EngineServerFailureError extends Error {
123+
// Store server response data as readonly property for debugging
124+
constructor(readonly responseData: ServerFailureResponse) {
125+
// Call super() with optional message
126+
super();
127+
}
128+
}
129+
```
130+
131+
## Naming Conventions
132+
133+
- **Use camelCase** for variables, functions, and methods
134+
- **Use PascalCase** for classes, interfaces, types, and enums
135+
- **Use CAPITAL_SNAKE_CASE** for constants and environment variables
136+
- **Client classes** should end with `Client` (e.g., `MarketClient`, `VertexClient`)
137+
- **Error classes** should end with `Error` (e.g., `ValidationError`, `NetworkError`)
138+
- **Type guards** should start with `is` (e.g., `isMarketOrder`, `isValidAddress`)
139+
140+
## Constants and Configuration
141+
142+
**Good constants patterns:**
143+
144+
```typescript
145+
/**
146+
* Common BigDecimal constants used throughout the SDK
147+
*/
148+
export const BigDecimals = Object.freeze({
149+
// Freeze object to prevent mutation
150+
// Use semantic names for commonly used values
151+
ZERO: toBigDecimal(0),
152+
ONE: toBigDecimal(1),
153+
INF: toBigDecimal(Infinity),
154+
MAX_I128: toBigDecimal('170141183460469231731687303715884105727'),
155+
});
156+
157+
/**
158+
* Quote product ID for USDC
159+
*/
160+
export const QUOTE_PRODUCT_ID = 0;
161+
```
162+
163+
## Utility Function Patterns
164+
165+
- Write pure functions where possible
166+
- Include comprehensive JSDoc with examples
167+
- Use proper type guards and validators
168+
- Handle edge cases gracefully
169+
170+
**Good utility function patterns:**
171+
172+
```typescript
173+
/**
174+
* BigDecimal is a renamed `BigNumber` type from `bignumber.js`.
175+
* Includes valid values & instances for BigDecimal.
176+
* @see https://mikemcl.github.io/bignumber.js/
177+
*/
178+
export type BigDecimalish = BigDecimal | BigDecimal.Value | bigint;
179+
180+
/**
181+
* Converts a value to an instance of BigDecimal
182+
* @param val - The value to convert to BigDecimal
183+
* @returns A new BigDecimal instance
184+
*/
185+
export function toBigDecimal(val: BigDecimalish): BigDecimal {
186+
// Handle different input types with type guards
187+
const bnConstructorVal = (() => {
188+
if (val instanceof BigDecimal) {
189+
return val; // Already BigDecimal, return as-is
190+
} else if (typeof val === 'string' || typeof val === 'number') {
191+
return val; // Native types supported by BigNumber constructor
192+
} else if (typeof val === 'bigint') {
193+
return val.toString(); // Convert bigint to string
194+
}
195+
// Fallback for unexpected types (edge case handling)
196+
return JSON.stringify(val);
197+
})();
198+
return new BigDecimal(bnConstructorVal);
199+
}
200+
```
201+
202+
## Code Quality Checklist
203+
204+
When reviewing SDK code, ensure:
205+
206+
- [ ] JSDoc format is used for all exported functions, classes, and types
207+
- [ ] Proper error handling with custom error classes
208+
- [ ] Type safety with no `any` types
209+
- [ ] Async operations use proper Promise handling
210+
- [ ] Constants are properly frozen and exported
211+
- [ ] Tests cover both success and error scenarios
212+
- [ ] Naming conventions are followed consistently

packages/client/package.json

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@
1616
"clean": "rm -rf dist && rm -f tsconfig.tsbuildinfo",
1717
"build": "tsup",
1818
"dev": "tsc -w",
19+
"lint": "eslint --cache './**/*.{ts,tsx}'",
20+
"lint:fix": "eslint --cache --fix './**/*.{ts,tsx}'",
1921
"typecheck": "tsc --noEmit"
2022
},
2123
"files": [

0 commit comments

Comments
 (0)