@arcadiasol/game-sdk 1.0.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 ADDED
@@ -0,0 +1,458 @@
1
+ # Arcadia Game SDK
2
+
3
+ SDK for integrating Arcadia wallet and payment features into Web3 games. Enables games to access wallet addresses for account linking and process payments through the Arcadia platform.
4
+
5
+ ## Features
6
+
7
+ - **Wallet Address Linking** - Get wallet address to use as user identifier
8
+ - **Payment Processing** - Pay-to-play and in-game purchases via Solana/USDC
9
+ - **Wallet Status** - Monitor wallet connection status
10
+ - **Iframe Support** - Works seamlessly in iframe environments
11
+ - **Zero Dependencies** - Minimal bundle size
12
+ - **TypeScript Support** - Full type definitions included
13
+
14
+ ## Installation
15
+
16
+ ### NPM
17
+
18
+ ```bash
19
+ npm install @arcadia/game-sdk
20
+ ```
21
+
22
+ ### CDN
23
+
24
+ ```html
25
+ <!-- Development -->
26
+ <script src="https://cdn.arcadia.com/sdk/v1/arcadia-game-sdk.js"></script>
27
+
28
+ <!-- Production (Minified) -->
29
+ <script src="https://cdn.arcadia.com/sdk/v1/arcadia-game-sdk.min.js"></script>
30
+ ```
31
+
32
+ ## Quick Start
33
+
34
+ ### NPM Usage
35
+
36
+ ```typescript
37
+ import { ArcadiaSDK } from '@arcadia/game-sdk';
38
+
39
+ // Initialize SDK
40
+ const arcadia = new ArcadiaSDK({
41
+ gameId: 'your-game-id',
42
+ });
43
+
44
+ await arcadia.init();
45
+
46
+ // Get wallet address (use as user ID)
47
+ const walletAddress = await arcadia.getWalletAddress();
48
+
49
+ if (!walletAddress) {
50
+ console.log('Please connect your wallet in Arcadia');
51
+ return;
52
+ }
53
+
54
+ // Link save data to wallet address
55
+ const saveData = await loadSaveDataByWallet(walletAddress);
56
+
57
+ // Pay to play
58
+ const result = await arcadia.payment.payToPlay(0.5, 'SOL');
59
+ console.log('Payment successful:', result.txSignature);
60
+ ```
61
+
62
+ ### CDN Usage
63
+
64
+ ```html
65
+ <!DOCTYPE html>
66
+ <html>
67
+ <head>
68
+ <script src="https://cdn.arcadia.com/sdk/v1/arcadia-game-sdk.min.js"></script>
69
+ </head>
70
+ <body>
71
+ <script>
72
+ // Initialize SDK
73
+ const arcadia = new ArcadiaGameSDK({
74
+ gameId: 'your-game-id',
75
+ });
76
+
77
+ arcadia.init().then(async () => {
78
+ // Get wallet address
79
+ const walletAddress = await arcadia.getWalletAddress();
80
+
81
+ if (!walletAddress) {
82
+ alert('Please connect your wallet in Arcadia');
83
+ return;
84
+ }
85
+
86
+ // Use wallet address as user ID
87
+ console.log('User wallet:', walletAddress);
88
+ });
89
+ </script>
90
+ </body>
91
+ </html>
92
+ ```
93
+
94
+ ## API Reference
95
+
96
+ ### Initialization
97
+
98
+ #### `new ArcadiaSDK(config: SDKConfig)`
99
+
100
+ Create a new SDK instance.
101
+
102
+ **Parameters:**
103
+ - `config.gameId` (string, required) - Your unique game identifier
104
+ - `config.parentOrigin` (string, optional) - Parent window origin for security (default: '*')
105
+ - `config.timeout` (number, optional) - Request timeout in milliseconds (default: 30000)
106
+
107
+ **Example:**
108
+ ```typescript
109
+ const arcadia = new ArcadiaSDK({
110
+ gameId: 'my-awesome-game',
111
+ parentOrigin: 'https://arcadia.com', // Optional: restrict to specific origin
112
+ timeout: 30000, // Optional: 30 second timeout
113
+ });
114
+ ```
115
+
116
+ #### `init(): Promise<void>`
117
+
118
+ Initialize SDK and request initialization data from parent window. Call this after creating the SDK instance.
119
+
120
+ **Example:**
121
+ ```typescript
122
+ await arcadia.init();
123
+ ```
124
+
125
+ ### Wallet Address
126
+
127
+ #### `getWalletAddress(): Promise<string | null>`
128
+
129
+ Get the connected wallet address. Use this as your user identifier and link all save data to it.
130
+
131
+ **Returns:** Wallet address (string) or null if not connected
132
+
133
+ **Example:**
134
+ ```typescript
135
+ const walletAddress = await arcadia.getWalletAddress();
136
+
137
+ if (!walletAddress) {
138
+ // Wallet not connected
139
+ showMessage('Please connect your wallet');
140
+ return;
141
+ }
142
+
143
+ // Use wallet address as user ID
144
+ const userId = walletAddress;
145
+ const saveData = await loadSaveDataByWallet(walletAddress);
146
+ ```
147
+
148
+ #### `isWalletConnected(): Promise<boolean>`
149
+
150
+ Check if wallet is currently connected.
151
+
152
+ **Returns:** true if connected, false otherwise
153
+
154
+ **Example:**
155
+ ```typescript
156
+ const connected = await arcadia.isWalletConnected();
157
+ if (!connected) {
158
+ showMessage('Please connect your wallet');
159
+ }
160
+ ```
161
+
162
+ #### `onWalletChange(callback: (connected: boolean, address: string | null) => void): void`
163
+
164
+ Listen for wallet connection changes.
165
+
166
+ **Example:**
167
+ ```typescript
168
+ arcadia.onWalletChange((connected, address) => {
169
+ if (!connected) {
170
+ // Wallet disconnected - pause game
171
+ pauseGame();
172
+ showMessage('Wallet disconnected. Please reconnect.');
173
+ } else {
174
+ // Wallet reconnected - resume game
175
+ resumeGame();
176
+ }
177
+ });
178
+ ```
179
+
180
+ #### `offWalletChange(callback: Function): void`
181
+
182
+ Remove a wallet change listener.
183
+
184
+ **Example:**
185
+ ```typescript
186
+ const callback = (connected, address) => { /* ... */ };
187
+ arcadia.onWalletChange(callback);
188
+ // Later...
189
+ arcadia.offWalletChange(callback);
190
+ ```
191
+
192
+ ### Payments
193
+
194
+ #### `payment.payToPlay(amount: number, token: 'SOL' | 'USDC'): Promise<PaymentResult>`
195
+
196
+ Process a pay-to-play payment (one-time payment to access game).
197
+
198
+ **Parameters:**
199
+ - `amount` (number) - Payment amount (must be > 0)
200
+ - `token` ('SOL' | 'USDC') - Token type
201
+
202
+ **Returns:** `PaymentResult` object with complete payment details:
203
+ - `success` (boolean) - Whether payment was successful
204
+ - `txSignature` (string) - Blockchain transaction signature (proof of payment)
205
+ - `amount` (number) - Amount paid by user
206
+ - `token` ('SOL' | 'USDC') - Token type used
207
+ - `timestamp` (string) - ISO timestamp when payment completed
208
+ - `purchaseId` (string, optional) - Arcadia purchase ID for tracking
209
+ - `platformFee` (number, optional) - Platform fee deducted
210
+ - `developerAmount` (number, optional) - Amount received by developer (after fees)
211
+
212
+ **Example:**
213
+ ```typescript
214
+ try {
215
+ const result = await arcadia.payment.payToPlay(0.5, 'SOL');
216
+
217
+ // All payment details are included - no need to query blockchain
218
+ console.log('Payment successful!');
219
+ console.log('Transaction:', result.txSignature);
220
+ console.log('Amount paid:', result.amount, result.token);
221
+ console.log('Completed at:', result.timestamp);
222
+ console.log('Purchase ID:', result.purchaseId);
223
+ console.log('Platform fee:', result.platformFee);
224
+ console.log('Developer receives:', result.developerAmount);
225
+
226
+ // Store in your database for reference
227
+ await savePurchase({
228
+ txSignature: result.txSignature,
229
+ amount: result.amount,
230
+ token: result.token,
231
+ timestamp: result.timestamp,
232
+ purchaseId: result.purchaseId,
233
+ });
234
+
235
+ // Start game
236
+ startGame();
237
+ } catch (error) {
238
+ console.error('Payment failed:', error.message);
239
+ showError('Payment failed. Please try again.');
240
+ }
241
+ ```
242
+
243
+ #### `payment.purchaseItem(itemId: string, amount: number, token: 'SOL' | 'USDC'): Promise<PaymentResult>`
244
+
245
+ Purchase an in-game item.
246
+
247
+ **Parameters:**
248
+ - `itemId` (string) - Unique item identifier
249
+ - `amount` (number) - Payment amount (must be > 0)
250
+ - `token` ('SOL' | 'USDC') - Token type
251
+
252
+ **Returns:** `PaymentResult` object with complete payment details (see `payToPlay` for full field list)
253
+
254
+ **Example:**
255
+ ```typescript
256
+ try {
257
+ const result = await arcadia.payment.purchaseItem('sword-001', 1.0, 'SOL');
258
+
259
+ // All payment details included - verify and process
260
+ if (result.success && result.amount === 1.0 && result.token === 'SOL') {
261
+ // Payment verified - add item to inventory
262
+ addItemToInventory('sword-001');
263
+
264
+ // Log purchase for analytics
265
+ logPurchase({
266
+ itemId: 'sword-001',
267
+ txSignature: result.txSignature,
268
+ amount: result.amount,
269
+ timestamp: result.timestamp,
270
+ purchaseId: result.purchaseId,
271
+ });
272
+ }
273
+ } catch (error) {
274
+ console.error('Purchase failed:', error.message);
275
+ showError('Purchase failed. Please try again.');
276
+ }
277
+ ```
278
+
279
+ ### Utility Methods
280
+
281
+ #### `isInIframe(): boolean`
282
+
283
+ Check if SDK is running in an iframe environment.
284
+
285
+ **Returns:** true if in iframe, false otherwise
286
+
287
+ #### `isInitialized(): boolean`
288
+
289
+ Check if SDK has been initialized.
290
+
291
+ **Returns:** true if initialized, false otherwise
292
+
293
+ #### `getConfig(): SDKConfig`
294
+
295
+ Get current SDK configuration.
296
+
297
+ **Returns:** SDK configuration object
298
+
299
+ #### `destroy(): void`
300
+
301
+ Cleanup SDK resources. Call this when game is unloaded.
302
+
303
+ ## Error Handling
304
+
305
+ The SDK throws specific error types for different scenarios:
306
+
307
+ ```typescript
308
+ import {
309
+ ArcadiaSDKError,
310
+ WalletNotConnectedError,
311
+ PaymentFailedError,
312
+ TimeoutError,
313
+ InvalidConfigError,
314
+ NotInIframeError,
315
+ InvalidAmountError,
316
+ InvalidTokenError,
317
+ } from '@arcadia/game-sdk';
318
+
319
+ try {
320
+ await arcadia.payment.payToPlay(0.5, 'SOL');
321
+ } catch (error) {
322
+ if (error instanceof WalletNotConnectedError) {
323
+ showMessage('Please connect your wallet');
324
+ } else if (error instanceof PaymentFailedError) {
325
+ showError('Payment failed: ' + error.message);
326
+ } else if (error instanceof TimeoutError) {
327
+ showError('Request timed out. Please try again.');
328
+ } else {
329
+ showError('An error occurred: ' + error.message);
330
+ }
331
+ }
332
+ ```
333
+
334
+ ## Account Linking
335
+
336
+ **Important:** Use wallet address as your user identifier.
337
+
338
+ ```typescript
339
+ // Get wallet address
340
+ const walletAddress = await arcadia.getWalletAddress();
341
+
342
+ // Link all save data to wallet address
343
+ await gameDatabase.save({
344
+ walletAddress: walletAddress,
345
+ level: 5,
346
+ score: 1000,
347
+ inventory: ['item1', 'item2'],
348
+ });
349
+
350
+ // Load save data by wallet address
351
+ const saveData = await gameDatabase.loadByWallet(walletAddress);
352
+ ```
353
+
354
+ ## Complete Example
355
+
356
+ ```typescript
357
+ import { ArcadiaSDK, WalletNotConnectedError, PaymentFailedError } from '@arcadia/game-sdk';
358
+
359
+ // Initialize SDK
360
+ const arcadia = new ArcadiaSDK({
361
+ gameId: 'my-game-id',
362
+ });
363
+
364
+ await arcadia.init();
365
+
366
+ // Get wallet address
367
+ const walletAddress = await arcadia.getWalletAddress();
368
+
369
+ if (!walletAddress) {
370
+ showMessage('Please connect your wallet in Arcadia to play');
371
+ return;
372
+ }
373
+
374
+ // Load save data
375
+ let saveData = await loadSaveDataByWallet(walletAddress);
376
+ if (!saveData) {
377
+ // First time player
378
+ saveData = createNewSave(walletAddress);
379
+ }
380
+
381
+ // Handle pay-to-play if required
382
+ if (gameRequiresPayment && !saveData.hasPaid) {
383
+ try {
384
+ const result = await arcadia.payment.payToPlay(0.5, 'SOL');
385
+ saveData.hasPaid = true;
386
+ await saveGameData(walletAddress, saveData);
387
+ startGame();
388
+ } catch (error) {
389
+ if (error instanceof WalletNotConnectedError) {
390
+ showMessage('Please connect your wallet');
391
+ } else if (error instanceof PaymentFailedError) {
392
+ showError('Payment failed: ' + error.message);
393
+ }
394
+ return;
395
+ }
396
+ } else {
397
+ startGame();
398
+ }
399
+
400
+ // Listen for wallet changes
401
+ arcadia.onWalletChange((connected, address) => {
402
+ if (!connected) {
403
+ pauseGame();
404
+ showMessage('Wallet disconnected. Please reconnect.');
405
+ }
406
+ });
407
+
408
+ // Handle in-game purchases
409
+ async function buyItem(itemId: string, price: number) {
410
+ try {
411
+ const result = await arcadia.payment.purchaseItem(itemId, price, 'SOL');
412
+ saveData.inventory.push(itemId);
413
+ await saveGameData(walletAddress, saveData);
414
+ showSuccess('Item purchased!');
415
+ } catch (error) {
416
+ showError('Purchase failed: ' + error.message);
417
+ }
418
+ }
419
+ ```
420
+
421
+ ## Browser Compatibility
422
+
423
+ - Modern browsers (Chrome, Firefox, Safari, Edge)
424
+ - ES2020 support required
425
+ - postMessage API support
426
+ - No polyfills needed
427
+
428
+ ## TypeScript
429
+
430
+ Full TypeScript support is included. Types are automatically available when using the SDK.
431
+
432
+ ```typescript
433
+ import { ArcadiaSDK, SDKConfig, PaymentResult } from '@arcadia/game-sdk';
434
+
435
+ const config: SDKConfig = {
436
+ gameId: 'my-game',
437
+ };
438
+
439
+ const arcadia = new ArcadiaSDK(config);
440
+ const result: PaymentResult = await arcadia.payment.payToPlay(0.5, 'SOL');
441
+ ```
442
+
443
+ ## Security
444
+
445
+ - Wallet address only (never private keys)
446
+ - All transactions signed in parent window
447
+ - Origin validation for postMessage (configurable)
448
+ - Request timeout prevents hanging
449
+ - No sensitive data in messages
450
+
451
+ ## Support
452
+
453
+ For issues, questions, or contributions, please visit our [GitHub repository](https://github.com/arcadia/game-sdk) or contact support@arcadia.com.
454
+
455
+ ## License
456
+
457
+ MIT
458
+
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Base error class for all SDK errors
3
+ */
4
+ export declare class ArcadiaSDKError extends Error {
5
+ code?: string | undefined;
6
+ constructor(message: string, code?: string | undefined);
7
+ }
8
+ /**
9
+ * Error thrown when wallet is not connected
10
+ */
11
+ export declare class WalletNotConnectedError extends ArcadiaSDKError {
12
+ constructor(message?: string);
13
+ }
14
+ /**
15
+ * Error thrown when payment fails
16
+ */
17
+ export declare class PaymentFailedError extends ArcadiaSDKError {
18
+ txSignature?: string | undefined;
19
+ constructor(message?: string, txSignature?: string | undefined);
20
+ }
21
+ /**
22
+ * Error thrown when request times out
23
+ */
24
+ export declare class TimeoutError extends ArcadiaSDKError {
25
+ constructor(message?: string);
26
+ }
27
+ /**
28
+ * Error thrown when SDK configuration is invalid
29
+ */
30
+ export declare class InvalidConfigError extends ArcadiaSDKError {
31
+ constructor(message?: string);
32
+ }
33
+ /**
34
+ * Error thrown when SDK is not running in iframe
35
+ */
36
+ export declare class NotInIframeError extends ArcadiaSDKError {
37
+ constructor(message?: string);
38
+ }
39
+ /**
40
+ * Error thrown when invalid amount is provided
41
+ */
42
+ export declare class InvalidAmountError extends ArcadiaSDKError {
43
+ constructor(message?: string);
44
+ }
45
+ /**
46
+ * Error thrown when invalid token is provided
47
+ */
48
+ export declare class InvalidTokenError extends ArcadiaSDKError {
49
+ constructor(message?: string);
50
+ }
51
+ //# sourceMappingURL=errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../../src/errors.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,qBAAa,eAAgB,SAAQ,KAAK;IACJ,IAAI,CAAC,EAAE,MAAM;gBAArC,OAAO,EAAE,MAAM,EAAS,IAAI,CAAC,EAAE,MAAM,YAAA;CAKlD;AAED;;GAEG;AACH,qBAAa,uBAAwB,SAAQ,eAAe;gBAC9C,OAAO,GAAE,MAA0E;CAKhG;AAED;;GAEG;AACH,qBAAa,kBAAmB,SAAQ,eAAe;IACE,WAAW,CAAC,EAAE,MAAM;gBAA/D,OAAO,GAAE,MAAyB,EAAS,WAAW,CAAC,EAAE,MAAM,YAAA;CAK5E;AAED;;GAEG;AACH,qBAAa,YAAa,SAAQ,eAAe;gBACnC,OAAO,GAAE,MAA+C;CAKrE;AAED;;GAEG;AACH,qBAAa,kBAAmB,SAAQ,eAAe;gBACzC,OAAO,GAAE,MAAoC;CAK1D;AAED;;GAEG;AACH,qBAAa,gBAAiB,SAAQ,eAAe;gBACvC,OAAO,GAAE,MAAiF;CAKvG;AAED;;GAEG;AACH,qBAAa,kBAAmB,SAAQ,eAAe;gBACzC,OAAO,GAAE,MAAiE;CAKvF;AAED;;GAEG;AACH,qBAAa,iBAAkB,SAAQ,eAAe;gBACxC,OAAO,GAAE,MAAkD;CAKxE"}
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Arcadia Game SDK
3
+ *
4
+ * SDK for integrating Arcadia wallet and payment features into Web3 games.
5
+ * Works in iframe environments by communicating with parent window via postMessage.
6
+ */
7
+ export { ArcadiaSDK } from './sdk';
8
+ export type { SDKConfig, PaymentResult, WalletInfo, MessageType, PaymentRequest, PaymentResponse, InitData, WalletAddressResponse, } from './types';
9
+ export { ArcadiaSDKError, WalletNotConnectedError, PaymentFailedError, TimeoutError, InvalidConfigError, NotInIframeError, InvalidAmountError, InvalidTokenError, } from './errors';
10
+ import { ArcadiaSDK } from './sdk';
11
+ export default ArcadiaSDK;
12
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAGH,OAAO,EAAE,UAAU,EAAE,MAAM,OAAO,CAAC;AAGnC,YAAY,EACV,SAAS,EACT,aAAa,EACb,UAAU,EACV,WAAW,EACX,cAAc,EACd,eAAe,EACf,QAAQ,EACR,qBAAqB,GACtB,MAAM,SAAS,CAAC;AAGjB,OAAO,EACL,eAAe,EACf,uBAAuB,EACvB,kBAAkB,EAClB,YAAY,EACZ,kBAAkB,EAClB,gBAAgB,EAChB,kBAAkB,EAClB,iBAAiB,GAClB,MAAM,UAAU,CAAC;AAGlB,OAAO,EAAE,UAAU,EAAE,MAAM,OAAO,CAAC;AACnC,eAAe,UAAU,CAAC"}