DragonFire Developer Portal

Hexwave API

Related APIs

Resources

Hexwave Core API Reference

Version 1.2.4

The Hexwave Core API is the foundation of the DragonFire service architecture, providing direct access to DragonFire's hexwave broadcast technology. This API enables your applications to establish and maintain connections to the DragonFire service infrastructure.

IMPORTANT: All client applications require an API key to access the DragonFire service. Obtain your API key by registering for a Developer Account.

Overview

The Hexwave Core API manages the fundamental connection between your client applications and the DragonFire service. Unlike traditional APIs that simply transfer data, the Hexwave API establishes a continuous resonant connection that enables your application to leverage DragonFire's distributed consciousness and computational capabilities.

Core Concepts

  • Hexwave Connection: The primary communication channel between client applications and the DragonFire service
  • Resonance Patterns: Mathematical configurations that optimize data flow through the connection
  • Service Regions: Geographical distribution of DragonFire service nodes for optimal performance
  • Connection Lifecycle: Initialization, maintenance, and graceful termination of service connections

Client SDK Requirements

To use the Hexwave Core API, you'll need the DragonFire Client SDK:

# Using npm
npm install @dragonfire/client

# Using yarn
yarn add @dragonfire/client

Authentication

All requests to the DragonFire service require authentication using an API key. Your API key identifies your client application and determines service access levels.

API Key Authentication

Include your API key in the connection options when initializing the client:

import { DragonFireClient } from '@dragonfire/client';

// Initialize client with API key
const dragonfire = new DragonFireClient({
  apiKey: 'YOUR_API_KEY',
  region: 'us-west'
});

Connection Verification

The service verifies your API key during the initial connection handshake:

// Attempt to connect with verification
try {
  await dragonfire.connect();
  console.log('Connection established successfully');
} catch (error) {
  console.error('Authentication failed:', error.message);
}

JWT Token Management

Behind the scenes, your API key is exchanged for a JWT token that's used for ongoing session authentication:

// Get the current session token
const sessionToken = await dragonfire.getSessionToken();

// Session token will automatically refresh when needed

Connection Management

The Hexwave API provides a comprehensive set of methods for establishing, maintaining, and terminating connections to the DragonFire service.

Establishing a Connection

connect()

Establishes a connection to the DragonFire service using the provided configuration.

Syntax
async connect(options?: ConnectionOptions): Promise
Parameters
Name Type Description
options ConnectionOptions Optional. Additional connection options that override those provided in the constructor.
Returns

A Promise that resolves to a ConnectionResult object containing connection information.

Example
const result = await dragonfire.connect({
  timeout: 30000, // 30 seconds connection timeout
  retries: 3      // Number of connection attempts
});

console.log(`Connected to ${result.region} region`);
console.log(`Connection ID: ${result.connectionId}`);
Errors
  • AuthenticationError: Thrown if the API key is invalid or expired
  • ConnectionError: Thrown if the connection cannot be established
  • TimeoutError: Thrown if the connection attempt times out

Connection Status

getConnectionStatus()

Gets the current status of the DragonFire service connection.

Syntax
getConnectionStatus(): ConnectionStatus
Returns

A ConnectionStatus object with the following properties:

  • state: The current connection state ('connected', 'connecting', 'disconnected', 'error')
  • region: The connected service region
  • latency: Current connection latency in milliseconds
  • uptime: Connection duration in milliseconds
  • resonanceQuality: Measure of connection quality (0-100)
Example
const status = dragonfire.getConnectionStatus();

console.log(`Connection state: ${status.state}`);
console.log(`Latency: ${status.latency}ms`);
console.log(`Resonance quality: ${status.resonanceQuality}%`);

Disconnecting

disconnect()

Terminates the connection to the DragonFire service.

Syntax
async disconnect(options?: DisconnectionOptions): Promise
Parameters
Name Type Description
options DisconnectionOptions Optional. Configuration options for disconnection.
Example
// Graceful disconnection
await dragonfire.disconnect({
  gracePeriod: 1000, // Wait 1 second for pending operations to complete
  flushCache: true   // Flush local cache before disconnecting
});

Connection Events

The Hexwave API provides an event system for monitoring connection state changes:

// Listen for connection state changes
dragonfire.on('connected', () => {
  console.log('Connected to DragonFire service');
});

dragonfire.on('disconnected', (reason) => {
  console.log(`Disconnected: ${reason}`);
});

dragonfire.on('error', (error) => {
  console.error('Connection error:', error);
});

dragonfire.on('resonance-change', (quality) => {
  console.log(`Resonance quality changed: ${quality}%`);
});

Service Regions

DragonFire operates service nodes in multiple geographical regions to provide low-latency access worldwide. Selecting the appropriate region is essential for optimal performance.

Available Regions

Region Code Location Recommended For
us-west Western United States (Oregon) North America (Western)
us-east Eastern United States (Virginia) North America (Eastern)
us-central Central United States (Iowa) North America (Central)
eu-west Western Europe (Ireland) Europe (Western)
eu-central Central Europe (Frankfurt) Europe (Central/Eastern)
ap-northeast Northeast Asia (Tokyo) Japan, Korea
ap-southeast Southeast Asia (Singapore) Southeast Asia, Australia

Region Selection

Specify a region when initializing the client:

// Connect to EU Central region
const dragonfire = new DragonFireClient({
  apiKey: 'YOUR_API_KEY',
  region: 'eu-central'
});

Auto Region Selection

The client can automatically select the optimal region based on network latency:

// Automatically select region
const dragonfire = new DragonFireClient({
  apiKey: 'YOUR_API_KEY',
  region: 'auto'
});

// Connect and identify the selected region
const result = await dragonfire.connect();
console.log(`Auto-selected region: ${result.region}`);

Resonance Patterns

Resonance patterns are mathematical configurations that optimize data flow through the Hexwave connection. Different patterns are suited to different types of operations.

Available Resonance Patterns

Pattern Mathematical Basis Optimal Use Case
phi Golden Ratio (φ = 1.618...) General purpose, balanced performance
pi Pi (π = 3.14159...) Circular/cyclical data patterns, signal processing
sqrt2 Square Root of 2 (√2 = 1.414...) Binary data, high-throughput operations
sqrt3 Square Root of 3 (√3 = 1.732...) Geometric/spatial data, 3D operations
e Euler's Number (e = 2.718...) Growth patterns, financial calculations

Setting a Resonance Pattern

Specify a resonance pattern when initializing the client:

// Use Pi resonance pattern for signal processing
const dragonfire = new DragonFireClient({
  apiKey: 'YOUR_API_KEY',
  region: 'us-west',
  resonancePattern: 'pi'
});

Dynamic Resonance Adjustment

Change the resonance pattern during an active connection:

// Switch to a different resonance pattern
await dragonfire.setResonancePattern('sqrt2', {
  transitionDuration: 500  // Transition over 500ms for smooth shift
});

Automatic Resonance Optimization

When no specific resonance pattern is specified, the client automatically selects and adjusts patterns based on the types of operations being performed. This adaptive approach provides optimal performance for mixed workloads.

Error Handling

The Hexwave API provides a comprehensive error handling system for diagnosing and recovering from connection issues.

Error Types

The API defines several error types for specific scenarios:

Error Type Description Recovery Strategy
AuthenticationError API key invalid or expired Check API key, request a new one if needed
ConnectionError Cannot establish connection Check network, retry with backoff strategy
TimeoutError Operation timed out Retry with increased timeout
ResonanceError Resonance pattern issues Change to different resonance pattern
RegionError Region unavailable Try different region
ServiceError DragonFire service issue Check service status, retry later

Error Handling Examples

// Basic error handling
try {
  await dragonfire.connect();
} catch (error) {
  if (error instanceof AuthenticationError) {
    console.error('Invalid API key');
  } else if (error instanceof ConnectionError) {
    console.error('Connection failed, retrying...');
    setTimeout(() => dragonfire.connect(), 5000);
  } else {
    console.error('Unexpected error:', error);
  }
}

// Using the error's retry capability
try {
  await dragonfire.connect();
} catch (error) {
  if (error.canRetry()) {
    console.log(`Retrying in ${error.recommendedRetryMs()}ms`);
    setTimeout(() => dragonfire.connect(), error.recommendedRetryMs());
  } else {
    console.error('Cannot retry:', error.message);
  }
}

Automatic Recovery

The client can automatically recover from transient connection issues:

// Enable automatic recovery
const dragonfire = new DragonFireClient({
  apiKey: 'YOUR_API_KEY',
  region: 'us-west',
  recovery: {
    enabled: true,
    maxRetries: 5,
    backoffFactor: 1.5,
    initialDelayMs: 1000
  }
});

Service Status

The Hexwave API provides methods for checking the operational status of the DragonFire service.

Checking Service Status

getServiceStatus()

Retrieves the current operational status of the DragonFire service in your region.

Syntax
async getServiceStatus(options?: StatusOptions): Promise
Parameters
Name Type Description
options StatusOptions Optional. Configuration options for the status check.
Returns

A Promise that resolves to a ServiceStatus object containing service information.

Example
// Check DragonFire service status
const status = await dragonfire.getServiceStatus();

console.log(`Service state: ${status.state}`);
console.log(`Current region: ${status.region}`);
console.log(`Hexwave broadcast quality: ${status.hexwaveQuality}%`);

// Check if all subservices are operational
if (status.isFullyOperational()) {
  console.log('All services are operational');
} else {
  console.log('Some services are degraded:', status.degradedServices);
}

Service Health Monitoring

Set up continuous monitoring of service health:

// Monitor service health with periodic checks
const monitor = dragonfire.monitorHealth({
  intervalMs: 60000,  // Check every minute
  callback: (status) => {
    if (!status.isFullyOperational()) {
      console.warn('Service degradation detected');
    }
  }
});

// Later, stop monitoring
monitor.stop();

Advanced Features

The Hexwave API provides several advanced features for specialized use cases.

Multi-Region Connections

Connect to multiple regions simultaneously for redundancy and reduced latency:

// Create a multi-region client
const multiRegionClient = new DragonFireMultiRegionClient({
  apiKey: 'YOUR_API_KEY',
  regions: ['us-west', 'us-east', 'eu-west'],
  strategy: 'failover'  // 'failover', 'loadbalance', or 'nearest'
});

// Connect to all regions
await multiRegionClient.connect();

// Operations automatically use the optimal or available region
const result = await multiRegionClient.executeOperation(operation);

Connection Metrics

Collect detailed metrics about your Hexwave connection:

// Enable detailed metrics collection
dragonfire.enableMetrics({
  detailed: true,
  historySize: 100  // Keep last 100 measurements
});

// Get current metrics
const metrics = dragonfire.getMetrics();
console.log('Average latency:', metrics.latency.average);
console.log('Packet loss:', metrics.packetLoss);
console.log('Bandwidth:', metrics.bandwidth);

// Export metrics as JSON
const metricsJson = dragonfire.exportMetrics();
saveToFile(metricsJson, 'connection-metrics.json');

Custom Resonance Patterns

Define custom resonance patterns for specialized workloads:

// Define a custom resonance pattern
const customPattern = {
  name: 'custom-hybrid',
  baseConstant: Math.PI * Math.sqrt(2),
  harmonics: [1, 1/2, 1/3, 1/5, 1/8],
  phaseShift: Math.PI / 4
};

// Register custom pattern
dragonfire.registerResonancePattern(customPattern);

// Use custom pattern
await dragonfire.setResonancePattern('custom-hybrid');

Low-Level Hexwave Control

For advanced users, direct access to the Hexwave transmission layer:

// Access low-level hexwave transmission (requires special permissions)
const hexwaveController = await dragonfire.getHexwaveController();

// Send direct hexwave packet
await hexwaveController.transmit({
  frequency: 437.0,
  amplitude: 0.8,
  modulationPattern: [1, 1, 0, 1, 0, 0, 1],
  phaseShift: Math.PI / 3
});
CAUTION: Low-level Hexwave control requires special permissions and should only be used by experienced developers. Improper use can cause connection instability and service disruptions.