HbarSuite Docs
  • Welcome to HbarSuite
  • HbarSuite Developer Documentation
    • HbarSuite Smart Engine Applications
      • @hsuite/cross-chain-exchange
      • @hsuite/dao
        • DAO Application Testing
      • @hsuite/exchange
      • @hsuite/launchpad
      • @hsuite/multisig
      • @hsuite/nft-exchange
      • HSuite Smart App - Enterprise Hedera Application Framework
    • HSuite Libraries
      • @hsuite/api-key - Enterprise API Key Authentication System
      • @hsuite/auth-types
      • @hsuite/auth - Authentication Module
      • @hsuite/client-types
      • @hsuite/client - Client Service Module
      • @hsuite/dkg-types - Distributed Key Generation Type Definitions
      • @hsuite/hashgraph-types - Hedera Hashgraph Type Definitions
      • @hsuite/health - Comprehensive System Health Monitoring
      • @hsuite/helpers - Utility Library
      • @hsuite/ipfs - InterPlanetary File System Integration
      • @hsuite/shared-types - Shared Type Definitions
      • @hsuite/smart-config - Configuration Management
      • @hsuite/smart-ledgers - Multi-Ledger Management
      • @hsuite/smart-network-types - Smart Network Type Definitions
      • @hsuite/smart-transaction-types - Smart Transaction Type Definitions
      • @hsuite/smartnode-sdk - SmartNode Software Development Kit
      • @hsuite/snapshots - Multi-Ledger Token Snapshot Management
      • @hsuite/subscriptions-types - Subscription Management Type Definitions
      • @hsuite/subscriptions - Enterprise Subscription Management System
      • @hsuite/throttler-types - Rate Limiting Type Definitions
      • @hsuite/throttler - Advanced Rate Limiting for NestJS
      • @hsuite/users-types - User Type Definitions
      • @hsuite/users - User Management Module
      • @hsuite/validators-types
  • General Documentation
    • Smart Apps and Interaction
      • Subscription-Based Model
      • Token-Gate Model
    • The Smart Node Network
      • security-layer
      • Type of Validators Explained
      • Understanding Validators in Our System
      • Automating Responses to Network Changes & Key Rotation
      • Ensuring Continuous Operation and Recovery
      • Generating and Sharing Keys Collaboratively
      • Handling Node Expulsion and Replacement
      • Managing Cluster Membership
      • Protecting Secrets with Shamir's Method
      • Security Layer Integration
      • Setting Up Secure Clusters
    • Tokenomics
      • Tokenomics v1
      • Tokenomics V2
    • What is a Smart Node?
  • Restful APIs Documentation
Powered by GitBook
On this page
  • 📚 Table of Contents
  • ✨ Quick Start
  • Installation
  • Basic Setup
  • NestJS Integration
  • 🏗️ Architecture
  • Core Component Areas
  • Module Structure
  • 🔧 API Reference
  • Core Interfaces
  • Runtime Models
  • 📖 Guides
  • Web3 Entity Management Guide
  • Token Gate Authentication Guide
  • Configuration Management Guide
  • Utility Token Guide
  • 🎯 Examples
  • Web3 Entity Management
  • Token Gate Authentication
  • Configuration Management
  • Shared Types Service Integration
  • 🔗 Integration
  • Required Dependencies
  • Module Integration
  • Documentation Generation
  • Integration with HSuite Ecosystem
  1. HbarSuite Developer Documentation
  2. HSuite Libraries

@hsuite/shared-types - Shared Type Definitions

Previous@hsuite/ipfs - InterPlanetary File System IntegrationNext@hsuite/smart-config - Configuration Management

Last updated 2 days ago

🔗 Comprehensive shared types and validation library for the Smart Node ecosystem with Web3 entity management

Enterprise-grade shared types library providing robust interfaces, runtime validation models, and comprehensive support for Web3 entities, token gate authentication, utility tokens, and configuration options used across the HSuite distributed application architecture.


📚 Table of Contents


✨ Quick Start

Installation

npm install @hsuite/shared-types

Basic Setup

import { Web3Entity, ITokenGateEntity, _Utility } from '@hsuite/shared-types';

// Web3 entity with token balances
const web3Entity: Web3Entity = {
  walletId: "0.0.1234567",
  publicKey: "302a300506032b6570032100a6ef694df5acc1a05a7988d0a34ea5d4d045d8340254812c5c680c7f8c026c6b",
  balance: [
    { token_id: "0.0.123", amount: "100" },
    { token_id: "0.0.456", amount: "200", serial_number: 42 }
  ]
};

// Utility token with validation
const governanceToken = new _Utility({
  name: "HSuite Governance Token",
  id: "0.0.789012",
  treasury: "0.0.987654",
  decimals: "8"
});

NestJS Integration

import { SharedTypesModule, SharedTypesService } from '@hsuite/shared-types';

@Module({
  imports: [SharedTypesModule],
  providers: [MyService]
})
export class MyModule {}

@Injectable()
export class MyService {
  constructor(private readonly sharedTypesService: SharedTypesService) {}
  
  validateEntity(entityData: any): boolean {
    return this.sharedTypesService.validateEntity(entityData);
  }
}

🏗️ Architecture

Core Component Areas

🌐 Web3 Entity Management

  • Wallet Identification - Blockchain wallet address and public key management

  • Token Balance Tracking - Comprehensive token ownership and amount tracking

  • Multi-blockchain Support - Hedera Hashgraph, Ethereum, and other blockchain networks

  • Validation Models - Runtime validation with comprehensive error handling

🔐 Token Gate Authentication

  • Access Control - Token-based authentication and authorization systems

  • Role Management - Role definitions with token ownership requirements

  • Metadata Management - Rich token metadata for enhanced access control

  • Configuration Options - Flexible token gate behavior configuration

⚙️ Configuration Management

  • Authentication Options - JWT, Redis, cookies, and Passport.js configuration

  • Network Settings - Hedera operator credentials and network configuration

  • Utility Tokens - Network utility token definitions and management

  • Application Configuration - Centralized application setting management

🧩 Shared Utilities

  • Type Validation - Runtime validation for all shared types

  • Error Handling - Comprehensive validation error reporting

  • Service Integration - NestJS dependency injection support

  • Documentation - Complete Swagger/OpenAPI integration

Module Structure

src/
├── index.ts                                    # Main exports and public API
├── shared-types.module.ts                      # NestJS module definition
├── shared-types.service.ts                     # Injectable service for DI
├── interfaces/                                 # Type-safe interface definitions
│   ├── web3-entity.interface.ts               # Web3 wallet entity interface
│   ├── token-gate-entity.interface.ts         # Token gate entity interface
│   ├── utility.interface.ts                   # Utility token interface
│   └── auth.configuration.*.interface.ts      # Authentication config interfaces
└── models/                                     # Runtime validation models
    ├── web3-entity.model.ts                   # Web3 entity implementation
    ├── token-gate-*.model.ts                  # Token gate implementations
    ├── utility.model.ts                       # Utility token implementation
    └── auth-configuration-options.model.ts    # Auth config implementation

🔧 API Reference

Core Interfaces

Web3 Entity Types

Web3Entity

  • Purpose: Represents a blockchain wallet entity with balance information

  • Properties: walletId, publicKey, balance

  • Usage: Wallet authentication and token balance tracking

ITokenGateEntity

  • Purpose: Token balance entry for access control

  • Properties: token_id, amount, serial_number (optional)

  • Usage: Token-based authentication and authorization

Configuration Types

_IUtility

  • Purpose: Network utility token interface

  • Properties: name, id, treasury, decimals

  • Usage: Utility token definitions and management

_IOptions

  • Purpose: Authentication configuration interface

  • Properties: redis, jwt, cookieOptions, operator, passport, appName

  • Usage: System-wide authentication configuration

Token Gate Types

_IRole - Role-based access control interface_IMetadata - Token metadata interface for enriched information_IProperties - Token properties for subscription plans and periodicity_ITokenGateOptions - Configuration options for token gate behavior

Runtime Models

All interfaces have corresponding model classes with validation:

  • Web3EntityModel - Implements Web3Entity with validation

  • TokenGateEntity - Implements ITokenGateEntity with metadata

  • _Utility - Implements _IUtility with runtime validation

  • Token Gate Models - Role, Metadata, Properties, and Options with validation


📖 Guides

Web3 Entity Management Guide

Complete guide to managing blockchain wallet entities and token balances. Comprehensive guide covering Web3 entity creation, token balance management, wallet integration, blockchain interaction, and enterprise-grade Web3 entity management with validation and security features.

Token Gate Authentication Guide

Implement token-based access control and role management systems. Advanced implementation guide covering token gate configuration, role-based access control, permission management, subscription handling, and enterprise-grade token-based authentication systems.

Configuration Management Guide

Set up authentication, network, and application configuration options. Detailed configuration guide covering authentication settings, network configurations, application options, environment management, and enterprise-grade configuration management with validation and security.

Utility Token Guide

Manage network utility tokens and service definitions. Comprehensive guide for utility token management, service configuration, network utility handling, token economics, and enterprise-grade utility token systems with complete lifecycle management.


🎯 Examples

Web3 Entity Management

import { Web3Entity, Web3EntityModel, ITokenGateEntity } from '@hsuite/shared-types';

@Injectable()
export class Web3EntityService {
  
  async createWeb3Entity(entityData: any) {
    try {
      // Define token balances
      const tokenBalances: ITokenGateEntity[] = [
        {
          token_id: "0.0.123456",
          amount: "1000.50"
        },
        {
          token_id: "0.0.789012",
          amount: "1",
          serial_number: 42 // NFT with serial number
        }
      ];

      // Create Web3 entity
      const entity: Web3Entity = {
        walletId: entityData.walletId,
        publicKey: entityData.publicKey,
        balance: tokenBalances
      };

      // Validate with model
      const validatedEntity = new Web3EntityModel(entity);

      return {
        success: true,
        entity: validatedEntity,
        tokenCount: validatedEntity.balance.length,
        hasNFTs: validatedEntity.balance.some(token => token.serial_number !== undefined)
      };
    } catch (error) {
      throw new Error(`Web3 entity creation failed: ${error.message}`);
    }
  }

  async validateTokenOwnership(walletId: string, requiredTokenId: string, minimumAmount: string): Promise<boolean> {
    try {
      // In real implementation, fetch from blockchain
      const entity = await this.getWeb3Entity(walletId);
      
      const tokenBalance = entity.balance.find(token => token.token_id === requiredTokenId);
      
      if (!tokenBalance) {
        return false;
      }

      return parseFloat(tokenBalance.amount) >= parseFloat(minimumAmount);
    } catch (error) {
      console.error('Token ownership validation failed:', error);
      return false;
    }
  }

  private async getWeb3Entity(walletId: string): Promise<Web3Entity> {
    // Mock implementation - in real scenario, fetch from database or blockchain
    return {
      walletId,
      publicKey: "mock-public-key",
      balance: [
        { token_id: "0.0.123456", amount: "1000.50" }
      ]
    };
  }
}

Token Gate Authentication

import { _IRole, _IMetadata, _IProperties, TokenGateEntity } from '@hsuite/shared-types';

@Injectable()
export class TokenGateService {
  
  async createTokenGate(tokenGateData: any) {
    try {
      // Define token gate metadata
      const metadata: _IMetadata = {
        name: tokenGateData.name,
        description: tokenGateData.description,
        properties: {
          tier: tokenGateData.tier,
          benefits: tokenGateData.benefits,
          accessLevel: tokenGateData.accessLevel
        }
      };

      // Define role requirements
      const role: _IRole = {
        name: tokenGateData.roleName,
        permissions: tokenGateData.permissions,
        requiredTokens: [
          {
            tokenId: tokenGateData.requiredTokenId,
            minimumAmount: tokenGateData.minimumAmount
          }
        ]
      };

      // Define properties for subscription
      const properties: _IProperties = {
        subscriptionPlan: tokenGateData.subscriptionPlan,
        periodicity: tokenGateData.periodicity,
        autoRenewal: tokenGateData.autoRenewal || false
      };

      // Create token gate entity
      const tokenGate = new TokenGateEntity({
        metadata,
        role,
        properties,
        token_id: tokenGateData.tokenId,
        amount: tokenGateData.amount,
        serial_number: tokenGateData.serialNumber
      });

      return {
        success: true,
        tokenGate,
        configuration: {
          metadata,
          role,
          properties
        }
      };
    } catch (error) {
      throw new Error(`Token gate creation failed: ${error.message}`);
    }
  }

  async validateAccess(walletId: string, tokenGateId: string): Promise<{ hasAccess: boolean; reason?: string }> {
    try {
      const tokenGate = await this.getTokenGate(tokenGateId);
      const userEntity = await this.getWeb3Entity(walletId);

      // Check if user has required tokens
      for (const requiredToken of tokenGate.role.requiredTokens) {
        const userToken = userEntity.balance.find(token => token.token_id === requiredToken.tokenId);
        
        if (!userToken) {
          return {
            hasAccess: false,
            reason: `Missing required token: ${requiredToken.tokenId}`
          };
        }

        if (parseFloat(userToken.amount) < parseFloat(requiredToken.minimumAmount)) {
          return {
            hasAccess: false,
            reason: `Insufficient token balance for: ${requiredToken.tokenId}`
          };
        }
      }

      return { hasAccess: true };
    } catch (error) {
      return {
        hasAccess: false,
        reason: `Access validation failed: ${error.message}`
      };
    }
  }

  private async getTokenGate(tokenGateId: string): Promise<any> {
    // Mock implementation
    return {
      role: {
        requiredTokens: [
          { tokenId: "0.0.123456", minimumAmount: "100" }
        ]
      }
    };
  }

  private async getWeb3Entity(walletId: string): Promise<Web3Entity> {
    // Mock implementation
    return {
      walletId,
      publicKey: "mock-key",
      balance: [
        { token_id: "0.0.123456", amount: "150" }
      ]
    };
  }
}

Configuration Management

import { _IOptions, _IUtility, _Utility } from '@hsuite/shared-types';
import { LedgerNetwork } from '@hsuite/smart-ledgers';

@Injectable()
export class ConfigurationService {
  
  async setupAuthenticationConfiguration(configData: any): Promise<_IOptions> {
    try {
      const authConfig: _IOptions = {
        redis: {
          host: configData.redis.host || 'localhost',
          port: configData.redis.port || 6379,
          ttl: configData.redis.ttl || 300
        },
        jwt: {
          secret: configData.jwt.secret,
          signOptions: {
            expiresIn: configData.jwt.expiresIn || '24h',
            issuer: configData.jwt.issuer || 'hsuite-platform'
          }
        },
        cookieOptions: {
          secure: configData.environment === 'production',
          httpOnly: true,
          sameSite: 'strict',
          maxAge: 86400000 // 24 hours
        },
        operator: {
          accountId: configData.operator.accountId,
          privateKey: configData.operator.privateKey,
          publicKey: configData.operator.publicKey,
          network: configData.operator.network || LedgerNetwork.HEDERA_TESTNET
        },
        passport: {
          defaultStrategy: 'jwt',
          session: false
        },
        appName: configData.appName || "HSuite Smart Node"
      };

      // Validate configuration
      this.validateAuthConfiguration(authConfig);

      return authConfig;
    } catch (error) {
      throw new Error(`Authentication configuration setup failed: ${error.message}`);
    }
  }

  async setupUtilityTokens(tokensData: any[]): Promise<_Utility[]> {
    try {
      const utilityTokens: _Utility[] = [];

      for (const tokenData of tokensData) {
        const utilityToken = new _Utility({
          name: tokenData.name,
          id: tokenData.id,
          treasury: tokenData.treasury,
          decimals: tokenData.decimals || "8"
        });

        utilityTokens.push(utilityToken);
      }

      return utilityTokens;
    } catch (error) {
      throw new Error(`Utility token setup failed: ${error.message}`);
    }
  }

  private validateAuthConfiguration(config: _IOptions): void {
    if (!config.jwt.secret) {
      throw new Error('JWT secret is required');
    }

    if (!config.operator.accountId || !config.operator.privateKey) {
      throw new Error('Operator credentials are required');
    }

    if (!config.redis.host || !config.redis.port) {
      throw new Error('Redis configuration is required');
    }
  }

  async getSystemConfiguration(): Promise<{
    auth: _IOptions;
    utilities: _Utility[];
    features: string[];
  }> {
    try {
      return {
        auth: await this.getAuthConfiguration(),
        utilities: await this.getUtilityTokens(),
        features: [
          'web3_authentication',
          'token_gate_access',
          'utility_tokens',
          'role_based_access',
          'subscription_management'
        ]
      };
    } catch (error) {
      throw new Error(`System configuration retrieval failed: ${error.message}`);
    }
  }

  private async getAuthConfiguration(): Promise<_IOptions> {
    // Implementation to retrieve auth config
    return {} as _IOptions;
  }

  private async getUtilityTokens(): Promise<_Utility[]> {
    // Implementation to retrieve utility tokens
    return [];
  }
}

Shared Types Service Integration

import { SharedTypesService } from '@hsuite/shared-types';

@Injectable()
export class IntegratedService {
  constructor(private readonly sharedTypesService: SharedTypesService) {}

  async processUserSession(sessionData: any) {
    try {
      // Validate entity data using shared service
      const isValidEntity = this.sharedTypesService.validateEntity(sessionData.web3Entity);
      
      if (!isValidEntity) {
        throw new Error('Invalid Web3 entity data');
      }

      // Process token gates
      const tokenGates = await this.processTokenGates(sessionData.tokenGates);

      // Setup user configuration
      const userConfig = await this.setupUserConfiguration(sessionData.config);

      return {
        success: true,
        session: {
          web3Entity: sessionData.web3Entity,
          tokenGates,
          configuration: userConfig,
          permissions: await this.calculatePermissions(sessionData.web3Entity, tokenGates)
        }
      };
    } catch (error) {
      throw new Error(`Session processing failed: ${error.message}`);
    }
  }

  private async processTokenGates(tokenGatesData: any[]): Promise<any[]> {
    return tokenGatesData.map(gate => {
      // Process and validate each token gate
      return this.validateAndProcessTokenGate(gate);
    });
  }

  private async setupUserConfiguration(configData: any): Promise<any> {
    // Setup user-specific configuration
    return this.sharedTypesService.setupConfiguration(configData);
  }

  private async calculatePermissions(web3Entity: any, tokenGates: any[]): Promise<string[]> {
    const permissions = [];

    // Calculate permissions based on token ownership
    for (const gate of tokenGates) {
      if (this.userMeetsRequirements(web3Entity, gate)) {
        permissions.push(...gate.permissions);
      }
    }

    return [...new Set(permissions)]; // Remove duplicates
  }

  private userMeetsRequirements(web3Entity: any, tokenGate: any): boolean {
    // Check if user meets token gate requirements
    return this.sharedTypesService.validateTokenGateRequirements(web3Entity, tokenGate);
  }

  private validateAndProcessTokenGate(gateData: any): any {
    // Validate and process individual token gate
    return this.sharedTypesService.processTokenGate(gateData);
  }
}

🔗 Integration

Required Dependencies

{
  "@nestjs/common": "^10.4.2",
  "@nestjs/core": "^10.4.2",
  "@hsuite/hashgraph-types": "^2.0.3",
  "@hsuite/subscriptions-types": "^2.1.1",
  "@hsuite/nestjs-swagger": "^1.0.3",
  "@compodoc/compodoc": "^1.1.23"
}

Module Integration

import { Module } from '@nestjs/common';
import { SharedTypesModule, SharedTypesService } from '@hsuite/shared-types';

@Module({
  imports: [SharedTypesModule],
  providers: [
    Web3EntityService,
    TokenGateService,
    ConfigurationService,
    IntegratedService
  ],
  exports: [
    Web3EntityService,
    TokenGateService,
    ConfigurationService,
    IntegratedService
  ]
})
export class MyModule {}

Documentation Generation

# Generate comprehensive documentation
npm run compodoc

# Generate documentation with coverage report
npm run compodoc:coverage

Integration with HSuite Ecosystem

// Complete integration with other HSuite modules
import { 
  Web3Entity, 
  ITokenGateEntity, 
  _IOptions, 
  SharedTypesService 
} from '@hsuite/shared-types';
import { AuthModule } from '@hsuite/auth';
import { HashgraphModule } from '@hsuite/hashgraph';

@Module({
  imports: [
    SharedTypesModule,
    AuthModule,
    HashgraphModule
  ]
})
export class SharedTypesEcosystemModule {}

@Injectable()
export class IntegratedSharedTypesService {
  constructor(
    private sharedTypesService: SharedTypesService,
    private authService: AuthService,
    private hashgraphService: HashgraphService
  ) {}

  async validateUserAccess(
    web3Entity: Web3Entity,
    requiredPermissions: string[]
  ): Promise<{ hasAccess: boolean; grantedPermissions: string[] }> {
    // Use shared types for validation
    const isValidEntity = this.sharedTypesService.validateEntity(web3Entity);
    
    if (!isValidEntity) {
      return { hasAccess: false, grantedPermissions: [] };
    }

    // Calculate permissions based on token ownership
    const grantedPermissions = await this.calculatePermissions(web3Entity);
    
    const hasAccess = requiredPermissions.every(permission => 
      grantedPermissions.includes(permission)
    );

    return { hasAccess, grantedPermissions };
  }

  private async calculatePermissions(web3Entity: Web3Entity): Promise<string[]> {
    const permissions = [];

    for (const token of web3Entity.balance) {
      const tokenPermissions = await this.getTokenPermissions(token);
      permissions.push(...tokenPermissions);
    }

    return [...new Set(permissions)];
  }

  private async getTokenPermissions(token: ITokenGateEntity): Promise<string[]> {
    // Get permissions based on token ownership
    return [];
  }
}

🔗 Comprehensive Shared Types: Enterprise-grade type definitions with runtime validation for Web3 entities, token gates, and configuration management.

🌐 Multi-Blockchain Support: Full support for Hedera Hashgraph, Ethereum, and other blockchain networks with consistent type interfaces.

🔐 Token-Based Authentication: Complete token gate system with role-based access control, metadata management, and subscription support.


Built with ❤️ by the HbarSuite Team Copyright © 2024 HbarSuite. All rights reserved.

✨ Quick Start
🏗️ Architecture
🔧 API Reference
📖 Guides
🎯 Examples
🔗 Integration