npm package: @hirosystems/chainhooks-client
Description: TypeScript client and type definitions for the Chainhooks API
Author: Hiro Systems
Latest version: 2.1.1

# @hirosystems/chainhooks-client

A TypeScript client for the Chainhooks API with full type safety and comprehensive schema definitions.

## Features

- 🚀 **Full TypeScript Support** - Complete type safety using TypeBox schemas
- 🔐 **Authentication** - Built-in API key and JWT support
- 📚 **Schema Export** - Access to all Chainhook schemas and types
- 🎯 **Modern API** - Promise-based async/await interface
- 🛡️ **Error Handling** - Comprehensive error handling with meaningful messages
- 🌐 **HTTP Client** - Uses undici for high-performance HTTP requests
- 🏗️ **Built-in URLs** - Pre-configured URLs for mainnet and testnet

## Installation

```bash
npm install @hirosystems/chainhooks-client
```

**Note:** This package uses [undici](https://github.com/nodejs/undici) as its HTTP client, which provides high-performance HTTP/1.1 and HTTP/2 support. It's automatically installed as a dependency.

## Quick Start

```typescript
import { ChainhooksClient, ChainhookDefinition } from '@hirosystems/chainhooks-client';

// Initialize the client
const client = new ChainhooksClient({
  baseUrl: 'https://api.mainnet.hiro.so',
  apiKey: 'your-api-key-here',
});

// Register a new chainhook
const chainhook: ChainhookDefinition = {
  name: 'My Stacks Chainhook',
  chain: 'stacks',
  network: 'mainnet',
  filters: {
    // Your filters here
  },
  options: {
    start_at_block_height: 1000000,
  },
  action: {
    // Your action configuration
  },
};

try {
  const result = await client.registerChainhook(chainhook);
  console.log('Chainhook registered:', result.uuid);
} catch (error) {
  console.error('Failed to register chainhook:', error.message);
}
```

## Pre-configured URLs

The client provides pre-configured URLs for convenience:

```typescript
import { CHAINHOOKS_BASE_URL } from '@hirosystems/chainhooks-client';

const client = new ChainhooksClient({
  baseUrl: CHAINHOOKS_BASE_URL.mainnet,  // https://api.mainnet.hiro.so
  apiKey: 'your-api-key',
});

// Or for testnet
const testnetClient = new ChainhooksClient({
  baseUrl: CHAINHOOKS_BASE_URL.testnet,  // https://api.testnet.hiro.so
  apiKey: 'your-api-key',
});
```

## API Methods

### Chainhook Management

#### `registerChainhook(definition: ChainhookDefinition): Promise<Chainhook>`
Register a new chainhook with the API.

#### `getChainhooks(options?: PaginationOptions): Promise<PaginatedChainhookResponse>`
Retrieve all chainhooks with optional pagination.

```typescript
// Get first 20 chainhooks
const chainhooks = await client.getChainhooks({ limit: 20, offset: 0 });

// Get next page
const nextPage = await client.getChainhooks({ limit: 20, offset: 20 });
```

#### `getChainhook(uuid: string): Promise<Chainhook>`
Retrieve a specific chainhook by its UUID.

#### `enableChainhook(uuid: string, enabled: boolean): Promise<void>`
Enable or disable a chainhook by its UUID.

#### `deleteChainhook(uuid: string): Promise<void>`
Delete a chainhook by its UUID.

### API Status

#### `getStatus(): Promise<ApiStatusResponse>`
Check the API status and version information.

## Configuration

The client accepts the following configuration options:

```typescript
interface ChainhooksClientConfig {
  baseUrl: string;           // Required: API base URL
  apiKey?: string;           // Optional: API key for authentication
  jwt?: string;              // Optional: JWT token for authentication
}
```

**Note:** You can use either `apiKey` or `jwt` for authentication, or both if needed.

## Schema Types

All Chainhook schemas are exported for use in your application:

```typescript
import {
  Chainhook,
  ChainhookDefinition,
  ChainhookStatus,
  ChainhookNetwork,
  PaginatedChainhookResponse,
  ApiStatusResponse,
  // ... and many more
} from '@hirosystems/chainhooks-client';
```

## Pagination

The client supports pagination for list operations:

```typescript
interface PaginationOptions {
  offset?: number;  // Starting position (default: 0)
  limit?: number;   // Number of results (default: 20, max: 60)
}
```

## Examples

### Complete Workflow

```typescript
import { ChainhooksClient, CHAINHOOKS_BASE_URL } from '@hirosystems/chainhooks-client';

const client = new ChainhooksClient({
  baseUrl: CHAINHOOKS_BASE_URL.mainnet,
  apiKey: process.env.CHAINHOOKS_API_KEY,
});

async function manageChainhooks() {
  try {
    // Check API status
    const status = await client.getStatus();
    console.log('API Status:', status.status);
    console.log('Server Version:', status.server_version);

    // List all chainhooks
    const { results, total } = await client.getChainhooks({ limit: 50 });
    console.log(`Found ${total} chainhooks`);

    // Get details of first chainhook
    if (results.length > 0) {
      const firstChainhook = await client.getChainhook(results[0].uuid);
      console.log('First chainhook:', firstChainhook.definition.name);
    }

  } catch (error) {
    console.error('Error managing chainhooks:', error.message);
  }
}
```

### Using JWT Authentication

```typescript
const client = new ChainhooksClient({
  baseUrl: CHAINHOOKS_BASE_URL.mainnet,
  jwt: 'your-jwt-token-here',
});

try {
  const result = await client.registerChainhook(chainhookDefinition);
  console.log('Success:', result.uuid);
} catch (error) {
  console.error('Failed:', error.message);
}
```

### Error Handling

```typescript
const client = new ChainhooksClient({
  baseUrl: CHAINHOOKS_BASE_URL.mainnet,
  apiKey: 'your-key',
});

try {
  const result = await client.registerChainhook(chainhookDefinition);
  console.log('Success:', result.uuid);
} catch (error) {
  console.error('Failed:', error.message);
}
```

## TypeScript Support

This package is written in TypeScript and provides full type definitions. All API methods, request/response types, and configuration interfaces are fully typed.

## Contributing

Contributions are welcome! Please ensure all changes maintain type safety and include appropriate tests.

## License

Apache-2.0