@arcadiasol/game-sdk
v1.0.0
Published
Arcadia Game SDK for wallet integration and payment processing in Web3 games
Maintainers
Readme
Arcadia Game SDK
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.
Features
- Wallet Address Linking - Get wallet address to use as user identifier
- Payment Processing - Pay-to-play and in-game purchases via Solana/USDC
- Wallet Status - Monitor wallet connection status
- Iframe Support - Works seamlessly in iframe environments
- Zero Dependencies - Minimal bundle size
- TypeScript Support - Full type definitions included
Installation
NPM
npm install @arcadia/game-sdkCDN
<!-- Development -->
<script src="https://cdn.arcadia.com/sdk/v1/arcadia-game-sdk.js"></script>
<!-- Production (Minified) -->
<script src="https://cdn.arcadia.com/sdk/v1/arcadia-game-sdk.min.js"></script>Quick Start
NPM Usage
import { ArcadiaSDK } from '@arcadia/game-sdk';
// Initialize SDK
const arcadia = new ArcadiaSDK({
gameId: 'your-game-id',
});
await arcadia.init();
// Get wallet address (use as user ID)
const walletAddress = await arcadia.getWalletAddress();
if (!walletAddress) {
console.log('Please connect your wallet in Arcadia');
return;
}
// Link save data to wallet address
const saveData = await loadSaveDataByWallet(walletAddress);
// Pay to play
const result = await arcadia.payment.payToPlay(0.5, 'SOL');
console.log('Payment successful:', result.txSignature);CDN Usage
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.arcadia.com/sdk/v1/arcadia-game-sdk.min.js"></script>
</head>
<body>
<script>
// Initialize SDK
const arcadia = new ArcadiaGameSDK({
gameId: 'your-game-id',
});
arcadia.init().then(async () => {
// Get wallet address
const walletAddress = await arcadia.getWalletAddress();
if (!walletAddress) {
alert('Please connect your wallet in Arcadia');
return;
}
// Use wallet address as user ID
console.log('User wallet:', walletAddress);
});
</script>
</body>
</html>API Reference
Initialization
new ArcadiaSDK(config: SDKConfig)
Create a new SDK instance.
Parameters:
config.gameId(string, required) - Your unique game identifierconfig.parentOrigin(string, optional) - Parent window origin for security (default: '*')config.timeout(number, optional) - Request timeout in milliseconds (default: 30000)
Example:
const arcadia = new ArcadiaSDK({
gameId: 'my-awesome-game',
parentOrigin: 'https://arcadia.com', // Optional: restrict to specific origin
timeout: 30000, // Optional: 30 second timeout
});init(): Promise<void>
Initialize SDK and request initialization data from parent window. Call this after creating the SDK instance.
Example:
await arcadia.init();Wallet Address
getWalletAddress(): Promise<string | null>
Get the connected wallet address. Use this as your user identifier and link all save data to it.
Returns: Wallet address (string) or null if not connected
Example:
const walletAddress = await arcadia.getWalletAddress();
if (!walletAddress) {
// Wallet not connected
showMessage('Please connect your wallet');
return;
}
// Use wallet address as user ID
const userId = walletAddress;
const saveData = await loadSaveDataByWallet(walletAddress);isWalletConnected(): Promise<boolean>
Check if wallet is currently connected.
Returns: true if connected, false otherwise
Example:
const connected = await arcadia.isWalletConnected();
if (!connected) {
showMessage('Please connect your wallet');
}onWalletChange(callback: (connected: boolean, address: string | null) => void): void
Listen for wallet connection changes.
Example:
arcadia.onWalletChange((connected, address) => {
if (!connected) {
// Wallet disconnected - pause game
pauseGame();
showMessage('Wallet disconnected. Please reconnect.');
} else {
// Wallet reconnected - resume game
resumeGame();
}
});offWalletChange(callback: Function): void
Remove a wallet change listener.
Example:
const callback = (connected, address) => { /* ... */ };
arcadia.onWalletChange(callback);
// Later...
arcadia.offWalletChange(callback);Payments
payment.payToPlay(amount: number, token: 'SOL' | 'USDC'): Promise<PaymentResult>
Process a pay-to-play payment (one-time payment to access game).
Parameters:
amount(number) - Payment amount (must be > 0)token('SOL' | 'USDC') - Token type
Returns: PaymentResult object with complete payment details:
success(boolean) - Whether payment was successfultxSignature(string) - Blockchain transaction signature (proof of payment)amount(number) - Amount paid by usertoken('SOL' | 'USDC') - Token type usedtimestamp(string) - ISO timestamp when payment completedpurchaseId(string, optional) - Arcadia purchase ID for trackingplatformFee(number, optional) - Platform fee deducteddeveloperAmount(number, optional) - Amount received by developer (after fees)
Example:
try {
const result = await arcadia.payment.payToPlay(0.5, 'SOL');
// All payment details are included - no need to query blockchain
console.log('Payment successful!');
console.log('Transaction:', result.txSignature);
console.log('Amount paid:', result.amount, result.token);
console.log('Completed at:', result.timestamp);
console.log('Purchase ID:', result.purchaseId);
console.log('Platform fee:', result.platformFee);
console.log('Developer receives:', result.developerAmount);
// Store in your database for reference
await savePurchase({
txSignature: result.txSignature,
amount: result.amount,
token: result.token,
timestamp: result.timestamp,
purchaseId: result.purchaseId,
});
// Start game
startGame();
} catch (error) {
console.error('Payment failed:', error.message);
showError('Payment failed. Please try again.');
}payment.purchaseItem(itemId: string, amount: number, token: 'SOL' | 'USDC'): Promise<PaymentResult>
Purchase an in-game item.
Parameters:
itemId(string) - Unique item identifieramount(number) - Payment amount (must be > 0)token('SOL' | 'USDC') - Token type
Returns: PaymentResult object with complete payment details (see payToPlay for full field list)
Example:
try {
const result = await arcadia.payment.purchaseItem('sword-001', 1.0, 'SOL');
// All payment details included - verify and process
if (result.success && result.amount === 1.0 && result.token === 'SOL') {
// Payment verified - add item to inventory
addItemToInventory('sword-001');
// Log purchase for analytics
logPurchase({
itemId: 'sword-001',
txSignature: result.txSignature,
amount: result.amount,
timestamp: result.timestamp,
purchaseId: result.purchaseId,
});
}
} catch (error) {
console.error('Purchase failed:', error.message);
showError('Purchase failed. Please try again.');
}Utility Methods
isInIframe(): boolean
Check if SDK is running in an iframe environment.
Returns: true if in iframe, false otherwise
isInitialized(): boolean
Check if SDK has been initialized.
Returns: true if initialized, false otherwise
getConfig(): SDKConfig
Get current SDK configuration.
Returns: SDK configuration object
destroy(): void
Cleanup SDK resources. Call this when game is unloaded.
Error Handling
The SDK throws specific error types for different scenarios:
import {
ArcadiaSDKError,
WalletNotConnectedError,
PaymentFailedError,
TimeoutError,
InvalidConfigError,
NotInIframeError,
InvalidAmountError,
InvalidTokenError,
} from '@arcadia/game-sdk';
try {
await arcadia.payment.payToPlay(0.5, 'SOL');
} catch (error) {
if (error instanceof WalletNotConnectedError) {
showMessage('Please connect your wallet');
} else if (error instanceof PaymentFailedError) {
showError('Payment failed: ' + error.message);
} else if (error instanceof TimeoutError) {
showError('Request timed out. Please try again.');
} else {
showError('An error occurred: ' + error.message);
}
}Account Linking
Important: Use wallet address as your user identifier.
// Get wallet address
const walletAddress = await arcadia.getWalletAddress();
// Link all save data to wallet address
await gameDatabase.save({
walletAddress: walletAddress,
level: 5,
score: 1000,
inventory: ['item1', 'item2'],
});
// Load save data by wallet address
const saveData = await gameDatabase.loadByWallet(walletAddress);Complete Example
import { ArcadiaSDK, WalletNotConnectedError, PaymentFailedError } from '@arcadia/game-sdk';
// Initialize SDK
const arcadia = new ArcadiaSDK({
gameId: 'my-game-id',
});
await arcadia.init();
// Get wallet address
const walletAddress = await arcadia.getWalletAddress();
if (!walletAddress) {
showMessage('Please connect your wallet in Arcadia to play');
return;
}
// Load save data
let saveData = await loadSaveDataByWallet(walletAddress);
if (!saveData) {
// First time player
saveData = createNewSave(walletAddress);
}
// Handle pay-to-play if required
if (gameRequiresPayment && !saveData.hasPaid) {
try {
const result = await arcadia.payment.payToPlay(0.5, 'SOL');
saveData.hasPaid = true;
await saveGameData(walletAddress, saveData);
startGame();
} catch (error) {
if (error instanceof WalletNotConnectedError) {
showMessage('Please connect your wallet');
} else if (error instanceof PaymentFailedError) {
showError('Payment failed: ' + error.message);
}
return;
}
} else {
startGame();
}
// Listen for wallet changes
arcadia.onWalletChange((connected, address) => {
if (!connected) {
pauseGame();
showMessage('Wallet disconnected. Please reconnect.');
}
});
// Handle in-game purchases
async function buyItem(itemId: string, price: number) {
try {
const result = await arcadia.payment.purchaseItem(itemId, price, 'SOL');
saveData.inventory.push(itemId);
await saveGameData(walletAddress, saveData);
showSuccess('Item purchased!');
} catch (error) {
showError('Purchase failed: ' + error.message);
}
}Browser Compatibility
- Modern browsers (Chrome, Firefox, Safari, Edge)
- ES2020 support required
- postMessage API support
- No polyfills needed
TypeScript
Full TypeScript support is included. Types are automatically available when using the SDK.
import { ArcadiaSDK, SDKConfig, PaymentResult } from '@arcadia/game-sdk';
const config: SDKConfig = {
gameId: 'my-game',
};
const arcadia = new ArcadiaSDK(config);
const result: PaymentResult = await arcadia.payment.payToPlay(0.5, 'SOL');Security
- Wallet address only (never private keys)
- All transactions signed in parent window
- Origin validation for postMessage (configurable)
- Request timeout prevents hanging
- No sensitive data in messages
Support
For issues, questions, or contributions, please visit our GitHub repository or contact [email protected].
License
MIT
