@goodz-core/sdk 0.1.0 → 0.2.0
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 +296 -0
- package/dist/chunk-K6IFJWLB.js +924 -0
- package/dist/chunk-K6IFJWLB.js.map +1 -0
- package/dist/index.d.ts +4 -1
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -1
- package/dist/ui/index.d.ts +56 -0
- package/dist/ui/index.js +3 -0
- package/dist/ui/index.js.map +1 -0
- package/package.json +26 -3
package/README.md
ADDED
|
@@ -0,0 +1,296 @@
|
|
|
1
|
+
# @goodz-core/sdk
|
|
2
|
+
|
|
3
|
+
Official SDK for **GoodZ.Core** — a type-safe API client for building GoodZ-powered applications. This package provides a zero-dependency HTTP client that speaks the tRPC wire protocol directly, along with OAuth helpers, Z-coin utilities, and full TypeScript type coverage.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install @goodz-core/sdk
|
|
9
|
+
# or
|
|
10
|
+
pnpm add @goodz-core/sdk
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
The SDK has only one runtime dependency (`superjson`) and requires Node.js 18+. It works in any JavaScript runtime that supports the Fetch API (Node.js, Deno, Bun, Cloudflare Workers, browsers).
|
|
14
|
+
|
|
15
|
+
## Quick Start
|
|
16
|
+
|
|
17
|
+
```ts
|
|
18
|
+
import { createGoodZClient } from "@goodz-core/sdk";
|
|
19
|
+
|
|
20
|
+
const goodz = createGoodZClient({
|
|
21
|
+
accessToken: "your-jwt-token",
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
// All methods are fully typed — IDE autocomplete works out of the box
|
|
25
|
+
const balance = await goodz.zcoin.getMyBalance();
|
|
26
|
+
console.log(`Balance: ${balance.balance} hundredths`);
|
|
27
|
+
|
|
28
|
+
const result = await goodz.zcoin.commercialTransfer({
|
|
29
|
+
instanceId: 90447,
|
|
30
|
+
buyerUserId: 1,
|
|
31
|
+
sellerUserId: 2,
|
|
32
|
+
priceZcoin: 1050, // 10.50 Z-coin in hundredths
|
|
33
|
+
saleType: "direct",
|
|
34
|
+
referenceId: "order-abc-123",
|
|
35
|
+
appClientId: "od_myapp",
|
|
36
|
+
});
|
|
37
|
+
console.log(`Trade ID: ${result.tradeId}`);
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
## Architecture
|
|
41
|
+
|
|
42
|
+
The SDK is designed around three principles:
|
|
43
|
+
|
|
44
|
+
**Zero tRPC dependency.** Unlike a typical tRPC client that requires `@trpc/client` and `@trpc/server` as peer dependencies (and transitively pulls in the entire server type tree), this SDK speaks the tRPC HTTP wire protocol directly using `fetch` + `superjson`. This means consumers never need to install tRPC packages, and the DTS bundle is fully self-contained.
|
|
45
|
+
|
|
46
|
+
**Hand-crafted types as API contract.** All input/output types are defined inside the SDK itself (in `src/types.ts`), mirroring the Zod schemas on the Core server. This is the same approach used by the Stripe SDK — the types serve as both documentation and compile-time contract. When Core's API evolves, the SDK types are updated and a new version is published.
|
|
47
|
+
|
|
48
|
+
**Namespace-based API surface.** Methods are organized into logical namespaces (`zcoin`, `inventory`, `collectible`, `user`, `auth`, `ip`) that mirror Core's tRPC router structure. Each namespace method is a thin wrapper around the transport layer, providing typed inputs and outputs.
|
|
49
|
+
|
|
50
|
+
## API Reference
|
|
51
|
+
|
|
52
|
+
### Client Configuration
|
|
53
|
+
|
|
54
|
+
```ts
|
|
55
|
+
interface GoodZClientConfig {
|
|
56
|
+
coreUrl?: string; // Default: "https://goodzcore.manus.space"
|
|
57
|
+
accessToken?: string; // Static JWT token
|
|
58
|
+
getAccessToken?: () => string | Promise<string>; // Dynamic token provider
|
|
59
|
+
headers?: Record<string, string>; // Custom headers for every request
|
|
60
|
+
}
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
The `getAccessToken` function takes precedence over `accessToken` when both are provided. Use it for auto-refresh scenarios.
|
|
64
|
+
|
|
65
|
+
### Namespaces
|
|
66
|
+
|
|
67
|
+
#### `goodz.zcoin` — Z-coin Payment & Settlement
|
|
68
|
+
|
|
69
|
+
The Z-coin namespace handles all monetary operations. These are the primary APIs that Commerce and Exchange apps use to process purchases.
|
|
70
|
+
|
|
71
|
+
| Method | Type | Description |
|
|
72
|
+
|--------|------|-------------|
|
|
73
|
+
| `getMyBalance()` | Query | Get authenticated user's Z-coin balance |
|
|
74
|
+
| `getMyHistory(input?)` | Query | Get Z-coin transaction history with pagination |
|
|
75
|
+
| `getDepositPackages(input?)` | Query | List available deposit packages with pricing |
|
|
76
|
+
| `createDepositOrder(input)` | Mutation | Create a Stripe checkout session for Z-coin deposit |
|
|
77
|
+
| `getDepositStatus(input)` | Query | Check deposit checkout session status |
|
|
78
|
+
| `commercialTransfer(input)` | Mutation | Atomic Z-coin payment + ownership transfer |
|
|
79
|
+
| `mintAndCharge(input)` | Mutation | Mint new instance + charge buyer atomically |
|
|
80
|
+
| `chargeUser(input)` | Mutation | Charge user's Z-coin for in-app purchases |
|
|
81
|
+
| `createDirectPurchaseOrder(input)` | Mutation | Create fiat-to-Z-coin direct purchase checkout |
|
|
82
|
+
|
|
83
|
+
**Key method: `commercialTransfer`** is the primary API for all secondary market transactions. It atomically debits the buyer's Z-coin balance, credits the seller (minus platform fee), and transfers card instance ownership — all in a single database transaction. The `referenceId` parameter provides idempotency, so duplicate calls (e.g., from retries) return the same result.
|
|
84
|
+
|
|
85
|
+
**Key method: `mintAndCharge`** is the primary API for primary sales (gacha, direct-from-creator). It mints a new card instance and charges the buyer in one atomic operation. Requires prior mint authorization via `inventory.grantMintAuth`.
|
|
86
|
+
|
|
87
|
+
#### `goodz.inventory` — Card Instance Management
|
|
88
|
+
|
|
89
|
+
| Method | Type | Description |
|
|
90
|
+
|--------|------|-------------|
|
|
91
|
+
| `getUserInventory(input)` | Query | Get a user's owned card instances |
|
|
92
|
+
| `confirmOwnership(input)` | Query | Check if user owns a specific card |
|
|
93
|
+
| `mint(input)` | Mutation | Mint new card instances (requires authorization) |
|
|
94
|
+
| `transfer(input)` | Mutation | Transfer a specific instance to another user |
|
|
95
|
+
| `transferByCard(input)` | Mutation | Transfer instances by cardId (oldest first) |
|
|
96
|
+
| `grantMintAuth(input)` | Mutation | Grant mint authorization to another user/app |
|
|
97
|
+
| `transferHistory(input)` | Query | Get transfer/ownership history |
|
|
98
|
+
|
|
99
|
+
For commercial transactions (purchases, trades), always use `zcoin.commercialTransfer` or `zcoin.mintAndCharge` instead of the raw `transfer`/`mint` methods. The raw methods are intended for administrative operations and gift transfers only.
|
|
100
|
+
|
|
101
|
+
#### `goodz.collectible` — Card & Instance Queries
|
|
102
|
+
|
|
103
|
+
| Method | Type | Description |
|
|
104
|
+
|--------|------|-------------|
|
|
105
|
+
| `getInstanceById(input)` | Query | Get instance by numeric ID |
|
|
106
|
+
| `getPublicInstance(input)` | Query | Get instance by instance code |
|
|
107
|
+
| `getPublicInstancesBatch(input)` | Query | Batch-fetch instances (max 100) |
|
|
108
|
+
| `getCardProfile(input)` | Query | Get card metadata, rarity, series info |
|
|
109
|
+
| `getShellImageUrl(input)` | Query | Get shell (packaging) image URL |
|
|
110
|
+
|
|
111
|
+
#### `goodz.user` — User Profiles
|
|
112
|
+
|
|
113
|
+
| Method | Type | Description |
|
|
114
|
+
|--------|------|-------------|
|
|
115
|
+
| `getPublicProfile(input)` | Query | Get profile by openId |
|
|
116
|
+
| `getPublicProfileById(input)` | Query | Get profile by internal userId |
|
|
117
|
+
|
|
118
|
+
#### `goodz.auth` — Authentication
|
|
119
|
+
|
|
120
|
+
| Method | Type | Description |
|
|
121
|
+
|--------|------|-------------|
|
|
122
|
+
| `me()` | Query | Get authenticated user's profile |
|
|
123
|
+
| `getOAuthAppInfo(input)` | Query | Get OAuth app info by client ID |
|
|
124
|
+
|
|
125
|
+
#### `goodz.ip` — IP Management (Franchise/Series/Card)
|
|
126
|
+
|
|
127
|
+
| Method | Type | Description |
|
|
128
|
+
|--------|------|-------------|
|
|
129
|
+
| `getFranchise(input)` | Query | Get franchise by ID or slug |
|
|
130
|
+
| `getSeries(input)` | Query | Get series by ID or slug |
|
|
131
|
+
| `listSeriesByFranchise(input)` | Query | List all series in a franchise |
|
|
132
|
+
| `getCard(input)` | Query | Get card by ID |
|
|
133
|
+
| `listCardsBySeries(input)` | Query | List all cards in a series |
|
|
134
|
+
|
|
135
|
+
### Raw Escape Hatches
|
|
136
|
+
|
|
137
|
+
For routes not yet covered by the typed namespaces, use the raw methods:
|
|
138
|
+
|
|
139
|
+
```ts
|
|
140
|
+
const data = await goodz.rawQuery("some.newRoute", { id: 123 });
|
|
141
|
+
const result = await goodz.rawMutation("some.newMutation", { name: "test" });
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
## Authentication
|
|
145
|
+
|
|
146
|
+
### Server-to-Server with Static Token
|
|
147
|
+
|
|
148
|
+
The simplest approach for backend services:
|
|
149
|
+
|
|
150
|
+
```ts
|
|
151
|
+
const goodz = createGoodZClient({
|
|
152
|
+
accessToken: process.env.CORE_ACCESS_TOKEN,
|
|
153
|
+
});
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
### Auto-Refresh with TokenManager
|
|
157
|
+
|
|
158
|
+
For long-running services that need automatic token refresh:
|
|
159
|
+
|
|
160
|
+
```ts
|
|
161
|
+
import { createGoodZClient } from "@goodz-core/sdk/core";
|
|
162
|
+
import { TokenManager } from "@goodz-core/sdk/auth";
|
|
163
|
+
|
|
164
|
+
const tokenManager = new TokenManager({
|
|
165
|
+
clientId: "od_myapp",
|
|
166
|
+
initialTokens: {
|
|
167
|
+
accessToken: savedAccessToken,
|
|
168
|
+
refreshToken: savedRefreshToken,
|
|
169
|
+
expiresAt: savedExpiresAt,
|
|
170
|
+
},
|
|
171
|
+
onTokenRefresh: async (tokens) => {
|
|
172
|
+
// Persist refreshed tokens to your database
|
|
173
|
+
await db.update(appTokens).set({
|
|
174
|
+
accessToken: tokens.accessToken,
|
|
175
|
+
refreshToken: tokens.refreshToken,
|
|
176
|
+
expiresAt: tokens.expiresAt,
|
|
177
|
+
});
|
|
178
|
+
},
|
|
179
|
+
});
|
|
180
|
+
|
|
181
|
+
const goodz = createGoodZClient({
|
|
182
|
+
getAccessToken: () => tokenManager.getValidToken(),
|
|
183
|
+
});
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
### OAuth Authorization Code Flow
|
|
187
|
+
|
|
188
|
+
For apps that authenticate users via GoodZ OAuth:
|
|
189
|
+
|
|
190
|
+
```ts
|
|
191
|
+
import { buildAuthorizationUrl, exchangeCode } from "@goodz-core/sdk/auth";
|
|
192
|
+
|
|
193
|
+
// Step 1: Redirect user to authorization URL
|
|
194
|
+
const authUrl = buildAuthorizationUrl({
|
|
195
|
+
clientId: "od_myapp",
|
|
196
|
+
redirectUri: "https://myapp.com/callback",
|
|
197
|
+
scope: "read write",
|
|
198
|
+
state: crypto.randomUUID(),
|
|
199
|
+
});
|
|
200
|
+
|
|
201
|
+
// Step 2: Exchange code for tokens in your callback handler
|
|
202
|
+
const tokens = await exchangeCode({
|
|
203
|
+
clientId: "od_myapp",
|
|
204
|
+
clientSecret: process.env.CLIENT_SECRET,
|
|
205
|
+
code: searchParams.get("code"),
|
|
206
|
+
redirectUri: "https://myapp.com/callback",
|
|
207
|
+
});
|
|
208
|
+
|
|
209
|
+
// Step 3: Create a user-scoped client
|
|
210
|
+
const userGoodz = createGoodZClient({
|
|
211
|
+
accessToken: tokens.accessToken,
|
|
212
|
+
});
|
|
213
|
+
```
|
|
214
|
+
|
|
215
|
+
## Z-coin Precision
|
|
216
|
+
|
|
217
|
+
GoodZ.Core stores Z-coin amounts in **hundredths** (1/100th of a Z-coin). For example, 10.50 Z-coin is stored as `1050`. The SDK provides utility functions to convert between display values and hundredths:
|
|
218
|
+
|
|
219
|
+
```ts
|
|
220
|
+
import { toHundredths, toDisplay, formatZcoin } from "@goodz-core/sdk/zcoin";
|
|
221
|
+
|
|
222
|
+
toHundredths(10.50); // → 1050
|
|
223
|
+
toDisplay(1050); // → 10.5
|
|
224
|
+
formatZcoin(1050); // → "10.50"
|
|
225
|
+
```
|
|
226
|
+
|
|
227
|
+
Always use `toHundredths()` when constructing API inputs to avoid the off-by-100x error:
|
|
228
|
+
|
|
229
|
+
```ts
|
|
230
|
+
// ✅ Correct
|
|
231
|
+
await goodz.zcoin.commercialTransfer({
|
|
232
|
+
priceZcoin: toHundredths(10.50), // 1050
|
|
233
|
+
// ...
|
|
234
|
+
});
|
|
235
|
+
|
|
236
|
+
// ❌ Wrong — this charges 0.10 Z-coin instead of 10.00
|
|
237
|
+
await goodz.zcoin.commercialTransfer({
|
|
238
|
+
priceZcoin: 10,
|
|
239
|
+
// ...
|
|
240
|
+
});
|
|
241
|
+
```
|
|
242
|
+
|
|
243
|
+
## Error Handling
|
|
244
|
+
|
|
245
|
+
All API errors are thrown as `GoodZApiError` instances with structured fields:
|
|
246
|
+
|
|
247
|
+
```ts
|
|
248
|
+
import { GoodZApiError } from "@goodz-core/sdk";
|
|
249
|
+
|
|
250
|
+
try {
|
|
251
|
+
await goodz.zcoin.commercialTransfer({ /* ... */ });
|
|
252
|
+
} catch (err) {
|
|
253
|
+
if (err instanceof GoodZApiError) {
|
|
254
|
+
console.error(err.code); // "BAD_REQUEST", "FORBIDDEN", "CONFLICT", etc.
|
|
255
|
+
console.error(err.httpStatus); // 400, 403, 409, etc.
|
|
256
|
+
console.error(err.path); // "zcoin.commercialTransfer"
|
|
257
|
+
console.error(err.message); // Human-readable error message
|
|
258
|
+
|
|
259
|
+
// Zod validation errors (if input was malformed)
|
|
260
|
+
if (err.zodErrors) {
|
|
261
|
+
for (const fieldErr of err.zodErrors) {
|
|
262
|
+
console.error(`${fieldErr.path.join(".")}: ${fieldErr.message}`);
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
// Full detailed string for logging
|
|
267
|
+
console.error(err.toDetailedString());
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
```
|
|
271
|
+
|
|
272
|
+
Common error codes and recommended handling:
|
|
273
|
+
|
|
274
|
+
| Code | HTTP | Meaning | Recommended Action |
|
|
275
|
+
|------|------|---------|--------------------|
|
|
276
|
+
| `BAD_REQUEST` | 400 | Invalid input or insufficient balance | Check input values, show user-friendly message |
|
|
277
|
+
| `UNAUTHORIZED` | 401 | Missing or invalid token | Redirect to login or refresh token |
|
|
278
|
+
| `FORBIDDEN` | 403 | No permission (e.g., not the owner) | Show permission denied message |
|
|
279
|
+
| `NOT_FOUND` | 404 | Resource doesn't exist | Show 404 page or fallback |
|
|
280
|
+
| `CONFLICT` | 409 | Version conflict (optimistic locking) | Retry the operation |
|
|
281
|
+
|
|
282
|
+
## Subpath Imports
|
|
283
|
+
|
|
284
|
+
For tree-shaking, import from specific subpaths:
|
|
285
|
+
|
|
286
|
+
```ts
|
|
287
|
+
import { createGoodZClient } from "@goodz-core/sdk/core";
|
|
288
|
+
import { TokenManager } from "@goodz-core/sdk/auth";
|
|
289
|
+
import { toHundredths } from "@goodz-core/sdk/zcoin";
|
|
290
|
+
```
|
|
291
|
+
|
|
292
|
+
The root import (`@goodz-core/sdk`) re-exports everything for convenience.
|
|
293
|
+
|
|
294
|
+
## License
|
|
295
|
+
|
|
296
|
+
MIT
|