npm package: @hsuite_leco/dao-library
Description: Reusable DAO component library for HSuite applications
Author: HSuite Team
Latest version: 1.0.2

# @hsuite/dao-library

A reusable DAO (Decentralized Autonomous Organization) component library for HSuite applications. This library provides a complete DAO governance solution that can be integrated into any Ionic/Angular application.

## 🎯 Features

- **Complete DAO Functionality**: Create and manage DAOs with full governance features
- **Proposal Management**: Create, vote on, and execute proposals
- **Voting System**: Token-weighted and non-weighted voting support
- **Real-time Updates**: WebSocket-based real-time event system
- **Provider Abstraction**: Pluggable architecture for wallet, notifications, IPFS, and API
- **TypeScript**: Full type safety and IntelliSense support
- **Ionic Compatible**: Built for Ionic/Angular applications

## 📦 Installation

### Local Workspace Installation

This library is currently configured for local workspace usage. Add to your `tsconfig.json`:

```json
{
  "compilerOptions": {
    "paths": {
      "@hsuite/dao-library": ["projects/dao-library/src/public-api"]
    }
  }
}
```

### Future npm Installation

Once published:

```bash
npm install @hsuite/dao-library
```

## 🚀 Quick Start

### Simple Setup (Using Default Providers)

The library now includes **default implementations** for all providers - just configure and go!

```typescript
import { NgModule } from '@angular/core';
import { DaoLibraryModule } from '@hsuite/dao-library';
import { environment } from './environments/environment';

@NgModule({
  imports: [
    DaoLibraryModule.forRoot({
      // Required: API Configuration
      apiUrl: environment.smartAppUrl,
      
      // Required: WalletConnect Configuration (for default wallet provider)
      walletConnect: {
        projectId: 'your-walletconnect-project-id',
        metadata: {
          name: 'Your App Name',
          description: 'Your app description',
          url: 'https://your-app.com',
          icons: ['https://your-app.com/icon.png']
        },
        network: 'mainnet' // or 'testnet'
      },
      
      // Optional: WebSocket for real-time updates
      websocket: {
        url: 'wss://your-api.com'
      },
      
      // Optional: IPFS Configuration
      ipfs: {
        gateway: environment.ipfsGateway
      },
      
      // Optional: Features & Routing
      routing: {
        basePath: '/dao',
        useHashRouting: true
      },
      features: {
        enableDashboard: true,
        enableProposals: true,
        enableVoting: true,
        enableMembership: true
      }
    })
  ]
})
export class AppModule {}
```

**That's it!** The library includes default implementations for:
- ✅ **WalletConnect v2** (Hedera integration)
- ✅ **HTTP/API Client** (Axios-based)
- ✅ **WebSocket** (Socket.io)
- ✅ **IPFS** (Upload & Gateway)
- ✅ **Notifications** (Ionic Toasts/Alerts)

### Advanced: Custom Provider Implementations (Optional)

You can override any provider with your own implementation:

```typescript
import {
  DaoLibraryModule,
  WALLET_PROVIDER,
  IWalletProvider
} from '@hsuite/dao-library';

// Your custom wallet implementation
@Injectable()
export class MyCustomWalletProvider implements IWalletProvider {
  // ... your implementation
}

@NgModule({
  imports: [
    DaoLibraryModule.forRoot({
      apiUrl: environment.smartAppUrl,
      // ... other config
    })
  ],
  providers: [
    // Override the default wallet provider
    { provide: WALLET_PROVIDER, useClass: MyCustomWalletProvider }
  ]
})
export class AppModule {}
```

## 🔌 Provider Interfaces

### IWalletProvider

```typescript
interface IWalletProvider {
  connect(): Promise<void>;
  disconnect(): Promise<void>;
  isConnected(): Promise<boolean>;
  getAccounts(): Promise<string[]>;
  getCurrentAccount(): Promise<string | null>;
  signTransaction(transaction: any): Promise<any>;
  signMessage(message: string): Promise<any>;
  onConnect(): Observable<string>;
  onDisconnect(): Observable<void>;
  onAccountChange(): Observable<string>;
}
```

### INotificationProvider

```typescript
interface INotificationProvider {
  showSuccess(message: string, duration?: number): Promise<void>;
  showError(message: string, duration?: number): Promise<void>;
  showWarning(message: string, duration?: number): Promise<void>;
  showInfo(message: string, duration?: number): Promise<void>;
  showLoading(message: string): Promise<void>;
  hideLoading(): Promise<void>;
  showModal(config: {
    title: string;
    message: string;
    buttons?: Array<{ text: string; handler?: () => void; role?: string }>;
  }): Promise<void>;
}
```

### IIpfsProvider

```typescript
interface IIpfsProvider {
  upload(file: File, metadata?: any): Promise<IpfsUploadResponse>;
  getGatewayUrl(cid: string): string;
  getCid(file: File): Promise<string>;
}
```

### IWebSocketProvider

```typescript
interface IWebSocketProvider {
  connect(url: string, accessToken?: string): void;
  disconnect(): void;
  on<T>(event: string): Observable<T>;
  emit(event: string, data: any): void;
  isConnected(): boolean;
}
```

### IApiProvider

```typescript
interface IApiProvider {
  get<T>(endpoint: string, walletId?: string): Promise<T>;
  post<T>(endpoint: string, body: any, walletId?: string): Promise<T>;
  patch<T>(endpoint: string, body: any, walletId?: string): Promise<T>;
  delete<T>(endpoint: string, walletId?: string): Promise<T>;
}
```

## ⚙️ Configuration Options

### DaoLibraryConfig

```typescript
interface DaoLibraryConfig {
  // Required
  apiUrl: string;
  
  // Optional
  ipfsGateway?: string;
  
  features?: {
    enableDashboard?: boolean;
    enableProposals?: boolean;
    enableVoting?: boolean;
    enableMembership?: boolean;
  };
  
  routing?: {
    basePath?: string;
    useHashRouting?: boolean;
    enableDeepLinking?: boolean;
  };
  
  theme?: {
    mode?: 'light' | 'dark' | 'auto';
    primaryColor?: string;
    accentColor?: string;
  };
  
  i18n?: {
    defaultLanguage?: string;
    supportedLanguages?: string[];
    translations?: { [key: string]: any };
  };
  
  debug?: boolean;
  
  analytics?: {
    enabled?: boolean;
    trackerId?: string;
  };
}
```

## 📚 Using the DAO Service

```typescript
import { Component } from '@angular/core';
import { DaoService } from '@hsuite/dao-library';

@Component({
  selector: 'app-my-component',
  template: '...'
})
export class MyComponent {
  constructor(private daoService: DaoService) {}

  async loadDaos() {
    const walletId = await this.getWalletId();
    const daos = await this.daoService.getDaos(walletId);
    console.log('DAOs:', daos);
  }

  async createDao(daoData: any) {
    const walletId = await this.getWalletId();
    const result = await this.daoService.createDao(walletId, daoData);
    console.log('DAO created:', result);
  }
}
```

## 🔔 Event System

Subscribe to real-time events:

```typescript
import { DaoService } from '@hsuite/dao-library';

export class MyComponent {
  constructor(private daoService: DaoService) {
    this.setupEventListeners();
  }

  private setupEventListeners() {
    const eventService = this.daoService.getEventService();
    
    // Listen for DAO creation progress
    eventService.onDaoCreationProgress().subscribe(event => {
      console.log('DAO Creation Progress:', event);
    });
    
    // Listen for DAO creation completed
    eventService.onDaoCreationCompleted().subscribe(event => {
      console.log('DAO Created:', event);
    });
    
    // Listen for errors
    eventService.onDaoCreationError().subscribe(event => {
      console.error('DAO Creation Error:', event);
    });
  }
}
```

## 🏗️ Architecture

### Provider Pattern

The library uses a provider pattern to decouple from specific implementations:

```
┌─────────────────────────────────────────────────┐
│    @hsuite/dao-library (Library)               │
│  ┌──────────────────────────────────────────┐  │
│  │  Uses Interface Abstractions             │  │
│  │  - IWalletProvider                        │  │
│  │  - INotificationProvider                  │  │
│  │  - IIpfsProvider                          │  │
│  │  - IWebSocketProvider                     │  │
│  │  - IApiProvider                           │  │
│  └──────────────────────────────────────────┘  │
└─────────────────────────────────────────────────┘
                    ↓
        ┌───────────┴───────────────┐
        ↓                           ↓
┌──────────────────┐      ┌──────────────────┐
│ Shell App        │      │   Wallet App     │
│                  │      │                  │
│ Provides:        │      │ Provides:        │
│ - WalletConnect  │      │ - Native Wallet  │
│ - Ionic Notif.   │      │ - Custom Notif.  │
│ - IPFS Gateway   │      │ - IPFS Gateway   │
└──────────────────┘      └──────────────────┘
```

## 📖 API Reference

### DaoService

#### DAO Management
- `createDao(walletId: string, dao: any): Promise<any>`
- `getDaos(walletId: string): Promise<any[]>`
- `getDaosByOwner(walletId: string, ownerAddress: string): Promise<any[]>`
- `getDaoByTokenId(walletId: string, tokenId: string): Promise<any>`
- `getDaosByMember(walletId: string, memberAddress: string): Promise<any[]>`

#### Proposal Management
- `createProposal(walletId: string, daoRefId: string, proposal: any): Promise<any>`
- `getDaoProposals(walletId: string, daoRefId: string): Promise<any[]>`
- `getProposal(walletId: string, proposalRefId: string): Promise<any>`
- `getSupportedProposalActions(walletId: string): Promise<any>`

#### Voting
- `castVote(walletId: string, voteData: any): Promise<any>`
- `getProposalVotes(walletId: string, proposalRefId: string): Promise<any[]>`
- `getProposalVoteCounts(walletId: string, proposalRefId: string): Promise<any>`
- `getVoterVote(walletId: string, proposalRefId: string, voterAddress: string): Promise<any>`

#### Membership
- `addMember(walletId: string, daoRefId: string, memberAddress: string): Promise<any>`
- `getMemberNftStatus(walletId: string, daoRefId: string, memberAddress: string): Promise<any>`
- `claimMemberNft(walletId: string, daoRefId: string, memberAddress: string): Promise<any>`

#### Dashboard
- `getDashboardStats(walletId: string, userAddress: string): Promise<any>`
- `getActiveProposalsForUser(walletId: string, userAddress: string): Promise<any[]>`
- `getUserVoteHistory(walletId: string, userAddress: string): Promise<any>`
- `getUserActivityFeed(walletId: string, userAddress: string): Promise<any[]>`
- `getPendingActionsForUser(walletId: string, userAddress: string): Promise<any>`
- `getGovernanceImpact(walletId: string, userAddress: string): Promise<any>`

### VoteCalculationsService

- `getVoteCountForOption(option: string, votes: any[], dao: any, snapshot: any): number`
- `getVotePercentageForOption(option: string, votes: any[], dao: any, voteCounts: any): number`
- `isQuorumReached(votes: any[], snapshot: any, dao: any, proposal: any): boolean`
- `getQuorumPercentage(votes: any[], snapshot: any, dao: any, proposal: any): number`
- `isProposalPassed(votes: any[], votingOptions: any[], dao: any, snapshot: any): boolean`

## 🤝 Contributing

This library is part of the HSuite ecosystem. For contribution guidelines, please refer to the main HSuite repository.

## 📄 License

MIT License - see LICENSE file for details

## 🔗 Links

- [HSuite Documentation](https://docs.hsuite.finance/)
- [GitHub Repository](https://github.com/hsuite/dao-library)

## 🆘 Support

For support and questions:
- Join our [Discord](https://discord.gg/ycjWvV59Cg)
- Follow us on [Twitter/X](https://x.com/HSuiteNetwork)

---

**Version**: 1.0.1  
**Status**: ✅ **Production Ready** (100% Independent)  
**Last Updated**: 2025-11-17