npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, πŸ‘‹, I’m Ryan HefnerΒ  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you πŸ™

Β© 2025 – Pkg Stats / Ryan Hefner

@hsuite/client

v2.1.3

Published

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

Downloads

47

Readme

@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

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.