Skip to content

Latest commit

 

History

17 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

AiFinPay × Casper — AI Agent Payment Protocol

AiFinPay × Casper

Payment infrastructure for autonomous AI agents — settled on Casper

Autonomous AI agents need to pay each other and pay for services — compute, data, APIs — with no human in the loop. AiFinPay is the payment protocol (x402); Casper is the on-chain settlement layer. This repository is the live Casper settlement contract, the x402 bridge, SDK examples, and an MCP server that lets AI agents settle payments on Casper.

CI CodeQL License: MIT Casper Rust Node.js MCP Buildathon

Quick Start · Architecture · Payment Flow · Sample Transactions · Demo · Roadmap


Table of Contents


Introduction

AiFinPay is payment infrastructure for the machine economy. This repository contains the Casper settlement backend: a Rust → Wasm contract in which agents self-register and pay_agent atomically transfers native CSPR before writing an immutable receipt.

Problem

Agent-to-agent and agent-to-service commerce needs three things that today's payment rails don't provide together:

  1. Identity — a stable, verifiable on-chain identity for each agent.
  2. A payment protocol — a machine-native way to request and authorize payment (no checkout page, no human).
  3. Settlement proof — an immutable, independently verifiable record that a payment happened.

Card rails and custodial wallets assume a human and a browser. Agents need programmatic settlement with cryptographic proof — at micropayment scale and micropayment cost.

Solution

AiFinPay closes the loop:

  • x402 protocol — a service returns HTTP 402 Payment Required; the agent settles on-chain and retries with proof.
  • Casper settlement contract — agents self-register an on-chain identity, then pay_agent atomically transfers CSPR and emits PaymentSettled.
  • Idempotent settlement — payments are keyed by request_id, so retries are safe and double-settlement is impossible.
  • MCP server — AI agents (e.g. Claude via Claude Code / Claude Desktop) settle on Casper as a native tool call.

Features

  • 🧾 Caller-bound registryregister_agent(agent_id, wallet) accepts only the caller's account hash.
  • 💸 Atomic settlementpay_agent(from, to, amount, request_id) moves CSPR and records the exact terms in one transaction.
  • 🔁 Idempotent by design — duplicate request_id is rejected (no double spend).
  • 🌐 x402 bridge — a reference compute gate that enforces HTTP 402 and verifies settlement on-chain before releasing a resource.
  • 🤖 MCP integration — drive settlements directly from an AI agent runtime.
  • 📊 Live dashboard — reads Casper RPC directly to show settlement counts and records.
  • 🦀 Minimal, auditable Rust contract — deterministic Wasm execution.

Architecture

flowchart LR
    subgraph Client["AI Agent Runtime"]
        A[AI Agent]
        SDK[AiFinPay SDK / MCP server]
    end

    subgraph Protocol["AiFinPay x402 Protocol"]
        API[x402 Bridge / API]
    end

    subgraph CasperChain["Casper Blockchain"]
        SC[AiFinPay Settlement Contract]
        LEDGER[(Immutable ledger<br/>agents · payments · events)]
    end

    M[Merchant / Service]

    A --> SDK
    SDK -->|register_agent / pay_agent| API
    API -->|HTTP 402 challenge| A
    API --> SC
    SC --> LEDGER
    SC -->|PaymentSettled event| API
    API -->|verified · unlock resource| M
    M -->|deliver result| A
Loading

Full storage layout, named keys, and error codes are in docs/ARCHITECTURE.md. A component + lifecycle overview is in ARCHITECTURE.md.

Why Casper

  • Predictable, low fees for high-frequency machine-to-machine micropayments.
  • Deterministic Wasm execution (Rust) — settlement logic is auditable and small.
  • Native on-chain events (PaymentSettled) give merchants cryptographic proof of payment without a trusted intermediary.
  • Clean account / identity model that fits agent registries well.
  • Idempotent settlement keyed by request_id — safe retries, no double spend.

Payment Flow

sequenceDiagram
    autonumber
    participant Agent as AI Agent
    participant Bridge as x402 Bridge / API
    participant Casper as Casper Contract
    participant Merchant as Merchant / Service

    Agent->>Casper: register_agent(agent_id, wallet)
    Merchant->>Casper: register_agent(provider_id, wallet)
    Agent->>Bridge: request resource (compute)
    Bridge-->>Agent: HTTP 402 Payment Required (pay_casper challenge)
    Agent->>Casper: pay_agent(from, to, amount, request_id)
    Casper-->>Casper: validate agents · record payment · emit PaymentSettled
    Casper-->>Agent: tx confirmed (deploy hash)
    Agent->>Bridge: retry request (+ request_id)
    Bridge->>Casper: verify PaymentSettled(request_id)
    Casper-->>Bridge: settlement confirmed
    Bridge->>Merchant: unlock resource
    Merchant-->>Agent: deliver result
Loading

Repository Structure

casper-contract/
├── src/                     # Rust → Wasm settlement contract
│   └── main.rs              #   register_agent · pay_agent · get_payment_count
├── demo/                    # Node.js: agent, x402 bridge, MCP server, dashboard
│   ├── agent-compute-demo.js  # ⭐ AI agent buys compute, settles on Casper
│   ├── compute-bridge.js      # x402 gate — verifies settlement on-chain
│   ├── casper-mcp.mjs         # MCP server for AI-agent-driven settlement
│   ├── deploy.js · keygen.js  # deploy + keypair generation
│   ├── dashboard.html         # live settlement dashboard
│   └── .env.example
├── examples/                # Copy-paste integration examples
├── scripts/                 # build / deploy / demo wrappers
├── docs/                    # ARCHITECTURE · DEPLOYMENT · DEMO_VIDEO
├── .github/                 # CI, CodeQL, Dependabot, issue/PR templates
├── Cargo.toml               # aifinpay-casper (Rust contract)
├── Makefile                 # make setup / build / deploy / agent-demo
└── SUBMISSION.md            # Buildathon submission summary

Quick Start

# 1. Clone
git clone https://github.com/AiFinPay/casper-contract.git
cd casper-contract

# 2. One-time setup (Rust wasm target + Node deps)
make setup

# 3. Build the contract to Wasm
make build

# 4. Generate a keypair, then fund it at the faucet
make keygen
#    → paste the account hash at https://testnet.cspr.live/tools/faucet, wait ~2 min

# 5. Run the headline demo: AI agent buys compute, settled on Casper
make agent-demo

The contract is already deployed on Casper testnet, so you can run the demo against the live contract hash without deploying your own. To deploy your own copy, use make deploy.

Installation & Configuration

Prerequisites: Rust (stable) with the wasm32-unknown-unknown target, and Node.js ≥ 18.

# Rust toolchain (contract)
rustup target add wasm32-unknown-unknown

# Node toolchain (demo / SDK / MCP)
cd demo && npm install && cp .env.example .env

Payment clients also require a reviewed deployments/casper-v2.json; an environment variable alone cannot enable an unverified contract.

Local Development

make fmt        # format Rust
make clippy     # lint (warnings as errors)
make test       # contract tests
make demo       # basic register + settle flow
make agent-demo # AI agent buys compute (x402 → Casper)
make mcp        # start the Casper MCP server
make dashboard  # serve the live dashboard

Deploying the Contract

make build      # target/wasm32-unknown-unknown/release/aifinpay_casper.wasm
make deploy     # deploys via demo/deploy.js, prints the new CONTRACT_HASH

Do not enable payment routes until the deployed Wasm/source provenance has been independently checked and the v2 manifest is committed with status: verified. Full walkthrough: docs/DEPLOYMENT.md.

Historical Casper deployments — quarantined

The hashes below are retained as historical evidence only. They are v1 deployments: pay_agent recorded an amount but did not transfer it, and a separate transfer produced the old demo balance change. They are not valid payment proof and all current clients reject them.

Field Value
Network casper (Casper 2.0 mainnet)
Contract hash contract-9903a5e3948e799196df54b17270bc6769338ac1cc36c9eb47e113f88d23f019
Package hash hash-7ad34a204952eef63d5dcf5159fb7d009e85dea4f49cbdf73dde190652dfa375
Explorer cspr.live mainnet
Install deploy 0d560c62…

Historical mainnet demonstration

The following two independent operations were previously described as one settlement. The contract call recorded a receipt; the later native transfer moved value.

Action Deploy Explorer
Register agent (buyer) aee06f58… view
Register agent (provider) 4f06da16… view
PaymentSettled (pay_agent) 80df5895… view
Value transfer (2.5 CSPR → provider) 564f19be… view

Do not reproduce this v1 flow. The v2 mainnet script requires separately controlled buyer/provider keys and performs no second transfer.

Historical Casper Testnet Deployment

Field Value
Network casper-test (Casper 2.0)
Public RPC https://node.testnet.casper.network/rpc
Explorer cspr.live testnet
Language Rust → WebAssembly (casper-contract 5.1.1, casper-types 6.1.0)

Entry Points

Entry Point Args Description
register_agent agent_id: String, wallet: String Self-register caller wallet → AgentRegistered
pay_agent from_agent: String, to_agent: String, amount: U512, request_id: String Transfer CSPR and record settlement → PaymentSettled
get_payment_count Total settled payments

Events

  • AgentRegisteredagent_id, wallet
  • PaymentSettledfrom, to, amount (motes), request_id

Contract Package Hash

hash-47df409829ddf0612617460293ba591a19b26fa0c06918878204088d3eb9b78a

View on cspr.live →

Sample Transactions

Historical v1 transactions from the agent-compute demo on casper-test (not valid settlement proof):

Action Deploy Explorer
Register agent (buyer) d4b7d0ad…27d23e0 view
Register agent (provider) 6c41c885…faac4e8 view
PaymentSettled (pay_agent) 0b55b516…ffb0137 view

Reproduce them yourself: make agent-demo (with a funded key at demo/keys/secret_key.pem).

SDK & API Examples

Small, runnable examples live in examples/:

The reference x402 gate is demo/compute-bridge.js; the AI agent client is demo/agent-compute-demo.js.

Environment Variables

Configure in demo/.env (see demo/.env.example):

Variable Default Description
NODE_URL https://node.testnet.casper.network/rpc Casper RPC endpoint
NETWORK_NAME casper-test Casper network name
KEYS_DIR ./keys Directory holding the signing key
CONTRACT_HASH Must match the verified v2 deployment manifest
PROVIDER_AGENT_ID Merchant identity self-registered by its own wallet
PROVIDER_KEYS_DIR Separate funded merchant key for two-party demos only
COMPUTE_UPSTREAM_URL (optional) Real OpenAI-compatible compute endpoint
COMPUTE_API_KEY (optional) API key for the upstream provider

Never commit .env, keys, or keypairs. .gitignore blocks demo/.env and demo/keys/, but always double-check before pushing.

Testing Instructions

make test                                    # Rust contract tests
cargo clippy --all-targets -- -D warnings    # lint
cargo fmt --all -- --check                   # format check
cd demo && node test-mcp.mjs                 # MCP server smoke test

End-to-end: run make agent-demo against the live contract and confirm the printed PaymentSettled deploy resolves to Success on cspr.live.

Screenshots

Agent Settlement Dashboard — a live view of the deployed testnet contract: registered agents, on-chain settlements, per-payment receipts, and the raw event log, all read straight from the Casper RPC. Run it locally with cd demo && node serve-dashboard.js.

AiFinPay × Casper agent settlement dashboard

Demo Video

The narrated walkthrough script is in docs/DEMO_VIDEO.md — an autonomous AI agent buys compute and settles it on Casper testnet in ~90 seconds, ending on the on-chain settlement proof.

📹 Video link: to be added.

Roadmap

See ROADMAP.md for the full plan. Highlights:

  • ✅ Live Casper settlement contract + end-to-end agentic payment flow + MCP server.
  • 🔜 USDC settlement, a typed @aifinpay/casper SDK on npm, hosted x402 gateway.
  • 🧭 Casper Mainnet, programmable spend limits, on-chain agent reputation.

Security

  • CodeQL, Dependabot, and secret scanning with push protection run on this repository.
  • Report vulnerabilities privately — see SECURITY.md. Do not open a public issue for security problems.

Contributing

Contributions are welcome — see CONTRIBUTING.md and our CODE_OF_CONDUCT.md. Use the issue and PR templates; CI (build, lint, CodeQL) must pass.

License

MIT © 2026 AiFinPay.

Acknowledgements

Casper Agentic Buildathon

This repository is AiFinPay's submission to the Casper Agentic Buildathon — a fully functional MVP on Casper testnet with a live contract, verifiable on-chain settlements, demo + testing instructions, and CI/security automation. See SUBMISSION.md.

Useful Links

About

Payment infrastructure for autonomous AI agents — the AiFinPay x402 protocol, settled on Casper. Live testnet contract, x402 bridge, SDK examples & MCP server.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages