> ## Documentation Index
> Fetch the complete documentation index at: https://docs.repstation.xyz/llms.txt
> Use this file to discover all available pages before exploring further.

# SDK Reference

> Complete API documentation for the IOTA Repstation TypeScript SDK

## Overview

The IOTA Repstation SDK provides a comprehensive TypeScript API for integrating decentralized reputation management into your applications. The SDK supports both browser and server environments with full type safety.

## Installation

<CodeGroup>
  ```bash npm theme={null}
  npm install @repstation/sdk
  ```

  ```bash yarn theme={null}
  yarn add @repstation/sdk
  ```

  ```bash pnpm theme={null}
  pnpm add @repstation/sdk
  ```
</CodeGroup>

## Import Paths

The SDK provides optimized bundles for different environments:

<CodeGroup>
  ```javascript Universal theme={null}
  import { RepstationClient } from '@repstation/sdk';
  ```

  ```javascript Browser-Specific theme={null}
  import { RepstationClient } from '@repstation/sdk/browser';
  ```

  ```javascript Server-Specific theme={null}
  import { createServer } from '@repstation/sdk/server';
  ```
</CodeGroup>

## Core Classes

### RepstationClient

The main client class for interacting with the IOTA Repstation system:

```typescript theme={null}
class RepstationClient {
  constructor(config: NetworkConfig, client?: IotaClient);
  
  // Static factory method (recommended)
  static async create(config: RepstationConfig): Promise<RepstationClient>;
  
  // Deal Management (returns Transaction objects for signing)
  openDealAdmin(params: OpenDealAdminParams): Transaction;
  openDealClient(params: OpenDealClientParams): Transaction;
  acceptDeal(params: AcceptDealParams): Transaction;
  closeDeal(params: CloseDealParams): Transaction;
  
  // Rating System (returns Transaction objects for signing)
  rate(params: RateParams): Transaction;
  updateRating(params: UpdateRatingParams): Transaction;
  revokeRating(params: RevokeRatingParams): Transaction;
  
  // Reputation Queries (async operations)
  getReputationProfile(params: GetReputationProfileParams): Promise<GetReputationProfileResponse>;
  getObject(params: GetObjectParams): Promise<any>;
  getProviderMetadata(params: GetProviderMetadataParams): Promise<GetProviderMetadataResponse>;
  
  // App Management (returns Transaction objects for signing)
  registerApp(params: RegisterAppParams): Transaction;
  mintClientCap(params: MintClientCapParams): Transaction;
  updateProviderMetadata(params: UpdateProviderMetadataParams): Transaction;
}
```

## Configuration Types

### RepstationConfig

```typescript theme={null}
interface RepstationConfig {
  network: 'testnet' | 'mainnet' | 'custom';
  packageId: string;
  rpcUrl?: string;          // Required for custom networks
  client?: IotaClient;      // Optional: provide your own client
}

interface NetworkConfig {
  packageId: string;
  registryId: string;       // Required
  aggregatesId: string;     // Required
  rpcUrl?: string;
}
```

## Deal Management Types

### Deal Creation

```typescript theme={null}
interface OpenDealAdminParams {
  admin_cap: string;        // AdminCap object ID
  party_b: string;          // Address of party B
  subject_ref: string;      // Deal subject reference as string
  amount: string;           // Deal amount as string
}

interface OpenDealClientParams {
  client_cap: string;       // ClientCap object ID
  party_b: string;          // Address of party B
  subject_ref: string;      // Deal subject reference as string
  amount: string;           // Deal amount as string
}

// Methods return Transaction objects for signing, not result objects
// The transaction needs to be signed and submitted by the caller
```

### Deal Lifecycle

```typescript theme={null}
interface AcceptDealParams {
  deal_id: string;          // Deal object ID to accept
}

interface CloseDealParams {
  deal_id: string;          // Deal object ID to close
}
```

## Rating System Types

### Rating Creation

```typescript theme={null}
interface RateParams {
  deal_id: string;          // Deal object ID to rate
  score: number;            // Rating score (1-100)
  category?: string;        // Optional rating category
}

interface UpdateRatingParams {
  endorsement_id: string;   // Endorsement object ID
  endorsement_cap: string;  // EndorsementCap object ID
  new_score: number;        // New rating score (1-100)
}

interface RevokeRatingParams {
  endorsement_id: string;   // Endorsement object ID
  endorsement_cap: string;  // EndorsementCap object ID
}
```

## Provider Management Types

### Provider Registration

```typescript theme={null}
interface RegisterAppParams {
  providerMetadata: {
    providerName: string;   // Required provider name
    publicUrl: string;      // Required public URL
    xHandle?: string;       // Optional X/Twitter handle
  };
}

interface UpdateProviderMetadataParams {
  adminCapId: string;       // AdminCap object ID
  providerName: string;     // Updated provider name
  publicUrl: string;        // Updated public URL
  xHandle?: string;         // Updated X/Twitter handle
}

interface MintClientCapParams {
  admin_cap: string;        // AdminCap object ID
  to: string;              // Address to mint capability to
  expires_at_ms?: number;   // Optional expiration timestamp
}
```

## Reputation Query Types

### Reputation Profile

```typescript theme={null}
interface GetReputationProfileParams {
  walletAddress: string;    // Wallet address to query
}

interface GetReputationProfileResponse {
  success: boolean;
  profile?: ReputationProfile;
  error?: string;
}

interface ReputationProfile {
  walletAddress: string;
  global?: ReputationStats;
  appScoped: AppScopedReputationData[];
  queryTimestamp: string;
}

interface ReputationStats {
  total: string;
  count: string;
  average: string;
}

interface AppScopedReputationData {
  appOwner: string;
  walletAddress: string;
  stats: ReputationStats;
}
```

## Provider Metadata Query Types

```typescript theme={null}
interface GetProviderMetadataParams {
  namespaceId: string;      // Provider namespace ID
}

interface GetProviderMetadataResponse {
  success: boolean;
  metadata?: ProviderMetadata;
  error?: string;
}

interface ProviderMetadata {
  providerName: string;
  publicUrl: string;
  xHandle?: string;
}
```

## Usage Examples

### Basic Client Setup

```javascript theme={null}
import { RepstationClient } from '@repstation/sdk';

// Create client using factory method (recommended)
const client = await RepstationClient.create({
  network: 'testnet',
  packageId: '0xYOUR_PACKAGE_ID'
});

// Or create directly with network config
const client = new RepstationClient({
  network: 'testnet',
  packageId: '0xYOUR_PACKAGE_ID',
  registryId: '0xREGISTRY_ID',
  aggregatesId: '0xAGGREGATES_ID'
});
```

### Working with Deals

```javascript theme={null}
// Open a deal (returns Transaction object)
const dealTx = client.openDealAdmin({
  admin_cap: '0xADMIN_CAP_ID',
  party_b: '0xCOUNTERPARTY_ADDRESS',
  subject_ref: 'NFT_12345',
  amount: '1000'
});

// Sign and submit the transaction
const result = await wallet.signAndSubmit(dealTx);
console.log('Deal ID:', result.objectChanges[0].objectId);
```

### Rating and Reputation

```javascript theme={null}
// Submit a rating
const rateTx = client.rate({
  deal_id: '0xDEAL_ID',
  score: 85,
  category: 'quality'
});

// Get reputation profile
const profile = await client.getReputationProfile({
  walletAddress: '0xUSER_ADDRESS'
});

if (profile.success) {
  console.log('Global reputation:', profile.profile?.global?.average);
}
```

## Error Handling

The SDK provides comprehensive error handling with custom error types:

```typescript theme={null}
class RepstationError extends Error {
  constructor(
    message: string,
    public code: string,
    public details?: any
  ) {
    super(message);
    this.name = 'RepstationError';
  }
}

// Usage example
try {
  await client.rate({
    deal_id: 'invalid-id',
    score: 85,
    category: 'delivery'
  });
} catch (error) {
  if (error instanceof RepstationError) {
    console.error('Contract error:', error.code, error.message);
  } else {
    console.error('Unexpected error:', error);
  }
}
```

## Common Error Codes

| Code               | Description                              | Solution                                         |
| ------------------ | ---------------------------------------- | ------------------------------------------------ |
| `INVALID_DEAL_ID`  | Deal ID not found or invalid format      | Verify deal ID exists and is correctly formatted |
| `DEAL_NOT_CLOSED`  | Attempting to rate before deal is closed | Close the deal first using `closeDeal()`         |
| `ALREADY_RATED`    | User has already rated this deal         | Use `updateRating()` instead of `rate()`         |
| `NOT_PARTY_MEMBER` | User is not a participant in the deal    | Only deal participants can rate each other       |
| `INVALID_SCORE`    | Score outside valid range (1-100)        | Provide a score between 1 and 100                |

## Mock Client

For development and testing, the SDK includes a mock client:

```typescript theme={null}
// Mock client is used automatically when no real IOTA client is provided
const mockClient = new RepstationClient({
  network: 'testnet',
  packageId: '0xMOCK_PACKAGE'
  // No client provided - uses MockIotaClient
});

// All operations return mock responses
const result = await mockClient.openDealAdmin({
  signer: '0xMOCK_SIGNER',
  admin_cap_id: '0xMOCK_CAP',
  party_b: '0xMOCK_PARTY_B',
  subject_ref: { type: 'TEST', id: '123' },
  amount: '1000'
});

console.log(result.deal_id); // Returns mock object ID
```

## Bundle Information

The SDK provides optimized bundles:

* **ESM Bundle**: `~27KB` - Modern ES modules for bundlers
* **CJS Bundle**: `~30KB` - CommonJS for Node.js compatibility
* **Types Bundle**: `~8KB` - Full TypeScript definitions
* **Browser Bundle**: Optimized for frontend applications
* **Server Bundle**: Optimized for Node.js applications

## Browser Compatibility

* Chrome 91+
* Firefox 90+
* Safari 14+
* Edge 91+

## Node.js Compatibility

* Node.js 16+
* TypeScript 4.5+

## Next Steps

<CardGroup cols={2}>
  <Card title="Deal Management" icon="handshake" href="/api-reference/deals/open-deal">
    Explore deal creation and lifecycle management APIs.
  </Card>

  <Card title="Rating System" icon="star" href="/api-reference/ratings/create-rating">
    Understand rating creation and management APIs.
  </Card>

  <Card title="Reputation Queries" icon="chart-line" href="/api-reference/reputation/get-profile">
    Learn about reputation data retrieval.
  </Card>

  <Card title="Integration Examples" icon="puzzle-piece" href="/integration/marketplace-example">
    See real-world integration patterns.
  </Card>
</CardGroup>
