npm package: 3x-auth-sdk
Description: 3X Authentication SDK with React UI - Works in React and Plain JS apps
Author: WeSee India
Latest version: 2.0.4

# Trix SDK v2.0

A modern, React-based authentication SDK for the 3X platform. Works seamlessly in React apps and plain JavaScript applications.

## 🚀 Features

- **React-based UI** - Clean, modern login modal built with React
- **Framework Agnostic** - Works in React, Vue, Angular, or plain JavaScript
- **Dual Build Support** - ESM for React apps, UMD for plain JS apps
- **Secure Authentication** - Client-side password hashing
- **Session Management** - Automatic session handling
- **Game Operations** - Create sessions, participate, declare winners

## 📦 Installation

```bash
npm install trix-sdk
```

## 🎯 Quick Start

### For React Apps

```javascript
import { AuthClient } from 'trix-sdk';

const authClient = new AuthClient({
  apiUrl: 'https://api.3x.com',
  apiKey: 'your-api-key',
  debug: true // Enable debug logging
});

// Login - Shows modal popup
// Returns: { success: true, message: string, data: { user_id, username, balance } }
const loginResponse = await authClient.login();

if (loginResponse.success) {
  console.log('Logged in as:', loginResponse.data.username);
  console.log('Balance:', loginResponse.data.balance);
  console.log('User ID:', loginResponse.data.user_id);
}

// Check authentication
if (authClient.isAuthenticated()) {
  const currentUser = authClient.getCurrentUser();
  console.log('Current user:', currentUser.username);
}

// Game operations
// Returns: { success: true, message: string, data: { sessionId, game_id, game_name, game_status } }
const sessionResponse = await authClient.createSession('my-game-123');
const sessionId = sessionResponse.data.sessionId;

// Returns: { success: true, message: string, data: { participation_id, session_id, game_id, user_id, stake_amount, tx_hash } }
const participateResponse = await authClient.participate('my-game-123', sessionId, 100);
console.log('Participation ID:', participateResponse.data.participation_id);

// Returns: { success: true, message: string, data: { winner_id, nft_id, publisher_share, trix_share, user_share, total_stake_amount } }
const winnerResponse = await authClient.declareWinner('my-game-123', sessionId, loginResponse.data.user_id);
console.log('Winner ID:', winnerResponse.data.winner_id);

// Logout
await authClient.logout();
```

### For Plain JavaScript Apps

```html
<!DOCTYPE html>
<html>
<head>
  <!-- Include React (required for UMD build) -->
  <script crossorigin src="https://unpkg.com/react@18/umd/react.production.min.js"></script>
  <script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"></script>
  
  <!-- Include Trix SDK -->
  <script src="https://unpkg.com/trix-sdk/dist/index.umd.js"></script>
  
  <!-- Include CSS -->
  <link rel="stylesheet" href="https://unpkg.com/trix-sdk/dist/trix-sdk.css">
</head>
<body>
  <script>
    const authClient = new TrixSDK.AuthClient({
      apiUrl: 'https://api.3x.com',
      apiKey: 'your-api-key'
    });
    
    // Login - Returns { success, message, data }
    authClient.login().then(response => {
      if (response.success) {
        console.log('Logged in:', response.data.username);
        console.log('Balance:', response.data.balance);
      }
    }).catch(error => {
      console.error('Login failed:', error.message);
    });
  </script>
</body>
</html>
```

## 📚 API Reference

### AuthClient

#### Constructor

```javascript
new AuthClient(config)
```

**Config Options:**
- `apiUrl` (string, required) - Base URL for 3X authentication API
- `apiKey` (string, required) - API key for game company authentication
- `debug` (boolean, optional) - Enable debug logging
- `requestTimeout` (number, optional) - Request timeout in milliseconds (default: 30000)

#### Methods

##### `login(options?)`

Initiates the login flow and shows the login modal.

**Returns:** `Promise<{ success: true, message: string, data: { user_id: number, username: string, balance: number } }>`

```javascript
const response = await authClient.login();
if (response.success) {
  console.log('User ID:', response.data.user_id);
  console.log('Username:', response.data.username);
  console.log('Balance:', response.data.balance);
}
```

##### `logout()`

Logs out the current user and clears session data.

```javascript
await authClient.logout();
```

##### `getCurrentUser()`

Returns the currently authenticated user, or `null` if not authenticated.

```javascript
const user = authClient.getCurrentUser();
```

##### `isAuthenticated()`

Checks if the user is currently authenticated.

```javascript
if (authClient.isAuthenticated()) {
  // User is logged in
}
```

##### `createSession(gameId)`

Creates a new game session. Requires user to be authenticated first.

**Returns:** `Promise<{ success: true, message: string, data: { sessionId: string, game_id: number, game_name: string, game_status: string } }>`

```javascript
const response = await authClient.createSession('my-game-123');
if (response.success) {
  console.log('Session ID:', response.data.sessionId);
  console.log('Game:', response.data.game_name);
}
```

##### `participate(gameId, sessionId, amount, userId?)`

Participates in a game session. Automatically validates balance and updates it after successful participation.

**Returns:** `Promise<{ success: true, message: string, data: { participation_id: number, session_id: string, game_id: number, user_id: number, stake_amount: number, tx_hash: string } }>`

```javascript
const response = await authClient.participate('my-game-123', sessionId, 100, user.id);
if (response.success) {
  console.log('Participation ID:', response.data.participation_id);
  console.log('TX Hash:', response.data.tx_hash);
}
```

##### `declareWinner(gameId, sessionId, winnerUserId)`

Declares a winner for a game session.

**Returns:** `Promise<{ success: true, message: string, data: { winner_id: number, nft_id: number, publisher_share: string, trix_share: string, user_share: string, total_stake_amount: string } }>`

```javascript
const response = await authClient.declareWinner('my-game-123', sessionId, winnerUserId);
if (response.success) {
  console.log('Winner ID:', response.data.winner_id);
  console.log('User Share:', response.data.user_share);
  console.log('Publisher Share:', response.data.publisher_share);
}
```

## 📄 License

MIT License - see [LICENSE](LICENSE) file for details.

## 📋 Response Format

All SDK methods return responses in the following format:

```javascript
{
  success: true,
  message: "Success message from backend",
  data: {
    // Endpoint-specific data
  }
}
```

### Error Handling

If a request fails, the SDK will throw an Error. Always use try/catch:

```javascript
try {
  const response = await authClient.login();
  if (response.success) {
    // Handle success
    console.log('User:', response.data.username);
  }
} catch (error) {
  console.error('Error:', error.message);
  // Handle error
}
```

## ⏱️ Timeout Configuration

The SDK has a default timeout of 30 seconds (30000ms) for all API requests. You can configure this:

```javascript
const authClient = new AuthClient({
  apiUrl: 'https://api.3x.com',
  apiKey: 'your-api-key',
  requestTimeout: 60000 // 60 seconds for long-running operations
});
```

**Note:** If an API call takes longer than the configured timeout, the SDK will throw a timeout error.


## 🔗 Links

- **Repository:** [GitHub](https://github.com/WeSee-India/Trix-sdk)
- **Issues:** [GitHub Issues](https://github.com/WeSee-India/Trix-sdk/issues)
- **NPM Package:** [trix-sdk](https://www.npmjs.com/package/3x-auth-sdk?activeTab=readme)