# REST API Integration

This guide helps developers integrate Clique Wallet into their applications using the RESTful API.

#### Prerequisites

* Access to a Clique Wallet instance
* The Clique Wallet API endpoint URL
* A web application or backend service where you want to integrate Clique Wallet
* Basic understanding of REST APIs and HTTP requests

#### Basic Setup

**1. Configure Your Clique Wallet Endpoint**

First, configure your application to point to your Clique Wallet instance:

```javascript
const WALLET_API_URL = 'https://your-wallet-instance.com';
```

**2. Understand the Authentication Flow**

Clique Wallet uses session-based authentication for user-facing applications. When a user successfully authenticates, Clique Wallet sets a secure HTTP-only session cookie that maintains the user's authentication state.

#### Your First Integration

**Step 1: User Authentication**

Users can authenticate using various methods. Here's a simple example using email verification:

**Request a Verification Code:**

```bash
curl -X POST https://your-wallet-instance.com/send_verification \
  -H "Content-Type: application/json" \
  -d '{
    "email": "user@example.com"
  }'
```

**Complete Login:**

After the user receives and enters the verification code:

```bash
curl -X POST https://your-wallet-instance.com/login \
  -H "Content-Type: application/json" \
  -c cookies.txt \
  -d '{
    "type": "Email",
    "data": {
      "email": "user@example.com",
      "code": "123456"
    }
  }'
```

Upon successful login, Clique Wallet will:

* Create wallets for all supported blockchains (if they don't exist)
* Set a secure session cookie
* Return user information including wallet addresses

**Step 2: Check Session Status**

To verify the user is authenticated and get their wallet information:

```bash
curl -X GET https://your-wallet-instance.com/session \
  -H "Content-Type: application/json" \
  -b cookies.txt
```

The response will include:

* User ID
* Wallet addresses for all supported networks (Solana, EVM-compatible chains, etc.)
* Authentication methods bound to the account

**Step 3: Get Wallet Addresses**

Wallet addresses are automatically created upon first login. You can retrieve them from the session response:

```json
{
  "id": "user-id",
  "wallets": [
    {
      "id": "wallet-id",
      "address": "0x...",
      "network": "Ethereum",
      "wallet_type": "Embedded",
      "wallet_set": "Main"
    },
    {
      "id": "wallet-id",
      "address": "So1...",
      "network": "Solana",
      "wallet_type": "Embedded",
      "wallet_set": "Main"
    }
  ]
}
```

**Step 4: Sign Your First Transaction**

To sign a transaction, send the transaction data to the sign endpoint:

```bash
curl -X POST https://your-wallet-instance.com/sign \
  -H "Content-Type: application/json" \
  -b cookies.txt \
  -d '{
    "address": "0x...",
    "network": "Ethereum",
    "message": "0x...",
    "need_check": true
  }'
```

The response will include the signature that can be used to submit the transaction to the blockchain.

#### Authentication Methods

Clique Wallet supports multiple authentication methods:

**Social OAuth (Google, X/Twitter, Telegram):**

1. Initialize OAuth flow with `/oauth/init`
2. Redirect user to the OAuth provider
3. Handle callback at `/oauth/callback`
4. Complete login with `/login` using the OAuth credentials

**External Wallet Connection:**

1. Get challenge message from `/challenge`
2. User signs the challenge with their external wallet
3. Complete login with `/login` using the signature

**Phone Verification:** Similar to email verification, but use `phone` instead of `email` in the request.

#### Common Patterns

**Checking if User is Logged In:**

```javascript
async function checkAuthStatus() {
  const response = await fetch('https://your-wallet-instance.com/session', {
    credentials: 'include' // Important: include cookies
  });
  
  if (response.ok) {
    const user = await response.json();
    return user;
  }
  return null;
}
```

**Handling Session Expiration:**

```javascript
async function ensureAuthenticated() {
  const user = await checkAuthStatus();
  if (!user) {
    // Redirect to login
    window.location.href = '/login';
    return null;
  }
  return user;
}
```

**Error Handling:**

```javascript
try {
  const response = await fetch('https://your-wallet-instance.com/sign', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    credentials: 'include',
    body: JSON.stringify(signRequest)
  });
  
  if (!response.ok) {
    const error = await response.json();
    console.error('Sign error:', error.error);
    // Handle error appropriately
  } else {
    const result = await response.json();
    // Use the signature
  }
} catch (error) {
  console.error('Network error:', error);
}
```
