HbarSuite Docs
  • Welcome to HbarSuite
  • HbarSuite Developer Documentation
    • HbarSuite Smart Engine Applications
      • @hsuite/cross-chain-exchange
      • @hsuite/dao
        • DAO Application Testing
      • @hsuite/exchange
      • @hsuite/launchpad
      • @hsuite/multisig
      • @hsuite/nft-exchange
      • HSuite Smart App - Enterprise Hedera Application Framework
    • HSuite Libraries
      • @hsuite/api-key - Enterprise API Key Authentication System
      • @hsuite/auth-types
      • @hsuite/auth - Authentication Module
      • @hsuite/client-types
      • @hsuite/client - Client Service Module
      • @hsuite/dkg-types - Distributed Key Generation Type Definitions
      • @hsuite/hashgraph-types - Hedera Hashgraph Type Definitions
      • @hsuite/health - Comprehensive System Health Monitoring
      • @hsuite/helpers - Utility Library
      • @hsuite/ipfs - InterPlanetary File System Integration
      • @hsuite/shared-types - Shared Type Definitions
      • @hsuite/smart-config - Configuration Management
      • @hsuite/smart-ledgers - Multi-Ledger Management
      • @hsuite/smart-network-types - Smart Network Type Definitions
      • @hsuite/smart-transaction-types - Smart Transaction Type Definitions
      • @hsuite/smartnode-sdk - SmartNode Software Development Kit
      • @hsuite/snapshots - Multi-Ledger Token Snapshot Management
      • @hsuite/subscriptions-types - Subscription Management Type Definitions
      • @hsuite/subscriptions - Enterprise Subscription Management System
      • @hsuite/throttler-types - Rate Limiting Type Definitions
      • @hsuite/throttler - Advanced Rate Limiting for NestJS
      • @hsuite/users-types - User Type Definitions
      • @hsuite/users - User Management Module
      • @hsuite/validators-types
  • General Documentation
    • Smart Apps and Interaction
      • Subscription-Based Model
      • Token-Gate Model
    • The Smart Node Network
      • security-layer
      • Type of Validators Explained
      • Understanding Validators in Our System
      • Automating Responses to Network Changes & Key Rotation
      • Ensuring Continuous Operation and Recovery
      • Generating and Sharing Keys Collaboratively
      • Handling Node Expulsion and Replacement
      • Managing Cluster Membership
      • Protecting Secrets with Shamir's Method
      • Security Layer Integration
      • Setting Up Secure Clusters
    • Tokenomics
      • Tokenomics v1
      • Tokenomics V2
    • What is a Smart Node?
  • Restful APIs Documentation
Powered by GitBook
On this page
  • Table of Contents
  • Quick Start
  • Installation
  • Basic Setup
  • Use Client Service
  • Architecture
  • Core Components
  • Module Structure
  • API Reference
  • ClientModule
  • ClientService
  • Guides
  • Web3 Authentication Setup
  • Multi-Ledger Configuration
  • HTTP Client Usage
  • Examples
  • Complete Module Configuration
  • Service Usage Patterns
  • Factory Configuration Pattern
  • Integration
  • Required Dependencies
  • Environment Variables
  • Network Health Monitoring
  • ⚡ Performance Tip: The client service automatically handles connection pooling and request retry logic for optimal performance across multiple blockchain networks.
  1. HbarSuite Developer Documentation
  2. HSuite Libraries

@hsuite/client - Client Service Module

Previous@hsuite/client-typesNext@hsuite/dkg-types - Distributed Key Generation Type Definitions

Last updated 2 days ago

🌐 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

Installation

npm install @hsuite/client

Basic Setup

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

@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.

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

Configuration Interface:

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

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

@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

// 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

{
  "@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

# 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

@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.

Built with ❤️ by the HbarSuite Team Copyright © 2024 HbarSuite. All rights reserved.

Quick Start
Architecture
API Reference
Guides
Examples
Integration