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

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Module Overview

Continue reading this section for the full explanation and source context.

Section Dev Mode (Zero Infrastructure)

Continue reading this section for the full explanation and source context.

Section Production Mode (Full Backend)

Continue reading this section for the full explanation and source context.

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 --> P

Sources: CLAUDE.md

Module Overview

ModulePurpose
index.tsMain SDK exports: MnemoPay, MnemoPayLite, MnemoPayNetwork classes
fico.tsAgent Credit Score (300-850); exports AgentCreditScore with legacy AgentFICO alias
behavioral.tsBehavioral finance engine implementing prospect theory and cooling-off mechanisms
integrity.tsMerkle tree memory integrity using SHA-256 hashing
anomaly.tsEWMA anomaly detection, BehaviorMonitor, and CanarySystem
adaptive.tsAdaptive AIMD rate limiting, anti-gaming protections, circuit breaker, PSI drift detection
commerce.tsCommerceEngine enabling autonomous shopping with financial mandates
fraud.tsGeo-enhanced fraud detection with location-based risk scoring
identity.tsIdentityRegistry, KYA verification, CapabilityTokens, and killswitch permissions
ledger.tsDouble-entry accounting ledger for precise transaction tracking
network.tsMulti-agent commerce network coordination
client.tsREST API client for backend communication
mcp/server.tsMCP 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

OperationDescription
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 --> K

LongMemEval 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:

RailRegionCurrenciesFeatures
PaystackAfricaNGN, GHS, ZAR, KESCheckout, saved cards, bank transfers, webhook verification, HMAC-SHA512
StripeGlobalUSD, EUR, GBP, 135+Card payments, manual capture, true escrow via PaymentIntents
LightningCryptoBTCInstant 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

ComponentWeightDescription
Payment History35%Historical transaction success rate
Utilization30%Credit usage patterns
Behavioral Signals20%Prospect theory analysis, cooling-off adherence
Anomaly Score10%EWMA deviation from baseline behavior
Identity Verification5%KYA completion level

Score Ranges

Score RangeRatingDescription
750-850ExcellentHigh-trust agent, minimal monitoring
650-749GoodStandard transaction limits
550-649FairEnhanced monitoring, lower limits
300-549PoorRestricted 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

PermissionDescription
payment.chargeInitiate charges
payment.refundProcess refunds
memory.writeStore memories
memory.readAccess memories
identity.delegateIssue sub-tokens
killswitchEmergency 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:

ComponentPurpose
CharterMission scope and operating principles
FiscalGateBudget enforcement and spending limits
Article 12Audit bundle requirements
MerkleAuditCryptographic 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

MethodDescription
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

VersionStatusKey Features
1.6.0AlphaLatest pre-release with hardening fixes
1.5.0StableGovernance fold, FiscalGate, MerkleAudit
1.4.0Past77.2% LongMemEval, 1M-op stress test
1.0.0PythonPython 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

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Payment Operations

Continue reading this section for the full explanation and source context.

Section Memory Operations

Continue reading this section for the full explanation and source context.

Section OpenAI Integration

Continue reading this section for the full explanation and source context.

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

RequirementVersion/Details
Node.jsv18+ recommended
npm/yarn/pnpmAny modern package manager
API KeyRequired for production use
EnvironmentNode.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] --> C

Sources: site/index.html:25-45

Core Operations

Payment Operations

MethodDescription
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

MethodDescription
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:

VariableDescriptionRequired
MNEMO_API_KEYYour MnemoPay API keyYes
STRIPE_KEYStripe secret keyFor Stripe payments
PAYSTACK_KEYPaystack secret keyFor Paystack payments
LIGHTNING_CONFIGLightning node configFor 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:

RailRegionFeatures
PaystackAfrica (NGN, GHS, ZAR, KES)Checkout, saved cards, bank transfers, HMAC-SHA512 security
StripeGlobal (USD, EUR, GBP)Card payments, manual capture for escrow, 135+ currencies
LightningCryptoInstant 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

ResourcePurpose
Full DocumentationComplete API reference
PricingStarter/Pro/Enterprise plans
EnterpriseCustom integrations and support

Sources: README.md:1-15

System Architecture

Related topics: Core Modules Reference, Payment Rails Overview, Charter & FiscalGate Governance

Section Related Pages

Continue reading this section for the full explanation and source context.

Section SDK Client Architecture

Continue reading this section for the full explanation and source context.

Section Payment Rail System

Continue reading this section for the full explanation and source context.

Section Identity and Access Control

Continue reading this section for the full explanation and source context.

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 --> ANOMALY

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

ComponentPurposeLanguage Support
Core SDKClient initialization, API abstractionTypeScript, Python
Payment RailsTransaction processingTypeScript, Python
MCP ServerModel Context Protocol integrationTypeScript
MiddlewareFramework integrationsTypeScript

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:#fff

Supported Payment Rails:

RailRegionCurrenciesFeatures
StripeGlobalUSD, EUR, GBP, 135+Manual capture for true escrow, PaymentIntents API
PaystackAfricaNGN, GHS, ZAR, KESCheckout, saved cards, bank transfers, webhook verification, HMAC-SHA512 security, 23 Nigerian banks pre-mapped
LightningCryptoBTCInstant settlement via Lightning Network
MockTestingAllTest 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 ComponentDescriptionImpact
Payment HistoryHistorical transaction success ratePrimary factor
Transaction VolumeTotal and average transaction sizesSecondary factor
Dispute RateRatio of disputed to total transactionsNegative impact
Response TimeSpeed of human approval responsesModerate impact
Behavioral PatternsAnomaly detection signalsRisk 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:

TierComponentsPurpose
Tier 1Production blockersCore functionality protection
Tier 2ObservabilityMonitoring and metrics
Tier 3Safety netsRate 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

IntegrationPackage PathPurpose
OpenAI@mnemopay/sdk/middleware/openaiOpenAI agent transaction middleware
Anthropic@mnemopay/sdk/middleware/anthropicAnthropic Claude agent middleware
LangGraph@mnemopay/sdk/langgraphLangGraph 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 --> STATE

Dashboard Tabs and Functions:

TabIconFunction
ConsoleSystem monitorOverview of transactions and account status
SessionUsersLogin/logout session management
BrainBrain iconMemory recall and query interface
DeveloperCode bracketsAPI key management
BillingCredit cardUsage metering and plan limits
MemoriesDatabaseMemory 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 MethodFunction
EWMAStatistical anomaly detection on transaction amounts and frequencies
FingerprintingBehavioral 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

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Memory Operations

Continue reading this section for the full explanation and source context.

Section Search Modes

Continue reading this section for the full explanation and source context.

Section Memory Structure

Continue reading this section for the full explanation and source context.

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 --> N

Sources: 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

OperationPurposeParameters
remember(content, namespace?, tags?, importance?)Store a memory with optional importance score and tagsContent string, namespace ID, tag array, importance 0-1
recall(query, namespace?, limit?, mode?)Retrieve relevant memories via semantic searchQuery 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 IDMemory ID
consolidate(namespace?)Prune stale memories below decay thresholdOptional 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:

FieldTypeDescription
idstringUnique memory identifier
contentstringThe memory content
namespacestringLogical partition for memory spaces
tagsstring[]Categorization tags
importancenumber0-1 importance score for retrieval weighting
createdAtDateCreation timestamp
updatedAtDateLast modification timestamp
accessCountnumberNumber 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

TypeDescriptionLedger Impact
chargeCreates escrow hold for delivered workDebit: Receivable, Credit: Escrow
settleFinalizes charge, moves funds to walletDebit: Escrow, Credit: Revenue
refundReverses a transactionDebit: Escrow, Credit: Receivable
disputeUser-initiated chargebackTriggers 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 Dispute

Sources: src/ledger.ts

Identity Module (`src/identity/`)

The identity system manages agent identification, capabilities, and permissions through a multi-layered approach.

Components

ComponentPurpose
IdentityRegistryCentral registry mapping agent IDs to identities
KYA (Know Your Agent)Onboarding verification for new agents
CapabilityTokensTime-limited permission grants
killswitchEmergency 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:

ComponentWeightDescription
Payment History35%Track record of successful settlements
Utilization30%Current escrow exposure relative to limits
Account Age15%Duration of active account
Diversity10%Range of transaction types and rails used
Reputation10%Social/professional reputation signals

Score Ranges

RangeClassificationDescription
800-850ExceptionalHighly reliable, lowest risk
740-799Very GoodReliable with minimal risk
670-739GoodAcceptable risk level
580-669FairElevated risk, monitor closely
300-579PoorHigh 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

FactorDescriptionThreshold
geoVelocityRapid location changes impossible for user>500km/hour
velocityVolumeUnusual transaction frequency>10 tx/hour
amountAnomalyStatistical outlier in transaction size>3σ from mean
patternDeviationDeviation from established behavioral patternsSimilarity <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

ComponentPurpose
EWMACore statistical monitoring with exponential weighting
BehaviorMonitorTracks behavioral baselines per agent
CanarySystemSynthetic 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

FeatureDescription
Prospect TheoryLoss aversion calculations (losses weighted 2x gains)
Cooling-Off PeriodsMandatory waiting periods for high-value transactions
NudgesBehavioral prompts to encourage positive outcomes

Cooling-Off Rules

High-value transactions (>100 USD equivalent) trigger mandatory review periods:

Amount RangeCooling Period
$100-$50024 hours
$500-$100072 hours
>$10007 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

FeatureDescription
MerkleAuditGenerates proof bundles for external verification
Chain VerificationValidates no memories were tampered with
TimestampingProvides 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

ComponentPurpose
AIMDAdditive Increase, Multiplicative Decrease rate control
Anti-GamingDetection of rate limit exploitation patterns
CircuitBreakerPrevents cascade failures
PSI DriftPopulation 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: Failure

Sources: 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)

ToolDescription
mcp__mnemopay__rememberStore a memory with optional importance and tags
mcp__mnemopay__recallRetrieve relevant memories via semantic search
mcp__mnemopay__forgetPermanently delete a memory
mcp__mnemopay__reinforceBoost memory importance
mcp__mnemopay__consolidatePrune stale memories

#### Payment Tools (4)

ToolDescription
mcp__mnemopay__chargeCreate escrow charge (max $500 × reputation)
mcp__mnemopay__settleFinalize pending charge
mcp__mnemopay__refundProcess refund
mcp__mnemopay__disputeFile 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

RailRegionCurrenciesFeatures
StripeGlobalUSD, EUR, GBP, 135+PaymentIntents, Manual Capture, Webhooks
PaystackAfricaNGN, GHS, ZAR, KESCheckout, Saved Cards, Bank Transfer, HMAC-SHA512
LightningCryptoBTCInstant 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
    end

Sources: src/index.ts

Main SDK Entry (`src/index.ts`)

The main index exports three SDK variants optimized for different use cases.

SDK Variants

VariantSizeUse Case
MnemoPay~74KBFull-featured production use
MnemoPayLite<20KBBrowser, edge functions, constrained environments
MnemoPayNetwork+~15KBMulti-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

ModeDescriptionInfrastructure Required
quick(agentId)Dev mode with mock servicesNone
init(config)Production mode with real servicesAPI keys, secrets
network(config)Multi-agent network modeNetwork 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

ParameterTypeDescription
agentIdstringUnique agent identifier
apiKeystringAPI authentication key
networkIdstringNetwork/tenant identifier

Optional Configuration

ParameterDefaultDescription
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:

ModuleTest Focus
MemoryCRUD operations, search accuracy, consolidation
LedgerDouble-entry balance, transaction states
IdentityKYA flow, capability tokens, killswitch
FraudGeo-velocity, pattern matching, thresholds
AnomalyEWMA calculation, alert thresholds
RailsPayment 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

Section Related Pages

Continue reading this section for the full explanation and source context.

Section StripeRail

Continue reading this section for the full explanation and source context.

Section PaystackRail

Continue reading this section for the full explanation and source context.

Section LightningRail

Continue reading this section for the full explanation and source context.

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:

ClassificationRailsUse CaseStatus
StableStripeRail, PaystackRail, LightningRailProduction deploymentslatest
Preview (Alpha)StripeMPPRail, X402Rail, GoogleAP2RailEvaluation and testingalpha

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:

OperationDescription
ChargeInitiate a payment from the customer's payment method
EscrowHold funds in a secure state pending verification or delivery
SettleRelease escrowed funds to the merchant/recipient
RefundReturn 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 VariablePurpose
STRIPE_SECRET_KEYStripe payments API key
PAYSTACK_SECRET_KEYPaystack payments API key
MNEMOPAY_PAYMENT_RAILActive rail: stripe, paystack, or mock
MNEMOPAY_COMMERCE_PROVIDERCommerce 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

BenefitDescription
Provider AbstractionSingle API interface for multiple payment providers
Rail SwitchingChange payment providers without code modifications
Hybrid RailsCombine multiple rails in a single agent configuration
Consistent Error HandlingUnified error responses across all providers
Audit TrailEvery operation logged in the hash-chained ledger

Choosing a Payment Rail

ScenarioRecommended Rail
Global card paymentsStripeRail
African markets (NGN, GHS, ZAR, KES)PaystackRail
BTC micropaymentsLightningRail
Crypto deposits settlementStripeMPPRail
On-chain USDC payments (Base)X402Rail
FIDO-aligned settlementGoogleAP2Rail

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)

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Unified PaymentRail Interface

Continue reading this section for the full explanation and source context.

Section Rail Selection Matrix

Continue reading this section for the full explanation and source context.

Section StripeRail

Continue reading this section for the full explanation and source context.

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

RailCoverageChannelStatusCurrencies
StripeRailGlobalstable (latest)StableUSD, EUR, GBP, +
PaystackRailAfricastable (latest)StableNGN, GHS, ZAR, KES
LightningRailBTC micropaymentsstable (latest)StableBTC
StripeMPPRailCrypto via Tempopreview (alpha)AlphaCrypto deposits
X402RailUSDC on Basepreview (alpha)AlphaUSDC
GoogleAP2RailAP2 v0.2 mandatepreview (alpha)AlphaMultiple

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.completed
  • customer.subscription.updated
  • customer.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 X402Signer interface
  • Zero crypto dependencies in SDK
  • EIP-3009 transferWithAuthorization standard
  • 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:

  1. Charge Phase — Funds are authorized and held in escrow
  2. Settlement Phase — Funds are captured and transferred
  3. 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

VariableRailDescription
STRIPE_SECRET_KEYStripe, StripeMPPStripe API key
PAYSTACK_SECRET_KEYPaystackPaystack API key
MNEMOPAY_PAYMENT_RAILAllstripe, paystack, or mock
MNEMOPAY_COMMERCE_PROVIDERShoppingfirecrawl, 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:

CommandDescription
/mnemopay:charge <amount> <description>Charge specified amount
/mnemopay:balanceCheck account balance
/mnemopay:history <period>View transaction history
/mnemopay:settleSettle pending transactions
/mnemopay:ficoView agent credit score
/mnemopay:remember <pref>Store payment preferences
/mnemopay:recallRetrieve 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

Sources: README.md:1-25

Alpha Payment Rails (StripeMPP, x402, GoogleAP2)

Related topics: Payment Rails Overview, Stripe, Paystack & Lightning Rails

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Key Features

Continue reading this section for the full explanation and source context.

Section API Configuration

Continue reading this section for the full explanation and source context.

Section Implementation Details

Continue reading this section for the full explanation and source context.

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.

RailTechnologyStatusChannel
StripeMPPRailCrypto deposits on Tempo via Stripe MPPalphanpm install @mnemopay/sdk@alpha
X402RailUSDC on Base via EIP-3009 transferWithAuthorizationalphanpm install @mnemopay/sdk@alpha
GoogleAP2RailAP2 v0.2 mandate-driven settlement (FIDO Alliance)alphanpm 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"] with crypto.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 PaymentRail interface as StripeRail Sources: 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 @experimental decorator — 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 transferWithAuthorization for 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

FeatureStripeRailStripeMPPRailX402RailGoogleAP2Rail
CurrencyUSD, EUR, GBPCrypto (Tempo)USDCMulti-currency
NetworkStripeTempoBase L2FIDO Network
EscrowManual captureManual captureAuthorization-basedMandate-based
Auth MethodStripe AuthStripe MPPEIP-3009 SignerFIDO Auth
StatusStableAlphaAlphaAlpha
API VersionLatest2026-03-04.previewN/Av0.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

Section Related Pages

Continue reading this section for the full explanation and source context.

Section System Components

Continue reading this section for the full explanation and source context.

Section Data Flow

Continue reading this section for the full explanation and source context.

Section 1. Charter

Continue reading this section for the full explanation and source context.

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:

  1. Mission Scope Declaration — Defines what tools and operations an agent is authorized to perform
  2. Budget Enforcement — Reserves and limits financial resources before mission execution
  3. Audit Trail — Generates tamper-evident logs and regulator-ready documentation
  4. 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
    end

Core 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

ScenarioActionResult
Mission succeedsSettle actual spendstatus: "ok"
Mission halts earlyRelease reserved budgetstatus: "halted"
Error occursRelease reserved budgetstatus: "error"
Overspend attemptedBlock operationBudget 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

MethodPurpose
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

JurisdictionRetention PeriodLegal Basis
European Union6 monthsEU AI Act Article 12
Default6 monthsEU 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

ImplementationUse Case
MockPaymentsUnit testing, development
StripePaymentsAdapterProduction (global)
PaystackPaymentsAdapterProduction (Africa)
LightningPaymentsAdapterProduction (micropayments)

Sources: CHANGELOG.md, src/governance/payments.ts

API Reference

Functions

#### validateCharter(charter: Charter): ValidationResult

Validates a charter declaration before mission execution.

ParameterTypeDescription
charterCharterMission charter to validate
ReturnsValidationResultContains 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.

ParameterTypeDescription
params.charterCharterMission charter
params.resultFiscalGateResultMission execution result
params.auditMerkleAuditAudit log

#### new MerkleAudit(options?: AuditOptions): MerkleAudit

Creates a new audit chain instance.

OptionTypeDefaultDescription
chainIdstringAuto-generatedUnique chain identifier
eventsAuditEvent[][]Initial events
retentionDaysnumber180Log 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:

  1. Logging of operations — All agent actions recorded with timestamps
  2. Traceability — Individual operations attributable to specific events
  3. Transparency — Audit bundles provide human-readable documentation
  4. 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 CategoryCoverage
Charter validationValid/invalid charter scenarios
MerkleAudit chainHash linking, tamper detection
FiscalGate pathsHappy path, halt, error scenarios
Article 12 bundleFile 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

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Layer 1: Hash-Chained Ledger

Continue reading this section for the full explanation and source context.

Section Layer 2: Merkle Integrity on Memories

Continue reading this section for the full explanation and source context.

Section Layer 3: HMAC on Transactions

Continue reading this section for the full explanation and source context.

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

ComponentPurpose
audit-chain.tsSHA-256 chained event log implementation
audit.tsCore audit primitives and verification
verify()Chain integrity verification method
toJSON()Serialization for audit export
ListenersReal-time event subscription system
Deterministic ReplayReproducible 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:

  1. Computing the hash of each event in sequence
  2. Comparing computed hashes against stored hashes
  3. Validating chain link integrity between consecutive events
  4. 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 --> F

Chain Integrity Mechanism

FeatureDescription
Hash AlgorithmSHA-256
Chain StructureEach entry references previous entry's hash
DetectionAny modification breaks the chain instantly
VerificationSequential 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 Confirmed

API Reference

MerkleAudit Core Methods

#### verify()

Verifies the complete chain integrity.

ParameterTypeDescription
startIndexnumberOptional starting point for verification
endIndexnumberOptional ending point for verification

#### toJSON()

Serializes the audit chain to JSON format for export and storage.

ParameterTypeDescription
compactbooleanOptional compact representation

Ledger Methods

#### Transaction Operations

MethodPurpose
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

CategoryCoverage
Chain IntegrityVerification of unbroken hash chain
Tamper DetectionDetection of modified entries
Replay AccuracyDeterministic replay verification
Listener EventsReal-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:

  1. Reserves full charter budget up-front
  2. Runs the agent loop with ledger recording
  3. Settles actual spend on success
  4. Releases reserved funds on halt/error
  5. Returns audit digest for verification

Security Properties

Tamper Detection

Attack VectorDetection Mechanism
Single Entry ModificationSHA-256 hash mismatch
Chain ReorderingSequential link validation
Entry DeletionHash chain break detection
Memory ManipulationMerkle 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

  1. Regular Verification: Periodically run verify() on the audit chain
  2. Backup Chain State: Export via toJSON() for disaster recovery
  3. Monitor Listeners: Implement listeners to track chain modifications
  4. Retention Compliance: Configure appropriate retention periods for regulatory needs

Ledger Operations

  1. Always Verify Before Settlement: Check chain integrity before fund release
  2. Use Escrow: Hold funds until human approval for autonomous transactions
  3. Monitor Disputes: Track dispute patterns for fraud detection
  4. 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

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Session Management

Continue reading this section for the full explanation and source context.

Section Permission Controls

Continue reading this section for the full explanation and source context.

Section Killswitch

Continue reading this section for the full explanation and source context.

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 --> REFUND

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

ComponentDescription
session.session?.accountIdUnique account identifier for the authenticated agent
session.session?.emailAssociated email for the session
session.authenticatedBoolean flag indicating authentication status
onLoginCallback function for session authentication
onLogoutCallback 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 TypePurpose
Charge PermissionAllows agent to initiate payment collection
Settle PermissionAllows agent to release escrowed funds
Refund PermissionAllows agent to process refunds
Admin PermissionAllows 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:

ParameterValueDescription
Ceiling500 × reputationMaximum charge per transaction
Decay0.05Half-life approximately 14 hours
Feedback Loop+0.05Importance 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

ControlFunction
Account ID InputSpecify target account for session operations
Refresh ButtonFetch latest session and compliance status
LoginAuthenticate and establish session
LogoutTerminate session and clear credentials
Members ListView team members with identity status

Developer API Keys

The Developer Panel manages API keys that authenticate agent-to-platform communications:

FeatureDescription
List KeysView all active API keys for the account
Create KeyGenerate new provisioning secret
Revoke KeyImmediately invalidate an existing key

Sources: dashboard/index.html:280-310

Security Considerations

Authentication Flow

  1. Agent requests session with valid credentials
  2. System verifies KYA compliance status
  3. On success, session token is issued with scoped permissions
  4. All subsequent API calls include session token
  5. 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:

MetricDescription
MissionsCurrent period transaction count
SeatsActive agent identities under management
Plan GateCompliance status (Active/Limit Reached)
Over LimitBoolean indicating if usage exceeds plan

Sources: dashboard/index.html:320-340

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.

high Security or permission risk needs validation

The project may affect permissions, credentials, data exposure, or host boundaries.

medium Project risk needs validation

The project should not be treated as fully validated until this signal is reviewed.

medium README/documentation is current enough for a first validation pass.

The project should not be treated as fully validated until this signal is reviewed.

medium Maintainer activity is unknown

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.

Sources 2

Count of project-level external discussion links exposed on this manual page.

Use Review before install

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.

Source: Project Pack community evidence and pitfall evidence