npm package: @livylabs/sdk
Description: TypeScript SDK for executing livy services with attestation verification
Author: Livy Labs
Latest version: 0.0.5

# Livy Labs SDK for JavaScript/TypeScript

A TypeScript SDK for executing services on remote servers with built-in authentication and attestation verification capabilities.

## Installation

```bash
npm install @livylabs/sdk
```

## Quick Start

```typescript
import { createClient } from '@livylabs/sdk';

// Create a client
const client = createClient({
  apiKey: 'your-api-key'
});

// Execute a service and get an attestation
const result = await client.run({
  serviceId: 'f8577eaf-8a57-4c30-b5ed-9e74bd56f964',
  params: {
    input: 'hello world',
    operation: 'process'
  },
  withAttestation: true,
  postToDataAvailability: false
});

// Verify the attestation
const isValid = await result.verifyAttestation();
console.log('Attestation valid:', isValid);
```

## Configuration

### SDKConfig

```typescript
interface SDKConfig {
  apiKey: string;          // Required: Your API key
  baseUrl?: string;        // Optional: API base URL (default: https://console.livylabs.xyz/api/proxy)
  timeout?: number;        // Optional: Request timeout in ms (default: 30000)
  retries?: number;        // Optional: Number of retries (default: 3)
  userId?: string;         // Optional: User ID for proxy requests
}
```

## API Reference

### createClient(config: SDKConfig): Client

Creates an authenticated client instance.

```typescript
const client = createClient({
  apiKey: 'your-api-key',
  baseUrl: 'https://custom-proxy.com/api',
  timeout: 10000,
  retries: 5
});
```

### client.run(params: RunParams): Promise<AttestationResult>

Executes a service and returns a result with optional attestation.

```typescript
const result = await client.run({
  serviceId: 'f8577eaf-8a57-4c30-b5ed-9e74bd56f964',
  params: {
    dataset: 'users.csv',
    operation: 'aggregate'
  },
  withAttestation: true,
  postToDataAvailability: false
});
```

### RunParams

Parameters for executing a service:

```typescript
interface RunParams {
  serviceId: string;                    // Unique identifier for the service to execute
  params?: Record<string, any>;         // Key-value pairs of parameters (optional)
  withAttestation?: boolean;            // Whether to generate attestation (default: true)
  postToDataAvailability?: boolean;     // Whether to post to data availability layer (default: false)
}
```

### AttestationResult

The result object contains execution data and verification methods:

```typescript
interface AttestationResult {
  status: string;                       // Status of the execution
  output: any;                         // The output from the service execution
  quote?: {                            // Cryptographic attestation data (if withAttestation was true)
    quote: string;                     // Base64-encoded attestation quote
    eventLog: string;                  // Event log entries
    rtmrs: string[];                   // Runtime Measurement Registers (4 RTMRs)
  };
  serviceId: string;                   // The service that was executed
  params: Record<string, any>;         // Parameters that were passed to the service
  withAttestation: boolean;            // Whether attestation was generated
  postedToDataAvailability: boolean;   // Whether data was posted to DA layer
  verifyAttestation(): Promise<boolean>; // Verify attestation integrity
}
```

## Error Handling

All errors extend `SDKError` with structured error codes:

```typescript
import { SDKError } from '@livylabs/sdk';

try {
  const result = await client.run({...});
} catch (error) {
  if (error instanceof SDKError) {
    console.error(`Error ${error.code}: ${error.message}`);
    
    switch (error.code) {
      case 'INVALID_API_KEY':
        // Handle authentication error
        break;
      case 'SERVICE_NOT_FOUND':
        // Handle missing service
        break;
      case 'TIMEOUT_ERROR':
        // Handle timeout
        break;
      // ... other error codes
    }
  }
}
```

### Error Codes

- `INVALID_API_KEY`: Authentication failed
- `SERVICE_NOT_FOUND`: Service doesn't exist
- `INVALID_PARAMS`: Malformed parameters
- `ATTESTATION_FAILED`: Server attestation error
- `VERIFICATION_FAILED`: Attestation verification failed
- `NETWORK_ERROR`: Network/HTTP error
- `TIMEOUT_ERROR`: Request timeout

## Examples

### Basic Usage

```typescript
import { createClient } from '@livylabs/sdk';

async function main() {
  const client = createClient({
    apiKey: process.env.LIVY_API_KEY!
  });

  try {
    const result = await client.run({
      serviceId: 'secure-computation-service',
      params: {
        data: [1, 2, 3, 4, 5],
        operation: 'sum'
      },
      withAttestation: true,
      postToDataAvailability: false
    });

    console.log('Execution status:', result.status);
    console.log('Output:', result.output);
    
    if (result.withAttestation) {
      const verified = await result.verifyAttestation();
      if (verified) {
        console.log('✅ Attestation verified successfully');
      } else {
        console.log('❌ Attestation verification failed');
      }
    }
  } catch (error) {
    console.error('Error:', error);
  }
}

main();
```

### With Custom Configuration

```typescript
const client = createClient({
  apiKey: 'your-api-key',
  baseUrl: 'https://custom-proxy.livylabs.xyz/api/proxy',
  timeout: 60000,  // 1 minute timeout
  retries: 5       // Retry up to 5 times
});
```

### Without Parameters

```typescript
// Some services don't require parameters
const result = await client.run({
  serviceId: 'status-check-service',
  withAttestation: false
});
```

### Error Handling Example

```typescript
import { createClient, SDKError } from '@livylabs/sdk';

async function robustExecution() {
  const client = createClient({
    apiKey: process.env.LIVY_API_KEY!
  });

  try {
    const result = await client.run({
      serviceId: 'data-analysis-service',
      params: { 
        dataset: 'large-dataset.csv',
        algorithm: 'ml-model-v2'
      },
      withAttestation: true,
      postToDataAvailability: true
    });

    // Always verify attestations in production
    if (result.withAttestation && await result.verifyAttestation()) {
      return result;
    } else if (result.withAttestation) {
      throw new Error('Attestation verification failed');
    }
    
    return result;
  } catch (error) {
    if (error instanceof SDKError) {
      switch (error.code) {
        case 'INVALID_API_KEY':
          console.error('Check your API key configuration');
          break;
        case 'SERVICE_NOT_FOUND':
          console.error('Service ID does not exist');
          break;
        case 'TIMEOUT_ERROR':
          console.error('Request timed out, try again later');
          break;
        case 'NETWORK_ERROR':
          console.error('Network issue:', error.message);
          break;
        default:
          console.error('SDK Error:', error.message);
      }
    } else {
      console.error('Unexpected error:', error);
    }
    throw error;
  }
}
```

## Development

### Building

```bash
npm run build
```

### Testing

```bash
npm test
```

### Linting

```bash
npm run lint
```

## Requirements

- Node.js 18.0.0 or higher
- TypeScript 5.0+ (for development)

## Security

- API keys should be stored securely (environment variables, secret managers)
- Never commit API keys to version control
- Always verify attestations before trusting results
- All requests use HTTPS for transport security

## License

MIT

## Support

For support and documentation, visit [https://docs.livylabs.xyz](https://docs.livylabs.xyz)