Autonomous DeFi Yield Agent on Casper Network
Casper Agentic AI Buildathon 2026 · Build Direction #1: Autonomous Yield-Routing Agent via MCP

Autonomous cyber dashboard — live AI decisions, portfolio trajectory, RWA oracle, on-chain proof

My Vaults — protocol AUM across every enrolled vault, per-wallet assets (liquid vs staked CSPR), agent gas/runway, and full staking & swap history
| Live Dashboard | https://casper.soenic.com |
| Backend API | https://agentcasper.soenic.com |
| Demo Video | https://youtu.be/4XiVtV4MWno |
| Smart Contract | https://testnet.cspr.live (hash-486a161b...) |
| X / Twitter | https://x.com/kata_enda |
| Telegram | https://t.me/soesoe14 |
| Discord | mas_end_47419 |
| GitHub | https://github.com/kataenda |
AGENT-CASPER is a fully autonomous DeFi yield optimization agent running on the Casper Network. On each polling cycle — a configurable interval (60s in the demo video for visible live activity, 300s in production to cut LLM cost on 24/7 operation) — the agent:
- Fetches real-world asset prices (PAXG/gold, UST10Y/T-bonds, WTI/oil)
- Fetches yield rates from Casper validators via CSPR.cloud
- Lets Claude AI autonomously query on-chain + RWA data via MCP tools and decide
- Autonomously executes on-chain rebalancing transactions when needed — and the RWA-driven allocation isn't cosmetic: it sets the staking target and swap direction (gold ↑ → de-risk + stake more; rates ↓ → risk-on)
- Delegates each vault's idle CSPR to a validator it selects itself (lowest-fee, active) for real native yield — per vault, sized to that vault's own balance, keeping a liquidity buffer (proven on-chain:
21354398…) - Posts verified RWA prices on-chain (auditable oracle trail), and both pays for and sells premium data via x402 micropayments — a service provider on Casper mainnet, not just a consumer
- Executes real, non-custodial DeFi swaps on Casper mainnet via the CSPR.trade MCP, and the swap now mirrors the AI's decision: de-risking stakes CSPR → sCSPR, risk-on unwinds sCSPR → CSPR, sized by how far the allocation drifts — the agent fetches live quotes, builds the transaction, signs it with its own key, and broadcasts it (verified live:
f28a4051…)
The system transforms a passive smart contract vault into a self-driving portfolio manager, uniting the three pillars of the Casper Innovation Track — Agentic AI · DeFi · RWA — and closes the loop with agent-to-agent commerce: an independent buyer agent (its own ed25519 identity) pays Agent Casper over x402 and settles on-chain — a real CEP-18 transfer_with_authorization between two distinct agents (eb0e914c…, Casper testnet) — putting the machine economy to work, not just describing it.
What's live vs. roadmap (honest scope). The Testnet YieldVault custodies real depositor CSPR on-chain — a payable
deposit()lands CSPR in the contract purse (verified86fd83a6…, 700 CSPR) — records AI-driven allocation changes and verified RWA prices on-chain, and routes that deposited CSPR into real yield. Native staking is now proven on-chain: the agent autonomously delegates the vault's CSPR to a Casper validator it picks itself (lowest-fee, active) viastake/unstake(Odraenv().delegate), keeping a liquidity buffer so ordinary withdrawals stay instant — three confirmed delegations of 500 CSPR (21354398…,5cd6bf7b…,aab61086…), ~2,200 CSPR delegated across the serviced vaults. Staking is agent-decided, per vault (each vault delegates its own balance — a 200 CSPR vault can't clear Casper's 500 minimum, a 2,000 CSPR vault delegates far more);STAKING_ENABLEDis an emergency kill-switch, not a feature toggle. The agent also executes allocation decisions as real, directional mainnet swaps (de-risk vs risk-on, sized by drift), signed with its own key. Still roadmap: routing capital into LP / multi-asset positions and tokenized-RWA custody (the vault is CSPR-native today).
Built using the Casper AI Toolkit — MCP Servers (Casper MCP + CSPR.trade MCP), CSPR.cloud, Odra Framework, x402, casper-js-sdk v5
Agent Casper is an autonomous vault manager that keeps CSPR yield optimal 24/7 with no human in the loop — and its agent logic is token-agnostic, ready to manage RWA-token yield as the Casper ecosystem matures.
Most people who want yield on CSPR lose part of it to the same things: they rebalance too late, get eaten by fees + slippage, and can't watch protocols around the clock. Agent Casper fixes that — acting as an autonomous fund manager that monitors conditions, computes whether a rebalance is worth it (gain above gas + slippage), and executes on its own. Today the focus is pure DeFi: optimizing CSPR yield via native staking. But because the agent's decision/rebalance logic is token-agnostic, the same agent can manage yield from RWA tokens (e.g. Parking Blox) the moment real-world assets flow onto Casper — one agent, two worlds: DeFi now, RWA next.
Honest scope: the vault today is CSPR-native (payable CSPR deposits). "Token-agnostic" describes the agent logic and architecture, not a shipped RWA-token deposit path — we sell a credible trajectory, not a fictional feature.
Who it's for. Picture a long-term CSPR holder who has no time to be a trader. They want their capital working — finding the best yield, moving on opportunity, avoiding wasted fees — without staring at a dashboard every hour. Agent Casper becomes their personal manager: autonomous, transparent, and covering its own operating costs from fees. The same principle later extends to RWA-token owners who want their assets productive without managing them by hand.
The problem. On-chain yield allocation is still manual and macro-blind. Treasuries and LPs rebalance by hand, ignore real-world signals (rates, gold, oil) that move risk appetite, and can't react to 24/7 markets while they sleep. There is no round-the-clock, explainable, on-chain agent that ties real-world data to on-chain action.
The solution. Agent Casper is an autonomous, RWA-aware allocation agent that runs continuously, reasons over live macro + validator data with Claude, records every decision on-chain for audit, and executes those decisions with real capital.
Who benefits — concrete users:
| User | Value delivered |
|---|---|
| DAO / protocol treasuries | Hands-off, policy-driven rebalancing with an on-chain audit trail of why each move was made |
| Retail LPs & stakers | A 24/7 agent that de-risks on flight-to-safety signals (gold ↑, Treasury ↑) they'd otherwise miss |
| Other AI agents | Buy Agent Casper's RWA-aware decisions & verified feeds over x402 — a paid, machine-to-machine data service |
| Casper validators | Autonomous, RWA-driven flows into liquid staking (sCSPR) add real, recurring on-chain volume |
What is genuinely real today (not simulated):
| Capability | Status | Proof |
|---|---|---|
| RWA market data (gold, UST10Y, WTI) | ✅ Real | CoinGecko + Yahoo Finance live APIs |
| On-chain RWA oracle trail | ✅ Real | update_rwa_price deploys on Testnet |
| AI-driven allocation decisions | ✅ Real | Claude via MCP tools, stored on-chain |
| Directional mainnet execution | ✅ Real | CSPR ⟷ sCSPR swaps on CSPR.trade (f28a4051…) |
| Agent-to-agent x402 settlement | ✅ Real | CEP-18 transfer_with_authorization (eb0e914c…) |
| Custody of depositor CSPR (contract purse) | ✅ Real | Payable deposit() lands CSPR in the contract purse — verified 86fd83a6… (700 CSPR, attached_value, no revert) |
| Multi-tenant vault servicing | ✅ Real | Any wallet deploys/owns its own vault, registers the agent on it (1dc138a9…), deposits real CSPR into it — and the agent autonomously rebalances the tenant vault each cycle (d7551fcb…, drift-gated). Live AUM: ~2,400 CSPR across 3 independently-owned vaults |
| Routing custodied capital into real yield | ✅ Real | Native staking — the agent autonomously delegates each vault's CSPR to a validator it picks itself. 3 confirmed delegations of 500 CSPR (21354398…, 5cd6bf7b…, aab61086…); ~2,200 CSPR delegated. Per vault, sized to each vault's own balance, liquidity buffer kept |
| RWA signals drive execution | ✅ Real | Verified gold/treasury/oil prices change the agent's allocation → which sets the staking target and swap direction (gold ↑ → de-risk + stake more; rates ↓ → risk-on). Deterministic in code, not just displayed |
| Verifiable AI decisions | ✅ Real | Each rebalance commits a sha256 of (inputs + decision) on-chain in its reasoning arg; the pre-image is served from /agent/decision-proof so anyone can recompute and check it |
| Tokenized-RWA custody (vault holds RWA tokens) | 🟡 Roadmap | The vault is CSPR-native today; the agent's logic is token-agnostic, ready to manage RWA-token yield as those assets arrive on Casper |
| Agent self-funding from revenue | 🟡 Implemented | Management fee accrues to a reserve the agent sweeps to its own gas account (collect_fees); vault fee = CSPR (primary gas), x402 sales = stablecoin (secondary, needs swap) |
Vision: the default autonomous, RWA-aware treasury layer for Casper — where any DAO, protocol, or agent can delegate 24/7 yield decisions to a transparent, on-chain AI whose every move is auditable and whose data is itself a sellable x402 service.
| Phase | Timeline | Milestones |
|---|---|---|
| 1 — Autonomous agent + real custody + multi-tenant + real yield (now) | ✅ Shipped | AI decision + on-chain proof layer, real native staking of vault CSPR (agent-decided, per vault — 21354398… + 2 more, ~2,200 CSPR delegated), real mainnet swap execution, x402 provider economy, upgradable payable vault that custodies real depositor CSPR (86fd83a6…), multi-wallet vaults serviced autonomously (tenant rebalance d7551fcb…), verifiable on-chain decision commitments, landing page + live dashboard (deposit/withdraw, owner emergency-pause) |
| 2 — Multi-asset yield + withdrawal accounting | Q3 2026 | Beyond native staking: route capital into LP pools / stables, per-position accounting, auto-compounding, performance fee on generated yield |
| 3 — Tokenized RWA + mainnet launch | Q4 2026 | Manage RWA-token yield (the agent logic is already token-agnostic), mainnet contract deploy, third-party security audit, risk caps & circuit breakers |
| 4 — Ecosystem & governance | 2027 | DAO governance over agent policy, an x402 agent marketplace (agents buy/sell each other's signals), SDK for others to deploy their own Casper agents |
Deployment plan. Frontend + backend already run 24/7 on a VPS (casper.soenic.com · agentcasper.soenic.com); Testnet contract is live. Phase 2 adds a mainnet contract behind the same operational stack, containerized (Coolify/Docker) with a backup CSPR.cloud key for quota resilience.
Adoption & growth strategy.
- Wedge: onboard 1–2 Casper-native DAOs/protocols as pilot treasuries for policy-driven rebalancing.
- Network effect: each agent that sells signals over x402 makes the marketplace more valuable — data compounds.
- Developer pull: open-source the agent framework so teams fork it for their own strategies (grows Casper on-chain activity).
- Sustainability: the vault's on-chain fee (
fee_bps) + x402 provider revenue fund continuous operation — the agent is designed to pay for its own gas.
Community & socials. X / Twitter · Telegram · Discord mas_end_47419 · GitHub · Demo video
┌─────────────────────────────────────────────────────────────────┐
│ AGENT-CASPER │
│ │
│ ┌──────────┐ ┌──────────────┐ ┌──────────────────────┐ │
│ │ RWA │ │ Claude AI │ │ YieldVault │ │
│ │ Oracle ├───▶│ Decision ├───▶│ Smart Contract │ │
│ │ PAXG/ │ │ Engine │ │ (Odra 2.x / Casper │ │
│ │ UST10Y/ │ │ (MCP Tools) │ │ Testnet) │ │
│ │ WTI Oil │ └──────────────┘ └──────────────────────┘ │
│ └──────────┘ │
│ │ ▲ │ │
│ ┌────▼──────────────┴────────────────────────▼──────────────┐ │
│ │ FastAPI Backend (Python) │ │
│ │ • Yield Agent loop (60s/300s) │ │
│ │ • CSPR.cloud middleware │ │
│ │ • x402 micropayment handler │ │
│ │ • WebSocket broadcast │ │
│ └────────────────────────────────────────────────────────────┘ │
│ │ │
│ ┌─────────────────────────▼──────────────────────────────────┐ │
│ │ Next.js Dashboard (React + TypeScript) │ │
│ │ • Real-time cyber dashboard │ │
│ │ • Casper Wallet integration │ │
│ │ • Deploy / Register Agent / Deposit buttons │ │
│ │ • AI chat interface │ │
│ └────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────┘
Buildathon requirement — every required AI Toolkit component is used:
| Required component | ✓ | Where in this project |
|---|---|---|
| x402 Micropayments | ✅ | x402.py — consumer and provider; on-chain CEP-18 transfer_with_authorization settlement (eb0e914c…) |
| MCP Servers (Casper MCP + CSPR.trade MCP) | ✅ | mcp_server.py (5 tools, driven by Claude) + cspr_trade.py (live mainnet swaps) |
| CSPR.click AI Agent Skill | ✅ | Official skill installed at .claude/skills/csprclick-skill/ — the exact SKILL.md from make-software/csprclick-examples (claude skill install cspr-click / npx skills add). Its SDK-integration guidance is applied: @make-software/csprclick-ui wired via CSPRClickProvider (mounts app-wide once a registered NEXT_PUBLIC_CSPRCLICK_APP_ID is set). The agent also creates & signs its own txs non-custodially (deployer.py, cspr_trade.py), keys stay local |
| CSPR.cloud APIs | ✅ | client.py — REST + Node RPC (balances, deploys, tx verification) |
| Odra Framework | ✅ | yield_vault.rs — upgradable, payable real-custody vault |
Detailed breakdown:
| Tool | Usage |
|---|---|
| CSPR.cloud | Block data, deploy status, account balances |
| Odra Framework 2.7.2 | YieldVault smart contract (Rust → WASM) |
| casper-js-sdk v5 | Frontend deploy signing, wallet integration |
| CSPR.click | @make-software/csprclick-ui wired via CSPRClickProvider (mounts when NEXT_PUBLIC_CSPRCLICK_APP_ID is set) — Casper Wallet / Ledger / Torus connect, account session + signing |
| x402 Protocol | HTTP-native pay-per-request, official CSPR.cloud exact scheme — EIP-712 (casper-eip-712) typed-data signed with the agent's ed25519 key, CEP-18 transfer_with_authorization settlement, verified against the live facilitator /verify (isValid: true). Enable via X402_ENABLED=true |
| MCP Server | Custom Casper MCP server exposes 5 blockchain tools to Claude (block height, yield rates, vault portfolio, RWA prices, account balance) |
| CSPR.trade MCP | Real non-custodial DeFi on Casper mainnet (https://mcp.cspr.trade/mcp, 24 tools). The agent uses it for live swap quotes and execution — build_swap → sign with the agent's own ed25519 key → broadcast via account_put_transaction. Funds never leave the agent's account. Exposed via /defi/quote, /defi/markets, /defi/swap |
| Casper Wallet | User authentication and transaction signing |
| Claude AI | Autonomous rebalancing decisions with RWA context (claude-haiku-4-5) |
Deployed on Casper Testnet:
Contract Hash: hash-486a161bf2d5d2b36b2cfda25557adf3c7b70ec1cda7cfb01dec0ba1545ac5ea
Network: casper-test
Framework: Odra 2.7.2 (Rust → WASM), upgradable + payable (real CSPR custody)
Upgradable in place — proven live. The package has already been upgraded on-chain (v1
983c9198…→ v204a04d88…) with the same package hash, depositor balances (1,000 CSPR TVL) and agent registration preserved —init()is idempotent, so an upgrade can never wipe state. The backend resolves the latest contract version from the package at runtime, so upgrades require no env/config changes. Deploys are wallet-scoped like any multi-wallet dApp: the/deploypage reads the connected wallet's own vault (itsyield_vault_prodnamed key) — fresh install if it has none, in-place upgrade if it does.
| Function | Description |
|---|---|
deposit() |
Payable — users deposit CSPR; a fee_bps management fee accrues to the fee reserve |
withdraw(amount) |
Users withdraw their CSPR balance (paid from the liquid buffer) |
register_agent(agent) |
Owner registers the AI agent address |
rebalance(strategy, pcts, reason) |
Agent executes a portfolio rebalance |
update_rwa_price(asset, price, yield) |
Agent posts verified RWA data on-chain |
set_validator(validator) |
Owner-only — authorises the validator the agent selects (lowest-fee, active). One-time grant, like register_agent; the agent then stakes to it autonomously |
stake(amount) / unstake(amount) |
Real yield — agent delegates/undelegates vault CSPR to the validator (env().delegate), keeping a liquidity buffer |
collect_fees() |
Agent self-funding — agent-only; sweeps the accrued fee reserve to the agent's own gas account |
set_fee_bps(bps) |
Owner sets the management fee (basis points, capped at 10%) |
get_portfolio() / get_tvl() / get_fee_bps() |
Read allocation, real TVL (liquid + staked), and the active fee |
get_liquid() / get_staked() / get_fee_reserve() |
Read the liquid buffer, delegated amount, and pending fee reserve |
emergency_pause() |
Owner safety control |
Deposited, Withdrawn, Rebalanced, AgentRegistered, RwaPriceUpdated, EmergencyPaused, FeeCollected, FeesSwept, Staked, Unstaked
This is agent-to-agent commerce — the machine economy, working today. Agent Casper doesn't just consume x402; it earns over x402. An independent buyer agent (its own ed25519 identity) discovers Agent Casper's services, pays for them, and settles on-chain — a real CEP-18
transfer_with_authorizationbetween two distinct agents, autonomous machine-to-machine payment with no human in the loop (eb0e914c…, Casper testnet). The closed, two-sided loop (the agent both pays for its RWA risk feed and gets paid for its AI decisions) is exactly the agent economy the Casper Manifest describes.
Agent Casper implements the x402 v2 HTTP-native pay-per-request protocol on both sides of the loop:
- Consumer — the agent pays per API call for its premium "RWA risk feed" each cycle.
- Provider — the agent sells its own services: other agents pay it for an on-demand
Claude AI recommendation (
/x402/decision) or an on-chain-verified RWA price feed (/x402/rwa-feed). Payment lands in the agent's own account, with real CEP-18transfer_with_authorizationsettlement demonstrated on-chain (Casper testnet, where the X402 token lives).
This is the official CSPR.cloud exact scheme — conformant with
@make-software/casper-x402 and
verified end-to-end against the live facilitator (/verify returns
isValid: true — reproduce with scripts/x402_verify_proof.py).
Flow (backend/casper/x402.py + backend/casper/eip712.py):
- Client requests a protected resource (
GET /premium/yield-forecast). - Server replies HTTP 402 Payment Required +
{resource, accepts:[PaymentRequirements]}(schemeexact, networkcasper:casper-test,asset= CEP-18 token package hash,extra= token name/version). - Client builds a
TransferWithAuthorizationand signs the EIP-712 typed-data digest (casper-eip-712domain:name, version, chain_name, contract_package_hash) with its ed25519 key —keccak256(0x1901 ‖ domainSeparator ‖ structHash). - Client retries with the base64
X-PAYMENTheader ({x402Version, resource, accepted, payload:{signature, publicKey, authorization}}). - Server recomputes the same digest, verifies the signature, binds it to the payer (
publicKey→ account hash →authorization.from), checks expiry + nonce, then settles via the facilitator as a CEP-18transfer_with_authorization.
Because settlement is a CEP-18 token transfer (not a native transfer), amounts are
true sub-CSPR micropayments — no 2.5 CSPR native-transfer floor. The facilitator pays
the deploy gas via its published feePayer; the agent only needs to hold the token.
x402 is real end-to-end — including genuine agent-to-agent settlement. Fully conformant with the official
exactscheme and settled on-chain by the live CSPR.cloud facilitator (Casper testnet, where the CEP-18 X402 token lives) — real 402 handshake, EIP-712 ed25519 proof accepted by the facilitator/verify(isValid: true), and a realtransfer_with_authorizationsubmitted by the facilitator/settle. Two on-chain proofs:
- Agent-to-agent (independent buyer → provider): a separate buyer agent with its own ed25519 identity (
00e2d5cd…) pays the Agent Casper provider (0088cb6d…) 1 X402 —eb0e914c…(funding transfer agent → buyer:7cc8be65…). This is the machine economy literally on-chain: two distinct agents, real token moving between them.- Settlement rail: the agent's own
transfer_with_authorizationof the deployed token —e297580f…(tokenc61db3d7…).Reproduce: deploy the token (
scripts/deploy_x402_token.py), fund the buyer (scripts/fund_buyer.py), then settle buyer → provider (scripts/buyer_pays_agent.py); self-settle:scripts/x402_settle_real.py; verify-only proof:scripts/x402_verify_proof.py.
Endpoints:
| Endpoint | Role | Description |
|---|---|---|
GET /premium/yield-forecast |
provider (testnet) | x402-protected resource — 402 without payment, premium data with valid X-PAYMENT |
GET|POST /x402/decision |
provider (mainnet) | Pay (CEP-18 token) → fresh Claude AI rebalance recommendation (RWA-aware) |
GET|POST /x402/rwa-feed |
provider (mainnet) | Pay (CEP-18 token) → aggregated RWA prices (PAXG, UST10Y, WTI) + on-chain proof deploy hashes |
GET /x402/info |
— | x402 config, payer address + token, facilitator support, provider service catalog |
GET /x402/supported |
— | Proxies the facilitator's supported schemes/networks |
The mainnet provider endpoints set payTo to the agent's own public key, so a paying
agent's CSPR is settled to Agent Casper. The ed25519 proof is verified on every request,
and there are two ways the payment settles on-chain:
- Facilitator pull — the official CSPR.cloud facilitator moves CSPR from a payer
that holds a registered x402 allowance (
settlement: facilitator). - Payer push (self-contained) — the payer submits a real native transfer to
payToand passes its deploy hash asauthorization.settlement_tx. The provider then verifies that transfer on-chain (payer → payTo, ≥ amount, executed Success) and reportssettlement: onchain_transfer_by_payerwith a realcspr.livetx.
Either way the proof is bound to the on-chain payment (the transfer's sender must equal
the proof's signer). If neither settles (e.g. an unfunded demo key), the proof is still
verified and the request honoured with settlement: proof_verified (pending).
Try it (against the live production backend):
# 1. Request without payment → HTTP 402 + PaymentRequirements
# (open this URL in a browser too — it shows the raw 402 challenge)
curl -i https://agentcasper.soenic.com/premium/yield-forecast
# 2. Inspect config, payer public key, and the live facilitator schemes
curl https://agentcasper.soenic.com/x402/info
# 3. Full end-to-end paid flow: 402 → ed25519-signed proof → HTTP 200 + premium data
# (run from the repo root; reads the agent key from backend/agent_secret_key.pem)
python demo_x402.py # proof only — no CSPR spent
python demo_x402.py --settle # also settles a real on-chain CSPR transfer
# 4. BUYER AGENT — an independent agent (its own fresh ed25519 identity each run)
# pays Agent Casper over mainnet x402 for BOTH provider services.
python demo_buyer_agent.py # proof only — settlement pending
# 5. REAL on-chain settlement: a funded mainnet buyer actually transfers CSPR to
# Agent Casper, proving the provider economy settles on-chain (agent earns).
python demo_buyer_agent.py --settle --key buyer_key.pem --cloud-key <CSPR_CLOUD_KEY>Replace the URL with
http://localhost:8000to try it against a local backend.demo_x402.pyruns the exactX402Handlerflow the agent uses (consumer side);demo_buyer_agent.pyplays an external buyer that pays for/x402/decisionand/x402/rwa-feed— proving the agent is a real x402 service provider, not just a consumer.
When X402_ENABLED=true, the agent also performs an x402 micropayment each cycle for
its "RWA risk feed"; the payment record (proof + settlement deploy hash) is included in
every cycle result broadcast over the WebSocket.
Beyond the testnet vault, Agent Casper performs real, non-custodial DeFi on Casper mainnet through the official CSPR.trade MCP (Uniswap-V2 DEX, 24 public MCP tools). This is genuine on-chain trading — verified live:
Flow (backend/casper/cspr_trade.py):
get_quote/estimate_slippage— live mainnet pricing, route, and price impact.build_swap— CSPR.trade returns an unsigned Casper 2.x TransactionV1.- The agent signs it locally with its own ed25519 key (the same key it uses for x402 proofs and rebalances) — the MCP never holds funds (non-custodial).
- The signed transaction is broadcast via
account_put_transactionto a Casper mainnet node, returning a real transaction hash.
Guardrails: input-amount cap, price-impact cap, and an explicit execute flag
(false = quote + build + sign only, no broadcast).
Autonomous decision → execution (closing the loop). When the AI decides to
REBALANCE, the agent can also fire a small real mainnet swap via CSPR.trade in
the same cycle — turning the on-chain allocation record into actual on-chain DeFi
execution (shown in the dashboard's decision log as a DeFi⚡MAINNET tx badge). This
is off by default (DEFI_EXECUTE_ON_REBALANCE=false) and spends the agent's own
mainnet CSPR, bounded by a base amount scaled by allocation drift (DEFI_SWAP_AMOUNT_CSPR
base, hard-capped by CSPR_TRADE_MAX_AMOUNT_CSPR), a per-day cap
(DEFI_MAX_SWAPS_PER_DAY), plus the amount + price-impact caps above. (The vault's
deposited capital already earns real yield via native staking — see below;
routing it into mainnet swaps / LP specifically is Phase 2.)
When does the agent actually swap? (economic discipline). A REBALANCE decision is
necessary but not sufficient — a swap costs gas + price impact, so the agent only fires
one when the move is materially worth the cost. Before executing, _swap_worth_it()
(backend/agent/yield_agent.py) applies two gates:
- Drift gate — the current allocation must be off the AI's target by at least
DEFI_MIN_DRIFT_PCTpercentage points (default10). This prevents churn: tiny, noise-level deviations are held, not traded. - Net-gain gate — the estimated annualized portfolio APY uplift from the
reallocation (weighted across the live per-strategy yield rates) must clear
DEFI_MIN_NET_GAIN_BPS(default50bps). A marginal improvement that wouldn't repay the swap cost is skipped. - De-risk bypass — if the AI flags
risk_level = HIGH(depeg, TVL drain, macro risk), the net-gain gate is bypassed so the agent can move to safety even at lower yield — capital preservation outweighs yield in a risk event.
Skipped swaps are reported in the cycle result as settlement: "below_threshold" with the
reason, so the dashboard still shows why the agent chose to hold. In short: swaps are
event-driven (an economic threshold is crossed), not schedule-driven — the poll
interval only sets how often the agent looks, never how often it trades.
Tuning DEFI_MIN_NET_GAIN_BPS — the minimum annualized APY uplift (bps) required to
justify a swap's cost:
| Value | Behaviour | When to use |
|---|---|---|
50 (0.5%) |
Healthy default — swap only when clearly profitable | ✅ Production (use this) |
100 (1%) |
More frugal — swaps very selectively | Minimise transactions |
25 (0.25%) |
More aggressive — swaps more often | When you trust swap costs are low |
0 |
Swap on any rebalance that doesn't lower APY | Semi-demo |
-1000 |
Always swap, including de-risk moves (APY drops) | Demo only |
A de-risk / flight-to-safety rebalance lowers APY, so with any positive threshold it won't swap (by design — you don't trade into a lower-yield allocation for yield reasons). Genuine high-risk moves still execute via the De-risk bypass above. For a live demo, set
-1000to force the swap, then restore50for honest, cost-aware behaviour.
Operator-tunable (no code change). The thresholds are plain environment variables, so the agent's posture is switched live — the production / real default is the strict "discipline" profile:
| Profile | DEFI_EXECUTE_ON_REBALANCE |
DEFI_MIN_DRIFT_PCT |
DEFI_MIN_NET_GAIN_BPS |
Behaviour |
|---|---|---|---|---|
| Real / discipline (default) | true |
10 |
50 |
Swaps only on a large, genuinely profitable reallocation |
| Demo (show execution live) | true |
5 |
20 |
Looser gates so a real swap fires during a short demo |
| Off | false |
— | — | No autonomous swaps at all |
For judging, the deployed agent runs the Real / discipline profile (
10/50) so every autonomous mainnet swap reflects a deliberate, cost-justified decision — not churn.
Endpoints:
| Endpoint | Description |
|---|---|
GET /defi/quote |
Live CSPR.trade mainnet swap quote (read-only, no wallet) |
GET /defi/markets |
Live CSPR.trade trading pairs |
GET|POST /defi/swap |
Build + sign + (with execute=true) broadcast a real swap; returns the tx hash |
GET /defi/history |
Persistent history of executed mainnet swaps (survives restarts) |
# Live mainnet quote (free, read-only)
curl "https://agentcasper.soenic.com/defi/quote?token_in=CSPR&token_out=sCSPR&amount=10"
# Execute a real non-custodial swap on mainnet (spends the agent's own CSPR)
curl -X POST https://agentcasper.soenic.com/defi/swap \
-H "Content-Type: application/json" \
-d '{"token_in":"CSPR","token_out":"sCSPR","amount":"10","execute":true}'The dashboard also exposes a Swap panel (header button) for the same flow with a real-mainnet confirmation step.
All activity is verifiable on the Casper Testnet explorer. Example transactions produced autonomously by the agent:
| Action | Entry point | Example deploy hash |
|---|---|---|
| Smart contract (package) | — | 486a161b… |
| Autonomous rebalance | rebalance |
f0352e2b… |
| RWA price on-chain (gold) | update_rwa_price |
b9f33ec3… |
| RWA price on-chain (treasury) | update_rwa_price |
0700586b… |
| x402 micropayment settlement | native transfer | ba8fb27e… |
x402 exact settle (facilitator transfer_with_authorization) |
CEP-18 X402 | e297580f… |
| Agent-to-agent x402 settle (independent buyer → provider) | CEP-18 X402 | eb0e914c… |
| Tenant vault register (2nd wallet registers the agent on ITS own vault) | register_agent |
1dc138a9… |
| Autonomous TENANT rebalance (multi-tenant servicing, drift-gated) | rebalance |
d7551fcb… |
| Validator authorised (owner grants the agent's own pick — 0% fee, active) | set_validator |
03b3b07f… |
| Native staking — real yield (agent delegates vault CSPR autonomously) | stake |
21354398… · 5cd6bf7b… · aab61086… |
Plus real DeFi on Casper mainnet via CSPR.trade MCP (verifiable on cspr.live):
| Action | Network | Transaction |
|---|---|---|
| Non-custodial swap (CSPR → sCSPR) | mainnet | f28a4051… |
| AI-decided autonomous swap (REBALANCE → CSPR → sCSPR, no human) | mainnet | 2bafdb43… |
The
2bafdb43…swap was triggered autonomously by the agent's own REBALANCE decision in a live cycle (not a manual call) — Claude decided, the agent signed and broadcast a real mainnet swap with its own key. The agent account has also produced 130+ processed transactions on Testnet to date.
| Layer | Technology |
|---|---|
| Smart Contract | Rust + Odra 2.7.2 → WASM (Casper 2.x) |
| Backend | Python 3.11 + FastAPI + httpx |
| AI | Anthropic Claude (claude-haiku-4-5) |
| Frontend | Next.js 14 + React 18 + TypeScript |
| UI | Tailwind CSS + Recharts + Lucide |
| Wallet | Casper Wallet Extension + casper-js-sdk v5 |
| CI/CD | GitHub Actions (auto-build WASM on push) |
Copy backend/.env.example to backend/.env and fill in all values:
# ── AI ──────────────────────────────────────────────────────────────────────
# Get your key at https://console.anthropic.com → API Keys
ANTHROPIC_API_KEY=sk-ant-api03-...
# ── Casper Network ────────────────────────────────────────────────────────
# Official CSPR.cloud endpoints (https://www.casper.network/ai)
CASPER_NODE_URL=https://node.testnet.cspr.cloud/rpc
CSPR_CLOUD_API_KEY=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx # Register at cspr.cloud
CSPR_CLOUD_BASE_URL=https://api.testnet.cspr.cloud
# ── Vault & Agent ─────────────────────────────────────────────────────────
# Filled in after deploying the contract via the dashboard
VAULT_CONTRACT_HASH=hash-xxxx...
# OPTIONAL network-failure fallback only — the backend resolves the LATEST
# contract version from the package on-chain at runtime (survives upgrades).
# Leave EMPTY in normal operation; a stale value here can never misroute calls.
VAULT_CONTRACT_VERSION_HASH=
AGENT_ACCOUNT_HASH=account-hash-xxxx...
AGENT_SECRET_KEY_PATH=./agent_secret_key.pem
# For Railway / cloud deployments: paste the PEM content directly here
# (replace newlines with \n)
# AGENT_SECRET_KEY_CONTENT=-----BEGIN PRIVATE KEY-----\nxxxx\n-----END PRIVATE KEY-----
# ── Admin auth (optional, recommended for public deployments) ──────────────
# Shared secret gating state-mutating endpoints (/agent/pause, /agent/resume,
# /rebalance/manual, /admin/setup, /defi/swap, /deploy). Leave EMPTY to keep them
# open; set a long random value to require the X-Admin-Token header on every
# privileged call. Paste the same value into the dashboard's /api "Admin token"
# field to operate those actions. Read-only endpoints are never gated.
ADMIN_TOKEN=
# ── Agent Configuration ───────────────────────────────────────────────────
AGENT_POLL_INTERVAL_SECONDS=300 # how often the agent looks (60 in demo, 300 in prod)
MAX_REBALANCES_PER_DAY=5 # Maximum rebalances allowed per day
# Post verified RWA prices (PAXG, UST10Y) on-chain via update_rwa_price().
RWA_ONCHAIN_ENABLED=true # Set false to disable on-chain RWA posting
RWA_POST_INTERVAL_SECONDS=3600 # Rate-limit: post at most once per interval
# ── x402 Micropayment (optional) ──────────────────────────────────────────
# Official CSPR.cloud `exact` scheme — the facilitator settles a CEP-18
# transfer_with_authorization. Amounts are in TOKEN BASE UNITS (see decimals),
# NOT native CSPR — there is no 2.5 CSPR native-transfer floor here.
X402_ENABLED=false
X402_FACILITATOR_URL=https://x402-facilitator.cspr.cloud
# x402 payTo — a Casper account-hash address ('00' + account hash), NOT a public
# key. A '01'+pubkey value makes the CEP-18 transfer_with_authorization revert
# on-chain. Leave unset to default to the agent's own address.
# X402_PAY_TO=00<recipient-account-hash>
X402_SETTLE_INTERVAL_SECONDS=3600 # rate-limit on-chain settlement
X402_SETTLE_ONCHAIN=true # per-cycle facilitator settle; false = proof-only
# CEP-18 settlement token: ASSET = 64-hex contract package hash exposing
# transfer_with_authorization; NAME/VERSION form the EIP-712 domain.
X402_ASSET=
X402_TOKEN_NAME=
X402_TOKEN_VERSION=1
X402_TOKEN_DECIMALS=6
X402_TOKEN_SYMBOL=
X402_PAYMENT_AMOUNT=1000000 # consumer per-request amount (token base units)
# Mainnet PROVIDER pricing — other agents pay THIS agent for premium data.
X402_DECISION_PRICE=5000000 # /x402/decision — token base units
X402_RWA_FEED_PRICE=2500000 # /x402/rwa-feed — token base units
# ── Real DeFi — autonomous swap on rebalance (CSPR.trade, mainnet) ─────────
# When the AI decides REBALANCE, optionally route a small, capped, non-custodial
# swap on Casper mainnet. OFF by default (spends the agent's own mainnet CSPR).
DEFI_EXECUTE_ON_REBALANCE=false # true = agent swaps autonomously on rebalance
DEFI_SWAP_AMOUNT_CSPR=5 # base size; scaled up by allocation drift, capped by CSPR_TRADE_MAX_AMOUNT_CSPR
DEFI_SWAP_TOKEN_IN=CSPR
DEFI_SWAP_TOKEN_OUT=sCSPR
DEFI_MAX_SWAPS_PER_DAY=1 # per-day safety cap (raise for repeat demos)
DEFI_MIN_DRIFT_PCT=10 # min allocation drift (pp) to bother swapping — anti-churn
DEFI_MIN_NET_GAIN_BPS=50 # min estimated APY uplift (bps) to justify gas+impact
CSPR_TRADE_MAX_AMOUNT_CSPR=25 # hard cap on input size per swap
CSPR_TRADE_MAX_PRICE_IMPACT_PCT=2.0 # abort a swap whose price impact exceeds this
# Demo tip: to make an autonomous swap fire during a short demo, set
# DEFI_EXECUTE_ON_REBALANCE=true, DEFI_MIN_DRIFT_PCT=5, DEFI_MIN_NET_GAIN_BPS=0,
# AGENT_POLL_INTERVAL_SECONDS=60 — and ensure the agent wallet holds mainnet CSPR
# and ANTHROPIC_API_KEY is valid (a swap only fires when the AI decides REBALANCE).
# ── Real yield — native staking (AGENT-DECIDED) ────────────────────────────
# The agent delegates the vault's CSPR to a Casper validator (native staking,
# env().delegate), sized by ITS OWN allocation decision — the conservative /
# safe-yield bucket IS the staked target — keeping a liquidity buffer so
# ordinary withdrawals stay instant.
# STAKING_ENABLED is an EMERGENCY KILL-SWITCH, not a feature toggle: it defaults
# to TRUE so the AI decides. Setting it false vetoes the agent's own conclusion.
# Leave EMPTY so the agent picks the most profitable validator itself.
STAKE_AMOUNT_CSPR=500 # per stake action (must clear Casper min delegation ~500)
STAKE_BUFFER_CSPR=200 # liquid CSPR always kept for instant withdrawals
STAKE_MAX_PER_DAY=2 # cap on stake actions per day
# ── Agent self-funding + gas-awareness ─────────────────────────────────────
# The agent sweeps the vault's accrued fee reserve to its own gas account
# (collect_fees) and refuels when low. Every on-chain action is pre-checked
# against the agent's real balance so it never executes what it can't pay for.
GAS_RESERVE_CSPR=20 # min agent runway kept before any action
GAS_PER_ACTION_CSPR=6 # est. gas per on-chain action (for runway math)
# ── Multi-tenant servicing ─────────────────────────────────────────────────
# Apply each cycle's AI target to every enrolled vault (drift-gated, capped/day).
MULTI_TENANT_ENABLED=true
TENANT_MIN_DRIFT_PCT=10
TENANT_MAX_REBALANCES_PER_DAY=2
# Mainnet node used to broadcast CSPR.trade swap deploys (bare domain = mainnet).
CSPR_MAINNET_NODE_URL=https://node.cspr.cloud/rpc
# ── App ───────────────────────────────────────────────────────────────────
APP_HOST=0.0.0.0
APP_PORT=8000
DEBUG=false- Python 3.11+
- Node.js 18+
- Casper Wallet browser extension
- Testnet CSPR from the faucet (at least ~250 CSPR)
- Anthropic API key from console.anthropic.com
- CSPR.cloud API key from cspr.cloud
git clone https://github.com/kataenda/agent-casper.git
cd agent-casper# Create virtual environment
python -m venv .venv
# Activate venv
.venv\Scripts\activate # Windows
# source .venv/bin/activate # Linux/Mac
# Install dependencies
pip install -r backend/requirements.txtCreate the .env file:
cp backend/.env.example backend/.env
# Edit backend/.env and fill in all required variablesStart the backend:
python -m uvicorn main:app --app-dir backend --host 0.0.0.0 --port 8000 --reloadBackend available at: http://localhost:8000
Swagger API docs: http://localhost:8000/docs
cd frontend
npm installCreate .env.local:
NEXT_PUBLIC_API_URL=http://localhost:8000
NEXT_PUBLIC_WS_URL=ws://localhost:8000
# Deployed vault package hash — enables the real payable deposit (contract custody)
NEXT_PUBLIC_VAULT_PACKAGE_HASH=hash-486a161bf2d5d2b36b2cfda25557adf3c7b70ec1cda7cfb01dec0ba1545ac5ea
# Optional — CSPR.click appId (register at https://console.cspr.build). Unset = wallet
# connect falls back to the Casper Wallet extension; CSPR.click UI stays dormant.
NEXT_PUBLIC_CSPRCLICK_APP_ID=Start the frontend:
npm run devDashboard available at: http://localhost:3000
Both backend and frontend are deployed on a self-hosted VPS using Coolify — a self-hostable Heroku/Netlify alternative. This gives full control over the environment and unrestricted outbound access to the Anthropic API.
- A VPS with at least 2 GB RAM (any provider: Hostinger, DigitalOcean, Hetzner, etc.)
- Docker installed on the VPS
- Coolify installed on the VPS
- A domain pointed to your VPS IP (e.g.
agentcasper.yourdomain.comfor backend,casper.yourdomain.comfor frontend)
-
In Coolify → New Application → Public Repository
-
Fill in:
Field Value Repository URL https://github.com/kataenda/agent-casperBranch masterBuild Pack DockerfileBase Directory /backendPorts Exposes 8000Domain https://agentcasper.yourdomain.com -
In Environment Variables, add:
Variable Value ANTHROPIC_API_KEYsk-ant-api03-...CASPER_NODE_URLhttps://node.testnet.cspr.cloud/rpcCSPR_CLOUD_API_KEYYour CSPR.cloud API key CSPR_CLOUD_BASE_URLhttps://api.testnet.cspr.cloudVAULT_CONTRACT_HASHhash-xxxx...VAULT_CONTRACT_VERSION_HASHleave empty — resolved live from the package on-chain (fallback only) AGENT_ACCOUNT_HASHaccount-hash-xxxx...AGENT_SECRET_KEY_CONTENTPEM content with \nfor newlinesMAX_REBALANCES_PER_DAY5AGENT_POLL_INTERVAL_SECONDS300(use60for a live demo)ADMIN_TOKENlong random secret — gates pause/resume/rebalance/swap/deploy/setup (leave empty to keep open) PORT8000DEBUGfalseAdmin auth: set
ADMIN_TOKENto a long random value to stop anonymous visitors triggering privileged actions from the public dashboard. After redeploying, paste the same value into the dashboard's API page → Admin token field (kept in your browser only) to operate those actions. Never commit the real value — keep it in Coolify env only.Tip for
AGENT_SECRET_KEY_CONTENT: PowerShell:(Get-Content agent_secret_key.pem -Raw) -replace "\r`n","\n" -replace "`n","\n"` -
Click Deploy — Coolify builds the Docker image and starts the container with HTTPS via Let's Encrypt.
-
In Coolify → New Application → Public Repository
-
Fill in:
Field Value Repository URL https://github.com/kataenda/agent-casperBranch masterBuild Pack NixpacksBase Directory /frontendPorts Exposes 3000Domain https://casper.yourdomain.com -
In Environment Variables, add:
Variable Value NEXT_PUBLIC_API_URLhttps://agentcasper.yourdomain.comNEXT_PUBLIC_WS_URLwss://agentcasper.yourdomain.com/wsNEXT_PUBLIC_VAULT_PACKAGE_HASHhash-486a161b...(enables real payable deposit)NEXT_PUBLIC_CSPRCLICK_APP_IDCSPR.click appId from console.cspr.build (optional) -
Click Deploy.
Add two A records in your DNS panel:
| Name | Type | Value |
|---|---|---|
agentcasper |
A | <your VPS IP> |
casper |
A | <your VPS IP> |
Coolify (via Traefik) will automatically obtain Let's Encrypt SSL certificates once DNS propagates.
# Backend health check
curl https://agentcasper.yourdomain.com/
# Expected response:
# {"name": "Agent Casper", "version": "1.0.0", "status": "running"}Check Coolify → backend app → Logs to confirm:
INFO agent.yield_agent — YieldAgent started — polling every 300s
INFO agent.yield_agent — [Block 8,xxx,xxx] Decision: REBALANCE | Confidence: 0.82
┌──────────────────┬──────────────────┬──────────────────┬──────────────────┐
│ PORTFOLIO VALUE │ REBALANCES │ AI DECISION │ BLOCK HEIGHT │
│ 1,332 CSPR │ 0 │ HOLD │ #8,102,213 │
│ Strategy: Bal. │ 0 cycles │ Confidence:82% │ Casper Testnet │
└──────────────────┴──────────────────┴──────────────────┴──────────────────┘
┌────────────────┬────────────────────────┬────────────────┬────────────────┐
│ RWA ORACLE │ PORTFOLIO TRAJECTORY │ ON-CHAIN PROOF│ YIELD INTEL. │
│ PAXG (Gold) │ Portfolio value │ Contract Live │ Conservative: │
│ UST10Y (Bond) │ chart over time │ Deploy hash │ 9.53% APY │
│ WTI (Oil) │ │ Last TX │ Aggressive: │
├────────────────┤ │ │ 14.50% APY │
│ ALLOC MATRIX │ │ │ │
│ Donut chart │ │ │ │
└────────────────┴────────────────────────┴────────────────┴────────────────┘
┌────────────────┬────────────────────────────────────────┬────────────────┐
│ VAULT ACTIONS │ NEURAL DECISION LOG │ ASK AI AGENT │
│ Deposit CSPR │ Full AI decision history │ Chat with │
│ TX History │ HOLD / REBALANCE + reasoning │ Claude AI │
└────────────────┴────────────────────────────────────────┴────────────────┘
- Install Casper Wallet in your browser
- Create or import a Casper account
- Get testnet CSPR from the faucet (minimum ~250 CSPR)
Go to the landing page: https://casper.soenic.com → click Launch app to open the dashboard at /dashboard.
Click the wallet button in the top right → Connect Casper Wallet. Once connected you can deposit (into your own vault or the shared protocol vault) and withdraw from the Vault Actions panel; the vault owner also gets an emergency-pause control and the one-time validator authorisation on /vault.
Skip this step if the contract is already deployed (hash is set in
.env)
- Click "Deploy Contract" in the Vault Actions panel
- Casper Wallet will ask for confirmation (~230 CSPR gas)
- Wait for confirmation (~2 minutes) — the Contract Hash will appear in the On-Chain Proof panel
- Click "Register Agent"
- Confirm in Casper Wallet
- Wait until the status shows
AGENT REGISTEREDin the On-Chain Proof panel
This grants the AI agent permission to execute rebalances on behalf of the vault.
- In the Vault Actions panel, enter the amount of CSPR
- Click "Deposit to Vault"
- Confirm in Casper Wallet
- The TVL (Total Value Locked) will update in the Portfolio Value card
Once CSPR is deposited, the agent is active automatically. Watch:
- AI Decision card: HOLD / REBALANCE / ALERT
- Neural Decision Log: Claude AI reasoning on each polling cycle (60s demo / 300s prod)
- Portfolio Trajectory: value chart over time
- Allocation Matrix: live donut chart of CONS/BALA/AGGR split
| Button | Action |
|---|---|
| START AGENT | Start the agent loop (polls on the configured interval — 60s demo / 300s prod) |
| STOP AGENT | Pause the agent loop |
| API | Open Swagger UI for backend API documentation |
Type directly in the "Ask about portfolio..." box in the bottom-right corner:
| Command | Example | Effect |
|---|---|---|
| start | start, resume, running |
Start the agent loop |
| stop | pause, stop |
Stop the agent loop |
| status | status, report |
Show full agent status |
| rebalance | rebalance, rebalance conservative |
Force an immediate rebalance |
| Free Q&A | what is TVL?, best strategy? |
Answered by Claude AI |
Example status output:
AGENT STATUS:
• Running: Yes
• Rebalances today: 2/5
• Total cycles: 24
• Block: #8,102,213
• TVL: 1,332.00 CSPR
• Allocation: CON=40% BAL=45% AGG=15%
• Strategy: Balanced
• Last decision: HOLD (88% confidence)
Example rebalance conservative output:
REBALANCE EXECUTED!
• Strategy: Conservative (CON=70% BAL=20% AGG=10%)
• TX Hash: 7563c5813420aa0a...
• View: https://testnet.cspr.live/deploy/7563c581...
| Decision | Meaning | When it happens |
|---|---|---|
| HOLD | Keep current allocation | Portfolio already optimal, daily quota exhausted, or stable market conditions |
| REBALANCE | Change portfolio allocation | AI finds a better risk-adjusted allocation |
| ALERT | Anomalous conditions detected | APY spike >50%, TVL drop >30%, or risk surge |
| Strategy | CONS | BALA | AGGR | Risk | Best for |
|---|---|---|---|---|---|
| Conservative | 70% | 20% | 10% | Low | Uncertain market, gold rising |
| Balanced | 40% | 45% | 15% | Medium | Normal conditions |
| Aggressive | 10% | 20% | 70% | High | Very high DeFi yields |
| Signal | Effect on AI |
|---|---|
| PAXG (gold) rises >1% | Favor Conservative allocation (flight-to-safety) |
| UST10Y (Treasury) >5% | Require DeFi yield premium ≥3× Treasury rate |
| UST10Y <3.5% | DeFi more attractive → Balanced/Aggressive acceptable |
| WTI (oil) surging | Raise risk threshold for Aggressive positions |
agent-casper/
├── contracts/
│ ├── src/yield_vault.rs # YieldVault Odra contract — upgradable + payable (real custody)
│ ├── Cargo.toml # Odra 2.7.2 dependencies
│ ├── Dockerfile.build # WASM compilation
│ ├── wasm/yield_vault.wasm # Built by CI
│ └── x402/Cep18X402.wasm # CEP-18 X402 token (make-software/casper-x402)
├── backend/
│ ├── main.py # FastAPI + WebSocket + agent lifecycle + admin & wallet-sign auth
│ ├── .env.example # Configuration template (incl. ADMIN_TOKEN)
│ ├── yield_vault.wasm # Vault wasm served to the browser deploy flow
│ ├── proxy_caller.wasm # Odra proxy-caller — attaches real CSPR to payable deposit()
│ ├── data/ # Runtime state (vault registry, cycle history) — created at runtime
│ ├── agent/
│ │ ├── yield_agent.py # Autonomous loop — services EVERY enrolled vault (multi-tenant)
│ │ └── decision_engine.py # Claude AI with MCP tools
│ └── casper/
│ ├── client.py # CSPR.cloud REST client (TTL-cached, paginated reads)
│ ├── deployer.py # Transaction signing (pycspr), on-chain version resolution
│ ├── rwa_oracle.py # PAXG / UST10Y / WTI price feeds
│ ├── mcp_server.py # MCP server — blockchain tools for Claude
│ ├── x402.py # x402 micropayment handler (consumer + provider)
│ ├── eip712.py # EIP-712 typed-data digest (casper-eip-712 port)
│ ├── cspr_trade.py # CSPR.trade MCP — real non-custodial DeFi swaps
│ ├── swap_log.py # Persistent on-chain swap history
│ ├── x402_settle_log.py # Persistent x402 settlement history
│ ├── vault_registry.py # Multi-tenant vault registry (evidence-based enrollment)
│ ├── trust_engine.py # Deterministic AI trust score from real on-chain data
│ └── trust_state.py # On-chain trust-score anchoring (transfer-id encoding)
├── frontend/src/
│ ├── app/
│ │ ├── page.tsx # Main cyber dashboard (protocol AUM headline, trajectory)
│ │ ├── vault/page.tsx # My Vaults — AUM, per-wallet assets (liquid/staked), gas runway, staking & swap history
│ │ ├── agent/page.tsx # Agent registry — Enrolled Vaults + AI Trust Engine
│ │ ├── deploy/page.tsx # Self-service vault deploy / upgrade / register (per wallet)
│ │ ├── swap/page.tsx # DeFi swap + live swap history (mainnet)
│ │ ├── x402/page.tsx # x402 service catalog + agent-to-agent proof
│ │ └── api/page.tsx # API reference + live "try it" (GET + POST)
│ ├── lib/
│ │ ├── adminAuth.ts # Admin auth: token + Sign-In-with-Wallet session
│ │ ├── walletVault.ts # Wallet-scoped vault resolution (multi-tenant backbone)
│ │ ├── vaultDeposit.ts # Payable deposit/withdraw builders (proxy-caller pattern)
│ │ ├── walletStore.ts # Connected-wallet state
│ │ ├── store.ts # Agent state store
│ │ └── useWebSocket.ts # Live WebSocket feed
│ └── components/ # DeployPanel, VaultControls, RWAPanel,
│ └── … # DecisionLog, ChatBox, AgentControls, etc.
├── scripts/
│ ├── deploy_x402_token.py # Deploy the CEP-18 X402 token (agent holds supply)
│ ├── fund_buyer.py # Fund a buyer agent with X402 tokens
│ ├── buyer_pays_agent.py # REAL agent-to-agent on-chain settlement
│ ├── x402_settle_real.py # Self-settle via the CSPR.cloud facilitator
│ ├── pay_live_endpoint.py # Full x402 flow against the LIVE production API
│ ├── x402_verify_proof.py # Facilitator /verify conformance proof
│ └── deploy_testnet.{sh,ps1} # Vault contract deploy helpers
├── demo_x402.py # Consumer-side x402 demo (agent's own flow)
├── demo_buyer_agent.py # Independent x402 buyer agent (own ed25519 key)
├── gen_buyer_key.py # Fresh ed25519 buyer identity (wallet creation)
├── .claude/skills/
│ └── csprclick-skill/ # Official CSPR.click AI Agent Skill (SKILL.md + references)
└── .github/workflows/
└── deploy-contract.yml # CI: auto-build WASM (mirrored into backend/)
Possible causes:
-
ANTHROPIC_API_KEYnot configured — Check Coolify backend logs. If you see⚠ ANTHROPIC_API_KEY is not set, add the key to Coolify Environment Variables and redeploy. -
Portfolio already at optimal allocation — If the reasoning says
"Portfolio already at optimal 40/45/15 allocation", the agent is correctly holding because no rebalance is needed. -
Daily rebalance quota exhausted — If the reasoning says
"Daily rebalance quota exhausted (5/5)", wait until midnight UTC for the counter to reset. You can increase the limit viaMAX_REBALANCES_PER_DAY. -
Market conditions not meeting threshold — The AI only rebalances when conditions warrant a change. HOLD is correct when the current allocation is already optimal.
WARNING agent.decision_engine — ANTHROPIC_API_KEY is not configured
→ Set ANTHROPIC_API_KEY=sk-ant-... in Coolify → Environment Variables → redeploy.
WARNING agent.decision_engine — Anthropic unexpected error: Connection error
→ Verify port 443 is open on VPS (ufw status). VPS environments have unrestricted outbound access unlike some PaaS platforms.
- Ensure
NEXT_PUBLIC_API_URLandNEXT_PUBLIC_WS_URLin Coolify frontend Environment Variables are correct - Verify both backend and frontend SSL certificates are valid (green padlock in browser)
- CORS is allowed for all origins (
*) by default
- Ensure the agent account has enough CSPR for gas (~5 CSPR per transaction)
- Verify
AGENT_SECRET_KEY_PATHorAGENT_SECRET_KEY_CONTENTis correct - Verify
VAULT_CONTRACT_HASHmatches the deployed contract
# Check which process is using port 8000
netstat -ano | findstr :8000 # Windows
lsof -i :8000 # Linux/Mac- The agent requires CSPR balance in the agent account to pay gas for rebalance transactions (~5 CSPR each)
- Maximum 5 rebalances per day (configurable via
MAX_REBALANCES_PER_DAY) - After 5 rebalances, the agent keeps monitoring but will not execute until the quota resets at midnight UTC
- Vault/rebalance/RWA transactions are visible at testnet.cspr.live; CSPR.trade DeFi swaps are on mainnet at cspr.live
- The YieldVault contract is on Casper Testnet. The CSPR.trade DeFi swaps run on mainnet and spend the agent account's own CSPR (the DEX is mainnet-only) — fund the agent's mainnet account to enable
/defi/swapexecution
Agent Casper is built to be a self-sustaining agent, not a one-off demo. Revenue comes from two streams:
| Stream | Status | How it works |
|---|---|---|
| x402 service fees | ✅ Live | The agent sells its intelligence: other agents pay 5 CSPR per AI rebalance recommendation (/x402/decision) and 2.5 CSPR per on-chain-verified RWA feed (/x402/rwa-feed). Payment settles into the agent's own mainnet account — machine-to-machine revenue that scales with adoption. |
| Vault management fee | ✅ In contract | The YieldVault charges an owner-configurable management fee on deposits (fee_bps, default 1%, capped 10%), credited to the protocol owner and emitted as a FeeCollected event. Implemented in yield_vault.rs — active on the live testnet instance once the updated WASM is deployed. |
| Vault performance fee | 🔄 Phase 2 | When the vault routes deposited capital into live yield positions, it additionally takes a performance fee (% of yield generated) — the standard model for an automated portfolio manager. |
This two-sided design means the agent earns both as a service provider in the x402 agent economy today, and as a yield manager on assets under management as the vault matures. Operating costs (gas, Claude inference, RWA data) are covered per-cycle, so the margin grows with usage rather than requiring continuous external funding.
- YieldVault with REAL custody on Casper Testnet — payable
deposit()lands CSPR in the contract purse (86fd83a6…); upgradable in place with state preserved (proven v1→v2 on-chain) - Multi-tenant vault servicing — any wallet self-service deploys/owns its vault, registers the agent on it (
1dc138a9…), and the agent autonomously services every enrolled vault (tenant rebalanced7551fcb…) — live AUM ~2,400 CSPR across 3 independently-owned vaults - Real native staking — the vault's CSPR earns — the agent selects a validator itself (lowest-fee, active) and autonomously delegates each vault's CSPR, sized to that vault's own balance (3 confirmed delegations of 500 CSPR:
21354398…,5cd6bf7b…,aab61086…) - RWA-driven execution — verified gold/treasury/oil signals change the allocation, which sets the staking target and swap direction (not just displayed)
- Verifiable AI decisions — each rebalance commits
sha256(inputs + decision)on-chain; pre-image served from/agent/decision-proofto recompute - Landing page + full dashboard — deposit / withdraw, owner emergency-pause, per-tenant staked breakdown; runtime state persisted (survives redeploys)
- Autonomous AI agent (Claude) with a configurable decision loop (60s demo / 300–900s prod) via MCP tools
- RWA oracle on-chain posting (PAXG, UST10Y)
- x402 micropayments — two-sided (consumer and provider, mainnet)
- Real non-custodial DeFi swaps on Casper mainnet via CSPR.trade MCP
- Sign-In with Wallet admin auth (owner verified on-chain) + AI Trust Engine with on-chain score anchoring
- Official CSPR.click AI Agent Skill installed in-repo; real-time cyber dashboard with WebSocket
- Beyond native staking (shipped): route capital into LP pools / stables and other Casper DeFi positions, with per-position accounting
- Auto-compounding of staking rewards + a performance fee on generated yield
- Live yield rate feeds from on-chain sources
- Per-vault strategy profiles — each tenant sets its own risk mandate (multi-vault servicing + per-vault staking already shipped in Phase 1)
- Mobile notifications (Telegram bot)
- Casper Mainnet deployment
- Full tenant isolation — multi-tenant servicing is already live (one agent identity autonomously manages every enrolled vault, proven on-chain). Productization completes the isolation: each user/DAO gets its own non-custodial agent key held in a KMS / threshold-signing setup (never a shared PEM), tenant-scoped state in a database (
tenant_idon every record), per-tenant dashboards, and wallet-signed auth on every tenant action (the owner flow ships today). The single-agent core stays the unit of execution — we replicate it per tenant rather than re-architect it. - x402 fee-based API for institutional access (CEP-18 stablecoin micropayments)
- DAO governance for strategy parameters
- Audited smart contracts
Follow the project and reach out:
| Channel | Link |
|---|---|
| X / Twitter | @kata_enda |
| Telegram | @soesoe14 |
| Discord | mas_end_47419 |
| GitHub | kataenda/agent-casper |
| Community Vote | Vote on CSPR.fans |
If you find this project useful, please vote for Agent Casper AI on CSPR.fans to help us advance to the Final Round of the Buildathon!
MIT License — Copyright (c) 2026 Soesoe
Built for the Casper Agentic AI Buildathon 2026
Stack: Claude AI · CSPR.cloud · Odra 2.7.2 · casper-js-sdk v5 · FastAPI · Next.js






