# @hsuite/hashgraph-types - Hedera Hashgraph Type Definitions

> 🌐 **Comprehensive TypeScript type system for Hedera Hashgraph network integration with complete SDK support**

Enterprise-grade type definitions and validation library providing robust interfaces, models, and runtime validation for all Hashgraph operations including transactions, accounts, tokens, DID management, and RESTful API interactions.

***

## 📚 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/hashgraph-types
```

### Basic Setup

```typescript
import { IHashgraph, Hashgraph } from '@hsuite/hashgraph-types';

// Interface-based type definitions
const operatorConfig: IHashgraph.IOperator = {
  accountId: "0.0.123456",
  privateKey: "302e020100300506032b657004220420...",
  publicKey: "302a300506032b6570032100..."
};

// Model-based runtime validation
const operator = new Hashgraph.Operator(operatorConfig);
```

### NestJS Integration

```typescript
import { Hashgraph } from '@hsuite/hashgraph-types';

@Controller('hashgraph')
export class HashgraphController {
  @Post('transaction')
  @ApiResponse({ type: Hashgraph.TransactionDetails })
  async createTransaction(@Body() data: any): Promise<Hashgraph.TransactionDetails> {
    return new Hashgraph.TransactionDetails(data);
  }
}
```

***

## 🏗️ Architecture

### Dual Namespace System

#### 🔧 **IHashgraph Namespace (Interfaces)**

* **Core Types** - Transaction details, identity, and key management
* **Account Operations** - Balance tracking and account management
* **Token Operations** - Fungible and non-fungible token interfaces
* **DID Operations** - W3C compliant decentralized identifiers
* **RESTful APIs** - Complete Hedera REST API interface definitions
* **Ledger Operations** - HCS, HTS, and account operations

#### 🏛️ **Hashgraph Namespace (Models)**

* **Runtime Validation** - Concrete classes with built-in validation
* **Swagger Integration** - Complete API documentation decorators
* **Cryptographic Support** - Ed25519, ECDSA, and RSA key management
* **Network Integration** - Mirror node and operator implementations

### Core Domains

#### 💰 **Account & Token Management**

* **Account Operations** - Create, update, delete, transfer
* **Balance Tracking** - HBAR and token balance management
* **Token Operations** - HTS fungible and non-fungible tokens
* **Multi-signature** - Threshold key management

#### 🔐 **Identity & Security**

* **DID Operations** - W3C compliant identity management
* **Verifiable Credentials** - Complete VC lifecycle support
* **Key Management** - Multi-algorithm cryptographic support
* **Signature Validation** - Transaction authentication

#### 📡 **Network Integration**

* **Mirror Nodes** - Historical data access and queries
* **RESTful APIs** - Complete Hedera service integration
* **Consensus Service** - HCS topic management
* **Network Monitoring** - Status and performance tracking

### Module Structure

```
src/
├── index.ts                                    # Main exports
├── interfaces/                                 # IHashgraph namespace
│   ├── hashgraph.namespace.ts                  # Central interface hub
│   ├── interfaces/                             # Core interfaces
│   └── namespaces/                             # Specialized domains
│       ├── commons/                            # Shared utilities
│       ├── did/                                # DID operations
│       ├── ledger/                             # Ledger operations
│       └── restful/                            # RESTful APIs
└── models/                                     # Hashgraph namespace
    ├── hashgraph.namespace.ts                  # Central model hub
    ├── models/                                 # Core implementations
    └── namespaces/                             # Domain implementations
```

***

## 🔧 API Reference

### Core Interface Types

**`IHashgraph.IOperator`**

* **Purpose**: Hedera network operator account configuration
* **Properties**: accountId, privateKey, publicKey
* **Usage**: Network operations and transaction submission

**`IHashgraph.ITransactionDetails`**

* **Purpose**: Comprehensive transaction metadata
* **Properties**: transactionId, status, consensusTimestamp, result
* **Usage**: Transaction tracking and status monitoring

**`IHashgraph.IAccountBalance`**

* **Purpose**: Account balance information
* **Properties**: hbarBalance, tokens
* **Usage**: Balance queries and tracking

### DID Operations

**`IHashgraph.IDID.IDocument`**

* **Purpose**: W3C compliant DID document structure
* **Properties**: id, verificationMethod, authentication
* **Usage**: Decentralized identity management

### RESTful API Types

**`IHashgraph.IRestful.IAccounts`**

* **Purpose**: Account REST API interfaces
* **Operations**: Info, balance, transactions
* **Usage**: Account data retrieval

**`IHashgraph.IRestful.IHTS`**

* **Purpose**: Token Service REST API interfaces
* **Operations**: Token info, balances, operations
* **Usage**: Token data and operations

***

## 📖 Guides

### **Transaction Management Guide**

Complete guide to Hedera transaction lifecycle and management with status monitoring, transaction validation, and offline signing workflows. Covers transaction details creation, identity verification, and comprehensive error handling for enterprise blockchain operations.

### **Account Operations Guide**

Account creation, management, and balance operations including HBAR transfers, multi-signature setups, and account lifecycle management. Features complete account state tracking, token associations, and operator configuration for Hedera network interactions.

### **Token Operations Guide**

HTS fungible and non-fungible token operations with comprehensive token lifecycle management, supply controls, and custom fee configurations. Includes token creation, minting, burning, and transfer operations with complete validation and security features.

### **DID Implementation Guide**

Decentralized identifier operations and W3C compliance with complete DID document management, verifiable credentials support, and cryptographic verification. Features complete identity lifecycle management with Ed25519 and ECDSA key support.

***

## 🎯 Examples

### Transaction Management

```typescript
@Injectable()
export class TransactionService {
  async createTransaction(txData: any) {
    try {
      // Create transaction details
      const details = new Hashgraph.TransactionDetails({
        transactionId: txData.transactionId,
        status: "PENDING",
        consensusTimestamp: new Date().toISOString()
      });

      // Create transaction identity
      const identity = new Hashgraph.TransactionIdEntity({
        signerPublicKey: txData.publicKey,
        signature: txData.signature
      });

      return { details, identity };
    } catch (error) {
      throw new Error(`Transaction creation failed: ${error.message}`);
    }
  }
}
```

### Account & Token Operations

```typescript
@Injectable()
export class AccountTokenService {
  async getAccountInfo(accountId: string) {
    try {
      // Account balance with tokens
      const balance = new Hashgraph.AccountBalance({
        hbarBalance: 100,
        tokens: new Map([
          ["0.0.123456", 1000],
          ["0.0.789012", 500]
        ])
      });

      // Individual token balance
      const tokenBalance = new Hashgraph.TokenBalance({
        tokenId: "0.0.123456",
        balance: 1000,
        decimals: 8,
        symbol: "HSUITE"
      });

      return { accountBalance: balance, tokenBalances: [tokenBalance] };
    } catch (error) {
      throw new Error(`Account info retrieval failed: ${error.message}`);
    }
  }
}
```

### DID Operations

```typescript
@Injectable()
export class DIDService {
  async registerDID(didData: any) {
    try {
      const didDocument = new Hashgraph.DID.Document.Register({
        did: didData.did,
        document: {
          "@context": ["https://www.w3.org/ns/did/v1"],
          id: didData.did,
          verificationMethod: [{
            id: "#key-1",
            type: "Ed25519VerificationKey2020",
            controller: didData.did,
            publicKeyMultibase: didData.publicKey
          }]
        }
      });

      return { success: true, document: didDocument };
    } catch (error) {
      throw new Error(`DID registration failed: ${error.message}`);
    }
  }
}
```

### Network Operations

```typescript
@Injectable()
export class NetworkService {
  async setupMirrorNode(config: any) {
    try {
      const mirrorNode = new Hashgraph.MirrorNode({
        endpoint: config.endpoint,
        apiKey: config.apiKey,
        timeout: config.timeout || 30000
      });

      const options = new Hashgraph.Options({
        maxTransactionFee: 1000000,
        transactionValidDuration: 120
      });

      return { mirrorNode, options };
    } catch (error) {
      throw new Error(`Network setup failed: ${error.message}`);
    }
  }
}
```

### Ledger Operations

```typescript
@Injectable()
export class LedgerService {
  async createToken(tokenData: any) {
    try {
      const tokenCreate = new Hashgraph.Ledger.HTS.FungibleToken.Create({
        name: tokenData.name,
        symbol: tokenData.symbol,
        decimals: tokenData.decimals,
        initialSupply: tokenData.initialSupply
      });

      return { operation: tokenCreate, type: 'fungible' };
    } catch (error) {
      throw new Error(`Token creation failed: ${error.message}`);
    }
  }

  async createTopic(topicData: any) {
    try {
      const topicCreate = new Hashgraph.Ledger.HCS.Topic.Create({
        memo: topicData.memo,
        adminKey: topicData.adminKey,
        submitKey: topicData.submitKey
      });

      return { operation: topicCreate, type: 'topic' };
    } catch (error) {
      throw new Error(`Topic creation failed: ${error.message}`);
    }
  }
}
```

***

## 🔗 Integration

### Required Dependencies

```json
{
  "@nestjs/common": "^10.4.2",
  "@nestjs/core": "^10.4.2",
  "@hsuite/nestjs-swagger": "^1.0.3",
  "@hsuite/did-sdk-js": "^1.0.3",
  "@hsuite/vc-sl-sdk-js": "^1.0.3",
  "@compodoc/compodoc": "^1.1.23"
}
```

### Module Integration

```typescript
import { Module } from '@nestjs/common';
import { Hashgraph, IHashgraph } from '@hsuite/hashgraph-types';

@Module({
  providers: [
    TransactionService,
    AccountTokenService,
    DIDService,
    NetworkService,
    LedgerService
  ]
})
export class HashgraphModule {}
```

### Documentation Generation

```bash
# Generate comprehensive documentation
npm run compodoc

# Generate documentation with coverage report
npm run compodoc:coverage
```

### Integration with HSuite Ecosystem

```typescript
// Complete integration with other HSuite modules
import { Hashgraph, IHashgraph } from '@hsuite/hashgraph-types';
import { AuthModule } from '@hsuite/auth';
import { SmartNetworkModule } from '@hsuite/smart-network';

@Module({
  imports: [AuthModule, SmartNetworkModule]
})
export class HashgraphEcosystemModule {}

@Injectable()
export class IntegratedHashgraphService {
  constructor(
    private authService: AuthService,
    private networkService: SmartNetworkService
  ) {}

  async executeSecureOperation(
    operationData: any,
    session: IAuth.ICredentials.IWeb3.IEntity
  ): Promise<Hashgraph.TransactionDetails> {
    // Validate permissions and execute operations
    const hasPermission = await this.authService.validatePermission(
      session,
      'hashgraph:operation'
    );

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

    // Execute Hashgraph operation
    const details = new Hashgraph.TransactionDetails(operationData);
    return details;
  }
}
```

***

**🌐 Enterprise Hashgraph Integration**: Comprehensive TypeScript definitions with complete Hedera SDK support and W3C DID compliance.

**💰 Complete Token & Account Support**: Full HTS and account operations with multi-signature capabilities and balance tracking.

**🔐 Advanced Identity Management**: DID operations, verifiable credentials, and enterprise-grade cryptographic key management.

***

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