# @hsuite/smart-ledgers - Multi-Ledger Management

> 🌐 **Comprehensive multi-blockchain ledger management with unified API interface**

Advanced ledger management system providing unified access to multiple blockchain networks including Hedera Hashgraph, Ripple/XRP Ledger, and other supported networks with standardized operations and error handling.

***

## 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/smart-ledgers
```

### Basic Setup

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

@Module({
  imports: [
    SmartLedgersModule.forRootAsync({
      useFactory: () => ({
        defaultChain: ChainType.HASHGRAPH,
        networks: {
          [ChainType.HASHGRAPH]: {
            network: LedgerNetwork.HEDERA_TESTNET,
            endpoint: 'https://testnet.hedera.com'
          },
          [ChainType.RIPPLE]: {
            network: LedgerNetwork.RIPPLE_TESTNET,
            endpoint: 'wss://s.altnet.rippletest.net:51233'
          }
        }
      })
    })
  ]
})
export class AppModule {}
```

### Basic Usage

```typescript
@Injectable()
export class LedgerService {
  constructor(private smartLedgersService: SmartLedgersService) {}

  async getAccountBalance(chainType: ChainType, accountId: string) {
    return await this.smartLedgersService.getBalance(chainType, accountId);
  }
}
```

***

## Architecture

### Core Multi-Ledger Framework

#### 🌐 **Unified Blockchain Interface**

* **Multi-Ledger Support** - Hedera Hashgraph and Ripple (XRP) networks with unified API
* **Service-Oriented Architecture** - Specialized services for tokens, accounts, storage, and transactions
* **Adapter Pattern** - Extensible design for adding new blockchain networks
* **Plugin System** - Abstract base class for building blockchain-specific operations

#### 🔧 **Specialized Service Layer**

* **Account Management** - Account creation, updates, balance queries, and lifecycle management
* **Token Operations** - Complete fungible and non-fungible token support with transfers
* **Transaction Processing** - Full transaction lifecycle with query, execute, and validation
* **Cryptographic Operations** - Key management, signing, verification, and secure operations

#### 🏛️ **Network & Configuration Management**

* **Network Abstraction** - Seamless switching between mainnet and testnet environments
* **Configuration Management** - Centralized configuration with validation and defaults
* **Connection Pooling** - Efficient network connection management and retry mechanisms
* **Type Safety** - Comprehensive TypeScript interfaces and runtime validation

#### 📊 **Monitoring & Integration**

* **Real-time Status** - Network status monitoring and connection health checks
* **NestJS Integration** - Full dependency injection and modular design patterns
* **Documentation** - JSDoc documentation with Compodoc support
* **Error Handling** - Comprehensive error handling with detailed error types

### Service Architecture

```
ILedger (Main Interface)
├── IClient              # Network and client operations
├── IAccounts            # Account management operations
├── IFungibleToken       # Fungible token operations  
├── INonFungibleToken    # NFT operations
├── ITransactions        # Transaction management
├── IStorage             # Storage operations (HCS for Hedera)
├── ILedgerCryptography  # Cryptographic operations
└── ILedgerContainer     # Container facade for all services
```

### Module Structure

```
src/
├── smart-ledgers.module.ts            # NestJS module configuration
├── smart-ledgers.service.ts           # Core service implementation
├── interfaces/                        # Service interfaces
│   ├── ledger.interface.ts           # Core ledger interface
│   ├── ledger-adapter.interface.ts   # Adapter interface
│   ├── accounts.interface.ts         # Account operations
│   ├── token.interface.ts            # Token operations
│   ├── transactions.interface.ts     # Transaction operations
│   ├── client.interface.ts           # Client operations
│   ├── storage.interface.ts          # Storage operations
│   └── cryptography.interface.ts     # Cryptographic operations
├── types/                            # TypeScript type definitions
│   ├── network.types.ts              # Network and configuration types
│   └── ledger.types.ts               # Transaction and operation types
├── ledgers/                          # Blockchain implementations
│   ├── hashgraph/                    # Hedera Hashgraph implementation
│   │   ├── hashgraph.adapter.ts     # Hedera adapter
│   │   ├── hashgraph.ledger.ts      # Hedera ledger
│   │   ├── hashgraph-container.ts   # Service container
│   │   └── services/                # Specialized services
│   │       ├── hashgraph-accounts.service.ts
│   │       ├── hashgraph-fungible-token.service.ts
│   │       ├── hashgraph-non-fungible-token.service.ts
│   │       ├── hashgraph-transactions.service.ts
│   │       ├── hashgraph-client.service.ts
│   │       ├── hashgraph-storage.service.ts
│   │       └── hashgraph-cryptography.service.ts
│   └── ripple/                       # Ripple (XRP) implementation
│       ├── ripple.adapter.ts         # Ripple adapter
│       ├── ripple.ledger.ts          # Ripple ledger
│       ├── ripple-container.ts       # Service container
│       └── services/                 # Specialized services
└── plugins/                          # Plugin system
    └── plugin.abstract.ts            # Abstract plugin base class
```

***

## API Reference

### SmartLedgersModule

#### Static Methods

**`forRootAsync(options: SmartLedgersAsyncOptions): DynamicModule`**

* **Purpose**: Configure module with async dependencies and multiple ledgers
* **Parameters**: Configuration options with ledger credentials and network settings
* **Features**: Multi-blockchain support, connection pooling, retry mechanisms
* **Returns**: Configured dynamic module with all adapters and services

### SmartLedgersService

#### Core Methods

**`getAdapter(chain: ChainType): ILedgerAdapter`**

* **Purpose**: Get specific blockchain adapter for operations
* **Parameters**: Chain type (HASHGRAPH, RIPPLE)
* **Returns**: Configured adapter with full service access
* **Usage**: Primary method for accessing blockchain-specific functionality

**`initializeLedger(type: ChainType, config: ILedgerConfig): Promise<void>`**

* **Purpose**: Initialize ledger with configuration
* **Parameters**: Chain type and configuration object
* **Process**: Validates configuration, establishes connections, initializes services
* **Error Handling**: Throws configuration or connection errors

**`getTransaction(type: ChainType, transactionId: string): Promise<any>`**

* **Purpose**: Retrieve transaction details from any supported blockchain
* **Parameters**: Chain type and transaction identifier
* **Returns**: Transaction details with status and metadata
* **Cross-chain**: Unified interface across different blockchain formats

**`getNetworkStatus(type: ChainType): Promise<any>`**

* **Purpose**: Get current network status and connection health
* **Parameters**: Chain type to check
* **Returns**: Network status with connection details and health metrics
* **Monitoring**: Real-time network monitoring capabilities

### ILedgerAdapter

#### Core Interface

**`getLedger(): ILedger`**

* **Purpose**: Get the main ledger interface for operations
* **Returns**: Configured ledger with all specialized services
* **Usage**: Gateway to all blockchain operations

**`initialize(config: ILedgerConfig): Promise<void>`**

* **Purpose**: Initialize adapter with configuration
* **Parameters**: Complete ledger configuration object
* **Process**: Validates config, establishes connections, prepares services

**`getType(): ChainType`**

* **Purpose**: Get the blockchain type this adapter handles
* **Returns**: Chain type enumeration value
* **Usage**: Runtime type checking and routing

### Specialized Services

#### IAccounts - Account Management

**`create(initialBalance: number, publicKey?: string): Promise<AccountResult>`**

* **Purpose**: Create new blockchain account
* **Parameters**: Initial balance and optional public key
* **Returns**: Account creation result with account ID and transaction details
* **Blockchain-specific**: Handles different account creation patterns

**`getInfo(accountId: string): Promise<AccountInfo>`**

* **Purpose**: Retrieve comprehensive account information
* **Parameters**: Account identifier
* **Returns**: Account details including balance, keys, and properties
* **Cross-chain**: Unified account information format

**`getBalance(accountId: string): Promise<BalanceInfo>`**

* **Purpose**: Get account balance for native and token assets
* **Parameters**: Account identifier
* **Returns**: Balance information with native and token breakdowns
* **Multi-asset**: Supports multiple token types per account

#### IFungibleToken - Token Operations

**`create(tokenConfig: TokenConfig): Promise<TokenResult>`**

* **Purpose**: Create new fungible token
* **Parameters**: Complete token configuration with supply, keys, properties
* **Returns**: Token creation result with token ID and metadata
* **Features**: Configurable supply, freeze, wipe, and admin keys

**`mint(tokenId: string, amount: number, supplyKey: string): Promise<MintResult>`**

* **Purpose**: Mint additional tokens to treasury
* **Parameters**: Token ID, amount to mint, supply key for authorization
* **Returns**: Mint transaction result with new total supply
* **Authorization**: Requires valid supply key signature

**`transfer(fromAccountId: string, toAccountId: string, tokenId: string, amount: number, senderPrivateKey: string): Promise<TransferResult>`**

* **Purpose**: Transfer tokens between accounts
* **Parameters**: From/to accounts, token ID, amount, sender's private key
* **Returns**: Transfer transaction result with updated balances
* **Validation**: Validates balances and authorization before transfer

#### INonFungibleToken - NFT Operations

**`mint(tokenId: string, metadata: string, supplyKey: string): Promise<NFTMintResult>`**

* **Purpose**: Mint new NFT with metadata
* **Parameters**: Token ID, metadata URI/hash, supply key for authorization
* **Returns**: NFT mint result with serial number and transaction details
* **Metadata**: Supports IPFS hashes and URI formats

**`transfer(tokenId: string, serialNumber: number, fromAccountId: string, toAccountId: string, senderPrivateKey: string): Promise<NFTTransferResult>`**

* **Purpose**: Transfer specific NFT between accounts
* **Parameters**: Token ID, serial number, from/to accounts, sender key
* **Returns**: Transfer result with ownership confirmation
* **Ownership**: Validates current ownership before transfer

**`burn(tokenId: string, serialNumber: number, supplyKey: string): Promise<BurnResult>`**

* **Purpose**: Permanently burn NFT from circulation
* **Parameters**: Token ID, serial number, supply key for authorization
* **Returns**: Burn transaction result with confirmation
* **Permanent**: Irreversible operation reducing total supply

#### ITransactions - Transaction Management

**`getTransaction(transactionId: string): Promise<TransactionDetails>`**

* **Purpose**: Get detailed transaction information
* **Parameters**: Transaction identifier
* **Returns**: Complete transaction details with status and effects
* **History**: Access to historical transaction data

**`executeOfflineTransaction(transaction: any): Promise<ExecutionResult>`**

* **Purpose**: Execute pre-signed transaction
* **Parameters**: Serialized transaction object
* **Returns**: Execution result with confirmation
* **Offline**: Supports offline transaction preparation

#### ILedgerCryptography - Cryptographic Operations

**`generateKeyPair(): Promise<KeyPair>`**

* **Purpose**: Generate new cryptographic key pair
* **Returns**: Public and private key pair for blockchain operations
* **Security**: Uses blockchain-specific cryptographic standards

**`sign(privateKey: string, message: string): Promise<Signature>`**

* **Purpose**: Sign message with private key
* **Parameters**: Private key and message to sign
* **Returns**: Digital signature for verification
* **Standards**: Follows blockchain-specific signature formats

**`verify(publicKey: string, message: string, signature: string): Promise<boolean>`**

* **Purpose**: Verify signature against message and public key
* **Parameters**: Public key, original message, signature to verify
* **Returns**: Boolean indicating signature validity
* **Verification**: Cryptographic signature verification

#### IStorage - Consensus Storage (Hedera HCS)

**`createTopic(topicConfig: TopicConfig): Promise<TopicResult>`**

* **Purpose**: Create new consensus topic for message storage
* **Parameters**: Topic configuration with keys and properties
* **Returns**: Topic creation result with topic ID
* **Consensus**: Hedera Consensus Service integration

**`submitMessage(topicId: string, message: string): Promise<MessageResult>`**

* **Purpose**: Submit message to consensus topic
* **Parameters**: Topic ID and message content
* **Returns**: Message submission result with sequence number
* **Ordering**: Messages are consensus-ordered and timestamped

### Error Types

| Error Type                    | Description                      | Resolution                                    |
| ----------------------------- | -------------------------------- | --------------------------------------------- |
| **LedgerNotInitializedError** | Ledger not properly initialized  | Initialize ledger with valid configuration    |
| **InvalidChainTypeError**     | Unsupported blockchain type      | Use supported chain types (HASHGRAPH, RIPPLE) |
| **NetworkConnectionError**    | Network connectivity issues      | Check network settings and connectivity       |
| **InsufficientBalanceError**  | Insufficient funds for operation | Ensure account has sufficient balance         |
| **InvalidCredentialsError**   | Invalid account credentials      | Verify account ID and private key             |
| **TransactionFailedError**    | Transaction execution failed     | Check transaction parameters and retry        |

***

## 📖 Guides

### **Multi-Blockchain Setup Guide**

Complete guide to setting up and configuring multiple blockchain networks. Comprehensive setup instructions covering multi-chain architecture, adapter configuration, network-specific settings, consensus mechanisms, and unified blockchain operations with seamless cross-chain interoperability.

### **Plugin Development Guide**

Advanced guide to creating custom blockchain plugins and extensions. Detailed development guide covering plugin architecture, adapter interface implementation, blockchain-specific customizations, API extensions, and integration patterns for enterprise blockchain solutions.

### **Token Operations Guide**

Comprehensive guide to fungible and non-fungible token operations across blockchains. Advanced token management covering multi-chain token creation, cross-chain transfers, metadata standards, supply management, and enterprise-grade token lifecycle operations.

### **Security Best Practices Guide**

Security recommendations and best practices for blockchain operations. Enterprise security guide covering private key management, transaction signing, access control, audit trails, and secure blockchain integration patterns for production deployments.

***

## Examples

### Enterprise Multi-Blockchain Service

```typescript
import { SmartLedgersService, ChainType, LedgerNetwork } from '@hsuite/smart-ledgers';
import { Injectable, Logger } from '@nestjs/common';

@Injectable()
export class EnterpriseBlockchainService {
  private readonly logger = new Logger(EnterpriseBlockchainService.name);

  constructor(private readonly smartLedgers: SmartLedgersService) {}

  async deployTokenAcrossChains(tokenConfig: any) {
    try {
      const chains = [ChainType.HASHGRAPH, ChainType.RIPPLE];
      const deploymentResults = [];

      for (const chain of chains) {
        try {
          const adapter = this.smartLedgers.getAdapter(chain);
          const tokenService = adapter.getLedger().getTokenService();

          // Create token on each blockchain
          const tokenResult = await tokenService.create({
            name: tokenConfig.name,
            symbol: tokenConfig.symbol,
            decimals: tokenConfig.decimals,
            initialSupply: tokenConfig.initialSupply,
            supplyKey: tokenConfig.supplyKey,
            adminKey: tokenConfig.adminKey
          });

          deploymentResults.push({
            chain,
            success: true,
            tokenId: tokenResult.tokenId,
            transactionId: tokenResult.transactionId,
            totalSupply: tokenResult.totalSupply
          });

          this.logger.log(`Token deployed on ${chain}: ${tokenResult.tokenId}`);

        } catch (error) {
          deploymentResults.push({
            chain,
            success: false,
            error: error.message
          });

          this.logger.error(`Failed to deploy token on ${chain}:`, error);
        }
      }

      // Cross-chain verification
      const verificationResults = await this.verifyTokenDeployments(deploymentResults);

      return {
        success: deploymentResults.some(r => r.success),
        deployments: deploymentResults,
        verification: verificationResults,
        crossChainMapping: this.createCrossChainMapping(deploymentResults),
        deployedAt: new Date().toISOString()
      };

    } catch (error) {
      this.logger.error('Multi-chain token deployment error:', error);
      throw error;
    }
  }

  async performCrossChainNFTOperations(nftConfig: any) {
    try {
      // Select primary and secondary chains
      const primaryChain = ChainType.HASHGRAPH;
      const secondaryChain = ChainType.RIPPLE;

      // Create NFT collection on primary chain
      const primaryNFT = await this.createNFTCollection(primaryChain, nftConfig);

      // Mirror NFT information on secondary chain
      const secondaryNFT = await this.mirrorNFTCollection(secondaryChain, nftConfig, primaryNFT);

      // Mint NFTs across chains
      const mintResults = await this.mintNFTsAcrossChains([
        { chain: primaryChain, tokenId: primaryNFT.tokenId },
        { chain: secondaryChain, tokenId: secondaryNFT.tokenId }
      ], nftConfig.initialMints);

      return {
        success: true,
        primaryChain: {
          chain: primaryChain,
          tokenId: primaryNFT.tokenId,
          mintedCount: mintResults.filter(r => r.chain === primaryChain).length
        },
        secondaryChain: {
          chain: secondaryChain,
          tokenId: secondaryNFT.tokenId,
          mintedCount: mintResults.filter(r => r.chain === secondaryChain).length
        },
        crossChainOperations: mintResults,
        timestamp: new Date().toISOString()
      };

    } catch (error) {
      this.logger.error('Cross-chain NFT operations error:', error);
      throw error;
    }
  }

  async monitorNetworkHealth() {
    try {
      const chains = [ChainType.HASHGRAPH, ChainType.RIPPLE];
      const healthStatus = [];

      for (const chain of chains) {
        try {
          const networkStatus = await this.smartLedgers.getNetworkStatus(chain);
          const adapter = this.smartLedgers.getAdapter(chain);
          const clientService = adapter.getLedger().getClientService();

          const detailedStatus = await clientService.getNetworkStatus();

          healthStatus.push({
            chain,
            healthy: true,
            status: networkStatus,
            details: detailedStatus,
            lastChecked: new Date().toISOString()
          });

        } catch (error) {
          healthStatus.push({
            chain,
            healthy: false,
            error: error.message,
            lastChecked: new Date().toISOString()
          });
        }
      }

      const overallHealth = healthStatus.every(status => status.healthy);

      return {
        overallHealth,
        chainStatus: healthStatus,
        totalChains: chains.length,
        healthyChains: healthStatus.filter(s => s.healthy).length,
        monitoredAt: new Date().toISOString()
      };

    } catch (error) {
      this.logger.error('Network health monitoring error:', error);
      throw error;
    }
  }

  private async verifyTokenDeployments(deployments: any[]): Promise<any> {
    // Implementation would verify token deployments across chains
    const successfulDeployments = deployments.filter(d => d.success);
    
    return {
      verified: successfulDeployments.length > 0,
      verifiedChains: successfulDeployments.map(d => d.chain),
      consistency: successfulDeployments.length === deployments.length
    };
  }

  private createCrossChainMapping(deployments: any[]): any {
    // Implementation would create mapping between chain-specific token IDs
    const mapping = {};
    deployments.filter(d => d.success).forEach(deployment => {
      mapping[deployment.chain] = deployment.tokenId;
    });
    return mapping;
  }

  private async createNFTCollection(chain: ChainType, config: any): Promise<any> {
    const adapter = this.smartLedgers.getAdapter(chain);
    const nftService = adapter.getLedger().getNftService();

    return await nftService.create({
      name: config.name,
      symbol: config.symbol,
      maxSupply: config.maxSupply,
      supplyKey: config.supplyKey,
      adminKey: config.adminKey
    });
  }

  private async mirrorNFTCollection(chain: ChainType, config: any, primaryNFT: any): Promise<any> {
    // Implementation would create corresponding NFT collection on secondary chain
    return await this.createNFTCollection(chain, {
      ...config,
      name: `${config.name} Mirror`,
      symbol: `${config.symbol}M`
    });
  }

  private async mintNFTsAcrossChains(collections: any[], mintConfigs: any[]): Promise<any[]> {
    const results = [];

    for (const collection of collections) {
      for (const mintConfig of mintConfigs) {
        try {
          const adapter = this.smartLedgers.getAdapter(collection.chain);
          const nftService = adapter.getLedger().getNftService();

          const mintResult = await nftService.mint(
            collection.tokenId,
            mintConfig.metadata,
            mintConfig.supplyKey
          );

          results.push({
            chain: collection.chain,
            tokenId: collection.tokenId,
            serialNumber: mintResult.serialNumber,
            success: true
          });

        } catch (error) {
          results.push({
            chain: collection.chain,
            tokenId: collection.tokenId,
            success: false,
            error: error.message
          });
        }
      }
    }

    return results;
  }
}
```

### Advanced Plugin Development System

```typescript
import { SmartLedgerPluginAbstract, ChainType } from '@hsuite/smart-ledgers';
import { Injectable, Logger } from '@nestjs/common';
import { SmartConfigService } from '@hsuite/smart-config';

/**
 * Chain-specific handlers for complex operations
 */
class HashgraphAdvancedHandler {
  private readonly logger = new Logger(HashgraphAdvancedHandler.name);

  async executeComplexTransaction(operations: any[]): Promise<any> {
    // Hedera-specific complex transaction logic
    this.logger.log(`Executing ${operations.length} operations on Hedera`);
    
    // Implementation would handle Hedera-specific transaction batching
    return {
      transactionId: `0.0.123@${Date.now()}.${Math.random() * 1000000000}`,
      operations: operations.length,
      status: 'success'
    };
  }

  async optimizeGasCosts(transactions: any[]): Promise<any> {
    // Hedera-specific gas optimization
    return {
      originalCost: transactions.length * 0.0001,
      optimizedCost: transactions.length * 0.00008,
      savings: 0.00002 * transactions.length
    };
  }
}

class RippleAdvancedHandler {
  private readonly logger = new Logger(RippleAdvancedHandler.name);

  async executeComplexTransaction(operations: any[]): Promise<any> {
    // Ripple-specific complex transaction logic
    this.logger.log(`Executing ${operations.length} operations on Ripple`);
    
    // Implementation would handle XRP Ledger-specific transaction features
    return {
      transactionId: `${Math.random().toString(36).substring(2, 15).toUpperCase()}`,
      operations: operations.length,
      status: 'success'
    };
  }

  async optimizeGasCosts(transactions: any[]): Promise<any> {
    // Ripple-specific fee optimization
    return {
      originalCost: transactions.length * 0.000012,
      optimizedCost: transactions.length * 0.00001,
      savings: 0.000002 * transactions.length
    };
  }
}

/**
 * Advanced operations plugin demonstrating complex chain-agnostic logic
 */
@Injectable()
export class AdvancedOperationsPlugin extends SmartLedgerPluginAbstract {
  protected handlers: Record<string, any>;
  private readonly logger = new Logger(AdvancedOperationsPlugin.name);

  constructor(
    protected readonly smartConfigService: SmartConfigService,
    protected readonly smartLedgersService: SmartLedgersService
  ) {
    super(smartConfigService, smartLedgersService);
    
    // Initialize chain-specific handlers
    this.handlers = {
      [ChainType.HASHGRAPH]: new HashgraphAdvancedHandler(),
      [ChainType.RIPPLE]: new RippleAdvancedHandler()
    };
  }

  async executeAtomicOperations(operations: any[]) {
    try {
      const handler = this.getChainHandler();
      
      // Validate operations before execution
      const validationResult = await this.validateOperations(operations);
      if (!validationResult.valid) {
        throw new Error(`Operation validation failed: ${validationResult.reason}`);
      }

      // Optimize operations for current chain
      const optimizedOperations = await this.optimizeOperations(operations);

      // Execute complex transaction
      const result = await handler.executeComplexTransaction(optimizedOperations);

      // Post-execution verification
      const verification = await this.verifyExecution(result);

      return {
        success: true,
        chain: this.chain,
        originalOperations: operations.length,
        optimizedOperations: optimizedOperations.length,
        executionResult: result,
        verification,
        completedAt: new Date().toISOString()
      };

    } catch (error) {
      this.logger.error('Atomic operations execution error:', error);
      throw error;
    }
  }

  async optimizeCostsAcrossChains(transactions: any[]) {
    try {
      const allChains = [ChainType.HASHGRAPH, ChainType.RIPPLE];
      const optimizationResults = [];

      for (const chainType of allChains) {
        // Switch context to different chain
        const handler = this.handlers[chainType];
        
        if (handler) {
          const optimization = await handler.optimizeGasCosts(transactions);
          optimizationResults.push({
            chain: chainType,
            ...optimization
          });
        }
      }

      // Find most cost-effective chain
      const bestChain = optimizationResults.reduce((best, current) => 
        current.optimizedCost < best.optimizedCost ? current : best
      );

      return {
        optimizations: optimizationResults,
        recommendation: {
          bestChain: bestChain.chain,
          estimatedCost: bestChain.optimizedCost,
          potentialSavings: optimizationResults[0].originalCost - bestChain.optimizedCost
        },
        analyzedAt: new Date().toISOString()
      };

    } catch (error) {
      this.logger.error('Cross-chain cost optimization error:', error);
      throw error;
    }
  }

  async monitorAndBalance(thresholds: any) {
    try {
      const currentChain = this.chain;
      const ledger = this.ledger;
      
      // Monitor current chain performance
      const performance = await this.monitorChainPerformance(ledger);

      // Check if rebalancing is needed
      const rebalanceNeeded = await this.assessRebalanceNeed(performance, thresholds);

      if (rebalanceNeeded.required) {
        // Execute rebalancing operations
        const rebalanceResult = await this.executeRebalancing(
          rebalanceNeeded.operations
        );

        return {
          monitored: true,
          rebalanced: true,
          currentChain,
          performance,
          rebalanceResult,
          timestamp: new Date().toISOString()
        };
      }

      return {
        monitored: true,
        rebalanced: false,
        currentChain,
        performance,
        status: 'within_thresholds',
        timestamp: new Date().toISOString()
      };

    } catch (error) {
      this.logger.error('Monitor and balance error:', error);
      throw error;
    }
  }

  private async validateOperations(operations: any[]): Promise<any> {
    // Implementation would validate operations for current chain
    return {
      valid: operations.length > 0,
      reason: operations.length === 0 ? 'No operations provided' : null
    };
  }

  private async optimizeOperations(operations: any[]): Promise<any[]> {
    // Implementation would optimize operations for current chain
    return operations.filter(op => op.type !== 'redundant');
  }

  private async verifyExecution(result: any): Promise<any> {
    // Implementation would verify transaction execution
    return {
      verified: result.status === 'success',
      transactionId: result.transactionId,
      timestamp: new Date().toISOString()
    };
  }

  private async monitorChainPerformance(ledger: any): Promise<any> {
    // Implementation would monitor blockchain performance metrics
    return {
      throughput: 95,
      latency: 3.2,
      errorRate: 0.1,
      gasPrice: 0.0001
    };
  }

  private async assessRebalanceNeed(performance: any, thresholds: any): Promise<any> {
    // Implementation would assess if rebalancing is needed
    const needsRebalance = performance.errorRate > thresholds.maxErrorRate;
    
    return {
      required: needsRebalance,
      operations: needsRebalance ? ['switch_chain', 'redistribute_load'] : []
    };
  }

  private async executeRebalancing(operations: any[]): Promise<any> {
    // Implementation would execute rebalancing operations
    return {
      operations: operations.length,
      success: true,
      newDistribution: 'balanced'
    };
  }
}
```

### Complete Account and Transaction Management

```typescript
import { SmartLedgersService, ChainType } from '@hsuite/smart-ledgers';
import { Injectable, Logger } from '@nestjs/common';

@Injectable()
export class ComprehensiveBlockchainService {
  private readonly logger = new Logger(ComprehensiveBlockchainService.name);

  constructor(private readonly smartLedgers: SmartLedgersService) {}

  async createAndFundAccount(chain: ChainType, initialBalance: number) {
    try {
      const adapter = this.smartLedgers.getAdapter(chain);
      const accountService = adapter.getLedger().getAccountService();
      const cryptoService = adapter.getLedger().getCryptographyService();

      // Generate new key pair
      const keyPair = await cryptoService.generateKeyPair();

      // Create account with initial balance
      const accountResult = await accountService.create(
        initialBalance,
        keyPair.publicKey
      );

      // Verify account creation
      const accountInfo = await accountService.getInfo(accountResult.accountId);

      return {
        success: true,
        account: {
          accountId: accountResult.accountId,
          publicKey: keyPair.publicKey,
          privateKey: keyPair.privateKey, // Store securely in production
          initialBalance,
          createdAt: new Date().toISOString()
        },
        verification: {
          verified: accountInfo.accountId === accountResult.accountId,
          currentBalance: accountInfo.balance,
          status: accountInfo.status
        },
        transactionId: accountResult.transactionId
      };

    } catch (error) {
      this.logger.error('Account creation error:', error);
      throw error;
    }
  }

  async performCompleteTokenWorkflow(chain: ChainType, accountCredentials: any) {
    try {
      const adapter = this.smartLedgers.getAdapter(chain);
      const tokenService = adapter.getLedger().getTokenService();
      const nftService = adapter.getLedger().getNftService();

      // Step 1: Create fungible token
      const fungibleToken = await tokenService.create({
        name: 'Enterprise Token',
        symbol: 'ENT',
        decimals: 8,
        initialSupply: 1000000,
        supplyKey: accountCredentials.privateKey,
        adminKey: accountCredentials.privateKey
      });

      // Step 2: Create NFT collection
      const nftCollection = await nftService.create({
        name: 'Enterprise NFTs',
        symbol: 'ENFT',
        maxSupply: 10000,
        supplyKey: accountCredentials.privateKey,
        adminKey: accountCredentials.privateKey
      });

      // Step 3: Mint some NFTs
      const nftMints = [];
      for (let i = 0; i < 5; i++) {
        const mintResult = await nftService.mint(
          nftCollection.tokenId,
          `https://metadata.example.com/nft/${i}`,
          accountCredentials.privateKey
        );
        nftMints.push(mintResult);
      }

      // Step 4: Get final balances and info
      const accountInfo = await adapter.getLedger().getAccountService()
        .getInfo(accountCredentials.accountId);

      return {
        success: true,
        workflow: {
          fungibleToken: {
            tokenId: fungibleToken.tokenId,
            name: 'Enterprise Token',
            symbol: 'ENT',
            totalSupply: fungibleToken.totalSupply
          },
          nftCollection: {
            tokenId: nftCollection.tokenId,
            name: 'Enterprise NFTs',
            symbol: 'ENFT',
            mintedCount: nftMints.length
          },
          nftMints: nftMints.map(mint => ({
            tokenId: nftCollection.tokenId,
            serialNumber: mint.serialNumber,
            transactionId: mint.transactionId
          }))
        },
        accountStatus: {
          accountId: accountCredentials.accountId,
          balance: accountInfo.balance,
          tokenAssociations: accountInfo.tokenAssociations || []
        },
        completedAt: new Date().toISOString()
      };

    } catch (error) {
      this.logger.error('Complete token workflow error:', error);
      throw error;
    }
  }

  async demonstrateStorageOperations(chain: ChainType, accountCredentials: any) {
    try {
      if (chain !== ChainType.HASHGRAPH) {
        return {
          supported: false,
          message: 'Storage operations are currently only supported on Hedera Hashgraph',
          chain
        };
      }

      const adapter = this.smartLedgers.getAdapter(chain);
      const storageService = adapter.getLedger().getStorageService();

      // Create a topic for message storage
      const topic = await storageService.createTopic({
        memo: 'Enterprise Application Messages',
        adminKey: accountCredentials.privateKey,
        submitKey: accountCredentials.privateKey
      });

      // Submit messages to the topic
      const messages = [
        'System initialization complete',
        'User authentication successful',
        'Transaction processing started',
        'Data backup completed',
        'System status: operational'
      ];

      const messageResults = [];
      for (const message of messages) {
        const result = await storageService.submitMessage(
          topic.topicId,
          message
        );
        messageResults.push(result);
      }

      // Get topic information
      const topicInfo = await storageService.getTopicInfo(topic.topicId);

      return {
        success: true,
        storage: {
          topicId: topic.topicId,
          messagesSubmitted: messageResults.length,
          topicInfo: {
            memo: topicInfo.memo,
            sequenceNumber: topicInfo.sequenceNumber,
            runningHash: topicInfo.runningHash
          }
        },
        messages: messageResults.map((result, index) => ({
          content: messages[index],
          sequenceNumber: result.sequenceNumber,
          transactionId: result.transactionId,
          consensusTimestamp: result.consensusTimestamp
        })),
        demonstratedAt: new Date().toISOString()
      };

    } catch (error) {
      this.logger.error('Storage operations demonstration error:', error);
      throw error;
    }
  }
}
```

***

## Integration

### Required Dependencies

```json
{
  "@nestjs/common": "^10.4.2",
  "@nestjs/core": "^10.4.2",
  "@hashgraph/sdk": "^2.62.0",
  "xrpl": "^2.14.0",
  "@hsuite/smart-config": "^2.1.1",
  "@hsuite/helpers": "^2.0.8"
}
```

### Environment Configuration

```bash
# Hedera Hashgraph Configuration
HEDERA_ACCOUNT_ID=0.0.123456
HEDERA_PRIVATE_KEY=302e020100300506032b657004220420...
HEDERA_PUBLIC_KEY=302a300506032b6570032100...
HEDERA_NETWORK=testnet
HEDERA_MAX_QUERY_PAYMENT=1
HEDERA_MAX_TRANSACTION_FEE=2

# Ripple (XRP) Configuration  
RIPPLE_ADDRESS=rUocf1ixKzTuEe34kmVhRvGqNCofY1NJzV
RIPPLE_SEED=sn3nxiW7v8KXzPzAqzyHXbSSKNuN9
RIPPLE_NETWORK=testnet
RIPPLE_TIMEOUT=30000
RIPPLE_FEE_CUSHION=1.2
RIPPLE_MAX_FEE_XRP=2

# General Configuration
SMART_LEDGERS_ENABLED=true
SMART_LEDGERS_DEFAULT_CHAIN=hashgraph
SMART_LEDGERS_RETRY_ATTEMPTS=3
SMART_LEDGERS_TIMEOUT=30000
```

### Module Integration

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

@Module({
  imports: [
    ConfigModule.forRoot(),
    SmartLedgersModule.forRootAsync({
      imports: [ConfigModule],
      useFactory: (configService: ConfigService) => ({
        ledgers: {
          [ChainType.HASHGRAPH]: {
            network: configService.get('HEDERA_NETWORK') === 'mainnet' 
              ? LedgerNetwork.HEDERA_MAINNET 
              : LedgerNetwork.HEDERA_TESTNET,
            credentials: {
              accountId: configService.get('HEDERA_ACCOUNT_ID'),
              privateKey: configService.get('HEDERA_PRIVATE_KEY'),
              publicKey: configService.get('HEDERA_PUBLIC_KEY')
            },
            options: {
              maxQueryPayment: configService.get('HEDERA_MAX_QUERY_PAYMENT', 1),
              maxTransactionFee: configService.get('HEDERA_MAX_TRANSACTION_FEE', 2),
              maxRetries: configService.get('SMART_LEDGERS_RETRY_ATTEMPTS', 3),
              timeout: configService.get('SMART_LEDGERS_TIMEOUT', 30000)
            }
          },
          [ChainType.RIPPLE]: {
            network: configService.get('RIPPLE_NETWORK') === 'mainnet'
              ? LedgerNetwork.RIPPLE_MAINNET
              : LedgerNetwork.RIPPLE_TESTNET,
            credentials: {
              address: configService.get('RIPPLE_ADDRESS'),
              seed: configService.get('RIPPLE_SEED')
            },
            options: {
              timeout: configService.get('RIPPLE_TIMEOUT', 30000),
              feeCushion: configService.get('RIPPLE_FEE_CUSHION', 1.2),
              maxFeeXRP: configService.get('RIPPLE_MAX_FEE_XRP', '2')
            }
          }
        }
      }),
      inject: [ConfigService],
      isGlobal: true
    })
  ]
})
export class BlockchainIntegrationModule {}
```

### Usage Patterns

```typescript
// Basic service injection
@Injectable()
export class MyService {
  constructor(private readonly smartLedgers: SmartLedgersService) {}

  async performOperation() {
    // Get adapter for specific chain
    const adapter = this.smartLedgers.getAdapter(ChainType.HASHGRAPH);
    
    // Access specialized services
    const accountService = adapter.getLedger().getAccountService();
    const nftService = adapter.getLedger().getNftService();
    
    // Perform operations
    const accountInfo = await accountService.getInfo('0.0.123456');
    const mintResult = await nftService.mint('0.0.789012', 'metadata', 'supplyKey');
  }
}
```

### Plugin Development

```typescript
// Create custom plugin extending base abstract class
@Injectable()
export class CustomPlugin extends SmartLedgerPluginAbstract {
  protected handlers = {
    [ChainType.HASHGRAPH]: new HashgraphHandler(),
    [ChainType.RIPPLE]: new RippleHandler()
  };

  async customOperation(data: any) {
    const handler = this.getChainHandler();
    return await handler.executeCustomLogic(data);
  }
}
```

### Network Switching

```typescript
// Switch between networks dynamically
const testnetAdapter = smartLedgers.getAdapter(ChainType.HASHGRAPH);
// Configure for mainnet operations
await smartLedgers.initializeLedger(ChainType.HASHGRAPH, {
  network: LedgerNetwork.HEDERA_MAINNET,
  credentials: mainnetCredentials
});
```

***

**🌐 Multi-Blockchain**: Unified interface for Hedera Hashgraph and Ripple (XRP) networks with extensible architecture.

**🔧 Service-Oriented**: Specialized services for accounts, tokens, transactions, and cryptographic operations.

**🏗️ Enterprise-Ready**: Full NestJS integration with comprehensive error handling and monitoring capabilities.

***

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