npm package: @gluonmoney/api-types
Description: TypeScript type definitions and API client for Gluon DApp Service
Author: Gluon DApp Team
Latest version: 0.1.6

# @gluon/api-types

TypeScript type definitions and API client for Gluon DApp Service.

## Installation

```bash
npm install @gluon/api-types
# or
yarn add @gluon/api-types
# or
pnpm add @gluon/api-types
```

## Usage

### Basic API Client Usage

```typescript
import { gluonAPI, createGluonAPI } from '@gluon/api-types';

// Option 1: Use the singleton instance
const api = gluonAPI;

// Option 2: Create a new instance with custom configuration
const customAPI = createGluonAPI('https://your-api-domain.com');

// Option 3: Create with authentication token
const authenticatedAPI = createGluonAPI('https://your-api-domain.com', {
  token: 'your-jwt-token-here',
});
```

### Type-Safe API Calls

```typescript
import {
  TelegramAuthDto,
  AuthResponseDto,
  ProfileResponseDto,
  CreateContactDto,
  ApiResponse,
} from '@gluon/api-types';

async function authenticate() {
  // Telegram authentication with type safety
  const telegramAuthData: TelegramAuthDto = {
    identifier: 'telegram_user_id',
    invitationCode: 'optional_invitation_code',
  };

  const authResponse: ApiResponse<AuthResponseDto> =
    await api.telegramAuthController_telegramAuth(telegramAuthData);

  // Set the received token for subsequent requests
  api.setAuthToken(authResponse.data.accessToken);

  return authResponse.data;
}

async function getUserProfile(): Promise<ProfileResponseDto> {
  const response = await api.profileController_getProfile();
  return response.data;
}

async function createContact(contactData: CreateContactDto) {
  const response = await api.contactController_createContact(contactData);
  return response.data;
}
```

### Available Authentication Methods

#### 1. TON Wallet Authentication

```typescript
// Get challenge for TON wallet
const challengeResponse = await api.tonWalletController_getChallenge();

// Authenticate with TON wallet proof
const tonAuthData: TonWalletAuthDto = {
  address: 'EQ...',
  network: '-239',
  message: challengeResponse.data.message,
  walletStateInit: 'te6cckECFgEAAwQAAgE0ARUBFP8A9...', // Wallet state init for verification
  proof: {
    timestamp: Date.now(),
    domain: { lengthBytes: 32, value: 'your-domain.com' },
    signature: 'base64-signature',
    payload: challengeResponse.data.message,
  },
};

const authResponse = await api.tonWalletController_authenticate(tonAuthData);
```

#### 2. Email OTP Authentication

```typescript
// Initiate email OTP
const emailOtpData: InitiateEmailOtpDto = {
  email: 'user@example.com',
  invitationCode: 'optional_code',
};

const otpResponse = await api.emailOtpController_initiateEmailOtp(emailOtpData);

// Verify email OTP
const verifyData: VerifyEmailOtpDto = {
  email: 'user@example.com',
  otpCode: '123456',
  bundle: 'encrypted-bundle',
  userId: otpResponse.data.userId,
  otpId: otpResponse.data.otpId,
};

const authResponse = await api.emailOtpController_verifyEmailOtp(verifyData);
```

#### 3. Telegram Authentication

```typescript
const telegramAuth: TelegramAuthDto = {
  identifier: 'telegram_user_id',
  invitationCode: 'optional_invitation_code',
};

const authResponse =
  await api.telegramAuthController_telegramAuth(telegramAuth);
```

### User Profile Management

```typescript
// Get user profile
const profile = await api.profileController_getProfile();

// Update user profile
const updateData: UpdateProfileDto = {
  username: 'New Display Name',
  avatarUrl: 'https://example.com/avatar.jpg',
};

const updatedProfile = await api.profileController_updateProfile(updateData);

// Update email with two-step verification
const emailUpdateData: UpdateEmailTwoStepDto = {
  newEmail: 'newemail@example.com',
};

const emailUpdateResponse =
  await api.profileController_updateEmail(emailUpdateData);
```

### Contact Management

```typescript
// Create a new contact
const newContact: CreateContactDto = {
  contactUserId: 'user-id-to-add',
  username: 'John Doe',
  sourceType: 'MANUAL',
  tags: ['friend', 'colleague'],
  notes: 'Met at conference',
};

const contact = await api.contactController_createContact(newContact);

// Get all contacts
const contacts = await api.contactController_getContacts();

// Get favorite contacts only
const favoriteContacts = await api.contactController_getFavoriteContacts();

// Update a contact
const updateContactData: UpdateContactDto = {
  username: 'Updated Name',
  tags: ['friend', 'business'],
  notes: 'Updated notes',
};

const updatedContact = await api.contactController_updateContact(
  { id: 'contact-id' },
  updateContactData,
);

// Toggle favorite status
await api.contactController_toggleFavorite({ id: 'contact-id' });

// Toggle block status
await api.contactController_toggleBlock({ id: 'contact-id' });
```

### Invitation System

```typescript
// Create invitation code
const invitation = await api.invitationController_createInvitation({
  type: 'REFERRAL',
});

// Get user's invitations
const userInvitations = await api.invitationController_getUserInvitations();

// Use invitation code
await api.invitationController_useInvitation({
  code: 'invitation-code',
  metadata: { source: 'web-app' },
});

// Get user's referral code
const referralCode = await api.invitationController_getUserReferralCode();

// Get referral statistics
const stats = await api.invitationController_getUserReferralStats();
```

### Token Management

```typescript
// Refresh access token
const refreshResponse = await api.commonAuthController_refreshToken({
  refreshToken: 'your-refresh-token',
});

// Update API client with new token
api.setAuthToken(refreshResponse.data.accessToken);

// Validate current token
const validation = await api.commonAuthController_validateToken();

// Logout (invalidate refresh token)
await api.commonAuthController_logout({
  refreshToken: 'your-refresh-token',
});

// Clear token from client
api.clearAuthToken();
```

### Error Handling

```typescript
import { ApiErrorResponse } from '@gluon/api-types';

async function apiCallWithErrorHandling() {
  try {
    const response = await api.profileController_getProfile();
    return response.data;
  } catch (error) {
    if (error instanceof Error) {
      if (error.message.includes('401')) {
        console.error('Authentication required - please login first');
        // Handle authentication error
      } else if (error.message.includes('403')) {
        console.error('Access forbidden - insufficient permissions');
        // Handle authorization error
      } else if (error.message.includes('404')) {
        console.error('Resource not found');
        // Handle not found error
      } else {
        console.error('API call failed:', error.message);
        // Handle generic error
      }
    }
    throw error;
  }
}
```

### Advanced Usage: Custom Service Class

```typescript
import {
  GluonAPIClient,
  createGluonAPI,
  AuthResponseDto,
  ProfileResponseDto,
  TelegramAuthDto,
} from '@gluon/api-types';

class GluonService {
  private client: GluonAPIClient;

  constructor(baseURL?: string, token?: string) {
    this.client = createGluonAPI(baseURL, { token });
  }

  async authenticate(telegramData: TelegramAuthDto): Promise<AuthResponseDto> {
    const response =
      await this.client.telegramAuthController_telegramAuth(telegramData);
    this.client.setAuthToken(response.data.accessToken);
    return response.data;
  }

  async getUserProfile(): Promise<ProfileResponseDto> {
    const response = await this.client.profileController_getProfile();
    return response.data;
  }

  async refreshToken(refreshToken: string): Promise<string> {
    const response = await this.client.commonAuthController_refreshToken({
      refreshToken,
    });
    const newToken = response.data.accessToken;
    this.client.setAuthToken(newToken);
    return newToken;
  }
}

// Usage
const gluonService = new GluonService('https://api.gluon.com');
```

## API Reference

### Available Interfaces

- `AuthResponseDto` - Authentication response
- `ProfileResponseDto` - User profile data
- `TelegramAuthDto` - Telegram authentication data
- `TonWalletAuthDto` - TON wallet authentication data
- `CreateContactDto` - Contact creation data
- `ContactResponseDto` - Contact information
- `InvitationResponseDto` - Invitation details
- `ApiResponse<T>` - Generic API response wrapper
- `ApiErrorResponse` - Error response structure

### Available API Methods

The API client includes methods for all endpoints:

- **Authentication**: `telegramAuthController_*`, `tonWalletController_*`, `emailOtpController_*`
- **User Profile**: `profileController_*`
- **Contacts**: `contactController_*`
- **Invitations**: `invitationController_*`
- **Organizations**: `organizationController_*`
- **Approvals**: `approvalController_*`

## Requirements

- Node.js >= 16.0.0
- TypeScript >= 4.5.0

## License

MIT

## Contributing

This package is auto-generated from the Gluon DApp Service OpenAPI specification.

For issues and feature requests, please visit: https://github.com/your-org/gluon-dapp-service/issues