Doramagic Project Pack · Human Manual
mnemopay-sdk
MnemoPay addresses the fundamental challenges of AI agent financial infrastructure:
Introduction to MnemoPay SDK
Related topics: Quick Start Guide, System Architecture
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Related Pages
Related topics: Quick Start Guide, System Architecture
Introduction to MnemoPay SDK
MnemoPay SDK is an AI agent trust and reputation SDK that provides memory, payments, identity, and agent credit scoring capabilities in a single package. It enables autonomous AI agents to handle financial operations, maintain persistent memory, and establish reputation across multi-agent systems.
Overview
MnemoPay addresses the fundamental challenges of AI agent financial infrastructure:
- Memory: Persistent memory with semantic recall and reinforcement capabilities
- Payments: Real money through Stripe, Paystack, and Lightning payment rails with escrow support
- Identity: KYA (Know Your Agent) verification, capability tokens, and permission management
- Agent Credit Score: FICO-equivalent scoring (300-850) for AI agents enabling creditworthiness evaluation
Sources: CLAUDE.md
Architecture
The SDK consists of 14 core modules in the src/ directory, providing approximately 74KB of compiled TypeScript functionality.
graph TD
subgraph "MnemoPay SDK Core"
A["index.ts<br/>Main SDK Entry"]
B["fico.ts<br/>Agent Credit Score"]
C["behavioral.ts<br/>Behavioral Finance"]
D["integrity.ts<br/>Merkle Integrity"]
E["anomaly.ts<br/>EWMA Detection"]
F["adaptive.ts<br/>AIMD/Circuit Breaker"]
G["commerce.ts<br/>Shopping Engine"]
H["fraud.ts<br/>Geo Fraud Detection"]
I["identity.ts<br/>KYA/CapabilityTokens"]
J["ledger.ts<br/>Double-Entry Ledger"]
K["network.ts<br/>Multi-Agent Network"]
L["client.ts<br/>REST Client"]
M["mcp/server.ts<br/>MCP Server"]
end
subgraph "Payment Rails"
N["rails/stripe.ts"]
O["rails/paystack.ts"]
P["rails/lightning.ts"]
end
A --> B
A --> C
A --> D
A --> E
A --> F
A --> G
A --> H
A --> I
A --> J
A --> K
A --> L
A --> M
L --> N
L --> O
L --> PSources: CLAUDE.md
Module Overview
| Module | Purpose |
|---|---|
index.ts | Main SDK exports: MnemoPay, MnemoPayLite, MnemoPayNetwork classes |
fico.ts | Agent Credit Score (300-850); exports AgentCreditScore with legacy AgentFICO alias |
behavioral.ts | Behavioral finance engine implementing prospect theory and cooling-off mechanisms |
integrity.ts | Merkle tree memory integrity using SHA-256 hashing |
anomaly.ts | EWMA anomaly detection, BehaviorMonitor, and CanarySystem |
adaptive.ts | Adaptive AIMD rate limiting, anti-gaming protections, circuit breaker, PSI drift detection |
commerce.ts | CommerceEngine enabling autonomous shopping with financial mandates |
fraud.ts | Geo-enhanced fraud detection with location-based risk scoring |
identity.ts | IdentityRegistry, KYA verification, CapabilityTokens, and killswitch permissions |
ledger.ts | Double-entry accounting ledger for precise transaction tracking |
network.ts | Multi-agent commerce network coordination |
client.ts | REST API client for backend communication |
mcp/server.ts | MCP server exposing 24 tools and 2 prompts for agent interaction |
Sources: CLAUDE.md
Two SDK Modes
MnemoPay provides two operational modes depending on deployment requirements:
Dev Mode (Zero Infrastructure)
const agent = MnemoPay.quick("agent-id");
Dev mode requires no backend infrastructure. Agents receive immediate access to memory, wallet functionality, and identity features directly in the client.
Sources: CLAUDE.md
Production Mode (Full Backend)
Production mode connects to the hosted MnemoPay console at https://mnemopay-landing.fly.dev/ and requires backend connectivity for:
- Persistent storage across sessions
- Real payment rail integration
- Multi-agent coordination
- Governance and audit capabilities
Sources: CHANGELOG.md
Quick Start
Installation
npm install @mnemopay/sdk
Development Workflow
npm install # install dependencies
npm run build # compile TypeScript
npm test # run 672+ vitest tests
npm run lint # type-check without emit
Sources: CLAUDE.md
Memory System
The memory system provides persistent, semantic memory capabilities for AI agents:
Core Operations
| Operation | Description |
|---|---|
remember(content, namespace, tags, importance) | Store new memory with semantic tagging |
recall(query, namespace, limit, mode) | Retrieve memories using hybrid search |
reason(query, namespace, limit, mode) | Complex reasoning over stored memories |
reinforce(memoryId) | Strengthen memory importance |
forget(memoryId) | Remove specific memories |
Memory Architecture
graph LR
A["User Input"] --> B["Namespace Router"]
B --> C["remember()"]
C --> D["Semantic Index"]
D --> E["Memory Store"]
F["Query"] --> G["recall()"]
G --> H["Hybrid Search"]
H --> I["Relevance Scorer"]
I --> J["Ranked Results"]
K["Graph Enrichment"] --> D
E --> KLongMemEval Benchmark
The memory system achieved 77.2% on the LongMemEval oracle benchmark, demonstrating strong multi-session retrieval capabilities. The system handles 1M+ operational stress tests in production environments.
Sources: site/journal/v1-4-0-longmemeval-77-2.html
Payment System
Payment Rails
MnemoPay integrates with three primary payment rails:
| Rail | Region | Currencies | Features |
|---|---|---|---|
| Paystack | Africa | NGN, GHS, ZAR, KES | Checkout, saved cards, bank transfers, webhook verification, HMAC-SHA512 |
| Stripe | Global | USD, EUR, GBP, 135+ | Card payments, manual capture, true escrow via PaymentIntents |
| Lightning | Crypto | BTC | Instant microtransactions for agent-to-agent payments |
Sources: site/index.legacy.html
Core Payment Operations
// Charge customer
await agent.charge(amount, reason);
// Settle transaction (release escrow)
await agent.settle(tx_id);
// Refund
await agent.refund(tx_id);
// Dispute handling
await agent.dispute(tx_id, reason);
Escrow Flow
graph TD
A["Agent charges()"] --> B["Funds held in Escrow"]
B --> C{"Human approves?"}
C -->|Yes| D["Agent settles()"]
C -->|No| E["Refund initiated"]
D --> F["Merchant receives funds"]
E --> G["Customer refunded"]Sources: site/index.legacy.html
Agent Credit Score
The Agent Credit Score (FICO-equivalent) provides a 300-850 scoring system for evaluating AI agent reliability and trustworthiness.
Scoring Components
| Component | Weight | Description |
|---|---|---|
| Payment History | 35% | Historical transaction success rate |
| Utilization | 30% | Credit usage patterns |
| Behavioral Signals | 20% | Prospect theory analysis, cooling-off adherence |
| Anomaly Score | 10% | EWMA deviation from baseline behavior |
| Identity Verification | 5% | KYA completion level |
Score Ranges
| Score Range | Rating | Description |
|---|---|---|
| 750-850 | Excellent | High-trust agent, minimal monitoring |
| 650-749 | Good | Standard transaction limits |
| 550-649 | Fair | Enhanced monitoring, lower limits |
| 300-549 | Poor | Restricted operations, high collateral |
Sources: CLAUDE.md
Identity and Access Control
KYA (Know Your Agent)
Identity verification ensures agents are properly registered and authorized:
// Register agent identity
const identity = await agent.identity.register({
agentId: "agent-001",
capabilities: ["payment", "memory", "commerce"],
verificationLevel: "standard"
});
// Issue capability token
const token = await agent.identity.issueToken(agentId, capabilities);
Permission Model
| Permission | Description |
|---|---|
payment.charge | Initiate charges |
payment.refund | Process refunds |
memory.write | Store memories |
memory.read | Access memories |
identity.delegate | Issue sub-tokens |
killswitch | Emergency shutdown |
Sources: CLAUDE.md
Integrity and Security
Merkle Memory Integrity
All memories are protected using SHA-256 Merkle trees, enabling cryptographic proof of memory authenticity and detecting tampering:
// Verify memory integrity
const audit = await agent.integrity.verify(memoryId);
const isValid = audit.proof.verify(rootHash, memoryId);
EWMA Anomaly Detection
Exponentially Weighted Moving Average (EWMA) detects behavioral deviations:
- Real-time monitoring of transaction patterns
- Fingerprinting of agent behavior baselines
- Canary systems for novel action detection
Sources: CLAUDE.md
Adaptive Rate Limiting
The adaptive module implements:
- AIMD (Additive Increase, Multiplicative Decrease): Graceful rate adjustment
- Circuit Breaker: Automatic shutdown on repeated failures
- Anti-Gaming: Detection of manipulation attempts
- PSI Drift: Population Stability Index monitoring
Governance
MnemoPay includes enterprise-grade governance features:
| Component | Purpose |
|---|---|
| Charter | Mission scope and operating principles |
| FiscalGate | Budget enforcement and spending limits |
| Article 12 | Audit bundle requirements |
| MerkleAudit | Cryptographic audit trail |
Sources: CHANGELOG.md
Python Integration
A Python port provides stable parity with the TypeScript SDK:
pip install mnemopay
The Python SDK mirrors the TypeScript PaymentRail interface and ships with MockRail and StripeRail implementations.
Sources: integrations/python-hosted/README.md
Python API Methods
| Method | Description |
|---|---|
remember(content, namespace, tags, importance) | Store memory |
recall(query, namespace, limit, mode) | Retrieve memories |
charge(amount, reason) | Process payment |
settle(tx_id) | Complete transaction |
graph(namespace) | Get memory graph |
usage_report() | Usage statistics |
Middleware Integration
MnemoPay provides middleware for popular AI frameworks:
OpenAI Integration
import { mnemoPayMiddleware } from "@mnemopay/sdk/middleware/openai";
Anthropic Integration
import { mnemoPayMiddleware } from "@mnemopay/sdk/middleware/anthropic";
LangGraph Integration
import { mnemoPayTools } from "@mnemopay/sdk/langgraph";
Sources: README.md
Version History
| Version | Status | Key Features |
|---|---|---|
| 1.6.0 | Alpha | Latest pre-release with hardening fixes |
| 1.5.0 | Stable | Governance fold, FiscalGate, MerkleAudit |
| 1.4.0 | Past | 77.2% LongMemEval, 1M-op stress test |
| 1.0.0 | Python | Python SDK stable release |
Sources: CHANGELOG.md
License
MnemoPay SDK is Apache 2.0 Licensed.
Sources: CLAUDE.md
Quick Start Guide
Related topics: Introduction to MnemoPay SDK
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Related Pages
Related topics: Introduction to MnemoPay SDK
Quick Start Guide
Overview
The Quick Start Guide provides developers with the fastest path to integrate MnemoPay SDK into their agent applications. MnemoPay is a full payment and memory system designed specifically for AI agents, enabling them to handle financial transactions, persistent memory, and identity management with zero configuration required.
Sources: README.md:1-15
Prerequisites
| Requirement | Version/Details |
|---|---|
| Node.js | v18+ recommended |
| npm/yarn/pnpm | Any modern package manager |
| API Key | Required for production use |
| Environment | Node.js runtime |
Installation
The MnemoPay SDK is available on npm and can be installed with a single command:
npm install @mnemopay/sdk
Sources: site/index.html:1-20
Quick Initialization
After installation, initialize your agent with a single function call that provides memory, wallet, and identity:
import { MnemoPay } from "@mnemopay/sdk";
// Initialize with agent ID - zero config needed
const mnemo = MnemoPay.quick("agent-id");
// Your agent now has:
// - Persistent memory system
// - Payment wallet
// - Unique identity
Sources: site/index.legacy.html:1-30
Four-Step Workflow
The following diagram illustrates the complete workflow from installation to production:
graph TD
A[Install<br/>npm install @mnemopay/sdk] --> B[Initialize<br/>MnemoPay.quick agent-id]
B --> C[Transact<br/>charge settle refund]
C --> D[Scale<br/>Multi-agent commerce]
E[Memory System] --> B
F[Payment Wallet] --> B
G[Agent Identity] --> B
H[Stripe] --> C
I[Paystack] --> C
J[Lightning] --> CSources: site/index.html:25-45
Core Operations
Payment Operations
| Method | Description |
|---|---|
charge(amount, reason) | Initiate a payment request |
settle(tx_id) | Complete an escrow release |
refund(tx_id) | Process a refund |
Sources: site/index.legacy.html:15-25
Memory Operations
| Method | Description |
|---|---|
remember(content, namespace, tags, importance) | Store new information |
recall(query, namespace, limit, mode) | Retrieve relevant memories |
reinforce(memoryId) | Increase memory importance |
forget(memoryId) | Remove a memory |
Sources: integrations/python-hosted/README.md:1-50
Environment Configuration
Create a .env file in your project root with the following variables:
| Variable | Description | Required |
|---|---|---|
MNEMO_API_KEY | Your MnemoPay API key | Yes |
STRIPE_KEY | Stripe secret key | For Stripe payments |
PAYSTACK_KEY | Paystack secret key | For Paystack payments |
LIGHTNING_CONFIG | Lightning node config | For Lightning payments |
Middleware Integration
MnemoPay provides middleware for popular AI frameworks:
OpenAI Integration
import { mnemoPayMiddleware } from "@mnemopay/sdk/middleware/openai";
Anthropic Integration
import { mnemoPayMiddleware } from "@mnemopay/sdk/middleware/anthropic";
LangGraph Integration
import { mnemoPayTools } from "@mnemopay/sdk/langgraph";
Sources: README.md:40-55
Complete Example
import { MnemoPay } from "@mnemopay/sdk";
// Initialize agent
const mnemo = MnemoPay.quick("checkout-agent-001");
// Store a memory
await mnemo.remember(
"Customer prefers express shipping",
"default",
["preference", "shipping"],
0.9
);
// Recall relevant information
const memories = await mnemo.recall("shipping preferences", "default", 5);
// Process a payment
const charge = await mnemo.charge(29.99, "Order #12345");
// Settle when order fulfilled
await mnemo.settle(charge.txId);
Sources: site/index.legacy.html:10-30
Payment Rails
MnemoPay supports three payment rails:
| Rail | Region | Features |
|---|---|---|
| Paystack | Africa (NGN, GHS, ZAR, KES) | Checkout, saved cards, bank transfers, HMAC-SHA512 security |
| Stripe | Global (USD, EUR, GBP) | Card payments, manual capture for escrow, 135+ currencies |
| Lightning | Crypto | Instant Bitcoin payments |
Sources: site/index.legacy.html:80-100
Dashboard Access
After initialization, you can monitor your agent's activity through the MnemoPay dashboard which provides:
- Real-time transaction monitoring
- Memory usage analytics
- Agent credit score (300-850 scale)
- Multi-agent network status
Sources: dashboard/index.html:1-50
Next Steps
| Resource | Purpose |
|---|---|
| Full Documentation | Complete API reference |
| Pricing | Starter/Pro/Enterprise plans |
| Enterprise | Custom integrations and support |
Sources: README.md:1-15
System Architecture
Related topics: Core Modules Reference, Payment Rails Overview, Charter & FiscalGate Governance
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Related Pages
Related topics: Core Modules Reference, Payment Rails Overview, Charter & FiscalGate Governance
System Architecture
Overview
The MnemoPay SDK is a financial infrastructure layer designed specifically for AI agents. It provides a comprehensive system that combines memory management, payment processing, identity verification, and fraud detection into a unified architecture. The SDK operates as an alpha release (v1.6.0-alpha) with stable v1.5.0 available on the latest npm tag, maintaining the same underlying architecture across versions.
The system is built to enable autonomous financial transactions where AI agents can charge, settle, and refund payments while maintaining persistent memory and earning credit scores based on their transaction behavior. This architectural approach treats agents as first-class financial actors with identity, reputation, and accountability mechanisms built into the core.
Core Architecture Layers
graph TD
subgraph GOVERNANCE["GOVERNANCE Layer"]
Charter["Charter"]
FiscalGate["FiscalGate"]
Article12["Article 12"]
MerkleAudit["MerkleAudit"]
end
subgraph IDENTITY["Identity Layer"]
KYA["KYA"]
Tokens["Tokens"]
Perms["Permissions"]
Killswitch["Killswitch"]
end
subgraph PAYMENTS["Payment Layer"]
Charge["charge()"]
Settle["settle()"]
Refund["refund()"]
Dispute["dispute()"]
end
subgraph MEMORY["Memory Layer"]
Remember["remember"]
Recall["recall"]
Reinforce["reinforce"]
Forget["forget"]
end
subgraph CREDIT["Agent Credit Score"]
Scoring["5-component scoring"]
ScoreRange["300-850 range"]
end
subgraph BEHAVIORAL["Behavioral Finance"]
Prospect["Prospect Theory"]
Nudges["Nudges"]
end
subgraph ANOMALY["Anomaly Detection"]
EWMA["EWMA"]
Fingerprinting["Fingerprinting"]
end
GOVERNANCE --> IDENTITY
GOVERNANCE --> PAYMENTS
MEMORY --> CREDIT
PAYMENTS --> CREDIT
CREDIT --> BEHAVIORAL
PAYMENTS --> ANOMALYSystem Components
SDK Client Architecture
The MnemoPay SDK operates through a client-based architecture where developers initialize the system using the MnemoPay.quick() factory method. This approach provides zero-configuration setup that immediately gives an agent access to memory capabilities, wallet functionality, and cryptographic identity verification. The client handles all communication with backend services while presenting a clean, intuitive API surface for developers.
The SDK is distributed as @mnemopay/sdk on npm and supports installation via standard Node.js package managers. The TypeScript implementation provides full type safety and IDE integration, while a Python port (mnemopay on PyPI) achieves stable parity with the TypeScript implementation, including the PaymentRail interface with sync API support.
| Component | Purpose | Language Support |
|---|---|---|
| Core SDK | Client initialization, API abstraction | TypeScript, Python |
| Payment Rails | Transaction processing | TypeScript, Python |
| MCP Server | Model Context Protocol integration | TypeScript |
| Middleware | Framework integrations | TypeScript |
Payment Rail System
The payment architecture implements a rail abstraction layer that supports multiple payment providers while maintaining a consistent interface. This design allows the system to switch between payment providers without changing application code, providing flexibility for different markets and use cases.
graph LR
App["Application"] --> SDK["MnemoPay SDK"]
SDK --> Stripe["Stripe Rail"]
SDK --> Paystack["Paystack Rail"]
SDK --> Lightning["Lightning Rail"]
SDK --> Mock["Mock Rail"]
Stripe --> StripeAPI["Stripe API<br/>USD, EUR, GBP"]
Paystack --> PaystackAPI["Paystack API<br/>NGN, GHS, ZAR, KES"]
Lightning --> LightningNet["Lightning Network<br/>BTC"]
style Stripe fill:#635bff,color:#fff
style Paystack fill:#00abd1,color:#fff
style Lightning fill:#f7931a,color:#fffSupported Payment Rails:
| Rail | Region | Currencies | Features |
|---|---|---|---|
| Stripe | Global | USD, EUR, GBP, 135+ | Manual capture for true escrow, PaymentIntents API |
| Paystack | Africa | NGN, GHS, ZAR, KES | Checkout, saved cards, bank transfers, webhook verification, HMAC-SHA512 security, 23 Nigerian banks pre-mapped |
| Lightning | Crypto | BTC | Instant settlement via Lightning Network |
| Mock | Testing | All | Test mode without real transactions |
The escrow mechanism holds funds until human approval, providing a critical safety layer for autonomous agent transactions. When an agent initiates a charge, funds are captured but not settled until explicit human authorization, preventing unauthorized autonomous spending.
Identity and Access Control
The identity layer implements Know Your Agent (KYA) verification with cryptographic tokens and permission management. A killswitch mechanism provides emergency stop capabilities, allowing immediate revocation of agent permissions across all active sessions.
Identity components operate through a multi-layered verification system:
- KYA (Know Your Agent): Agent registration and verification process
- Tokens: Cryptographic credentials for API authentication
- Permissions: Granular access control for agent capabilities
- Killswitch: Emergency permission revocation system
Agent Credit Score System
Agents receive credit scores ranging from 300 to 850, calculated through a five-component scoring model. This scoring system directly influences the agent's financial capabilities, including transaction limits and pricing terms.
| Score Component | Description | Impact |
|---|---|---|
| Payment History | Historical transaction success rate | Primary factor |
| Transaction Volume | Total and average transaction sizes | Secondary factor |
| Dispute Rate | Ratio of disputed to total transactions | Negative impact |
| Response Time | Speed of human approval responses | Moderate impact |
| Behavioral Patterns | Anomaly detection signals | Risk adjustment |
The credit score affects the Ceiling parameter, calculated as $500 × reputation per charge, and determines the agent's decay rate with a half-life of approximately 14 hours. Settling transactions adds +0.05 importance to the memory reinforcement system, creating a feedback loop that improves score accuracy over time.
Communication Architecture
Backend Communication
The MnemoPay console backend implements a robust communication infrastructure with the following characteristics:
- REST API: Primary interface for synchronous operations
- WebSockets: Real-time event streaming for dashboard updates
- Webhooks: Asynchronous notification system for payment events
The hosted console at mnemopay-landing.fly.dev implements three-tier reliability architecture:
| Tier | Components | Purpose |
|---|---|---|
| Tier 1 | Production blockers | Core functionality protection |
| Tier 2 | Observability | Monitoring and metrics |
| Tier 3 | Safety nets | Rate limiting, body-size caps, idempotent webhooks |
Observability Stack
graph TD
subgraph OBSERVABILITY["Observability Layer"]
Metrics["Prometheus /metrics"]
Logs["Structured JSON Logging"]
Health["Health Endpoints"]
end
subgraph SAFETY["Safety Layer"]
RateLimit["Rate Limiting"]
BodyCap["Body Size Caps"]
CORS["CORS Allowlist"]
Headers["Security Headers"]
end
subgraph DELIVERY["Delivery Layer"]
Webhook["Webhook Notifications"]
Idempotent["Idempotent Processing"]
Shutdown["Graceful Shutdown"]
end
Metrics --> Prometheus["Prometheus"]
Logs --> ELK["ELK Stack"]
Health --> Ready["/readyz endpoint"]
RateLimit --> SAFETY
Webhook --> Idempotent
Ready --> ReadyResponse{"readyz response<br/>productionReady: true"}Security headers including Content-Security-Policy, X-Content-Type-Options, and X-Frame-Options protect the dashboard from common web vulnerabilities. The /readyz endpoint returns productionReady: true when all systems are operational, serving as a health check for load balancers and orchestrators.
Middleware Integrations
The SDK provides middleware packages for seamless integration with popular AI frameworks, enabling automatic transaction tracking and payment capabilities within existing agent workflows.
Available Middleware
| Integration | Package Path | Purpose |
|---|---|---|
| OpenAI | @mnemopay/sdk/middleware/openai | OpenAI agent transaction middleware |
| Anthropic | @mnemopay/sdk/middleware/anthropic | Anthropic Claude agent middleware |
| LangGraph | @mnemopay/sdk/langgraph | LangGraph tools integration |
MCP Server
The Model Context Protocol (MCP) server enables standardized communication between AI models and external tools. The MCP server implementation in src/mcp/server.ts uses require.main === module to prevent spurious server starts when consumers import from @mnemopay/sdk/mcp in browser bundles or test harnesses. This auto-start guard replaces the previous loose process.argv heuristic that caused issues with browser consumers.
Dashboard Architecture
The web-based dashboard provides real-time monitoring and management capabilities through a React-based single-page application. The dashboard architecture uses a tabbed interface with specialized panels for different operational concerns.
graph TD
subgraph DASHBOARD["Dashboard Components"]
Console["Console Panel"]
Session["Session Panel"]
Brain["Brain Panel"]
Developer["Developer Panel"]
Billing["Billing Panel"]
Repos["Repos Panel"]
end
subgraph STATE["Application State"]
Profile["Profile<br/>wallet, reputation, memoriesCount"]
Overview["Overview<br/>transactions, members, apiKeys"]
Session["Session<br/>login, logout state"]
Repos["Repos<br/>GitHub monitoring"]
end
Console --> STATE
Session --> STATE
Brain --> STATE
Developer --> STATE
Billing --> STATE
Repos --> STATEDashboard Tabs and Functions:
| Tab | Icon | Function |
|---|---|---|
| Console | System monitor | Overview of transactions and account status |
| Session | Users | Login/logout session management |
| Brain | Brain icon | Memory recall and query interface |
| Developer | Code brackets | API key management |
| Billing | Credit card | Usage metering and plan limits |
| Memories | Database | Memory persistence configuration |
GitHub Repository Monitoring
The dashboard includes a repository monitoring feature that tracks GitHub forks and upstream stars. Repositories are displayed with status indicators showing:
- Upstream star count
- Last update date
- Pull request information with title, number, and creation date
- Error states when fetching fails
Behavioral Finance System
The architecture incorporates behavioral finance principles through prospect theory implementation and nudging mechanisms. These components work together to influence agent decision-making in financial contexts, encouraging optimal behavior while preventing risky transaction patterns.
Anomaly Detection
Transaction anomaly detection uses Exponentially Weighted Moving Average (EWMA) statistical methods combined with behavioral fingerprinting. This dual approach identifies both statistical outliers and behavioral patterns that deviate from established agent profiles.
| Detection Method | Function |
|---|---|
| EWMA | Statistical anomaly detection on transaction amounts and frequencies |
| Fingerprinting | Behavioral pattern recognition across transaction sequences |
Governance Framework
The governance layer provides institutional controls over agent financial activities through four primary mechanisms:
- Charter: Defines agent mission scope and authorized activities
- FiscalGate: Budget enforcement for transaction limits
- Article 12: Compliance and regulatory requirements
- MerkleAudit: Cryptographic audit trail for transaction verification
This multi-layered governance ensures agents operate within defined parameters while maintaining full accountability for their financial actions.
SDK Installation and Quick Start
# Install the SDK
npm install @mnemopay/sdk
# Python installation (alternative)
pip install mnemopay
// Initialize with zero configuration
import { MnemoPay } from "@mnemopay/sdk";
const agent = MnemoPay.quick("agent-id");
// The agent now has:
// - Persistent memory
// - Wallet functionality
// - Cryptographic identity
// - Payment capabilities
Sources: README.md:1-40 Sources: site/index.html Sources: site/index.legacy.html Sources: dashboard/index.html Sources: CHANGELOG.md
Sources: README.md:1-40
Core Modules Reference
Related topics: System Architecture
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Related Pages
Related topics: System Architecture
Core Modules Reference
The MnemoPay SDK comprises 14 core modules organized in the src/ directory, providing a comprehensive trust and reputation infrastructure for AI agents that handle money. This reference documents all foundational modules, their responsibilities, and how they interrelate to form a complete payment and identity system.
Architecture Overview
The SDK architecture follows a layered design where core primitives (memory, ledger, identity) support higher-order features (payments, commerce, fraud detection). The main export MnemoPay bundles all modules into a unified interface (~74KB), while MnemoPayLite provides a lightweight alternative and MnemoPayNetwork extends functionality for multi-agent scenarios.
graph TD
subgraph "Core Layer"
M[Memory/Recall]
L[Ledger]
I[Identity]
end
subgraph "Trust Layer"
F[FICO - Agent Credit Score]
B[Behavioral Finance]
IN[Integrity - Merkle Trees]
end
subgraph "Safety Layer"
A[Anomaly Detection]
AD[Adaptive - AIMD/Circuit Breaker]
FR[Fraud Detection]
end
subgraph "Commerce Layer"
C[Commerce Engine]
N[Network]
R[Payment Rails]
end
M --> F
M --> B
L --> A
I --> AD
F --> FR
B --> C
C --> R
N --> R
I --> NSources: README.md:40-55
Memory Module (`src/recall/`)
The memory module provides persistent, searchable memory capabilities for agents using semantic and hybrid retrieval. It supports the core memory operations: remember, recall, reinforce, forget, and consolidate.
Memory Operations
| Operation | Purpose | Parameters |
|---|---|---|
remember(content, namespace?, tags?, importance?) | Store a memory with optional importance score and tags | Content string, namespace ID, tag array, importance 0-1 |
recall(query, namespace?, limit?, mode?) | Retrieve relevant memories via semantic search | Query string, namespace, result limit, search mode |
reinforce(memoryId) | Boost a memory's importance score (+0.01 to +0.5) | Memory ID |
forget(memoryId) | Permanently delete a memory by ID | Memory ID |
consolidate(namespace?) | Prune stale memories below decay threshold | Optional namespace filter |
Search Modes
The recall engine supports multiple retrieval modes for different use cases:
graph LR
A[Query] --> B{Mode}
B -->|semantic| C[Vector Embedding Search]
B -->|keyword| D[BM25 Full-Text Search]
B -->|hybrid| E[Weighted Combination]
C --> F[Results]
D --> F
E --> F- semantic: Pure vector similarity search using embeddings
- keyword: Traditional BM25-based keyword matching
- hybrid: Weighted combination of both approaches (default)
Sources: src/recall/engine.ts
Memory Structure
Each memory entry contains:
| Field | Type | Description |
|---|---|---|
id | string | Unique memory identifier |
content | string | The memory content |
namespace | string | Logical partition for memory spaces |
tags | string[] | Categorization tags |
importance | number | 0-1 importance score for retrieval weighting |
createdAt | Date | Creation timestamp |
updatedAt | Date | Last modification timestamp |
accessCount | number | Number of times recalled |
Sources: integrations/openclaw/SKILL.md:20-35
Ledger Module (`src/ledger.ts`)
The ledger implements double-entry bookkeeping for all financial transactions. Every monetary operation creates balanced entries ensuring accounting integrity across charges, settlements, and refunds.
Transaction Types
| Type | Description | Ledger Impact |
|---|---|---|
charge | Creates escrow hold for delivered work | Debit: Receivable, Credit: Escrow |
settle | Finalizes charge, moves funds to wallet | Debit: Escrow, Credit: Revenue |
refund | Reverses a transaction | Debit: Escrow, Credit: Receivable |
dispute | User-initiated chargeback | Triggers fraud analysis |
Transaction States
stateDiagram-v2
[*] --> pending: charge()
pending --> escrow: User Approval
pending --> cancelled: Timeout/Reject
escrow --> settled: settle()
escrow --> refunded: refund()
settled --> disputed: User Dispute
disputed --> refunded: Won Dispute
disputed --> settled: Lost DisputeSources: src/ledger.ts
Identity Module (`src/identity/`)
The identity system manages agent identification, capabilities, and permissions through a multi-layered approach.
Components
| Component | Purpose |
|---|---|
IdentityRegistry | Central registry mapping agent IDs to identities |
KYA (Know Your Agent) | Onboarding verification for new agents |
CapabilityTokens | Time-limited permission grants |
killswitch | Emergency capability revocation |
Identity Model
interface Identity {
agentId: string;
publicKey: string;
reputation: number; // 0-1 score
kyaStatus: KYAStatus;
capabilities: Capability[];
createdAt: Date;
lastActive: Date;
}
Sources: src/identity/index.ts
Agent Credit Score (`src/fico.ts`)
The Agent Credit Score provides a portable, standardized credit evaluation (300-850 range) for AI agents, enabling trust assessment across different platforms and use cases.
Scoring Components
The FICO module calculates scores using five weighted factors:
| Component | Weight | Description |
|---|---|---|
| Payment History | 35% | Track record of successful settlements |
| Utilization | 30% | Current escrow exposure relative to limits |
| Account Age | 15% | Duration of active account |
| Diversity | 10% | Range of transaction types and rails used |
| Reputation | 10% | Social/professional reputation signals |
Score Ranges
| Range | Classification | Description |
|---|---|---|
| 800-850 | Exceptional | Highly reliable, lowest risk |
| 740-799 | Very Good | Reliable with minimal risk |
| 670-739 | Good | Acceptable risk level |
| 580-669 | Fair | Elevated risk, monitor closely |
| 300-579 | Poor | High risk, limited capabilities |
Sources: src/fico.ts
Fraud Detection (`src/fraud.ts`)
The fraud module provides geo-enhanced fraud detection with pattern recognition and behavioral analysis.
Detection Mechanisms
graph TD
A[Transaction Request] --> B[Geo Analysis]
A --> C[Pattern Matching]
A --> D[Velocity Check]
B --> E{Risk Score}
C --> E
D --> E
E -->|Low| F[Allow]
E -->|Medium| G[Flag for Review]
E -->|High| H[Block + Alert]Risk Factors
| Factor | Description | Threshold |
|---|---|---|
geoVelocity | Rapid location changes impossible for user | >500km/hour |
velocityVolume | Unusual transaction frequency | >10 tx/hour |
amountAnomaly | Statistical outlier in transaction size | >3σ from mean |
patternDeviation | Deviation from established behavioral patterns | Similarity <0.6 |
Sources: src/fraud.ts
Anomaly Detection (`src/anomaly.ts`)
EWMA (Exponentially Weighted Moving Average) anomaly detection monitors behavioral patterns and identifies deviations that may indicate compromise or abuse.
Components
| Component | Purpose |
|---|---|
EWMA | Core statistical monitoring with exponential weighting |
BehaviorMonitor | Tracks behavioral baselines per agent |
CanarySystem | Synthetic transactions to verify system integrity |
Alert Levels
graph LR
A[Metric Stream] --> B[EWMA Calculation]
B --> C{Deviation Check}
C -->|< 2σ| D[Normal]
C -->|2-3σ| E[Warning]
C -->|> 3σ| F[Critical Alert]
D --> G[No Action]
E --> H[Log + Notify]
F --> I[Block + Response]Sources: src/anomaly.ts
Behavioral Finance (`src/behavioral.ts`)
The behavioral module implements concepts from behavioral economics to influence agent decision-making and user interactions.
Features
| Feature | Description |
|---|---|
| Prospect Theory | Loss aversion calculations (losses weighted 2x gains) |
| Cooling-Off Periods | Mandatory waiting periods for high-value transactions |
| Nudges | Behavioral prompts to encourage positive outcomes |
Cooling-Off Rules
High-value transactions (>100 USD equivalent) trigger mandatory review periods:
| Amount Range | Cooling Period |
|---|---|
| $100-$500 | 24 hours |
| $500-$1000 | 72 hours |
| >$1000 | 7 days |
Sources: src/behavioral.ts
Integrity Module (`src/integrity.ts`)
Merkle tree-based memory integrity provides cryptographic proof of memory chain integrity using SHA-256 hashing.
Verification Process
graph TD
A[Memory Entry] --> B[SHA-256 Hash]
B --> C[Merkle Tree Node]
C --> D{Root Hash}
D --> E[Audit Request]
E --> F[Prove Path]
F --> G[Verify against Root]
G --> H[Valid/Invalid]Audit Capabilities
| Feature | Description |
|---|---|
MerkleAudit | Generates proof bundles for external verification |
| Chain Verification | Validates no memories were tampered with |
| Timestamping | Provides proof of memory existence at time T |
Sources: src/integrity.ts
Adaptive Module (`src/adaptive.ts`)
Adaptive rate limiting and anti-gaming mechanisms prevent abuse while allowing legitimate high-throughput scenarios.
Components
| Component | Purpose |
|---|---|
AIMD | Additive Increase, Multiplicative Decrease rate control |
| Anti-Gaming | Detection of rate limit exploitation patterns |
CircuitBreaker | Prevents cascade failures |
PSI Drift | Population Stability Index for distribution shifts |
Circuit Breaker States
stateDiagram-v2
[*] --> Closed: Normal Operation
Closed --> Open: Failure Threshold
Open --> HalfOpen: Recovery Timeout
HalfOpen --> Closed: Success
HalfOpen --> Open: FailureSources: src/adaptive.ts
Commerce Engine (`src/commerce.ts`)
The commerce engine enables autonomous shopping with configurable mandates and spending policies.
Mandate Structure
interface Mandate {
id: string;
agentId: string;
rules: CommerceRule[];
maxAmount: number;
maxFrequency: number;
allowedCategories: string[];
createdAt: Date;
}
Shopping Workflow
graph TD
A[User Request] --> B[Parse Intent]
B --> C[Check Mandate Permissions]
C -->|Permitted| D[Find Best Offer]
C -->|Denied| E[Return Error]
D --> F[Execute Purchase]
F --> G[Charge Escrow]
G --> H[Confirm to User]
E --> I[Log Denial]Sources: src/commerce.ts
MCP Server (`src/mcp/server.ts`)
The Model Context Protocol server exposes SDK functionality as MCP tools for integration with LLM agents.
Available Tools (24 total)
#### Memory Tools (5)
| Tool | Description |
|---|---|
mcp__mnemopay__remember | Store a memory with optional importance and tags |
mcp__mnemopay__recall | Retrieve relevant memories via semantic search |
mcp__mnemopay__forget | Permanently delete a memory |
mcp__mnemopay__reinforce | Boost memory importance |
mcp__mnemopay__consolidate | Prune stale memories |
#### Payment Tools (4)
| Tool | Description |
|---|---|
mcp__mnemopay__charge | Create escrow charge (max $500 × reputation) |
mcp__mnemopay__settle | Finalize pending charge |
mcp__mnemopay__refund | Process refund |
mcp__mnemopay__dispute | File dispute for chargeback |
#### Additional Tools
- Identity management tools
- Ledger query tools
- Reputation management tools
- Usage and audit tools
Sources: src/mcp/server.ts Sources: integrations/openclaw/SKILL.md:40-60
Payment Rails (`src/rails/`)
The rails module provides abstraction over multiple payment providers, enabling cross-border commerce through standardized interfaces.
Supported Rails
| Rail | Region | Currencies | Features |
|---|---|---|---|
| Stripe | Global | USD, EUR, GBP, 135+ | PaymentIntents, Manual Capture, Webhooks |
| Paystack | Africa | NGN, GHS, ZAR, KES | Checkout, Saved Cards, Bank Transfer, HMAC-SHA512 |
| Lightning | Crypto | BTC | Instant settlement, Micropayments |
Rail Interface
interface PaymentRail {
charge(amount: number, currency: string, options: ChargeOptions): Promise<ChargeResult>;
settle(chargeId: string): Promise<SettlementResult>;
refund(chargeId: string, amount?: number): Promise<RefundResult>;
verifyWebhook(payload: any, signature: string): boolean;
}
Escrow Flow
sequenceDiagram
participant Agent
participant SDK
participant Rail
participant Escrow
participant User
Agent->>SDK: charge(amount)
SDK->>Rail: Create PaymentIntent
Rail-->>SDK: Pending Charge
SDK->>Escrow: Hold Funds
User->>User: Review Work
alt Approved
User->>SDK: approve()
SDK->>Rail: Capture
SDK->>Escrow: Release to Wallet
SDK->>SDK: reputation += 0.01
else Rejected
User->>SDK: dispute()
SDK->>SDK: Fraud Analysis
endSources: src/index.ts
Main SDK Entry (`src/index.ts`)
The main index exports three SDK variants optimized for different use cases.
SDK Variants
| Variant | Size | Use Case |
|---|---|---|
MnemoPay | ~74KB | Full-featured production use |
MnemoPayLite | <20KB | Browser, edge functions, constrained environments |
MnemoPayNetwork | +~15KB | Multi-agent scenarios |
Quick Start
import { MnemoPay } from '@mnemopay/sdk';
// Development mode - zero infrastructure
const agent = MnemoPay.quick("agent-id");
// Store memory
await agent.remember("User prefers Express shipping", { importance: 0.8 });
// Recall previous context
const memories = await agent.recall("shipping preferences");
// Charge for work delivered
const charge = await agent.charge(25.00, "Monthly report delivery");
// Settle after user approval
await agent.settle(charge.id);
Initialization Modes
| Mode | Description | Infrastructure Required |
|---|---|---|
quick(agentId) | Dev mode with mock services | None |
init(config) | Production mode with real services | API keys, secrets |
network(config) | Multi-agent network mode | Network registry |
Sources: src/index.ts Sources: README.md:55-75
Module Dependencies
Understanding module dependencies is crucial for proper integration and troubleshooting.
graph TD
R[Recall/Memory] --> L[Ledger]
I[Identity] --> R
I --> F[FICO]
F --> FR[Fraud]
B[Behavioral] --> C[Commerce]
A[Anomaly] --> L
AD[Adaptive] --> A
L --> N[Network]
I --> N
C --> RA[Rails]
R --> IN[Integrity]Configuration Reference
Required Configuration
| Parameter | Type | Description |
|---|---|---|
agentId | string | Unique agent identifier |
apiKey | string | API authentication key |
networkId | string | Network/tenant identifier |
Optional Configuration
| Parameter | Default | Description |
|---|---|---|
mode | "dev" | Runtime mode: dev, production, network |
rail | "stripe" | Primary payment rail |
region | "us-east-1" | Deployment region |
logLevel | "warn" | Logging verbosity |
Sources: src/index.ts
Testing
The SDK includes 672+ vitest tests covering all modules:
npm test # Run all tests
npm run build # Compile TypeScript
npm run lint # Type-check without emit
Test coverage is distributed across:
| Module | Test Focus |
|---|---|
| Memory | CRUD operations, search accuracy, consolidation |
| Ledger | Double-entry balance, transaction states |
| Identity | KYA flow, capability tokens, killswitch |
| Fraud | Geo-velocity, pattern matching, thresholds |
| Anomaly | EWMA calculation, alert thresholds |
| Rails | Payment flows, webhook verification |
Sources: README.md:40-55
Payment Rails Overview
Related topics: Stripe, Paystack & Lightning Rails, Alpha Payment Rails (StripeMPP, x402, GoogleAP2), System Architecture
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Related Pages
Related topics: Stripe, Paystack & Lightning Rails, Alpha Payment Rails (StripeMPP, x402, GoogleAP2), System Architecture
Payment Rails Overview
Introduction
The MnemoPay SDK provides a unified payment abstraction layer called Payment Rails, which enables AI agents to process payments across multiple payment providers through a consistent interface. This architecture decouples business logic from payment provider specifics, allowing developers to switch between or combine payment rails without modifying core application code.
The Payment Rails system supports both stable, production-ready rails and preview/alpha rails for emerging payment methods. All rails share a common API contract, ensuring predictable behavior regardless of the underlying payment provider. Sources: README.md:1-45
Architecture Overview
graph TD
A[Agent / Application] --> B[MnemoPay SDK Core]
B --> C[Payment Rail Abstraction Layer]
C --> D[StripeRail]
C --> E[PaystackRail]
C --> F[LightningRail]
C --> G[StripeMPPRail]
C --> H[X402Rail]
C --> I[GoogleAP2Rail]
D --> J[Stripe API]
E --> K[Paystack API]
F --> L[LND / Lightning Network]
G --> M[Stripe MPP]
H --> N[Base / EIP-3009]
I --> O[Google AP2]Rail Classification
Payment rails in MnemoPay are classified into two stability tiers:
| Classification | Rails | Use Case | Status |
|---|---|---|---|
| Stable | StripeRail, PaystackRail, LightningRail | Production deployments | latest |
| Preview (Alpha) | StripeMPPRail, X402Rail, GoogleAP2Rail | Evaluation and testing | alpha |
Sources: README.md:8-16
Stable Rails
StripeRail
StripeRail provides global card payment processing supporting USD, EUR, GBP, and 135+ currencies. It uses Stripe's PaymentIntents API with manual capture to enable true escrow functionality.
Supported Currencies: USD, EUR, GBP, +135 currencies Use Cases: Global payments, subscription billing, e-commerce Security: PCI-compliant via Stripe
Initialization:
import { StripeRail } from "@mnemopay/sdk";
const stripe = new StripeRail(process.env.STRIPE_SECRET_KEY!);
Sources: README.md:20-24
PaystackRail
PaystackRail focuses on African markets, supporting NGN (Nigerian Naira), GHS (Ghanaian Cedi), ZAR (South African Rand), and KES (Kenyan Shilling). It provides checkout, saved cards, bank transfers, and webhook verification with HMAC-SHA512 security.
Supported Currencies: NGN, GHS, ZAR, KES Regional Coverage: Africa (23 Nigerian banks pre-mapped) Security: HMAC-SHA512 webhook verification
Initialization:
import { PaystackRail } from "@mnemopay/sdk";
const paystack = new PaystackRail(process.env.PAYSTACK_SECRET_KEY!);
Sources: README.md:21-22
LightningRail
LightningRail enables Bitcoin sub-cent micropayments through the Lightning Network, ideal for high-frequency, low-value transactions that would be impractical on the base chain.
Supported: BTC sub-cent micropayments Use Cases: Microtransactions, pay-per-use API calls, tips Requirements: LND URL and macaroon authentication
Initialization:
import { LightningRail } from "@mnemopay/sdk";
const lightning = new LightningRail(LND_URL, MACAROON);
Sources: README.md:23-24
Preview Rails (Alpha)
Preview rails are available for evaluation but may have breaking changes in future releases.
StripeMPPRail
StripeMPPRail enables crypto deposits on Tempo via Stripe's Mass Payment Program (MPP). This rail allows agents to accept cryptocurrency payments that are converted and settled through Stripe's infrastructure.
Supported: Crypto deposits via Stripe MPP Status: alpha (v1.6.0-alpha) Use Case: Crypto-to-fiat settlement for agents
import { StripeMPPRail } from "@mnemopay/sdk";
const mpp = new StripeMPPRail(process.env.STRIPE_SECRET_KEY!);
Sources: src/rails/stripe-mpp.ts
X402Rail
X402Rail implements the EIP-3009 standard for USDC payments on Base. This rail enables transferWithAuthorization, a standardized way to execute payments with cryptographic authorization.
Supported: USDC on Base via EIP-3009 Status: alpha (v1.6.0-alpha) Use Case: On-chain USDC payments with standardized authorization
import { X402Rail } from "@mnemopay/sdk";
import { YourEip3009Signer } from "./your-signer";
const x402 = new X402Rail({ signer: yourEip3009Signer });
Requirements: Bring-your-own EIP-3009 signer implementation
Sources: src/rails/x402.ts
GoogleAP2Rail
GoogleAP2Rail implements the FIDO Alliance's AP2 v0.2 mandate-driven settlement specification. This rail uses mandate-based authorization flows for payment authorization.
Supported: AP2 v0.2 mandate-driven settlement Standard: FIDO Alliance Status: alpha (v1.6.0-alpha) Use Case: FIDO-aligned payment authorization
import { GoogleAP2Rail } from "@mnemopay/sdk";
const ap2 = new GoogleAP2Rail({ mandate, endpoint, signer });
Sources: src/rails/google-ap2.ts
Common Payment Operations
All payment rails support the same core operations for payment lifecycle management:
| Operation | Description |
|---|---|
| Charge | Initiate a payment from the customer's payment method |
| Escrow | Hold funds in a secure state pending verification or delivery |
| Settle | Release escrowed funds to the merchant/recipient |
| Refund | Return funds to the customer |
The double-entry ledger system ensures every financial operation is recorded with corresponding debit and credit entries, maintaining balanced books with zero penny drift. Sources: site/index.html
Environment Configuration
Real Payment Rails
For production deployments using real payment providers:
| Environment Variable | Purpose |
|---|---|
STRIPE_SECRET_KEY | Stripe payments API key |
PAYSTACK_SECRET_KEY | Paystack payments API key |
MNEMOPAY_PAYMENT_RAIL | Active rail: stripe, paystack, or mock |
MNEMOPAY_COMMERCE_PROVIDER | Commerce provider: firecrawl, shopify, or mock |
Sources: claude-plugin/README.md
Mock/Sandbox Mode
For development and testing, the SDK defaults to mock/sandbox mode. Set MNEMOPAY_PAYMENT_RAIL=mock to use simulated payment operations without real money movement.
Quick Setup
import {
PaystackRail, StripeRail, LightningRail, // stable
StripeMPPRail, X402Rail, GoogleAP2Rail, // alpha
} from "@mnemopay/sdk";
// Stable rails
const paystack = new PaystackRail(process.env.PAYSTACK_SECRET_KEY!);
const stripe = new StripeRail(process.env.STRIPE_SECRET_KEY!);
const lightning = new LightningRail(LND_URL, MACAROON);
// Alpha rails (v1.6.0-alpha)
const mpp = new StripeMPPRail(process.env.STRIPE_SECRET_KEY!);
const x402 = new X402Rail({ signer: yourEip3009Signer });
const ap2 = new GoogleAP2Rail({ mandate, endpoint, signer });
// Quick agent initialization
const agent = MnemoPay.quick("my-agent", {
rail: stripe, // Use any configured rail
// ... other config
});
Sources: README.md:26-40
Architecture Benefits
| Benefit | Description |
|---|---|
| Provider Abstraction | Single API interface for multiple payment providers |
| Rail Switching | Change payment providers without code modifications |
| Hybrid Rails | Combine multiple rails in a single agent configuration |
| Consistent Error Handling | Unified error responses across all providers |
| Audit Trail | Every operation logged in the hash-chained ledger |
Choosing a Payment Rail
| Scenario | Recommended Rail |
|---|---|
| Global card payments | StripeRail |
| African markets (NGN, GHS, ZAR, KES) | PaystackRail |
| BTC micropayments | LightningRail |
| Crypto deposits settlement | StripeMPPRail |
| On-chain USDC payments (Base) | X402Rail |
| FIDO-aligned settlement | GoogleAP2Rail |
Summary
The Payment Rails system provides MnemoPay agents with flexible, production-ready payment infrastructure across six different payment providers. Stable rails (Stripe, Paystack, Lightning) handle traditional payment flows, while preview rails (StripeMPP, X402, GoogleAP2) enable emerging crypto and mandate-based payment methods. All rails share a common interface, allowing seamless switching and hybrid configurations.
Sources: README.md:8-16
Stripe, Paystack & Lightning Rails
Related topics: Payment Rails Overview, Alpha Payment Rails (StripeMPP, x402, GoogleAP2)
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Related Pages
Related topics: Payment Rails Overview, Alpha Payment Rails (StripeMPP, x402, GoogleAP2)
Stripe, Paystack & Lightning Rails
Overview
The payment rails system in MnemoPay SDK provides a unified abstraction layer over multiple payment providers, enabling AI agents to process transactions across different geographic regions and payment methods through a consistent API. This architecture decouples business logic from provider-specific implementations, allowing seamless switching between payment rails without code changes.
The SDK currently supports three stable payment rails: StripeRail (global USD, EUR, GBP), PaystackRail (African markets), and LightningRail (Bitcoin micropayments). Additionally, preview rails include StripeMPPRail for crypto deposits, X402Rail for USDC on Base, and GoogleAP2Rail for mandate-driven settlement.
Sources: README.md:1-25
Architecture
Unified PaymentRail Interface
All payment rails implement the PaymentRail interface, ensuring consistent behavior across providers. This abstraction allows developers to:
- Process charges with identical method signatures regardless of provider
- Access two-phase escrow (charge → settle/refund)
- Utilize provider-specific features when needed
- Switch rails with minimal configuration changes
import { PaystackRail, StripeRail, LightningRail } from "@mnemopay/sdk";
// All three use the same API pattern
const paystack = new PaystackRail(process.env.PAYSTACK_SECRET_KEY!);
const stripe = new StripeRail(process.env.STRIPE_SECRET_KEY!);
const lightning = new LightningRail(LND_URL, MACAROON);
Sources: README.md:28-38
Rail Selection Matrix
| Rail | Coverage | Channel | Status | Currencies |
|---|---|---|---|---|
StripeRail | Global | stable (latest) | Stable | USD, EUR, GBP, + |
PaystackRail | Africa | stable (latest) | Stable | NGN, GHS, ZAR, KES |
LightningRail | BTC micropayments | stable (latest) | Stable | BTC |
StripeMPPRail | Crypto via Tempo | preview (alpha) | Alpha | Crypto deposits |
X402Rail | USDC on Base | preview (alpha) | Alpha | USDC |
GoogleAP2Rail | AP2 v0.2 mandate | preview (alpha) | Alpha | Multiple |
Sources: README.md:1-12
Stable Rails
StripeRail
StripeRail provides global card payment processing with manual capture for true escrow functionality. It uses Stripe's PaymentIntents API and supports 135+ currencies.
Key Features:
- Manual capture mode for two-phase escrow (charge → settle)
- PaymentIntents API with full payment method support
- Webhook verification for payment events
- Refund handling with full/partial support
Configuration:
const stripe = new StripeRail(process.env.STRIPE_SECRET_KEY!);
const agent = MnemoPay.quick("billing-agent", { stripe: { secretKey: process.env.STRIPE_SECRET_KEY } });
Sources: README.md:30-32, site/index.html:45-50
Webhook Endpoint:
POST https://dashboard.mnemopay.com/api/v1/billing/stripe/webhook
Handled Events:
checkout.session.completedcustomer.subscription.updatedcustomer.subscription.deleted
Sources: dashboard/DEPLOYMENT.md:22-28
PaystackRail
PaystackRail focuses on African markets with support for Nigerian Naira (NGN), Ghanaian Cedi (GHS), South African Rand (ZAR), and Kenyan Shilling (KES). It provides comprehensive checkout, saved cards, bank transfers, and webhook verification.
Key Features:
- 23 Nigerian banks pre-mapped
- HMAC-SHA512 webhook security
- Multiple payment methods (cards, bank transfer)
- Checkout and saved card support
Configuration:
const paystack = new PaystackRail(process.env.PAYSTACK_SECRET_KEY!);
Sources: README.md:31, site/index.html:58-62
Environment Variables:
PAYSTACK_SECRET_KEY=sk_live_... # Required for Paystack payments
MNEMOPAY_PAYMENT_RAIL=paystack # Set payment rail
Sources: claude-plugin/README.md:8-10
LightningRail
LightningRail enables sub-cent Bitcoin micropayments through the Lightning Network. It connects to LND (Lightning Network Daemon) for instant, low-fee transactions.
Key Features:
- Sub-cent micropayments
- Instant settlement via Lightning Network
- LND connection with macaroon authentication
- Low fees for high-frequency microtransactions
Configuration:
const lightning = new LightningRail(LND_URL, MACAROON);
Sources: README.md:32
Preview Rails (Alpha)
StripeMPPRail
Stripe Machine Payments Protocol (MPP) rail routes agent payments as crypto deposits on the Tempo network via Stripe's MPP-enabled PaymentIntents API.
Technical Details:
- API version:
2026-03-04.preview - Payment method types:
["crypto"] - Capture method:
"manual"for two-phase escrow - In-flight capture deduplication
- Idempotency-key forwarding
Configuration:
const mpp = new StripeMPPRail(process.env.STRIPE_SECRET_KEY!);
Key Methods:
fromClient(client, opts?)— for tests and shared Stripe client patterns
Sources: CHANGELOG.md:20-45
X402Rail
The x402 protocol implements HTTP 402 revival for USDC payments on Base L2 via EIP-3009 transferWithAuthorization. Agents sign transactions off-chain, and a facilitator submits to chain on capture.
Key Features:
- Pluggable
X402Signerinterface - Zero crypto dependencies in SDK
- EIP-3009
transferWithAuthorizationstandard - USDC on Base L2
Configuration:
const x402 = new X402Rail({ signer: yourEip3009Signer });
Sources: CHANGELOG.md:46-55
GoogleAP2Rail
Google Agent Payment Protocol (AP2) v0.2 provides mandate-driven settlement through the FIDO Alliance open standard.
Configuration:
const ap2 = new GoogleAP2Rail({ mandate, endpoint, signer });
Sources: CHANGELOG.md:56-60
Payment Flow Architecture
graph TD
A[Agent Request] --> B[PaymentRail Interface]
B --> C{Provider Selection}
C -->|Global| D[StripeRail]
C -->|Africa| E[PaystackRail]
C -->|BTC| F[LightningRail]
D --> G[Charge with Escrow]
E --> G
F --> G
G --> H[Manual Capture]
H --> I[await settle()]
H --> J[await refund()]
I --> K[Funds Released]
J --> L[Funds Returned]Two-Phase Escrow Model
All payment rails implement a two-phase commit pattern:
- Charge Phase — Funds are authorized and held in escrow
- Settlement Phase — Funds are captured and transferred
- Refund Phase — Funds are returned to the customer
const tx = await agent.charge(49.00, "Pro plan, monthly");
// Escrow holds funds until you approve
await agent.settle(tx.id);
// Money moves. Ledger balanced. Credit score updated.
Sources: site/index.html:45-50
Double-Entry Ledger
Every financial operation in the payment rails is recorded in a double-entry ledger system, ensuring complete audit trails and preventing discrepancies.
// Ledger maintains balance integrity across all rails
// SHA-256 hash-chained for tamper evidence
Sources: site/index.html:15-17, CLAUDE.md:8
Environment Configuration
| Variable | Rail | Description |
|---|---|---|
STRIPE_SECRET_KEY | Stripe, StripeMPP | Stripe API key |
PAYSTACK_SECRET_KEY | Paystack | Paystack API key |
MNEMOPAY_PAYMENT_RAIL | All | stripe, paystack, or mock |
MNEMOPAY_COMMERCE_PROVIDER | Shopping | firecrawl, shopify, or mock |
Sources: claude-plugin/README.md:8-10
Integration Examples
Production Setup
import MnemoPay from "@mnemopay/sdk";
// Production configuration with full features
const agent = await MnemoPay.create({
agentId: "my-agent",
storage: sqliteAdapter,
rail: stripeRail
});
// Charge with automatic escrow
const tx = await agent.charge(49.00, "Pro plan, monthly");
await agent.settle(tx.id);
Quick Start (Dev Mode)
// Dev mode - zero infrastructure required
const agent = MnemoPay.quick("my-agent");
// All features work, defaults to mock/sandbox
// Swap to real rail with configuration
Sources: CLAUDE.md:20-35
CLI Commands
The Claude plugin provides payment management commands:
| Command | Description |
|---|---|
/mnemopay:charge <amount> <description> | Charge specified amount |
/mnemopay:balance | Check account balance |
/mnemopay:history <period> | View transaction history |
/mnemopay:settle | Settle pending transactions |
/mnemopay:fico | View agent credit score |
/mnemopay:remember <pref> | Store payment preferences |
/mnemopay:recall | Retrieve payment preferences |
Sources: claude-plugin/README.md:18-26
Testing
The payment rails have comprehensive test coverage:
- StripeRail tests: Payment flows, webhooks, refunds
- PaystackRail tests: Checkout, bank transfers, webhook verification
- LightningRail tests: Invoice creation, payment forwarding
- StripeMPPRail tests: 20 dedicated tests for MPP flow
Sources: CHANGELOG.md:31-32, CHANGELOG.md:29
See Also
- Agent Credit Score — Agent trust scoring (300-850)
- Double-Entry Ledger — Financial transaction tracking
- Shopping Module — Autonomous product discovery and purchase
- MCP Server — 24 tools for agent payment operations
Sources: README.md:1-25
Alpha Payment Rails (StripeMPP, x402, GoogleAP2)
Related topics: Payment Rails Overview, Stripe, Paystack & Lightning Rails
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Related Pages
Related topics: Payment Rails Overview, Stripe, Paystack & Lightning Rails
Alpha Payment Rails (StripeMPP, x402, GoogleAP2)
Overview
Alpha Payment Rails are experimental payment rail implementations introduced in MnemoPay SDK v1.6.0-alpha as part of the v1.6.x rail sprint. These rails provide alternative payment methods beyond the stable payment rails (Stripe, Paystack, Lightning) and enable crypto-native payment flows for AI agents.
| Rail | Technology | Status | Channel |
|---|---|---|---|
StripeMPPRail | Crypto deposits on Tempo via Stripe MPP | alpha | npm install @mnemopay/sdk@alpha |
X402Rail | USDC on Base via EIP-3009 transferWithAuthorization | alpha | npm install @mnemopay/sdk@alpha |
GoogleAP2Rail | AP2 v0.2 mandate-driven settlement (FIDO Alliance) | alpha | npm install @mnemopay/sdk@alpha |
Sources: README.md
StripeMPPRail
StripeMPPRail implements the Stripe Machine Payments Protocol (MPP), enabling agents to route payments as crypto deposits on the Tempo network through Stripe's MPP-enabled PaymentIntents API.
Key Features
- Crypto Payment Method: Uses
payment_method_types: ["crypto"]withcrypto.deposit_options.networks - Two-Phase Escrow: Implements
capture_method: "manual"for true escrow semantics - Deduplication: In-flight capture deduplication prevents double-settlement
- Idempotency: Full idempotency-key forwarding for safe retries
- Drop-in Swap: Same
PaymentRailinterface asStripeRailSources: CHANGELOG.md:19-36
API Configuration
import { StripeMPPRail } from "@mnemopay/sdk";
// Alpha preview (v1.6.0-alpha)
const mpp = new StripeMPPRail(process.env.STRIPE_SECRET_KEY!);
Implementation Details
- Pinned to Stripe API version:
2026-03-04.preview - Tagged with
@experimentaldecorator — preview API can change without semver guarantees - 20 dedicated tests in the test suite
- Includes
fromClient(client, opts?)factory for tests and shared Stripe client patterns
Sources: CHANGELOG.md:20-35
X402Rail
X402Rail implements the EIP-3009 transferWithAuthorization standard, enabling USDC payments on Base network with off-chain authorization and on-chain settlement.
Features
- EIP-3009 Compliance: Uses
transferWithAuthorizationfor delegated transfers - USDC Native: Direct USDC transfers on Base L2
- Bring Your Own Signer: Requires user-provided EIP-3009 signer implementation
Configuration
import { X402Rail } from "@mnemopay/sdk";
const x402 = new X402Rail({ signer: yourEip3009Signer });
Sources: README.md
GoogleAP2Rail
GoogleAP2Rail implements the FIDO Alliance's AP2 (Authorizing Payment 2.0) v0.2 specification, providing mandate-driven settlement with FIDO-based authentication.
Features
- AP2 v0.2: Implements FIDO Alliance payment authentication standard
- Mandate-Driven: Settlement occurs based on pre-authorized mandates
- FIDO Integration: Leverages FIDO authentication for payment authorization
Configuration
import { GoogleAP2Rail } from "@mnemopay/sdk";
const ap2 = new GoogleAP2Rail({ mandate, endpoint, signer });
Sources: README.md
Architecture
graph TD
A[MnemoPay Agent] --> B[PaymentRail Interface]
B --> C[Stable Rails]
B --> D[Alpha Rails]
C --> C1[StripeRail]
C --> C2[PaystackRail]
C --> C3[LightningRail]
D --> D1[StripeMPPRail]
D --> D2[X402Rail]
D --> D3[GoogleAP2Rail]
D1 --> D1A[Stripe MPP API<br/>2026-03-04.preview]
D1A --> D1B[Tempo Network<br/>Crypto Deposits]
D2 --> D2A[EIP-3009<br/>transferWithAuthorization]
D2A --> D2B[Base Network<br/>USDC]
D3 --> D3A[AP2 v0.2<br/>FIDO Alliance]
D3A --> D3B[Mandate-Driven<br/>Settlement]Payment Rail Comparison
| Feature | StripeRail | StripeMPPRail | X402Rail | GoogleAP2Rail |
|---|---|---|---|---|
| Currency | USD, EUR, GBP | Crypto (Tempo) | USDC | Multi-currency |
| Network | Stripe | Tempo | Base L2 | FIDO Network |
| Escrow | Manual capture | Manual capture | Authorization-based | Mandate-based |
| Auth Method | Stripe Auth | Stripe MPP | EIP-3009 Signer | FIDO Auth |
| Status | Stable | Alpha | Alpha | Alpha |
| API Version | Latest | 2026-03-04.preview | N/A | v0.2 |
Installation
Alpha rails are available under the alpha npm dist-tag:
npm install @mnemopay/sdk@alpha
The default latest dist-tag still points at 1.5.0 (stable). Opt in to alpha with the above command.
Sources: CHANGELOG.md:6-14
Usage Example
import {
PaystackRail, StripeRail, LightningRail, // stable
StripeMPPRail, X402Rail, GoogleAP2Rail, // alpha
} from "@mnemopay/sdk";
// Stable rails
const paystack = new PaystackRail(process.env.PAYSTACK_SECRET_KEY!);
const stripe = new StripeRail(process.env.STRIPE_SECRET_KEY!);
const lightning = new LightningRail(LND_URL, MACAROON);
// Alpha preview rails
const mpp = new StripeMPPRail(process.env.STRIPE_SECRET_KEY!);
const x402 = new X402Rail({ signer: yourEip3009Signer }); // bring-your-own crypto
const ap2 = new GoogleAP2Rail({ mandate, endpoint, signer });
Sources: README.md
Road to v1.6.0
The full 1.6.0 minor release will ship when the v1.6.x rail sprint completes, including:
- Stripe MPP native integration
- x402 native integration
- Google AP2 native integration
- Python rail port
Sources: CHANGELOG.md:14-17
Important Notes
Experimental Status
Alpha rails are tagged @experimental and subject to API changes:
"preview API can change without semver guarantees from Stripe; pin apiVersion in production"
For production deployments of StripeMPPRail, it is recommended to pin the apiVersion to prevent unexpected breaking changes.
Sources: CHANGELOG.md:34-35
Future Stable Release
When the v1.6.0 stable release ships, the latest npm tag will be updated to point to the version containing these rails as stable implementations.
Sources: README.md
Charter & FiscalGate Governance
Related topics: MerkleAudit & Hash-Chained Ledger, Identity & KYA Compliance, System Architecture
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Related Pages
Related topics: MerkleAudit & Hash-Chained Ledger, Identity & KYA Compliance, System Architecture
Charter & FiscalGate Governance
Overview
The Charter & FiscalGate Governance module is a first-class system within the MnemoPay SDK that provides budget enforcement, mission scoping, and regulatory audit capabilities for AI agents that handle financial operations. This governance layer ensures agents operate within defined constraints while maintaining transparent, verifiable audit trails.
┌──────────────────────────────────────────────────────────────────┐
│ GOVERNANCE LAYER │
├──────────────────────────────────────────────────────────────────┤
│ Charter · FiscalGate · Article 12 · MerkleAudit │
│ mission scope, budget enforcement, audit bundles │
└──────────────────────────────────────────────────────────────────┘
Sources: README.md
Purpose & Scope
The governance module addresses critical requirements for production AI agent deployments:
- Mission Scope Declaration — Defines what tools and operations an agent is authorized to perform
- Budget Enforcement — Reserves and limits financial resources before mission execution
- Audit Trail — Generates tamper-evident logs and regulator-ready documentation
- Compliance — Aligns with EU AI Act Article 12 requirements for high-risk AI systems
Sources: CHANGELOG.md
Architecture
System Components
graph TD
A[MnemoPay SDK] --> B[Governance Module]
B --> C[Charter]
B --> D[FiscalGate]
B --> E[MerkleAudit]
B --> F[Article12Bundle]
B --> G[PaymentsAdapter]
C --> H[Mission Declaration]
C --> I[Allowed Tools]
C --> J[Budget Cap]
D --> K[Budget Reservation]
D --> L[Agent Loop Execution]
D --> M[Spend Settlement]
E --> N[SHA-256 Chain]
E --> O[Event Replay]
E --> P[Tamper Detection]
F --> Q[mission.json]
F --> R[events.json]
F --> S[events.csv]
F --> T[chain.txt]
F --> U[manifest.json]Sources: CHANGELOG.md
Data Flow
sequenceDiagram
participant A as Agent
participant C as Charter
participant F as FiscalGate
participant M as MerkleAudit
participant P as Payments
participant R as Regulator
A->>C: Submit mission declaration
C->>C: validateCharter()
C-->>F: Validated charter
F->>M: Initialize audit chain
F->>P: Reserve budget (charter.budgetCap)
F->>A: Begin mission execution
loop Mission Operations
A->>F: Operation request
F->>M: Log event (sha256)
F->>P: Check budget remaining
P-->>F: Budget status
F-->>A: Approved/Rejected
end
alt Success
F->>P: Settle actual spend
F->>M: Finalize chain
F->>R: buildArticle12Bundle()
else Halt/Error
F->>P: Release reserved budget
F->>M: Log termination event
endCore Components
1. Charter
The Charter schema declares an agent mission's goal, authorized tools, and budget constraints.
interface Charter {
missionId: string;
goal: string;
allowedTools: string[];
budgetCap: number;
currency: string;
createdAt: Date;
}
#### Charter Validation
The validateCharter() function ensures mission declarations are well-formed and within acceptable parameters:
- Validates required fields are present
- Checks budget cap is a positive value
- Verifies allowed tools list is non-empty
- Ensures goal description is meaningful
Sources: src/governance/charter.ts
2. FiscalGate
The FiscalGate primitive (runMission()) is the core budget enforcement mechanism.
interface FiscalGateResult {
status: "ok" | "halted" | "error";
spentUsd: number;
outputs: any[];
auditDigest: string;
// ... additional fields
}
#### Execution Flow
graph TD
A[runMission ctx] --> B[Reserve full budget]
B --> C[Execute agent loop]
C --> D{All operations complete?}
D -->|Yes| E{Spent within budget?}
D -->|No| F[Log operation]
F --> C
E -->|Yes| G[Settle actual spend]
E -->|No| H[Release excess reservation]
G --> I[Return ok status]
H --> I
D -->|Halt signal| J[Release budget]
D -->|Error| K[Release budget]
J --> L[Return halted status]
K --> M[Return error status]#### Key Behaviors
| Scenario | Action | Result |
|---|---|---|
| Mission succeeds | Settle actual spend | status: "ok" |
| Mission halts early | Release reserved budget | status: "halted" |
| Error occurs | Release reserved budget | status: "error" |
| Overspend attempted | Block operation | Budget preserved |
Sources: CHANGELOG.md, src/governance/payments.ts
3. MerkleAudit
The MerkleAudit system provides a SHA-256 chained event log with verification capabilities.
interface MerkleAudit {
// Core methods
log(event: AuditEvent): void;
verify(): boolean;
toJSON(): AuditLog;
// Event subscription
on(event: string, callback: Function): void;
// Deterministic operations
replay(): AuditEvent[];
}
#### Chain Structure
graph LR
E1[Event 1] --> H1[Hash 1]
H1 --> E2[Event 2]
E2 --> H2[Hash 2]
H2 --> E3[Event 3]
E3 --> H3[Hash 3]
style H1 fill:#f96
style H2 fill:#f96
style H3 fill:#f96#### Verification Methods
| Method | Purpose |
|---|---|
verify() | Validates chain integrity |
toJSON() | Exports audit log for storage |
replay() | Reconstructs deterministic state |
Sources: CHANGELOG.md
4. Article 12 Bundle
The buildArticle12Bundle() function generates regulator-handable documentation for EU AI Act compliance.
interface Article12Bundle {
charter: Charter;
result: FiscalGateResult;
audit: MerkleAudit;
// Output files
mission: string; // mission.json
events: string; // events.json
eventsCsv: string; // events.csv
chain: string; // chain.txt
manifest: {
checksums: Record<string, string>;
retention: {
policy: string;
expiresAt: string;
};
};
}
#### Default Retention Policy
| Jurisdiction | Retention Period | Legal Basis |
|---|---|---|
| European Union | 6 months | EU AI Act Article 12 |
| Default | 6 months | EU AI Act Article 12 |
Sources: CHANGELOG.md, src/governance/article12.ts, src/governance/policies/eu-ai-act.ts
5. PaymentsAdapter
A pluggable interface for payment processing backends.
interface PaymentsAdapter {
charge(amount: number, currency: string): Promise<ChargeResult>;
settle(transactionId: string): Promise<SettleResult>;
refund(transactionId: string): Promise<RefundResult>;
getBalance(): Promise<Balance>;
}
class MockPayments implements PaymentsAdapter {
// Reference implementation for testing
}
#### Built-in Implementations
| Implementation | Use Case |
|---|---|
MockPayments | Unit testing, development |
StripePaymentsAdapter | Production (global) |
PaystackPaymentsAdapter | Production (Africa) |
LightningPaymentsAdapter | Production (micropayments) |
Sources: CHANGELOG.md, src/governance/payments.ts
API Reference
Functions
#### validateCharter(charter: Charter): ValidationResult
Validates a charter declaration before mission execution.
| Parameter | Type | Description |
|---|---|---|
charter | Charter | Mission charter to validate |
| Returns | ValidationResult | Contains valid: boolean and optional errors: string[] |
#### runMission(ctx: MissionContext): Promise<FiscalGateResult>
Executes an agent mission with budget enforcement.
interface MissionContext {
charter: Charter;
agentLoop: () => Promise<void>;
onOperation?: (op: Operation) => void;
}
interface FiscalGateResult {
status: "ok" | "halted" | "error";
spentUsd: number;
outputs: any[];
auditDigest: string;
terminatedAt?: Date;
error?: string;
}
#### buildArticle12Bundle(params: BundleParams): Article12Bundle
Generates a regulatory audit bundle.
| Parameter | Type | Description |
|---|---|---|
params.charter | Charter | Mission charter |
params.result | FiscalGateResult | Mission execution result |
params.audit | MerkleAudit | Audit log |
#### new MerkleAudit(options?: AuditOptions): MerkleAudit
Creates a new audit chain instance.
| Option | Type | Default | Description |
|---|---|---|---|
chainId | string | Auto-generated | Unique chain identifier |
events | AuditEvent[] | [] | Initial events |
retentionDays | number | 180 | Log retention period |
Sources: src/governance/charter.ts, src/governance/payments.ts, src/governance/article12.ts
EU AI Act Compliance
The governance module implements compliance measures for EU AI Act Article 12, which requires high-risk AI systems to maintain:
- Logging of operations — All agent actions recorded with timestamps
- Traceability — Individual operations attributable to specific events
- Transparency — Audit bundles provide human-readable documentation
- Retention — 6-month minimum log retention
// EU AI Act Article 12 compliance configuration
const euCompliance = {
article: "Article 12",
jurisdiction: "European Union",
retentionMonths: 6,
requirements: [
"operation_logging",
"event_traceability",
"human_oversight",
"audit_trail"
]
};
Sources: src/governance/policies/eu-ai-act.ts
Testing
The governance module includes comprehensive test coverage in tests/governance.spec.ts:
| Test Category | Coverage |
|---|---|
| Charter validation | Valid/invalid charter scenarios |
| MerkleAudit chain | Hash linking, tamper detection |
| FiscalGate paths | Happy path, halt, error scenarios |
| Article 12 bundle | File generation, checksum validation |
Sources: CHANGELOG.md
Usage Example
import {
Charter,
validateCharter,
runMission,
MerkleAudit,
buildArticle12Bundle,
MockPayments
} from "@mnemopay/sdk/governance";
// 1. Declare mission charter
const charter: Charter = {
missionId: "procurement-001",
goal: "Purchase office supplies under $500",
allowedTools: ["search", "compare", "buy"],
budgetCap: 500,
currency: "USD",
createdAt: new Date()
};
// 2. Validate charter
const validation = validateCharter(charter);
if (!validation.valid) {
throw new Error(`Invalid charter: ${validation.errors.join(", ")}`);
}
// 3. Create audit trail
const audit = new MerkleAudit({ retentionDays: 180 });
// 4. Execute mission with budget enforcement
const result = await runMission({
charter,
agentLoop: async () => {
// Agent operations here
}
});
// 5. Generate regulatory bundle
const bundle = buildArticle12Bundle({
charter,
result,
audit
});
Summary
The Charter & FiscalGate Governance system provides:
- Declarative mission scoping via Charter documents
- Automatic budget enforcement through FiscalGate
- Tamper-evident logging via MerkleAudit chains
- Regulatory compliance with EU AI Act Article 12 bundles
- Pluggable payments via PaymentsAdapter interface
This governance infrastructure ensures AI agents operate responsibly within financial constraints while maintaining the audit trails required for regulatory compliance and operational transparency.
Sources: README.md
MerkleAudit & Hash-Chained Ledger
Related topics: Charter & FiscalGate Governance, Core Modules Reference
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Related Pages
Related topics: Charter & FiscalGate Governance, Core Modules Reference
MerkleAudit & Hash-Chained Ledger
Overview
MerkleAudit and Hash-Chained Ledger form the cryptographic integrity backbone of the MnemoPay SDK. These two systems work together to provide verifiable, tamper-evident event logging and transaction recording for AI agents operating in financial workflows.
Purpose: The system ensures that every event and ledger entry can be independently verified, that modifications to historical data are immediately detectable, and that audit trails meet regulatory requirements such as EU AI Act Article 12.
Key Characteristics:
- SHA-256 cryptographic chaining for sequential integrity
- Merkle tree verification for memory integrity
- Deterministic replay for audit verification
- Listener subscriptions for real-time monitoring
- Three independent tamper-detection layers
Sources: CHANGELOG.md
Architecture
The integrity system consists of three independent layers working in concert:
graph TD
A[Tamper Detection Layers] --> B[Hash-Chained Ledger]
A --> C[Merkle Integrity on Memories]
A --> D[HMAC on Transactions]
B --> E[SHA-256 Sequential Linking]
C --> F[Merkle Tree Verification]
D --> G[HMAC-SHA512 Security]Layer 1: Hash-Chained Ledger
The ledger maintains a double-entry accounting system where every entry links to the previous entry via SHA-256 hash. If any entry is modified, the chain breaks instantly, making tampering immediately detectable.
Sources: site/index.html
Layer 2: Merkle Integrity on Memories
The MerkleAudit system provides Merkle tree-based verification for agent memories, ensuring that stored memory states can be cryptographically verified.
Layer 3: HMAC on Transactions
Transaction-level HMAC-SHA512 security provides an additional verification layer for financial operations.
MerkleAudit System
Core Components
| Component | Purpose |
|---|---|
audit-chain.ts | SHA-256 chained event log implementation |
audit.ts | Core audit primitives and verification |
verify() | Chain integrity verification method |
toJSON() | Serialization for audit export |
| Listeners | Real-time event subscription system |
| Deterministic Replay | Reproducible audit reconstruction |
Sources: CHANGELOG.md
Event Log Structure
The MerkleAudit system maintains a sequentially chained event log where each event contains:
graph LR
A[Event N] --> B[SHA-256 Hash of Event N]
B --> C[Links to Event N-1 Hash]
C --> D[Event N-1]
D --> E[SHA-256 Hash of Event N-1]
E --> F[Links to Event N-2 Hash]Verification Process
The verify() method performs chain integrity checks by:
- Computing the hash of each event in sequence
- Comparing computed hashes against stored hashes
- Validating chain link integrity between consecutive events
- Reporting any detected breaks or inconsistencies
Listener Subscriptions
The system supports listener subscriptions for real-time monitoring:
- Events can trigger registered callbacks as they are appended
- Listeners receive the full event context upon notification
- Supports multiple concurrent subscribers
Deterministic Replay
The deterministic replay feature enables:
- Complete reconstruction of audit state from the chain
- Reproducible verification of past states
- Compliance with regulatory audit requirements
Hash-Chained Ledger
Double-Entry Accounting
The ledger implements true double-entry bookkeeping where every transaction affects at least two accounts:
graph TD
A[Transaction] --> B[Debit Entry]
A --> C[Credit Entry]
B --> D[Account A Balance]
C --> E[Account B Balance]
D --> F[Ledger Balanced ✓]
E --> FChain Integrity Mechanism
| Feature | Description |
|---|---|
| Hash Algorithm | SHA-256 |
| Chain Structure | Each entry references previous entry's hash |
| Detection | Any modification breaks the chain instantly |
| Verification | Sequential hash recomputation and comparison |
Sources: site/index.html
Transaction Flow
sequenceDiagram
participant Agent
participant Ledger
participant Escrow
participant Verification
Agent->>Ledger: Initiate Transaction
Ledger->>Verification: Compute Previous Hash
Verification->>Ledger: Hash Verified
Ledger->>Ledger: Append with Chain Link
Ledger->>Escrow: Hold Funds
Escrow->>Agent: Escrow ConfirmedAPI Reference
MerkleAudit Core Methods
#### verify()
Verifies the complete chain integrity.
| Parameter | Type | Description |
|---|---|---|
startIndex | number | Optional starting point for verification |
endIndex | number | Optional ending point for verification |
#### toJSON()
Serializes the audit chain to JSON format for export and storage.
| Parameter | Type | Description |
|---|---|---|
compact | boolean | Optional compact representation |
Ledger Methods
#### Transaction Operations
| Method | Purpose |
|---|---|
charge() | Initiate a charge with escrow hold |
settle() | Release escrowed funds |
refund() | Process a refund transaction |
dispute() | Open a dispute on a transaction |
Sources: site/index.legacy.html
Test Coverage
The governance module includes comprehensive test coverage:
- 11 governance tests in
tests/governance.spec.ts - Charter validation tests
- MerkleAudit chain and tamper detection tests
- FiscalGate happy path, halt, and error path tests
- Article 12 bundle generation tests
Sources: CHANGELOG.md
Test Categories
| Category | Coverage |
|---|---|
| Chain Integrity | Verification of unbroken hash chain |
| Tamper Detection | Detection of modified entries |
| Replay Accuracy | Deterministic replay verification |
| Listener Events | Real-time notification testing |
Integration with Governance Module
MerkleAudit integrates deeply with the Governance module:
Article 12 Compliance
The system supports EU AI Act Article 12 audit requirements:
- 6-month default retention period
- Deterministic SHA-256 digest for tamper detection
- Compliance bundle generation via
buildArticle12Bundle()
Audit Bundle Structure
When generating Article 12 compliance bundles:
graph TD
A[buildArticle12Bundle] --> B[mission.json]
A --> C[events.json]
A --> C2[events.csv]
A --> D[chain.txt]
A --> E[manifest.json]
E --> F[Checksums]
E --> G[Retention Metadata]FiscalGate Integration
The runMission(ctx) function uses the audit chain for mission execution:
- Reserves full charter budget up-front
- Runs the agent loop with ledger recording
- Settles actual spend on success
- Releases reserved funds on halt/error
- Returns audit digest for verification
Security Properties
Tamper Detection
| Attack Vector | Detection Mechanism |
|---|---|
| Single Entry Modification | SHA-256 hash mismatch |
| Chain Reordering | Sequential link validation |
| Entry Deletion | Hash chain break detection |
| Memory Manipulation | Merkle tree verification |
Cryptographic Guarantees
- Pre-image Resistance: Cannot derive previous entries from current hash
- Collision Resistance: Cannot find two events with same hash
- Chain Binding: Each entry cryptographically bound to all predecessors
Best Practices
Audit Trail Maintenance
- Regular Verification: Periodically run
verify()on the audit chain - Backup Chain State: Export via
toJSON()for disaster recovery - Monitor Listeners: Implement listeners to track chain modifications
- Retention Compliance: Configure appropriate retention periods for regulatory needs
Ledger Operations
- Always Verify Before Settlement: Check chain integrity before fund release
- Use Escrow: Hold funds until human approval for autonomous transactions
- Monitor Disputes: Track dispute patterns for fraud detection
- Maintain Credit Score: Higher scores yield lower transaction fees
Conclusion
MerkleAudit and the Hash-Chained Ledger provide the cryptographic foundation for trustworthy AI agent financial operations. With SHA-256 chaining, Merkle tree verification, and HMAC transaction security, the system ensures that every event and transaction is verifiable, tamper-evident, and compliant with regulatory requirements.
Sources: site/index.html
Sources: CHANGELOG.md
Identity & KYA Compliance
Related topics: Charter & FiscalGate Governance
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Related Pages
Related topics: Charter & FiscalGate Governance
Identity & KYA Compliance
Overview
Identity & KYA (Know Your Agent) Compliance is a core pillar of the MnemoPay SDK architecture, providing identity management, permission controls, and compliance verification for AI agents that handle financial transactions.
The Identity subsystem enables autonomous agents to establish verified digital identities, manage session authentication, control access permissions, and maintain compliance with regulatory requirements through a multi-layered approach.
Sources: README.md:1-50
Architecture
graph TD
subgraph Identity & KYA Compliance
DID[Decentralized ID]
SES[Session Management]
PERM[Permissions]
KILL[Killswitch]
TOKEN[Token Economy]
BRAIN[Memory Brain]
end
subgraph Agent Operations
CHARGE[charge()]
SETTLE[settle()]
REFUND[refund()]
end
DID --> SES
SES --> PERM
PERM --> KILL
SES --> TOKEN
DID --> BRAIN
PERM --> CHARGE
PERM --> SETTLE
PERM --> REFUNDCore Components
Session Management
The Session Panel provides authenticated session handling for agent identities. It integrates with the dashboard's operator console to manage sign-in and sign-out operations for agent accounts.
| Component | Description |
|---|---|
session.session?.accountId | Unique account identifier for the authenticated agent |
session.session?.email | Associated email for the session |
session.authenticated | Boolean flag indicating authentication status |
onLogin | Callback function for session authentication |
onLogout | Callback function for session termination |
Sources: dashboard/index.html:200-230
#### Session State Display
The dashboard conditionally renders session status based on authentication state:
{session?.authenticated ? (
<div className="text-right">
<div className="text-xs text-gray-500 uppercase tracking-wider">Signed in as</div>
<div className="text-sm font-mono text-white">{sanitize(session.session?.email || '—')}</div>
<div className="text-[10px] text-gray-500 font-mono">account: {sanitize(session.session?.accountId || accountId)}</div>
</div>
) : (
<div className="text-right">
<div className="text-xs text-amber-400 uppercase tracking-wider">Not signed in</div>
<div className="text-[10px] text-gray-500 font-mono">account: {sanitize(accountId)} (anonymous)</div>
</div>
)}
Sources: dashboard/index.html:150-170
Permission Controls
The permission system gates critical financial operations. Agents must have appropriate permissions before executing charge(), settle(), or refund() operations.
| Permission Type | Purpose |
|---|---|
| Charge Permission | Allows agent to initiate payment collection |
| Settle Permission | Allows agent to release escrowed funds |
| Refund Permission | Allows agent to process refunds |
| Admin Permission | Allows management of API keys and billing |
Killswitch
The killswitch mechanism provides emergency shutdown capability for agent operations. When triggered, it immediately revokes all active permissions and halts pending transactions.
graph LR
A[Anomaly Detected] --> B{Killswitch Active?}
B -->|Yes| C[Revoke All Permissions]
B -->|No| D[Log Warning]
C --> E[Cancel Pending Transactions]
E --> F[Notify Compliance System]Token Economy
The Identity module integrates with MnemoPay's token-based economy:
| Parameter | Value | Description |
|---|---|---|
| Ceiling | 500 × reputation | Maximum charge per transaction |
| Decay | 0.05 | Half-life approximately 14 hours |
| Feedback Loop | +0.05 | Importance reinforcement on settle |
Sources: dashboard/index.html:350-360
Compliance Workflow
graph TD
A[Agent Initialization] --> B[Create Session]
B --> C{KYA Verification}
C -->|Pass| D[Assign Permissions]
C -->|Fail| E[Restricted Mode]
D --> F[Enable Financial Ops]
E --> G[Monitor & Retry]
G --> C
F --> H[Log to Audit Trail]
H --> I[Periodic Compliance Check]
I -->|Compliant| F
I -->|Violation| J[Killswitch Triggered]Dashboard Integration
The Identity & KYA Compliance features are accessible through the MnemoPay Console dashboard via the Session tab:
{tab === 'session' && <SessionPanel
session={session}
accountId={accountId}
members={overview?.members || []}
onLogin={loginSession}
onLogout={logoutSession}
onRefresh={fetchAll}
/>}
Sources: dashboard/index.html:400-410
Available Controls
| Control | Function |
|---|---|
| Account ID Input | Specify target account for session operations |
| Refresh Button | Fetch latest session and compliance status |
| Login | Authenticate and establish session |
| Logout | Terminate session and clear credentials |
| Members List | View team members with identity status |
Developer API Keys
The Developer Panel manages API keys that authenticate agent-to-platform communications:
| Feature | Description |
|---|---|
| List Keys | View all active API keys for the account |
| Create Key | Generate new provisioning secret |
| Revoke Key | Immediately invalidate an existing key |
Sources: dashboard/index.html:280-310
Security Considerations
Authentication Flow
- Agent requests session with valid credentials
- System verifies KYA compliance status
- On success, session token is issued with scoped permissions
- All subsequent API calls include session token
- Session expires after configured TTL or manual logout
Anomaly Detection
The compliance system monitors agent behavior patterns:
- Unusual transaction volumes
- Unexpected geographic access patterns
- Rapid permission escalation attempts
- Deviations from established operational baselines
Sources: README.md:1-30
Billing & Compliance Metrics
The Billing Panel displays compliance-related metrics:
| Metric | Description |
|---|---|
| Missions | Current period transaction count |
| Seats | Active agent identities under management |
| Plan Gate | Compliance status (Active/Limit Reached) |
| Over Limit | Boolean indicating if usage exceeds plan |
Sources: dashboard/index.html:320-340
Related Documentation
- Agent Credit Score — Agent scoring for compliance gating
- Behavioral Finance — Prospect theory and nudge mechanisms
- Anomaly Detection — EWMA and fingerprinting systems
- Audit Trail — Ledger health and compliance logging
Sources: README.md:1-50
Doramagic Pitfall Log
Source-linked risks stay visible on the manual page so the preview does not read like a recommendation.
The project may affect permissions, credentials, data exposure, or host boundaries.
The project should not be treated as fully validated until this signal is reviewed.
The project should not be treated as fully validated until this signal is reviewed.
Users cannot judge support quality until recent activity, releases, and issue response are checked.
Doramagic Pitfall Log
Doramagic extracted 8 source-linked risk signals. Review them before installing or handing real data to the project.
1. Security or permission risk: Security or permission risk needs validation
- Severity: high
- Finding: Security or permission risk is backed by a source signal: Security or permission risk needs validation. Treat it as a review item until the current version is checked.
- User impact: The project may affect permissions, credentials, data exposure, or host boundaries.
- Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
- Evidence: packet_text.keyword_scan | github_repo:1197975871 | https://github.com/mnemopay/mnemopay-sdk | matched secret / private key / privacy / trading / finance keyword
2. Project risk: Project risk needs validation
- Severity: medium
- Finding: Project risk is backed by a source signal: Project risk needs validation. Treat it as a review item until the current version is checked.
- User impact: The project should not be treated as fully validated until this signal is reviewed.
- Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
- Evidence: identity.distribution | github_repo:1197975871 | https://github.com/mnemopay/mnemopay-sdk | repo=mnemopay-sdk; install=@mnemopay/sdk
3. Capability assumption: README/documentation is current enough for a first validation pass.
- Severity: medium
- Finding: README/documentation is current enough for a first validation pass.
- User impact: The project should not be treated as fully validated until this signal is reviewed.
- Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
- Evidence: capability.assumptions | github_repo:1197975871 | https://github.com/mnemopay/mnemopay-sdk | README/documentation is current enough for a first validation pass.
4. Maintenance risk: Maintainer activity is unknown
- Severity: medium
- Finding: Maintenance risk is backed by a source signal: Maintainer activity is unknown. Treat it as a review item until the current version is checked.
- User impact: Users cannot judge support quality until recent activity, releases, and issue response are checked.
- Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
- Evidence: evidence.maintainer_signals | github_repo:1197975871 | https://github.com/mnemopay/mnemopay-sdk | last_activity_observed missing
5. Security or permission risk: no_demo
- Severity: medium
- Finding: no_demo
- User impact: The project may affect permissions, credentials, data exposure, or host boundaries.
- Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
- Evidence: downstream_validation.risk_items | github_repo:1197975871 | https://github.com/mnemopay/mnemopay-sdk | no_demo; severity=medium
6. Security or permission risk: no_demo
- Severity: medium
- Finding: no_demo
- User impact: The project may affect permissions, credentials, data exposure, or host boundaries.
- Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
- Evidence: risks.scoring_risks | github_repo:1197975871 | https://github.com/mnemopay/mnemopay-sdk | no_demo; severity=medium
7. Maintenance risk: issue_or_pr_quality=unknown
- Severity: low
- Finding: issue_or_pr_quality=unknown。
- User impact: Users cannot judge support quality until recent activity, releases, and issue response are checked.
- Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
- Evidence: evidence.maintainer_signals | github_repo:1197975871 | https://github.com/mnemopay/mnemopay-sdk | issue_or_pr_quality=unknown
8. Maintenance risk: release_recency=unknown
- Severity: low
- Finding: release_recency=unknown。
- User impact: Users cannot judge support quality until recent activity, releases, and issue response are checked.
- Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
- Evidence: evidence.maintainer_signals | github_repo:1197975871 | https://github.com/mnemopay/mnemopay-sdk | release_recency=unknown
Source: Doramagic discovery, validation, and Project Pack records
Community Discussion Evidence
These external discussion links are review inputs, not standalone proof that the project is production-ready.
Count of project-level external discussion links exposed on this manual page.
Open the linked issues or discussions before treating the pack as ready for your environment.
Community Discussion Evidence
Doramagic exposes project-level community discussion separately from official documentation. Review these links before using mnemopay-sdk with real data or production workflows.
- v0.9.0 — Autonomous Commerce + Universal Client - github / github_release
- Security or permission risk needs validation - GitHub / issue
Source: Project Pack community evidence and pitfall evidence