# https://github.com/mnemopay/mnemopay-sdk 项目说明书

生成时间：2026-05-15 06:25:49 UTC

## 目录

- [Introduction to MnemoPay SDK](#introduction)
- [Quick Start Guide](#quick-start)
- [System Architecture](#architecture)
- [Core Modules Reference](#core-modules)
- [Payment Rails Overview](#payment-rails-overview)
- [Stripe, Paystack & Lightning Rails](#stripe-rail)
- [Alpha Payment Rails (StripeMPP, x402, GoogleAP2)](#alpha-rails)
- [Charter & FiscalGate Governance](#charter-fiscalgate)
- [MerkleAudit & Hash-Chained Ledger](#merkle-audit)
- [Identity & KYA Compliance](#identity-kya)

<a id='introduction'></a>

## Introduction to MnemoPay SDK

### 相关页面

相关主题：[Quick Start Guide](#quick-start), [System Architecture](#architecture)

<details>
<summary>Relevant Source Files</summary>

以下源码文件用于生成本页说明：

- [README.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/README.md)
- [CLAUDE.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/CLAUDE.md)
- [CHANGELOG.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/CHANGELOG.md)
- [site/index.legacy.html](https://github.com/mnemopay/mnemopay-sdk/blob/main/site/index.legacy.html)
- [integrations/python-hosted/README.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/integrations/python-hosted/README.md)
</details>

# 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

资料来源：[CLAUDE.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/CLAUDE.md)

## Architecture

The SDK consists of 14 core modules in the `src/` directory, providing approximately 74KB of compiled TypeScript functionality.

```mermaid
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
```

资料来源：[CLAUDE.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/CLAUDE.md)

### Module Overview

| Module | Purpose |
|--------|---------|
| `index.ts` | Main SDK exports: MnemoPay, MnemoPayLite, MnemoPayNetwork classes |
| `fico.ts` | Agent Credit Score (300-850); exports `AgentCreditScore` with legacy `AgentFICO` alias |
| `behavioral.ts` | Behavioral finance engine implementing prospect theory and cooling-off mechanisms |
| `integrity.ts` | Merkle tree memory integrity using SHA-256 hashing |
| `anomaly.ts` | EWMA anomaly detection, BehaviorMonitor, and CanarySystem |
| `adaptive.ts` | Adaptive AIMD rate limiting, anti-gaming protections, circuit breaker, PSI drift detection |
| `commerce.ts` | CommerceEngine enabling autonomous shopping with financial mandates |
| `fraud.ts` | Geo-enhanced fraud detection with location-based risk scoring |
| `identity.ts` | IdentityRegistry, KYA verification, CapabilityTokens, and killswitch permissions |
| `ledger.ts` | Double-entry accounting ledger for precise transaction tracking |
| `network.ts` | Multi-agent commerce network coordination |
| `client.ts` | REST API client for backend communication |
| `mcp/server.ts` | MCP server exposing 24 tools and 2 prompts for agent interaction |

资料来源：[CLAUDE.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/CLAUDE.md)

## Two SDK Modes

MnemoPay provides two operational modes depending on deployment requirements:

### Dev Mode (Zero Infrastructure)

```typescript
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.

资料来源：[CLAUDE.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/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

资料来源：[CHANGELOG.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/CHANGELOG.md)

## Quick Start

### Installation

```bash
npm install @mnemopay/sdk
```

### Development Workflow

```bash
npm install        # install dependencies
npm run build      # compile TypeScript
npm test           # run 672+ vitest tests
npm run lint       # type-check without emit
```

资料来源：[CLAUDE.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/CLAUDE.md)

## Memory System

The memory system provides persistent, semantic memory capabilities for AI agents:

### Core Operations

| Operation | Description |
|-----------|-------------|
| `remember(content, namespace, tags, importance)` | Store new memory with semantic tagging |
| `recall(query, namespace, limit, mode)` | Retrieve memories using hybrid search |
| `reason(query, namespace, limit, mode)` | Complex reasoning over stored memories |
| `reinforce(memoryId)` | Strengthen memory importance |
| `forget(memoryId)` | Remove specific memories |

### Memory Architecture

```mermaid
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.

资料来源：[site/journal/v1-4-0-longmemeval-77-2.html](https://github.com/mnemopay/mnemopay-sdk/blob/main/site/journal/v1-4-0-longmemeval-77-2.html)

## Payment System

### Payment Rails

MnemoPay integrates with three primary payment rails:

| Rail | Region | Currencies | Features |
|------|--------|------------|----------|
| **Paystack** | Africa | NGN, GHS, ZAR, KES | Checkout, saved cards, bank transfers, webhook verification, HMAC-SHA512 |
| **Stripe** | Global | USD, EUR, GBP, 135+ | Card payments, manual capture, true escrow via PaymentIntents |
| **Lightning** | Crypto | BTC | Instant microtransactions for agent-to-agent payments |

资料来源：[site/index.legacy.html](https://github.com/mnemopay/mnemopay-sdk/blob/main/site/index.legacy.html)

### Core Payment Operations

```typescript
// 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

```mermaid
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"]
```

资料来源：[site/index.legacy.html](https://github.com/mnemopay/mnemopay-sdk/blob/main/site/index.legacy.html)

## Agent Credit Score

The Agent Credit Score (FICO-equivalent) provides a 300-850 scoring system for evaluating AI agent reliability and trustworthiness.

### Scoring Components

| Component | Weight | Description |
|-----------|--------|-------------|
| Payment History | 35% | Historical transaction success rate |
| Utilization | 30% | Credit usage patterns |
| Behavioral Signals | 20% | Prospect theory analysis, cooling-off adherence |
| Anomaly Score | 10% | EWMA deviation from baseline behavior |
| Identity Verification | 5% | KYA completion level |

### Score Ranges

| Score Range | Rating | Description |
|-------------|--------|-------------|
| 750-850 | Excellent | High-trust agent, minimal monitoring |
| 650-749 | Good | Standard transaction limits |
| 550-649 | Fair | Enhanced monitoring, lower limits |
| 300-549 | Poor | Restricted operations, high collateral |

资料来源：[CLAUDE.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/CLAUDE.md)

## Identity and Access Control

### KYA (Know Your Agent)

Identity verification ensures agents are properly registered and authorized:

```typescript
// Register agent identity
const identity = await agent.identity.register({
  agentId: "agent-001",
  capabilities: ["payment", "memory", "commerce"],
  verificationLevel: "standard"
});

// Issue capability token
const token = await agent.identity.issueToken(agentId, capabilities);
```

### Permission Model

| Permission | Description |
|-------------|-------------|
| `payment.charge` | Initiate charges |
| `payment.refund` | Process refunds |
| `memory.write` | Store memories |
| `memory.read` | Access memories |
| `identity.delegate` | Issue sub-tokens |
| `killswitch` | Emergency shutdown |

资料来源：[CLAUDE.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/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:

```typescript
// 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

资料来源：[CLAUDE.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/CLAUDE.md)

### Adaptive Rate Limiting

The adaptive module implements:

- **AIMD (Additive Increase, Multiplicative Decrease)**: Graceful rate adjustment
- **Circuit Breaker**: Automatic shutdown on repeated failures
- **Anti-Gaming**: Detection of manipulation attempts
- **PSI Drift**: Population Stability Index monitoring

## Governance

MnemoPay includes enterprise-grade governance features:

| Component | Purpose |
|-----------|---------|
| **Charter** | Mission scope and operating principles |
| **FiscalGate** | Budget enforcement and spending limits |
| **Article 12** | Audit bundle requirements |
| **MerkleAudit** | Cryptographic audit trail |

资料来源：[CHANGELOG.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/CHANGELOG.md)

## Python Integration

A Python port provides stable parity with the TypeScript SDK:

```bash
pip install mnemopay
```

The Python SDK mirrors the TypeScript `PaymentRail` interface and ships with `MockRail` and `StripeRail` implementations.

资料来源：[integrations/python-hosted/README.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/integrations/python-hosted/README.md)

### Python API Methods

| Method | Description |
|--------|-------------|
| `remember(content, namespace, tags, importance)` | Store memory |
| `recall(query, namespace, limit, mode)` | Retrieve memories |
| `charge(amount, reason)` | Process payment |
| `settle(tx_id)` | Complete transaction |
| `graph(namespace)` | Get memory graph |
| `usage_report()` | Usage statistics |

## Middleware Integration

MnemoPay provides middleware for popular AI frameworks:

### OpenAI Integration

```typescript
import { mnemoPayMiddleware } from "@mnemopay/sdk/middleware/openai";
```

### Anthropic Integration

```typescript
import { mnemoPayMiddleware } from "@mnemopay/sdk/middleware/anthropic";
```

### LangGraph Integration

```typescript
import { mnemoPayTools } from "@mnemopay/sdk/langgraph";
```

资料来源：[README.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/README.md)

## Version History

| Version | Status | Key Features |
|---------|--------|--------------|
| 1.6.0 | Alpha | Latest pre-release with hardening fixes |
| 1.5.0 | Stable | Governance fold, FiscalGate, MerkleAudit |
| 1.4.0 | Past | 77.2% LongMemEval, 1M-op stress test |
| 1.0.0 | Python | Python SDK stable release |

资料来源：[CHANGELOG.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/CHANGELOG.md)

## License

MnemoPay SDK is Apache 2.0 Licensed.

---

<a id='quick-start'></a>

## Quick Start Guide

### 相关页面

相关主题：[Introduction to MnemoPay SDK](#introduction)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [README.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/README.md)
- [site/index.html](https://github.com/mnemopay/mnemopay-sdk/blob/main/site/index.html)
- [site/index.legacy.html](https://github.com/mnemopay/mnemopay-sdk/blob/main/site/index.legacy.html)
- [integrations/python-hosted/README.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/integrations/python-hosted/README.md)
- [dashboard/index.html](https://github.com/mnemopay/mnemopay-sdk/blob/main/dashboard/index.html)
</details>

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

资料来源：[README.md:1-15](https://github.com/mnemopay/mnemopay-sdk/blob/main/README.md)

## Prerequisites

| Requirement | Version/Details |
|-------------|-----------------|
| Node.js | v18+ recommended |
| npm/yarn/pnpm | Any modern package manager |
| API Key | Required for production use |
| Environment | Node.js runtime |

## Installation

The MnemoPay SDK is available on npm and can be installed with a single command:

```bash
npm install @mnemopay/sdk
```

资料来源：[site/index.html:1-20](https://github.com/mnemopay/mnemopay-sdk/blob/main/site/index.html)

## Quick Initialization

After installation, initialize your agent with a single function call that provides memory, wallet, and identity:

```typescript
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
```

资料来源：[site/index.legacy.html:1-30](https://github.com/mnemopay/mnemopay-sdk/blob/main/site/index.legacy.html)

## Four-Step Workflow

The following diagram illustrates the complete workflow from installation to production:

```mermaid
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
```

资料来源：[site/index.html:25-45](https://github.com/mnemopay/mnemopay-sdk/blob/main/site/index.html)

## Core Operations

### Payment Operations

| Method | Description |
|--------|-------------|
| `charge(amount, reason)` | Initiate a payment request |
| `settle(tx_id)` | Complete an escrow release |
| `refund(tx_id)` | Process a refund |

资料来源：[site/index.legacy.html:15-25](https://github.com/mnemopay/mnemopay-sdk/blob/main/site/index.legacy.html)

### Memory Operations

| Method | Description |
|--------|-------------|
| `remember(content, namespace, tags, importance)` | Store new information |
| `recall(query, namespace, limit, mode)` | Retrieve relevant memories |
| `reinforce(memoryId)` | Increase memory importance |
| `forget(memoryId)` | Remove a memory |

资料来源：[integrations/python-hosted/README.md:1-50](https://github.com/mnemopay/mnemopay-sdk/blob/main/integrations/python-hosted/README.md)

## Environment Configuration

Create a `.env` file in your project root with the following variables:

| Variable | Description | Required |
|----------|-------------|----------|
| `MNEMO_API_KEY` | Your MnemoPay API key | Yes |
| `STRIPE_KEY` | Stripe secret key | For Stripe payments |
| `PAYSTACK_KEY` | Paystack secret key | For Paystack payments |
| `LIGHTNING_CONFIG` | Lightning node config | For Lightning payments |

## Middleware Integration

MnemoPay provides middleware for popular AI frameworks:

### OpenAI Integration

```typescript
import { mnemoPayMiddleware } from "@mnemopay/sdk/middleware/openai";
```

### Anthropic Integration

```typescript
import { mnemoPayMiddleware } from "@mnemopay/sdk/middleware/anthropic";
```

### LangGraph Integration

```typescript
import { mnemoPayTools } from "@mnemopay/sdk/langgraph";
```

资料来源：[README.md:40-55](https://github.com/mnemopay/mnemopay-sdk/blob/main/README.md)

## Complete Example

```typescript
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);
```

资料来源：[site/index.legacy.html:10-30](https://github.com/mnemopay/mnemopay-sdk/blob/main/site/index.legacy.html)

## Payment Rails

MnemoPay supports three payment rails:

| Rail | Region | Features |
|------|--------|----------|
| Paystack | Africa (NGN, GHS, ZAR, KES) | Checkout, saved cards, bank transfers, HMAC-SHA512 security |
| Stripe | Global (USD, EUR, GBP) | Card payments, manual capture for escrow, 135+ currencies |
| Lightning | Crypto | Instant Bitcoin payments |

资料来源：[site/index.legacy.html:80-100](https://github.com/mnemopay/mnemopay-sdk/blob/main/site/index.legacy.html)

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

资料来源：[dashboard/index.html:1-50](https://github.com/mnemopay/mnemopay-sdk/blob/main/dashboard/index.html)

## Next Steps

| Resource | Purpose |
|----------|---------|
| [Full Documentation](https://mnemopay.com) | Complete API reference |
| [Pricing](https://mnemopay.com#pricing) | Starter/Pro/Enterprise plans |
| [Enterprise](https://github.com/mnemopay/mnemopay-sdk/blob/main/site/enterprise.html) | Custom integrations and support |

---

<a id='architecture'></a>

## System Architecture

### 相关页面

相关主题：[Core Modules Reference](#core-modules), [Payment Rails Overview](#payment-rails-overview), [Charter & FiscalGate Governance](#charter-fiscalgate)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [README.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/README.md)
- [CHANGELOG.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/CHANGELOG.md)
- [dashboard/index.html](https://github.com/mnemopay/mnemopay-sdk/blob/main/dashboard/index.html)
- [site/index.html](https://github.com/mnemopay/mnemopay-sdk/blob/main/site/index.html)
- [site/index.legacy.html](https://github.com/mnemopay/mnemopay-sdk/blob/main/site/index.legacy.html)
</details>

# 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

```mermaid
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.

| Component | Purpose | Language Support |
|-----------|---------|------------------|
| Core SDK | Client initialization, API abstraction | TypeScript, Python |
| Payment Rails | Transaction processing | TypeScript, Python |
| MCP Server | Model Context Protocol integration | TypeScript |
| Middleware | Framework integrations | TypeScript |

### Payment Rail System

The payment architecture implements a rail abstraction layer that supports multiple payment providers while maintaining a consistent interface. This design allows the system to switch between payment providers without changing application code, providing flexibility for different markets and use cases.

```mermaid
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:**

| Rail | Region | Currencies | Features |
|------|--------|------------|----------|
| Stripe | Global | USD, EUR, GBP, 135+ | Manual capture for true escrow, PaymentIntents API |
| Paystack | Africa | NGN, GHS, ZAR, KES | Checkout, saved cards, bank transfers, webhook verification, HMAC-SHA512 security, 23 Nigerian banks pre-mapped |
| Lightning | Crypto | BTC | Instant settlement via Lightning Network |
| Mock | Testing | All | Test mode without real transactions |

The escrow mechanism holds funds until human approval, providing a critical safety layer for autonomous agent transactions. When an agent initiates a charge, funds are captured but not settled until explicit human authorization, preventing unauthorized autonomous spending.

### Identity and Access Control

The identity layer implements Know Your Agent (KYA) verification with cryptographic tokens and permission management. A killswitch mechanism provides emergency stop capabilities, allowing immediate revocation of agent permissions across all active sessions.

Identity components operate through a multi-layered verification system:

- **KYA (Know Your Agent)**: Agent registration and verification process
- **Tokens**: Cryptographic credentials for API authentication
- **Permissions**: Granular access control for agent capabilities
- **Killswitch**: Emergency permission revocation system

### Agent Credit Score System

Agents receive credit scores ranging from 300 to 850, calculated through a five-component scoring model. This scoring system directly influences the agent's financial capabilities, including transaction limits and pricing terms.

| Score Component | Description | Impact |
|----------------|-------------|--------|
| Payment History | Historical transaction success rate | Primary factor |
| Transaction Volume | Total and average transaction sizes | Secondary factor |
| Dispute Rate | Ratio of disputed to total transactions | Negative impact |
| Response Time | Speed of human approval responses | Moderate impact |
| Behavioral Patterns | Anomaly detection signals | Risk adjustment |

The credit score affects the **Ceiling** parameter, calculated as `$500 × reputation` per charge, and determines the agent's decay rate with a half-life of approximately 14 hours. Settling transactions adds +0.05 importance to the memory reinforcement system, creating a feedback loop that improves score accuracy over time.

## Communication Architecture

### Backend Communication

The MnemoPay console backend implements a robust communication infrastructure with the following characteristics:

- **REST API**: Primary interface for synchronous operations
- **WebSockets**: Real-time event streaming for dashboard updates
- **Webhooks**: Asynchronous notification system for payment events

The hosted console at `mnemopay-landing.fly.dev` implements three-tier reliability architecture:

| Tier | Components | Purpose |
|------|------------|---------|
| Tier 1 | Production blockers | Core functionality protection |
| Tier 2 | Observability | Monitoring and metrics |
| Tier 3 | Safety nets | Rate limiting, body-size caps, idempotent webhooks |

### Observability Stack

```mermaid
graph TD
    subgraph OBSERVABILITY["Observability Layer"]
        Metrics["Prometheus /metrics"]
        Logs["Structured JSON Logging"]
        Health["Health Endpoints"]
    end
    
    subgraph SAFETY["Safety Layer"]
        RateLimit["Rate Limiting"]
        BodyCap["Body Size Caps"]
        CORS["CORS Allowlist"]
        Headers["Security Headers"]
    end
    
    subgraph DELIVERY["Delivery Layer"]
        Webhook["Webhook Notifications"]
        Idempotent["Idempotent Processing"]
        Shutdown["Graceful Shutdown"]
    end
    
    Metrics --> Prometheus["Prometheus"]
    Logs --> ELK["ELK Stack"]
    Health --> Ready["/readyz endpoint"]
    RateLimit --> SAFETY
    Webhook --> Idempotent
    Ready --> ReadyResponse{"readyz response<br/>productionReady: true"}
```

Security headers including Content-Security-Policy, X-Content-Type-Options, and X-Frame-Options protect the dashboard from common web vulnerabilities. The `/readyz` endpoint returns `productionReady: true` when all systems are operational, serving as a health check for load balancers and orchestrators.

## Middleware Integrations

The SDK provides middleware packages for seamless integration with popular AI frameworks, enabling automatic transaction tracking and payment capabilities within existing agent workflows.

### Available Middleware

| Integration | Package Path | Purpose |
|-------------|--------------|---------|
| OpenAI | `@mnemopay/sdk/middleware/openai` | OpenAI agent transaction middleware |
| Anthropic | `@mnemopay/sdk/middleware/anthropic` | Anthropic Claude agent middleware |
| LangGraph | `@mnemopay/sdk/langgraph` | LangGraph tools integration |

### MCP Server

The Model Context Protocol (MCP) server enables standardized communication between AI models and external tools. The MCP server implementation in `src/mcp/server.ts` uses `require.main === module` to prevent spurious server starts when consumers import from `@mnemopay/sdk/mcp` in browser bundles or test harnesses. This auto-start guard replaces the previous loose `process.argv` heuristic that caused issues with browser consumers.

## Dashboard Architecture

The web-based dashboard provides real-time monitoring and management capabilities through a React-based single-page application. The dashboard architecture uses a tabbed interface with specialized panels for different operational concerns.

```mermaid
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:**

| Tab | Icon | Function |
|-----|------|----------|
| Console | System monitor | Overview of transactions and account status |
| Session | Users | Login/logout session management |
| Brain | Brain icon | Memory recall and query interface |
| Developer | Code brackets | API key management |
| Billing | Credit card | Usage metering and plan limits |
| Memories | Database | Memory persistence configuration |

### GitHub Repository Monitoring

The dashboard includes a repository monitoring feature that tracks GitHub forks and upstream stars. Repositories are displayed with status indicators showing:

- Upstream star count
- Last update date
- Pull request information with title, number, and creation date
- Error states when fetching fails

## Behavioral Finance System

The architecture incorporates behavioral finance principles through prospect theory implementation and nudging mechanisms. These components work together to influence agent decision-making in financial contexts, encouraging optimal behavior while preventing risky transaction patterns.

### Anomaly Detection

Transaction anomaly detection uses Exponentially Weighted Moving Average (EWMA) statistical methods combined with behavioral fingerprinting. This dual approach identifies both statistical outliers and behavioral patterns that deviate from established agent profiles.

| Detection Method | Function |
|-----------------|----------|
| EWMA | Statistical anomaly detection on transaction amounts and frequencies |
| Fingerprinting | Behavioral pattern recognition across transaction sequences |

## Governance Framework

The governance layer provides institutional controls over agent financial activities through four primary mechanisms:

- **Charter**: Defines agent mission scope and authorized activities
- **FiscalGate**: Budget enforcement for transaction limits
- **Article 12**: Compliance and regulatory requirements
- **MerkleAudit**: Cryptographic audit trail for transaction verification

This multi-layered governance ensures agents operate within defined parameters while maintaining full accountability for their financial actions.

## SDK Installation and Quick Start

```bash
# Install the SDK
npm install @mnemopay/sdk

# Python installation (alternative)
pip install mnemopay
```

```typescript
// 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
```

资料来源：[README.md:1-40](https://github.com/mnemopay/mnemopay-sdk/blob/main/README.md)
资料来源：[site/index.html](https://github.com/mnemopay/mnemopay-sdk/blob/main/site/index.html)
资料来源：[site/index.legacy.html](https://github.com/mnemopay/mnemopay-sdk/blob/main/site/index.legacy.html)
资料来源：[dashboard/index.html](https://github.com/mnemopay/mnemopay-sdk/blob/main/dashboard/index.html)
资料来源：[CHANGELOG.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/CHANGELOG.md)

---

<a id='core-modules'></a>

## Core Modules Reference

### 相关页面

相关主题：[System Architecture](#architecture)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [src/index.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/index.ts)
- [src/recall/engine.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/recall/engine.ts)
- [src/fraud.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/fraud.ts)
- [src/identity/index.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/identity/index.ts)
- [src/ledger.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/ledger.ts)
- [src/fico.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/fico.ts)
- [src/behavioral.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/behavioral.ts)
- [src/integrity.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/integrity.ts)
- [src/anomaly.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/anomaly.ts)
- [src/adaptive.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/adaptive.ts)
- [src/commerce.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/commerce.ts)
- [src/mcp/server.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/mcp/server.ts)
</details>

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

```mermaid
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
```

资料来源：[README.md:40-55]()

## Memory Module (`src/recall/`)

The memory module provides persistent, searchable memory capabilities for agents using semantic and hybrid retrieval. It supports the core memory operations: remember, recall, reinforce, forget, and consolidate.

### Memory Operations

| Operation | Purpose | Parameters |
|-----------|---------|------------|
| `remember(content, namespace?, tags?, importance?)` | Store a memory with optional importance score and tags | Content string, namespace ID, tag array, importance 0-1 |
| `recall(query, namespace?, limit?, mode?)` | Retrieve relevant memories via semantic search | Query string, namespace, result limit, search mode |
| `reinforce(memoryId)` | Boost a memory's importance score (+0.01 to +0.5) | Memory ID |
| `forget(memoryId)` | Permanently delete a memory by ID | Memory ID |
| `consolidate(namespace?)` | Prune stale memories below decay threshold | Optional namespace filter |

### Search Modes

The recall engine supports multiple retrieval modes for different use cases:

```mermaid
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)

资料来源：[src/recall/engine.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/recall/engine.ts)

### Memory Structure

Each memory entry contains:

| Field | Type | Description |
|-------|------|-------------|
| `id` | string | Unique memory identifier |
| `content` | string | The memory content |
| `namespace` | string | Logical partition for memory spaces |
| `tags` | string[] | Categorization tags |
| `importance` | number | 0-1 importance score for retrieval weighting |
| `createdAt` | Date | Creation timestamp |
| `updatedAt` | Date | Last modification timestamp |
| `accessCount` | number | Number of times recalled |

资料来源：[integrations/openclaw/SKILL.md:20-35]()

## Ledger Module (`src/ledger.ts`)

The ledger implements double-entry bookkeeping for all financial transactions. Every monetary operation creates balanced entries ensuring accounting integrity across charges, settlements, and refunds.

### Transaction Types

| Type | Description | Ledger Impact |
|------|-------------|---------------|
| `charge` | Creates escrow hold for delivered work | Debit: Receivable, Credit: Escrow |
| `settle` | Finalizes charge, moves funds to wallet | Debit: Escrow, Credit: Revenue |
| `refund` | Reverses a transaction | Debit: Escrow, Credit: Receivable |
| `dispute` | User-initiated chargeback | Triggers fraud analysis |

### Transaction States

```mermaid
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
```

资料来源：[src/ledger.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/ledger.ts)

## Identity Module (`src/identity/`)

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

### Components

| Component | Purpose |
|-----------|---------|
| `IdentityRegistry` | Central registry mapping agent IDs to identities |
| `KYA` (Know Your Agent) | Onboarding verification for new agents |
| `CapabilityTokens` | Time-limited permission grants |
| `killswitch` | Emergency capability revocation |

### Identity Model

```typescript
interface Identity {
  agentId: string;
  publicKey: string;
  reputation: number;        // 0-1 score
  kyaStatus: KYAStatus;
  capabilities: Capability[];
  createdAt: Date;
  lastActive: Date;
}
```

资料来源：[src/identity/index.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/identity/index.ts)

## Agent Credit Score (`src/fico.ts`)

The Agent Credit Score provides a portable, standardized credit evaluation (300-850 range) for AI agents, enabling trust assessment across different platforms and use cases.

### Scoring Components

The FICO module calculates scores using five weighted factors:

| Component | Weight | Description |
|-----------|--------|-------------|
| Payment History | 35% | Track record of successful settlements |
| Utilization | 30% | Current escrow exposure relative to limits |
| Account Age | 15% | Duration of active account |
| Diversity | 10% | Range of transaction types and rails used |
| Reputation | 10% | Social/professional reputation signals |

### Score Ranges

| Range | Classification | Description |
|-------|-----------------|-------------|
| 800-850 | Exceptional | Highly reliable, lowest risk |
| 740-799 | Very Good | Reliable with minimal risk |
| 670-739 | Good | Acceptable risk level |
| 580-669 | Fair | Elevated risk, monitor closely |
| 300-579 | Poor | High risk, limited capabilities |

资料来源：[src/fico.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/fico.ts)

## Fraud Detection (`src/fraud.ts`)

The fraud module provides geo-enhanced fraud detection with pattern recognition and behavioral analysis.

### Detection Mechanisms

```mermaid
graph TD
    A[Transaction Request] --> B[Geo Analysis]
    A --> C[Pattern Matching]
    A --> D[Velocity Check]
    B --> E{Risk Score}
    C --> E
    D --> E
    E -->|Low| F[Allow]
    E -->|Medium| G[Flag for Review]
    E -->|High| H[Block + Alert]
```

### Risk Factors

| Factor | Description | Threshold |
|--------|-------------|-----------|
| `geoVelocity` | Rapid location changes impossible for user | >500km/hour |
| `velocityVolume` | Unusual transaction frequency | >10 tx/hour |
| `amountAnomaly` | Statistical outlier in transaction size | >3σ from mean |
| `patternDeviation` | Deviation from established behavioral patterns | Similarity <0.6 |

资料来源：[src/fraud.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/fraud.ts)

## Anomaly Detection (`src/anomaly.ts`)

EWMA (Exponentially Weighted Moving Average) anomaly detection monitors behavioral patterns and identifies deviations that may indicate compromise or abuse.

### Components

| Component | Purpose |
|-----------|---------|
| `EWMA` | Core statistical monitoring with exponential weighting |
| `BehaviorMonitor` | Tracks behavioral baselines per agent |
| `CanarySystem` | Synthetic transactions to verify system integrity |

### Alert Levels

```mermaid
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]
```

资料来源：[src/anomaly.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/anomaly.ts)

## Behavioral Finance (`src/behavioral.ts`)

The behavioral module implements concepts from behavioral economics to influence agent decision-making and user interactions.

### Features

| Feature | Description |
|---------|-------------|
| Prospect Theory | Loss aversion calculations (losses weighted 2x gains) |
| Cooling-Off Periods | Mandatory waiting periods for high-value transactions |
| Nudges | Behavioral prompts to encourage positive outcomes |

### Cooling-Off Rules

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

| Amount Range | Cooling Period |
|--------------|-----------------|
| $100-$500 | 24 hours |
| $500-$1000 | 72 hours |
| >$1000 | 7 days |

资料来源：[src/behavioral.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/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

```mermaid
graph TD
    A[Memory Entry] --> B[SHA-256 Hash]
    B --> C[Merkle Tree Node]
    C --> D{Root Hash}
    D --> E[Audit Request]
    E --> F[Prove Path]
    F --> G[Verify against Root]
    G --> H[Valid/Invalid]
```

### Audit Capabilities

| Feature | Description |
|---------|-------------|
| `MerkleAudit` | Generates proof bundles for external verification |
| Chain Verification | Validates no memories were tampered with |
| Timestamping | Provides proof of memory existence at time T |

资料来源：[src/integrity.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/integrity.ts)

## Adaptive Module (`src/adaptive.ts`)

Adaptive rate limiting and anti-gaming mechanisms prevent abuse while allowing legitimate high-throughput scenarios.

### Components

| Component | Purpose |
|-----------|---------|
| `AIMD` | Additive Increase, Multiplicative Decrease rate control |
| Anti-Gaming | Detection of rate limit exploitation patterns |
| `CircuitBreaker` | Prevents cascade failures |
| `PSI Drift` | Population Stability Index for distribution shifts |

### Circuit Breaker States

```mermaid
stateDiagram-v2
    [*] --> Closed: Normal Operation
    Closed --> Open: Failure Threshold
    Open --> HalfOpen: Recovery Timeout
    HalfOpen --> Closed: Success
    HalfOpen --> Open: Failure
```

资料来源：[src/adaptive.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/adaptive.ts)

## Commerce Engine (`src/commerce.ts`)

The commerce engine enables autonomous shopping with configurable mandates and spending policies.

### Mandate Structure

```typescript
interface Mandate {
  id: string;
  agentId: string;
  rules: CommerceRule[];
  maxAmount: number;
  maxFrequency: number;
  allowedCategories: string[];
  createdAt: Date;
}
```

### Shopping Workflow

```mermaid
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]
```

资料来源：[src/commerce.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/commerce.ts)

## MCP Server (`src/mcp/server.ts`)

The Model Context Protocol server exposes SDK functionality as MCP tools for integration with LLM agents.

### Available Tools (24 total)

#### Memory Tools (5)

| Tool | Description |
|------|-------------|
| `mcp__mnemopay__remember` | Store a memory with optional importance and tags |
| `mcp__mnemopay__recall` | Retrieve relevant memories via semantic search |
| `mcp__mnemopay__forget` | Permanently delete a memory |
| `mcp__mnemopay__reinforce` | Boost memory importance |
| `mcp__mnemopay__consolidate` | Prune stale memories |

#### Payment Tools (4)

| Tool | Description |
|------|-------------|
| `mcp__mnemopay__charge` | Create escrow charge (max $500 × reputation) |
| `mcp__mnemopay__settle` | Finalize pending charge |
| `mcp__mnemopay__refund` | Process refund |
| `mcp__mnemopay__dispute` | File dispute for chargeback |

#### Additional Tools

- Identity management tools
- Ledger query tools
- Reputation management tools
- Usage and audit tools

资料来源：[src/mcp/server.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/mcp/server.ts)
资料来源：[integrations/openclaw/SKILL.md:40-60]()

## Payment Rails (`src/rails/`)

The rails module provides abstraction over multiple payment providers, enabling cross-border commerce through standardized interfaces.

### Supported Rails

| Rail | Region | Currencies | Features |
|------|--------|------------|----------|
| Stripe | Global | USD, EUR, GBP, 135+ | PaymentIntents, Manual Capture, Webhooks |
| Paystack | Africa | NGN, GHS, ZAR, KES | Checkout, Saved Cards, Bank Transfer, HMAC-SHA512 |
| Lightning | Crypto | BTC | Instant settlement, Micropayments |

### Rail Interface

```typescript
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

```mermaid
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
```

资料来源：[src/index.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/index.ts)

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

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

### SDK Variants

| Variant | Size | Use Case |
|---------|------|----------|
| `MnemoPay` | ~74KB | Full-featured production use |
| `MnemoPayLite` | <20KB | Browser, edge functions, constrained environments |
| `MnemoPayNetwork` | +~15KB | Multi-agent scenarios |

### Quick Start

```typescript
import { MnemoPay } from '@mnemopay/sdk';

// Development mode - zero infrastructure
const agent = MnemoPay.quick("agent-id");

// Store memory
await agent.remember("User prefers Express shipping", { importance: 0.8 });

// Recall previous context
const memories = await agent.recall("shipping preferences");

// Charge for work delivered
const charge = await agent.charge(25.00, "Monthly report delivery");

// Settle after user approval
await agent.settle(charge.id);
```

### Initialization Modes

| Mode | Description | Infrastructure Required |
|------|-------------|------------------------|
| `quick(agentId)` | Dev mode with mock services | None |
| `init(config)` | Production mode with real services | API keys, secrets |
| `network(config)` | Multi-agent network mode | Network registry |

资料来源：[src/index.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/index.ts)
资料来源：[README.md:55-75]()

## Module Dependencies

Understanding module dependencies is crucial for proper integration and troubleshooting.

```mermaid
graph TD
    R[Recall/Memory] --> L[Ledger]
    I[Identity] --> R
    I --> F[FICO]
    F --> FR[Fraud]
    B[Behavioral] --> C[Commerce]
    A[Anomaly] --> L
    AD[Adaptive] --> A
    L --> N[Network]
    I --> N
    C --> RA[Rails]
    R --> IN[Integrity]
```

## Configuration Reference

### Required Configuration

| Parameter | Type | Description |
|-----------|------|-------------|
| `agentId` | string | Unique agent identifier |
| `apiKey` | string | API authentication key |
| `networkId` | string | Network/tenant identifier |

### Optional Configuration

| Parameter | Default | Description |
|-----------|---------|-------------|
| `mode` | `"dev"` | Runtime mode: dev, production, network |
| `rail` | `"stripe"` | Primary payment rail |
| `region` | `"us-east-1"` | Deployment region |
| `logLevel` | `"warn"` | Logging verbosity |

资料来源：[src/index.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/index.ts)

## Testing

The SDK includes 672+ vitest tests covering all modules:

```bash
npm test           # Run all tests
npm run build      # Compile TypeScript
npm run lint       # Type-check without emit
```

Test coverage is distributed across:

| Module | Test Focus |
|--------|------------|
| Memory | CRUD operations, search accuracy, consolidation |
| Ledger | Double-entry balance, transaction states |
| Identity | KYA flow, capability tokens, killswitch |
| Fraud | Geo-velocity, pattern matching, thresholds |
| Anomaly | EWMA calculation, alert thresholds |
| Rails | Payment flows, webhook verification |

---

<a id='payment-rails-overview'></a>

## Payment Rails Overview

### 相关页面

相关主题：[Stripe, Paystack & Lightning Rails](#stripe-rail), [Alpha Payment Rails (StripeMPP, x402, GoogleAP2)](#alpha-rails), [System Architecture](#architecture)

<details>
<summary>Related Source Files</summary>

以下源码文件用于生成本页说明：

- [src/rails/index.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/rails/index.ts)
- [src/rails/stripe-mpp.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/rails/stripe-mpp.ts)
- [src/rails/x402.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/rails/x402.ts)
- [src/rails/google-ap2.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/rails/google-ap2.ts)
</details>

# 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. 资料来源：[README.md:1-45]()

## Architecture Overview

```mermaid
graph TD
    A[Agent / Application] --> B[MnemoPay SDK Core]
    B --> C[Payment Rail Abstraction Layer]
    C --> D[StripeRail]
    C --> E[PaystackRail]
    C --> F[LightningRail]
    C --> G[StripeMPPRail]
    C --> H[X402Rail]
    C --> I[GoogleAP2Rail]
    D --> J[Stripe API]
    E --> K[Paystack API]
    F --> L[LND / Lightning Network]
    G --> M[Stripe MPP]
    H --> N[Base / EIP-3009]
    I --> O[Google AP2]
```

## Rail Classification

Payment rails in MnemoPay are classified into two stability tiers:

| Classification | Rails | Use Case | Status |
|---|---|---|---|
| **Stable** | `StripeRail`, `PaystackRail`, `LightningRail` | Production deployments | `latest` |
| **Preview (Alpha)** | `StripeMPPRail`, `X402Rail`, `GoogleAP2Rail` | Evaluation and testing | `alpha` |

资料来源：[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:**
```ts
import { StripeRail } from "@mnemopay/sdk";

const stripe = new StripeRail(process.env.STRIPE_SECRET_KEY!);
```

资料来源：[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:**
```ts
import { PaystackRail } from "@mnemopay/sdk";

const paystack = new PaystackRail(process.env.PAYSTACK_SECRET_KEY!);
```

资料来源：[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:**
```ts
import { LightningRail } from "@mnemopay/sdk";

const lightning = new LightningRail(LND_URL, MACAROON);
```

资料来源：[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

```ts
import { StripeMPPRail } from "@mnemopay/sdk";

const mpp = new StripeMPPRail(process.env.STRIPE_SECRET_KEY!);
```

资料来源：[src/rails/stripe-mpp.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/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

```ts
import { X402Rail } from "@mnemopay/sdk";
import { YourEip3009Signer } from "./your-signer";

const x402 = new X402Rail({ signer: yourEip3009Signer });
```

**Requirements:** Bring-your-own EIP-3009 signer implementation

资料来源：[src/rails/x402.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/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

```ts
import { GoogleAP2Rail } from "@mnemopay/sdk";

const ap2 = new GoogleAP2Rail({ mandate, endpoint, signer });
```

资料来源：[src/rails/google-ap2.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/rails/google-ap2.ts)

## Common Payment Operations

All payment rails support the same core operations for payment lifecycle management:

| Operation | Description |
|---|---|
| **Charge** | Initiate a payment from the customer's payment method |
| **Escrow** | Hold funds in a secure state pending verification or delivery |
| **Settle** | Release escrowed funds to the merchant/recipient |
| **Refund** | Return funds to the customer |

The double-entry ledger system ensures every financial operation is recorded with corresponding debit and credit entries, maintaining balanced books with zero penny drift. 资料来源：[site/index.html](https://github.com/mnemopay/mnemopay-sdk/blob/main/site/index.html)

## Environment Configuration

### Real Payment Rails

For production deployments using real payment providers:

| Environment Variable | Purpose |
|---|---|
| `STRIPE_SECRET_KEY` | Stripe payments API key |
| `PAYSTACK_SECRET_KEY` | Paystack payments API key |
| `MNEMOPAY_PAYMENT_RAIL` | Active rail: `stripe`, `paystack`, or `mock` |
| `MNEMOPAY_COMMERCE_PROVIDER` | Commerce provider: `firecrawl`, `shopify`, or `mock` |

资料来源：[claude-plugin/README.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/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

```ts
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
});
```

资料来源：[README.md:26-40]()

## Architecture Benefits

| Benefit | Description |
|---|---|
| **Provider Abstraction** | Single API interface for multiple payment providers |
| **Rail Switching** | Change payment providers without code modifications |
| **Hybrid Rails** | Combine multiple rails in a single agent configuration |
| **Consistent Error Handling** | Unified error responses across all providers |
| **Audit Trail** | Every operation logged in the hash-chained ledger |

## Choosing a Payment Rail

| Scenario | Recommended Rail |
|---|---|
| Global card payments | `StripeRail` |
| African markets (NGN, GHS, ZAR, KES) | `PaystackRail` |
| BTC micropayments | `LightningRail` |
| Crypto deposits settlement | `StripeMPPRail` |
| On-chain USDC payments (Base) | `X402Rail` |
| FIDO-aligned settlement | `GoogleAP2Rail` |

## Summary

The Payment Rails system provides MnemoPay agents with flexible, production-ready payment infrastructure across six different payment providers. Stable rails (Stripe, Paystack, Lightning) handle traditional payment flows, while preview rails (StripeMPP, X402, GoogleAP2) enable emerging crypto and mandate-based payment methods. All rails share a common interface, allowing seamless switching and hybrid configurations.

---

<a id='stripe-rail'></a>

## Stripe, Paystack & Lightning Rails

### 相关页面

相关主题：[Payment Rails Overview](#payment-rails-overview), [Alpha Payment Rails (StripeMPP, x402, GoogleAP2)](#alpha-rails)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [README.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/README.md)
- [CHANGELOG.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/CHANGELOG.md)
- [CLAUDE.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/CLAUDE.md)
- [CLAUDE.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/CLAUDE.md)
- [dashboard/DEPLOYMENT.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/dashboard/DEPLOYMENT.md)
- [site/index.html](https://github.com/mnemopay/mnemopay-sdk/blob/main/site/index.html)
</details>

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

资料来源：[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

```typescript
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);
```

资料来源：[README.md:28-38]()

### Rail Selection Matrix

| Rail | Coverage | Channel | Status | Currencies |
|------|----------|---------|--------|------------|
| `StripeRail` | Global | stable (`latest`) | Stable | USD, EUR, GBP, + |
| `PaystackRail` | Africa | stable (`latest`) | Stable | NGN, GHS, ZAR, KES |
| `LightningRail` | BTC micropayments | stable (`latest`) | Stable | BTC |
| `StripeMPPRail` | Crypto via Tempo | preview (`alpha`) | Alpha | Crypto deposits |
| `X402Rail` | USDC on Base | preview (`alpha`) | Alpha | USDC |
| `GoogleAP2Rail` | AP2 v0.2 mandate | preview (`alpha`) | Alpha | Multiple |

资料来源：[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:**
```typescript
const stripe = new StripeRail(process.env.STRIPE_SECRET_KEY!);
const agent = MnemoPay.quick("billing-agent", { stripe: { secretKey: process.env.STRIPE_SECRET_KEY } });
```

资料来源：[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`

资料来源：[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:**
```typescript
const paystack = new PaystackRail(process.env.PAYSTACK_SECRET_KEY!);
```

资料来源：[README.md:31](), [site/index.html:58-62]()

**Environment Variables:**
```bash
PAYSTACK_SECRET_KEY=sk_live_...  # Required for Paystack payments
MNEMOPAY_PAYMENT_RAIL=paystack   # Set payment rail
```

资料来源：[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:**
```typescript
const lightning = new LightningRail(LND_URL, MACAROON);
```

资料来源：[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:**
```typescript
const mpp = new StripeMPPRail(process.env.STRIPE_SECRET_KEY!);
```

**Key Methods:**
- `fromClient(client, opts?)` — for tests and shared Stripe client patterns

资料来源：[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:**
```typescript
const x402 = new X402Rail({ signer: yourEip3009Signer });
```

资料来源：[CHANGELOG.md:46-55]()

### GoogleAP2Rail

Google Agent Payment Protocol (AP2) v0.2 provides mandate-driven settlement through the FIDO Alliance open standard.

**Configuration:**
```typescript
const ap2 = new GoogleAP2Rail({ mandate, endpoint, signer });
```

资料来源：[CHANGELOG.md:56-60]()

## Payment Flow Architecture

```mermaid
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

```typescript
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.
```

资料来源：[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.

```typescript
// Ledger maintains balance integrity across all rails
// SHA-256 hash-chained for tamper evidence
```

资料来源：[site/index.html:15-17](), [CLAUDE.md:8]()

## Environment Configuration

| Variable | Rail | Description |
|----------|------|-------------|
| `STRIPE_SECRET_KEY` | Stripe, StripeMPP | Stripe API key |
| `PAYSTACK_SECRET_KEY` | Paystack | Paystack API key |
| `MNEMOPAY_PAYMENT_RAIL` | All | `stripe`, `paystack`, or `mock` |
| `MNEMOPAY_COMMERCE_PROVIDER` | Shopping | `firecrawl`, `shopify`, or `mock` |

资料来源：[claude-plugin/README.md:8-10]()

## Integration Examples

### Production Setup

```typescript
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)

```typescript
// Dev mode - zero infrastructure required
const agent = MnemoPay.quick("my-agent");

// All features work, defaults to mock/sandbox
// Swap to real rail with configuration
```

资料来源：[CLAUDE.md:20-35]()

## CLI Commands

The Claude plugin provides payment management commands:

| Command | Description |
|---------|-------------|
| `/mnemopay:charge <amount> <description>` | Charge specified amount |
| `/mnemopay:balance` | Check account balance |
| `/mnemopay:history <period>` | View transaction history |
| `/mnemopay:settle` | Settle pending transactions |
| `/mnemopay:fico` | View agent credit score |
| `/mnemopay:remember <pref>` | Store payment preferences |
| `/mnemopay:recall` | Retrieve payment preferences |

资料来源：[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

资料来源：[CHANGELOG.md:31-32](), [CHANGELOG.md:29]()

## See Also

- [Agent Credit Score](agent-credit-score) — Agent trust scoring (300-850)
- [Double-Entry Ledger](ledger) — Financial transaction tracking
- [Shopping Module](shopping) — Autonomous product discovery and purchase
- [MCP Server](mcp-server) — 24 tools for agent payment operations

---

<a id='alpha-rails'></a>

## Alpha Payment Rails (StripeMPP, x402, GoogleAP2)

### 相关页面

相关主题：[Payment Rails Overview](#payment-rails-overview), [Stripe, Paystack & Lightning Rails](#stripe-rail)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [src/rails/stripe-mpp.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/rails/stripe-mpp.ts)
- [src/rails/x402.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/rails/x402.ts)
- [src/rails/google-ap2.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/rails/google-ap2.ts)
- [src/client.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/client.ts)
</details>

# Alpha Payment Rails (StripeMPP, x402, GoogleAP2)

## Overview

Alpha Payment Rails are experimental payment rail implementations introduced in MnemoPay SDK v1.6.0-alpha as part of the v1.6.x rail sprint. These rails provide alternative payment methods beyond the stable payment rails (Stripe, Paystack, Lightning) and enable crypto-native payment flows for AI agents.

| Rail | Technology | Status | Channel |
|------|-----------|--------|---------|
| `StripeMPPRail` | Crypto deposits on Tempo via Stripe MPP | alpha | `npm install @mnemopay/sdk@alpha` |
| `X402Rail` | USDC on Base via EIP-3009 transferWithAuthorization | alpha | `npm install @mnemopay/sdk@alpha` |
| `GoogleAP2Rail` | AP2 v0.2 mandate-driven settlement (FIDO Alliance) | alpha | `npm install @mnemopay/sdk@alpha` |

资料来源：[README.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/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` 资料来源：[CHANGELOG.md:19-36](https://github.com/mnemopay/mnemopay-sdk/blob/main/CHANGELOG.md)

### API Configuration

```typescript
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

资料来源：[CHANGELOG.md:20-35](https://github.com/mnemopay/mnemopay-sdk/blob/main/CHANGELOG.md)

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

```typescript
import { X402Rail } from "@mnemopay/sdk";

const x402 = new X402Rail({ signer: yourEip3009Signer });
```

资料来源：[README.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/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

```typescript
import { GoogleAP2Rail } from "@mnemopay/sdk";

const ap2 = new GoogleAP2Rail({ mandate, endpoint, signer });
```

资料来源：[README.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/README.md)

## Architecture

```mermaid
graph TD
    A[MnemoPay Agent] --> B[PaymentRail Interface]
    B --> C[Stable Rails]
    B --> D[Alpha Rails]
    
    C --> C1[StripeRail]
    C --> C2[PaystackRail]
    C --> C3[LightningRail]
    
    D --> D1[StripeMPPRail]
    D --> D2[X402Rail]
    D --> D3[GoogleAP2Rail]
    
    D1 --> D1A[Stripe MPP API<br/>2026-03-04.preview]
    D1A --> D1B[Tempo Network<br/>Crypto Deposits]
    
    D2 --> D2A[EIP-3009<br/>transferWithAuthorization]
    D2A --> D2B[Base Network<br/>USDC]
    
    D3 --> D3A[AP2 v0.2<br/>FIDO Alliance]
    D3A --> D3B[Mandate-Driven<br/>Settlement]
```

## Payment Rail Comparison

| Feature | StripeRail | StripeMPPRail | X402Rail | GoogleAP2Rail |
|---------|------------|---------------|----------|---------------|
| Currency | USD, EUR, GBP | Crypto (Tempo) | USDC | Multi-currency |
| Network | Stripe | Tempo | Base L2 | FIDO Network |
| Escrow | Manual capture | Manual capture | Authorization-based | Mandate-based |
| Auth Method | Stripe Auth | Stripe MPP | EIP-3009 Signer | FIDO Auth |
| Status | Stable | Alpha | Alpha | Alpha |
| API Version | Latest | 2026-03-04.preview | N/A | v0.2 |

## Installation

Alpha rails are available under the `alpha` npm dist-tag:

```bash
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.

资料来源：[CHANGELOG.md:6-14](https://github.com/mnemopay/mnemopay-sdk/blob/main/CHANGELOG.md)

## Usage Example

```typescript
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 });
```

资料来源：[README.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/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

资料来源：[CHANGELOG.md:14-17](https://github.com/mnemopay/mnemopay-sdk/blob/main/CHANGELOG.md)

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

资料来源：[CHANGELOG.md:34-35](https://github.com/mnemopay/mnemopay-sdk/blob/main/CHANGELOG.md)

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

---

<a id='charter-fiscalgate'></a>

## Charter & FiscalGate Governance

### 相关页面

相关主题：[MerkleAudit & Hash-Chained Ledger](#merkle-audit), [Identity & KYA Compliance](#identity-kya), [System Architecture](#architecture)

<details>
<summary>Related Source Files</summary>

The following source files were used to generate this documentation:

- [src/governance/charter.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/governance/charter.ts)
- [src/governance/payments.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/governance/payments.ts)
- [src/governance/article12.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/governance/article12.ts)
- [src/governance/policies/eu-ai-act.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/governance/policies/eu-ai-act.ts)
</details>

# 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                │
└──────────────────────────────────────────────────────────────────┘
```

资料来源：[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

资料来源：[CHANGELOG.md]()

## Architecture

### System Components

```mermaid
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]
```

资料来源：[CHANGELOG.md]()

### Data Flow

```mermaid
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.

```typescript
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

资料来源：[src/governance/charter.ts]()

### 2. FiscalGate

The `FiscalGate` primitive (`runMission()`) is the core budget enforcement mechanism.

```typescript
interface FiscalGateResult {
  status: "ok" | "halted" | "error";
  spentUsd: number;
  outputs: any[];
  auditDigest: string;
  // ... additional fields
}
```

#### Execution Flow

```mermaid
graph TD
    A[runMission ctx] --> B[Reserve full budget]
    B --> C[Execute agent loop]
    C --> D{All operations complete?}
    D -->|Yes| E{Spent within budget?}
    D -->|No| F[Log operation]
    F --> C
    E -->|Yes| G[Settle actual spend]
    E -->|No| H[Release excess reservation]
    G --> I[Return ok status]
    H --> I
    D -->|Halt signal| J[Release budget]
    D -->|Error| K[Release budget]
    J --> L[Return halted status]
    K --> M[Return error status]
```

#### Key Behaviors

| Scenario | Action | Result |
|----------|--------|--------|
| Mission succeeds | Settle actual spend | `status: "ok"` |
| Mission halts early | Release reserved budget | `status: "halted"` |
| Error occurs | Release reserved budget | `status: "error"` |
| Overspend attempted | Block operation | Budget preserved |

资料来源：[CHANGELOG.md](), [src/governance/payments.ts]()

### 3. MerkleAudit

The `MerkleAudit` system provides a SHA-256 chained event log with verification capabilities.

```typescript
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

```mermaid
graph LR
    E1[Event 1] --> H1[Hash 1]
    H1 --> E2[Event 2]
    E2 --> H2[Hash 2]
    H2 --> E3[Event 3]
    E3 --> H3[Hash 3]
    
    style H1 fill:#f96
    style H2 fill:#f96
    style H3 fill:#f96
```

#### Verification Methods

| Method | Purpose |
|--------|---------|
| `verify()` | Validates chain integrity |
| `toJSON()` | Exports audit log for storage |
| `replay()` | Reconstructs deterministic state |

资料来源：[CHANGELOG.md]()

### 4. Article 12 Bundle

The `buildArticle12Bundle()` function generates regulator-handable documentation for EU AI Act compliance.

```typescript
interface Article12Bundle {
  charter: Charter;
  result: FiscalGateResult;
  audit: MerkleAudit;
  
  // Output files
  mission: string;      // mission.json
  events: string;      // events.json
  eventsCsv: string;   // events.csv
  chain: string;       // chain.txt
  manifest: {
    checksums: Record<string, string>;
    retention: {
      policy: string;
      expiresAt: string;
    };
  };
}
```

#### Default Retention Policy

| Jurisdiction | Retention Period | Legal Basis |
|--------------|------------------|-------------|
| European Union | 6 months | EU AI Act Article 12 |
| Default | 6 months | EU AI Act Article 12 |

资料来源：[CHANGELOG.md](), [src/governance/article12.ts](), [src/governance/policies/eu-ai-act.ts]()

### 5. PaymentsAdapter

A pluggable interface for payment processing backends.

```typescript
interface PaymentsAdapter {
  charge(amount: number, currency: string): Promise<ChargeResult>;
  settle(transactionId: string): Promise<SettleResult>;
  refund(transactionId: string): Promise<RefundResult>;
  getBalance(): Promise<Balance>;
}

class MockPayments implements PaymentsAdapter {
  // Reference implementation for testing
}
```

#### Built-in Implementations

| Implementation | Use Case |
|---------------|----------|
| `MockPayments` | Unit testing, development |
| `StripePaymentsAdapter` | Production (global) |
| `PaystackPaymentsAdapter` | Production (Africa) |
| `LightningPaymentsAdapter` | Production (micropayments) |

资料来源：[CHANGELOG.md](), [src/governance/payments.ts]()

## API Reference

### Functions

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

Validates a charter declaration before mission execution.

| Parameter | Type | Description |
|-----------|------|-------------|
| `charter` | `Charter` | Mission charter to validate |
| **Returns** | `ValidationResult` | Contains `valid: boolean` and optional `errors: string[]` |

#### `runMission(ctx: MissionContext): Promise<FiscalGateResult>`

Executes an agent mission with budget enforcement.

```typescript
interface MissionContext {
  charter: Charter;
  agentLoop: () => Promise<void>;
  onOperation?: (op: Operation) => void;
}

interface FiscalGateResult {
  status: "ok" | "halted" | "error";
  spentUsd: number;
  outputs: any[];
  auditDigest: string;
  terminatedAt?: Date;
  error?: string;
}
```

#### `buildArticle12Bundle(params: BundleParams): Article12Bundle`

Generates a regulatory audit bundle.

| Parameter | Type | Description |
|-----------|------|-------------|
| `params.charter` | `Charter` | Mission charter |
| `params.result` | `FiscalGateResult` | Mission execution result |
| `params.audit` | `MerkleAudit` | Audit log |

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

Creates a new audit chain instance.

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `chainId` | `string` | Auto-generated | Unique chain identifier |
| `events` | `AuditEvent[]` | `[]` | Initial events |
| `retentionDays` | `number` | `180` | Log retention period |

资料来源：[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

```typescript
// 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"
  ]
};
```

资料来源：[src/governance/policies/eu-ai-act.ts]()

## Testing

The governance module includes comprehensive test coverage in `tests/governance.spec.ts`:

| Test Category | Coverage |
|---------------|----------|
| Charter validation | Valid/invalid charter scenarios |
| MerkleAudit chain | Hash linking, tamper detection |
| FiscalGate paths | Happy path, halt, error scenarios |
| Article 12 bundle | File generation, checksum validation |

资料来源：[CHANGELOG.md]()

## Usage Example

```typescript
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.

---

<a id='merkle-audit'></a>

## MerkleAudit & Hash-Chained Ledger

### 相关页面

相关主题：[Charter & FiscalGate Governance](#charter-fiscalgate), [Core Modules Reference](#core-modules)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [src/governance/audit-chain.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/governance/audit-chain.ts)
- [src/governance/audit.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/governance/audit.ts)
- [src/integrity.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/integrity.ts)
- [src/ledger.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/ledger.ts)
- [tests/governance.spec.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/tests/governance.spec.ts)
</details>

# 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

资料来源：[CHANGELOG.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/CHANGELOG.md)

## Architecture

The integrity system consists of three independent layers working in concert:

```mermaid
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.

资料来源：[site/index.html](https://github.com/mnemopay/mnemopay-sdk/blob/main/site/index.html)

### Layer 2: Merkle Integrity on Memories

The MerkleAudit system provides Merkle tree-based verification for agent memories, ensuring that stored memory states can be cryptographically verified.

### Layer 3: HMAC on Transactions

Transaction-level HMAC-SHA512 security provides an additional verification layer for financial operations.

## MerkleAudit System

### Core Components

| Component | Purpose |
|-----------|---------|
| `audit-chain.ts` | SHA-256 chained event log implementation |
| `audit.ts` | Core audit primitives and verification |
| `verify()` | Chain integrity verification method |
| `toJSON()` | Serialization for audit export |
| Listeners | Real-time event subscription system |
| Deterministic Replay | Reproducible audit reconstruction |

资料来源：[CHANGELOG.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/CHANGELOG.md)

### Event Log Structure

The MerkleAudit system maintains a sequentially chained event log where each event contains:

```mermaid
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:

```mermaid
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

| Feature | Description |
|---------|-------------|
| Hash Algorithm | SHA-256 |
| Chain Structure | Each entry references previous entry's hash |
| Detection | Any modification breaks the chain instantly |
| Verification | Sequential hash recomputation and comparison |

资料来源：[site/index.html](https://github.com/mnemopay/mnemopay-sdk/blob/main/site/index.html)

### Transaction Flow

```mermaid
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.

| Parameter | Type | Description |
|-----------|------|-------------|
| `startIndex` | `number` | Optional starting point for verification |
| `endIndex` | `number` | Optional ending point for verification |

#### `toJSON()`

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

| Parameter | Type | Description |
|-----------|------|-------------|
| `compact` | `boolean` | Optional compact representation |

### Ledger Methods

#### Transaction Operations

| Method | Purpose |
|--------|---------|
| `charge()` | Initiate a charge with escrow hold |
| `settle()` | Release escrowed funds |
| `refund()` | Process a refund transaction |
| `dispute()` | Open a dispute on a transaction |

资料来源：[site/index.legacy.html](https://github.com/mnemopay/mnemopay-sdk/blob/main/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

资料来源：[CHANGELOG.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/CHANGELOG.md)

### Test Categories

| Category | Coverage |
|----------|----------|
| Chain Integrity | Verification of unbroken hash chain |
| Tamper Detection | Detection of modified entries |
| Replay Accuracy | Deterministic replay verification |
| Listener Events | Real-time notification testing |

## Integration with Governance Module

MerkleAudit integrates deeply with the Governance module:

### Article 12 Compliance

The system supports EU AI Act Article 12 audit requirements:

- **6-month default retention** period
- **Deterministic SHA-256 digest** for tamper detection
- **Compliance bundle generation** via `buildArticle12Bundle()`

### Audit Bundle Structure

When generating Article 12 compliance bundles:

```mermaid
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 Vector | Detection Mechanism |
|---------------|---------------------|
| Single Entry Modification | SHA-256 hash mismatch |
| Chain Reordering | Sequential link validation |
| Entry Deletion | Hash chain break detection |
| Memory Manipulation | Merkle tree verification |

### Cryptographic Guarantees

- **Pre-image Resistance**: Cannot derive previous entries from current hash
- **Collision Resistance**: Cannot find two events with same hash
- **Chain Binding**: Each entry cryptographically bound to all predecessors

## Best Practices

### Audit Trail Maintenance

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.

资料来源：[site/index.html](https://github.com/mnemopay/mnemopay-sdk/blob/main/site/index.html)

---

<a id='identity-kya'></a>

## Identity & KYA Compliance

### 相关页面

相关主题：[Charter & FiscalGate Governance](#charter-fiscalgate)

<details>
<summary>Relevant Source Files</summary>

The following source files were retrieved and used to generate this documentation:

- [dashboard/index.html](https://github.com/mnemopay/mnemopay-sdk/blob/main/dashboard/index.html)
- [README.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/README.md)

Note: The identity module source files (`src/identity/index.ts`, `src/identity/wallet.ts`, `src/identity/bundle.ts`, `src/identity/did.ts`) referenced in the task were not available in the retrieved repository context. This documentation is based on the architectural references and dashboard implementation found in the available context.
</details>

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

资料来源：[README.md:1-50]()

## Architecture

```mermaid
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.

| Component | Description |
|-----------|-------------|
| `session.session?.accountId` | Unique account identifier for the authenticated agent |
| `session.session?.email` | Associated email for the session |
| `session.authenticated` | Boolean flag indicating authentication status |
| `onLogin` | Callback function for session authentication |
| `onLogout` | Callback function for session termination |

资料来源：[dashboard/index.html:200-230]()

#### Session State Display

The dashboard conditionally renders session status based on authentication state:

```tsx
{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>
)}
```

资料来源：[dashboard/index.html:150-170]()

### Permission Controls

The permission system gates critical financial operations. Agents must have appropriate permissions before executing `charge()`, `settle()`, or `refund()` operations.

| Permission Type | Purpose |
|-----------------|---------|
| Charge Permission | Allows agent to initiate payment collection |
| Settle Permission | Allows agent to release escrowed funds |
| Refund Permission | Allows agent to process refunds |
| Admin Permission | Allows management of API keys and billing |

### Killswitch

The killswitch mechanism provides emergency shutdown capability for agent operations. When triggered, it immediately revokes all active permissions and halts pending transactions.

```mermaid
graph LR
    A[Anomaly Detected] --> B{Killswitch Active?}
    B -->|Yes| C[Revoke All Permissions]
    B -->|No| D[Log Warning]
    C --> E[Cancel Pending Transactions]
    E --> F[Notify Compliance System]
```

### Token Economy

The Identity module integrates with MnemoPay's token-based economy:

| Parameter | Value | Description |
|-----------|-------|-------------|
| Ceiling | `500 × reputation` | Maximum charge per transaction |
| Decay | 0.05 | Half-life approximately 14 hours |
| Feedback Loop | +0.05 | Importance reinforcement on settle |

资料来源：[dashboard/index.html:350-360]()

## Compliance Workflow

```mermaid
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:

```tsx
{tab === 'session' && <SessionPanel 
  session={session} 
  accountId={accountId} 
  members={overview?.members || []} 
  onLogin={loginSession} 
  onLogout={logoutSession} 
  onRefresh={fetchAll} 
/>}
```

资料来源：[dashboard/index.html:400-410]()

### Available Controls

| Control | Function |
|---------|----------|
| Account ID Input | Specify target account for session operations |
| Refresh Button | Fetch latest session and compliance status |
| Login | Authenticate and establish session |
| Logout | Terminate session and clear credentials |
| Members List | View team members with identity status |

## Developer API Keys

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

| Feature | Description |
|---------|-------------|
| List Keys | View all active API keys for the account |
| Create Key | Generate new provisioning secret |
| Revoke Key | Immediately invalidate an existing key |

资料来源：[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

资料来源：[README.md:1-30]()

## Billing & Compliance Metrics

The Billing Panel displays compliance-related metrics:

| Metric | Description |
|--------|-------------|
| Missions | Current period transaction count |
| Seats | Active agent identities under management |
| Plan Gate | Compliance status (Active/Limit Reached) |
| Over Limit | Boolean indicating if usage exceeds plan |

资料来源：[dashboard/index.html:320-340]()

## Related Documentation

- [Agent Credit Score](https://github.com/mnemopay/mnemopay-sdk) — Agent scoring for compliance gating
- [Behavioral Finance](https://github.com/mnemopay/mnemopay-sdk) — Prospect theory and nudge mechanisms
- [Anomaly Detection](https://github.com/mnemopay/mnemopay-sdk) — EWMA and fingerprinting systems
- [Audit Trail](https://github.com/mnemopay/mnemopay-sdk) — Ledger health and compliance logging

---

---

## Doramagic 踩坑日志

项目：mnemopay/mnemopay-sdk

摘要：发现 8 个潜在踩坑项，其中 1 个为 high/blocking；最高优先级：安全/权限坑 - 涉及密钥、隐私或敏感领域。

## 1. 安全/权限坑 · 涉及密钥、隐私或敏感领域

- 严重度：high
- 证据强度：source_linked
- 发现：项目文本出现 secret/private key/privacy/trading/finance 等敏感关键词。
- 对用户的影响：金融、交易、隐私和密钥场景必须比普通工具更保守。
- 建议检查：补敏感数据流、密钥存储和权限边界审查。
- 防护动作：敏感领域或密钥场景必须保守推荐并要求人工复核。
- 证据：packet_text.keyword_scan | github_repo:1197975871 | https://github.com/mnemopay/mnemopay-sdk | matched secret / private key / privacy / trading / finance keyword

## 2. 身份坑 · 仓库名和安装名不一致

- 严重度：medium
- 证据强度：runtime_trace
- 发现：仓库名 `mnemopay-sdk` 与安装入口 `@mnemopay/sdk` 不完全一致。
- 对用户的影响：用户照着仓库名搜索包或照着包名找仓库时容易走错入口。
- 建议检查：在 npm/PyPI/GitHub 上确认包名映射和官方 README 说明。
- 复现命令：`npm install @mnemopay/sdk`
- 防护动作：页面必须同时展示 repo 名和真实安装入口，避免用户搜索错包。
- 证据：identity.distribution | github_repo:1197975871 | https://github.com/mnemopay/mnemopay-sdk | repo=mnemopay-sdk; install=@mnemopay/sdk

## 3. 能力坑 · 能力判断依赖假设

- 严重度：medium
- 证据强度：source_linked
- 发现：README/documentation is current enough for a first validation pass.
- 对用户的影响：假设不成立时，用户拿不到承诺的能力。
- 建议检查：将假设转成下游验证清单。
- 防护动作：假设必须转成验证项；没有验证结果前不能写成事实。
- 证据：capability.assumptions | github_repo:1197975871 | https://github.com/mnemopay/mnemopay-sdk | README/documentation is current enough for a first validation pass.

## 4. 维护坑 · 维护活跃度未知

- 严重度：medium
- 证据强度：source_linked
- 发现：未记录 last_activity_observed。
- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。
- 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。
- 防护动作：维护活跃度未知时，推荐强度不能标为高信任。
- 证据：evidence.maintainer_signals | github_repo:1197975871 | https://github.com/mnemopay/mnemopay-sdk | last_activity_observed missing

## 5. 安全/权限坑 · 下游验证发现风险项

- 严重度：medium
- 证据强度：source_linked
- 发现：no_demo
- 对用户的影响：下游已经要求复核，不能在页面中弱化。
- 建议检查：进入安全/权限治理复核队列。
- 防护动作：下游风险存在时必须保持 review/recommendation 降级。
- 证据：downstream_validation.risk_items | github_repo:1197975871 | https://github.com/mnemopay/mnemopay-sdk | no_demo; severity=medium

## 6. 安全/权限坑 · 存在评分风险

- 严重度：medium
- 证据强度：source_linked
- 发现：no_demo
- 对用户的影响：风险会影响是否适合普通用户安装。
- 建议检查：把风险写入边界卡，并确认是否需要人工复核。
- 防护动作：评分风险必须进入边界卡，不能只作为内部分数。
- 证据：risks.scoring_risks | github_repo:1197975871 | https://github.com/mnemopay/mnemopay-sdk | no_demo; severity=medium

## 7. 维护坑 · issue/PR 响应质量未知

- 严重度：low
- 证据强度：source_linked
- 发现：issue_or_pr_quality=unknown。
- 对用户的影响：用户无法判断遇到问题后是否有人维护。
- 建议检查：抽样最近 issue/PR，判断是否长期无人处理。
- 防护动作：issue/PR 响应未知时，必须提示维护风险。
- 证据：evidence.maintainer_signals | github_repo:1197975871 | https://github.com/mnemopay/mnemopay-sdk | issue_or_pr_quality=unknown

## 8. 维护坑 · 发布节奏不明确

- 严重度：low
- 证据强度：source_linked
- 发现：release_recency=unknown。
- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。
- 建议检查：确认最近 release/tag 和 README 安装命令是否一致。
- 防护动作：发布节奏未知或过期时，安装说明必须标注可能漂移。
- 证据：evidence.maintainer_signals | github_repo:1197975871 | https://github.com/mnemopay/mnemopay-sdk | release_recency=unknown

<!-- canonical_name: mnemopay/mnemopay-sdk; human_manual_source: deepwiki_human_wiki -->
