Skip to content

About

HBARPAYMENTS

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

πŸ›‘οΈ Hedera Spend Guardian

Policy-enforced AI agent for Hedera Testnet β€” 5 custom policies guard every transaction

Live Demo Hedera AI Bounty Framework HAK


πŸ“– Overview

Hedera Spend Guardian is an autonomous AI agent that leverages the Hedera Agent Kit v4 with LangChain/LangGraph and DeepSeek V4 Pro to interact with Hedera Testnet. Every tool callβ€”whether an on-chain transfer or an off-chain API requestβ€”is intercepted by a 5-layer policy engine before execution.

Core Architecture

User Message β†’ /api/chat
 β†’ Policy Engine (5 Custom Policies)
   β”œβ”€ SpendLimitPolicy    β†’ Daily HBAR cap + per-transaction limit
   β”œβ”€ ServiceAllowPolicy  β†’ Whitelist external APIs (Tavily, OpenAI, Hedera)
   β”œβ”€ TimeWindowPolicy    β†’ Business hours only (9:00–23:00 UTC)
   β”œβ”€ MaxSpendPolicy      β†’ USD-based daily budget + per-project caps
   └─ AllowlistPolicy     β†’ Counterparty guard + API provider filtering
 β†’ Pre-Execution Gate (wrapped-tools.ts)
 β†’ HAK v4 + LangChain Agent (6 tools)
 β†’ Hooks: AuditLogHook (HCS) + AlertHook (Telegram)
 β†’ DeepSeek LLM response

Policies Implemented

5 composable policies run in sequence β€” the first block wins:

Policy Type Enforcement
SpendLimitPolicy Financial safety Caps daily spend (default: 5 HBAR) + per-tx limit (default: 2 HBAR)
ServiceAllowPolicy Off-chain guard Whitelists which external services the agent can call
TimeWindowPolicy Temporal guard Restricts transactions to business hours (9:00–23:00 UTC), queries exempt
MaxSpendPolicy USD-based budgeting Global + per-project daily USD caps with HBAR→USD conversion
AllowlistPolicy Counterparty guard Blocks transfers to unauthorized accounts + unapproved API providers

All policies are composable β€” they run in sequence via policyEngine.evaluate(), and the first block wins. The pre-execution gate in wrapped-tools.ts prevents any transaction from reaching the network before all 5 policies pass.


πŸš€ Quick Start

# Clone
https://github.com/374group-tech/hederapayments.git && cd hederapayments

# Install
npm install

# Configure
cp .env.example .env
# Edit .env with your Hedera testnet credentials + DeepSeek API key

# Run
npm run dev

Open http://localhost:3000


βš™οΈ Environment Variables

# Hedera Testnet (ED25519 account)
HEDERA_OPERATOR_ID=0.0.9253164
HEDERA_OPERATOR_KEY=302e...

# DeepSeek API (free tier at platform.deepseek.com)
DEEPSEEK_API_KEY=sk-...

# Policy configuration (optional β€” defaults shown)
DAILY_SPEND_LIMIT_HBAR=5
MAX_PER_TX_HBAR=2
BUSINESS_START_HOUR=9
BUSINESS_END_HOUR=23
ALLOWED_SERVICES=tavily,openai,hedera
TAVILY_API_KEY=tvly-...

🧩 Tech Stack

Layer Technology Purpose
Framework Next.js 16 (App Router) Full-stack React app
Language TypeScript Type-safe agent code
Hedera SDK @hiero-ledger/sdk v2.85 ED25519 signing + HCS
Agent Kit @hashgraph/hedera-agent-kit ^4.0.0 Hedera tools for agent
LangChain @hashgraph/hedera-agent-kit-langchain ^1.0.0 + LangGraph Agent orchestration
LLM DeepSeek V4 Pro (via Pioneer.ai) Cost-optimized reasoning + direct SDK for transfers
UI React 19 + Tailwind CSS 4 Chat panel + policy dashboard
Hosting Vercel Production deployment

πŸ“Š Live Demo

πŸ”— hederapayments.vercel.app

The app features:

  • πŸ’¬ Chat Panel β€” Send requests to the policy-guarded agent
  • πŸ“Š Policy Status Sidebar β€” Real-time spend tracking, service whitelist, and time window status
  • πŸ“œ HCS Audit Trail β€” Every agent action logged to Hedera Consensus Service (topic ID visible in sidebar)
  • 🎨 Dark Theme β€” Clean, modern UI built with Tailwind CSS

πŸ” Safety & Autonomy

The agent signs transactions autonomously using ED25519 private key stored server-side. However, LLM-based function calling is unreliable for financial transactions β€” DeepSeek often outputs tool calls as text rather than executing them natively. Our architecture solves this with a hybrid model:

Operation Execution Model Why
Transfers (transfer_hbar) Direct Hedera SDK 100% reliable, zero hallucination, HashScan-verified
Balance queries Direct Hedera SDK Instant, zero LLM cost, no tool call overhead
Account info Direct Hedera SDK Deterministic, always accurate
Free-form chat DeepSeek V4 Pro Agent Flexible reasoning, full LangChain/LangGraph pipeline

The policy engine evaluates ALL transfers BEFORE direct SDK execution β€” the pre-execution gate intercepts the parsed intent (amount + recipient), runs all 5 policies, and only allows the SDK transaction if every policy passes. This is a stronger safety guarantee than relying on LLM tool calls that may hallucinate or silently fail.

  • βœ… No HashPack popups β€” agent signs directly via @hiero-ledger/sdk
  • βœ… 5-layer policy defense β€” every transaction passes through SpendLimit β†’ ServiceAllow β†’ TimeWindow β†’ MaxSpend β†’ Allowlist before execution
  • βœ… Immutable audit trail β€” every decision logged to HCS for full traceability
  • βœ… Testnet only β€” funds are HBAR testnet, no real value at risk

πŸ§ͺ Agent Interaction Example

// POST /api/chat β€” { "message": "Transfer 1 HBAR to 0.0.12345" }

// Agent flow:
// 1. PolicyEngine.evaluate() checks all 5 policies
// 2. SpendLimitPolicy: 1 HBAR ≀ 2 HBAR per-tx β†’ βœ…
// 3. ServiceAllowPolicy: "hedera" is allowed β†’ βœ…
// 4. TimeWindowPolicy: 14:00 UTC is within 9-23 β†’ βœ…
// 5. MaxSpendPolicy: 1 Γ— $0.07 = $0.07 < $50 β†’ βœ…
// 6. AllowlistPolicy: recipient in allowlist β†’ βœ…
// 7. Transaction signed with ED25519 key, submitted to testnet
// 8. HCS audit log written
// 9. Response returned with policy status + HashScan link

// Response:
{
 "message": "Successfully transferred 1 HBAR to 0.0.12345. Tx: 0.0.9253164@...",
 "blocked": false,
 "policyResults": [
   { "allowed": true, "policy": "SpendLimitPolicy" },
   { "allowed": true, "policy": "ServiceAllowPolicy" },
   { "allowed": true, "policy": "TimeWindowPolicy" },
   { "allowed": true, "policy": "MaxSpendPolicy" },
   { "allowed": true, "policy": "AllowlistPolicy" }
 ],
 "status": {
   "spendLimit": { "spentToday": 1, "dailyLimit": 5, "perTxLimit": 2 },
   "serviceAllow": { "allowedServices": ["tavily", "openai", "hedera"] },
   "timeWindow": { "startHour": 9, "endHour": 23 },
   "maxSpend": { "spentTodayUsd": 0.07, "dailyLimitUsd": 500, "remainingUsd": 499.93 },
   "allowlist": { "apiProviders": ["openai", "tavily"], "accountIds": ["0.0.12345"] }
 },
 "topicId": "0.0.5XXXXXX"
}

πŸ“ Project Structure

hederapayments/
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ app/
β”‚   β”‚   β”œβ”€β”€ api/chat/route.ts      # POST /api/chat β€” agent endpoint
β”‚   β”‚   β”œβ”€β”€ layout.tsx              # Root layout
β”‚   β”‚   └── page.tsx                # Chat panel + policy dashboard
β”‚   └── lib/
β”‚       β”œβ”€β”€ config.ts               # Zod env validation
β”‚       β”œβ”€β”€ hedera-client.ts        # Client.forTestnet() with ED25519
β”‚       β”œβ”€β”€ hcs-audit.ts            # HCS topic + message submission
β”‚       β”œβ”€β”€ constants.ts            # Operator ID export
β”‚       β”œβ”€β”€ wrapped-tools.ts        # Pre-execution policy gate (wrap HAK tools)
β”‚       β”œβ”€β”€ policy-engine.ts        # Orchestrates all policies
β”‚       β”œβ”€β”€ hooks/
β”‚       β”‚   β”œβ”€β”€ index.ts            # Hook exports
β”‚       β”‚   β”œβ”€β”€ AlertHook.ts        # Telegram alerts on blocks/high-value tx
β”‚       β”‚   └── AuditLogHook.ts     # HCS immutable audit trail (v2.0)
β”‚       └── policies/
β”‚           β”œβ”€β”€ types.ts            # PolicyResult + PolicyContext
β”‚           β”œβ”€β”€ spend-limit.ts      # SpendLimitPolicy (v1.0)
β”‚           β”œβ”€β”€ service-allow.ts    # ServiceAllowPolicy (v1.0)
β”‚           β”œβ”€β”€ time-window.ts      # TimeWindowPolicy (v1.0)
β”‚           β”œβ”€β”€ max-spend.ts        # MaxSpendPolicy (v2.0 β€” USD-based)
β”‚           └── allowlist.ts        # AllowlistPolicy (v2.0 β€” counterparty)
β”œβ”€β”€ package.json
β”œβ”€β”€ tsconfig.json
β”œβ”€β”€ .env.example
└── README.md

πŸ› Known Issues & Workarounds

TypeScript build errors (TS1259/TS2749)

@hiero-ledger/sdk transitive dependencies require:

// tsconfig.json
{
 "compilerOptions": {
   "esModuleInterop": true,
   "allowSyntheticDefaultImports": true,
   "target": "ES2017"
 }
}

Tool type mismatch

toolkit.getTools() returns HederaAgentKitTool[] β€” use as any cast for LangGraph compatibility.


πŸ‘¨β€πŸ’» For Judges: 60-Second Test Guide

Step Action What to Verify
1 Open hederapayments.vercel.app Dark-themed chat panel + policy sidebar loads with "5 custom policies" subtitle
2 Type "Check my balance" and press Send Agent responds via DeepSeek + HAK tools with real HBAR balance
3 Observe Policy Status sidebar All 5 policies show live configuration (SpendLimit, ServiceAllow, TimeWindow, MaxSpend, Allowlist)
4 Type "Transfer 1 HBAR to 0.0.XXXXX" and send Policy Engine evaluates all 5; response shows blocked or success with policyResults array
5 Check response JSON in DevTools β†’ Network β†’ /api/chat policyResults has 5 entries, status has all 5 policy statuses, topicId present
6 Verify source: src/lib/policies/ 5 custom policy classes, composable in policy-engine.ts, guarded by wrapped-tools.ts
7 Check src/lib/hooks/ AuditLogHook (HCS immutability) + AlertHook (Telegram notifications) β€” 643 lines

βœ… Bounty Checklist

Requirement Status Evidence
Public GitHub repo βœ… github.com/374group-tech/hederapayments
Uses Hedera Agent Kit βœ… HAK v4 + LangChain toolkit, 6 tools exposed
5 custom policies βœ… SpendLimit, ServiceAllow, TimeWindow, MaxSpend, Allowlist β€” composable engine (source)
Composable policy engine βœ… PolicyEngine evaluates all 5 in sequence (source)
Pre-execution gate βœ… wrapped-tools.ts β€” blocks BEFORE on-chain tx (source)
HCS Audit Trail βœ… AuditLogHook β€” immutable on-chain log via HCS (source)
Telegram Alerts βœ… AlertHook β€” real-time notifications on blocks/high-value/daily-limit (source)
Live demo (public URL) βœ… hederapayments.vercel.app
GitHub feedback issue βœ… Issue #933 on hashgraph/hedera-agent-kit-js
Human safety (no fund drain) βœ… 5-layer policy defense: spend caps + service whitelist + time window + USD budget + counterparty allowlist
Agent autonomy βœ… ED25519 server-side signing, no HashPack popups needed
README with architecture βœ… Architecture diagram + full tech stack above
Iterative git history βœ… 29 commits across development window, all authored by 374group-tech

πŸ”— On-Chain Verification

Every agent action is verifiable on Hedera Testnet:

  • HCS Audit Trail β€” look up the topicId returned in every /api/chat response on HashScan Testnet. Every agent decision (allowed/blocked) is recorded immutably.
  • Transfers β€” if the agent executes a transfer_hbar, the transaction ID is returned in the response. Verify sender, recipient, and amount on HashScan.
  • Account β€” 0.0.9253164 on HashScan β€” ED25519 key, used for agent signing.

πŸ“œ License

MIT β€” built for the Hedera AI Bounty Week 5 (Policy Agent).


Built by 374group-tech for the Hedera AI Bounty Campaign β€” June 2026

πŸ”— YouTube description should include:

πŸ”— Live Demo: https://hederapayments.vercel.app/
πŸ“‚ GitHub: https://github.com/374group-tech/hederapayments
πŸ† Built for Hedera AI Bounty Week 5 β€” Policy Agent
#Hedera #HBAR #AI #Web3 #AgenticCommerce

About

HBARPAYMENTS

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages