@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/clientBasic 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 exportsAPI 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:
Errorif 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=30000Network 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.
