// Example of another agent hiring wader-agent. // // A liquidity assistant for the team of a small token project. The team asks a // question in plain words; Claude decides whether it needs a fresh pool health // report, and if so the assistant buys one from wader-agent over x402, paying // HBAR from the team's own Hedera testnet account. Spending is capped in code, // not left to the model. // // HEDERA_ACCOUNT_ID=0.0.x HEDERA_PRIVATE_KEY=302e... ANTHROPIC_API_KEY=... \ // node examples/liquidity-assistant.ts "Can our pool take a 200 HBAR buy?" [pool address] import Anthropic from "@anthropic-ai/sdk"; import { decodePaymentResponseHeader, wrapFetchWithPayment, x402Client } from "@x402/fetch"; import { PrivateKey, createClientHederaSigner } from "@x402/hedera"; import { ExactHederaScheme } from "@x402/hedera/exact/client"; const NETWORK = "hedera:testnet"; const WADER_URL = process.env.WADER_URL ?? "https://wader.live"; const MODEL = process.env.ASSISTANT_MODEL ?? "claude-haiku-5-5"; // Most the assistant may spend in one run, and on one report (tinybars). const BUDGET = BigInt(process.env.BUDGET_TINYBAR ?? 150_000_000); const MAX_PER_REPORT = BigInt(process.env.MAX_PER_REPORT_TINYBAR ?? 200_000_000); const [question, defaultPool] = process.argv.slice(2); if (!question) throw new Error('Usage: node examples/liquidity-assistant.ts "" [pool address]'); const accountId = process.env.HEDERA_ACCOUNT_ID; const privateKey = process.env.HEDERA_PRIVATE_KEY; if (!accountId || !privateKey) throw new Error("HEDERA_ACCOUNT_ID and HEDERA_PRIVATE_KEY are required"); const signer = createClientHederaSigner(accountId, PrivateKey.fromStringDer(privateKey), { network: NETWORK }); let spent = 0n; const receipts: string[] = []; const reports = new Map(); // Buys one report, unless this run already has one for the pool or the budget would be exceeded. async function buyPoolReport(pool: string): Promise { if (!/^0x[0-9a-fA-F]{40}$/.test(pool)) return "Error: pool must be a 0x address of 40 hex digits."; const key = pool.toLowerCase(); if (reports.has(key)) return JSON.stringify(reports.get(key)); let price: bigint | null = null; const client = x402Client .fromConfig({ schemes: [{ network: NETWORK, client: new ExactHederaScheme(signer) }], spendControls: { allowedAssets: [{ network: NETWORK, asset: "0.0.0", maxAmountPerPayment: MAX_PER_REPORT.toString() }] }, }) .onBeforePaymentCreation(async ({ selectedRequirements }) => { price = BigInt(selectedRequirements.amount); if (spent + price > BUDGET) return { abort: true, reason: "over the assistant's budget" }; }); let response: Response; try { response = await wrapFetchWithPayment(fetch, client)(`${WADER_URL}/report?pool=${key}`); } catch (error) { return `Error: the purchase did not go through (${error instanceof Error ? error.message : String(error)}).`; } const body = (await response.json().catch(() => ({}))) as { error?: string; commentary?: string; facts?: unknown }; if (!response.ok) return `Error from wader-agent (${response.status}): ${body.error ?? "no details"}. Nothing was charged.`; const settlement = response.headers.get("PAYMENT-RESPONSE"); const tx = settlement ? decodePaymentResponseHeader(settlement).transaction : "unknown"; if (price !== null) spent += price; receipts.push(`${key}: ${Number(price ?? 0n) / 1e8} HBAR, transaction ${tx}`); const report = { commentary: body.commentary, facts: body.facts }; reports.set(key, report); return JSON.stringify(report); } const tools: Anthropic.Tool[] = [ { name: "buy_pool_report", description: "Buys a fresh health report on one SaucerSwap V2 pool on Hedera testnet from wader-agent, paid in HBAR from the team's budget. " + "Returns JSON: a commentary plus facts, including what must be paid in, and what is received, to move the price 1/2/5/10% each way (depth), the last 24 hours of trading, and liquidity provider yield. " + "Each call spends real testnet HBAR, so call it only when the answer depends on the pool's current state, and at most once per pool.", input_schema: { type: "object", properties: { pool: { type: "string", description: "Pool contract address, 0x followed by 40 hex digits." } }, required: ["pool"], }, }, ]; const system = `You are the liquidity assistant of a small token project. The team runs a thin liquidity pool on SaucerSwap (Hedera testnet) and asks you practical questions: can the pool absorb a given trade, how much liquidity is missing, is providing liquidity paying off. You can buy a pool health report with the buy_pool_report tool. It costs the team HBAR, so buy only when the question needs the pool's current numbers. ${defaultPool ? `The team's pool is ${defaultPool}.` : "If the team names no pool, ask which one instead of guessing."} Answer from the report's facts and do the arithmetic yourself when the question needs it, for example by placing a trade size between two rows of the depth table. Say plainly when the facts cannot answer the question. These are test-network tokens with no real value, and you do not give investment advice. Keep the answer under 200 words.`; const claude = new Anthropic(); const messages: Anthropic.MessageParam[] = [{ role: "user", content: question }]; for (let turn = 0; turn < 6; turn++) { const response = await claude.messages.create({ model: MODEL, max_tokens: 4000, system, tools, messages }); if (response.stop_reason === "refusal") throw new Error("The model declined to answer."); messages.push({ role: "assistant", content: response.content }); const calls = response.content.filter((b): b is Anthropic.ToolUseBlock => b.type === "tool_use"); if (calls.length === 0 || response.stop_reason === "end_turn") { const answer = response.content.filter(b => b.type === "text").map(b => b.text).join("").trim(); console.log(answer || "(no answer)"); break; } const results: Anthropic.ToolResultBlockParam[] = []; for (const call of calls) { const pool = (call.input as { pool?: unknown }).pool; const content = call.name === "buy_pool_report" && typeof pool === "string" ? await buyPoolReport(pool) : "Error: unknown tool or missing pool."; results.push({ type: "tool_result", tool_use_id: call.id, content }); } messages.push({ role: "user", content: results }); } console.log(`\nSpent ${Number(spent) / 1e8} HBAR of a ${Number(BUDGET) / 1e8} HBAR budget.`); for (const receipt of receipts) console.log(` ${receipt}`);