Skip to content

Commit 83f5fe2

Browse files
committed
added AGENTS + CLAUDE md files
1 parent 03dc4f4 commit 83f5fe2

File tree

3 files changed

+528
-0
lines changed

3 files changed

+528
-0
lines changed

AGENTS.md

Lines changed: 394 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,394 @@
1+
# AGENTS.md - Game-Based Reward System Development Guide
2+
3+
## Project Overview
4+
5+
This document provides high-level directives for creating a Web3 gaming platform with an integrated reward system using the Thirdweb API. The architecture described here can be adapted to any technology stack while maintaining the core Web3 functionality patterns.
6+
7+
## System Architecture
8+
9+
### Core Components
10+
11+
1. **Frontend Game Interface** - Interactive game client with real-time gameplay
12+
2. **Authentication System** - Web3 wallet management and user sessions
13+
3. **Reward Engine** - Token distribution and game economics
14+
4. **Transaction Management** - Blockchain interaction and state management
15+
5. **Asset Management** - NFT and token inventory system
16+
17+
## Thirdweb API Integration Patterns
18+
19+
The app uses several thirdweb API v1 endpoints organized by functionality:
20+
21+
> **📚 Complete API Reference**: For full thirdweb API documentation, see [thirdweb API Reference](https://api.thirdweb.com/llms.txt)
22+
23+
### 1. User Authentication System
24+
25+
#### Implementation Strategy
26+
- Use email-based authentication for simplified user onboarding
27+
- Implement automatic wallet creation and management behind the scenes
28+
- Maintain secure session management with CSRF protection
29+
30+
#### Thirdweb API Endpoints Used
31+
- `POST /v1/auth/initiate` - Start authentication flow with email verification
32+
- `POST /v1/auth/complete` - Complete authentication and receive wallet credentials
33+
- `GET /v1/wallets/me` - Retrieve authenticated user's wallet details
34+
35+
#### Key Directives
36+
1. **Seamless Onboarding**: Abstract Web3 complexity from users during initial signup
37+
2. **Session Persistence**: Implement secure local storage for user sessions with expiration
38+
3. **Error Handling**: Provide clear feedback for authentication failures and retry mechanisms
39+
4. **Security First**: Always validate CSRF tokens and implement proper origin checking
40+
41+
#### Implementation Pattern
42+
```
43+
Client Request → Email Input → OTP Verification → Wallet Creation → Session Storage
44+
```
45+
46+
### 2. Transaction Management System
47+
48+
#### Implementation Strategy
49+
- Batch related transactions for gas efficiency
50+
- Implement transaction encoding for custom contract interactions
51+
- Provide real-time transaction status updates to users
52+
53+
#### Thirdweb API Endpoints Used
54+
- `POST /v1/transactions` - Submit encoded transactions to blockchain
55+
- `POST /v1/contracts/write` - Execute smart contract method calls
56+
- `POST /v1/contracts/read` - Query contract state and balances
57+
58+
#### Key Directives
59+
1. **Gas Optimization**: Batch multiple operations in single transactions where possible
60+
2. **User Experience**: Provide clear transaction status and confirmation feedback
61+
3. **Error Recovery**: Implement retry logic for failed transactions
62+
4. **State Synchronization**: Update local state immediately after successful transactions
63+
64+
#### Transaction Flow Pattern
65+
```
66+
User Action → Transaction Encoding → Blockchain Submission → Status Monitoring → State Update
67+
```
68+
69+
### 3. Reward System Architecture
70+
71+
#### Implementation Strategy
72+
- Server-side reward calculation to prevent client-side manipulation
73+
- Real-time token distribution based on game performance
74+
- Transparent and auditable reward mechanics
75+
76+
#### Thirdweb API Endpoints Used
77+
- `POST /v1/contracts/write` - Mint reward tokens directly to user wallets
78+
- `GET /v1/contracts/read` - Query user token balances for display
79+
- `POST /v1/transactions` - Execute complex reward distribution logic
80+
81+
#### Key Directives
82+
1. **Security First**: Always validate rewards server-side using game performance metrics
83+
2. **Immediate Gratification**: Distribute rewards in real-time during or immediately after gameplay
84+
3. **Transparency**: Provide clear feedback on reward calculation and distribution
85+
4. **Scalability**: Design reward system to handle high-frequency distributions efficiently
86+
87+
#### Reward Distribution Pattern
88+
```
89+
Game Completion → Performance Analysis → Server Validation → Token Minting → Balance Update
90+
```
91+
92+
### 4. Digital Asset Purchasing System
93+
94+
#### Implementation Strategy
95+
- Create marketplace for purchasable NFT assets (characters, power-ups, cosmetics)
96+
- Implement multi-step transaction flows with proper approval handling
97+
- Provide clear pricing and ownership verification before purchases
98+
- Handle both ERC-20 token payments and direct purchases
99+
100+
#### Thirdweb API Endpoints Used
101+
- `POST /v1/contracts/read` - Check user token balances and asset ownership
102+
- `POST /v1/contracts/write` - Execute approval and purchase transactions
103+
- `POST /v1/transactions` - Handle batched approval + purchase operations
104+
- `GET /v1/wallets/tokens` - Retrieve comprehensive token balances
105+
- `GET /v1/wallets/nfts` - Query user's NFT inventory
106+
107+
#### Key Directives
108+
1. **Two-Step Purchase Flow**: Always implement approve → purchase pattern for ERC-20 payments
109+
2. **Balance Verification**: Check user balances before allowing purchase attempts
110+
3. **Transaction Batching**: Combine approval and purchase into single user action when possible
111+
4. **Price Transparency**: Display costs clearly in both token amounts and USD equivalents
112+
5. **Ownership Verification**: Prevent duplicate purchases of unique assets
113+
6. **Gas Estimation**: Provide transaction cost estimates before execution
114+
115+
#### Purchase Flow Patterns
116+
117+
**ERC-20 Token Purchase:**
118+
```
119+
Asset Selection → Balance Check → Price Display → Approval Transaction → Purchase Transaction → Inventory Update
120+
```
121+
122+
**Direct Purchase (Native Token):**
123+
```
124+
Asset Selection → Balance Check → Price Display → Purchase Transaction → Inventory Update
125+
```
126+
127+
**Batch Purchase:**
128+
```
129+
Multiple Asset Selection → Total Cost Calculation → Batch Approval → Batch Purchase → Bulk Inventory Update
130+
```
131+
132+
#### Purchase Implementation Guidelines
133+
1. **Pre-Purchase Validation**: Always verify sufficient balance and asset availability
134+
2. **Progressive Loading**: Show transaction status for each step in multi-step flows
135+
3. **Error Recovery**: Provide clear retry mechanisms for failed transactions
136+
4. **Receipt Generation**: Create transaction receipts with asset details and hashes
137+
5. **Inventory Sync**: Immediately update local state after successful purchases
138+
139+
### 5. Asset Management and NFT System
140+
141+
#### Implementation Strategy
142+
- Real-time inventory management and balance tracking
143+
- Asset utility integration with gameplay mechanics
144+
- Transfer and trading capabilities (if desired)
145+
- Asset metadata and visual representation
146+
147+
#### Thirdweb API Endpoints Used
148+
- `GET /v1/contracts/read` - Query NFT ownership and metadata
149+
- `POST /v1/contracts/read` - Batch read operations for multiple assets
150+
- `GET /v1/wallets/nfts` - Comprehensive NFT inventory retrieval
151+
- `POST /v1/transactions` - Handle asset transfers and burns
152+
153+
#### Key Directives
154+
1. **Real-time Updates**: Keep inventory synchronized with blockchain state
155+
2. **Asset Utility**: Integrate owned assets meaningfully into gameplay
156+
3. **Visual Representation**: Display asset images and metadata clearly
157+
4. **Usage Tracking**: Monitor asset usage for analytics and balancing
158+
159+
#### Asset Management Pattern
160+
```
161+
Game Launch → Inventory Fetch → Asset Display → Usage Integration → State Sync
162+
```
163+
164+
## Technical Implementation Guidelines
165+
166+
### Environment Configuration
167+
168+
#### Required Environment Variables
169+
```bash
170+
# Thirdweb Configuration
171+
THIRDWEB_SECRET_KEY=your_secret_key
172+
NEXT_PUBLIC_THIRDWEB_CLIENT_ID=your_client_id
173+
THIRDWEB_API_BASE_URL=https://api.thirdweb.com
174+
175+
# Smart Contract Addresses
176+
TOKEN_CONTRACT_ADDRESS=your_erc20_token_contract
177+
NFT_CONTRACT_ADDRESS=your_erc1155_nft_contract
178+
ADMIN_ADDRESS=your_admin_wallet_address
179+
180+
# Network Configuration
181+
CHAIN_ID=your_target_chain_id
182+
183+
# Game Economy Settings
184+
GAME_REWARD_BASE=minimum_reward_per_game
185+
GAME_REWARD_MAX=maximum_reward_per_game
186+
```
187+
188+
### Session Management and Security
189+
190+
#### Session Architecture Strategy
191+
- Implement hybrid session management combining server-side security with client-side convenience
192+
- Use HTTP-only cookies for sensitive authentication tokens
193+
- Maintain separate CSRF tokens for state-changing operations
194+
- Provide session persistence options for user convenience
195+
196+
#### Session Management Implementation
197+
198+
##### Server-Side Session Security
199+
1. **HTTP-Only Cookie Storage**: Store authentication tokens in secure, HTTP-only cookies
200+
2. **CSRF Token Pairing**: Generate unique CSRF tokens paired with each session
201+
3. **Session Expiration**: Implement configurable session timeouts (recommended: 1-7 days)
202+
4. **Token Rotation**: Periodically refresh authentication tokens for long-lived sessions
203+
5. **Origin Validation**: Verify request origins match expected domains
204+
205+
##### Client-Side Session Convenience
206+
1. **Local Storage Persistence**: Store non-sensitive user preferences and UI state
207+
2. **Remember Me Functionality**: Allow users to opt into extended session duration
208+
3. **Automatic Re-authentication**: Detect expired sessions and prompt for re-authentication
209+
4. **Session Recovery**: Gracefully handle network interruptions and session restoration
210+
211+
##### Session Lifecycle Management
212+
```
213+
Login → Token Generation → Cookie Storage → CSRF Pairing → Session Validation → Periodic Refresh → Logout/Expiry
214+
```
215+
216+
#### Session Security Best Practices
217+
218+
##### Authentication Security
219+
1. **CSRF Protection**: Implement CSRF tokens for all state-changing operations
220+
2. **Secure Cookie Configuration**: Use secure, SameSite, and HTTP-only flags appropriately
221+
3. **Origin Validation**: Verify request origins for additional security
222+
4. **Input Validation**: Validate all user inputs server-side before processing
223+
5. **Session Invalidation**: Immediately invalidate sessions on logout or security events
224+
225+
##### Token Management
226+
1. **Token Entropy**: Use cryptographically secure random token generation
227+
2. **Token Scope**: Limit token permissions to minimum required scope
228+
3. **Token Storage**: Never store sensitive tokens in localStorage or sessionStorage
229+
4. **Token Transmission**: Always transmit tokens over HTTPS in production
230+
5. **Token Cleanup**: Implement automatic cleanup of expired tokens
231+
232+
##### Session Monitoring
233+
1. **Concurrent Session Limits**: Optionally limit concurrent sessions per user
234+
2. **Suspicious Activity Detection**: Monitor for unusual login patterns
235+
3. **Session Analytics**: Track session duration and user engagement metrics
236+
4. **Security Event Logging**: Log authentication failures and security events
237+
238+
#### Session Implementation Patterns
239+
240+
##### Session Establishment
241+
```
242+
Email Verification → Thirdweb Auth → Token Receipt → Cookie Creation → CSRF Generation → Client Notification
243+
```
244+
245+
##### Session Validation
246+
```
247+
Request Received → Cookie Extraction → Token Validation → CSRF Verification → Origin Check → Request Processing
248+
```
249+
250+
##### Session Refresh
251+
```
252+
Token Expiry Detection → Background Refresh → New Token Storage → UI State Preservation
253+
```
254+
255+
#### Transaction Security
256+
1. **Server-Side Validation**: Always validate transaction parameters on the server
257+
2. **Rate Limiting**: Implement appropriate rate limits for transaction endpoints
258+
3. **Balance Checks**: Verify user balances before executing spend transactions
259+
4. **Error Handling**: Provide secure error messages that don't leak sensitive information
260+
5. **Transaction Signing**: Ensure all transactions are properly signed and authorized
261+
262+
### Database and State Management
263+
264+
#### Local State Patterns
265+
1. **Optimistic Updates**: Update UI immediately while transactions confirm
266+
2. **Error Recovery**: Revert optimistic updates if transactions fail
267+
3. **Cache Management**: Implement appropriate caching for blockchain data
268+
4. **Sync Strategies**: Regularly sync local state with blockchain truth
269+
270+
#### Persistent Storage
271+
1. **User Preferences**: Store non-sensitive user settings locally
272+
2. **Game Progress**: Maintain game state separate from blockchain assets
273+
3. **Session Data**: Securely store authentication tokens with proper expiration
274+
4. **Cache Invalidation**: Implement strategies for cache freshness and invalidation
275+
276+
## Game Economics Design
277+
278+
### Token Economy Structure
279+
280+
#### Primary Token (ERC-20)
281+
- **Purpose**: Primary in-game currency for purchases and rewards
282+
- **Distribution**: Performance-based rewards, direct purchases, special events
283+
- **Utility**: Asset purchases, power-up acquisitions, special features
284+
- **Economics**: Balanced inflation through gameplay rewards and deflation through purchases
285+
286+
#### NFT Assets (ERC-1155)
287+
- **Characters**: Unique playable assets with different abilities or aesthetics
288+
- **Power-ups**: Consumable items that provide temporary gameplay advantages
289+
- **Collectibles**: Rare items with potential future utility or trading value
290+
- **Achievements**: Non-transferable proof of accomplishments
291+
292+
### Reward Calculation Strategy
293+
294+
#### Performance Metrics
295+
1. **Base Rewards**: Minimum tokens for game completion
296+
2. **Performance Multipliers**: Additional rewards based on score, time, or achievements
297+
3. **Streak Bonuses**: Increased rewards for consecutive play sessions
298+
4. **Special Events**: Temporary multipliers for engagement campaigns
299+
300+
#### Anti-Abuse Measures
301+
1. **Server Validation**: All reward calculations performed server-side
302+
2. **Rate Limiting**: Prevent rapid-fire reward claiming
303+
3. **Behavioral Analysis**: Monitor for suspicious patterns in gameplay
304+
4. **Manual Review**: Flag unusually high reward claims for verification
305+
306+
## Implementation Roadmap
307+
308+
### Phase 1: Foundation (Weeks 1-2)
309+
1. Set up basic project structure with chosen framework
310+
2. Implement Thirdweb authentication system
311+
3. Create basic game interface and mechanics
312+
4. Establish smart contract integration patterns
313+
314+
### Phase 2: Core Features (Weeks 3-4)
315+
1. Implement reward distribution system
316+
2. Create asset management and NFT integration
317+
3. Build transaction management with proper error handling
318+
4. Add comprehensive input validation and security measures
319+
320+
### Phase 3: Enhancement (Weeks 5-6)
321+
1. Optimize transaction batching and gas efficiency
322+
2. Implement advanced game features and power-ups
323+
3. Add comprehensive monitoring and analytics
324+
4. Perform security audits and penetration testing
325+
326+
### Phase 4: Polish (Weeks 7-8)
327+
1. Enhance user experience with loading states and feedback
328+
2. Implement comprehensive error recovery mechanisms
329+
3. Add social features and leaderboards
330+
4. Prepare for production deployment and scaling
331+
332+
## Technology Stack Flexibility
333+
334+
### Frontend Framework Options
335+
- **React/Next.js**: Recommended for full-stack development with built-in API routes
336+
- **Vue.js/Nuxt.js**: Alternative with similar capabilities and patterns
337+
- **Svelte/SvelteKit**: Lightweight option with excellent performance
338+
- **Vanilla JS**: For maximum control and minimal dependencies
339+
340+
### Backend/API Layer Options
341+
- **Next.js API Routes**: Integrated solution for React applications
342+
- **Express.js**: Standalone Node.js server with full control
343+
- **Fastify**: High-performance alternative to Express
344+
- **Python Flask/FastAPI**: For Python-based backend development
345+
- **Go/Rust**: For maximum performance and efficiency
346+
347+
### Database Options
348+
- **PostgreSQL**: For complex relational data and analytics
349+
- **MongoDB**: For flexible document-based storage
350+
- **SQLite**: For simple applications with minimal setup
351+
- **Redis**: For caching and session management
352+
- **Local Storage/IndexedDB**: For client-side data persistence
353+
354+
## Performance Optimization
355+
356+
### Blockchain Interaction Optimization
357+
1. **Batch Requests**: Group multiple read operations together
358+
2. **Caching Strategy**: Cache frequently accessed blockchain data
359+
3. **Lazy Loading**: Load blockchain data only when needed
360+
4. **Connection Pooling**: Reuse connections for API requests
361+
362+
### User Experience Optimization
363+
1. **Optimistic UI**: Update interface before blockchain confirmation
364+
2. **Loading States**: Provide clear feedback during async operations
365+
3. **Error Recovery**: Graceful handling of network and blockchain errors
366+
4. **Progressive Enhancement**: Ensure basic functionality without Web3
367+
368+
### Game Performance
369+
1. **Frame Rate**: Maintain consistent 60fps gameplay
370+
2. **Memory Management**: Properly clean up game objects and listeners
371+
3. **Asset Optimization**: Compress images and audio files
372+
4. **Network Optimization**: Minimize API calls during active gameplay
373+
374+
## Monitoring and Analytics
375+
376+
### Key Metrics to Track
377+
1. **User Engagement**: Session duration, return rate, game completions
378+
2. **Economic Metrics**: Token distribution, NFT purchases, wallet balances
379+
3. **Technical Performance**: API response times, transaction success rates
380+
4. **Security Events**: Failed authentication attempts, suspicious activities
381+
382+
### Implementation Tools
383+
1. **Application Monitoring**: Error tracking and performance monitoring
384+
2. **Blockchain Analytics**: Transaction monitoring and wallet tracking
385+
3. **User Analytics**: Gameplay patterns and user behavior analysis
386+
4. **Business Intelligence**: Revenue tracking and economic health metrics
387+
388+
## Conclusion
389+
390+
This architecture provides a robust foundation for building Web3 gaming applications with integrated reward systems. The patterns described here leverage Thirdweb's infrastructure while maintaining flexibility for different technology choices and business requirements.
391+
392+
The key to success lies in balancing Web3 functionality with traditional gaming user experience expectations. Focus on making blockchain interactions transparent and beneficial to users while maintaining the security and decentralization benefits of Web3 technology.
393+
394+
Remember that this is a living document - adapt these patterns based on your specific game mechanics, target audience, and business objectives while maintaining the core principles of security, user experience, and economic sustainability.

0 commit comments

Comments
 (0)