I built an agent that converts USDT into Argentine pesos, Brazilian reais and a few other LatAm currencies on Celo, and is designed to say no most of the time. This is the long version: why refusals beat conversions, how the money path works without CELO in the wallet, what the ledger actually guarantees, and where it all falls short because I never funded the wallet.
The brief and the constraint that shaped everything
The brief for "Agents on Open Rails" was money that moves without a human in the loop, on open rails. Celo has the useful pieces: stablecoins with real depth, a firm quote RFQ venue in Textile, x402 for payments, ERC-8004 for identity, ERC-8021 for attribution, and CIP-64 so a transaction can pay its fee in a stablecoin.
The constraint was the hackathon's rules: no personal_sign or eth_signTypedData on the money path, never display a wallet address in the UI, no CELO in the UI, no withdraw-to-external-address field, USDT has to work, bundle under 2 MB, legacy transactions with explicit amount + fee balance checks.
Reading that list carefully tells you what the product is allowed to be. It rules out a wallet, a swap widget, a signing prompt. So I stopped thinking about a UI for moving money and started thinking about a decision engine whose output is evidence.
The idea: refusals as receipts
An FX agent that always converts is not an agent, it is a cron job with a market order attached. The interesting behaviour is the refusal: seeing a quote, deciding it is worse than the obligation you are trying to fund, and not trading.
So the contract I wrote for the agent is:
- The operator names a break-even rate for the obligation,
--target 1700meaning 1700 wARS per USDT or better. - The agent converts at or above it.
- Below it, and before the deadline, it refuses. The refusal records the print, the reference, the bps gap, and the dollar cost avoided.
- If the deadline arrives and the book never cleared, it converts anyway, marks the fill
forced: true, and records the concession. An obligation gets met; the price paid for meeting it late is on the record.
The consequence is that a day where nothing traded does not produce an empty log. It produces a receipt that says: I saw 1668.39, you asked for 1700, I saved you 186 bps, here is the hash.
That is a thing a finance team can actually read, and it is the difference between automation they trust and automation they audit.
Architecture
Five pieces, each with a job it cannot delegate:
-
Observe. Textile FX v2:
POST /v2/rfq/previewfor a firm quote on a size,GET /v2/rfq/levelsfor the two sided book. Keyless: auth is a signature, not an API key. - Decide. A pure function. Six gates, then the target rule. No I/O, no clock except what is passed in.
-
Execute. One chokepoint,
sendTagged(), which attaches the CIP-64 fee currency and the ERC-8021 suffix. Nothing else in the repo is allowed to broadcast. - Record. Append only JSONL with a sha256 chain. This is the product's memory and its proof.
-
Publish. Derive
state.jsonfrom the ledger, ship it to a static dashboard. The dashboard is a view; the ledger is the truth.
The important architectural decision is #4 before #5. If the dashboard owned the state, everything downstream would be unverifiable. Because the ledger owns it, the dashboard can be deleted and rebuilt and nothing is lost or faked.
The decision function
All policy is in one place, src/strategy.ts. It is pure on purpose: the entire risk surface of the agent is testable without a chain, a mock, or a clock.
if (args.deadlineAt && now >= args.deadlineAt) {
return { action: "convert", edgeBps: vsTarget, price, size, forced: true };
}
return {
action: "refuse",
reason: "TARGET_NOT_MET",
...base,
edgeBps: vsTarget,
avoidedUsd: size * ((-policy.toleranceBps - vsTarget) / 10_000),
detail: `${vsTarget.toFixed(1)} bps under the ${target} target · ${args.deadlineAt ? `settles by ${new Date(args.deadlineAt).toISOString().slice(11, 16)}Z if the book never clears it` : "waiting for a better print"}`,
};
avoidedUsd deserves a second look. It is the difference between the target you wanted and the tolerance you would accept, priced at the tranche size. So a 25 USDT tranche refused 241 bps under target with zero tolerance avoids about 25 * 241 / 10000 = $0.60. Small numbers per tick, but the point is that refusals are priced, not narrated. When you sum them over a week you get a real figure to compare against the fees you did not pay.
Six gates run before the target rule, in this order, each returning its own reason code:
// abbreviated from src/strategy.ts
if (ageMs > policy.maxQuoteAgeMs) return refuse("STALE_QUOTE", ...);
if (depthUsd < size * policy.minBookRatio) return refuse("BOOK_THIN", ...);
if (Math.abs(dislocation) > policy.dislocationBps) return refuse("PRICE_DISLOCATION", ...);
if (usedTodayUsd + size > policy.dailyCapUsd) return refuse("DAILY_CAP", ...);
Order matters. Staleness first because every other judgement is meaningless on an old quote. Depth second because a deep book that is dislocated is a wrong feed, not an opportunity. Cap last because it is the only gate that is about the past rather than the present.
The reference price for the edge calculation is an EWMA over the last referenceWindow observations, not the last print. Using the last print would make every tick look like zero edge, which is exactly the bug that makes naive bots churn.
Gas without CELO, and why the adapter address matters
Celo's CIP-64 fee abstraction lets a transaction pay its fee in an ERC-20. That is the difference between an agent that can operate on stablecoin funding and one that cannot: a treasury holding USDT does not want to also hold a gas token it never uses.
The implementation is four lines, and the subtle part is the address:
export function taggedWalletClient(account: PrivateKeyAccount) {
return createWalletClient({ account, chain: celo, transport: http(CELO_RPC) }).extend(
withAttribution(ATTRIBUTION_CODE),
);
}
export async function sendTagged(
wallet: any,
account: PrivateKeyAccount,
tx: { to: `0x${string}`; data?: `0x${string}`; value?: bigint },
): Promise<`0x${string}`> {
return wallet.sendTransaction({
account,
to: tx.to,
data: tx.data,
value: tx.value,
feeCurrency: FEE_CURRENCIES[feeCurrency()] as `0x${string}`,
});
}
FEE_CURRENCIES maps USDT to 0x0E2A3e05bc9A16F5292A6170456A710cb89C6f72. That is the fee adapter, not the token. USDT's token is 0x48065f…3d5e. If you pass the token where the adapter belongs, the transaction reverts during simulation, not submission, which means your error handling sees a confusing failure that looks like nonce or gas trouble. I lost about forty minutes to this. Put the adapter mapping in one constant and never inline it.
The panic path matters here too: an agent with zero CELO and zero USDT has to fail as a refusal, not an exception. run in dry mode never needs either, which is how the demo works at all.
Attribution, which cannot be backfilled
ERC-8021 suffixes are built into the wallet client at construction. That is the whole reason taggedWalletClient() exists as a separate function instead of a flag on each send: the tag is part of the client, so a caller cannot forget it.
export const ATTRIBUTION_CODE = "celo_a513a55229eb";
The compiled suffix ends up as 0x63656c6f5f613531…8021 8021 8021 on every transaction. npm run agent -- doctor prints it, so you can confirm the code is live before you ever send anything.
This is one place where the hackathon rules and good engineering agree. "Add this tag to every transaction, untagged transactions never count" is an instruction that a careless codebase will satisfy in one path and violate in another. Making it a construction time property removes the class of bug entirely.
The ledger: cheap, boring, hard to fake
I did not want a database and I definitely did not want to claim a blockchain. The requirement was narrower: given a run, prove that no row was edited afterwards, without trusting my code.
export function hashEntry(e: Omit<Entry, "hash">): string {
return (
"0x" +
createHash("sha256")
.update(`${e.seq}|${e.at}|${e.kind}|${canonical(e.body)}|${e.prev}`)
.digest("hex")
);
}
Each entry is {seq, at, kind, body, prev, hash} where prev is the previous entry's hash, or 0x00…00 at genesis. canonical() sorts keys before serialising so the hash depends on values, not on object insertion order. Eight kinds cover the lifecycle: RUN_START, OBSERVATION, DECISION, PAYMENT, RFQ_CREATED, TX_SENT, FILL, RUN_END.
What this buys:
- Tamper evidence. Change a rate in row 4 and rows 4 through 14 all stop verifying.
- Ordering. The chain encodes sequence, so you cannot reorder refusals to look smarter.
- Portability. A JSONL file and forty lines of code audited by anyone, on any machine, with no dependencies.
What it does not buy: it is not consensus. Someone who controls the whole file can rewrite it end to end. For an operator auditing their own agent that is fine. For an agent claiming performance to a third party, the next step is publishing the head hash on chain, which is on the roadmap rather than in the repo.
Verification is a single command:
$ npm run verify
ledger INTACT · 14 entries · sha256 chain
decisions 6 · conversions 4 · refusals 2
refused TARGET_NOT_MET 2
quoted $150 · filled $0 · avoided cost $1.2085
savings 0 bps ($0) · cogs $0 · net $0
Notice filled $0. That is the honest line, and it is in the tool's own output rather than buried in a README caveat.
Keyless auth, and choosing EIP-191 over EIP-712
Textile's v2 API authenticates with a signature over a taker control message rather than an API key. That is a good fit for an agent because there is no secret to leak or rotate, but it forces a choice: typed data (EIP-712) or a plain message signature (EIP-191).
I picked EIP-191 with a five minute window. EIP-712's sixty second window is tighter than a tick that fetches a quote, writes a ledger entry, and publishes state on a slow connection. An auth failure mid tick is not a refusal with a reason code, it is an exception, and I did not want a class of failure that sits outside the decision taxonomy.
export function takerControlText(args: { taker: `0x${string}`; at: number }) {
return `Textile FX taker control\naddress: ${args.taker}\nissued: ${args.at}`;
}
The signature is produced per request at the moment of quoting. No session token, no cache, nothing to reuse across ticks.
x402: the agent pays for its own thinking
The last piece is cost of goods. An agent that queries a paid rate service and a paid model should book those as costs, otherwise its PnL is fiction.
src/x402.ts implements the buyer side of the exact scheme: read the payment challenge, pick the requirement matching the network and asset, sign an EIP-3009 transferWithAuthorization, and replay the request with the payment header.
const TRANSFER_WITH_AUTHORIZATION_ABI = parseAbi([
"function transferWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce,uint8 v,bytes32 r,bytes32 s)",
]);
EIP-3009 rather than a plain transfer matters because it removes the approval transaction from the hot path: one signature, one settlement, no two step dance per call.
Every PAYMENT entry records mode: "live" | "dry". A dry run cannot be mistaken for real spend, which is the whole reason that field exists. report then prints savings, cogs and net so the discipline and the cost sit next to each other on one screen.
The dashboard
React 18 and Vite, hand written CSS, no component library, about 150 kB. It shows four things:
- the print against the target line, so you can see the gate as a distance rather than a number;
- the decision feed, refusals and fills in order, each with its reason code;
- the ledger table, the append only tape, numeric columns right aligned;
- PnL: quoted, filled, avoided, savings, cogs, net.
The build writes straight into docs/, which is what GitHub Pages serves. Two details cost me time:
The chart hid its own target line. The SVG domain was computed from the observed series, so a target outside the observed range rendered off canvas, which is precisely the case where the target matters most. Fixed by folding the target into the domain with eight percent padding.
Tables overflowed at 390 px. Numeric columns need width; squashing them makes the tape unreadable, which defeats the point. A .tablewrap with overflow-x: auto and a min-width keeps the numbers legible and the page width fixed.
Also: Vite's emptyOutDir deletes .nojekyll, and Pages stops serving underscore prefixed asset paths without it. build:web restores the file with a touch so a clean clone can always rebuild the deployed site.
What is real and what is not
Real, and verifiable from this repo:
- Live Textile quotes against the Celo mainnet book, keyless.
- The six gate decision engine, the target rule, and forced settlement, exercised in a 6 tick dry run.
- A 14 entry sha256 chain that verifies from genesis.
- CIP-64 fee currency and ERC-8021 attribution wired into a single send path, confirmed by
doctor. - A dashboard deployed from the same
docs/a reader can rebuild. - Clean
tsc --noEmiton strict TypeScript.
Not real, and stated as such everywhere:
- No on chain fill. The wallet had no Celo mainnet balance, so nothing was broadcast.
- No ERC-8004 registration transaction. The registry call is written and gated behind a key.
- No x402 payment receipt. The buyer is implemented and runs dry.
- No round trip of the swap calldata against mainnet. It is built from the published contract and unproven in production.
I could have shipped a screenshot with a plausible transaction hash and nobody would have checked within the judging window. That would have made the ledger a lie on its first day, which is a strange thing to do to a product whose entire claim is that it records what happened.
What I would build next
Three things, in order of how much they would change the product:
Counterfactuals. For every refusal, compute the print that would have made the trade correct, then chart captured versus avoided over a month. That turns "I refused 40 times" into "I refused 40 times and it was right 31 of them", which is the only version of this pitch a treasury team will fund.
Deadline aware ladder. The current forced settlement is a cliff: nothing, nothing, everything. Slicing conversions as the deadline approaches and the book improves would bound the worst case without giving up the target.
Agent to agent RFQ. The interesting version of this product is not a human treasury; it is another agent shopping three FX agents over x402. That needs a serving side, a quote format, and reputation that another agent can price, which is exactly what ERC-8004 exists for.
What I took away
The most useful thing I learned is that an agent's trustworthiness lives in its refusal path, not its success path. Anyone can wire a swap. The product is the recorded decision not to, with a number attached and a hash behind it.
The second is that constraints like "no CELO in the UI" and "tag every transaction" are not obstacles to design around, they are design briefs. They pushed this toward a decision engine with an audit trail instead of another wallet front end, which turned out to be the more interesting product anyway.
If you build on this, fork it. The repo is small enough to read in an afternoon and the interesting failures are all still unsolved.
Code & more: https://www.dailybuild.xyz/project/314-umbral

Top comments (0)