Agents & API
Worked example
What it does
This example swaps 10 USDC for HYPE on Elysium. It quotes the swap, builds it, sends the approvals the build asks for, sends the swap with the agent’s own wallet and reports it. The blocks below are one file, in order.
The script sends real transactions. Use a wallet you are willing to spend from.
Installviem, and a runner for ES modules such as tsx.OXLEY_API_KEYYour API key. See Getting an API key.AGENT_PRIVATE_KEYThe private key of a wallet that holds at least 10 USDC on Elysium and a little HYPE for gas.ELYSIUM_RPC_URLAn Elysium RPC endpoint.
Set up
Elysium is its own chain, with chain id 99901. The helper adds the key to each call and waits when a call is over a limit. The send helper signs with the agent’s own wallet and waits for the transaction to land.
import { createPublicClient, createWalletClient, defineChain, http, parseUnits, type Hex } from 'viem';
import { privateKeyToAccount } from 'viem/accounts';
const API = 'https://oxley-agents.web3bandit.workers.dev';
const apiKey = process.env.OXLEY_API_KEY!;
const account = privateKeyToAccount(process.env.AGENT_PRIVATE_KEY as Hex);
const elysium = defineChain({
id: 99901,
name: 'Elysium',
nativeCurrency: { name: 'HYPE', symbol: 'HYPE', decimals: 18 },
rpcUrls: { default: { http: [process.env.ELYSIUM_RPC_URL!] } },
});
const publicClient = createPublicClient({ chain: elysium, transport: http() });
const wallet = createWalletClient({ account, chain: elysium, transport: http() });
type Tx = { chainId: number; from: Hex; to: Hex; data: Hex; value: string; gas?: string };
// One call to the API: adds the key, waits and retries on 429, throws on any other error.
async function oxley<T>(path: string, init: RequestInit = {}): Promise<T> {
for (let attempt = 1; ; attempt++) {
const response = await fetch(`${API}${path}`, {
...init,
headers: { authorization: `Bearer ${apiKey}`, 'content-type': 'application/json' },
});
if (response.status === 429 && attempt < 3) {
const seconds = Number(response.headers.get('retry-after')) || 1;
await new Promise((resolve) => setTimeout(resolve, seconds * 1000));
continue;
}
const body = await response.json();
if (!response.ok) throw new Error(`${response.status} ${body.error}: ${body.reason}`);
return body as T;
}
}
// Sign and send an unsigned step from the API, then wait for it to land.
async function send(tx: Tx): Promise<Hex> {
const hash = await wallet.sendTransaction({ to: tx.to, data: tx.data, value: BigInt(tx.value), gas: tx.gas ? BigInt(tx.gas) : undefined });
const receipt = await publicClient.waitForTransactionReceipt({ hash });
if (receipt.status !== 'success') throw new Error(`Transaction ${hash} reverted`);
return hash;
}Quote
Take the token addresses from the API rather than writing them in. Amounts are base units as strings, so 10 USDC is parseUnits('10', 6) as a string. The price is a guide: it shows what the swap would return and the minimum after slippage.
const { tokens } = await oxley<{ tokens: { address: Hex; symbol: string; decimals: number }[] }>('/v1/swap/tokens');
const usdc = tokens.find((token) => token.symbol === 'USDC')!;
const hype = tokens.find((token) => token.symbol === 'HYPE')!;
const sellAmount = parseUnits('10', usdc.decimals).toString();
const query = new URLSearchParams({ sellToken: usdc.address, buyToken: hype.address, sellAmount, taker: account.address });
const price = await oxley<{ buyAmount: string; minBuyAmount: string }>(`/v1/swap/price?${query}`);
console.log(`About ${price.buyAmount} base units of HYPE, at least ${price.minBuyAmount}`);Build
The build returns a buildId, the quote it is built from (with the minimum out and when it expires) and the steps: the approvals still needed, then the swap as the last step. Check what you are about to sign here, before the next block. Keep the buildId.
const build = await oxley<{
buildId: string;
quote: { minBuyAmount: string; expiresAt: number };
steps: { kind: 'approval' | 'transaction'; label: string; tx: Tx }[];
}>('/v1/swap/build', {
method: 'POST',
body: JSON.stringify({ sellToken: usdc.address, buyToken: hype.address, sellAmount, taker: account.address, slippageBps: 50 }),
});
console.log(`Minimum out ${build.quote.minBuyAmount}; steps: ${build.steps.map((step) => step.label).join(', ')}`);Approve and send
Send the steps in order and wait for each to land: the approvals, then the swap. The wallet signs and broadcasts them; oxley never sees the key. A quote is only good until quote.expiresAt, so send promptly and build again if it passes.
if (build.quote.expiresAt * 1000 < Date.now()) throw new Error('The quote expired. Build again.');
let txHash: Hex | undefined;
for (const step of build.steps) {
txHash = await send(step.tx);
console.log(`${step.label}: ${txHash}`);
}
if (!txHash) throw new Error('The build returned no steps.');
// The last step is the swap itself: its hash is the one to report.Report
Report the swap so it counts toward your volume. The outcome says whether it counted. Asking for the swap’s status with the buildId counts too.
const report = await oxley<{ outcome: string; volume30dUsd: number }>('/v1/report', {
method: 'POST',
body: JSON.stringify({ buildId: build.buildId, txHash }),
});
console.log(`Report: ${report.outcome}; 30-day volume ${report.volume30dUsd} USD`);
const status = await oxley<{ status: string }>(`/v1/swap/status?${new URLSearchParams({ hash: txHash, buildId: build.buildId })}`);
console.log('Swap', status.status);Bridging the same way
A bridge follows the same loop. Read POST /v1/bridge/quote for every hop, then POST /v1/bridge/build with the same intent for the first leg. Send its steps in order, as above. Transfers must start on an EVM chain.
Follow the first leg with POST /v1/bridge/status, passing the buildId. When it has been delivered, build the next hop with the intent the build returned, and repeat. Report each hop’s transaction with that hop’s buildId.