Skip to content
frekrampPublic

About

A spending limit for your AI trader. User-owned accounts on Robinhood Chain where on-chain rules decide what an AI agent's trades can do.

Topics

Resources

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Kedge

License: MIT Live on Robinhood Chain testnet Guarantee: 35 tests, 5 invariants and a mainnet fork run Account: 152 Hardhat, 18 fuzz and invariant Solidity 0.8.28 Core coverage: 100% of lines, 96% of branches Slither: no real High or Medium

Let AI trade for you. Your max loss is guaranteed.

Live site · The guarantee · Live demo · Contracts on the explorer

For judges, 60 seconds, no wallet needed

  1. Watch it pay out. The crash drill: a guaranteed account, a 60% fall on demo price feeds, and the guarantee stopping the agent and paying the loss beyond the limit, to the unit. Every step is a testnet transaction.
  2. Draft your rules. Open a guaranteed account: tell the Mandate Architect your rules in plain words. It drafts the on-chain rules, says why for each number, and quotes the guarantee. No wallet needed for this step.
  3. See a live cover. The guaranteed account Kedge's AI trades: its loss meter against a 5% limit, the bond set aside for it, and the Concierge, which answers from its receipts.
  4. Try to break it. Try it on /demo: seven attacks on demo accounts, and "Trick the AI", where you write the message. Each is a real testnet transaction, and each is refused.

Every claim and its evidence on one page: docs/JUDGE_EVIDENCE.md. npm run verify checks every receipt against the chain.

The Split on /demo: one decision, buy $1.20 of Tesla, sent to two real accounts. Under the Relaxed (Standard) account's rules it executes; the Strict (Cautious) account's $0.50 per-trade limit blocks it, and its receipt shows $1.20 requested against $0.50 allowed.

The max-loss guarantee

AI agents now trade for people: Robinhood alone reports over a hundred thousand agentic trading accounts. When one loses money, nobody pays. Research on insuring AI agents calls their risk largely unpriced and invisible: an agent can do almost anything, and nobody can see what it did.

Kedge makes that risk bounded and visible, and then guarantees it. The account's on-chain mandate bounds what the AI can do; its receipts show everything it did; and a new contract, KedgeGuarantee, backs the user's limit with a bond.

  1. You set a limit. Open a Kedge account through the guarantee with a max loss from 2% to 20%. The guarantee owns the account on your behalf, so Kedge's AI is the only agent that can trade it, and every deposit and withdrawal is counted.
  2. The AI trades inside your rules. The account checks every trade on chain, as always, and the engine's Risk Officer sizes each buy so a 25% drop in it would use at most half the loss room you have left.
  3. Past your limit, you're paid. When the account's value, priced on chain from its own feeds, falls past your limit, anyone can call settle: the agent is stopped and the bond pays you the loss beyond the limit, up to a 30% loss. Kedge's Guardian makes that call after every check. Nobody can block it.

What the contract promises, and how each is tested (test-foundry/KedgeGuarantee*.t.sol):

Promise Checked by
Fully backed: a deposit is refused unless the free bond can pay the most it could ever cost An invariant over random runs of users, the agent, crashes, broken feeds and the backer: what is set aside never exceeds the bond, and the bond equals funded plus fees, less released, less paid
Valued on chain: cash plus each stock at its price feed 1,000 random cases against an independent calculation, and real Chainlink prices on a Robinhood Chain mainnet fork
No payout on a stale or broken price Unit tests with stale, paused and negative feeds, on mock and real feeds
Withdrawing can't fake a loss 1,000 random withdrawals: the loss ratio never rises (to within one smallest unit)
The backer can't stop a payout The backer takes back all free bond, and the payout still lands; there is no pause
You can always leave Closing works with broken and stale feeds, and hands you the account
Only the guaranteed agent The invariant: an open cover's agent is the guaranteed one, or nobody

Run them: forge test --match-contract KedgeGuarantee (35 tests and 5 invariants), and RH_MAINNET_FORK=1 forge test --match-contract GuaranteeMainnetFork -vv (real USDG, TSLA, AMZN and Chainlink).

The AI team. Each role's work can be checked:

Role What it does Where to check it
Mandate Architect Drafts a guaranteed account's rules from your own words, each number held inside the guarantee's bounds You sign the exact rules; its prompt is published by hash
Analyst Kedge's AI trader (Claude Haiku 4.5): reads the market and decides Every decision is a receipt on chain, with its published record
Risk Officer Sizes each buy for a guaranteed account to the loss room left, or holds it back Its note is kept on the account's receipt
Guardian Settles any cover past its limit after every check settle transactions; anyone can send one
Underwriter The bond's exact worst case for a cover, and the chance of reaching the limit from a stated model The contract checks full backing at every deposit
Concierge Answers a question about one account from its own receipts It cites the receipts it used

On testnet (all verified on the explorer):

What Address or transaction
The live guarantee, 60 USDG bond 0xE821464B5eccF69F54711131f0D93f6c5952121f
Its first cover, traded by Kedge's AI, 5% limit 0x3e0845fEab1CD26622e6878057c9979117575BF6
The crash drill's guarantee (demo feeds, a drill agent) 0xFb549630a9cEacFAc132cE36Bae09A374498F1Bc
The drill's payout: 0.961769 USDG, the loss beyond 5% 0x0f5864…4d89d

What the guarantee does not do.

  • On testnet, prices come from feeds Kedge's keeper mirrors from the real Chainlink feeds on Robinhood Chain mainnet (see DEPLOYMENTS.md). On mainnet the guarantee would read Chainlink directly. The crash drill used two demo feeds, labelled as such, and never touched the live ones.
  • No payout on an old price. When the market is closed, nothing is settled until a price is fresh again, so a weekend gap is settled at the first fresh price after it.
  • It pays real losses beyond your limit, up to a 30% loss. It doesn't stop the market from moving: an account with more of its money in stock carries more of that risk, which the per-stock cap bounds.
  • It is a contractual bond on a test network, not an insurance policy. A real-money version needs legal review for each place it is offered.

Why this matters

"Crucially, humans remain in control by deciding exactly how much capital to allocate and set the specific safety guardrails."

Robinhood, announcing Agentic Trading, July 1, 2026 (the announcement)

Kedge enforces those guardrails on chain, and guarantees the result. (Kedge is an independent project, not affiliated with Robinhood.)

In 30 seconds

  • What it is: an account the user owns on chain, through which an AI agent trades tokenized stocks, but only inside the owner's rules: which stocks, how much per trade and per day, and how fresh the price must be.
  • An AI agent (Claude) proposes, on-chain rules decide. The agent picks a trade; the account's own contract checks it against the rules and runs it or refuses it. The agent can't withdraw, and can't change the rules.
  • Refusals are public receipts. A refused trade leaves a Blocked event with its reason and the two numbers the rule compared. For the live agent, each receipt number is the hash of its published decision record, reasoning included, and anyone can re-check it with Verify. Since 26 Sep a record also names the model (claude-haiku-4-5) and the keccak256 of the system prompt it was given; the prompt is published at /api/engine/prompts/<hash>, and Verify re-hashes it too. Older records verify exactly as before.
  • Live on Robinhood Chain testnet (an Arbitrum Orbit chain), with Paxos USDG and Robinhood's test Stock Tokens.
  • Checked against mainnet, on a fork. The same contracts, on a local fork of Robinhood Chain mainnet, execute a trade and give all 19 refusal reasons against real USDG, Stock Tokens and Chainlink feeds; nothing is sent to mainnet. Run it: npm run test:mainnet-fork. Results, what changes for mainnet, the audit plan and a launch checklist: docs/MAINNET.md.
  • Markets close; the rule doesn't. Stock tokens trade 24/7, but reference prices freeze when markets close, and Kedge stops the AI trading on a frozen price. On testnet the live accounts' feeds follow the real Chainlink feeds' freshness on Robinhood Chain mainnet, so a weekend shows it (see "The live feeds follow the real market" in DEPLOYMENTS.md).

Built for Robinhood Chain, an Arbitrum Orbit chain (ArbOS 61), by Kedge Labs.

Where it stands

Live on Robinhood Chain testnet, with test money that has no value. Kedge is unaudited.

  • The agent is running (status). Kedge's reference agent uses Claude Haiku 4.5 and checks the market every 10 minutes. It sends each decision to every account that follows it, and publishes each decision's full record. Two of its live receipts: executed, a $0.50 Tesla buy within a $1.50 per-trade limit, and refused, a $1.00 Amazon buy over a $0.50 per-trade limit (TradeTooLarge). On an account's public page, like this one, every receipt shows the agent's reason, and Verify re-hashes the published record and checks it against the receipt number on chain. The agent decides at full size and trades 1/100 of it, so a reason that names dollars (its budget, cash, holdings or size) carries a note on the receipt: "The AI reasons at full size (100×)."
  • The max-loss guarantee is live: /guarantee shows its bond, every cover, the Guardian's record and the crash drill, read from the chain.
  • The web app at https://kedge-ebon.vercel.app: the landing page and the /demo walkthrough of one decision meeting two mandates.
  • Onboarding at /app: the Mandate Architect drafts your rules from your words, one signature opens a guaranteed account, and the drip deposits test USDG through the guarantee, so it is covered from the start.
  • Account pages: /account for owners (the rules, every receipt, stop, resume, withdraw) and a public page for any account at /a/<address>. Both show when the AI trader last checked the market and, while the market is closed, that trading is paused because prices are frozen.
  • Every contract is verified on the explorer, the guarantee's six included. DEPLOYMENTS.md lists every address and transaction.
  • Every decision sent on chain is in ledger.json, and npm run verify checks all of it against the chain (below).

Check every receipt yourself

ledger.json holds every decision Kedge's engine has sent to an account on chain: 101 on 26 Sep 2026 at 17:38 UTC, across 7 accounts, each with the exact record text its receipt number is the hash of. npm run verify checks all of it against Robinhood Chain testnet with only the file and the public RPC: no engine, no key, no transaction. It needs Node 20 or later.

npm ci
npm run verify

The real output:

$ npm run verify
Kedge ledger check: ledger.json against Robinhood Chain testnet (chain 46630)
101 entries, exported 2026-09-26 17:38 UTC, over https://rpc.testnet.chain.robinhood.com

✓ 101 of 101 records hash (keccak256) to their receipt numbers, and each is canonical JSON
✓ 101 of 101 records name chain 46630, Kedge's agent 0xeFeb…33B8, and the entry's source, trade and amount
✓ 101 of 101 transactions succeeded, were sent by that agent, and came after their record's time
✓ 101 of 101 carry the account's own receipt for that receipt number: 34 Executed, 67 Blocked
✓ 101 of 101 match their receipt: the outcome, the stock, and for the 67 refusals the reason
✓ 85 of 85 amounts and 67 of 67 pairs of numbers compared are the same on chain (16 entries store no amount)
✓ The AI traders' totals match: 29 executed ($22.65), 55 refused ($47.55)
  refused by: TradeTooLarge 22, BudgetExceeded 15, CostCapExceeded 11, InsufficientBalance 7

All 101 entries check out.

For each entry it re-hashes the record, then finds the account's own Executed or Blocked event for that receipt number in the transaction, and compares the outcome, the reason, the stock, the amount and the two numbers the rule compared. Try it's 16 entries don't store the amount sent, so for those the amount isn't compared. The AI traders' totals are the landing page's "Refused by Kedge" at export time: npm run ledger saves a fresh copy from the live engine (/api/engine/ledger) and stops if its totals differ from the engine's.

Contract quality, for judges

Start reading here: contracts/KedgeAccount.sol, deployed and verified as every Kedge account, for example this one. contracts/README.md maps each file to core, venue or mock.

  • Tests: 152 Hardhat tests, plus 11 Foundry fuzz properties at 1,000 runs each and 7 invariants at 256 runs of 128 random calls (229,376 calls). Run them all with npm run test:all.
  • Mutation score: 31 of 31 hand-made mutants of the account are caught (an off-by-one at the window reset, cost overwritten instead of added, a check out of order, an unlimited approval, and more).
  • Static analysis: Slither 0.11.6 and Aderyn 0.6.8 found no real High or Medium. Slither's 7 High and Medium flags in the core are deliberate patterns, each triaged with its reason and its tests; rerun it with the command in static analysis, which fails on any new one.
  • Coverage: KedgeAccount 100% of lines and functions and 96% of branches (146 of 152 paths); KedgeFactory 100%. The 6 untaken paths are listed with why.
  • Adversarial review: 29 hostile tests found 1 Medium and 5 Lows, and a later review 3 more Lows. Each was fixed after its failing test; none let the agent move funds.
  • Best practices: 14 of 14 checks pass (a pinned compiler, custom errors, events, a reentrancy guard, SafeERC20, no tx.origin or delegatecall, and more), with the deployed code unchanged.

Threat model · Static analysis · Checklist · Coverage · Gas

The problem

Handing a trading agent your keys means trusting its code, its prompts and every dependency with everything in the wallet. Limits written inside the agent are not limits: the agent can change them, and a bug or a prompt injection can skip them. And when a guardrail does refuse a trade, it usually reverts: all that is left is a failed transaction, with no event saying which rule refused it or why.

Kedge puts the limits where the agent can't change them, in an account contract the user owns, and records every refusal that reaches the policy check as a permanent public receipt.

The demo: one decision, two sets of rules

On the real testnet market

One agent decision, "buy $1.20 of TSLA", goes to two accounts with the same decision ID. Same agent, same decision, same market. The only difference is each owner's mandate. The agent is its own address with its own key: it sends every trade and owns nothing.

The web app calls the two presets Relaxed (Standard) and Strict (Cautious), and the agent the AI trader.

Standard account Cautious account
Max per trade $1.50 $0.50
24 hour buy budget $5 $2
Prices up to 25 hours old 1 hour old
Result Executed: spent 1.20 USDG, received 0.003118 TSLA Blocked: TradeTooLarge ($1.20 requested, $0.50 allowed)

The agent's try at AMD, a real test Stock Token the mandate does not allow, is blocked with AssetNotAllowed.

script/deploy-real.js built this market with Paxos USDG and Robinhood's official test TSLA, and the 23 Sep revision's script/redeploy-real.js re-created its two accounts with the presets, at 1:100 scale because that is what the faucets give. The venue and price feeds are labelled mocks (Robinhood Chain testnet has no Chainlink feeds), seeded at Chainlink's real mainnet prices at deploy time.

Every refusal reason, recorded

The same split runs on a demo market with mock tokens at full size: one decision, "buy $120 of mNVDA", sent to two accounts with the same decision ID.

Standard account Cautious account
Max per trade $150 $50
24 hour buy budget $500 $200
Prices up to 25 hours old 1 hour old
The agent sends buy $120 of mNVDA the same decision
Result Executed: spent 120.00 mUSDC, received 0.5978 mNVDA Blocked: TradeTooLarge, with the two numbers it compared ($120 requested, $50 allowed)
Receipt on testnet Executed Blocked

script/deploy.js produces both receipts, plus a refused buy of a token that has a pool but that no mandate allows (AssetNotAllowed). script/scenarios.js then records six more:

Scenario What happens Receipt
Bad price Someone pumps the mNVDA pool about 10%. The agent tries a $100 buy. Blocked: PriceDeviation
Stale price The reference price is 26 hours old and the mandate allows 25 hours. Blocked: OracleStale
Feed down The reference feed stops answering. Blocked: OracleUnavailable
Duplicate The headline decision is sent a second time. Blocked: Duplicate
Agent withdraws The agent calls withdraw() to send $100 of the account's cash to itself. A failed transaction from the agent's address: OwnableUnauthorizedAccount
Owner exit The owner stops the agent. Three seconds later the price feed goes down, and both withdrawals of all cash and stock go through while it is down. stop() and withdraw() succeed. The agent's next trade reverts with NotAgent.

Both scripts are safe to run again. Every receipt above is live on Robinhood Chain testnet; DEPLOYMENTS.md lists every address and transaction. The venue and the price feeds are labelled mocks in both deployments. The tokens are Robinhood's and Paxos's real test tokens on the real market (USDG, TSLA, AMZN, AMD) and mocks on the demo market (mUSDC, mNVDA, mAAPL, RUG). None of them has any monetary value.

How the pieces fit

flowchart TD
    owner["Owner's wallet"] -->|"creates the account with its rules;<br/>deposits, stops, withdraws"| account
    drip["Test money tap (web app)"] -->|"test USDG for a new account"| account
    feeds["Price feeds"] -.->|"reference prices"| engine
    engine["Agent engine<br/>Claude Haiku, every 10 minutes"] -->|"trade(decisionId, ...)"| account
    account["KedgeAccount: the owner's rules"] --> checks{"Checks, in a fixed order"}
    feeds -->|"price and its age"| checks
    checks -->|"all pass"| venue["Exchange"]
    keeper["Keeper (the engine's own wallet)"] -->|"puts the pool back at its<br/>reference before each trade"| venue
    venue --> executed["Executed receipt"]
    checks -->|"one fails"| blocked["Blocked receipt:<br/>the reason and the two numbers"]
    executed --> web["Web app: /account and /a/…"]
    blocked --> web
    engine -.->|"publishes each decision record;<br/>receipt number = its keccak256"| web
    web --> verify["Verify: re-hash the record,<br/>match the receipt number"]
Loading

What makes Kedge different

  • Refusals are receipts. A refused trade emits Blocked(reason) and the transaction succeeds, so the refusal is permanent public evidence, with the two numbers the rule compared. Guardrails that revert leave only a failed transaction, with no reason on record.
  • The account sets the minimum output, not the agent. Every swap must return at least the higher of the venue's own quote and the oracle value of the whole trade, each less the owner's tolerance. The balances are measured after the swap, not trusted.
  • Checks the data, not the clock. Instead of fixed trading hours, Kedge checks how old the reference price is, and reads the Stock Token's own pause flags, which the issuer sets during corporate actions such as splits.
  • Runs on the real testnet market. Accounts hold Paxos USDG and Robinhood's official test Stock Tokens, and node script/feed-watch.js shows how old the real Chainlink stock feeds on Robinhood Chain mainnet are right now.

Guarantees

Every claim below has at least one named test. Hardhat tests are shown as suite › test.

Guarantee Tests
The agent can call trade() and nothing else. It can't withdraw, deposit, or change the mandate, the allowlists, the feeds or the agent. KedgeAccount: custody › the agent cannot withdraw, deposit, or change the policy, the agent, the allowlists or the feeds · testFuzz_onlyTheOwnerCanWithdraw · invariant_agentNeverHoldsFunds
Only the agent can trade. Not strangers, not even the owner. KedgeAccount: custody › strangers and the owner cannot trade: only the agent can · testFuzz_onlyTheAgentCanTrade
The owner can always withdraw. No dependency on the agent, the price feed, the venue or the expiry. KedgeAccount: custody › the owner can withdraw with the agent revoked, the feed paused, the venue removed and the mandate expired · Adversarial review › withdraw works whatever the feed does and whatever venue is allowed · Adversarial review › renounceOwnership is disabled, so the owner cannot lock the funds in by accident
stop() revokes the agent at once. KedgeAccount: custody › stop() revokes the agent at once
Refusals that reach the policy check are recorded on chain. A refused trade moves nothing, emits Blocked with its reason and the two numbers the rule compared, and succeeds. Every test in KedgeAccount: every refusal is a receipt (one per reason, each asserting the exact event and unchanged balances) · KedgeAccount: trading › a blocked trade is a successful transaction that returns false · invariant_blockedCallsNeverMoveTokens
A decision ID runs at most once, even after it was blocked and the mandate changed. KedgeAccount: decisions run at most once › a decision runs at most once, even after it was blocked and the policy changed · invariant_decisionNeverExecutesTwice · testFuzz_decisionExecutesAtMostOnce
check() returns the same verdict trade() records. KedgeAccount: trading › check() predicts the verdict trade() then records · invariant_checkAgreesWithTradeAndItsReceipt · testFuzz_checkAgreesWithTradeAndRefusalsMoveNothing
A per-trade limit. For a sell, the size is the venue's quote. KedgeAccount: trading › headline: one decision executes under a $150 limit and is blocked under a $50 limit · KedgeAccount: every refusal is a receipt › TradeTooLarge: over the per-trade limit, and the limit itself is allowed · KedgeAccount: trading › a sell is sized by the venue's quote against the per-trade limit
A buy budget that resets 24 hours after the window opens. Sells don't count. KedgeAccount: the 24 hour buy budget › resets 24 hours after the window opens, not on a rolling basis · … › sells never use the budget · invariant_windowSpentWithinBudget · testFuzz_buysNeverExceedTheWindowBudget
An acquisition-cost cap per stock. KedgeAccount: every refusal is a receipt › CostCapExceeded: over the acquisition-cost cap for one stock
The agent can only sell what it bought through the account. Tokens sent in directly are never sold by it. KedgeAccount: custody › tokens sent in directly are untracked and the agent cannot sell them · invariant_trackedUnitsNeverExceedBalance
Tracking stays honest through sells and withdrawals. KedgeAccount: trading › executes a sell and releases cost in proportion · KedgeAccount: custody › full and partial withdrawals keep tracking honest · testFuzz_sellReleasesCostInProportion · testFuzz_withdrawKeepsTrackingHonest
Blocks trades priced too far from the oracle. KedgeAccount: price guard › a pumped pool blocks buys, and the same buy runs once the pool is back · … › a dumped pool blocks sells · all 8 tests in Oracle floor: decimals matrix · invariant_agentOnlyMovesValueThroughSwapsThatMetMinOut
minOut is the higher of the slippage floor and the oracle floor, never below one unit, and set by the account. KedgeAccount: price guard › check() returns minOut = max(slippage floor, oracle floor) (both cases) · Adversarial review › a trade never executes for zero output, even on a dust sell · testFuzz_fairOutMatchesTextbookFormula
Pauses when the reference price is stale, missing, invalid or unreachable. KedgeAccount: price guard › stale, paused, zero-price and missing feeds all block · the Oracle* and NoPriceFeed receipt tests · Adversarial review › hostile price feeds (14 tests)
Pauses when the stock itself is paused, by its issuer (tokenPaused()) or by a registry-wide pause (paused()), with a receipt instead of a revert. Tokens without these flags trade normally. The three AssetPaused tests in KedgeAccount: Stock Token pause guard · … › a pause flag that answers with … (4 tests) · … › check order: … (2 tests)
A paused quote token (USDG has an issuer pause) is refused with a QuotePaused receipt instead of reverting, and trading resumes when the pause is lifted. The 4 tests in KedgeAccount: a paused quote token leaves a receipt
A feed, venue or pause flag can't make a trade revert or cost more than a bounded amount: each read gets 100,000 gas and copies only the words it needs. The 7 tests in KedgeAccount: bounded reads (a feed or quote that burns its gas, an answer too large to build, a valid answer followed by kilobytes of junk, pause flags that burn gas), each sent with a 10M gas limit
A refusal's two numbers explain it: over the limit for size, budget, cost cap, balance, tracked units, age and expiry; the quote under the floor for the price check; zeros otherwise. Every test in KedgeAccount: every refusal is a receipt (each asserts both numbers, in check() and in the event) · testFuzz_checkAgreesWithTradeAndRefusalsMoveNothing
The venue is paid at most amountIn, the output is measured, and no allowance is left behind. Adversarial review › a venue that takes more than amountIn is caught: the trade reverts with VenueOverspent · KedgeAccount: execution › a venue that quotes honestly but delivers half is caught: the trade reverts with InsufficientOutput · KedgeAccount: execution › no allowance is left with the venue after a swap
A venue, token or agent contract cannot call back into the account during a trade. Adversarial review › a venue that re-enters the account during a swap gets nowhere · Adversarial review › a token that calls back into the account on transfer cannot re-enter it
The factory keeps no rights over an account once the call that creates it returns. (During createAccountWithMandate it is the owner, only so it can apply the mandate.) KedgeFactory › makes the caller the owner, and the factory keeps no rights · KedgeFactory: createAccountWithMandate › the factory keeps no rights once the account is created · testFuzz_mandateAccountBelongsToTheCallerAlone
A new account with its whole mandate takes one transaction. If anything in the mandate is invalid, the transaction reverts and no account is created. KedgeFactory: createAccountWithMandate › creates a configured account owned by the caller in one transaction · … › applies every setting of the mandate · … › mismatched asset and feed lists revert, and nothing is created · … › a mandate the account would reject reverts the whole creation · testFuzz_mismatchedListsRevert · on testnet: the tester's only transaction

Test count: 152 Hardhat tests and 18 Foundry tests. The Foundry suite runs 11 fuzz properties at 1,000 runs each, and 7 invariants at 256 runs of 128 random calls each (32,768 calls per invariant, 229,376 in total). In those runs a handler plays the agent, a pool attacker, a failing oracle, the clock, strangers sending tokens, and the owner. Coverage is measured, not assumed: 97% of invariant runs execute buys and 70% execute sells, so the invariants are exercised by real trades, not only by refusals. As a check that they can fail, removing the price guard or the budget check from the contract makes them fail. And as a check on the whole suite, 31 hand-made mutants of the account contract (an off-by-one at the window reset, cost overwritten instead of added, a check moved out of order, an unlimited approval, and so on) each make at least one test fail.

What is not guaranteed

  • Good trades. Inside the mandate, the agent chooses. Kedge limits what it can do, not whether it is right.
  • A correct oracle. The price guard trusts the feed. It also guards only one side: it never blocks a trade for being priced better than the reference, because a better price only helps the user.
  • Losses inside your tolerances. Each trade can land up to your deviation tolerance (2% in the demo) below the reference price, plus venue fees. Sells don't use the budget, so buying and selling back and forth can lose up to roughly twice that tolerance on the day's buys.
  • A receipt for every attempt. Calls from anyone but the agent revert, and so do venue failures and failed checks after the swap. Those leave a failed transaction, not a Blocked event.
  • Instant mandate changes. A change takes effect from the block it is mined in. Lowering the budget partway through a window leaves nothing to spend until it resets.
  • A rolling budget. The budget runs on fixed 24 hour windows, as specified. Buys just before a reset and just after it can together spend up to twice the budget within a short time.
  • Issuer controls. Stablecoin and Stock Token issuers can pause or freeze their tokens. Kedge can't override that: while a Stock Token is paused, nobody can move it, the owner included. Kedge refuses trades in it with a receipt, and the owner can still withdraw everything else. While the quote token (USDG) is paused, Kedge refuses every trade with a QuotePaused receipt, and nobody can move USDG until the pause is lifted.
  • Non-standard tokens. Tokens that charge a fee on transfer or rebase, and tokens or feeds with more than 36 decimals, are out of scope. The quote token is treated as worth exactly $1.
  • Ownership transfers. Transferring ownership is one step, so a wrong address can't be undone. Renouncing is disabled.

How it works

The owner creates an account with its whole mandate in one transaction, KedgeFactory.createAccountWithMandate: which venues and stocks are allowed, a price feed for each stock, the limits in the policy below, and one agent address. That address can call trade() and nothing else. The factory holds ownership only while it applies the settings, then hands it to the caller. On testnet, a brand-new tester created an account, received a drip of test USDG without signing anything, and the agent's first trade executed: one transaction from the tester in total. Its gas, 0.0005 ETH, came from the deployer beforehand.

For every trade(decisionId, venue, tokenIn, tokenOut, amountIn):

  1. One validation function, shared with the check() dry run, runs the checks in a fixed order and stops at the first failure: Duplicate → Expired → VenueNotAllowed → AssetNotAllowed → UnsupportedPair → ZeroAmount → InsufficientBalance → ExceedsTracked → NoLiquidity → TradeTooLarge → BudgetExceeded → CostCapExceeded → NoPriceFeed → OracleUnavailable → OracleInvalid → OracleStale → AssetPaused → QuotePaused → PriceDeviation.
  2. The decision ID is marked used, whatever the outcome.
  3. If a check failed: emit Blocked(agent, decisionId, venue, tokenIn, tokenOut, amountIn, reason, value, limit), move nothing, return false. The transaction succeeds. value and limit are the two numbers the rule compared: the trade's value and the per-trade limit, the price's age and the max age, the quote and the oracle floor, and so on; zeros for rules that compare no numbers.
  4. If every check passed: minOut = max(quote × (1 minus slippage), oracle value × (1 minus deviation), 1 unit). The account approves exactly amountIn, calls the venue, clears the approval, and measures its balances. It reverts if the venue took more than amountIn or delivered less than minOut.
  5. Budget and tracking update from the measured amounts, and Executed(agent, decisionId, venue, tokenIn, tokenOut, spent, received, quoteValue) is emitted.

Reads of the venue quote, the price feed and the pause flags are bounded static calls: each gets 100,000 gas (READ_GAS) and copies only the words it needs, with length checks. A feed or venue that reverts, has no code, returns malformed data, burns its gas or answers with megabytes still produces a Blocked receipt, at a bounded cost to the agent, instead of reverting the trade.

The mandate

struct Policy {
    uint256 maxTradeQuote;   // max quote value of one trade
    uint256 budgetPerWindow; // max quote spent on buys per fixed 24 hour window (only buys count)
    uint256 maxCostPerAsset; // max acquisition cost of the tracked units of one stock
    uint16  maxSlippageBps;  // tolerance against the venue's own quote, at most 5000
    uint16  maxDeviationBps; // tolerance against the oracle value, at most 5000
    uint32  maxOracleAge;    // seconds; an older price blocks trading; must be above 0
    uint64  expiry;          // the agent's authority lapses after this time; 0 means never
}
Owner can Agent can Anyone can
deposit, withdraw, stop, setAgent, setPolicy, setAssetAllowed, setVenueAllowed, setPriceFeed, transferOwnership trade read: check, policy, budgetRemaining, windowResetsAt, windowSpent, decisionUsed, trackedUnits, trackedCost

Adversarial review

After the contract passed its first 74 tests, a second suite attacked it with hostile price feeds, venues that lie or call back in, tokens with transfer hooks and backdoors, and an agent that is itself a contract. 14 of those 29 tests failed at first. Each fix went in only after its failing test. No finding let the agent move funds.

Severity Scenario Fixed
Medium renounceOwnership(), inherited from OpenZeppelin Ownable, could leave the account with no owner, so nobody could withdraw. Disabled: it reverts with RenounceDisabled.
Low A price feed with no code, or one returning short, empty or malformed data, made the trade revert instead of leaving an OracleUnavailable receipt. try/catch does not catch a failed decode. Raw staticcall with length checks; every field is decoded as a full word.
Low A venue with no code, or a short or empty quote, made the trade revert instead of leaving a NoLiquidity receipt. Raw staticcall with a length check.
Low A feed with 60 decimals or an int256 maximum answer overflowed the oracle math, so the trade reverted instead of being blocked. Powers of ten cancel first, a saturating 512-bit mulDiv handles the rest, and feeds above 36 decimals are OracleInvalid. Fuzzed against the textbook formula.
Low Tokens with more than 36 decimals could be allowed or used as the quote token, feeding the overflow above. Refused with UnsupportedDecimals.
Low A dust trade could execute for zero output: every floor rounded down to zero and a venue that paid short delivered nothing. minOut is at least one unit.
Low (23 Sep review) A feed, venue or pause flag could burn all the gas forwarded to it, or answer with megabytes the account then copied, so the agent paid for it or the trade reverted. Each read gets a fixed 100,000-gas stipend and copies only the words it needs.
Low (23 Sep review) A paused quote token made the swap revert, leaving no receipt. Checked before the swap: QuotePaused.
Low (23 Sep review) Blocked did not say which numbers the rule compared. Blocked carries value and limit.

What held up without changes: calls back into the account from a venue, from a token's transfer hook and from a contract agent; a venue taking more than amountIn; withdrawals with every kind of hostile feed; feeds with 0, 8, 18 and 36 decimals; negative prices; and zero or future timestamps.

Bring your own agent

Kedge's agent is one AI; yours can be another. Kedge ships an MCP server (engine/src/mcp/, on the official MCP SDK), so Claude Desktop, or any MCP client, can read a Kedge account, ask it whether a trade would pass, and propose trades. A proposal goes through Kedge's engine: it is recorded as a decision with your agent's reason (the receipt number is the keccak256 of that record, reason included), then sent from Kedge's agent address, so the account's rules decide it on chain like any other decision. The agent role can only call trade(): no tool, key or route here can withdraw or change the rules, and the MCP server holds no wallet key at all.

Tool What it does
get_account(address) The rules, the cash and holdings, and today's spend and what's left of the budget
check_trade(account, side, stock, amount) Runs the account's own check() for that trade and gives the verdict in plain words
propose_trade(account, side, stock, amount, reason) Sends it through the engine as a decision, and returns the result, the transaction and the receipt link

Claude Desktop in 30 seconds:

  1. On your account's page (/account), under "Use your own AI", press Make a key and sign the message. Nothing is sent on chain; the key is shown once.

  2. Build the server once: cd engine && npm ci && npm run build.

  3. In Claude Desktop, open Settings, Developer, Edit Config, add Kedge, and restart it:

    {
      "mcpServers": {
        "kedge": {
          "command": "node",
          "args": ["/absolute/path/to/kedge/engine/dist/mcp/index.js"],
          "env": { "KEDGE_AGENT_KEY": "kedge_..." }
        }
      }
    }
  4. Ask it: "Check my Kedge account 0x... and propose buying $3 of Tesla." With a per-trade limit under $3, the account refuses it with TradeTooLarge, and the receipt, with your agent's reason, appears on the account's page.

Step by step for a Mac, with the exact prompt for a refusal and then a counter-offer: docs/mcp.md.

A live run (26 Sep 2026). Through a real MCP client and the live engine, the tester's account (0x1b12…9a5F, $1.50 a trade) got a $3 Tesla buy from Claude Desktop's server and refused it on chain with TradeTooLarge: the transaction and the receipt. The key behind it was made with the owner's signature alone; the owner's wallet sent nothing.

Without KEDGE_AGENT_KEY the server still reads and checks. KEDGE_ENGINE_URL, KEDGE_RPC and KEDGE_SITE point it elsewhere, for example at a local fork.

How a key works. The owner signs a readable message (the account, a label, the time) in their wallet. The engine checks on chain that the signer owns the account, keeps only the key's SHA-256, and accepts each signed message once, within 10 minutes of its time. A key proposes for its one account only, and the owner revokes it the same way. Limits: one trade per account per check (10 minutes, as for Kedge's own decisions), 60 proposals per network per hour, and 100 a day across all accounts, since each one spends the agent's gas.

Run it

Requires Node 20 or later and Foundry.

npm install
npx hardhat test   # 152 tests
forge test         # 11 fuzz properties and 7 invariants

The demo on a local chain:

npx hardhat node                                          # terminal 1
npx hardhat run script/deploy.js --network localhost      # terminal 2
npx hardhat run script/scenarios.js --network localhost

How old are the real Chainlink stock feeds right now? Read-only, no key needed:

node script/feed-watch.js

Hosting

Part Where Address
Web app Vercel https://kedge-ebon.vercel.app, and kedgelabs.com once the domain is registered
Engine A DigitalOcean droplet in Singapore (1 vCPU, 1 GB, Ubuntu 24.04), behind Caddy with automatic HTTPS https://kedge-ebon.vercel.app/api/engine/health, through the web app

The engine runs as a systemd service under its own user, sandboxed, with its decision record in SQLite under /var/lib/kedge. It listens on localhost only; Caddy handles HTTPS in front of it, and the firewall allows only SSH, HTTP and HTTPS. It starts idle: until its owner sets ENGINE_ACTIVE=true, it answers reads and refuses the rest.

Browsers and Kedge's MCP server reach the engine through the web app, at /api/engine (web/app/api/engine/[...path]/route.ts). The proxy forwards only the engine's public routes, never its admin one, and passes each visitor's address along with a secret the two share, so the engine's per-visitor rate limits still apply. The server's own address stays in the host's settings.

Everything needed to rebuild the server is in engine/deploy/:

ssh root@HOST 'bash -s' < engine/deploy/setup-droplet.sh     # once: user, firewall, fail2ban, updates, swap, Node 24, Caddy
ssh kedge@HOST 'sudo bash -s' < engine/deploy/harden-ssh.sh  # then: no root login, no passwords
ssh kedge@HOST 'sudo bash -s -- API_HOSTNAME' < engine/deploy/install-engine.sh
ssh kedge@HOST kedge-deploy                                   # every later deploy: pull, build, restart, check

Its settings and keys live on the server in /etc/kedge/engine.env (mode 600), never in the repo; engine/.env.example documents each one. engine/railway.json keeps a Railway configuration as an alternative host.

Repository

Path What is there
contracts/ KedgeAccount, KedgeFactory, IKedgeVenue, IPriceFeed
contracts/mocks/ Testnet mocks: MockToken, MockStockToken, MiniAMM, MockPriceFeed, ShortChangeVenue, HoldProbe. hostile/ holds attackers used only in tests.
test/ Hardhat tests (JavaScript, chai)
test-foundry/ Foundry fuzz and invariant tests
web/ The web app (Next.js): the landing page, /demo, /app, /account and the public /a/[address]
docs/brand/ The logo ("Limit gate"): SVG and PNG masters, the wordmark font's license, and the site's favicon and preview cuts
engine/ The reference agent: one decision per check, sent to every account that follows it; engine/src/mcp/ is the MCP server for your own agent; engine/deploy/ runs it on a server
script/ deploy.js and scenarios.js (mock demo), deploy-real.js (real testnet market), probe-real-assets.js, feed-watch.js (real mainnet feeds, read-only), verify.js, and deployments-md.js, which builds DEPLOYMENTS.md; ledger-export.mjs and verify-ledger.mjs (npm run ledger, npm run verify)
ledger.json Every decision the engine sent to an account on chain, with its record; npm run verify checks it against the chain
docs/ JUDGE_EVIDENCE.md (every claim and its evidence), MAINNET.md, mcp.md, security/

Next milestones

  1. kedgelabs.com and api.kedgelabs.com in place of the temporary addresses above.

Kedge is currently an unaudited testnet prototype, with no real-money investment service or promise of returns. Any production rollout would require jurisdiction-specific legal review of the assets, execution model, distribution and applicable user-eligibility requirements.

© 2026 Kedge Labs · MIT License

About

A spending limit for your AI trader. User-owned accounts on Robinhood Chain where on-chain rules decide what an AI agent's trades can do.

Topics

Resources

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages