docs · v0.1
GETTING STARTED

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.

AGENTSseller · buyer · worker · lender→ACCESSMCP server + auth→BRAINorchestrator→HEDERA EVMregistry · facility · router · Aqua
ROOT OF TRUSTNothing is financeable without a buyer-signed EIP-712 confirmation. Credit decisions are deterministic — AI explains a decision but never approves one.

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.

.env
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
terminal
$ 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.

.mcp.json · one seller connection
{
  "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.

auth flow
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
ROLESCOPES (KYA LEVEL ≥ 2)
sellerreceivable:write receivable:read credit:read facility:open budget:write spend:reserve stats:read
buyerreceivable:confirm receivable:read credit:read repay:write stats:read
workerreceivable:read credit:read spend:reserve spend:pay spend:commit stats:read
lenderreceivable:read credit:read stats:read lend:write
owneragent:admin (the KYA issuer only, JWT-bearer grant)
IDEMPOTENT BY DESIGNEvery state-changing tool takes an 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.

LAYERCOMPONENTRESPONSIBILITY
AccessMCP serverTool surface for every agent. OAuth 2.1 resource server; scopes and roles per tool.
BrainOrchestratorVerify and dedupe, credit score, KYA, two-phase spend, coordinator signer, co-signer, event log.
EVMReceivableRegistryVerifies the EIP-712 confirmation. Canonical ID. State machine.
EVMCreditFacilityFunds through Aqua, holds USDC, manages budgets and reservations, schedules checks.
EVMRepaymentRouterTakes the buyer's payment and runs the waterfall.
EVMAquaCreditSwapVMRouterOfficial Aqua plus SwapVM with the credit opcode.
NativeHTS · HCS · HSSUSDC 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.

0Unknown key. Nothing allowed.
1Key proven, UAID registered. Read tools only.
2Owner KYC/KYB hash plus a signed mandate. Sellers borrow; workers spend.
3External KYA attestation or repayment history. Required to act as a buyer.

Fake-buyer controls

Owner separationownerGroup(buyer) ≠ ownerGroup(seller), enforced in register.
Reputation thresholdRepayments update reputation on-chain and on HCS.
Per-buyer exposure capIn the borrowing base and in every lender's strategy.
EIP-712 · owner → agent mandate
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.

domain "AgentReceivables" · v1 · chainId 296
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

None→Confirmed→Financed→Repaid
exitsOverdue→DefaultedCancelled · before Financed

Registry rules

01state[id] == NoneDUPLICATE_RECEIVABLE
02ECDSA.recover(typed data) == buyerBAD_BUYER_SIG
03payTo == repaymentRouterWRONG_PAYEE
04Before deadline; due date within 1–120 daysTERM_INELIGIBLE
05nonces[buyer] == nonce, then incrementBAD_NONCE
06Buyer KYA ≥ 3, seller ≥ 2, neither revokedKYA_FAIL
07ownerGroup(buyer) ≠ ownerGroup(seller)SELF_DEALING

Credit 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.

CreditFacility.sol
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

debt(id) ≤ borrowingBase(id)
Σ budgets ≤ funded
seller gets 0 while any lender is owed
committed + reserved + available = funded

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.

opcodes/ReceivableCredit.sol
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

Lender A7.00%$4,000 filled
Lender B8.50%$2,000 filled
Lender C13.00%not needed

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.

01 RESERVELimits checked twice. Exactly the amount moves to the spend wallet.
02 PAYCo-signer signs only if payTo, asset and amount match the reservation.
03 COMMITHedera tx ID recorded on-chain and to HCS.
— RELEASEOn timeout, unspent USDC is pulled back via allowance.
merchant · paid research API
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.

fee_i = principal_i × apr_i × max(elapsed, minTerm) / 365d
lenderDue = Σ (principal_i + fee_i)
payment → lenders pro rata → seller remainder
Receivable · Net 30 · 75% advance$10,000.00
Funded · A $4,000 @ 7% + B $2,000 @ 8.5%$6,000.00
Fees · A $23.01 + B $13.97$36.99
Lenders receive$6,036.99
Seller agent receives$3,963.01 + undrawn
REFERENCE

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.

TOOLROLESCOPEEFFECT
register_agentowneragent:adminKYARegistry.register by the KYA issuer · HCS-14 profile as AgentRegistered
upload_invoice_documentsellerreceivable:writeStores the invoice file and reads its fields · InvoiceDocumentStored (hashes only) · optional HFS copy
get_invoice_documentanyreceivable:read—
upload_receivablesellerreceivable:writePending record + EIP-712 confirmation request · ReceivableUploaded
confirm_receivablebuyerreceivable:confirmReceivableRegistry.register · receivable NFT mint · ReceivableConfirmed + NftMinted
get_receivable_statusanyreceivable:read—
get_quotessellercredit:read— (Aqua discovery + solver preview)
open_facilitysellerfacility:openCreditFacility.openAndFund, cheapest strategies first · FacilityFunded
set_budgetssellerbudget:writeCreditFacility.setBudgets (seller key, or calldata to sign)
reserve_spendsellerworkerspend:reserveEngine checkSpend, then CreditFacility.reserve · SpendReserved / SpendRejected
pay_x402workerspend:payCo-signed x402 payment (Hedera transfer) to an allowed merchant origin
commit_spendworkerspend:commitCreditFacility.commit · SpendCommitted
release_spendsellerworkerspend:reserveCreditFacility.release of an expired reservation · SpendReleased
repay_receivablebuyerrepay:writeUSDC.approve + RepaymentRouter.repay, lenders first · Repaid
explain_decisionanycredit:read— (AI explains a deterministic decision, never makes one)
list_agentsanystats:read—
get_agent_statsanystats:read—
whoamianystats:read— (the caller's address, role, KYA level and scopes from its token; no chain reads)
fund_agentslenderlend:writeAqua ship of a credit (and optional base-yield) strategy · StrategyShipped
get_lender_yieldlenderstats:read—
close_strategylenderlend:writeAqua 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.

ENDPOINTRETURNS
GET /health{ ok, resource, authorizationServer, events } — liveness and the audit event count
GET /eventsAuditEvent[] — every state change and rejection, oldest first, each mirrored on the HCS audit topic
GET /agentsAgentStats[] — KYA level, score, risk slab and rate, on-time %, receivables funded / repaid / defaulted, spend by merchant
GET /lendersLenderYield[] — capital, lent, idle, funded slabs and sellers, farming / lending / blended APR, extra earned over farming
GET /receivables/:idState, amount funded and the lenders owed for one receivable
GET /invoices/:keccak256The invoice file itself, so anyone can hash it against the registry's detailsCommitment
GET /events · one AuditEvent
{
  "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_RECEIVABLEregistry
BAD_BUYER_SIGregistry
WRONG_PAYEEregistry
BAD_NONCEregistry
TERM_INELIGIBLEregistry
KYA_FAILregistry
SELF_DEALINGregistry
NOT_CONFIRMEDfacility · opcode
BORROWING_BASE_EXCEEDEDfacility
NOT_CHEAPEST_FIRSTfacility
AGENT_BUDGET_EXCEEDEDengine · facility
TX_LIMIT_EXCEEDEDengine · facility
DAILY_LIMIT_EXCEEDEDengine · facility
MERCHANT_NOT_ALLOWEDengine · facility
GLOBAL_CREDIT_LIMIT_EXCEEDEDengine · facility
RESERVATION_EXPIREDfacility
FACILITY_NOT_ACTIVEfacility
PAUSEDfacility
NOT_PARTYfacility · MCP
WALLET_BUSYfacility
RESERVATION_NOT_OPENfacility
BUDGETS_EXCEED_FUNDEDfacility
NOT_FINANCEDrepayment router
ZERO_AMOUNTrepayment router
SELLER_NOT_FUNDED_BY_LENDERAqua opcode
LENDER_RESERVE_TOO_LOWAqua opcode
INSUFFICIENT_SCOPEMCP · scope check
KYA_LEVEL_TOO_LOWauth server

A contract revert outside this list is CONTRACT_REVERTED. The MCP server adds its own codes:

CODEMEANING
INSUFFICIENT_SCOPEThe token lacks the tool's scope or role (reason: scope | role)
NOT_PARTYThe caller is not the seller, buyer or worker this call is about
BAD_INPUTMalformed id, address, amount or URL (field)
INVOICE_MISMATCHThe invoice document's printed terms differ from the submitted ones
NOT_FOUNDUnknown pending id, receivable or strategy
NOT_DEPLOYEDaddresses.json lacks a contract the call needs
IDEMPOTENCY_KEY_REUSEDSame idempotency key, different arguments
CREDIT_DECLINEDThe deterministic credit decision is not approved (reasons)
NO_ELIGIBLE_LIQUIDITYNo lender strategy can fund the receivable (skipped)
SPEND_WALLET_NOT_REGISTEREDreserve_spend wallet is not the worker's registered 2-of-2 with the co-signer
MERCHANT_URL_NOT_ALLOWEDpay_x402 URL origin is not configured for the reservation's merchant
COSIGNER_REFUSEDThe policy co-signer refused the x402 payment (reason)
PAYMENT_FAILEDThe merchant answered without a settlement
PAYMENT_IN_FLIGHTA payment for this reservation is in flight or was co-signed without a seen settlement
RESERVATION_PAIDrelease_spend on a reservation pay_x402 settled: commit it instead
RESERVATION_NOT_EXPIREDrelease_spend before the reservation's expiry
ALREADY_REPAIDrepay_receivable on a receivable that is already Repaid
KEY_NOT_HELDThe server would need an agent key it does not hold (demo flags off)
CONTRACT_REVERTEDA contract reverted with a custom error outside the shared list (error, args)
CHAIN_ERRORAn RPC failure or an undecodable revert
INTERNALAnything else

Configuration

NetworkHedera testnet · EVM chain ID 296
JSON-RPC relayhttps://testnet.hashio.io/api
Mirror nodehttps://testnet.mirrornode.hedera.com/api/v1
USDC (testnet)0.0.429274 · 0x0000000000000000000000000000000000068cda · 6 dp
WHBAR0xb1F616b8134F602c3Bb465fB5b5e6565cCAd37Ed · 8 dp
System contractsHTS 0x167 · HAS 0x16a · HSS 0x16b
x402 facilitatorsapi.testnet.blocky402.com · x402.org/facilitator · testnet.facilitator.launa.dev
Explorerhttps://hashscan.io/testnet
MCP endpointhttp://localhost:4030/mcp · POST · stateless Streamable HTTP
Read APIhttp://localhost:4030 · GET · no auth
Authorization serverhttp://localhost:4020
HCS audit topic0.0.11338927
Receivable NFT0.0.11338934

MCP server environment

VARIABLEDEFAULTUSE
MCP_PORT4030Listen port
HOST127.0.0.1Interface the MCP and authorization servers bind to
MCP_RESOURCE_URLhttp://localhost:4030/mcpToken audience and MCP path
AUTH_ISSUERhttp://localhost:4020Authorization server; metadata fetched at boot, issuer must match
COORDINATOR_KEY, COSIGNER_KEYrequiredCoordinator writes; x402 co-signature
KYA_ISSUER_KEY—register_agent
HCS_AUDIT_TOPIC_ID, RECEIVABLE_NFT_TOKEN_IDdeployments/testnet/hedera.jsonAudit topic and receivable NFT collection
DATA_DIRapps/mcp-server/dataevents.jsonl, idempotency.json, pending.json, invoices/
CORS_ORIGINShttp://localhost:3000Browser origins allowed on the read API (add the admin console's origin)
ANTHROPIC_API_KEY—explain_decision via claude-haiku-5-5
HFS_ENABLEDfalseAlso 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_MODELhttp://localhost:11434, qwen2.5:7bOllama OpenAI-compatible endpoint
AGENT_KEYS_IN_PROCESSfalseDemo: the server signs as seller, buyer and workers (true), or only the listed roles (seller,worker); other roles get calldata
LENDER_KEYS_IN_PROCESSfalseDemo: the server signs as lenders
AQUA_FROM_BLOCKswap router creation blockFirst 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↑