Skip to content

Commit 108b93f

Browse files
yinkscsscursoragent
andcommitted
feat: complete Phase 1 foundation — monorepo, services, SDK
Phase 1 of SolAgent — a non-custodial AI agent wallet platform for Solana. Infrastructure: - Turborepo monorepo with Bun runtime, TypeScript strict mode - Docker Compose (PostgreSQL, Redis, Redpanda, Kora fee relayer) - GitHub Actions CI (lint, typecheck, test, build) - ESLint 9 flat config + Prettier + Husky pre-commit hooks Packages: - @solagent/common — shared types, Zod schemas, error classes, Kora client - @solagent/db — Drizzle ORM schemas (8 tables), migrations, seed data - @solagent/events — Redpanda event publisher with typed topics - @solagent/sdk — TypeScript SDK with wallet, policy, transaction modules Services: - wallet-engine (port 3002) — CRUD, LocalProvider, TurnkeyProvider, HD derivation, import/export, balance caching - policy-engine (port 3003) — spending limits, allowlists, blocklists, evaluation pipeline, audit events - transaction-engine (port 3004) — build, simulate, sign, submit, confirm lifecycle with state machine 200 tests passing across 23 test files. Co-authored-by: Cursor <cursoragent@cursor.com>
0 parents  commit 108b93f

179 files changed

Lines changed: 13987 additions & 0 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

.agents/skills/code-refactoring/SKILL.md

Lines changed: 499 additions & 0 deletions
Large diffs are not rendered by default.
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
N:code-refactoring
2+
D:Simplify and refactor code while preserving behavior, improving clarity, and reducing complexity....
3+
G:refactoring code-quality DRY SOLID design-patterns
4+
U[4]:
5+
**코드 리뷰**: 복잡하거나 중복된 코드 발견
6+
**새 기능 추가 전**: 기존 코드 정리
7+
**버그 수정 후**: 근본 원인 제거
8+
**기술 부채 해소**: 정기적인 리팩토링
9+
S[5]{n,action}:
10+
1,Extract Method (메서드 추출)
11+
2,Remove Duplication (중복 제거)
12+
3,Replace Conditional with Polymorphism
13+
4,Introduce Parameter Object
14+
5,SOLID 원칙 적용
Lines changed: 306 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,306 @@
1+
---
2+
name: performance-optimization
3+
description: Optimize application performance for speed, efficiency, and scalability. Use when improving page load times, reducing bundle size, optimizing database queries, or fixing performance bottlenecks. Handles React optimization, lazy loading, caching, code splitting, and profiling.
4+
tags: [performance, optimization, React, lazy-loading, caching, profiling, web-vitals]
5+
platforms: [Claude, ChatGPT, Gemini]
6+
---
7+
8+
# Performance Optimization
9+
10+
11+
## When to use this skill
12+
13+
- **느린 페이지 로드**: Lighthouse 점수 낮음
14+
- **느린 렌더링**: 사용자 인터랙션 지연
15+
- **큰 번들 크기**: 다운로드 시간 증가
16+
- **느린 쿼리**: 데이터베이스 병목
17+
18+
## Instructions
19+
20+
### Step 1: 성능 측정
21+
22+
**Lighthouse (Chrome DevTools)**:
23+
```bash
24+
# CLI
25+
npm install -g lighthouse
26+
lighthouse https://example.com --view
27+
28+
# CI에서 자동화
29+
lighthouse https://example.com --output=json --output-path=./report.json
30+
```
31+
32+
**Web Vitals 측정** (React):
33+
```typescript
34+
import { getCLS, getFID, getFCP, getLCP, getTTFB } from 'web-vitals';
35+
36+
function sendToAnalytics(metric: any) {
37+
// Google Analytics, Datadog 등으로 전송
38+
console.log(metric);
39+
}
40+
41+
getCLS(sendToAnalytics);
42+
getFID(sendToAnalytics);
43+
getFCP(sendToAnalytics);
44+
getLCP(sendToAnalytics);
45+
getTTFB(sendToAnalytics);
46+
```
47+
48+
### Step 2: React 최적화
49+
50+
**React.memo (불필요한 리렌더링 방지)**:
51+
```tsx
52+
// ❌ 나쁜 예: 부모가 리렌더링될 때마다 자식도 리렌더링
53+
function ExpensiveComponent({ data }: { data: Data }) {
54+
return <div>{/* 복잡한 렌더링 */}</div>;
55+
}
56+
57+
// ✅ 좋은 예: props 변경 시에만 리렌더링
58+
const ExpensiveComponent = React.memo(({ data }: { data: Data }) => {
59+
return <div>{/* 복잡한 렌더링 */}</div>;
60+
});
61+
```
62+
63+
**useMemo & useCallback**:
64+
```tsx
65+
function ProductList({ products, category }: Props) {
66+
// ✅ 필터링 결과 메모이제이션
67+
const filteredProducts = useMemo(() => {
68+
return products.filter(p => p.category === category);
69+
}, [products, category]);
70+
71+
// ✅ 콜백 메모이제이션
72+
const handleAddToCart = useCallback((id: string) => {
73+
addToCart(id);
74+
}, []);
75+
76+
return (
77+
<div>
78+
{filteredProducts.map(product => (
79+
<ProductCard key={product.id} product={product} onAdd={handleAddToCart} />
80+
))}
81+
</div>
82+
);
83+
}
84+
```
85+
86+
**Lazy Loading & Code Splitting**:
87+
```tsx
88+
import { lazy, Suspense } from 'react';
89+
90+
// ✅ Route-based code splitting
91+
const Dashboard = lazy(() => import('./pages/Dashboard'));
92+
const Profile = lazy(() => import('./pages/Profile'));
93+
const Settings = lazy(() => import('./pages/Settings'));
94+
95+
function App() {
96+
return (
97+
<Suspense fallback={<div>Loading...</div>}>
98+
<Routes>
99+
<Route path="/dashboard" element={<Dashboard />} />
100+
<Route path="/profile" element={<Profile />} />
101+
<Route path="/settings" element={<Settings />} />
102+
</Routes>
103+
</Suspense>
104+
);
105+
}
106+
107+
// ✅ Component-based lazy loading
108+
const HeavyChart = lazy(() => import('./components/HeavyChart'));
109+
110+
function Dashboard() {
111+
return (
112+
<div>
113+
<h1>Dashboard</h1>
114+
<Suspense fallback={<Skeleton />}>
115+
<HeavyChart data={data} />
116+
</Suspense>
117+
</div>
118+
);
119+
}
120+
```
121+
122+
### Step 3: 번들 크기 최적화
123+
124+
**Webpack Bundle Analyzer**:
125+
```bash
126+
npm install --save-dev webpack-bundle-analyzer
127+
128+
# package.json
129+
{
130+
"scripts": {
131+
"analyze": "webpack-bundle-analyzer build/stats.json"
132+
}
133+
}
134+
```
135+
136+
**Tree Shaking (사용하지 않는 코드 제거)**:
137+
```typescript
138+
// ❌ 나쁜 예: 전체 라이브러리 임포트
139+
import _ from 'lodash';
140+
141+
// ✅ 좋은 예: 필요한 것만 임포트
142+
import debounce from 'lodash/debounce';
143+
```
144+
145+
**Dynamic Imports**:
146+
```typescript
147+
// ✅ 필요할 때만 로드
148+
button.addEventListener('click', async () => {
149+
const { default: Chart } = await import('chart.js');
150+
new Chart(ctx, config);
151+
});
152+
```
153+
154+
### Step 4: 이미지 최적화
155+
156+
**Next.js Image 컴포넌트**:
157+
```tsx
158+
import Image from 'next/image';
159+
160+
function ProductImage() {
161+
return (
162+
<Image
163+
src="/product.jpg"
164+
alt="Product"
165+
width={500}
166+
height={500}
167+
priority // LCP 이미지인 경우
168+
placeholder="blur" // 블러 플레이스홀더
169+
sizes="(max-width: 768px) 100vw, 50vw"
170+
/>
171+
);
172+
}
173+
```
174+
175+
**WebP 포맷 사용**:
176+
```html
177+
<picture>
178+
<source srcset="image.webp" type="image/webp">
179+
<source srcset="image.jpg" type="image/jpeg">
180+
<img src="image.jpg" alt="Fallback">
181+
</picture>
182+
```
183+
184+
### Step 5: 데이터베이스 쿼리 최적화
185+
186+
**N+1 쿼리 문제 해결**:
187+
```typescript
188+
// ❌ 나쁜 예: N+1 queries
189+
const posts = await db.post.findMany();
190+
for (const post of posts) {
191+
const author = await db.user.findUnique({ where: { id: post.authorId } });
192+
// 101번 쿼리 (1 + 100)
193+
}
194+
195+
// ✅ 좋은 예: JOIN 또는 include
196+
const posts = await db.post.findMany({
197+
include: {
198+
author: true
199+
}
200+
});
201+
// 1번 쿼리
202+
```
203+
204+
**인덱스 추가**:
205+
```sql
206+
-- 느린 쿼리 식별
207+
EXPLAIN ANALYZE SELECT * FROM users WHERE email = 'test@example.com';
208+
209+
-- 인덱스 추가
210+
CREATE INDEX idx_users_email ON users(email);
211+
212+
-- 복합 인덱스
213+
CREATE INDEX idx_orders_user_date ON orders(user_id, created_at);
214+
```
215+
216+
**캐싱 (Redis)**:
217+
```typescript
218+
async function getUserProfile(userId: string) {
219+
// 1. 캐시 확인
220+
const cached = await redis.get(`user:${userId}`);
221+
if (cached) {
222+
return JSON.parse(cached);
223+
}
224+
225+
// 2. DB 조회
226+
const user = await db.user.findUnique({ where: { id: userId } });
227+
228+
// 3. 캐시 저장 (1시간)
229+
await redis.setex(`user:${userId}`, 3600, JSON.stringify(user));
230+
231+
return user;
232+
}
233+
```
234+
235+
## Output format
236+
237+
### 성능 최적화 체크리스트
238+
239+
```markdown
240+
## Frontend
241+
- [ ] React.memo로 불필요한 리렌더링 방지
242+
- [ ] useMemo/useCallback 적절히 사용
243+
- [ ] Lazy loading & Code splitting
244+
- [ ] 이미지 최적화 (WebP, lazy loading)
245+
- [ ] 번들 크기 분석 및 감소
246+
247+
## Backend
248+
- [ ] N+1 쿼리 제거
249+
- [ ] 데이터베이스 인덱스 추가
250+
- [ ] Redis 캐싱
251+
- [ ] API Response 압축 (gzip)
252+
- [ ] CDN 사용
253+
254+
## 측정
255+
- [ ] Lighthouse 점수 90+
256+
- [ ] LCP < 2.5s
257+
- [ ] FID < 100ms
258+
- [ ] CLS < 0.1
259+
```
260+
261+
## Constraints
262+
263+
### 필수 규칙 (MUST)
264+
265+
1. **측정 먼저**: 추측하지 말고 프로파일링
266+
2. **점진적 개선**: 한 번에 하나씩 최적화
267+
3. **성능 모니터링**: 지속적으로 추적
268+
269+
### 금지 사항 (MUST NOT)
270+
271+
1. **조기 최적화**: 병목이 없는데 최적화하지 않음
272+
2. **가독성 희생**: 성능을 위해 코드를 복잡하게 만들지 않음
273+
274+
## Best practices
275+
276+
1. **80/20 법칙**: 20% 노력으로 80% 개선
277+
2. **사용자 중심**: 실제 사용자 경험 개선에 집중
278+
3. **자동화**: CI에서 성능 회귀 테스트
279+
280+
## References
281+
282+
- [web.dev/vitals](https://web.dev/vitals/)
283+
- [React Optimization](https://react.dev/learn/render-and-commit#optimizing-performance)
284+
- [Webpack Bundle Analyzer](https://github.com/webpack-contrib/webpack-bundle-analyzer)
285+
286+
## Metadata
287+
288+
### 버전
289+
- **현재 버전**: 1.0.0
290+
- **최종 업데이트**: 2025-01-01
291+
- **호환 플랫폼**: Claude, ChatGPT, Gemini
292+
293+
### 관련 스킬
294+
- [database-schema-design](../../backend/database/SKILL.md)
295+
- [ui-components](../../frontend/ui-components/SKILL.md)
296+
297+
### 태그
298+
`#performance` `#optimization` `#React` `#caching` `#lazy-loading` `#web-vitals` `#code-quality`
299+
300+
## Examples
301+
302+
### Example 1: Basic usage
303+
<!-- Add example content here -->
304+
305+
### Example 2: Advanced usage
306+
<!-- Add advanced example content here -->
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
N:performance-optimization
2+
D:Optimize application performance for speed, efficiency, and scalability. Use when improving page ...
3+
G:performance optimization React lazy-loading caching
4+
U[4]:
5+
**느린 페이지 로드**: Lighthouse 점수 낮음
6+
**느린 렌더링**: 사용자 인터랙션 지연
7+
**큰 번들 크기**: 다운로드 시간 증가
8+
**느린 쿼리**: 데이터베이스 병목
9+
S[5]{n,action}:
10+
1,성능 측정
11+
2,React 최적화
12+
3,번들 크기 최적화
13+
4,이미지 최적화
14+
5,데이터베이스 쿼리 최적화

.cursor/rules/use-skills.mdc

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
---
2+
description: Route every request through the appropriate installed agent skills before responding
3+
alwaysApply: true
4+
---
5+
6+
# Always Use Installed Skills
7+
8+
Before responding to any request, check which installed skills are relevant and read their SKILL.md to follow their instructions. Multiple skills may apply to a single request.
9+
10+
## Skill Registry
11+
12+
| Skill | Path | Trigger |
13+
|-------|------|---------|
14+
| Brainstorming | ~/.agents/skills/brainstorming/SKILL.md | Any creative work: new features, components, functionality, or behavior changes. **Must run before implementation.** |
15+
| Software Architecture | ~/.agents/skills/software-architecture/SKILL.md | Writing, designing, reviewing, or analyzing any code |
16+
| Subagent-Driven Development | ~/.agents/skills/subagent-driven-development/SKILL.md | Executing an implementation plan with independent tasks |
17+
| Prompt Engineering Patterns | ~/.agents/skills/prompt-engineering-patterns/SKILL.md | Designing, optimizing, or debugging LLM prompts |
18+
| Web Design Guidelines | ~/.agents/skills/web-design-guidelines/SKILL.md | Reviewing or building UI — accessibility, UX, design audits |
19+
| Planning with Files | ~/.claude/skills/SKILL.md | Complex multi-step tasks (3+ steps) or research projects |
20+
| Find Skills | ~/.agents/skills/find-skills/SKILL.md | User asks "how do I do X", wants to extend capabilities, or needs a domain-specific tool |
21+
| Create Rule | ~/.cursor/skills-cursor/create-rule/SKILL.md | Creating or modifying .cursor/rules/*.mdc files |
22+
| Create Skill | ~/.cursor/skills-cursor/create-skill/SKILL.md | Creating new SKILL.md files or skill directories |
23+
| Create Subagent | ~/.cursor/skills-cursor/create-subagent/SKILL.md | Creating custom subagent .md files in .cursor/agents/ |
24+
| Migrate to Skills | ~/.cursor/skills-cursor/migrate-to-skills/SKILL.md | Converting old rules or slash commands to skills format |
25+
| Update Cursor Settings | ~/.cursor/skills-cursor/update-cursor-settings/SKILL.md | Changing editor settings, themes, keybindings, or settings.json |
26+
| Performance Optimization | .agents/skills/performance-optimization/SKILL.md | Improving page load times, bundle size, database queries, caching, React optimization, or fixing performance bottlenecks |
27+
| Code Refactoring | .agents/skills/code-refactoring/SKILL.md | Simplifying complex code, removing duplication, applying design patterns (Extract Method, SOLID, DRY), or cleaning up technical debt |
28+
29+
## Routing Rules
30+
31+
1. **Read before acting** — For each matching skill, read its SKILL.md and follow its instructions immediately.
32+
2. **Multiple skills can apply** — e.g. a new feature request triggers both Brainstorming and Software Architecture.
33+
3. **Brainstorming gates implementation** — Never start coding a new feature without going through Brainstorming first and getting user approval on the design.
34+
4. **Software Architecture always applies to code** — Any code you write, review, or modify must follow its principles (early returns, no deep nesting, library-first, domain naming, clean architecture).
35+
5. **Planning with Files for complex work** — If a task requires 3+ steps, create task_plan.md, findings.md, and progress.md before starting.
36+
6. **Find Skills as fallback** — When no installed skill covers the domain, search for one via `npx skills find`.
37+
7. **Performance Optimization for perf work** — When fixing slowness, optimizing queries, reducing bundle size, or improving Web Vitals, follow its measurement-first approach.
38+
8. **Code Refactoring for cleanup** — When simplifying code, removing duplication, or applying design patterns, follow its behavior-preservation workflow (test first, small steps, validate after).

.cursor/settings.json

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
{
2+
"plugins": {
3+
"superpowers": {
4+
"enabled": true
5+
},
6+
"compound-engineering": {
7+
"enabled": true
8+
}
9+
}
10+
}

.env.example

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
DATABASE_URL=postgresql://solagent:dev_password@localhost:5432/solagent
2+
REDIS_URL=redis://localhost:6379
3+
REDPANDA_BROKERS=localhost:9092
4+
SOLANA_RPC_URL=https://api.devnet.solana.com
5+
SOLANA_NETWORK=devnet
6+
HELIUS_API_KEY=
7+
TURNKEY_API_KEY=
8+
TURNKEY_ORGANIZATION_ID=
9+
KORA_URL=http://localhost:8911
10+
LOG_LEVEL=debug

0 commit comments

Comments
 (0)