Agents & API

Example autonomous agent

A minimal on-chain agent loop that reads state from the API and tunes a strategy's fees with real HYPE volatility, with rate-limit handling.

Last updated 3 min readv1.0

This is the shape of a safe autonomous agent: read the clock and state from the API, simulate, then send a transaction from a dedicated agent address, keep mutations sparse, and back off on 429.

  1. Create an agent wallet

    A fresh address that holds only gas. Never reuse your main wallet's key.

  2. Authorise it on-chain

    From the strategy owner's wallet, call ForgeFactory.setAgent(strategy, agent, callsPerHour, selectors) with a low callsPerHour (max 120) and only the selectors the bot needs.

  3. Run the loop

    EM_BASE=https://<host> OWNER=0x… AGENT_PK=0x… npx tsx fee-bot.ts

  4. Watch it

    Every mutation appears in the strategy's mutation log as an agent action. Revoke with ForgeFactory.revokeAgent(strategy, agent).

fee-bot.tsTypeScript
// fee-bot.ts: a minimal on-chain agent for Elysium Morning (Elysium mainnet, real funds).
// It reads state from the REST API and sends transactions itself with a dedicated agent key.
// Run: EM_BASE=https://<host> OWNER=0x... AGENT_PK=0x... npx tsx fee-bot.ts
//
// Prerequisite: the strategy owner authorised this agent address from their wallet:
//   ForgeFactory.setAgent(strategy, agent, callsPerHour, [setFeeBounds selector])
import { createPublicClient, createWalletClient, defineChain, encodeFunctionData, http, parseAbi } from "viem";
import { privateKeyToAccount } from "viem/accounts";

const BASE = process.env.EM_BASE!;
const OWNER = process.env.OWNER!.toLowerCase();       // owner of the strategies this agent tunes
const agent = privateKeyToAccount(process.env.AGENT_PK as `0x${string}`); // dedicated key, keep only gas in it
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));

const FACTORY_ABI = parseAbi(["function mutate(address strategy, bytes data) returns (bytes)"]);
const AMM_ABI = parseAbi(["function setFeeBounds(uint256 newBase, uint256 newMax)"]);

async function api<T>(path: string): Promise<T> {
  for (let attempt = 0; ; attempt++) {
    const res = await fetch(BASE + path);
    if (res.status === 429 && attempt < 3) {          // respect rate limits
      await sleep(Number(res.headers.get("Retry-After") ?? 5) * 1000);
      continue;
    }
    const body = await res.json();
    if (!res.ok) throw Object.assign(new Error(body.error), { code: body.code, status: res.status });
    return body as T;
  }
}

/** Fee target from realised volatility of recent HYPE prices (annualised, %). */
function targetBounds(vol: number) {
  const base = Math.round(Math.min(60, 8 + vol * 0.1));
  const max = Math.round(Math.min(300, base * 6));
  return { base, max };                                // inside the clamm-dyn bounds: base 1-100, max 20-300
}

const cfg = await api<{ chainId: number; rpcUrl: string; addresses: { forgeFactory: `0x${string}` } }>("/api/chain/config");
const chain = defineChain({
  id: cfg.chainId, name: "Elysium",
  nativeCurrency: { name: "HYPE", symbol: "HYPE", decimals: 18 },
  rpcUrls: { default: { http: [cfg.rpcUrl] } },
});
const pub = createPublicClient({ chain, transport: http() });
const wallet = createWalletClient({ account: agent, chain, transport: http() });

const prices: number[] = [];

async function tick() {
  const hype = await api<{ priceUsd: number }>("/api/market/hype");
  prices.push(hype.priceUsd);
  if (prices.length > 60) prices.shift();

  // evolve the strategies this agent is authorised for, at most once per tick each
  const all = await api<{ id: string; owner: string; params: Record<string, number> }[]>("/api/strategies?status=live");
  const want = targetBounds(realisedVol(prices));
  for (const s of all.filter((s) => s.owner === OWNER)) {
    if (Math.abs(s.params.baseFee - want.base) < 3) continue;   // hysteresis: every mutation is public and rate-limited
    const data = encodeFunctionData({ abi: AMM_ABI, functionName: "setFeeBounds", args: [BigInt(want.base), BigInt(want.max)] });
    try {
      // simulate first: reverts (not authorised, out of bounds, rate cap) cost no gas
      const { request } = await pub.simulateContract({
        account: agent, address: cfg.addresses.forgeFactory, abi: FACTORY_ABI,
        functionName: "mutate", args: [s.id as `0x${string}`, data],
      });
      const hash = await wallet.writeContract(request);
      console.log("mutate", s.id, hash);
    } catch (e) {
      console.warn("mutate", s.id, (e as Error).message.split("\n")[0]);
    }
  }
}

function realisedVol(p: number[]) {
  if (p.length < 3) return 50;
  const r = p.slice(1).map((v, i) => Math.log(v / p[i]));
  const m = r.reduce((a, b) => a + b, 0) / r.length;
  const sd = Math.sqrt(r.reduce((a, b) => a + (b - m) ** 2, 0) / (r.length - 1));
  return sd * Math.sqrt(525_600 / 0.5) * 100; // 30 s samples → annualised %
}

for (;;) {
  await tick().catch((e) => console.error("tick", e.code ?? e));
  await sleep(30_000);
}

#Hardening checklist

  • Idempotency: remember what you already sent, so a restart does not repeat a mutation; the factory also rate-limits each agent.
  • Hysteresis: only mutate when the target moves meaningfully; every mutation is public and counts against the agent's hourly cap.
  • Bounds: read GET /api/templates and clamp before sending, and simulateContract first so reverts cost no gas.
  • Clock: use msToBoundary from the server, never Date.now() arithmetic against hard-coded offsets.
  • Freshness: check GET /api/chain/status (lagBlocks) before trusting API views.
  • Observability: log code and status for every failure and revert reason; alert on repeated failures.
Something unclear or wrong on this page? Report it.Updated Dec 1, 2026 · v1.0