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

# JavaScript SDK

> Official JavaScript/TypeScript SDK for usmewe

# JavaScript SDK

The official usmewe JavaScript SDK for Node.js and browser applications.

## Installation

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

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

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

## Quick Start

```typescript theme={null}
import { UsmeweClient } from '@usmewe/sdk';

// Initialize the client
const usmewe = new UsmeweClient({
  apiKey: 'your_api_key', // or use JWT auth
  environment: 'production' // or 'testnet'
});

// Get user's Trust Score
const score = await usmewe.trustScore.get('user_id');
console.log(`Trust Score: ${score.score}`);
```

## Authentication

### API Key (Server-side)

```typescript theme={null}
const usmewe = new UsmeweClient({
  apiKey: process.env.USMEWE_API_KEY,
  environment: 'production'
});
```

### JWT Token (Client-side)

```typescript theme={null}
const usmewe = new UsmeweClient({
  environment: 'production'
});

// Set token after user authentication
usmewe.setToken(jwtToken);
```

### Supabase Integration

```typescript theme={null}
import { createClient } from '@supabase/supabase-js';
import { UsmeweClient } from '@usmewe/sdk';

const supabase = createClient(SUPABASE_URL, SUPABASE_KEY);

// Get token from Supabase session
const { data: { session } } = await supabase.auth.getSession();

const usmewe = new UsmeweClient({
  token: session?.access_token,
  environment: 'production'
});
```

## Core Methods

### Users

```typescript theme={null}
// Get current user
const me = await usmewe.users.me();

// Get user by ID
const user = await usmewe.users.get('user_id');

// Update profile
await usmewe.users.update({
  displayName: 'New Name',
  settings: { notifications: true }
});

// Get user activity
const activity = await usmewe.users.getActivity({ limit: 10 });
```

### Trust Score

```typescript theme={null}
// Get Trust Score
const score = await usmewe.trustScore.get('user_id');
console.log(score.breakdown);

// Get score history
const history = await usmewe.trustScore.getHistory('user_id', '30d');

// Simulate score changes
const simulation = await usmewe.trustScore.simulate({
  actions: [
    { type: 'repayment', count: 5 }
  ]
});
```

### Loans

```typescript theme={null}
// Check eligibility
const eligibility = await usmewe.loans.checkEligibility();

// Create loan request
const loan = await usmewe.loans.create({
  amount: 50,
  duration: 14,
  purpose: 'Emergency expense'
});

// Get loan details
const loanDetails = await usmewe.loans.get('loan_id');

// List user loans
const loans = await usmewe.loans.list({ status: 'active' });

// Repay loan
await usmewe.loans.repay('loan_id', { amount: 51.35 });

// Cancel pending loan
await usmewe.loans.cancel('loan_id');
```

### Trust Vault

```typescript theme={null}
// Get vault status
const status = await usmewe.vault.getStatus();

// Get user position
const position = await usmewe.vault.getPosition();

// Deposit USDC
const deposit = await usmewe.vault.deposit({ amount: 1000 });

// Withdraw
const withdraw = await usmewe.vault.withdraw({ tmUSDCAmount: 500 });

// Get yield history
const yields = await usmewe.vault.getYieldHistory('30d');
```

### Social Vault

```typescript theme={null}
// Create Social Vault
await usmewe.socialVault.create({
  dailyLimit: 100,
  timelockDuration: 86400,
  requiredSignatures: 2,
  duressPin: '1234'
});

// Deposit
await usmewe.socialVault.deposit({ amount: 500 });

// Instant withdrawal
await usmewe.socialVault.withdrawInstant({
  amount: 50,
  recipient: '0x...'
});

// Request large withdrawal
const request = await usmewe.socialVault.requestWithdrawal({
  amount: 500,
  recipient: '0x...'
});

// Emergency lock
await usmewe.socialVault.lock({ duressPin: '1234' });
```

### Guardians

```typescript theme={null}
// Add guardian
await usmewe.guardians.add({ walletAddress: '0x...' });

// List guardians
const guardians = await usmewe.guardians.list();

// Remove guardian
await usmewe.guardians.remove('guardian_id');

// Approve withdrawal (as guardian)
await usmewe.guardians.approveWithdrawal('withdrawal_id');
```

## Error Handling

```typescript theme={null}
import { UsmeweError, UsmeweErrorCode } from '@usmewe/sdk';

try {
  await usmewe.loans.create({ amount: 1000, duration: 14 });
} catch (error) {
  if (error instanceof UsmeweError) {
    switch (error.code) {
      case UsmeweErrorCode.NOT_ELIGIBLE:
        console.log('Not eligible for this loan amount');
        break;
      case UsmeweErrorCode.INSUFFICIENT_BALANCE:
        console.log('Insufficient balance');
        break;
      default:
        console.log(`Error: ${error.message}`);
    }
  }
}
```

## TypeScript Support

The SDK is written in TypeScript and exports all types:

```typescript theme={null}
import type {
  User,
  TrustScore,
  Loan,
  VaultPosition,
  Guardian
} from '@usmewe/sdk';

const handleUser = (user: User) => {
  console.log(user.trustScore);
};
```

## Webhooks Verification

```typescript theme={null}
import { verifyWebhookSignature } from '@usmewe/sdk';

app.post('/webhooks', (req, res) => {
  const isValid = verifyWebhookSignature(
    req.body,
    req.headers['x-usmewe-signature'],
    WEBHOOK_SECRET
  );

  if (!isValid) {
    return res.status(401).send('Invalid signature');
  }

  // Process webhook
  res.status(200).send('OK');
});
```

## Configuration Options

```typescript theme={null}
const usmewe = new UsmeweClient({
  apiKey: 'your_api_key',
  environment: 'production', // 'production' | 'testnet'
  timeout: 30000, // Request timeout in ms
  retries: 3, // Number of retries
  baseUrl: 'https://api.usmewe.com', // Custom base URL
  onError: (error) => {
    // Global error handler
    console.error('SDK Error:', error);
  }
});
```

## Browser Support

The SDK works in modern browsers:

```html theme={null}
<script type="module">
  import { UsmeweClient } from 'https://cdn.usmewe.com/sdk/latest.esm.js';

  const usmewe = new UsmeweClient({
    environment: 'production'
  });
</script>
```

## Examples

### Complete Loan Flow

```typescript theme={null}
// 1. Check eligibility
const { eligible, maxAmount } = await usmewe.loans.checkEligibility();

if (!eligible) {
  console.log('Not eligible for loans');
  return;
}

// 2. Create loan request
const loan = await usmewe.loans.create({
  amount: Math.min(50, maxAmount),
  duration: 14
});

console.log(`Loan created: ${loan.id}`);
console.log(`Net amount: ${loan.netAmount} USDC`);
console.log(`Due date: ${loan.dueDate}`);

// 3. Later: Repay the loan
await usmewe.loans.repay(loan.id, { amount: loan.totalRepayment });
console.log('Loan repaid!');
```

<CardGroup cols={2}>
  <Card title="React Hooks" icon="react" href="/developers/sdks/react-hooks">
    React-specific hooks
  </Card>

  <Card title="API Reference" icon="code" href="/developers/api-reference/overview">
    Full API documentation
  </Card>
</CardGroup>
