Documentation
Build

Integration guide

Sign-in, reading data, sending transactions, real-time updates and errors.

Everything the UI needs is served by this backend. Interactive reference (try requests in the browser): /docs on a running server. Machine-readable spec: openapi.json (generate a typed client with npx openapi-typescript docs/openapi.json -o src/api.d.ts).

#Run it locally in two minutes

You do not need Postgres, Docker or a testnet wallet.

bash
pnpm install
pnpm contracts:compile        # once

pnpm chain:node               # terminal 1: local chain on http://127.0.0.1:8545 (chain id 31337)

NETWORK=local pnpm deploy:contracts     # terminal 2: deploys the contracts + mock tokens, prints keeper keys
# put the three printed *_PRIVATE_KEY lines into .env, then:
NETWORK=local pnpm dev        # API on http://localhost:8080, docs on http://localhost:8080/docs

pnpm seed:local               # terminal 3: creates a lender and a borrower, prints their keys

The local stack uses live HyperCore prices and order books, so the numbers you see are real market data. pnpm seed:local prints two development private keys you can import into MetaMask/Rabby (network: RPC http://127.0.0.1:8545, chain id 31337).

Without any deployment (NETWORK=testnet today) the API still serves prices, order books, execution estimates and risk analytics; lending endpoints answer 503 PROTOCOL_NOT_DEPLOYED. GET /v1/config tells you which mode you are in (deployed), the chain id and all contract and token addresses.

#Conventions

KindFormatExample
Token amountinteger string in base units; pair with the market's decimals"1000000" = 1 USDC
USD value, pricedecimal string"62.4317"
Ratio / rate / APY / health factordecimal string, 1 = 100%"0.0425" = 4.25%
Percentage parameternumber in basis points6000 = 60%
TimeISO-8601 string, or ms epoch where the field ends in Time/At as a number
AddressEIP-55 checksummed in responses; any case accepted in requests

Use viem's parseUnits / formatUnits with decimals for amounts. Never use JS number for token amounts.

Every market can be addressed by symbol or token address: /v1/markets/WHYPE and /v1/markets/0xbA87…5E81 are the same.

#Connecting a wallet and signing in

Reading positions does not require signing in: everything on /v1/accounts/:address is public chain data. Sign-in is only for personal features (notifications, settings).

Sign-in is EIP-4361 (Sign-In with Ethereum):

ts
// 1. ask for a nonce and a ready-to-sign message
const { message } = await api.post("/v1/auth/nonce", {
  address,                                // the connected wallet
  domain: window.location.host,           // must be allow-listed on the server (SIWE_DOMAINS)
  uri: window.location.origin,
});

// 2. the wallet signs it (wagmi: signMessageAsync, viem: walletClient.signMessage)
const signature = await signMessageAsync({ message });

// 3. exchange it for tokens
const { accessToken, refreshToken, expiresIn } = await api.post("/v1/auth/verify", { message, signature });
  • Send Authorization: Bearer <accessToken> on /v1/auth/me, /v1/me/*.
  • The access token lasts 15 minutes. Call POST /v1/auth/refresh { refreshToken } to get a new pair. Refresh tokens are single-use: always store the new one. Reusing an old one revokes the session (the user has to sign in again).
  • POST /v1/auth/logout ends the session.
  • Signing in never moves funds and never approves anything.

#Reading data

ScreenCall
Markets tableGET /v1/markets
Market page (with rate curve)GET /v1/markets/:asset, charts: GET /v1/markets/:asset/history?hours=168
Dashboard / positionsGET /v1/accounts/:address
HistoryGET /v1/accounts/:address/activity?limit=25&cursor=
Price, spread, depthGET /v1/prices/:symbol
Order bookGET /v1/prices/:symbol/orderbook?levels=25
"What would I get if I sold X?"GET /v1/prices/:symbol/estimate?side=sell&size=1000
Risk parametersGET /v1/risk, GET /v1/risk/:symbol
Protocol totalsGET /v1/stats
Fee engine / transparencyGET /v1/fees (incl. launchpadSources: the Montra creator fees collected), /v1/fees/distributions, /v1/fees/allocation-history
LiquidationsGET /v1/liquidations, GET /v1/liquidations/:id
RewardsGET /v1/accounts/:address/rewards

#The account view

GET /v1/accounts/:address returns one entry per market (so it also carries wallet balances and allowances for markets the user has not touched yet):

jsonc
{
  "health": {
    "healthFactor": "1.4",            // null when there is no debt; below 1 = liquidatable
    "status": "healthy",              // no_debt | healthy | at_risk | liquidatable
    "collateralUsd": "40000",
    "debtUsd": "20000",
    "borrowLimitUsd": "24000",        // how much may be borrowed in total
    "liquidationLimitUsd": "28000",   // liquidation starts when debt exceeds this
    "borrowLimitUsedBps": 8333,
    "executableCollateralUsd": "39920.5",        // what the collateral would fetch on HyperCore now
    "liquidityAdjustedHealthFactor": "1.397"
  },
  "positions": [{
    "symbol": "WHYPE", "decimals": 18,
    "supplied": "1000000000000000000000", "suppliedUsd": "40000",
    "borrowed": "0", "isCollateral": true,
    "maxWithdraw": "166666666666666666666",     // use for the "max" button
    "maxBorrow": "0",
    "liquidationPriceUsd": "28.5714",           // null for USDC
    "walletBalance": "0", "allowance": "0"
  }]
}

Two numbers are specific to this protocol and worth showing:

  • risk.effectiveLtvBps / effectiveLiquidationThresholdBps on a market: the LTV and threshold after the liquidity-aware haircut. They move with order-book depth and volatility.
  • executableCollateralUsd vs collateralUsd: reference value versus what the order book would actually pay.

#Previewing an action

Before the user confirms, show what will happen:

ts
const preview = await api.post(`/v1/accounts/${address}/preview`, {
  action: "borrow",                 // supply | withdraw | borrow | repay | enableCollateral | disableCollateral
  asset: "USDC",
  amount: parseUnits("5000", 6).toString(),
});
// preview.allowed, preview.problems (e.g. ["INSUFFICIENT_COLLATERAL"]),
// preview.before.healthFactor, preview.after.healthFactor

problems codes: ZERO_AMOUNT, INSUFFICIENT_WALLET_BALANCE, INSUFFICIENT_SUPPLY_BALANCE, INSUFFICIENT_POOL_LIQUIDITY, INSUFFICIENT_COLLATERAL, SUPPLY_CAP_EXCEEDED, BORROW_CAP_EXCEEDED, SUPPLY_PAUSED, BORROW_PAUSED, ASSET_FROZEN, PRICE_STALE, NO_DEBT, NOT_COLLATERAL_ASSET, LIQUIDATION_IN_PROGRESS, PAUSED, NOTHING_TO_CLAIM.

A market whose risk.frozen is true accepts no new borrowing against or of that asset (see risk.freezeReasons: e.g. PERP_DIVERGENCE, THIN_BOOK, PRICE_WARMUP). Repaying, supplying and withdrawing within limits always work. Grey out the borrow button rather than letting the user hit 422.

#Sending transactions

The backend is non-custodial. It never sees a private key and never sends a transaction for a user. It builds the calldata; the wallet signs and sends it.

ts
const { steps } = await api.post("/v1/tx/supply", {
  account: address,
  asset: "WHYPE",
  amount: parseUnits("10", 18).toString(),
});

for (const step of steps) {               // e.g. [approve, supply] — send in order
  const hash = await walletClient.sendTransaction({
    to: step.to, data: step.data, value: BigInt(step.value),
  });
  await publicClient.waitForTransactionReceipt({ hash });
}
// then refetch /v1/accounts/:address
EndpointBodyNotes
POST /v1/tx/supplyaccount, asset, amountadds an approve step when the allowance is too low
POST /v1/tx/withdrawaccount, asset, amount | "max""max" withdraws everything, no dust
POST /v1/tx/borrowaccount, asset, amount
POST /v1/tx/repayaccount, asset, amount | "max""max" clears the debt including interest that accrues before it is mined
POST /v1/tx/collateralaccount, asset, enabled
POST /v1/tx/claim-rewardsaccount, kind, tokenkind: yield_booster or borrow_rebates

Each step has { kind, chainId, to, data, value, description }. description is a human-readable label you can show in a stepper ("Approve the lending pool to spend WHYPE").

The request is simulated first. If the action would revert on-chain, the API answers 422 ACTION_NOT_ALLOWED with error.details.problems instead of returning a transaction that would fail and waste gas. The same preview object is included in a successful response.

Make sure the wallet is on the right chain (chainId in each step, and in /v1/config). Elysium is not in viem's chain list under that name (viem's elysium export is a different chain): define it with defineChain({ id: 99901 /* testnet 99801 */, … }).

#Real-time updates

ws(s)://<host>/v1/ws — JSON messages. Payloads are identical to the REST responses, so hydrate from REST and then apply the stream.

ts
const ws = new WebSocket(`${WS_URL}/v1/ws`);
ws.onopen = () => {
  ws.send(JSON.stringify({ op: "subscribe", channel: "prices" }));
  ws.send(JSON.stringify({ op: "subscribe", channel: "markets" }));
  ws.send(JSON.stringify({ op: "subscribe", channel: "account", address }));
  ws.send(JSON.stringify({ op: "auth", token: accessToken }));   // optional: notifications
};
ws.onmessage = (e) => {
  const msg = JSON.parse(e.data);
  switch (msg.type) {
    case "prices":       /* msg.data  = GET /v1/prices .prices      (about 1/s)        */ break;
    case "markets":      /* msg.data  = GET /v1/markets .markets    (when it changes)  */ break;
    case "account":      /* msg.data  = GET /v1/accounts/:address   (when it changes)  */ break;
    case "notification": /* msg.data  = one notification                               */ break;
  }
};

Other messages: hello, subscribed, unsubscribed, authenticated, pong (reply to {op:"ping"}), error ({code, message}). Up to 5 account subscriptions per socket and 20 sockets per IP. Notification delivery stops when the access token presented with auth expires (you get an INVALID_ACCESS_TOKEN error message): send a fresh auth after each token refresh. The server pings every 30 s; reconnect with backoff when the socket closes.

Notifications (GET /v1/me/notifications, or the socket): health_warning, liquidatable, liquidation_started, liquidation_settled, liquidation_cancelled.

#Errors

Every error has the same shape and a stable code:

json
{ "error": { "code": "ACTION_NOT_ALLOWED", "message": "This borrow would fail: INSUFFICIENT_COLLATERAL",
             "details": { "problems": ["INSUFFICIENT_COLLATERAL"] } } }
HTTPcodeMeaning
400VALIDATION_ERRORmalformed request; details lists the fields
400UNKNOWN_MARKET, NO_ORDER_BOOK, INVALID_SIZE
400SIWE_DOMAIN_NOT_ALLOWED, SIWE_WRONG_CHAIN, SIWE_INVALID_MESSAGE
401UNAUTHORIZED, INVALID_ACCESS_TOKENmissing/expired access token: refresh it
401SIWE_INVALID_SIGNATURE, SIWE_INVALID_NONCE, SIWE_EXPIREDstart the sign-in again
401INVALID_REFRESH_TOKEN, REFRESH_TOKEN_REUSEDthe user must sign in again
403FORBIDDENadmin-only endpoint
404NOT_FOUND, UNKNOWN_MARKET
422ACTION_NOT_ALLOWEDthe transaction would revert; see details.problems
429RATE_LIMITED600 requests/min per IP (30/min on sign-in endpoints)
502HYPERCORE_UNAVAILABLE, CHAIN_UNAVAILABLEupstream is down; retry
503PROTOCOL_NOT_DEPLOYEDcontracts are not deployed on this network yet
503PRICE_UNAVAILABLE, ORDER_BOOK_UNAVAILABLE, RISK_UNAVAILABLEdata not ready; retry

#Endpoint map

text
GET  /healthz  /readyz  /metrics  /docs
GET  /v1/config
GET  /v1/stats

POST /v1/auth/nonce            POST /v1/auth/verify      POST /v1/auth/refresh
POST /v1/auth/logout   (auth)  GET  /v1/auth/me  (auth)
GET  /v1/me/settings   (auth)  PUT  /v1/me/settings  (auth)
GET  /v1/me/notifications (auth)                         POST /v1/me/notifications/read (auth)

GET  /v1/markets               GET  /v1/markets/:asset   GET /v1/markets/:asset/history
GET  /v1/prices                GET  /v1/prices/:symbol
GET  /v1/prices/:symbol/orderbook    /estimate    /history
GET  /v1/risk                  GET  /v1/risk/:symbol     GET /v1/risk/:symbol/history

GET  /v1/accounts/:address     POST /v1/accounts/:address/preview
GET  /v1/accounts/:address/activity    /liquidations    /rewards

POST /v1/tx/supply  /withdraw  /borrow  /repay  /collateral  /claim-rewards

GET  /v1/liquidations          GET  /v1/liquidations/:id
GET  /v1/fees                  GET  /v1/fees/distributions     GET /v1/fees/allocation-history
GET  /v1/rewards/epochs
GET  /v1/admin/status  (admin)
WS   /v1/ws