Skip to main content

JavaScript SDK

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

Installation

npm install @usmewe/sdk

Quick Start

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)

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

JWT Token (Client-side)

const usmewe = new UsmeweClient({
  environment: 'production'
});

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

Supabase Integration

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

// 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

// 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

// 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

// 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

// 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

// 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

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:
import type {
  User,
  TrustScore,
  Loan,
  VaultPosition,
  Guardian
} from '@usmewe/sdk';

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

Webhooks Verification

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

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:
<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

// 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!');