@turtleclub/hooks 0.5.0-beta.12 → 0.5.0-beta.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,51 +1,220 @@
1
- # @turtledev/hooks
1
+ # @turtle-club/hooks
2
2
 
3
- React hooks and utilities for building applications with the Turtle ecosystem.
3
+ React hooks package for Turtle Club APIs, providing type-safe data fetching with TanStack Query integration.
4
4
 
5
5
  ## Installation
6
6
 
7
7
  ```bash
8
- npm install @turtledev/hooks
9
- # or
10
- yarn add @turtledev/hooks
11
- # or
12
- bun add @turtledev/hooks
8
+ bun add @turtle-club/hooks
13
9
  ```
14
10
 
15
- ## Features
11
+ ## Setup
16
12
 
17
- - 🎣 **React Query hooks** for API endpoints
18
- - 🔧 **Utility functions** for chains, formatting, and numbers
19
- - 🔄 **Automatic caching** and persistence
20
- - 📝 **TypeScript** support with full type safety
13
+ Wrap your application with the `TurtleHooksProvider`:
21
14
 
22
- ## Usage
15
+ ```tsx
16
+ import { TurtleHooksProvider } from '@turtle-club/hooks';
23
17
 
24
- ### API Hooks
18
+ function App() {
19
+ return (
20
+ <TurtleHooksProvider
21
+ apiConfig={{
22
+ apiKey: 'your-api-key',
23
+ earnApiKey: 'your-earn-api-key'
24
+ }}
25
+ >
26
+ <YourApp />
27
+ </TurtleHooksProvider>
28
+ );
29
+ }
30
+ ```
31
+
32
+ ## Package Structure
33
+
34
+ ```
35
+ src/
36
+ ├── index.ts # Root export (re-exports v2)
37
+ └── v2/
38
+ ├── index.ts # Main entry point (aggregates all endpoints)
39
+ ├── lib/ # Shared utilities
40
+ │ ├── api-client.ts # HTTP client singleton (supports "api" | "earn" domains)
41
+ │ ├── query-config.ts # TanStack Query defaults
42
+ │ └── turtle-provider.tsx # React context provider
43
+ ├── schemas/ # Shared types across endpoints
44
+ │ └── shared.ts # Common schemas (Chain, Token, Opportunity, etc.)
45
+ └── [endpoint]/ # Individual endpoint folders
46
+ ├── api.ts # API functions
47
+ ├── hooks.ts # React hooks (queries & mutations)
48
+ ├── queries.ts # TanStack Query key factory
49
+ ├── schema.ts # Zod schemas & types
50
+ └── index.ts # Barrel export
51
+ ```
52
+
53
+ ## Endpoint Structure Pattern
54
+
55
+ Each endpoint follows a consistent 5-file structure:
56
+
57
+ ### 1. `schema.ts` - Zod Schemas & Types
58
+ ```typescript
59
+ import { z } from "zod";
60
+
61
+ // Request schema (if needed)
62
+ export const getResourceRequestSchema = z.object({
63
+ filter: z.string().optional(),
64
+ });
65
+
66
+ // Response schema
67
+ export const resourceResponseSchema = z.object({
68
+ id: z.string(),
69
+ name: z.string(),
70
+ });
71
+
72
+ // Infer types from schemas
73
+ export type GetResourceRequest = z.infer<typeof getResourceRequestSchema>;
74
+ export type ResourceResponse = z.infer<typeof resourceResponseSchema>;
75
+ ```
76
+
77
+ ### 2. `api.ts` - API Functions
78
+ ```typescript
79
+ import type { QueryFunctionContext } from "@tanstack/react-query";
80
+ import { apiClient } from "../lib/api-client";
81
+ import { resourceResponseSchema, type ResourceResponse } from "./schema";
82
+
83
+ export async function getResource(
84
+ id: string,
85
+ context?: QueryFunctionContext
86
+ ): Promise<ResourceResponse> {
87
+ const data = await apiClient.fetch(`/v1/resource/${id}`, {
88
+ method: "GET",
89
+ domain: "api", // or "earn" for Earn API
90
+ signal: context?.signal,
91
+ });
92
+
93
+ const result = resourceResponseSchema.safeParse(data);
94
+ if (!result.success) {
95
+ console.log("[ZOD ERROR]", result.error);
96
+ throw new Error(`Failed to parse resource: ${result.error.message}`);
97
+ }
98
+ return result.data;
99
+ }
100
+ ```
101
+
102
+ ### 3. `queries.ts` - Query Key Factory
103
+ ```typescript
104
+ import { createQueryKeys } from "@lukemorales/query-key-factory";
105
+ import { getResource } from "./api";
25
106
 
107
+ export const resourceQueries = createQueryKeys("resource", {
108
+ byId: (id: string) => ({
109
+ queryKey: [id],
110
+ queryFn: (context) => getResource(id, context),
111
+ }),
112
+ list: (filters?: Filters) => ({
113
+ queryKey: [{ filters }],
114
+ queryFn: (context) => getResources(filters, context),
115
+ }),
116
+ });
117
+ ```
118
+
119
+ ### 4. `hooks.ts` - React Hooks
26
120
  ```typescript
27
- import { useOrganizations, useConfig } from "@turtledev/hooks";
28
-
29
- function MyComponent() {
30
- const { data: organizations, isLoading } = useOrganizations();
31
-
32
- if (isLoading) return <div>Loading...</div>;
33
-
34
- return <div>{organizations?.name}</div>;
121
+ import { useQuery, useMutation } from "@tanstack/react-query";
122
+ import { resourceQueries } from "./queries";
123
+ import { createQueryOptions } from "../lib/query-config";
124
+
125
+ export interface UseResourceOptions
126
+ extends Omit<UseQueryOptions<ResourceResponse, Error>, "queryKey" | "queryFn"> {
127
+ id: string;
35
128
  }
129
+
130
+ export function useResource({ id, ...options }: UseResourceOptions) {
131
+ return useQuery(createQueryOptions(resourceQueries.byId(id), options));
132
+ }
133
+
134
+ // For mutations
135
+ export function useCreateResource() {
136
+ return useMutation({
137
+ mutationFn: (input: CreateResourceInput) => createResource(input),
138
+ });
139
+ }
140
+ ```
141
+
142
+ ### 5. `index.ts` - Barrel Export
143
+ ```typescript
144
+ export * from "./schema";
145
+ export * from "./api";
146
+ export * from "./queries";
147
+ export * from "./hooks";
148
+ ```
149
+
150
+ ## Available Endpoints
151
+
152
+ ### Earn API (`domain: "earn"`)
153
+ | Endpoint | Description |
154
+ |----------|-------------|
155
+ | `earn-opportunities` | Earn protocol opportunities |
156
+ | `earn-route` | Route calculations for deposits/withdrawals |
157
+ | `earn-membership` | User membership management |
158
+ | `earn-deposits` | Deposit records |
159
+ | `earn-interactions` | Deposit/withdraw/claim interactions |
160
+ | `enso-balances` | Enso protocol balances |
161
+
162
+ ### Main API (`domain: "api"`)
163
+ | Endpoint | Description |
164
+ |----------|-------------|
165
+ | `opportunities` | General opportunities |
166
+ | `products` | Product CRUD operations |
167
+ | `balance` | Portfolio and token balances |
168
+ | `widget` | Widget configuration |
169
+ | `supported-chains` | Chain configuration |
170
+ | `supported-tokens` | Token configuration |
171
+ | `geocheck` | Geographic checks |
172
+ | `streams` | Stream data |
173
+ | `swap` | Swap routing |
174
+ | `users` | User data |
175
+
176
+ ## Shared Schemas
177
+
178
+ Import shared types from `schemas/shared.ts`:
179
+
180
+ ```typescript
181
+ import {
182
+ chainSchema,
183
+ tokenSchema,
184
+ opportunitySchema,
185
+ type Chain,
186
+ type Token,
187
+ type Opportunity
188
+ } from '@turtle-club/hooks';
36
189
  ```
37
190
 
38
- ## Available Hooks
191
+ Available shared schemas:
192
+ - `chainSchema` / `Chain`
193
+ - `tokenSchema` / `Token`
194
+ - `organizationSchema` / `Organization`
195
+ - `productSchema` / `Product`
196
+ - `vaultConfigSchema` / `VaultConfig`
197
+ - `lendingConfigSchema` / `LendingConfig`
198
+ - `incentiveSchema` / `Incentive`
199
+ - `opportunitySchema` / `Opportunity`
200
+ - `paginationMetadataSchema` / `PaginationMetadata`
201
+
202
+ ## Query Defaults
203
+
204
+ All queries use consistent defaults from `lib/query-config.ts`:
39
205
 
40
- ### Endpoints
41
- - `useOrganizations()` - Get organization data
42
- - `useOrganizationDeals()` - Get organization deals
43
- - `useOrganizationsDeals()` - Get all organizations deals
44
- - `useProjectTvl()` - Get project TVL data
45
- - `useExists()` - Check if user exists
46
- - `usePrepareSignup()` - Prepare signup process
47
- - `useSignup()` - Complete signup
206
+ ```typescript
207
+ export const queryDefaults = {
208
+ staleTime: 5 * 60 * 1000, // 5 minutes
209
+ gcTime: 10 * 60 * 1000, // 10 minutes
210
+ retry: 1,
211
+ refetchOnWindowFocus: false,
212
+ };
213
+ ```
48
214
 
49
- ### Configuration
50
- - `useConfig()` - Get current API configuration
215
+ ## Adding a New Endpoint
51
216
 
217
+ 1. Create a new folder in `src/v2/` with the endpoint name
218
+ 2. Create the 5 standard files: `schema.ts`, `api.ts`, `queries.ts`, `hooks.ts`, `index.ts`
219
+ 3. Add the queries import and merge in `src/v2/index.ts`
220
+ 4. Add the export in `src/v2/index.ts`