> For the complete documentation index, see [llms.txt](https://docs.pretoke.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.pretoke.xyz/api-reference/auth.md).

# Auth

Wallet-based login via TON Connect. See [Wallet Login Explained](/how-it-works/wallet-login-explained.md) for the full conceptual walkthrough.

***

## POST /auth/connect

{% hint style="info" %}
**Auth required:** No (public endpoint)
{% endhint %}

Verifies a TON Connect proof and issues a session token, creating the user account on first login.

### Request body

| Field                      | Type   | Required | Description                                                                              |
| -------------------------- | ------ | -------- | ---------------------------------------------------------------------------------------- |
| `address`                  | string | yes      | Wallet address (raw or friendly format)                                                  |
| `publicKey`                | string | yes      | Wallet's public key, hex-encoded                                                         |
| `proof.timestamp`          | number | yes      | Unix timestamp when the proof was signed; must be within 5 minutes of the server's clock |
| `proof.domain.lengthBytes` | number | yes      | Byte length of the domain string                                                         |
| `proof.domain.value`       | string | yes      | Domain the proof was signed for; must match the platform's configured domain             |
| `proof.payload`            | string | yes      | The one-time payload issued by the frontend before connecting                            |
| `proof.signature`          | string | yes      | Base64-encoded ed25519 signature                                                         |
| `telegramInitData`         | string | no       | Raw Telegram WebApp `initData` string, included only when launched inside Telegram       |

### Response `200 OK`

```json
{
  "data": {
    "accessToken": "eyJhbGciOi...",
    "expiresAt": 1751586400,
    "userId": "usr_01hz...",
    "walletAddress": "0:abcd...ef01"
  },
  "requestId": "..."
}
```

| Field           | Type   | Description                                                                      |
| --------------- | ------ | -------------------------------------------------------------------------------- |
| `accessToken`   | string | JWT bearer token — use in `Authorization: Bearer <token>` on subsequent requests |
| `expiresAt`     | number | Unix timestamp when the token expires (24h from issuance)                        |
| `userId`        | string | Internal user ID                                                                 |
| `walletAddress` | string | The verified wallet address, now bound to this session                           |

### Code examples

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST "https://predict.pretoke.xyz/api/v1/auth/connect" \
  -H "Content-Type: application/json" \
  -d '{
    "address": "0:abcdef...",
    "publicKey": "9c3f...",
    "proof": {
      "timestamp": 1751500000,
      "domain": { "lengthBytes": 17, "value": "ton-prediction.app" },
      "payload": "a1b2c3...",
      "signature": "base64-signature=="
    }
  }'
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const response = await fetch('https://predict.pretoke.xyz/api/v1/auth/connect', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    address: '0:abcdef...',
    publicKey: '9c3f...',
    proof: {
      timestamp: Math.floor(Date.now() / 1000),
      domain: { lengthBytes: 17, value: 'ton-prediction.app' },
      payload: 'a1b2c3...',
      signature: 'base64-signature=='
    }
  })
});

const { data } = await response.json();
// Store data.accessToken for subsequent requests
console.log('Logged in as:', data.walletAddress);
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import time

response = requests.post(
    "https://predict.pretoke.xyz/api/v1/auth/connect",
    json={
        "address": "0:abcdef...",
        "publicKey": "9c3f...",
        "proof": {
            "timestamp": int(time.time()),
            "domain": {"lengthBytes": 17, "value": "ton-prediction.app"},
            "payload": "a1b2c3...",
            "signature": "base64-signature=="
        }
    }
)

data = response.json()["data"]
access_token = data["accessToken"]
print(f"Logged in as: {data['walletAddress']}")
```

{% endtab %}

{% tab title="Node.js" %}

```javascript
const axios = require('axios');

const { data: result } = await axios.post('https://predict.pretoke.xyz/api/v1/auth/connect', {
  address: '0:abcdef...',
  publicKey: '9c3f...',
  proof: {
    timestamp: Math.floor(Date.now() / 1000),
    domain: { lengthBytes: 17, value: 'ton-prediction.app' },
    payload: 'a1b2c3...',
    signature: 'base64-signature=='
  }
});

const accessToken = result.data.accessToken;
console.log('Token:', accessToken);
```

{% endtab %}
{% endtabs %}

### Errors

`401 Unauthorized` — missing `address`/`publicKey`/`proof`, expired proof (>5 min old), domain mismatch, or invalid signature.

***

## POST /auth/refresh

{% hint style="info" %}
**Auth required:** Yes (existing token with less than 1 hour remaining)
{% endhint %}

Issues a fresh token when the current one has less than one hour of validity remaining. Rejects the call if there's more than an hour left.

### Request

Send the current token either as the `Authorization: Bearer <token>` header (preferred) or in the body:

```json
{ "token": "eyJhbGciOi..." }
```

### Response `200 OK`

Same shape as `/auth/connect` — a new `accessToken`, `expiresAt`, `userId`, `walletAddress`.

### Code examples

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST "https://predict.pretoke.xyz/api/v1/auth/refresh" \
  -H "Authorization: Bearer <your-token>" \
  -H "Content-Type: application/json"
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const response = await fetch('https://predict.pretoke.xyz/api/v1/auth/refresh', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${accessToken}`,
    'Content-Type': 'application/json'
  }
});

const { data } = await response.json();
accessToken = data.accessToken; // Update stored token
```

{% endtab %}

{% tab title="Python" %}

```python
response = requests.post(
    "https://predict.pretoke.xyz/api/v1/auth/refresh",
    headers={"Authorization": f"Bearer {access_token}"}
)

data = response.json()["data"]
access_token = data["accessToken"]
```

{% endtab %}

{% tab title="Node.js" %}

```javascript
const { data: result } = await axios.post(
  'https://predict.pretoke.xyz/api/v1/auth/refresh',
  {},
  { headers: { Authorization: `Bearer ${accessToken}` } }
);

accessToken = result.data.accessToken;
```

{% endtab %}
{% endtabs %}

### Errors

`401 Unauthorized` — no token provided, invalid/expired token, session not found, or more than 1 hour of validity remaining.

***

## POST /auth/logout

{% hint style="info" %}
**Auth required:** Yes
{% endhint %}

Invalidates the current session server-side immediately.

### Response

`204 No Content`

### Code examples

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST "https://predict.pretoke.xyz/api/v1/auth/logout" \
  -H "Authorization: Bearer <your-token>"
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
await fetch('https://predict.pretoke.xyz/api/v1/auth/logout', {
  method: 'POST',
  headers: { 'Authorization': `Bearer ${accessToken}` }
});
```

{% endtab %}

{% tab title="Python" %}

```python
requests.post(
    "https://predict.pretoke.xyz/api/v1/auth/logout",
    headers={"Authorization": f"Bearer {access_token}"}
)
```

{% endtab %}

{% tab title="Node.js" %}

```javascript
await axios.post('https://predict.pretoke.xyz/api/v1/auth/logout', {}, {
  headers: { Authorization: `Bearer ${accessToken}` }
});
```

{% endtab %}
{% endtabs %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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, and the optional `goal` query parameter:

```
GET https://docs.pretoke.xyz/api-reference/auth.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
