npm package: @hauska-sdk/core
Description: CNS Protocol Core SDK - Unified SDK for Payment, VDA, and Document Retrieval
Author: Hauska SDK Team
Latest version: 0.1.0

# @hauska-sdk/core

**CNS Protocol Core SDK** - Unified SDK for Payment, VDA, and Document Retrieval

The CNS Protocol Core SDK provides a single, unified interface for all CNS Protocol functionality, combining Payment, VDA (Verified Digital Assets), Document Retrieval, and Wallet Management into one easy-to-use package.

## Installation

```bash
npm install @hauska-sdk/core
```

## Quick Start

```typescript
import { CNSSDK } from "@hauska-sdk/core";
import { PostgreSQLStorageAdapter } from "@hauska-sdk/adapters-storage-postgres";

// Initialize SDK
const sdk = new CNSSDK({
  vda: {
    storageAdapter: new PostgreSQLStorageAdapter({
      connectionString: process.env.DATABASE_URL!,
    }),
  },
  payment: {
    storage: new PostgreSQLStorageAdapter({
      connectionString: process.env.DATABASE_URL!,
    }),
    blockchain: {
      chain: "base",
      token: "USDC",
      facilitatorWallet: "0xYourFacilitatorWallet",
      baseRpcUrl: "https://mainnet.base.org",
    },
  },
  retrieval: {
    pinata: {
      pinataJwt: process.env.PINATA_JWT!,
      pinataGateway: "https://gateway.pinata.cloud",
    },
  },
});

// Create a data room with document
const dataRoom = await sdk.createDataRoom({
  ownerWallet: {
    userId: "owner-123",
    password: "secure-password",
  },
  vdaParams: {
    assetType: "deed",
    address: "123 Main St, Schertz, TX 78154",
    spoke: "real-estate",
  },
  document: {
    content: Buffer.from("Property documents..."),
    name: "property-deed.pdf",
    encrypt: true,
  },
  accessPass: {
    recipientWallet: {
      userId: "buyer-456",
      password: "buyer-password",
    },
    permissions: ["view", "download"],
    expiry: Date.now() + 30 * 24 * 3600000, // 30 days
  },
});

console.log(`Data room created: ${dataRoom.vda.id}`);
console.log(`Document uploaded: ${dataRoom.document?.cid}`);
```

## Features

### 🎯 Unified API
- Single entry point for all CNS Protocol functionality
- Automatic wallet management
- Seamless integration between Payment, VDA, and Retrieval modules

### 💰 Payment Processing
- HTTP 402 Payment Required protocol (x402)
- Crypto payment verification (USDC on Base L2)
- Fiat payment support (via Circle API)
- Automatic payment recording and audit trails

### 🏷️ VDA Management
- Mint Verified Digital Assets (metadata-only ownership proofs)
- Create and manage access passes
- Transfer ownership
- Cross-spoke search (real-estate, healthcare, architect, etc.)

### 📄 Document Retrieval
- IPFS document upload/download via Pinata
- AES-256-GCM encryption
- Gated access control (VDA ownership or access passes)
- PDF watermarking for access pass viewers
- Access logging and analytics

### 🔐 Wallet Management
- Automatic wallet creation per user
- Secure wallet encryption
- EIP-712 signing support

## Core Concepts

### Verified Digital Assets (VDAs)
VDAs are metadata-only ownership proofs, not tokens or NFTs. They represent ownership of real-world assets (properties, medical records, blueprints, etc.) without tokenization.

### Access Passes
Time-bound VDAs that grant temporary, permissioned access to other VDAs. Perfect for data rooms, medical record sharing, and document collaboration.

### Spokes
Industry verticals (e.g., `real-estate`, `healthcare`, `architect`). Each spoke can have its own metadata schema while sharing universal metadata keys (`address`, `legalDesc`, `patientId`, `api14`).

### Universal Metadata
Standardized metadata keys that enable cross-spoke search:
- `address` - Physical address (real estate)
- `legalDesc` - Legal description (real estate)
- `patientId` - Patient identifier (healthcare)
- `api14` - API 14 identifier (oil & gas)

## Documentation

- [Getting Started Guide](./docs/getting-started.md) - Step-by-step setup and first steps
- [API Reference](./docs/api-reference.md) - Complete API documentation
- [Examples](./docs/examples.md) - Real-world usage examples
- [Troubleshooting](./docs/troubleshooting.md) - Common issues and solutions

## Examples

### Architect Invoice Flow
```typescript
import { architectInvoiceFlow } from "@hauska-sdk/core/examples/architect-invoice-flow";

// Complete flow: Create invoice → Payment → Transfer blueprint
const result = await architectInvoiceFlow();
```

### Data Room Creation
```typescript
// Create a data room with encrypted documents
const dataRoom = await sdk.createDataRoom({
  ownerWallet: { userId: "owner", password: "pass" },
  vdaParams: {
    assetType: "deed",
    address: "123 Main St",
    spoke: "real-estate",
  },
  document: {
    content: Buffer.from("..."),
    encrypt: true,
  },
});
```

### Purchase and Mint VDA
```typescript
// Purchase and mint a VDA in a single operation
const result = await sdk.purchaseAndMintVDA({
  wallet: { userId: "user", password: "pass" },
  amount: "5000",
  currency: "USDC",
  method: "crypto",
  vdaParams: {
    assetType: "blueprint",
    address: "123 Main St",
    spoke: "architect",
  },
});
```

See [Examples Guide](./docs/examples.md) for more complete examples.

## Error Handling

The SDK uses structured error types for better error handling:

```typescript
import {
  SDKError,
  PaymentError,
  VDAError,
  RetrievalError,
  WalletError,
  ConfigurationError,
  isSDKError,
  isRetryableError,
} from "@hauska-sdk/core";

try {
  await sdk.purchaseAndMintVDA({ /* ... */ });
} catch (error) {
  if (isSDKError(error)) {
    console.error(`Error code: ${error.code}`);
    console.error(`Context:`, error.context);
    
    if (isRetryableError(error)) {
      // Retry logic
    }
  }
}
```

See [Error Handling](./docs/api-reference.md#error-handling) for more details.

## Logging and Monitoring

The SDK supports logging and metrics hooks for monitoring:

```typescript
const sdk = new CNSSDK({
  // ... config
  logHook: (level, message, data) => {
    console.log(`[${level}] ${message}`, data);
  },
  metricsHook: (event, data) => {
    // Send to your analytics service
    analytics.track(event, data);
  },
});
```

## Adapters

The SDK uses adapters for storage, blockchain, and IPFS:

### Storage Adapters
- `@hauska-sdk/adapters-storage-postgres` - PostgreSQL (production)
- `@hauska-sdk/adapters-storage-redis` - Redis caching layer
- `@hauska-sdk/adapters-storage-mock` - In-memory (testing)

### Blockchain Adapters
- `@hauska-sdk/adapters-blockchain-ethers` - Ethers.js (Base L2)

### IPFS Adapters
- Pinata (via `@hauska-sdk/retrieval`)

## Requirements

- Node.js 18+
- TypeScript 5.3+
- PostgreSQL (for production storage)
- Pinata account (for IPFS storage)
- Base L2 RPC endpoint (for blockchain operations)

## License

MIT

## Related Packages

- [`@hauska-sdk/payment`](../payment/README.md) - Payment SDK
- [`@hauska-sdk/vda`](../vda/README.md) - VDA SDK
- [`@hauska-sdk/retrieval`](../retrieval/README.md) - Retrieval SDK
- [`@hauska-sdk/wallet`](../wallet/README.md) - Wallet Management

## Support

- [GitHub Issues](https://github.com/hauska-sdk/issues)
- [Documentation](https://docs.hauska-sdk.com)
- [Discord](https://discord.gg/hauska-sdk)