# Examples

## Examples (SDK vNext)

Looking to integrate with Treza using the **new SDK**? This page shows end‑to‑end examples: initializing the client, selecting a provider, creating enclaves, managing lifecycle, fetching logs, working with scheduled tasks, API keys, Docker Hub helpers, and GitHub OAuth—using real, copy‑pasteable snippets.

{% hint style="info" %}
All snippets are TypeScript-first and work in Node 18+. See the `/examples` folder of `treza-labs/treza-sdk` for runnable files.
{% endhint %}

***

### Installation

```bash
npm install @treza/sdk
```

### Quick Start

```ts
import { TrezaClient } from '@treza/sdk';

const client = new TrezaClient({
  baseUrl: process.env.TREZA_BASE_URL ?? 'https://app.trezalabs.com',
  timeout: 30_000,
});

const WALLET = process.env.WALLET_ADDRESS!; // e.g. '0x4B0897b0513fdc7C541B6d9D7E929C4e5364D2dB'

async function main() {
  // 1) Discover providers
  const providers = await client.getProviders();
  const provider = providers[0];
  console.log('Using provider:', provider.name, provider.id);

  // 2) Create an enclave
  const enclave = await client.createEnclave({
    name: 'My Trading Bot',
    description: 'Secure environment for trading algorithms',
    region: provider.regions[0] ?? 'us-east-1',
    walletAddress: WALLET,
    providerId: provider.id,
    providerConfig: {
      dockerImage: 'trading-bot:latest',
      cpuCount: 2,
      memoryMiB: 512,
    },
  });

  console.log('Enclave created:', enclave.id, 'status:', enclave.status);

  // 3) Get logs (application-only)
  const appLogs = await client.getEnclaveLogs(enclave.id, 'application', 50);
  console.log('Application log entries:', (appLogs.logs.application ?? []).length);

  // 4) Pause → Resume lifecycle
  const paused = await client.pauseEnclave(enclave.id, WALLET);
  console.log('Paused →', paused.enclave.status);

  const resumed = await client.resumeEnclave(enclave.id, WALLET);
  console.log('Resumed →', resumed.enclave.status);
}

main().catch((e) => {
  console.error(e);
  process.exit(1);
});
```

{% hint style="info" %}
Set these before running examples:
{% endhint %}

```bash
export TREZA_BASE_URL=https://app.trezalabs.com
export WALLET_ADDRESS=0x4B0897b0513fdc7C541B6d9D7E929C4e5364D2dB
# Optional for GitHub examples
export GITHUB_ACCESS_TOKEN=gho_xxxxxxxxxxxxxxxxxxxx
```

:::

***

### Provider Management

Discover and inspect available providers (e.g., AWS Nitro), regions, and config schema.

```ts
import { TrezaClient } from '@treza/sdk';

const client = new TrezaClient();

async function listProviders() {
  const providers = await client.getProviders();
  console.log('Available providers:', providers.length);
  for (const p of providers) {
    console.log(`- ${p.name} (${p.id})`);
    console.log('  Regions:', p.regions.join(', '));
    console.log('  Config schema keys:', Object.keys(p.configSchema ?? {}));
  }
}

listProviders();
```

Fetch a specific provider:

```ts
const nitro = await client.getProvider('aws-nitro');
console.log(nitro.name, nitro.regions);
```

***

### Enclave Management (Create / Update / Delete)

```ts
import { TrezaClient } from '@treza/sdk';

const client = new TrezaClient();
const WALLET = process.env.WALLET_ADDRESS!;

async function createUpdateDelete() {
  const [provider] = await client.getProviders();

  const enclave = await client.createEnclave({
    name: 'ML Training Environment',
    description: 'Private model training',
    region: provider.regions[0],
    walletAddress: WALLET,
    providerId: provider.id,
    providerConfig: {
      dockerImage: 'ml-training:latest',
      cpuCount: 4,
      memoryMiB: 2048,
    },
  });

  console.log('Created enclave:', enclave.id);

  const updated = await client.updateEnclave({
    id: enclave.id,
    walletAddress: WALLET,
    description: 'Updated description',
    region: enclave.region,
    providerConfig: { ...enclave.providerConfig, dockerImage: 'ml-training:v2' },
  });

  console.log('Updated image:', updated.providerConfig?.dockerImage);

  // Delete (irreversible)
  const msg = await client.deleteEnclave(enclave.id, WALLET);
  console.log(msg);
}

createUpdateDelete();
```

***

### Enclave Lifecycle (Pause / Resume / Terminate)

```ts
import { TrezaClient } from '@treza/sdk';

const client = new TrezaClient();
const WALLET = process.env.WALLET_ADDRESS!;

async function lifecycle(enclaveId: string) {
  const before = await client.getEnclave(enclaveId);
  console.log('Before:', before.status);

  const paused = await client.pauseEnclave(enclaveId, WALLET);
  console.log('Pausing →', paused.enclave.status);

  const resumed = await client.resumeEnclave(enclaveId, WALLET);
  console.log('Resuming →', resumed.enclave.status);

  const terminated = await client.terminateEnclave(enclaveId, WALLET);
  console.log('Terminating →', terminated.enclave.status);
}

// lifecycle('enc_123456');
```

***

### Logs (Application, Errors, and Providers)

```ts
import { TrezaClient } from '@treza/sdk';

const client = new TrezaClient();

async function logs(enclaveId: string) {
  // All logs
  const all = await client.getEnclaveLogs(enclaveId, 'all', 100);
  console.log('Log types:', Object.keys(all.logs));

  // App-only
  const app = await client.getEnclaveLogs(enclaveId, 'application', 50);
  console.log('App entries:', (app.logs.application ?? []).length);

  // Errors-only
  const errs = await client.getEnclaveLogs(enclaveId, 'errors', 50);
  console.log('Errors:', (errs.logs.errors ?? []).length);
}
```

> Available log types: `all`, `ecs`, `stepfunctions`, `lambda`, `application`, `errors`.

***

### Docker Hub Helpers

Search images and list tags directly from the SDK.

```ts
import { TrezaClient } from '@treza/sdk';

const client = new TrezaClient();

async function docker() {
  const search = await client.searchDockerImages('hello-world');
  console.log('Found images:', search.count);

  const tags = await client.getDockerTags('library/node');
  console.log('First 5 tags:', tags.tags.slice(0, 5).map(t => t.name));
}
```

***

### Tasks (Scheduling inside Enclaves)

```ts
import { TrezaClient } from '@treza/sdk';

const client = new TrezaClient();
const WALLET = process.env.WALLET_ADDRESS!;

async function tasks(enclaveId: string) {
  const created = await client.createTask({
    name: 'Daily Price Monitor',
    description: 'Monitor prices and send alerts',
    enclaveId,
    schedule: '0 9 * * *', // 9am daily
    walletAddress: WALLET,
  });
  console.log('Task created:', created.id);

  const all = await client.getTasks(WALLET);
  console.log('Tasks for wallet:', all.length);
}
```

Update / delete tasks:

```ts
const updated = await client.updateTask({ id: 'task_123', walletAddress: WALLET, schedule: '0 */6 * * *', status: 'running' });
const msg = await client.deleteTask('task_123', WALLET);
```

***

### API Keys (Least-Privilege Access)

```ts
import { TrezaClient } from '@treza/sdk';

const client = new TrezaClient();
const WALLET = process.env.WALLET_ADDRESS!;

async function apiKeys() {
  const created = await client.createApiKey({
    name: 'Production Key',
    permissions: ['enclaves:read', 'tasks:read', 'logs:read'],
    walletAddress: WALLET,
  });
  console.log('API key (show once):', created.key);

  const keys = await client.getApiKeys(WALLET);
  console.log('Key count:', keys.length);
}
```

Update / delete keys:

```ts
await client.updateApiKey({ id: 'key_123', walletAddress: WALLET, status: 'active', permissions: ['enclaves:read', 'enclaves:write'] });
await client.deleteApiKey('key_123', WALLET);
```

***

### GitHub OAuth (Optional)

```ts
import { TrezaClient } from '@treza/sdk';

const client = new TrezaClient();

async function githubOAuth() {
  const { authUrl } = await client.getGitHubAuthUrl('custom-state');
  console.log('Authorize at:', authUrl);

  // After your OAuth callback:
  const code = 'code-from-callback';
  const token = await client.exchangeGitHubCode({ code, state: 'custom-state' });
  console.log('GitHub user:', token.user.login);

  const repos = await client.getGitHubRepositories(token.access_token);
  console.log('Repos:', repos.repositories.length);
}
```

Branches for a repo:

```ts
const branches = await client.getRepositoryBranches({ accessToken: process.env.GITHUB_ACCESS_TOKEN!, repository: 'username/repo-name' });
console.log('Branches:', branches.branches.map(b => b.name));
```

Connect a repo to an enclave:

```ts
await client.updateEnclave({
  id: 'enc_123456',
  walletAddress: process.env.WALLET_ADDRESS!,
  githubConnection: { isConnected: true, selectedRepo: 'myorg/my-repo', selectedBranch: 'main' },
});
```

***

### Error Handling

`TrezaSdkError` includes `message`, `code`, `statusCode`, and optional `details`.

```ts
import { TrezaClient, TrezaSdkError } from '@treza/sdk';

const client = new TrezaClient();

async function robust() {
  try {
    await client.getEnclaves('invalid-wallet');
  } catch (err) {
    if (err instanceof TrezaSdkError) {
      console.error('Treza SDK Error:', {
        message: err.message,
        code: err.code,
        statusCode: err.statusCode,
        details: err.details,
      });

      if (err.statusCode === 400) console.log('Check your wallet format.');
      if (err.statusCode === 404) console.log('Enclave not found or access denied.');
    } else {
      console.error('Unexpected error:', err);
    }
  }
}
```

***

### Types (What You Can Import)

```ts
import type {
  // Core
  TrezaConfig, Enclave, Provider, Task, ApiKey, GitHubConnection,
  // Requests / Responses
  CreateEnclaveRequest, UpdateEnclaveRequest,
  CreateTaskRequest, UpdateTaskRequest,
  CreateApiKeyRequest, UpdateApiKeyRequest,
  EnclaveResponse, EnclavesResponse,
  ProviderResponse, ProvidersResponse,
  TaskResponse, TasksResponse,
  ApiKeyResponse, ApiKeysResponse,
  // Lifecycle & Logs
  EnclaveLifecycleRequest, EnclaveLifecycleResponse,
  LogEntry, LogsResponse,
  // Docker
  DockerImage, DockerTag, DockerSearchResponse, DockerTagsResponse,
  // GitHub
  GitHubUser, Repository, Branch, GitHubAuthResponse, GitHubTokenResponse,
  // Errors
  ApiError,
} from '@treza/sdk';
```

***

### Example Runner (Monorepo-friendly)

Structure your `/examples` folder like this:

```
examples/
  quick-start.ts
  providers.ts
  enclave-lifecycle.ts
  logs.ts
  docker.ts
  tasks.ts
  api-keys.ts
  github-oauth.ts
```

Run any file with `ts-node`:

```bash
# env first
export WALLET_ADDRESS=0x4B0897b0513fdc7C541B6d9D7E929C4e5364D2dB
export TREZA_BASE_URL=https://app.trezalabs.com

npx ts-node examples/quick-start.ts
```

***

### Troubleshooting

* **401/403**: Ensure your wallet address owns/has access to the resource.
* **404**: Wrong `enclaveId` or the resource belongs to a different wallet.
* **Lifecycle ops stuck**: Check provider logs via `getEnclaveLogs(enclaveId, 'all')` and verify `providerConfig` (image exists, CPU/mem within quota).
* **Docker tag not found**: Prefix official images with `library/` (e.g., `library/node`).

***

### See Also

* [API Reference](/developers/rest-api.md) → *(SDK Reference section)*
* Concepts → *Providers, Enclaves, Lifecycle*
* Guides → *Deploy your first enclave*


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.trezalabs.com/developers/examples.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
