Autonomous working capital on Hedera
A seller agent turns a buyer-agent-signed receivable into USDC working capital that its worker agents can spend through x402. When the buyer agent pays, lenders are repaid first, automatically.
Quickstart
Every agent needs an ECDSA secp256k1 key and a Hedera testnet account with an EVM alias. Fund accounts with testnet USDC from the Circle faucet, then drive all eight steps from scripted agents.
HEDERA_OPERATOR_ID=0.0.x
HEDERA_OPERATOR_KEY=0x… # ECDSA
COORDINATOR_KEY=0x… COSIGNER_KEY=0x… KYA_ISSUER_KEY=0x…
SELLER_KEY BUYER_KEY WORKER_RESEARCH_KEY WORKER_COMPUTE_KEY
LENDER_A_KEY LENDER_B_KEY LENDER_C_KEY
HCS_AUDIT_TOPIC_ID=0.0.x
USDC_TOKEN_ID=0.0.429274
X402_FACILITATOR_URL=https://api.testnet.blocky402.com$ pnpm install && pnpm -r build $ pnpm setup:accounts # demo accounts → .env.accounts (run once) $ pnpm -F @casheth/merchant start # x402 merchant · :3003 $ pnpm -F @casheth/auth start # authorization server · :4020 $ pnpm -F @casheth/mcp start # MCP server + read API · :4030 $ pnpm demo # drives all eight steps
Connect an agent
Agents reach CashETH through one MCP endpoint, http://localhost:4030/mcp: stateless Streamable HTTP, POST only, JSON responses, no session id. Any MCP client works; point it at the endpoint and it discovers the authorization server from the 401.
{
"mcpServers": {
"casheth-seller": {
"type": "http", "url": "http://localhost:4030/mcp",
"oauth": { "scopes": "receivable:write receivable:read credit:read facility:open budget:write spend:reserve stats:read" },
"timeout": 600000
}
}
}The seller is the only agent you sign in as: the sign-in page shows your seller and its permissions, and you click Approve. The buyer, the lenders and the workers are run by the server, so the seller drives the whole flow (request_buyer_confirmation, buy_with_credit, settle_receivable). Call whoami to see which account the connection acts as.
The MCP server is an OAuth 2.1 resource server. An agent signs a JWT with its ECDSA secp256k1 key and exchanges it (RFC 7523 JWT-bearer) at the CashETH authorization server for a 10-minute token bound to the MCP audience. Identity is the token's agent claim; role and scopes come from its KYARegistry entry. Tokens are never passed through to other services.
1 POST /mcp, no token → 401 + resource_metadata 2 GET /.well-known/oauth-protected-resource/mcp 3 POST {AUTH_ISSUER}/token grant_type=jwt-bearer assertion=<agent JWT> resource=…/mcp 4 ← { access_token, expires_in: 600, scope } 5 POST /mcp Authorization: Bearer … → 200
| ROLE | SCOPES (KYA LEVEL ≥ 2) |
|---|---|
| seller | receivable:write receivable:read credit:read facility:open budget:write spend:reserve stats:read |
| buyer | receivable:confirm receivable:read credit:read repay:write stats:read |
| worker | receivable:read credit:read spend:reserve spend:pay spend:commit stats:read |
| lender | receivable:read credit:read stats:read lend:write |
| owner | agent:admin (the KYA issuer only, JWT-bearer grant) |
idempotencyKey (8–128 chars). A repeat returns the stored result with _meta.replayed: true and no side effects; the same key with different arguments is IDEMPOTENCY_KEY_REUSED. Human MCP clients such as Claude Code can use the demo authorization-code grant (AUTH_DEMO_GRANT=true, local only).Architecture
Everything runs on Hedera testnet, so lock and lend happen in one transaction. Off-chain trust is limited to the coordinator, whose every limit the contracts re-check, and the policy co-signer, which can refuse a payment but cannot move funds alone.
| LAYER | COMPONENT | RESPONSIBILITY |
|---|---|---|
| Access | MCP server | Tool surface for every agent. OAuth 2.1 resource server; scopes and roles per tool. |
| Brain | Orchestrator | Verify and dedupe, credit score, KYA, two-phase spend, coordinator signer, co-signer, event log. |
| EVM | ReceivableRegistry | Verifies the EIP-712 confirmation. Canonical ID. State machine. |
| EVM | CreditFacility | Funds through Aqua, holds USDC, manages budgets and reservations, schedules checks. |
| EVM | RepaymentRouter | Takes the buyer's payment and runs the waterfall. |
| EVM | AquaCreditSwapVMRouter | Official Aqua plus SwapVM with the credit opcode. |
| Native | HTS · HCS · HSS | USDC and receivable NFT · audit topic · scheduled overdue and default checks. |
Agents & KYA
Every agent has an ECDSA key, an HCS-14 UAID with its profile on HCS, and a KYARegistry entry holding role, level, owner-group hash, expiry and revocation.
Fake-buyer controls
AgentMandate(address agent, uint8 role, uint256 maxPerTx, uint256 maxDaily,
address[] merchants, uint64 expiresAt, uint256 nonce)Receivables
The buyer agent signs a typed confirmation whose payTo must equal the repayment router. Only commitments, amounts and states go on-chain; the invoice and its salt are shared with matched lenders only.
struct ReceivableConfirmation { address seller; // seller agent EVM address address buyer; // buyer agent (the signer) address currency; // USDC ERC-20 facade uint256 amount; // base units, 6 decimals uint64 dueDate; bytes32 buyerRef; // buyer's PO / AP reference bytes32 detailsCommitment; // keccak256(invoiceDocHash, salt) address payTo; // MUST equal RepaymentRouter uint256 nonce; uint64 deadline; } id = keccak256(abi.encode(buyer, buyerRef))
State machine
Registry rules
DUPLICATE_RECEIVABLEBAD_BUYER_SIGWRONG_PAYEETERM_INELIGIBLEBAD_NONCEKYA_FAILSELF_DEALINGCredit facility
One contract holds many facilities, keyed by receivable ID. openAndFund fills strategies cheapest-first and marks the ID Financed in the same transaction — any failure reverts everything.
function openAndFund(bytes32 id, Fill[] calldata fills, uint16 advanceBps, uint256 limit, bytes calldata coordinatorSig) external onlyCoordinator; // 1. registry.state(id) == Confirmed // 2. sum(fills) <= amount * advanceBps / 1e4 and <= limit // 3. fills sorted by aprBps ascending // 4. router.swap(...) per fill → credit opcode → onCreditFill // 5. registry.markFinanced(id) // 6. HSS: markOverdue @ due+7d, markDefaulted @ due+30d
Invariants
Aqua & SwapVM
We redeploy the official Aqua registry and a SwapVM router with one extra instruction. _receivableCredit runs first in each lender's program and gates every fill on the on-chain receivable state. USDC stays in the lender's wallet until a fill.
taker == facility // only our facility can fill registry.state(id) == Confirmed // the core rule dueDate - now <= maxTenorDays advance <= maxAdvanceBps kya.reputation(buyer).onTime >= minBuyerOnTime makerExposure(buyer) + amount <= maxPerBuyer → price 1 RCN : 1 USDC, facility.onCreditFill(id, maker, amount, aprBps)
Solver, worked example
x402 spending
x402 on Hedera debits the client's own account, so a contract cannot pay directly. Each worker pays from a spend wallet with a 2-of-2 threshold key — worker plus policy co-signer — that holds zero balance between payments.
GET /research?topic=… 402 Payment Required network hedera:testnet asset 0.0.429274 (USDC) amount 250000 # $0.25 payTo 0.0.… feePayer facilitator
External x402 merchants
Workers can buy from any x402 merchant through the same reserve → pay_x402 → commit flow and guardrails. Nothing is trusted from a merchant's catalogue: the MCP server fetches only origins listed in MERCHANT_ORIGINS, the seller's budget must allow the payee, and the co-signer signs only when the 402's payTo equals the reservation's merchant. A rogue payee is refused as COSIGNER_REFUSED and recorded as SpendRejected.
Repayment waterfall
Partial payments go to lenders first. A payment after a default still reaches lenders first. Spending stops at the due date; overdue and default checks are scheduled through HSS and are also permissionless.
MCP tools
21 tools. Each checks the token's scope, then its role, then that the caller is the right party; a failure is a tool result with a code, not an HTTP error. Every result is one JSON text item. Mutating tools also take an idempotencyKey. Tools that need an agent's own key return calldata for the agent to sign unless the demo key flags are on.
| TOOL | ROLE | SCOPE | EFFECT |
|---|---|---|---|
| register_agent | owner | agent:admin | KYARegistry.register by the KYA issuer · HCS-14 profile as AgentRegistered |
| upload_invoice_document | seller | receivable:write | Stores the invoice file and reads its fields · InvoiceDocumentStored (hashes only) · optional HFS copy |
| get_invoice_document | any | receivable:read | — |
| upload_receivable | seller | receivable:write | Pending record + EIP-712 confirmation request · ReceivableUploaded |
| confirm_receivable | buyer | receivable:confirm | ReceivableRegistry.register · receivable NFT mint · ReceivableConfirmed + NftMinted |
| get_receivable_status | any | receivable:read | — |
| get_quotes | seller | credit:read | — (Aqua discovery + solver preview) |
| open_facility | seller | facility:open | CreditFacility.openAndFund, cheapest strategies first · FacilityFunded |
| set_budgets | seller | budget:write | CreditFacility.setBudgets (seller key, or calldata to sign) |
| reserve_spend | sellerworker | spend:reserve | Engine checkSpend, then CreditFacility.reserve · SpendReserved / SpendRejected |
| pay_x402 | worker | spend:pay | Co-signed x402 payment (Hedera transfer) to an allowed merchant origin |
| commit_spend | worker | spend:commit | CreditFacility.commit · SpendCommitted |
| release_spend | sellerworker | spend:reserve | CreditFacility.release of an expired reservation · SpendReleased |
| repay_receivable | buyer | repay:write | USDC.approve + RepaymentRouter.repay, lenders first · Repaid |
| explain_decision | any | credit:read | — (AI explains a deterministic decision, never makes one) |
| list_agents | any | stats:read | — |
| get_agent_stats | any | stats:read | — |
| whoami | any | stats:read | — (the caller's address, role, KYA level and scopes from its token; no chain reads) |
| fund_agents | lender | lend:write | Aqua ship of a credit (and optional base-yield) strategy · StrategyShipped |
| get_lender_yield | lender | stats:read | — |
| close_strategy | lender | lend:write | Aqua dock · StrategyDocked |
Read API
The same server answers unauthenticated GET requests on http://localhost:4030 for dashboards, including the admin console at /admin. It returns only hashes, addresses, amounts and states. Amounts are USDC base units as strings (6 decimals: "250000" is $0.25). Browser origins must be listed in CORS_ORIGINS.
| ENDPOINT | RETURNS |
|---|---|
| GET /health | { ok, resource, authorizationServer, events } — liveness and the audit event count |
| GET /events | AuditEvent[] — every state change and rejection, oldest first, each mirrored on the HCS audit topic |
| GET /agents | AgentStats[] — KYA level, score, risk slab and rate, on-time %, receivables funded / repaid / defaulted, spend by merchant |
| GET /lenders | LenderYield[] — capital, lent, idle, funded slabs and sellers, farming / lending / blended APR, extra earned over farming |
| GET /receivables/:id | State, amount funded and the lenders owed for one receivable |
| GET /invoices/:keccak256 | The invoice file itself, so anyone can hash it against the registry's detailsCommitment |
{
"v": 1, "type": "SpendCommitted", "seq": 42, "prevSeq": 41,
"ts": "2026-11-07T12:04:31.000Z",
"id": "0x…", # receivable id
"spendId": "0x…", "amount": "800000", "merchant": "0.0.…",
"agent": "0x…", # the calling agent
"hashscan": "https://hashscan.io/testnet/transaction/…",
"hcsSeq": 214 # same message on the HCS audit topic
}Error codes
The same names are used by the engine, the contracts and the MCP server, so a rejection reads the same wherever it is caught.
DUPLICATE_RECEIVABLEregistryBAD_BUYER_SIGregistryWRONG_PAYEEregistryBAD_NONCEregistryTERM_INELIGIBLEregistryKYA_FAILregistrySELF_DEALINGregistryNOT_CONFIRMEDfacility · opcodeBORROWING_BASE_EXCEEDEDfacilityNOT_CHEAPEST_FIRSTfacilityAGENT_BUDGET_EXCEEDEDengine · facilityTX_LIMIT_EXCEEDEDengine · facilityDAILY_LIMIT_EXCEEDEDengine · facilityMERCHANT_NOT_ALLOWEDengine · facilityGLOBAL_CREDIT_LIMIT_EXCEEDEDengine · facilityRESERVATION_EXPIREDfacilityFACILITY_NOT_ACTIVEfacilityPAUSEDfacilityNOT_PARTYfacility · MCPWALLET_BUSYfacilityRESERVATION_NOT_OPENfacilityBUDGETS_EXCEED_FUNDEDfacilityNOT_FINANCEDrepayment routerZERO_AMOUNTrepayment routerSELLER_NOT_FUNDED_BY_LENDERAqua opcodeLENDER_RESERVE_TOO_LOWAqua opcodeINSUFFICIENT_SCOPEMCP · scope checkKYA_LEVEL_TOO_LOWauth serverA contract revert outside this list is CONTRACT_REVERTED. The MCP server adds its own codes:
| CODE | MEANING |
|---|---|
| INSUFFICIENT_SCOPE | The token lacks the tool's scope or role (reason: scope | role) |
| NOT_PARTY | The caller is not the seller, buyer or worker this call is about |
| BAD_INPUT | Malformed id, address, amount or URL (field) |
| INVOICE_MISMATCH | The invoice document's printed terms differ from the submitted ones |
| NOT_FOUND | Unknown pending id, receivable or strategy |
| NOT_DEPLOYED | addresses.json lacks a contract the call needs |
| IDEMPOTENCY_KEY_REUSED | Same idempotency key, different arguments |
| CREDIT_DECLINED | The deterministic credit decision is not approved (reasons) |
| NO_ELIGIBLE_LIQUIDITY | No lender strategy can fund the receivable (skipped) |
| SPEND_WALLET_NOT_REGISTERED | reserve_spend wallet is not the worker's registered 2-of-2 with the co-signer |
| MERCHANT_URL_NOT_ALLOWED | pay_x402 URL origin is not configured for the reservation's merchant |
| COSIGNER_REFUSED | The policy co-signer refused the x402 payment (reason) |
| PAYMENT_FAILED | The merchant answered without a settlement |
| PAYMENT_IN_FLIGHT | A payment for this reservation is in flight or was co-signed without a seen settlement |
| RESERVATION_PAID | release_spend on a reservation pay_x402 settled: commit it instead |
| RESERVATION_NOT_EXPIRED | release_spend before the reservation's expiry |
| ALREADY_REPAID | repay_receivable on a receivable that is already Repaid |
| KEY_NOT_HELD | The server would need an agent key it does not hold (demo flags off) |
| CONTRACT_REVERTED | A contract reverted with a custom error outside the shared list (error, args) |
| CHAIN_ERROR | An RPC failure or an undecodable revert |
| INTERNAL | Anything else |
Configuration
Hedera testnet · EVM chain ID 296https://testnet.hashio.io/apihttps://testnet.mirrornode.hedera.com/api/v10.0.429274 · 0x0000000000000000000000000000000000068cda · 6 dp0xb1F616b8134F602c3Bb465fB5b5e6565cCAd37Ed · 8 dpHTS 0x167 · HAS 0x16a · HSS 0x16bapi.testnet.blocky402.com · x402.org/facilitator · testnet.facilitator.launa.devhttps://hashscan.io/testnethttp://localhost:4030/mcp · POST · stateless Streamable HTTPhttp://localhost:4030 · GET · no authhttp://localhost:40200.0.113389270.0.11338934MCP server environment
| VARIABLE | DEFAULT | USE |
|---|---|---|
| MCP_PORT | 4030 | Listen port |
| HOST | 127.0.0.1 | Interface the MCP and authorization servers bind to |
| MCP_RESOURCE_URL | http://localhost:4030/mcp | Token audience and MCP path |
| AUTH_ISSUER | http://localhost:4020 | Authorization server; metadata fetched at boot, issuer must match |
| COORDINATOR_KEY, COSIGNER_KEY | required | Coordinator writes; x402 co-signature |
| KYA_ISSUER_KEY | — | register_agent |
| HCS_AUDIT_TOPIC_ID, RECEIVABLE_NFT_TOKEN_ID | deployments/testnet/hedera.json | Audit topic and receivable NFT collection |
| DATA_DIR | apps/mcp-server/data | events.jsonl, idempotency.json, pending.json, invoices/ |
| CORS_ORIGINS | http://localhost:3000 | Browser origins allowed on the read API (add the admin console's origin) |
| ANTHROPIC_API_KEY | — | explain_decision via claude-haiku-5-5 |
| HFS_ENABLED | false | Also store invoice documents on the Hedera File Service |
| CASHETH_LLM_PROVIDER | — (probe) | ollama forces the local model for invoice field extraction |
| OLLAMA_BASE_URL, CASHETH_LLM_MODEL | http://localhost:11434, qwen2.5:7b | Ollama OpenAI-compatible endpoint |
| AGENT_KEYS_IN_PROCESS | false | Demo: the server signs as seller, buyer and workers (true), or only the listed roles (seller,worker); other roles get calldata |
| LENDER_KEYS_IN_PROCESS | false | Demo: the server signs as lenders |
| AQUA_FROM_BLOCK | swap router creation block | First block for Aqua log discovery |
| MERCHANT_ORIGINS | — | Extra accountId=origin pairs: the only origins pay_x402 fetches |
Contract addresses are read from deployments/testnet/addresses.json on every call, never hard-coded.
BACK TOOverview↑