> For the complete documentation index, see [llms.txt](https://docs.makapay.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.makapay.io/guides/vault.md).

# Vault System

The Vault system provides businesses with deterministic deposit addresses for their users. Each user gets a unique address that accepts any enabled token, with automatic processing and webhook notifications.

## Overview

**Key Features:**

* **One Address Per User** - Each user gets a single deposit address that accepts ANY enabled token
* **Deterministic Addresses** - Addresses are computed using CREATE2, same across all supported chains
* **Automatic Processing** - Deposits are detected and processed automatically
* **Webhook Notifications** - Real-time notifications when deposits are processed
* **Flat Fee** - Exactly one 1% fee on every completed deposit: from the token swept when no conversion succeeds, or from realized converted output after a successful Auto-Conversion
* **Non-Custodial Withdrawals** - Payout requests submitted via API and approved from your own wallet — see [Withdrawals](#withdrawals)

> **Sandbox scope:** when `NEXT_PUBLIC_MAKA_NETWORK` is `testnet` or `local`, new accounts use ordinary V2 Vault addresses and cannot acquire the `conversionCapable` latch. An already-latched account keeps router-salted derivation, but those addresses use signed passthrough: Vault deposits settle in the deposited asset without conversion and pay the normal single 1% fee. Disabling remains available, and the latch is never cleared, so existing addresses remain recoverable.

## How It Works

### Architecture

```
┌─────────────────────────────────────────────────────────────────┐
│                         User Flow                                │
├─────────────────────────────────────────────────────────────────┤
│                                                                  │
│  1. Business creates user     2. User deposits tokens            │
│     via API/Dashboard            to their address                │
│           │                           │                          │
│           ▼                           ▼                          │
│  ┌─────────────────┐         ┌─────────────────┐                │
│  │ MakaPay Backend │         │ Deposit Address │                │
│  │ computeAddress()│         │  (CREATE2)      │                │
│  └────────┬────────┘         └────────┬────────┘                │
│           │                           │                          │
│           ▼                           ▼                          │
│  ┌─────────────────┐         ┌─────────────────┐                │
│  │ Deposit Address │         │ Deposit Detected│                │
│  │ returned to     │         │ by cron job     │                │
│  │ business        │         └────────┬────────┘                │
│  └─────────────────┘                  │                          │
│                                       ▼                          │
│                              ┌─────────────────┐                │
│  3. Funds swept to           │ Factory.process()│                │
│     business wallet          │ sweeps funds    │                │
│           ▲                  └────────┬────────┘                │
│           │                           │                          │
│           └───────────────────────────┘                          │
│                                                                  │
│  4. Webhook sent to business with deposit details                │
│                                                                  │
└─────────────────────────────────────────────────────────────────┘
```

### Address Computation

Deposit addresses are deterministic using CREATE2:

```
salt = keccak256(userId, casinoAddress)
address = CREATE2(factory, salt, walletBytecode)
```

**Important:** The same `userId` + `casinoAddress` combination always produces the same deposit address, regardless of which token is being deposited.

## Business ID (`publicId`)

When you create your vault, MakaPay assigns you a **Business ID** — a public identifier that looks like:

```
biz_abc123def456ghij
```

You can find it on **Dashboard → Vault → Settings**, in the field labelled *Business ID*. It appears in every vault API response as the `publicId` field.

### What it's for

The Business ID identifies your vault on **public, unauthenticated endpoints** — places where exposing your secret API key would be unsafe. The canonical example is the "supported tokens" endpoint your customer-facing frontend calls to render the deposit UI:

```
GET /api/vault/v1/business/biz_abc123def456ghij/tokens
```

That endpoint returns the chains and tokens you accept, with no auth required. The Business ID is the only thing identifying your vault in the request.

### What it is *not*

* **Not a secret.** Treat it like a username, not a password. It's safe to embed in client-side code, share with customers, paste in screenshots.
* **Not your API key.** Your API key (`mk_...`) is the secret that authorises mutations — creating users, fetching deposits, reading config. Never put your API key in client-side code; use the Business ID for public reads instead.
* **Not your wallet address.** Your wallet address is where funds settle. The Business ID is just an identifier for the vault record.

### How to use it safely

| Where                                           | Use Business ID? | Use API Key?              |
| ----------------------------------------------- | ---------------- | ------------------------- |
| Frontend (browser, mobile app)                  | Yes              | **No**                    |
| Backend (server, edge function)                 | Yes              | Yes                       |
| `GET /vault/v1/business/{publicId}/tokens`      | Required         | Not used                  |
| `POST /vault/v1/users` (create deposit address) | Not used         | Required                  |
| `GET /vault/v1/deposits`                        | Not used         | Required                  |
| Webhook payload signing                         | Not used         | Webhook secret (separate) |

A typical setup: your frontend reads the supported-tokens list with the Business ID, lets the customer pick a token, then your backend calls `POST /vault/v1/users` (with the API key) to mint that customer's deposit address.

### Rotation

Business IDs are stable for the lifetime of the vault — they don't rotate. If you ever need a new one, you'd create a new vault account, which would also give you a new on-chain casino identity and therefore different deposit addresses for every user.

## Smart Contracts

### Contract Addresses

| Contract                                     | Address                                      | Networks                      |
| -------------------------------------------- | -------------------------------------------- | ----------------------------- |
| Guarded FactoryV2 (active release pin)       | `0xEbcA32C9C343d6CabbD06E5118193672c4735474` | All EVM Vault networks        |
| WalletV2 implementation (active release pin) | `0xef8eA69Baea137e6b20358e27222597508E1bf6b` | All EVM Vault networks        |
| ConversionRouterV2 (active release pin)      | `0x75d2BE781770BEfa5E939DDD9Df657FD52fE1385` | All EVM Vault networks        |
| FactoryV1 (legacy recovery only)             | `0xDEBd5F39a53e86DC1887eaf9eBc9B8a8E635bEA2` | Historical EVM addresses only |

Every new or re-derived EVM deposit address uses FactoryV2 after its bytecode is verified on the destination chain. FactoryV1 addresses remain immutable historical addresses: keep monitoring them for recovery, but never issue or display one as a new address.

### Upgrade an existing EVM Vault

Every existing EVM Vault has an idempotent **Dashboard → Vault → Settings → Vault contract upgrade** action. **Migrate Vault & all users** first verifies the Vault's fixed 1% on-chain configuration, then re-derives every existing EVM user through FactoryV2. Ordinary users remain ordinary; users already assigned to an Auto-Conversion router move to RouterV2.

CREATE2 includes the factory and settlement identity, so an upgraded user can receive a new deposit address. Fetch the current address after migration and update the address shown in your cashier. The previous address remains indexed and monitored for historical deposits and recovery. A partial migration is safe to run again: already-current rows are skipped.

### Factory Functions

#### `computeAddress(string userId, address casino)`

Computes the deterministic deposit address for a user.

```solidity
function computeAddress(
    string calldata userId,
    address casino
) external view returns (address)
```

**Parameters:**

* `userId` - Your internal user identifier (e.g., "user\_123", "player\_abc")
* `casino` - Your business wallet for an ordinary address, or Makapay's canonical conversion router for an Auto-Conversion address

**Returns:** The deposit address for this user

Use the Vault Users API to create production deposit addresses. Auto-Conversion scopes the user identity by business and selects the canonical router automatically; calling `computeAddress` with only the visible external user ID and your wallet would derive a different ordinary address.

#### `process(string userId, address casino, address token, bytes callbackData)`

Processes a deposit by sweeping funds from the deposit address to the casino wallet.

```solidity
function process(
    string calldata userId,
    address casino,
    address token,
    bytes calldata callbackData
) external returns (address wallet, uint256 amount, uint256 fee)
```

**Parameters:**

* `userId` - The user's identifier
* `casino` - Your business wallet address
* `token` - The token contract address being processed
* `callbackData` - Optional data passed to your callback (usually the userId encoded)

**Returns:**

* `wallet` - The deposit wallet address
* `amount` - Total amount processed (before fee)
* `fee` - Fee amount deducted

### Fee Structure

Vault deposits have one MakaPay fee:

| Deposit type                                                  | Fee basis                                                                                      | What you receive                                                   |
| ------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ------------------------------------------------------------------ |
| No successful conversion (ordinary, passthrough, or degraded) | 1% of the token being swept                                                                    | 99% of the swept token                                             |
| Successful Auto-Conversion                                    | 1% of the realized converted output, after swap execution and the 6 bps deBridge affiliate fee | 99% of the realized converted output                               |
| Vault withdrawal                                              | No MakaPay fee                                                                                 | The requested payout; your signing wallet pays its own network gas |

The Vault fee is fixed at **1% (100 bps)**. It is not changed by payment-link fee modes, merchant type, plan, or agent markup.

If no conversion succeeds, the factory charges the single 1% fee from the token being swept and sends the remaining 99% to your settlement wallet. This includes ordinary deposits, stablecoins that do not need conversion, passthrough tokens, and degraded conversion fallbacks. With a successful [Auto-Conversion](https://docs.makapay.io/guides/vault-auto-conversion.md), the factory takes no source-token fee: the full source deposit enters the route, deBridge applies the configured **6 bps affiliate fee** during swap execution, and MakaPay then charges the single 1% Vault fee from the realized target-token output before sending the remaining 99% to you.

## Business mode (gaming vs. recurring payments)

Every vault account has a `useCase` of either `"gaming"` (default, including legacy accounts with no value stored) or `"business"`. This is **purely a dashboard vocabulary and onboarding switch** — it never changes address derivation, sweeping, fees, or webhook behavior. The underlying product is identical either way: one permanent deposit address per counterparty, every inbound transfer auto-detected/swept/webhooked.

Set it in **Dashboard > Vault > Settings > Vault Configuration** under "What are you collecting?":

* **Player deposits** (`gaming`) — the original Vault vocabulary: Users, Deposits, Platform Wallets, and the casino simulator onboarding step.
* **Recurring payments from businesses** (`business`) — swaps the dashboard copy to Clients / Payments received / Recurring Payments, omits the casino simulator from onboarding, and unlocks per-client metadata:
  * **Client name** (`displayName`) and **Contact email** (`contactEmail`) on the create-client dialog — the Reference ID (`externalUserId`) is auto-slugified from the name but stays editable and, once created, is permanent (used in webhooks/API, exactly like `User ID` in gaming mode).
  * **Notes** (free text) editable afterward from the client detail page's "Edit details" dialog, alongside name/email.
  * A **"Copy payment instructions"** button on the client's QR dialog that copies a ready-to-send plaintext block naming the business, the client, the accepted tokens/networks, and the permanent deposit address.

`displayName` / `contactEmail` / `notes` are stored on `vaultUsers` as purely descriptive metadata — they are never part of the CREATE2 salt, never indexed, and have no effect on sweeping or fees.

## Dashboard Setup

### 1. Configure Your Vault

Navigate to **Dashboard > Vault > Settings**:

1. **What are you collecting?** - Choose `gaming` (player deposits) or `business` (recurring payments) — see [Business mode](#business-mode-gaming-vs-recurring-payments)
2. **Business Name** - Your business display name
3. **Wallet Address** - Where processed funds are sent
4. **Enabled Tokens** - Select which tokens to accept (USDT, USDC, etc.)

Auto-conversion is available only on Ethereum, Polygon, BSC, and Base where a swap route is configured. MakaChain deposits always sweep as the original token to the configured wallet; they are never sent to deBridge or an auto-swap.

5. **Settlement choice** - During onboarding, choose whether eligible non-stable deposits are forwarded as received or converted to USDT/USDC before payout. Stablecoin deposits are not swapped; the single 1% Vault fee is taken from the stablecoin during the sweep.
6. **Existing EVM Vaults** - Use **Vault contract upgrade → Migrate Vault & all users** once the V2 contracts are available on every supported EVM network. Refresh the deposit address displayed to each user afterward. Old addresses remain monitored for recovery, and the migration is safe to retry.

### 2. Create User / Client Addresses

Navigate to **Dashboard > Vault > Users** (labeled **Clients** in business mode):

1. Click **Create User** (**Add Client** in business mode)
2. In gaming mode, enter the **User ID** (your internal identifier). In business mode, enter the **Client name** — the **Reference ID** is auto-slugified from it (editable before creation, permanent after) — and optionally a **Contact email**.
3. The deposit address is generated automatically

### 3. Configure Webhooks (Optional)

Navigate to **Dashboard > Vault > Settings > Webhooks**:

1. Enter your **Webhook URL**
2. Save — Makapay generates the **Webhook Secret** used for signature verification (regenerate it any time from the same card)

A webhook saved from the dashboard is subscribed to **every** event, deposits and withdrawals alike. To receive only a subset, pin an explicit `events` list through `PUT /api/vault/v1/config/webhooks` — but keep `withdrawal.rejected` in it, or your backend never learns to re-credit a declined player payout.

### 4. Try the Casino Simulator (Optional, gaming mode only)

This onboarding step is omitted entirely for `business`-mode vaults — it has no meaning for B2B recurring payments. Gaming-mode vaults still see it.

Navigate to **Dashboard > Vault > Demo > Casino** ("Lucky Vault Casino") — a simulator that role-plays a casino and its player against the real vault REST API using your API key:

* **Player card** (left) and **operator console** (right), with the "Behind the scenes" feed at the bottom of the page narrating every REST call, status transition and the webhooks a production backend would receive.
* A single **guided walkthrough** (auto-opens on first visit, re-launchable from the header) explains the page, then walks you through one real payout end-to-end — funding, cash-out, operator approval, on-chain verification.
* The **player selector** lists every player of your vault (not just demo-created ones); its last option deep-links to `/dashboard/vault/users?create=1`, which auto-opens the create-user dialog.
* The **token selector** lists your enabled tokens; its last option deep-links to `/dashboard/vault/settings#tokens`.
* The demo's browser-local casino ledger credits completed deposits using the settled net asset (including converted target output). When you attach an existing player, it reconciles completed deposits against that player's withdrawal history so the displayed balance reflects real Vault activity without replaying funds that were already withdrawn. Production casinos keep this idempotent ledger in their own backend and update it from signed webhooks.

## API Integration

### Authentication

All API endpoints require an API key in the `x-api-key` header:

```bash
curl -X GET "https://app.makapay.io/api/vault/v1/config" \
  -H "x-api-key: YOUR_API_KEY"
```

### Vault Configuration Endpoints

You can fully configure your vault via the API — no dashboard needed. See the [API Reference](https://docs.makapay.io/developers/api-reference.md#vault-configuration-api) for detailed documentation of all parameters and response formats.

> **Note on `walletAddress`:** if your account has [Recipient Wallets](https://docs.makapay.io/security/recipient-wallets.md) enforcement enabled, the `walletAddress` you pass to `POST` or `PATCH /api/vault/v1/config` must be in your verified address book. Unknown addresses return **HTTP 422** with `code: "RECIPIENT_NOT_ALLOWLISTED"` and a `helpUrl` pointing at the dashboard. Add the address under **Dashboard → Settings → Recipient Wallets** (requires a 2FA code) and retry.

#### Changing your payout wallet

Change `walletAddress` in **Dashboard → Platform Wallets → Settings** (you review what happens to every user before confirming) or with `PATCH /api/vault/v1/config`. What happens depends on how each user's deposit address was created:

* **Auto-Conversion users keep their deposit address.** Their future deposits pay out to the new wallet. Where a payout is already recorded on-chain for an address, it is updated automatically, usually within a few minutes, followed by a short safety window. Deposits that arrive during the update stay in their deposit address and are paid out to the new wallet as soon as it completes. Settings shows the progress for every user.
* **All other users get a new deposit address**, because the wallet is part of how their address is derived. Fetch and display the new address. The previous address stays monitored, but deposits to it are still paid out to the wallet it was created for, so keep access to that wallet.
* Before the change, the dashboard asks you to confirm separately if any user gets a new address, or if any older address keeps paying your old wallet.
* Each user's page lists every deposit address they have had, where each one pays out (and whether it follows wallet changes), and the wallet each deposit was actually paid to.
* Re-submitting your current wallet (including the same address in different letter case) changes nothing.
* A wallet change is unavailable while a Vault contract upgrade is still running. Finish or retry the upgrade first.

On sandbox, a `POST` or `PATCH` request with `autoConversion.enabled: true` returns **HTTP 403** with `code: "CONVERSION_UNAVAILABLE_ON_SANDBOX"`. Create or update the Vault with Auto-Conversion disabled. Sandbox Vault deposits settle in the deposited asset without conversion. New sandbox accounts use ordinary V2 addresses; already-latched accounts retain router-salted derivation and signed passthrough.

| Method | Endpoint                        | Description               |
| ------ | ------------------------------- | ------------------------- |
| POST   | `/api/vault/v1/config`          | Create vault account      |
| GET    | `/api/vault/v1/config`          | Get vault configuration   |
| PATCH  | `/api/vault/v1/config`          | Update vault settings     |
| POST   | `/api/vault/v1/config/tokens`   | Add accepted token        |
| DELETE | `/api/vault/v1/config/tokens`   | Remove accepted token     |
| GET    | `/api/vault/v1/config/webhooks` | Get webhook config        |
| PUT    | `/api/vault/v1/config/webhooks` | Create/update webhook     |
| DELETE | `/api/vault/v1/config/webhooks` | Delete webhook            |
| POST   | `/api/vault/v1/config/webhooks` | Regenerate webhook secret |

#### Quick Setup Example

```bash
# 1. Create your vault
curl -X POST https://app.makapay.io/api/vault/v1/config \
  -H "x-api-key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "businessName": "My Casino",
    "walletAddress": "0x742d35Cc6634C0532925a3b844Bc9e7595f8fE00",
    "enabledTokens": [
      {"chainId": 137, "token": "0xc2132D05D31c914a87C6611C10748AEb04B58e8F", "tokenSymbol": "USDT"},
      {"chainId": 56, "token": "0x55d398326f99059ff775485246999027b3197955", "tokenSymbol": "USDT"}
    ]
  }'

# 2. Set up a webhook
curl -X PUT https://app.makapay.io/api/vault/v1/config/webhooks \
  -H "x-api-key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://yoursite.com/webhook/vault",
    "events": [
      "deposit.completed", "deposit.failed",
      "withdrawal.requested", "withdrawal.completed",
      "withdrawal.rejected", "withdrawal.failed"
    ]
  }'
# → Save the `secret` from the response for signature verification

# 3. Generate deposit addresses for your users
curl -X POST https://app.makapay.io/api/vault/v1/users \
  -H "x-api-key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"externalUserId": "player_42", "chainId": 137, "tokenAddress": "0xc2132D05D31c914a87C6611C10748AEb04B58e8F"}'
```

### Read-Only Endpoints

#### Get Vault Configuration

```http
GET /api/vault/v1/config
```

**Response:**

```json
{
  "success": true,
  "data": {
    "publicId": "biz_abc123",
    "businessName": "My Casino",
    "walletAddress": "0x...",
    "feeBps": 100,
    "isActive": true,
    "enabledTokens": [
      {
        "chainId": 11155111,
        "tokenSymbol": "USDT",
        "tokenAddress": "0x..."
      }
    ]
  }
}
```

#### Create User / Get Deposit Address

```http
POST /api/vault/v1/users
Content-Type: application/json

{
  "externalUserId": "user_123",
  "chainId": 11155111,
  "tokenAddress": "0x..."
}
```

**Response:**

```json
{
  "success": true,
  "data": {
    "depositAddress": "0x...",
    "externalUserId": "user_123",
    "chainId": 11155111,
    "tokenSymbol": "USDT",
    "isNew": true
  }
}
```

#### Get User Info

```http
GET /api/vault/v1/users?externalUserId=user_123
```

**Response:**

```json
{
  "success": true,
  "data": {
    "externalUserId": "user_123",
    "depositAddress": "0x...",
    "chainId": 11155111,
    "tokenSymbol": "USDT",
    "totalDeposited": "1000000000",
    "depositCount": 5,
    "lastDepositAt": 1704067200000
  }
}
```

#### List Deposits

```http
GET /api/vault/v1/deposits?limit=50&status=completed
```

**Query Parameters:**

* `limit` - Max results (default: 50, max: 100)
* `cursor` - Opaque `continueCursor` from the previous page; omit on the first request
* `status` - Filter by status: `detected`, `processing`, `converting`, `completed`, `failed`
* `externalUserId` - Filter by user

**Response:**

```json
{
  "success": true,
  "data": {
    "deposits": [
      {
        "depositId": "abc123",
        "externalUserId": "user_123",
        "amount": "500000000000000000",
        "fee": "0",
        "netAmount": "500000000000000000",
        "decimals": 18,
        "formattedAmount": "0.5",
        "formattedFee": "0",
        "formattedNetAmount": "0.5",
        "chainId": 1,
        "tokenSymbol": "ETH",
        "tokenAddress": "0x0000000000000000000000000000000000000000",
        "status": "completed",
        "depositTxHash": "0x...",
        "processTxHash": "0x...",
        "createdAt": 1704067200000,
        "processedAt": 1704067260000,
        "conversion": {
          "mode": "convert",
          "targetToken": "0x...",
          "targetTokenSymbol": "USDT",
          "grossOut": "1250000000",
          "feeAmount": "12500000",
          "netOut": "1237500000",
          "realizedOut": "1237500000",
          "affiliateFeeBps": 6,
          "outcome": "converted",
          "attempts": 1,
          "targetDecimals": 6,
          "formattedGrossOut": "1250",
          "formattedFeeAmount": "12.5",
          "formattedNetOut": "1237.5",
          "formattedRealizedOut": "1237.5"
        }
      }
    ],
    "total": 1,
    "continueCursor": "opaque-cursor",
    "isDone": false
  }
}
```

`decimals` / `formatted*` are described under [Amounts, `decimals`, and `formatted*` fields](#amounts-decimals-and-formatted-fields). Scam "airdrop" tokens that bots send to deposit addresses (e.g. a token whose symbol is a claim website) are filtered out of this list and never emit a webhook — see [Spam tokens](#spam-tokens).

Continue requesting with `?cursor=<continueCursor>` until `isDone` is `true`. When `externalUserId` is present, filtering happens before pagination, so each page belongs to that player.

For `conversion.outcome: "converted"`, credit `conversion.netOut` in `conversion.targetToken` (or use the historical `conversion.realizedOut` fallback). The top-level `amount`, `fee`, `netAmount`, and token fields remain source-accounting fields. For a degraded passthrough or a deposit without `conversion`, credit the top-level `netAmount` in the source token.

#### Get Supported Tokens (Public)

```http
GET /api/vault/v1/business/{publicId}/tokens
```

No authentication required. Returns publicly available token information.

**Response:**

```json
{
  "tokens": [
    {
      "chainId": 11155111,
      "symbol": "USDT",
      "address": "0x..."
    },
    {
      "chainId": 11155111,
      "symbol": "USDC",
      "address": "0x..."
    }
  ]
}
```

## Withdrawals

Withdrawals are **non-custodial**: Makapay never holds or moves your funds. Your backend submits a withdrawal request, the request appears in your Makapay dashboard (Platform Wallets → Withdrawals), and an operator approves it by signing the payout **from your own wallet** (browser wallet or WalletConnect QR). Makapay then verifies the transaction on-chain and notifies your backend. Makapay charges no fee on withdrawals; the wallet that signs the payout pays the on-chain network gas directly.

### How It Works

Who does what, in order:

1. **Player** asks to withdraw in your cashier.
2. **Your backend** debits the player's balance, then sends the request to Makapay (one `POST`).
3. **Makapay** stores the request as `pending`, notifies your backend (webhook) and your operator (dashboard + Telegram).
4. **Your operator** opens the Makapay dashboard and clicks **Approve** (their wallet pops up and signs the payout from your wallet) or **Reject**.
5. **Makapay** watches the blockchain and only marks the request `completed` after the exact transfer — right token, right sender, right recipient, right amount — is confirmed on-chain.
6. **Your backend** reacts to the final webhook: `completed` → show the player it's paid; `rejected` → put the money back on their balance.

```mermaid
sequenceDiagram
    autonumber
    actor Player
    participant Casino as Your Backend
    participant Makapay
    actor Operator as Your Operator
    participant Chain as Blockchain

    Player->>Casino: Requests withdrawal in your cashier
    Casino->>Casino: Debit the player's balance FIRST
    Casino->>Makapay: POST /api/vault/v1/withdrawals
    Makapay-->>Casino: 200 (status: pending)
    Makapay->>Casino: Webhook: withdrawal.requested
    Makapay->>Operator: Request appears in dashboard (+ Telegram)

    alt Operator approves
        Operator->>Chain: Signs payout from YOUR wallet
        Makapay->>Chain: Verifies transfer: token + sender + recipient + amount
        Chain-->>Makapay: Confirmed (3 blocks)
        Makapay->>Casino: Webhook: withdrawal.completed
        Casino->>Player: Show "paid" + transaction link
    else Operator rejects (or you cancel via DELETE)
        Makapay->>Casino: Webhook: withdrawal.rejected
        Casino->>Casino: Re-credit the player's balance
        Casino->>Player: Funds returned to balance
    end
```

### Your Integration: Three Things to Build

Everything else — the approval queue, the wallet signing, the on-chain verification — happens in the Makapay dashboard. Your backend only needs:

1. **Send the request.** When a player asks to withdraw: debit their balance in your system **first**, then call `POST /api/vault/v1/withdrawals` with your own withdrawal ID (`externalWithdrawalId`). If your call times out, retry with the **same** ID — you'll get the same request back, never a duplicate.
2. **Handle two webhooks.**
   * `withdrawal.completed` → the payout is on-chain and final. Show the player it's paid. Do nothing to the balance (you already debited it).
   * `withdrawal.rejected` → put the money back on the player's balance. This is the only event that means "re-credit".
3. **Run a reconciliation check (recommended).** Every few minutes, call `GET /api/vault/v1/withdrawals?status=pending` (and `?status=rejected`) and compare against your records — this catches anything a webhook outage missed.

Three rules that keep the money right:

* **Never re-credit on `failed`.** A failed request means the operator is investigating (for example a transaction that couldn't be verified). Makapay does not tell you a payout failed unless it's certain — wait for the final `rejected` or `completed`.
* **Never create a second request for the same withdrawal.** Reuse your `externalWithdrawalId` on retries; it is the idempotency key.
* **Debit before you call, re-credit only on `rejected`.** The player's balance in your system and the request lifecycle then always agree.

### Withdrawal Lifecycle

| Status       | Meaning                                                                                                          |
| ------------ | ---------------------------------------------------------------------------------------------------------------- |
| `pending`    | Awaiting operator decision in the dashboard                                                                      |
| `approving`  | Operator is signing the payout in their wallet                                                                   |
| `confirming` | Payout transaction broadcast — Makapay is verifying it on-chain                                                  |
| `completed`  | Payout verified on-chain (token, sender, recipient, and amount all match) and past 3 block confirmations — final |
| `rejected`   | Declined by the operator or cancelled via API — return the funds to the player's balance                         |
| `failed`     | Payout transaction reverted or could not be verified                                                             |

```mermaid
stateDiagram-v2
    [*] --> pending: POST /api/vault/v1/withdrawals
    pending --> approving: Operator clicks Approve + live USD quote is pinned
    pending --> rejected: Operator rejects / you cancel (DELETE)
    approving --> pending: Operator closes the wallet without signing
    approving --> confirming: Wallet signs, payout broadcast
    confirming --> completed: Verified on-chain + 3 confirmations
    confirming --> failed: Reverted or could not be verified
    failed --> confirming: Operator re-verifies in dashboard
    failed --> pending: Operator resets in dashboard
    completed --> [*]
    rejected --> [*]
```

When you receive `withdrawal.rejected`, re-credit the player's balance. When you receive `withdrawal.completed`, the payout is final. `failed` is never final on its own — the operator resolves it from the dashboard, and your backend just waits for the next event.

### Create Withdrawal Request

```http
POST /api/vault/v1/withdrawals
```

**Request Body:**

```json
{
  "externalUserId": "user_123",
  "externalWithdrawalId": "wd_789",
  "chainId": 11155111,
  "tokenAddress": "0x...",
  "amountUsd": "100.00",
  "destinationAddress": "0x...",
  "metadata": "optional, echoed back in webhooks (max 1KB)"
}
```

* `externalWithdrawalId` is **your** withdrawal ID and acts as an idempotency key: retrying the same request returns the existing withdrawal instead of creating a duplicate. Always debit the player's balance *before* calling this endpoint, and only restore it on `withdrawal.rejected` / after a cancel.
* `amountUsd` is the player-requested USD value with up to two decimal places. The request chooses the payout token and network, but does not lock a token quantity yet.
* When the operator approves, Makapay resolves the current token/USD price through the shared Alchemy price service, rounds the payout up to the token's smallest unit, stores that exact quote, and gives the wallet that amount to sign. The on-chain verifier checks the stored amount.
* Legacy integrations may still send `amount` as a raw token-unit string instead of `amountUsd`, but must provide exactly one of the two fields.
* The token must be enabled for your vault. Use the zero address (`0x0000000000000000000000000000000000000000`) as `tokenAddress` to withdraw the chain's native token.
* Solana withdrawals are not yet available (`SOLANA_WITHDRAWALS_NOT_IMPLEMENTED`, HTTP 501).

**Response:**

```json
{
  "success": true,
  "data": {
    "withdrawalId": "abc123",
    "externalWithdrawalId": "wd_789",
    "externalUserId": "user_123",
    "destinationAddress": "0x...",
    "amount": null,
    "requestedAmountUsd": "100.00",
    "quotedTokenPriceUsd": null,
    "quotedPriceSource": null,
    "quotedAt": null,
    "decimals": 6,
    "tokenAddress": "0x...",
    "tokenSymbol": "USDT",
    "chainId": 11155111,
    "status": "pending",
    "payoutTxHash": null,
    "rejectionReason": null,
    "metadata": null,
    "createdAt": 1704067200000,
    "resolvedAt": null,
    "isNew": true
  }
}
```

### List / Reconcile Withdrawals

```http
GET /api/vault/v1/withdrawals?status=pending&limit=50
GET /api/vault/v1/withdrawals?externalWithdrawalId=wd_789
```

**Query Parameters:**

* `limit` - Max results (default: 50, max: 100)
* `cursor` - Opaque `continueCursor` from the previous page; omit on the first request
* `status` - Filter by status (see lifecycle table)
* `externalUserId` - Filter by user
* `externalWithdrawalId` - Exact lookup by your withdrawal ID

List responses include `continueCursor` and `isDone`. Continue until `isDone` is `true` when performing a full reconciliation. Use this endpoint to reconcile state if your webhook endpoint was down.

### Cancel Withdrawal Request

```http
DELETE /api/vault/v1/withdrawals?externalWithdrawalId=wd_789
```

Only `pending` requests can be cancelled (e.g. the player cancelled in your cashier). Cancelling resolves the request as `rejected` with `rejectionReason: "cancelled_by_casino"` and fires a `withdrawal.rejected` webhook.

## Webhooks

### Webhook Events

| Event                  | Description                                          |
| ---------------------- | ---------------------------------------------------- |
| `deposit.completed`    | Deposit successfully processed                       |
| `deposit.failed`       | Deposit processing failed                            |
| `deposit.*`            | All deposit events                                   |
| `withdrawal.requested` | A withdrawal request was created                     |
| `withdrawal.completed` | Payout verified on-chain — final                     |
| `withdrawal.rejected`  | Request declined or cancelled — re-credit the player |
| `withdrawal.failed`    | Payout transaction reverted or could not be verified |
| `withdrawal.*`         | All withdrawal events                                |

Omitting `events` on create subscribes the webhook to every event above. If you pass an explicit list, `withdrawal.rejected` and `withdrawal.completed` are the two you cannot skip: rejection is the signal to give the player their balance back, and completion is the signal that the payout is final.

Withdrawal webhooks are retried up to 3 times (immediately, after 5 minutes, and after 10 minutes) until your endpoint returns a 2xx. Make your handler idempotent on `(event, data.withdrawalId)`.

**Withdrawal payload `data`:** `withdrawalId`, `externalWithdrawalId`, `externalUserId`, `requestedAmountUsd`, `amount`, `decimals`, `quotedTokenPriceUsd`, `quotedPriceSource`, `quotedAt`, `tokenSymbol`, `tokenAddress`, `chainId`, `destinationAddress`, `status`, `payoutTxHash`, `rejectionReason`, `metadata`, `requestedAt`, `resolvedAt`. For USD requests, `amount` and quote fields are `null` on `withdrawal.requested` and are populated after approval. Signature verification is identical to deposit webhooks (below).

### Webhook Payload

```json
{
  "event": "deposit.completed",
  "data": {
    "depositId": "abc123",
    "externalUserId": "user_123",
    "amount": "4000000000000000",
    "fee": "40000000000000",
    "netAmount": "3960000000000000",
    "decimals": 18,
    "formattedAmount": "0.004",
    "formattedFee": "0.00004",
    "formattedNetAmount": "0.00396",
    "tokenSymbol": "ETH",
    "tokenAddress": "0x0000000000000000000000000000000000000000",
    "chainId": 1,
    "depositAddress": "0x...",
    "status": "completed",
    "depositTxHash": "0x...",
    "processTxHash": "0x...",
    "timestamp": 1704067260000
  },
  "timestamp": 1704067260000
}
```

#### Amounts, `decimals`, and `formatted*` fields

`amount`, `fee`, and `netAmount` are **integer strings in the token's smallest unit** (wei for ETH, `1e-6` units for USDT/USDC), never decimal token amounts. `1 ETH` is `"1000000000000000000"` (18 zeroes); `1 USDT` is `"1000000"` (6 zeroes). Every token has its own `decimals`. Credit the player with `netAmount / 10^decimals`, and **never** with the raw string — crediting `"3960000000000000"` as dollars is how a $10 ETH deposit becomes a multi-trillion balance.

To make that cross-check trivial, every deposit webhook and every row of `GET /api/vault/v1/deposits` also carries:

| Field                | Meaning                                                                       |
| -------------------- | ----------------------------------------------------------------------------- |
| `decimals`           | Decimals for `amount` / `fee` / `netAmount` (18 for ETH, 6 for USDT/USDC, …)  |
| `formattedAmount`    | `amount` as an exact decimal string, e.g. `"0.004"`                           |
| `formattedFee`       | `fee` as an exact decimal string                                              |
| `formattedNetAmount` | `netAmount` as an exact decimal string — the value to credit in `tokenSymbol` |

For converted deposits the `conversion` object carries the same for the target token: `targetDecimals`, `formattedGrossOut`, `formattedFeeAmount`, `formattedNetOut`, `formattedRealizedOut` — credit `formattedNetOut` in `targetTokenSymbol`.

The `formatted*` strings are plain decimals with no exponent notation and no thousands separators (`"0.000000000000000001"`, not `"1e-18"`). They are `null` only if the raw value could not be parsed, which should never happen — treat `null` as "do not credit, contact support".

Amounts are **token quantities, not USD**. To show a USD figure, multiply by the token's current price (or use the `tokenSymbol` to decide: USDT/USDC are $1 per unit).

### Webhook Signature Verification

If you configure a webhook secret, requests include an `X-Webhook-Signature` header:

```
X-Webhook-Signature: sha256(JSON.stringify(payload) + secret)
```

**Verification Example (Node.js):**

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

function verifyWebhook(payload, signature, secret) {
  const expected = crypto
    .createHash('sha256')
    .update(JSON.stringify(payload) + secret)
    .digest('hex');
  return signature === expected;
}

// In your webhook handler:
app.post('/webhook', (req, res) => {
  const signature = req.headers['x-webhook-signature'];
  const isValid = verifyWebhook(req.body, signature, process.env.WEBHOOK_SECRET);

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

  // Process the webhook...
  const { event, data } = req.body;

  if (event === 'deposit.completed') {
    const converted = data.conversion?.outcome === 'converted';
    const amount = converted
      ? data.conversion.netOut ?? data.conversion.realizedOut
      : data.netAmount;
    const token = converted
      ? data.conversion.targetToken
      : data.tokenAddress;

    // Credit exactly once in the asset that actually settled.
    await creditUserBalance(data.externalUserId, token, amount);
  }

  res.json({ received: true });
});
```

## Integration Examples

### Computing Address On-Chain (Solidity)

```solidity
interface ICasinoWalletFactory {
    function computeAddress(
        string calldata userId,
        address casino
    ) external view returns (address);
}

contract MyIntegration {
    ICasinoWalletFactory public factory =
        ICasinoWalletFactory(0xEbcA32C9C343d6CabbD06E5118193672c4735474);

    function getDepositAddress(string calldata userId) external view returns (address) {
        return factory.computeAddress(userId, address(this));
    }
}
```

### Computing Address Off-Chain (JavaScript)

```javascript
import { createPublicClient, http } from 'viem';
import { sepolia } from 'viem/chains';

const FACTORY_ADDRESS = '0xEbcA32C9C343d6CabbD06E5118193672c4735474';
const FACTORY_ABI = [
  {
    inputs: [
      { name: 'userId', type: 'string' },
      { name: 'casino', type: 'address' }
    ],
    name: 'computeAddress',
    outputs: [{ name: '', type: 'address' }],
    stateMutability: 'view',
    type: 'function'
  }
];

const client = createPublicClient({
  chain: sepolia,
  transport: http()
});

async function getDepositAddress(userId, casinoAddress) {
  const address = await client.readContract({
    address: FACTORY_ADDRESS,
    abi: FACTORY_ABI,
    functionName: 'computeAddress',
    args: [userId, casinoAddress]
  });
  return address;
}

// Usage
const depositAddress = await getDepositAddress('user_123', '0xYourWallet...');
console.log('Deposit to:', depositAddress);
```

### Full Integration Flow

```javascript
// 1. Create user and get deposit address
const response = await fetch('https://app.makapay.io/api/vault/v1/users', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'x-api-key': process.env.MAKAPAY_API_KEY
  },
  body: JSON.stringify({
    externalUserId: 'user_123',
    chainId: 11155111,
    tokenAddress: '0x...' // USDT address
  })
});

const { data } = await response.json();
const depositAddress = data.depositAddress;

// 2. Show address to user (they send tokens here)
console.log('Send USDT to:', depositAddress);

// 3. Handle webhook when deposit is processed
app.post('/webhooks/makapay', async (req, res) => {
  const { event, data } = req.body;

  if (event === 'deposit.completed') {
    const converted = data.conversion?.outcome === 'converted';
    const amount = converted
      ? data.conversion.netOut ?? data.conversion.realizedOut
      : data.netAmount;
    const tokenAddress = converted
      ? data.conversion.targetToken
      : data.tokenAddress;
    const tokenSymbol = converted
      ? data.conversion.targetTokenSymbol
      : data.tokenSymbol;

    // Store balances per chain + token and enforce depositId idempotency.
    await creditUserBalance({
      depositId: data.depositId,
      externalUserId: data.externalUserId,
      chainId: data.chainId,
      tokenAddress,
      amount: BigInt(amount)
    });

    console.log(`Credited ${amount} ${tokenSymbol} to ${data.externalUserId}`);
  }

  res.json({ received: true });
});
```

## Reporting (Backend — Phase 1, Dashboard UI — Phase 2)

Expanded reporting for a casino's own vault account: totals/averages/counts for deposits and withdrawals, a status breakdown, a per-token breakdown, a zero-filled day/month volume time series, live on-chain available balance, and a row-level export feed. All queries/actions are scoped to the caller's own vault account (Clerk identity → `vaultAccounts.by_user`) — none take a `vaultAccountId` argument from the client.

**Explicitly out of scope** (product architecture can't support them): GEO breakdown and "abandoned transaction" tracking.

| Function                        | File                        | Kind   | Purpose                                                                                                                                                                                                              |
| ------------------------------- | --------------------------- | ------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `getVaultReportSummary`         | `convex/vault/reporting.ts` | query  | Deposit/withdrawal count, volume, fees, average, per-status counts, per-token breakdown, stablecoin-equivalent totals, for a `{from, to}` window (default: last 7 days, matching `DateRangeFilter`'s default preset) |
| `getVaultTimeSeries`            | `convex/vault/reporting.ts` | query  | Zero-filled day/month volume buckets (UTC) over `{from, to}`                                                                                                                                                         |
| `getVaultTransactionsForExport` | `convex/vault/reporting.ts` | query  | Row-level feed for CSV/Excel/PDF export, capped via `.take()` (max 5000, default 1000), returns `truncated: boolean`                                                                                                 |
| `getVaultAvailableBalance`      | `convex/vault/balances.ts`  | action | Live on-chain balance per enabled token (native/ERC-20) of the vault's own wallet, plus an in-flight (not-yet-settled deposits) figure                                                                               |

Key accounting rules (shared with `vault/stats.ts` via `convex/vault/lib/accounting.ts`):

* **Never sum raw `netAmount` for a converted deposit.** V2 auto-converted deposits settle in the TARGET token (`conversion.netOut`/`realizedOut`) — use `humanSettlementAmounts()`, the single accounting helper shared by `getVaultStats`, `getDailyStats`, and every reporting query.
* **Cross-token sums are stablecoin-only.** Not every vault token is a stablecoin (ETH/BNB/SOL/MAKA are enabled on some chains). A "total across all tokens" is only ever computed from tokens flagged `isStablecoin` in `SUPPORTED_TOKENS` (`isStablecoinToken()`), and is always labeled `...StablecoinUsd`/`...StablecoinVolumeUsd` — never a plain "total". Everything else is broken out per-token, unsummed.
* **Withdrawal amounts** follow the existing convention: `requestedAmountUsd ?? humanizeAmount(amount, decimals)`.
* **Time-basis divergence (intentional):** both tables are range-scanned on `createdAt` (via the new `by_account_created` index). Within that set, withdrawal per-status *counts* use `createdAt`, but completed-withdrawal *volume* additionally requires `resolvedAt ?? createdAt` to fall inside the window — mirroring `getWithdrawalStats`'s existing 30-day-volume convention. A request created near the end of a window but resolved after it is counted in the status breakdown but not in that window's volume.
* **Export settlement token symbol:** converted deposits carry a `settlementTokenSymbol` distinct from `tokenSymbol` (the source token), so exports never mislabel a converted amount under the wrong symbol.
* `vaultUsers.lastKnownBalance` is NOT a balance rollup (it's the un-swept residual at a deposit address) — never used for reporting balance figures.
* On-chain balance lookups use the same RPC coverage as `depositProcessor.ts` (every vault-supported chain including MakaChain), NOT `walletBalances.ts` (Alchemy-keyed by deBridge chain IDs, which don't line up with vault chain IDs).
* Every raw table scan is bounded (`.take()`, never an unbounded `.collect()`). If a merchant's history ever exceeds the bound, the planned fix is a precomputed daily-rollup table (not built in this phase).

**Dashboard UI (Phase 2)**: `/dashboard/vault/reports` (a new "Reports" tab on `VaultSubNav`) renders this data — `src/app/dashboard/vault/reports/page.tsx`:

* A single `DateRangeFilter` (default preset `7d`, same as the backend's own default window) feeds `getVaultReportSummary` and `getVaultTimeSeries` reactively via `useQuery`. Granularity auto-picks `"day"` for ranges ≤ 92 days, else `"month"`.
* **"All" preset caveat**: `DateRangeFilter`'s "All" preset yields `{from: undefined, to: undefined}`, but `resolveRange()` in `reporting.ts` treats an *omitted* `from` as "default to the last 7 days" (for hypothetical callers that don't pass a range at all) — NOT as "no lower bound". The reports page maps `preset === "all"` to an explicit `from: 0` (epoch start) before calling `getVaultReportSummary` / `getVaultTimeSeries` / passing props to `ExportVaultReportModal`, so "All" never silently narrows to 7 days. `getVaultTimeSeries`'s `from`/`to` args are non-optional, so this page must always resolve a concrete number itself — never send `undefined` through when the user picked "All".
* Available balance is fetched from `getVaultAvailableBalance` via `useAction` — NOT automatically on mount, since it makes live RPC calls. The UI shows an explicit "Load Balance" / "Refresh" button and a loading state; the full per-token list is collapsible, and any per-token `error` string is shown inline rather than hidden.
* Stat cards explicitly label `stablecoinDepositVolumeUsd` / `stablecoinWithdrawalVolumeUsd` as "stablecoin-equivalent" — never presented as an unqualified USD total, per the accounting rule above. The "Avg" hint on the Deposits/Withdrawals cards (and the export's summary sheet) uses the stablecoin-gated `stablecoinDepositAverage` / `stablecoinWithdrawalAverage` fields, NOT the raw `deposits.average` / `withdrawals.average` — those are cross-token sums (e.g. 2.5 ETH + 100 USDT summed as if both were $1) and must never be labeled or formatted as stablecoin-equivalent USD. `deposits.average` / `withdrawals.average` stay in the summary payload as an honest "across-all-tokens, unitless" figure but are not surfaced in any "(stablecoin-equivalent)" UI element.
* The volume-over-time chart's `depositVolume`/`withdrawalVolume` bucket fields (`getVaultTimeSeries`) are likewise gated to stablecoin tokens only — the chart card explicitly says "Stablecoin-equivalent volume" under its title so viewers don't read it as an all-token USD total. `depositCount`/`withdrawalCount` stay ungated (raw event counts, not dollar figures).
* Status breakdowns render `deposits.statusCounts` / `withdrawals.statusCounts` via `StatusBadge`.
* The volume-over-time chart is a hand-rolled dependency-free component, `src/components/vault/VaultVolumeChart.tsx` (no chart library in this repo) — paired bars per bucket (deposit vs withdrawal), native `title` tooltip, `EmptyState` when a range has zero activity in every bucket. Bucket labels build a UTC-midnight `Date` and MUST format it with `toLocaleDateString(..., { timeZone: "UTC" })` — omitting `timeZone: "UTC"` shifts the label by a day/month for any viewer in a negative-UTC-offset timezone, since all bucketing (`bucketKeyUtc` in `reporting.ts`) is UTC.
* A `truncated: true` flag from the summary/time-series queries surfaces as an inline notice to narrow the date range, rather than silently under-reporting.
* **Export (Phase 3)**: `src/components/vault/ExportVaultReportModal.tsx`, opened from an "Export" button in the reports page's `PageHeader` actions (next to `DateRangeFilter`). Reuses the current date range and the already-fetched `getVaultReportSummary` result as props — never adds a second range picker and never refetches the summary itself.
  * Fetches `getVaultTransactionsForExport` on click only (via `useConvex()`, not a reactive `useQuery`) with `kind: "all", limit: 5000`, since this can return up to 5000 rows and must not re-run on every deposit/withdrawal webhook. A `truncated: true` response surfaces as a toast warning rather than silently truncating.
  * Formats: **CSV** (flat "Transactions" rows only — a CSV can't hold two sheets), **Excel** (two sheets: "Summary" built from the summary prop, "Transactions" row-level data), **PDF** (MAKAPAY header block reused verbatim from `ExportPaymentsModal.tsx`, landscape A4, a summary `autoTable` above a transactions `autoTable`).
  * Converted deposits (`settlementTokenSymbol` present and distinct) render as `"<token> (converted to <settlementToken>)"` in every format's Token column, plus a separate "Settled As" column in CSV/Excel — never left ambiguous under the original deposit token symbol.

## Supported Networks

Vault deposit addresses work on every network below. Production uses the mainnets; the sandbox environment uses the testnets. Unless [Auto-Conversion](https://docs.makapay.io/guides/vault-auto-conversion.md) is enabled, deposits settle in the deposited asset.

| Network           | Chain ID | Environment | Status |
| ----------------- | -------- | ----------- | ------ |
| MakaChain         | 777178   | Production  | Active |
| Ethereum          | 1        | Production  | Active |
| Polygon           | 137      | Production  | Active |
| BNB Smart Chain   | 56       | Production  | Active |
| Base              | 8453     | Production  | Active |
| Sepolia Testnet   | 11155111 | Sandbox     | Active |
| MakaChain Testnet | 777177   | Sandbox     | Active |

## Deposit Statuses

| Status       | Description                                                                                  |
| ------------ | -------------------------------------------------------------------------------------------- |
| `detected`   | Deposit detected, awaiting processing                                                        |
| `processing` | Currently being processed on-chain                                                           |
| `converting` | Auto-Conversion is being quoted, executed, or retried; the deposit has not yet been credited |
| `completed`  | Successfully processed, funds sent to wallet                                                 |
| `failed`     | Processing failed (will retry automatically)                                                 |

## Best Practices

### User ID Guidelines

* Use unique, stable identifiers (database IDs, UUIDs)
* Don't use email addresses (may change)
* Don't use session tokens (temporary)
* Keep IDs under 100 characters

### Security

1. **Store API keys securely** - Use environment variables, never commit to code
2. **Verify webhook signatures** - Always validate the `X-Webhook-Signature` header
3. **Use HTTPS** - All webhook endpoints must use HTTPS
4. **Idempotency** - Handle duplicate webhook deliveries gracefully

### Error Handling

1. **Check deposit status** - Poll the deposits endpoint if webhooks fail
2. **Retry logic** - Failed deposits are automatically retried
3. **Monitor failed deposits** - Set up alerts for repeated failures

## Troubleshooting

### Deposit Not Detected

1. Verify the correct deposit address was used
2. Check the token is in the enabled tokens list
3. Ensure the deposit meets that token's configured USD minimum (defaults to $1.00). Native assets are priced at detection time; there is no blanket `0.001 ETH` / `0.001 POL` cutoff. During a temporary price-oracle outage, a small anti-spam native fallback of `> 0.0001` is used.
4. Wait for block confirmations

### Webhook Not Received

1. Verify webhook URL is accessible from the internet
2. Check webhook is enabled and active
3. Ensure the event type is selected
4. Check your server logs for incoming requests

### Spam Tokens

Deposit addresses are public, so bots occasionally "airdrop" worthless scam tokens to them — typically with a claim website as the token symbol or name (`claim-usd.com`, `www.usdt-reward.io`) and an absurd balance. They have no value and no effect on your real deposits.

MakaPay filters them automatically when a token that is **not** in your enabled-token list arrives:

* symbol or name contains a URL / bare domain, or airdrop-scam vocabulary (`claim`, `reward`, `airdrop`, `bonus`, …), or
* the token has no market price in Alchemy's price feed.

A filtered token is never shown on the dashboard, never returned by `GET /api/vault/v1/deposits`, and never emits a webhook. Your enabled tokens and native assets (ETH, BNB, POL, …) are never filtered, and a genuine non-enabled token that is not a scam still appears as a stranded deposit for manual recovery. If you believe a real token was filtered, contact support — the record is kept and can be restored.

### Process Transaction Failed

1. Check the casino wallet address is correct
2. Verify sufficient gas on the processing account
3. Check the token contract is valid
4. Review error message in the deposit record

## Rate Limits

| Endpoint      | Limit    |
| ------------- | -------- |
| Create User   | 100/min  |
| Get User      | 1000/min |
| List Deposits | 100/min  |
| Get Config    | 100/min  |

## Support

* **Documentation**: [docs.makapay.com](https://docs.makapay.io)
* **GitHub Issues**: [github.com/makapay/issues](https://github.com/makapay/issues)
* **Email**: <support@makapay.com>


---

# 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 by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.makapay.io/guides/vault.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
