# @hsuite/client - Client Service Module

> 🌐 **Comprehensive NestJS client module for Web3 authentication and multi-ledger communication**

A powerful client service module that provides Web3-based authentication flow, dynamic node connection management, and network resilience with multi-chain support for HSuite applications.

***

## Table of Contents

* [Quick Start](#quick-start)
* [Architecture](#architecture)
* [API Reference](#api-reference)
* [Guides](#guides)
* [Examples](#examples)
* [Integration](#integration)

***

## Quick Start

### Installation

```bash
npm install @hsuite/client
```

### Basic Setup

```typescript
import { ClientModule } from '@hsuite/client';
import { ChainType, LedgerNetwork } from '@hsuite/smart-ledgers';

@Module({
  imports: [
    ClientModule.forRootAsync({
      useFactory: () => ({
        enabled: true,
        baseUrl: 'https://api.yourapp.com',
        ledgers: {
          [ChainType.HASHGRAPH]: {
            network: LedgerNetwork.HEDERA_TESTNET,
            credentials: {
              accountId: '0.0.123456',
              privateKey: 'your-private-key',
              publicKey: 'your-public-key'
            }
          }
        }
      })
    })
  ]
})
export class AppModule {}
```

### Use Client Service

```typescript
@Injectable()
export class YourService {
  constructor(private clientService: ClientService) {}

  async makeRequest() {
    const response = await this.clientService.axios.get('/api/data');
    return response.data;
  }
}
```

***

## Architecture

### Core Components

#### 🔐 **Authentication Flow**

* **Web3 Authentication** - Cryptographic signing with private key management
* **Session Management** - Cookie jar support for session persistence
* **Credential Storage** - Secure storage of Web3 credentials

#### 🌐 **Network Management**

* **Dynamic Node Connection** - Automatic failover and node discovery
* **Multi-Chain Support** - Hedera, Ripple, and other blockchain networks
* **Health Monitoring** - Periodic connection health checks

#### ⚡ **HTTP Client**

* **Axios Integration** - Configured HTTP client with interceptors
* **Request/Response Handling** - Automatic authentication header injection
* **Error Handling** - Network resilience with retry mechanisms

### Module Structure

```
src/
├── interfaces/          # TypeScript interfaces
├── client.service.ts    # Core client service implementation
├── client.module.ts     # Module configuration and setup
├── client.service.spec.ts # Unit tests
└── index.ts            # Public API exports
```

***

## API Reference

### ClientModule

#### Static Methods

**`forRootAsync(options: ClientModuleAsyncOptions): Promise<DynamicModule>`**

Configures the client module with async dependency injection and global scope.

```typescript
interface ClientModuleAsyncOptions {
  imports?: any[];
  useFactory?: (...args: any[]) => Promise<IClient.IOptions> | IClient.IOptions;
  inject?: any[];
  useClass?: Type<any>;
}
```

**Configuration Interface:**

```typescript
interface IClient.IOptions {
  enabled: boolean;
  baseUrl?: string;
  ledgers: Record<ChainType, ILedgerConfig>;
}
```

### ClientService

#### Properties

**`login: Auth.Credentials.Web3.Response.Login`**

* Current Web3 login credentials and authentication state
* **Returns**: Web3 authentication response with wallet details

**`operator: ISmartNetwork.IOperator.IEntity`**

* Current operator information for blockchain transactions
* **Returns**: Operator entity with account details and permissions

**`axios: AxiosInstance`**

* Configured axios instance for making authenticated HTTP requests
* **Returns**: Axios instance with auth headers and interceptors

#### Methods

**`onModuleInit(): Promise<void>`**

* Initializes client connection and performs Web3 authentication
* Called automatically during module startup
* **Throws**: `Error` if authentication or connection fails

***

## Guides

### Web3 Authentication Setup

Configure Web3 authentication with wallet integration and signature verification. Set up blockchain-based authentication flows and credential management.

### Multi-Ledger Configuration

Set up support for multiple blockchain networks with failover capabilities. Configure Hedera Hashgraph, Ripple/XRP Ledger, and other supported networks.

### HTTP Client Usage

Learn how to use the configured axios instance for authenticated API calls. Implement request interceptors, error handling, and retry logic.

***

## Examples

### Complete Module Configuration

```typescript
import { ClientModule } from '@hsuite/client';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { ChainType, LedgerNetwork } from '@hsuite/smart-ledgers';

@Module({
  imports: [
    ClientModule.forRootAsync({
      imports: [ConfigModule],
      useFactory: (configService: ConfigService) => ({
        enabled: true,
        baseUrl: configService.get('BASE_URL'),
        ledgers: {
          [ChainType.HASHGRAPH]: {
            network: LedgerNetwork.HEDERA_TESTNET,
            credentials: {
              accountId: configService.get('OPERATOR_ID'),
              privateKey: configService.get('OPERATOR_PRIVATE_KEY'),
              publicKey: configService.get('OPERATOR_PUBLIC_KEY')
            },
            options: {
              maxRetries: 3,
              timeout: 30000
            }
          },
          [ChainType.RIPPLE]: {
            network: LedgerNetwork.RIPPLE_TESTNET,
            credentials: {
              wallet: configService.get('RIPPLE_WALLET'),
              secret: configService.get('RIPPLE_SECRET')
            }
          }
        }
      }),
      inject: [ConfigService]
    })
  ]
})
export class AppModule {}
```

### Service Usage Patterns

```typescript
@Injectable()
export class BlockchainService {
  constructor(private clientService: ClientService) {}

  async getAccountInfo() {
    // Access current operator details
    const operator = this.clientService.operator;
    console.log('Operator Account:', operator.accountId);

    // Access login credentials
    const login = this.clientService.login;
    console.log('Wallet ID:', login.walletId);

    return { operator, login };
  }

  async makeAuthenticatedRequest() {
    try {
      // Use configured axios instance
      const response = await this.clientService.axios.get('/api/transactions');
      
      return {
        data: response.data,
        status: response.status,
        headers: response.headers
      };
    } catch (error) {
      console.error('Request failed:', error.message);
      throw error;
    }
  }

  async postTransaction(transactionData: any) {
    // POST requests with authentication
    const response = await this.clientService.axios.post('/api/submit', {
      transaction: transactionData,
      signature: 'auto-generated'
    });

    return response.data;
  }
}
```

### Factory Configuration Pattern

```typescript
// Custom configuration factory
@Injectable()
export class ClientConfigFactory {
  constructor(private configService: ConfigService) {}

  createClientOptions(): IClient.IOptions {
    return {
      enabled: this.configService.get('CLIENT_ENABLED', true),
      baseUrl: this.configService.get('API_BASE_URL'),
      ledgers: {
        [ChainType.HASHGRAPH]: {
          network: this.configService.get('HEDERA_NETWORK'),
          credentials: {
            accountId: this.configService.get('HEDERA_ACCOUNT_ID'),
            privateKey: this.configService.get('HEDERA_PRIVATE_KEY'),
            publicKey: this.configService.get('HEDERA_PUBLIC_KEY')
          },
          options: {
            maxRetries: this.configService.get('MAX_RETRIES', 3),
            timeout: this.configService.get('REQUEST_TIMEOUT', 30000)
          }
        }
      }
    };
  }
}

// Usage in module
ClientModule.forRootAsync({
  useClass: ClientConfigFactory
})
```

***

## Integration

### Required Dependencies

```json
{
  "@hsuite/smart-network-types": "^2.0.0",
  "@hsuite/auth-types": "^2.1.2", 
  "@hsuite/smart-config": "^2.1.1",
  "@hsuite/smart-ledgers": "^2.0.0"
}
```

### Environment Variables

```env
# API Configuration
BASE_URL=https://api.yourapp.com
CLIENT_ENABLED=true

# Hedera Configuration
HEDERA_NETWORK=testnet
HEDERA_ACCOUNT_ID=0.0.123456
HEDERA_PRIVATE_KEY=302e020100300506032b657004220420...
HEDERA_PUBLIC_KEY=302a300506032b6570032100...

# Ripple Configuration (optional)
RIPPLE_NETWORK=testnet
RIPPLE_WALLET=rN7n7otQDd6FczFgLdSqtcsAUxDkw6fzRH
RIPPLE_SECRET=snGHtDdoRNJkL5dX...

# Request Settings
MAX_RETRIES=3
REQUEST_TIMEOUT=30000
```

### Network Health Monitoring

```typescript
@Injectable()
export class HealthService {
  constructor(private clientService: ClientService) {}

  async checkNetworkHealth() {
    try {
      // Test network connectivity
      const response = await this.clientService.axios.get('/health');
      
      return {
        status: 'healthy',
        operator: this.clientService.operator,
        lastCheck: new Date(),
        networkResponse: response.status
      };
    } catch (error) {
      return {
        status: 'unhealthy',
        error: error.message,
        lastCheck: new Date()
      };
    }
  }
}
```

***

**🔐 Security Note**: Keep private keys and credentials secure. Use environment variables and never commit sensitive data to version control.

## **⚡ Performance Tip**: The client service automatically handles connection pooling and request retry logic for optimal performance across multiple blockchain networks.

<p align="center">Built with ❤️ by the HSuite Team<br>Copyright © 2025 HSuite. All rights reserved.</p>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.hsuite.network/developers/libs/client.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
