npm package: @games-fun/server-sdk
Description: Server-side SDK for Games.fun platform
Author: Games.fun
Latest version: 0.1.0

# Games.fun Server SDK

A lightweight, flexible SDK for interacting with the Games.fun platform from your game server.

## Installation

```bash
npm install @games-fun/server-sdk
```

## Features

- **Wallet API Client**: Interact with the Games.fun Wallet API to manage your game's wallet and send tokens to players
- **JWT Utilities**: Generate and verify JWT tokens for player authentication
- **Flexible Design**: Use only the parts you need, no framework lock-in

## Usage

### Wallet API

```typescript
import { WalletClient } from '@games-fun/server-sdk';

// Initialize the wallet client
const walletClient = new WalletClient({
  apiKey: 'your-api-key'
});

// Get the game's wallet
async function getGameWallet() {
  try {
    const wallet = await walletClient.getWallet();
    console.log(`Game wallet address: ${wallet.address}`);
    return wallet;
  } catch (error) {
    console.error('Failed to get wallet:', error);
  }
}

// Send SOL to a player
async function rewardPlayerWithSol(playerAddress, amount) {
  try {
    const result = await walletClient.sendSol({
      recipient: playerAddress,
      amount: amount.toString() // amount in lamports (1 SOL = 1,000,000,000 lamports)
    });
    console.log(`Transaction signature: ${result.signature}`);
    return result;
  } catch (error) {
    console.error('Failed to send SOL:', error);
  }
}

// Send tokens to a player
async function rewardPlayerWithTokens(playerAddress, amount, tokenMint) {
  try {
    const result = await walletClient.sendToken({
      recipient: playerAddress,
      amount: amount.toString(),
      tokenMint
    });
    console.log(`Transaction signature: ${result.signature}`);
    return result;
  } catch (error) {
    console.error('Failed to send tokens:', error);
  }
}
```

### JWT Authentication

```typescript
import { JWTUtils } from '@games-fun/server-sdk';

// Generate a JWT token for player authentication
function generatePlayerToken(playerId, permissions = ['play']) {
  const secretKey = process.env.JWT_SECRET_KEY;
  
  const token = JWTUtils.generateToken(
    {
      sub: playerId,
      permissions
    },
    secretKey,
    {
      expiresIn: '24h' // Token expires in 24 hours
    }
  );
  
  return token;
}

// Verify a JWT token
function verifyPlayerToken(token) {
  const secretKey = process.env.JWT_SECRET_KEY;
  
  const result = JWTUtils.verifyToken(token, secretKey);
  
  if (result.valid) {
    console.log('Token is valid:', result.payload);
    return result.payload;
  } else {
    console.error('Token verification failed:', result.error);
    return null;
  }
}
```

## Express.js Integration Example

```typescript
import express from 'express';
import { WalletClient, JWTUtils } from '@games-fun/server-sdk';

const app = express();
app.use(express.json());

const walletClient = new WalletClient({
  apiKey: process.env.GAMES_FUN_API_KEY
});

const JWT_SECRET = process.env.JWT_SECRET;

// Middleware to verify JWT tokens
function authenticateToken(req, res, next) {
  const authHeader = req.headers['authorization'];
  const token = authHeader && authHeader.split(' ')[1];
  
  if (!token) {
    return res.status(401).json({ error: 'Authentication required' });
  }
  
  const result = JWTUtils.verifyToken(token, JWT_SECRET);
  
  if (!result.valid) {
    return res.status(403).json({ error: 'Invalid token' });
  }
  
  req.user = result.payload;
  next();
}

// Issue a token
app.post('/auth/token', async (req, res) => {
  const { playerId } = req.body;
  
  if (!playerId) {
    return res.status(400).json({ error: 'Player ID is required' });
  }
  
  const token = JWTUtils.generateToken({ sub: playerId }, JWT_SECRET);
  
  res.json({ token });
});

// Reward a player (protected route)
app.post('/rewards/token', authenticateToken, async (req, res) => {
  const { recipient, amount, tokenMint } = req.body;
  
  try {
    const result = await walletClient.sendToken({
      recipient,
      amount: amount.toString(),
      tokenMint
    });
    
    res.json({ success: true, signature: result.signature });
  } catch (error) {
    res.status(500).json({ 
      error: error instanceof Error ? error.message : 'Failed to send tokens' 
    });
  }
});

app.listen(3000, () => {
  console.log('Server running on port 3000');
});
```

## API Reference

### WalletClient

- `new WalletClient(options)`: Create a new wallet client
- `getWallet()`: Get the game's wallet
- `createWallet()`: Create a new wallet for the game
- `sendSol(params)`: Send SOL to a recipient
- `sendToken(params)`: Send tokens to a recipient

### JWTUtils

- `generateToken(payload, secretOrPrivateKey, options)`: Generate a JWT token
- `verifyToken(token, secretOrPublicKey, options)`: Verify a JWT token
- `decodeToken(token)`: Decode a JWT token without verification

## License

MIT