# @hsuite/smartnode-sdk - SmartNode Software Development Kit

> 🚀 **Comprehensive SDK for SmartNode services and multi-ledger blockchain operations**

Enterprise-grade TypeScript SDK providing unified access to SmartNode network operations, validator management, and complete Hedera Hashgraph integration with extensible architecture for multi-blockchain support.

***

## 📚 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/smartnode-sdk
```

### Basic Setup

```typescript
import { SmartNodeSdkModule } from '@hsuite/smartnode-sdk';

@Module({
  imports: [
    SmartNodeSdkModule.forRootAsync({
      imports: [ConfigModule],
      useFactory: (configService: ConfigService) => ({
        client: {
          baseUrl: configService.get('SMARTNODE_BASE_URL'),
          timeout: configService.get('SMARTNODE_TIMEOUT', 30000),
          headers: {
            'Authorization': `Bearer ${configService.get('SMARTNODE_API_KEY')}`
          }
        }
      }),
      inject: [ConfigService]
    })
  ]
})
export class AppModule {}
```

### Basic Usage

```typescript
@Injectable()
export class BlockchainService {
  constructor(private smartNodeSdk: SmartNodeSdkService) {}

  async getNetworkStatus() {
    // Get SmartNode network status
    const status = await this.smartNodeSdk.sdk.smartNode.general.getStatus();
    const network = await this.smartNodeSdk.sdk.smartNode.general.getNetwork();
    
    return { status, network };
  }

  async manageAccount(accountId: string) {
    // Get account information via Hedera integration
    const accountInfo = await this.smartNodeSdk.sdk.hashgraph.accounts.getInfo(accountId);
    const balance = await this.smartNodeSdk.sdk.hashgraph.accounts.getAccountBalance(accountId);
    
    return { accountInfo, balance };
  }
}
```

***

## 🏗️ Architecture

### Hierarchical SDK Structure

The SDK provides a comprehensive, hierarchical structure through the `SmartNodeSdkService`:

```typescript
sdk: {
  smartNode: {
    general: GeneralSdk;           // Core SmartNode operations
    validators: ValidatorsSdk;     // Validator management
  },
  hashgraph: {
    accounts: AccountsHashgraphSdk;      // Account management
    transactions: TransactionsHashgraphSdk; // Transaction operations
    hcs: HcsHashgraphSdk;               // Hedera Consensus Service
    hts: HtsHashgraphSdk;               // Hedera Token Service
  },
  ripple: {
    // Future: Ripple blockchain integration
  }
}
```

### Core Components

#### 🌐 **SmartNode Services**

* **General Operations** - Node identification, status monitoring, network management
* **Validator Management** - Consensus, token, and account validator operations
* **Network Coordination** - Multi-node communication and coordination

#### ⚡ **Hedera Hashgraph Integration**

* **Account Services** - Complete account lifecycle management
* **Transaction Services** - Transaction submission and monitoring
* **Consensus Service (HCS)** - Topic management and messaging
* **Token Service (HTS)** - Token operations and management

#### 🔄 **Extensible Architecture**

* **Multi-Ledger Support** - Ready for Ripple and other blockchain integrations
* **Modular Design** - Independent service modules with clear separation
* **Type-Safe Configuration** - Full TypeScript support with runtime validation

### Module Structure

```
src/
├── smartnode-sdk.service.ts        # Main SDK orchestration service
├── smartnode-sdk.module.ts         # NestJS module configuration
├── sdk-options.interface.ts        # Configuration interfaces
├── smart-nodes/
│   ├── base.smart-node.ts          # Base SDK class
│   ├── general.smart-node.ts       # General SmartNode operations
│   └── validators.smart-node.ts    # Validator management
├── hashgraph/
│   ├── accounts.hashgraph.ts       # Account operations
│   ├── transactions.hashgraph.ts   # Transaction management
│   ├── hcs.hashgraph.ts           # Consensus service
│   └── hts.hashgraph.ts           # Token service
└── types/
    ├── interfaces/                 # TypeScript interfaces
    └── models/                     # Implementation models
```

***

## 🔧 API Reference

### SmartNodeSdkService

#### Core SDK Structure

```typescript
class SmartNodeSdkService {
  readonly sdk: {
    smartNode: {
      general: GeneralSdk;
      validators: ValidatorsSdk;
    };
    hashgraph: {
      accounts: AccountsHashgraphSdk;
      transactions: TransactionsHashgraphSdk;
      hcs: HcsHashgraphSdk;
      hts: HtsHashgraphSdk;
    };
    ripple: {};
  };
}
```

### SmartNode Services

#### GeneralSdk - Core SmartNode Operations

**`getIdentifier(): Promise<ISmartNetwork.IOperator.IEntity>`**

* Retrieves SmartNode operator entity details
* **Returns**: Unique identifier and node details
* **Usage**: Node identification in network operations

**`getStatus(): Promise<ISmartNetwork.ISmartNode.IState>`**

* Gets current operational status and health metrics
* **Returns**: Node status, uptime, performance metrics
* **Usage**: Health monitoring and diagnostics

**`getNetwork(): Promise<Array<ISmartNetwork.INetwork.IEntity>>`**

* Retrieves comprehensive list of whitelisted smart-nodes
* **Returns**: Array of network entities with status and capabilities
* **Usage**: Network topology and node discovery

**`getUtilities(): Promise<any>`**

* Retrieves HSuite utility tokens and capabilities
* **Returns**: Available utilities and their configurations
* **Usage**: Feature discovery and capability assessment

#### ValidatorsSdk - Validator Management

**Consensus Validators:**

* `addConsensusValidator(params): Promise<string>` - Submit new consensus validator
* `readConsensusValidator(timestamp): Promise<IValidators.IConsensus.IValidationParams>` - Retrieve consensus validator

**Token Validators:**

* `addTokenValidator(params): Promise<string>` - Submit new token validator
* `readTokenValidator(timestamp): Promise<IValidators.IToken.IValidationParams>` - Retrieve token validator

**Account Validators:**

* `addAccountValidator(params): Promise<string>` - Submit new account validator
* `readAccountValidator(timestamp): Promise<IValidators.IAccount.IValidationParams>` - Retrieve account validator

### Hedera Hashgraph Services

#### AccountsHashgraphSdk - Account Management

**Account Information:**

* `getInfo(accountId): Promise<IHashgraph.ILedger.IAccounts.IResponse.IInfo>` - Account details
* `getKeys(accountId): Promise<any>` - Account public keys
* `getAccountBalance(accountId): Promise<any>` - Account balance query

**Account Lifecycle:**

* `createAccount(params): Promise<any>` - Create new account
* `updateAccount(accountId, params): Promise<any>` - Update account properties
* `deleteAccount(accountId, params): Promise<any>` - Delete account

**Transfer Operations:**

* `transferHbar(params): Promise<any>` - HBAR transfers
* `transferToken(params): Promise<any>` - Fungible token transfers
* `transferNftToken(params): Promise<any>` - NFT transfers

#### TransactionsHashgraphSdk - Transaction Management

**Transaction Operations:**

* Transaction submission and status monitoring
* Transaction history and queries
* Fee estimation and optimization
* Batch transaction processing

#### HcsHashgraphSdk - Hedera Consensus Service

**Topic Management:**

* Topic creation, update, and deletion
* Topic configuration and permissions
* Topic information retrieval

**Message Operations:**

* Message submission to topics
* Message retrieval and history
* Subscription management

#### HtsHashgraphSdk - Hedera Token Service

**Token Management:**

* Token creation and configuration
* Token information queries
* Supply management operations

**Token Operations:**

* Token transfers and approvals
* NFT minting and burning
* Token association and dissociation

### Configuration Interfaces

#### SDK Options Interface

```typescript
interface ISdk.IOptions {
  client: IClient.IOptions;
}

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

***

## 📖 Guides

### **SmartNode Network Guide**

Learn about SmartNode network operations and topology management. Comprehensive guide covering network architecture, node discovery, consensus mechanisms, validator management, and enterprise-grade SmartNode deployment and operations.

### **Validator Setup Guide**

Configure and manage validators across different topics. Advanced configuration guide covering validator deployment, consensus topic management, validation rules, performance monitoring, and enterprise validator infrastructure management.

### **Hedera Integration Guide**

Complete guide to using Hedera Hashgraph services through the SDK. Detailed integration guide covering Hedera account management, transaction processing, token operations, consensus service, and enterprise Hedera blockchain integration.

***

## 🎯 Examples

### SmartNode Network Operations

```typescript
import { SmartNodeSdkService } from '@hsuite/smartnode-sdk';

@Injectable()
export class NetworkMonitoringService {
  constructor(private smartNodeSdk: SmartNodeSdkService) {}

  async monitorNetworkHealth() {
    try {
      // Get current node status
      const nodeStatus = await this.smartNodeSdk.sdk.smartNode.general.getStatus();
      
      // Get network topology
      const networkNodes = await this.smartNodeSdk.sdk.smartNode.general.getNetwork();
      
      // Get node identifier
      const nodeIdentifier = await this.smartNodeSdk.sdk.smartNode.general.getIdentifier();
      
      // Get available utilities
      const utilities = await this.smartNodeSdk.sdk.smartNode.general.getUtilities();

      return {
        currentNode: {
          identifier: nodeIdentifier,
          status: nodeStatus,
          health: nodeStatus.health || 'unknown'
        },
        network: {
          totalNodes: networkNodes.length,
          activeNodes: networkNodes.filter(node => node.status === 'active').length,
          nodes: networkNodes.map(node => ({
            id: node.id,
            status: node.status,
            capabilities: node.capabilities
          }))
        },
        utilities: utilities,
        monitoredAt: new Date().toISOString()
      };
    } catch (error) {
      throw new Error(`Network monitoring failed: ${error.message}`);
    }
  }

  async getNetworkConnectivity() {
    const network = await this.smartNodeSdk.sdk.smartNode.general.getNetwork();
    
    const connectivityReport = {
      totalNodes: network.length,
      onlineNodes: 0,
      offlineNodes: 0,
      nodeDetails: []
    };

    for (const node of network) {
      const isOnline = node.status === 'active' || node.status === 'online';
      
      if (isOnline) {
        connectivityReport.onlineNodes++;
      } else {
        connectivityReport.offlineNodes++;
      }

      connectivityReport.nodeDetails.push({
        nodeId: node.id,
        status: node.status,
        lastSeen: node.lastSeen || 'unknown',
        networkRole: node.role || 'participant'
      });
    }

    return {
      ...connectivityReport,
      networkHealth: (connectivityReport.onlineNodes / connectivityReport.totalNodes * 100).toFixed(2) + '%',
      timestamp: new Date().toISOString()
    };
  }
}
```

### Validator Management Operations

```typescript
import { SmartNodeSdkService } from '@hsuite/smartnode-sdk';
import { IValidators } from '@hsuite/validators-types';

@Injectable()
export class ValidatorManagementService {
  constructor(private smartNodeSdk: SmartNodeSdkService) {}

  async setupConsensusValidator(validationConfig: any) {
    try {
      const validationParams: Omit<IValidators.IConsensus.IValidationParams, 'validateParams'> = {
        conditions: {
          requireSubmitKey: validationConfig.requireSubmitKey || true,
          maxMessageSize: validationConfig.maxMessageSize || 1024,
          allowPublicSubmission: validationConfig.allowPublicSubmission || false,
          messageEncoding: validationConfig.messageEncoding || 'utf-8'
        }
      };

      // Add consensus validator
      const timestamp = await this.smartNodeSdk.sdk.smartNode.validators.addConsensusValidator(
        validationParams
      );

      return {
        success: true,
        validatorTimestamp: timestamp,
        validatorType: 'consensus',
        configuration: validationParams,
        message: 'Consensus validator added successfully'
      };
    } catch (error) {
      throw new Error(`Consensus validator setup failed: ${error.message}`);
    }
  }

  async setupTokenValidator(tokenValidationConfig: any) {
    try {
      const validationParams: Omit<IValidators.IToken.IValidationParams, 'validateParams'> = {
        conditions: {
          maxTransferAmount: tokenValidationConfig.maxTransferAmount || '1000000',
          allowMinting: tokenValidationConfig.allowMinting !== false,
          allowBurning: tokenValidationConfig.allowBurning !== false,
          requireKyc: tokenValidationConfig.requireKyc || false,
          freezeDefault: tokenValidationConfig.freezeDefault || false,
          decimals: tokenValidationConfig.decimals || 18,
          maxSupply: tokenValidationConfig.maxSupply || '10000000000'
        }
      };

      const timestamp = await this.smartNodeSdk.sdk.smartNode.validators.addTokenValidator(
        validationParams
      );

      return {
        success: true,
        validatorTimestamp: timestamp,
        validatorType: 'token',
        configuration: validationParams
      };
    } catch (error) {
      throw new Error(`Token validator setup failed: ${error.message}`);
    }
  }

  async setupAccountValidator(accountValidationConfig: any) {
    try {
      const validationParams: Omit<IValidators.IAccount.IValidationParams, 'validateParams'> = {
        smartNodeSecurity: accountValidationConfig.securityLevel || 'partial',
        updateConditions: {
          values: accountValidationConfig.allowedUpdates || ['maxAutomaticTokenAssociations', 'accountMemo'],
          controller: accountValidationConfig.updateController || 'owner'
        },
        actionsConditions: {
          values: accountValidationConfig.allowedActions || ['transfer', 'update'],
          controller: accountValidationConfig.actionController || 'owner'
        },
        tokenGates: {
          fungibles: { tokens: accountValidationConfig.fungibleTokenGates || [] },
          nonFungibles: { tokens: accountValidationConfig.nftTokenGates || [] },
          timeRange: accountValidationConfig.tokenGateTimeRange || null
        },
        swapConditions: {
          prices: accountValidationConfig.swapPrices || []
        }
      };

      const timestamp = await this.smartNodeSdk.sdk.smartNode.validators.addAccountValidator(
        validationParams
      );

      return {
        success: true,
        validatorTimestamp: timestamp,
        validatorType: 'account',
        configuration: validationParams
      };
    } catch (error) {
      throw new Error(`Account validator setup failed: ${error.message}`);
    }
  }

  async getValidatorStatus(validatorType: 'consensus' | 'token' | 'account', timestamp: string) {
    try {
      let validator;

      switch (validatorType) {
        case 'consensus':
          validator = await this.smartNodeSdk.sdk.smartNode.validators.readConsensusValidator(timestamp);
          break;
        case 'token':
          validator = await this.smartNodeSdk.sdk.smartNode.validators.readTokenValidator(timestamp);
          break;
        case 'account':
          validator = await this.smartNodeSdk.sdk.smartNode.validators.readAccountValidator(timestamp);
          break;
        default:
          throw new Error(`Unsupported validator type: ${validatorType}`);
      }

      return {
        validatorType,
        timestamp,
        configuration: validator,
        status: 'active',
        retrievedAt: new Date().toISOString()
      };
    } catch (error) {
      throw new Error(`Validator status retrieval failed: ${error.message}`);
    }
  }
}
```

### Hedera Account Management

```typescript
import { SmartNodeSdkService } from '@hsuite/smartnode-sdk';
import { IHashgraph } from '@hsuite/hashgraph-types';

@Injectable()
export class HederaAccountService {
  constructor(private smartNodeSdk: SmartNodeSdkService) {}

  async getCompleteAccountInfo(accountId: string) {
    try {
      // Get account information
      const accountInfo = await this.smartNodeSdk.sdk.hashgraph.accounts.getInfo(accountId);
      
      // Get account balance
      const balance = await this.smartNodeSdk.sdk.hashgraph.accounts.getAccountBalance(accountId);
      
      // Get account keys (if available)
      let keys;
      try {
        keys = await this.smartNodeSdk.sdk.hashgraph.accounts.getKeys(accountId);
      } catch (error) {
        console.warn('Failed to retrieve account keys:', error.message);
        keys = null;
      }

      return {
        account: {
          id: accountId,
          balance: balance,
          info: accountInfo,
          keys: keys
        },
        status: 'active',
        retrievedAt: new Date().toISOString()
      };
    } catch (error) {
      throw new Error(`Account information retrieval failed: ${error.message}`);
    }
  }

  async performAccountOperations(operations: any[]) {
    const results = [];

    for (const operation of operations) {
      try {
        let result;

        switch (operation.type) {
          case 'create':
            result = await this.smartNodeSdk.sdk.hashgraph.accounts.createAccount(operation.params);
            break;
          case 'update':
            result = await this.smartNodeSdk.sdk.hashgraph.accounts.updateAccount(
              operation.accountId,
              operation.params
            );
            break;
          case 'delete':
            result = await this.smartNodeSdk.sdk.hashgraph.accounts.deleteAccount(
              operation.accountId,
              operation.params
            );
            break;
          case 'transferHbar':
            result = await this.smartNodeSdk.sdk.hashgraph.accounts.transferHbar(operation.params);
            break;
          case 'transferToken':
            result = await this.smartNodeSdk.sdk.hashgraph.accounts.transferToken(operation.params);
            break;
          case 'transferNft':
            result = await this.smartNodeSdk.sdk.hashgraph.accounts.transferNftToken(operation.params);
            break;
          default:
            throw new Error(`Unsupported operation type: ${operation.type}`);
        }

        results.push({
          operation: operation.type,
          success: true,
          result: result,
          executedAt: new Date().toISOString()
        });
      } catch (error) {
        results.push({
          operation: operation.type,
          success: false,
          error: error.message,
          failedAt: new Date().toISOString()
        });
      }
    }

    return {
      totalOperations: operations.length,
      successful: results.filter(r => r.success).length,
      failed: results.filter(r => !r.success).length,
      results: results
    };
  }

  async batchTransferHbar(transfers: Array<{from: string, to: string, amount: number}>) {
    const transferResults = [];

    for (const transfer of transfers) {
      try {
        const result = await this.smartNodeSdk.sdk.hashgraph.accounts.transferHbar({
          from: transfer.from,
          to: transfer.to,
          amount: transfer.amount,
          memo: `Batch transfer ${new Date().toISOString()}`
        });

        transferResults.push({
          from: transfer.from,
          to: transfer.to,
          amount: transfer.amount,
          success: true,
          transactionResult: result
        });
      } catch (error) {
        transferResults.push({
          from: transfer.from,
          to: transfer.to,
          amount: transfer.amount,
          success: false,
          error: error.message
        });
      }
    }

    return {
      batchSize: transfers.length,
      successful: transferResults.filter(r => r.success).length,
      failed: transferResults.filter(r => !r.success).length,
      totalAmount: transfers.reduce((sum, t) => sum + t.amount, 0),
      results: transferResults
    };
  }
}
```

### Hedera Consensus Service Operations

```typescript
import { SmartNodeSdkService } from '@hsuite/smartnode-sdk';

@Injectable()
export class HederaConsensusService {
  constructor(private smartNodeSdk: SmartNodeSdkService) {}

  async manageConsensusTopic(topicOperations: any) {
    try {
      const results = {};

      // Create topic if requested
      if (topicOperations.create) {
        const createResult = await this.smartNodeSdk.sdk.hashgraph.hcs.createTopic(
          topicOperations.create
        );
        results['create'] = createResult;
      }

      // Update topic if requested
      if (topicOperations.update && topicOperations.topicId) {
        const updateResult = await this.smartNodeSdk.sdk.hashgraph.hcs.updateTopic(
          topicOperations.topicId,
          topicOperations.update
        );
        results['update'] = updateResult;
      }

      // Submit message if requested
      if (topicOperations.submitMessage && topicOperations.topicId) {
        const messageResult = await this.smartNodeSdk.sdk.hashgraph.hcs.submitMessage({
          topicId: topicOperations.topicId,
          message: topicOperations.submitMessage.message,
          signature: topicOperations.submitMessage.signature
        });
        results['submitMessage'] = messageResult;
      }

      // Get topic info if requested
      if (topicOperations.getInfo && topicOperations.topicId) {
        const infoResult = await this.smartNodeSdk.sdk.hashgraph.hcs.getTopicInfo(
          topicOperations.topicId
        );
        results['info'] = infoResult;
      }

      return {
        success: true,
        topicId: topicOperations.topicId,
        operations: Object.keys(results),
        results: results,
        completedAt: new Date().toISOString()
      };
    } catch (error) {
      throw new Error(`Consensus topic management failed: ${error.message}`);
    }
  }

  async subscribeToTopic(topicId: string, onMessage: (message: any) => void) {
    try {
      // Note: Actual subscription implementation would depend on the SDK method
      const subscription = await this.smartNodeSdk.sdk.hashgraph.hcs.subscribeTo(
        topicId,
        onMessage
      );

      return {
        success: true,
        topicId: topicId,
        subscriptionId: subscription.subscriptionId || 'unknown',
        subscribedAt: new Date().toISOString()
      };
    } catch (error) {
      throw new Error(`Topic subscription failed: ${error.message}`);
    }
  }
}
```

### Hedera Token Service Operations

```typescript
import { SmartNodeSdkService } from '@hsuite/smartnode-sdk';

@Injectable()
export class HederaTokenService {
  constructor(private smartNodeSdk: SmartNodeSdkService) {}

  async manageToken(tokenOperations: any) {
    try {
      const results = {};

      // Create token if requested
      if (tokenOperations.create) {
        const createResult = await this.smartNodeSdk.sdk.hashgraph.hts.createToken(
          tokenOperations.create
        );
        results['create'] = createResult;
      }

      // Update token if requested
      if (tokenOperations.update && tokenOperations.tokenId) {
        const updateResult = await this.smartNodeSdk.sdk.hashgraph.hts.updateToken(
          tokenOperations.tokenId,
          tokenOperations.update
        );
        results['update'] = updateResult;
      }

      // Mint tokens if requested
      if (tokenOperations.mint && tokenOperations.tokenId) {
        const mintResult = await this.smartNodeSdk.sdk.hashgraph.hts.mintToken(
          tokenOperations.tokenId,
          tokenOperations.mint
        );
        results['mint'] = mintResult;
      }

      // Burn tokens if requested
      if (tokenOperations.burn && tokenOperations.tokenId) {
        const burnResult = await this.smartNodeSdk.sdk.hashgraph.hts.burnToken(
          tokenOperations.tokenId,
          tokenOperations.burn
        );
        results['burn'] = burnResult;
      }

      // Get token info if requested
      if (tokenOperations.getInfo && tokenOperations.tokenId) {
        const infoResult = await this.smartNodeSdk.sdk.hashgraph.hts.getTokenInfo(
          tokenOperations.tokenId
        );
        results['info'] = infoResult;
      }

      return {
        success: true,
        tokenId: tokenOperations.tokenId,
        operations: Object.keys(results),
        results: results,
        completedAt: new Date().toISOString()
      };
    } catch (error) {
      throw new Error(`Token management failed: ${error.message}`);
    }
  }

  async performTokenTransfers(transfers: any[]) {
    const transferResults = [];

    for (const transfer of transfers) {
      try {
        let result;

        if (transfer.type === 'fungible') {
          result = await this.smartNodeSdk.sdk.hashgraph.accounts.transferToken({
            tokenId: transfer.tokenId,
            from: transfer.from,
            to: transfer.to,
            amount: transfer.amount
          });
        } else if (transfer.type === 'nft') {
          result = await this.smartNodeSdk.sdk.hashgraph.accounts.transferNftToken({
            tokenId: transfer.tokenId,
            from: transfer.from,
            to: transfer.to,
            serialNumber: transfer.serialNumber
          });
        } else {
          throw new Error(`Unsupported transfer type: ${transfer.type}`);
        }

        transferResults.push({
          ...transfer,
          success: true,
          result: result
        });
      } catch (error) {
        transferResults.push({
          ...transfer,
          success: false,
          error: error.message
        });
      }
    }

    return {
      totalTransfers: transfers.length,
      successful: transferResults.filter(r => r.success).length,
      failed: transferResults.filter(r => !r.success).length,
      results: transferResults
    };
  }
}
```

### Comprehensive SDK Integration

```typescript
import { SmartNodeSdkService } from '@hsuite/smartnode-sdk';
import { Injectable } from '@nestjs/common';

@Injectable()
export class ComprehensiveBlockchainService {
  constructor(private smartNodeSdk: SmartNodeSdkService) {}

  async performComplexWorkflow(workflowConfig: any) {
    const workflowResults = {
      workflowId: workflowConfig.id || Date.now().toString(),
      startedAt: new Date().toISOString(),
      steps: [],
      errors: []
    };

    try {
      // Step 1: Check SmartNode network health
      const networkStatus = await this.smartNodeSdk.sdk.smartNode.general.getStatus();
      workflowResults.steps.push({
        step: 'network_health_check',
        success: true,
        result: { health: networkStatus.health, status: 'operational' }
      });

      // Step 2: Setup validators if required
      if (workflowConfig.setupValidators) {
        const validatorTimestamp = await this.smartNodeSdk.sdk.smartNode.validators.addConsensusValidator(
          workflowConfig.validatorConfig
        );
        workflowResults.steps.push({
          step: 'validator_setup',
          success: true,
          result: { timestamp: validatorTimestamp }
        });
      }

      // Step 3: Create Hedera account if required
      if (workflowConfig.createAccount) {
        const accountResult = await this.smartNodeSdk.sdk.hashgraph.accounts.createAccount(
          workflowConfig.accountConfig
        );
        workflowResults.steps.push({
          step: 'account_creation',
          success: true,
          result: accountResult
        });
      }

      // Step 4: Create token if required
      if (workflowConfig.createToken) {
        const tokenResult = await this.smartNodeSdk.sdk.hashgraph.hts.createToken(
          workflowConfig.tokenConfig
        );
        workflowResults.steps.push({
          step: 'token_creation',
          success: true,
          result: tokenResult
        });
      }

      // Step 5: Submit consensus message if required
      if (workflowConfig.submitMessage) {
        const messageResult = await this.smartNodeSdk.sdk.hashgraph.hcs.submitMessage({
          topicId: workflowConfig.topicId,
          message: workflowConfig.message
        });
        workflowResults.steps.push({
          step: 'consensus_message',
          success: true,
          result: messageResult
        });
      }

      workflowResults['completedAt'] = new Date().toISOString();
      workflowResults['status'] = 'completed';
      workflowResults['successfulSteps'] = workflowResults.steps.filter(s => s.success).length;

      return workflowResults;
    } catch (error) {
      workflowResults.errors.push({
        error: error.message,
        occurredAt: new Date().toISOString()
      });

      workflowResults['status'] = 'failed';
      workflowResults['failedAt'] = new Date().toISOString();

      throw new Error(`Workflow execution failed: ${error.message}`);
    }
  }

  async getSystemOverview() {
    try {
      // Get SmartNode information
      const [nodeIdentifier, nodeStatus, network, utilities] = await Promise.allSettled([
        this.smartNodeSdk.sdk.smartNode.general.getIdentifier(),
        this.smartNodeSdk.sdk.smartNode.general.getStatus(),
        this.smartNodeSdk.sdk.smartNode.general.getNetwork(),
        this.smartNodeSdk.sdk.smartNode.general.getUtilities()
      ]);

      return {
        smartNode: {
          identifier: nodeIdentifier.status === 'fulfilled' ? nodeIdentifier.value : null,
          status: nodeStatus.status === 'fulfilled' ? nodeStatus.value : null,
          network: network.status === 'fulfilled' ? network.value : null,
          utilities: utilities.status === 'fulfilled' ? utilities.value : null
        },
        sdk: {
          services: ['smartNode', 'hashgraph'],
          smartNodeServices: ['general', 'validators'],
          hashgraphServices: ['accounts', 'transactions', 'hcs', 'hts'],
          futureServices: ['ripple']
        },
        timestamp: new Date().toISOString()
      };
    } catch (error) {
      throw new Error(`System overview generation failed: ${error.message}`);
    }
  }
}
```

***

## 🔗 Integration

### Required Dependencies

```json
{
  "@nestjs/common": "^10.4.2",
  "@nestjs/core": "^10.4.2",
  "@hsuite/client": "^2.1.2",
  "@hsuite/hashgraph-types": "^2.0.3",
  "@hsuite/smart-network-types": "^2.0.0",
  "@hsuite/validators-types": "^2.0.0",
  "@hsuite/nestjs-swagger": "^1.0.3",
  "@hashgraph/sdk": "^2.62.0",
  "@hsuite/helpers": "^2.1.0"
}
```

### Environment Variables

```env
# SmartNode Configuration
SMARTNODE_BASE_URL=https://api.smartnode.example.com
SMARTNODE_API_KEY=your_api_key_here
SMARTNODE_TIMEOUT=30000

# Network Configuration
SMARTNODE_NETWORK_ID=testnet
SMARTNODE_OPERATOR_ID=0.0.123456
SMARTNODE_OPERATOR_KEY=your_operator_key

# Client Configuration
HTTP_TIMEOUT=30000
MAX_RETRIES=3
ENABLE_LOGGING=true
```

### Module Configuration

```typescript
import { SmartNodeSdkModule } from '@hsuite/smartnode-sdk';
import { ConfigModule, ConfigService } from '@nestjs/config';

@Module({
  imports: [
    SmartNodeSdkModule.forRootAsync({
      imports: [ConfigModule],
      useFactory: (configService: ConfigService) => ({
        client: {
          baseUrl: configService.get('SMARTNODE_BASE_URL'),
          timeout: configService.get('SMARTNODE_TIMEOUT', 30000),
          headers: {
            'Authorization': `Bearer ${configService.get('SMARTNODE_API_KEY')}`,
            'Content-Type': 'application/json'
          },
          retries: configService.get('MAX_RETRIES', 3),
          enableLogging: configService.get('ENABLE_LOGGING', true)
        }
      }),
      inject: [ConfigService]
    })
  ]
})
export class AppModule {}
```

### Integration with HSuite Ecosystem

```typescript
// Complete integration with other HSuite modules
@Module({
  imports: [
    AuthModule,
    SmartNodeSdkModule,
    ValidatorsModule,
    HashgraphModule,
    SmartConfigModule
  ]
})
export class BlockchainEcosystemModule {}

@Injectable()
export class IntegratedBlockchainService {
  constructor(
    private smartNodeSdk: SmartNodeSdkService,
    private authService: AuthService,
    private validatorsService: ValidatorsService
  ) {}

  async executeSecureOperation(
    operation: any,
    session: IAuth.ICredentials.IWeb3.IEntity
  ) {
    // 1. Validate permissions
    const hasPermission = await this.authService.validatePermission(
      session,
      `smartnode:${operation.type}`
    );

    if (!hasPermission) {
      throw new Error('Insufficient permissions for SmartNode operation');
    }

    // 2. Check network health
    const networkStatus = await this.smartNodeSdk.sdk.smartNode.general.getStatus();
    if (networkStatus.health !== 'healthy') {
      throw new Error('SmartNode network is not healthy');
    }

    // 3. Execute operation via SDK
    let result;
    switch (operation.type) {
      case 'account_create':
        result = await this.smartNodeSdk.sdk.hashgraph.accounts.createAccount(operation.params);
        break;
      case 'token_create':
        result = await this.smartNodeSdk.sdk.hashgraph.hts.createToken(operation.params);
        break;
      case 'validator_add':
        result = await this.smartNodeSdk.sdk.smartNode.validators.addConsensusValidator(operation.params);
        break;
      default:
        throw new Error(`Unsupported operation type: ${operation.type}`);
    }

    return {
      success: true,
      operation: operation.type,
      result: result,
      executedBy: session.walletId,
      executedAt: new Date().toISOString()
    };
  }
}
```

***

**🚀 Enterprise SDK**: Comprehensive SmartNode integration with full TypeScript support and enterprise-grade reliability.

**🌐 Multi-Ledger Ready**: Extensible architecture supporting Hedera Hashgraph with planned Ripple integration.

**⚡ Developer Focused**: Type-safe APIs with comprehensive documentation and extensive example implementations.

***

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