Build with AI agents
Everything an AI coding agent needs to wire a frontend to Aethr.
You are an AI coding agent connecting a web frontend to Aethr's backend.
This file is everything you need. Deeper reference: docs/FRONTEND.md.
The machine-readable spec is docs/openapi.json, and live interactive
docs are at <API_URL>/docs.
#What the backend is
A REST + WebSocket API for a lending protocol on Elysium (chain id 99901; testnet 99801, local dev 31337). Users connect a wallet to:
- supply and borrow USDC and WHYPE;
- watch their health factor;
- repay, withdraw and claim rewards.
The backend computes everything the UI shows and builds the transactions. The user's wallet signs and sends them.
#Hard rules
- Never ask for, store or send a private key or seed phrase. The backend never needs one from a user.
- Token amounts are strings of base units (
"1000000"= 1 USDC, which has 6 decimals). Convert with viem'sparseUnitsandformatUnits, using the market'sdecimals. Never use JSnumberfor amounts. - USD values, prices and ratios are decimal strings (
"0.0425"= 4.25%). Basis points are numbers (6000= 60%). - Transactions come from
/v1/tx/*. Send each returned step in order with the user's wallet and wait for each receipt. Do not hand-encode contract calls. - A market is addressed by symbol or token address (
/v1/markets/WHYPE). - Read
GET /v1/configat startup. It gives:chainId;deployed: if false, only price and risk data are available and lending calls return503 PROTOCOL_NOT_DEPLOYED;- contract and token addresses.
#Setup
Recommended stack: React with wagmi + viem (any wallet connector works).
// chain.ts — viem's built-in "elysium" export is a DIFFERENT chain; define it yourself
import { defineChain } from "viem";
export const elysium = defineChain({
id: 99901,
name: "Elysium",
nativeCurrency: { name: "HYPE", symbol: "HYPE", decimals: 18 },
rpcUrls: { default: { http: ["https://rpc.elysium.kinetiq.xyz"] } },
blockExplorers: { default: { name: "Elysium Explorer", url: "https://elysium.kinetiq.xyz/explorer" } },
contracts: { multicall3: { address: "0xcA11bde05977b3631167028862bE2a173976CA11" } },
});Optional typed client: npx openapi-typescript <backend>/docs/openapi.json -o src/api-types.ts.
// api.ts — minimal client with error handling and token refresh
export const API = import.meta.env.VITE_API_URL; // e.g. https://api.yourapp.xyz
export class ApiError extends Error {
constructor(public status: number, public code: string, message: string, public details?: any) { super(message); }
}
let session: { accessToken: string; refreshToken: string } | null = JSON.parse(localStorage.getItem("session") ?? "null");
const save = (s: typeof session) => { session = s; localStorage.setItem("session", JSON.stringify(s)); };
export async function api<T>(method: string, path: string, body?: unknown, auth = false): Promise<T> {
const send = () =>
fetch(API + path, {
method,
headers: {
...(body ? { "content-type": "application/json" } : {}),
...(auth && session ? { authorization: `Bearer ${session.accessToken}` } : {}),
},
body: body ? JSON.stringify(body) : undefined,
});
let res = await send();
if (res.status === 401 && auth && session) {
// access tokens last 15 min; refresh tokens are SINGLE USE: always store the new pair
const r = await fetch(API + "/v1/auth/refresh", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ refreshToken: session.refreshToken }) });
if (r.ok) { save(await r.json()); res = await send(); } else { save(null); }
}
const json = res.status === 204 ? null : await res.json();
if (!res.ok) throw new ApiError(res.status, json?.error?.code, json?.error?.message, json?.error?.details);
return json as T;
}#Connecting a wallet and signing in
You only need sign-in for notifications and settings. Positions are public: read
/v1/accounts/:address right after the wallet connects.
const { message } = await api("POST", "/v1/auth/nonce", { address, domain: window.location.host, uri: window.location.origin });
const signature = await signMessageAsync({ message }); // wagmi
save(await api("POST", "/v1/auth/verify", { message, signature })); // { accessToken, refreshToken, ... }
// sign out: await api("POST", "/v1/auth/logout", {}, true); save(null);domain must be listed in the backend's SIWE_DOMAINS (for local dev, localhost:3000
or localhost:5173 are allowed by default).
#Sending a transaction (the one pattern for every action)
async function run(path: string, body: object) {
try {
const { steps } = await api<{ steps: Array<{ to: `0x${string}`; data: `0x${string}`; value: string; description: string }> }>("POST", path, body);
for (const step of steps) { // e.g. [approve, supply]
setStatus(step.description); // human-readable, show it in a stepper
const hash = await walletClient.sendTransaction({ to: step.to, data: step.data, value: BigInt(step.value) });
await publicClient.waitForTransactionReceipt({ hash });
}
await refetchAccount(); // GET /v1/accounts/:address
} catch (e) {
if (e instanceof ApiError && e.code === "ACTION_NOT_ALLOWED") showProblems(e.details.problems); // the tx would have failed
else throw e;
}
}
run("/v1/tx/supply", { account, asset: "WHYPE", amount: parseUnits("10", 18).toString() });
run("/v1/tx/borrow", { account, asset: "USDC", amount: parseUnits("500", 6).toString() });
run("/v1/tx/repay", { account, asset: "USDC", amount: "max" }); // clears all debt incl. interest
run("/v1/tx/withdraw", { account, asset: "WHYPE", amount: "max" });
run("/v1/tx/collateral", { account, asset: "WHYPE", enabled: false });
run("/v1/tx/claim-rewards", { account, kind: "yield_booster", token: "USDC" }); // or "borrow_rebates"Before the user confirms, show a preview: health factor before and after, and whether the action is allowed:
const p = await api("POST", `/v1/accounts/${account}/preview`, { action: "borrow", asset: "USDC", amount });
// p.allowed, p.problems[], p.before.healthFactor, p.after.healthFactor, p.after.borrowLimitUsedBps#Pages → endpoints
| Page / component | Call | Key fields |
|---|---|---|
| App boot | GET /v1/config | chainId, deployed, tokens, contracts |
| Markets table | GET /v1/markets | symbol, priceUsd, supplyApy, borrowApy, totalSupplyUsd, totalBorrowUsd, utilization, availableLiquidity, risk.effectiveLtvBps, risk.frozen |
| Market page | GET /v1/markets/:asset + /history?hours=168 | rateCurve[] (interest-rate chart), history points |
| Dashboard | GET /v1/accounts/:address | health.healthFactor (null = no debt; <1 liquidatable), health.status, health.borrowLimitUsedBps, positions[] |
| Supply / borrow modal | the position row from the account call | walletBalance, maxWithdraw, maxBorrow (use for the MAX button), liquidationPriceUsd |
| History tab | GET /v1/accounts/:address/activity?limit=25&cursor= | items[].type, txHash, time; paginate with nextCursor |
| Rewards | GET /v1/accounts/:address/rewards | claimable per kind and token |
| Liquidation alert | activeLiquidationId on the account; GET /v1/liquidations/:id | status, timeline[] |
| Prices / order book | GET /v1/prices, /v1/prices/:symbol/orderbook, /estimate?side=sell&size=1000 | midUsd, spreadBps, depth; estimate netUsd vs theoreticalUsd |
| Protocol stats | GET /v1/stats | TVL, debt, insurance fund, bad debt |
| Revenue / transparency | GET /v1/fees | launchpadSources[] (Montra fees collected), allocation[] (the 40/25/15/10/10 split), totals |
| Notifications (signed in) | GET /v1/me/notifications, POST /v1/me/notifications/read | kind: health_warning, liquidatable, liquidation_started, liquidation_settled |
UI rules that matter:
- Health factor colours: ≥ 1.5 green, 1.2–1.5 amber, < 1.2 red.
statusis already computed for you:healthy,at_risk(below 1.2),liquidatable(below 1). - If
risk.frozenis true, disable Borrow for that market and showrisk.freezeReasons. Supply, repay and withdraw still work. - Use the backend's
maxBorrowandmaxWithdrawfor MAX buttons rather than computing your own. - Show
executableCollateralUsdnext tocollateralUsd("what your collateral would sell for right now"). This number is specific to this protocol.
#Live updates (WebSocket)
const ws = new WebSocket(API.replace(/^http/, "ws") + "/v1/ws");
ws.onopen = () => {
ws.send(JSON.stringify({ op: "subscribe", channel: "prices" })); // ~1/s
ws.send(JSON.stringify({ op: "subscribe", channel: "markets" })); // on change
ws.send(JSON.stringify({ op: "subscribe", channel: "account", address })); // on change
if (session) ws.send(JSON.stringify({ op: "auth", token: session.accessToken })); // notifications
};
ws.onmessage = (e) => {
const m = JSON.parse(e.data);
// m.type: "prices" | "markets" | "account" | "notification" | "error" | ...
// m.data has the same shape as the matching REST response: replace your cached copy
};Reconnect with backoff when the socket closes. After each token refresh, send auth again.
#Errors you will see
Every error is { "error": { "code", "message", "details"? } }.
code | What to do |
|---|---|
ACTION_NOT_ALLOWED (422) | Show details.problems, e.g. INSUFFICIENT_COLLATERAL, INSUFFICIENT_WALLET_BALANCE, ASSET_FROZEN |
VALIDATION_ERROR (400) | Bug in your request; details lists the fields |
UNAUTHORIZED / INVALID_ACCESS_TOKEN (401) | Refresh, or sign in again |
REFRESH_TOKEN_REUSED (401) | Sign in again |
PROTOCOL_NOT_DEPLOYED (503) | Contracts are not on this network yet; show prices only |
HYPERCORE_UNAVAILABLE / CHAIN_UNAVAILABLE (502) | Temporary; retry |
RATE_LIMITED (429) | Back off |
#Running the backend locally while you build
pnpm install && pnpm contracts:compile
pnpm chain:node # terminal 1: local chain, chain id 31337, RPC http://127.0.0.1:8545
NETWORK=local pnpm deploy:contracts # terminal 2: prints 3 keeper keys; put them in .env
NETWORK=local pnpm dev # API on http://localhost:8080
pnpm seed:local # terminal 3: creates a lender + a borrower, prints wallet keys to importPrices are live HyperCore data even locally. For local dev, set the wallet's network to
RPC http://127.0.0.1:8545, chain id 31337, and read chainId from /v1/config instead
of hard-coding 99901.