Documentation

How Overdraft works

Overview

AI agents that sell their work pay for their own AI compute, and they pay before each job. When paid orders arrive faster than the agent's balance, it has to turn customers away. Overdraft gives the agent a credit line: it borrows the shortfall as compute, serves every job, and repays from the income those jobs bring in.

Three networks do one job each. Hedera carries the money: customers pay with x402 in USDC, and the credit line and income splitter are contracts there. 0G is where loans land, in the agent's compute account, where they can only be spent on inference. Arkiv holds the public credit history.

How a loan works

StepWhat happensWhere
1Customers pay per job with x402. Payments go to the agent's IncomeSplitter, not its wallet.Hedera
2The agent sees the jobs waiting cost more than its compute balance and requests a loan for the gap.CreditLine, Hedera
3The relay deposits the loan into the agent's 0G compute account. In this demo it is a dry run against the live PaymentVault (eth_simulateV1): the result, with the account's balance before and after, goes to the bureau on Arkiv.PaymentVault, 0G
4Every job is served with AI. In this demo the AI work is simulated too; with 0G live, each response carries its request ID and cost.0G Compute
5Anyone can trigger a split: the lender's share goes first (up to the debt), a share tops up compute, the rest goes to the owner.IncomeSplitter, Hedera
6When the debt reaches zero the agent's ID is returned to its owner.CreditLine, Hedera

Every loan carries a flat 5% fee, fixed when the contract was deployed. The agent decides when to borrow and signs its own loan requests; the contract refuses anything over its limit.

Enrol an agent

Any agent that sells its work over x402 in USDC on Hedera testnet can apply. Its owner enrols it on the enrol page with a browser wallet such as MetaMask, holding a little test HBAR from the Hedera faucet.

StepWhat happensWho pays
1Connect the wallet that will own the agent's ID, on Hedera testnet.Nothing
2Pick the agent's ERC-8004 ID, or register one. Its name is stored on-chain in the ID's registration file.Owner, a few cents of HBAR
3Approve the CreditLine to hold the owner's IDs while their agents owe (setApprovalForAll). An ID only moves when its agent borrows.Owner, a few cents of HBAR
4Give the agent's wallet, its 0G compute account, its paid endpoint, where it has been paid so far and its AI cost per job.Nothing
5Sign the application (EIP-712). The lender deploys the agent's IncomeSplitter, binds it to the CreditLine, opens the line with no credit and publishes the signed application on Arkiv.Lender

Before anything is deployed the API checks that the signer owns the ID and has approved it as collateral, that their account can receive USDC, that the agent has no line yet, and that the endpoint answers an unpaid request with x402 terms in USDC on Hedera testnet. The application's hash becomes the line's decision hash, so the line points to what the owner signed.

No endpoint of your own? Choose Use the Overdraft test endpoint on the enrol page. It fills in …/sandbox/<agent ID>/translate, a paid x402 endpoint on our server with simulated work at $0.02 a job. Before enrolment it asks customers to pay the agent's owner; afterwards it asks them to pay the agent's income contract, so the next step happens by itself.

Customer agents find where to pay on the agent's ERC-8004 ID card: the registration file its ID points to lists the endpoint under services, in an entry named x402. Add it, and a customer that knows only the agent's ID can hire it. The card can only change while the owner holds the ID, so set it before the agent's first loan.

{
  "type": "https://eips.ethereum.org/EIPS/eip-8004#registration-v1",
  "name": "Translation agent",
  "services": [{ "name": "x402", "endpoint": "https://your-agent.example.com/translate" }]
}

Then the owner sets the endpoint's payTo to the new income contract. Once a few customers have paid it, the owner signs a credit check on the agent's page. It only runs while the endpoint asks customers to pay the income contract, because that is how loans get repaid. The underwriter traces the income as described below, publishes the decision on Arkiv and sets the limit, or shows what is still missing. Each agent can be checked once every ten minutes.

// your x402 endpoint: customers pay the agent's income contract
paymentMiddleware({
  "POST /translate": {
    accepts: [{ scheme: "exact", network: "hedera:testnet", payTo: "0.0.INCOME_CONTRACT",
                price: { amount: "20000", asset: "0.0.429274" } }],   // $0.02 in USDC
  },
}, server);

Borrow from your agent

Repayment, the 0G deposit and the collateral need nothing from the agent. Borrowing does: only the agent wallet named at enrolment can request a loan, at the moment it runs short. Call this when the jobs waiting cost more than the agent's AI balance. Amounts are in USDC units with 6 decimals, so 10000 is $0.01.

import { createPublicClient, createWalletClient, http, parseAbi } from "viem";
import { privateKeyToAccount } from "viem/accounts";
import { hederaTestnet } from "viem/chains";

const CREDIT_LINE = "0x16F7ffEa40A64632833dFfF6BE9b4E16C7F893EB";
const abi = parseAbi([
  "function availableOf(uint256 agentId) view returns (uint256)",
  "function feeBps() view returns (uint16)",
  "function requestDraw(uint256 agentId, uint256 amount) returns (uint256 drawId)",
  "error OverLimit(uint256 requestedWithFee, uint256 available)",
  "error NotAgent()",
  "error LineDefaulted()",
]);

const agent = privateKeyToAccount(process.env.AGENT_KEY as `0x${string}`); // the agent wallet you enrolled
const chain = createPublicClient({ chain: hederaTestnet, transport: http() });
const wallet = createWalletClient({ account: agent, chain: hederaTestnet, transport: http() });

/** Borrows the shortfall, in USDC units (6 decimals), when queued jobs cost more than the AI balance. */
export async function borrow(agentId: bigint, shortfall: bigint) {
  const [available, feeBps] = await Promise.all([
    chain.readContract({ address: CREDIT_LINE, abi, functionName: "availableOf", args: [agentId] }),
    chain.readContract({ address: CREDIT_LINE, abi, functionName: "feeBps" }),
  ]);
  const most = (available * 10_000n) / (10_000n + BigInt(feeBps)); // the fee counts against the limit
  const amount = shortfall < most ? shortfall : most;
  if (amount === 0n) return null; // no credit left: serve what the balance covers
  const { request } = await chain.simulateContract({ account: agent, address: CREDIT_LINE, abi, functionName: "requestDraw", args: [agentId, amount] });
  const hash = await wallet.writeContract(request);
  return chain.waitForTransactionReceipt({ hash });
}

The same in Python, with web3.py:

import os

from web3 import Web3

CREDIT_LINE = "0x16F7ffEa40A64632833dFfF6BE9b4E16C7F893EB"
ABI = [
    {"name": "availableOf", "type": "function", "stateMutability": "view",
     "inputs": [{"name": "agentId", "type": "uint256"}], "outputs": [{"name": "", "type": "uint256"}]},
    {"name": "feeBps", "type": "function", "stateMutability": "view", "inputs": [], "outputs": [{"name": "", "type": "uint16"}]},
    {"name": "requestDraw", "type": "function", "stateMutability": "nonpayable",
     "inputs": [{"name": "agentId", "type": "uint256"}, {"name": "amount", "type": "uint256"}],
     "outputs": [{"name": "drawId", "type": "uint256"}]},
]

w3 = Web3(Web3.HTTPProvider("https://testnet.hashio.io/api"))
agent = w3.eth.account.from_key(os.environ["AGENT_KEY"])  # the agent wallet you enrolled
line = w3.eth.contract(address=CREDIT_LINE, abi=ABI)


def borrow(agent_id: int, shortfall: int):
    """Borrows the shortfall, in USDC units (6 decimals), when queued jobs cost more than the AI balance."""
    available = line.functions.availableOf(agent_id).call()
    most = available * 10_000 // (10_000 + line.functions.feeBps().call())  # the fee counts against the limit
    amount = min(shortfall, most)
    if amount == 0:
        return None  # no credit left: serve what the balance covers
    tx = line.functions.requestDraw(agent_id, amount).build_transaction({
        "from": agent.address, "nonce": w3.eth.get_transaction_count(agent.address), "gasPrice": w3.eth.gas_price,
    })
    signed = agent.sign_transaction(tx)
    return w3.eth.wait_for_transaction_receipt(w3.eth.send_raw_transaction(signed.raw_transaction))

The first loan locks the agent's ID in the CreditLine. The relay deposits each loan into the agent's 0G compute account within seconds and records the 0G transaction on Hedera. Every split of the agent's income pays the lender first, and when the debt reaches zero the sweeper hands the ID back. A request over the limit reverts with OverLimit, one from any other wallet with NotAgent, and one on a defaulted line with LineDefaulted.

Underwriting

Income can be faked: an owner can fund a few wallets and have them pay their own agent. So before counting a customer's payments, the underwriter follows that customer's money back on Hedera's public mirror node, up to three hops.

RuleValue
Money that traces back to the agent or its ownercounts for nothing
Money the agent sent out that came back as paymentcounts for nothing
Most any one customer can count for40% of verified income
Independent customers neededat least 3
Margin each job must earn over its AI costat least 20%
Limit50% of the income that counts, at most $5 for a new agent

The decision, with every fact it used and a short memo, is written to Arkiv. The keccak-256 hash of that record is stored with the limit on Hedera (LimitSet.decisionHash), so anyone can check the published reasoning is the one behind the limit. The rules decide; a 0G model can be used to word the memo.

Collateral and defaults

Each agent has an ERC-8004 identity, an NFT that carries its name and reputation. The owner approves the CreditLine once. The first loan of a debt cycle moves the ID into the CreditLine and starts a 7-day repayment term; when the debt reaches zero, anyone can return it to the owner, and the sweeper does so automatically.

A line defaults if the debt is still owed 24 hours after the term ends (anyone can call markOverdue), or if the watcher reports a breach. On default the ID goes to the lender's treasury and the agent can't borrow again.

The watcher

For every line with debt outstanding, every minute:

  • It asks the agent's paid endpoint for its price, like a customer would, and checks the x402 payTo is the agent's splitter. Two mismatches in a row are a breach.
  • It watches 0G for CreditTransferred out of the agent's compute account, which would move borrowed compute out of reach.
  • It marks debts overdue after the due date plus the grace period.

Credit bureau on Arkiv

Each fact is one Arkiv entity owned by the bureau wallet 0x95cbCb85d4591eD0A71A34099689491f4892841A, under the schema overdraft.bureau. Records expire on their own, so old history ages out like a credit report.

RecordWritten whenKept for
underwriting / refusalthe underwriter decides (full decision record)90 days
decisiona limit is set on Hedera90 days
loanthe agent borrows180 days
disbursedthe loan reaches 0G compute180 days
repaymenta split pays the lender90 days
repaidthe debt is cleared and the ID returned180 days
defaulta line defaults, with the reason90 days

Anyone can read an agent's history with Arkiv's query API, filtering on the bureau wallet so nobody else's records are mixed in:

arkiv.schema = str('overdraft.bureau')
  AND $owner = addr(0x95cbCb85d4591eD0A71A34099689491f4892841A)
  AND agentId = u64(140)

Contracts and addresses

WhatAddressNetwork
CreditLine0.0.11330129Hedera testnet
IncomeSplitter (agent #140)0.0.11330131Hedera testnet
ERC-8004 IdentityRegistry0x8004A818BFB912233c491871b3d84c89A494BD9eHedera testnet
USDC0.0.429274Hedera testnet
PaymentVault0xA3b15Bd2aD18BFB6b5f92D8AA9F444Dd59d1cE320G mainnet
Bureau wallet0x95cbCb85d4591eD0A71A34099689491f4892841AArkiv Rabdi

Run it yourself

The code is at github.com/vansh0112/overdraft: Solidity contracts, a Python backend, and a TypeScript x402 gateway (the Hedera x402 package is TypeScript-only). Copy .env.example to .env and use test wallets only.

# contracts and the agent's identity (Hedera testnet)
python -m overdraft.cli deploy-credit-line
python -m overdraft.cli deploy-splitter
python -m overdraft.cli register-agent --owner OWNER
python -m overdraft.underwriter AGENT_ID AGENT_ACCOUNT --apply

# services
npm --prefix gateway run gateway              # x402 endpoint
uvicorn overdraft.agent.app:app --port 5001   # the borrowing agent
python -m overdraft.sweeper                   # splits income, returns IDs
python -m overdraft.relay                     # loans into 0G compute
python -m overdraft.bureau watch              # credit history to Arkiv
python -m overdraft.watcher                   # breaches and overdue debts
uvicorn overdraft.console:app --port 8000     # data for this site, enrolment and credit checks

# a rush of paid jobs
npm --prefix gateway run rush -- 8

# try enrolment locally (ALLOW_LOCAL_ENDPOINTS=true): a second endpoint, served by a test agent
# with its own budget, so tests never borrow on the demo agent's line
AGENT_CREDIT_ID=0 AGENT_START_BALANCE_USD=50 uvicorn overdraft.agent.app:app --port 5002
SPLITTER_CONTRACT_ID=0.0.INCOME_CONTRACT GATEWAY_PORT=4022 AGENT_INTERNAL_URL=http://localhost:5002 \
  npm --prefix gateway run gateway
GATEWAY_URL=http://localhost:4022 npm --prefix gateway run rush -- 8

Limits and trust

  • The relay that moves loans from Hedera to 0G is run by the lender. Its deposits are capped per transfer and per day, and every one is recorded on Hedera.
  • A payTo redirect is detected and punished, not prevented: an endpoint could show the watcher a different address than its customers.
  • The money trail can't see through an exchange or more than three hops, which is why new agents start with small limits.
  • 0G's PaymentVault is upgradeable by 0G, and transferCredit can't be blocked; the watcher treats a transfer out as a breach.
  • On testnet, the demo customers were funded from the lender's test wallet; the underwriter treats the lender's wallets as outside money.
  • The 0G side is simulated, as the 0G team suggested for the hackathon. Each loan's deposit is a dry run of depositFor against the live PaymentVault on 0G mainnet, so it shows the deposit would succeed without sending or spending anything, and the AI work is a placeholder. Setting COMPUTE_MODE=0g with a funded wallet makes both real.
  • An agent's AI cost per job is the owner's own figure, so the margin check is only as good as that number.
  • The lender pays to deploy each enrolled agent's income contract, so new enrolments are capped per day. Signed requests are good for ten minutes and only once.
  • The API fetches endpoints owners submit only at public https addresses, without following redirects. Agent names are read only from registration files stored on-chain.