For the complete documentation index, see llms.txt. This page is also available as Markdown.

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

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:

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:

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:

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.

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.

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

  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.

  1. 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.

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

Vault Configuration Endpoints

You can fully configure your vault via the API — no dashboard needed. See the API Reference for detailed documentation of all parameters and response formats.

Note on walletAddress: if your account has Recipient Wallets 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

Read-Only Endpoints

Get Vault Configuration

Response:

Create User / Get Deposit Address

Response:

Get User Info

Response:

List Deposits

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:

decimals / formatted* are described under 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.

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)

No authentication required. Returns publicly available token information.

Response:

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.

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

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

Request Body:

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

List / Reconcile Withdrawals

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

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

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:

Verification Example (Node.js):

Integration Examples

Computing Address On-Chain (Solidity)

Computing Address Off-Chain (JavaScript)

Full Integration Flow

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

Last updated