Skip to content

feat: @x402/mnemopay — economic memory for AI agent payments#1904

Open
t49qnsx7qt-kpanks wants to merge 1 commit intox402-foundation:mainfrom
t49qnsx7qt-kpanks:feat/mnemopay-middleware
Open

feat: @x402/mnemopay — economic memory for AI agent payments#1904
t49qnsx7qt-kpanks wants to merge 1 commit intox402-foundation:mainfrom
t49qnsx7qt-kpanks:feat/mnemopay-middleware

Conversation

@t49qnsx7qt-kpanks
Copy link
Copy Markdown

@t49qnsx7qt-kpanks t49qnsx7qt-kpanks commented Apr 2, 2026

Summary

AI agents using x402 today are stateless — they pay the 402, get the resource, and immediately forget. They never learn which endpoints are cheap, which are reliable, or which alternatives exist. This PR adds @x402/mnemopay, a middleware package that gives x402 agents economic memory via MnemoPay.

What it does

withMnemoPay() wraps any x402-enabled fetch function and adds four memory operations around each payment:

Phase Action MnemoPay API
Before request Recall past experiences with this endpoint recall()
After 402 payment Record the charge amount charge()
On success Settle — reinforce the positive memory settle() → +reputation
On failure Refund — dock the memory refund() → -reputation

Over time, agents build a knowledge base of endpoint costs, reliability rates, and alternatives — turning every payment into a learning event.

Why this matters

The x402 protocol is uniquely positioned for AI-native commerce. But stateless payments leave value on the table. An agent that remembers its payment history can:

  • Detect price anomalies: "This endpoint usually costs $0.02, but today it's $0.10"
  • Track reliability: "This endpoint fails 40% of the time — prefer the alternative"
  • Build reputation: Agents that make consistently good payment decisions earn higher reputation scores
  • Optimize spend: Over hundreds of API calls, memory-driven agents spend less for the same outcomes

Usage

import { wrapFetchWithPayment } from "@x402/fetch";
import { withMnemoPay } from "@x402/mnemopay";
import { MnemoPayLite } from "@mnemopay/sdk";

const payFetch = wrapFetchWithPayment(fetch, client);
const agent = new MnemoPayLite("my-agent", 0.05);
const smartFetch = withMnemoPay(payFetch, { agent });

// Agent now remembers every payment outcome
const response = await smartFetch("https://api.example.com/paid-endpoint");

Package details

  • Located at typescript/packages/http/mnemopay/
  • Follows existing x402 package conventions (tsup, vitest, eslint config)
  • @mnemopay/sdk is a peer dependency — no new runtime deps in x402 core
  • Defines a MnemoPayAgent interface so users can bring their own implementation
  • 14 tests covering success/failure flows, graceful degradation, and edge cases
  • Zero impact on existing packages — purely additive

Test plan

  • Verify withMnemoPay() passes through non-402 responses unchanged
  • Verify recall() is called before each request with the endpoint URL
  • Verify settle() is called on successful payments
  • Verify refund() is called on failed payments
  • Verify memory/recall failures don't break the payment flow (graceful degradation)
  • Verify the package builds with tsup and follows the existing dual CJS/ESM export pattern
  • Verify compatibility with @x402/fetch and @x402/axios wrapped functions

🤖 Generated with Claude Code

Live Demo

Try it now: https://t49qnsx7qt-kpanks.github.io/mnemopay-demo/

The Feedback Loop in 30 Seconds

Round 1: Agent has NO memory. Picks randomly.
  -> Hired Alice $80. Fast but buggy.
  -> Settled. Reputation: 0.51 | Memories: 1

Round 2: Agent tries Bob.
  -> Hired Bob $120. Perfect quality, on time.
  -> Settled. Reputation: 0.52 | Memories: 2

Round 3: Agent tries Carol.
  -> Hired Carol $95. Missed deadline by 3 days.
  -> REFUNDED. Reputation: 0.52 | Memories: 3

=== Agent recalls before Round 4 ===

  1. [score: 0.900] Carol missed deadline — refund (high importance, decaying)
  2. [score: 0.750] Bob: perfect quality, on time (reinforced by settle)
  3. [score: 0.600] Alice: fast but buggy (neutral)

Result: Agent now picks Bob. No LLM needed for this insight.
settle() reinforced the memory. refund() flagged the failure.
This IS the MnemoPay feedback loop.

How it works

Payment succeeds → settle() → memories that led to decision get +0.05 importance
Payment fails    → refund() → agent reputation docked -0.05
                 → high-importance failure memory stored
Over time        → agent consistently picks best value providers

5-line integration

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

const agent = MnemoPay.quick('my-agent');
await agent.remember('Bob delivers perfect code');
const tx = await agent.charge(120, 'landing page');
await agent.settle(tx.id); // memories reinforced, reputation +0.01

AI agents using x402 today are stateless — they pay and forget. This package
layers MnemoPay's economic memory on top of x402 payment flows so agents
remember costs, track endpoint reliability, and build reputation from
real payment outcomes.

- withMnemoPay() wraps any x402-enabled fetch with memory operations
- Before each request: recall() checks past payment experiences
- On success: settle() reinforces the positive memory (+reputation)
- On failure: refund() docks the memory (-reputation)
- recallEndpointInsight() surfaces cost history and success rates
- Full test suite with 14 tests covering all payment flow paths
- Follows existing x402 package structure (tsup, vitest, eslint)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
@cb-heimdall
Copy link
Copy Markdown

cb-heimdall commented Apr 2, 2026

🟡 Heimdall Review Status

Requirement Status More Info
Reviews 🟡 0/1
Denominator calculation
Show calculation
1 if user is bot 0
1 if user is external 0
2 if repo is sensitive 0
From .codeflow.yml 1
Additional review requirements
Show calculation
Max 0
0
From CODEOWNERS 0
Global minimum 0
Max 1
1
1 if commit is unverified 1
Sum 2

@vercel
Copy link
Copy Markdown

vercel bot commented Apr 2, 2026

@t49qnsx7qt-kpanks is attempting to deploy a commit to the Coinbase Team on Vercel.

A member of the Team first needs to authorize it.

@github-actions github-actions bot added typescript sdk Changes to core v2 packages labels Apr 2, 2026
@t49qnsx7qt-kpanks
Copy link
Copy Markdown
Author

Hey team! Added a live interactive demo to the PR description: try it here. It shows the feedback loop in action — an agent hiring freelancers, learning from settlements and refunds, and consistently picking the best value by round 7-8. The core idea: settle() reinforces the memories that led to good decisions, refund() flags failures. Over time, the agent develops economic intuition without any LLM reasoning needed. Happy to walk through the implementation or answer any questions!

@postmode
Copy link
Copy Markdown

postmode commented Apr 2, 2026

One pattern we're exploring for agent-to-agent payment contexts: if the payer agent is operating through a managed custody layer (rather than controlling its own signing key), the PAYMENT-SIGNATURE header is technically signed by the custodian infrastructure, not the agent's x402 identity. This creates an attribution gap where the payment is valid on-chain but the agent's reputation history in ERC-8004 doesn't accrue correctly.
Wondering if the facilitator spec has a path for delegated signing authority, or if this is considered an application-layer concern. Would affect how managed wallet providers integrate.

@t49qnsx7qt-kpanks
Copy link
Copy Markdown
Author

@postmode Great question — this is exactly the kind of edge case that matters for production agent deployments.

Short answer: MnemoPay sidesteps this problem by design. The wallet is agent-local, not custodial — the agent holds its own signing key and produces the PAYMENT-SIGNATURE header directly. There is no custodian infrastructure in the signing path, so the on-chain identity and the reputation identity are always the same address.

Here is how the pieces fit together:

  1. Agent-local wallet. Each agent manages its own key. The x402 facilitator sees the agent's address as the payer, and MnemoPay's reputation ledger maps to that same address. No attribution gap.

  2. Reputation-gated limits. Rather than relying on a custodian to enforce spending policy, MnemoPay uses a reputation score (0.0–1.0) that gates transaction limits. A freshly provisioned agent starts with low limits; the score increases through successful settlements and decays on refunds/disputes. This is the trust layer, not a custody layer.

  3. Fraud detection before signing. Before the agent ever signs a payment, MnemoPay's fraud detection checks velocity, amount anomalies, and counterparty history. This provides the guardrails that managed custody typically offers, without moving the signing authority off the agent.

  4. x402 handles settlement. The actual on-chain settlement goes through the x402 payment protocol as specified. MnemoPay adds the memory/reputation layer on top — it records which payments led to good outcomes (settle() reinforces the associated memories) and which did not (refund() flags them). Over time this gives the agent economic intuition about which counterparties and price points to trust.

For the managed-custody pattern you describe, the attribution gap is real and I think it is fundamentally a facilitator-spec concern — the spec would need a way to bind a delegated signer to the logical agent identity (something like an X-Agent-Identity header that the custodian cosigns). That said, MnemoPay's architecture intentionally avoids this by keeping signing authority with the agent. If a deployment requires managed custody for regulatory or operational reasons, the reputation layer could still work as long as the facilitator can map the custodian's signature back to the originating agent — but that mapping would need to live in the x402 spec, not in MnemoPay.

Happy to dig deeper on any of this.

@postmode
Copy link
Copy Markdown

postmode commented Apr 3, 2026

@postmode Great question — this is exactly the kind of edge case that matters for production agent deployments.

Short answer: MnemoPay sidesteps this problem by design. The wallet is agent-local, not custodial — the agent holds its own signing key and produces the PAYMENT-SIGNATURE header directly. There is no custodian infrastructure in the signing path, so the on-chain identity and the reputation identity are always the same address.

Here is how the pieces fit together:

  1. Agent-local wallet. Each agent manages its own key. The x402 facilitator sees the agent's address as the payer, and MnemoPay's reputation ledger maps to that same address. No attribution gap.
  2. Reputation-gated limits. Rather than relying on a custodian to enforce spending policy, MnemoPay uses a reputation score (0.0–1.0) that gates transaction limits. A freshly provisioned agent starts with low limits; the score increases through successful settlements and decays on refunds/disputes. This is the trust layer, not a custody layer.
  3. Fraud detection before signing. Before the agent ever signs a payment, MnemoPay's fraud detection checks velocity, amount anomalies, and counterparty history. This provides the guardrails that managed custody typically offers, without moving the signing authority off the agent.
  4. x402 handles settlement. The actual on-chain settlement goes through the x402 payment protocol as specified. MnemoPay adds the memory/reputation layer on top — it records which payments led to good outcomes (settle() reinforces the associated memories) and which did not (refund() flags them). Over time this gives the agent economic intuition about which counterparties and price points to trust.

For the managed-custody pattern you describe, the attribution gap is real and I think it is fundamentally a facilitator-spec concern — the spec would need a way to bind a delegated signer to the logical agent identity (something like an X-Agent-Identity header that the custodian cosigns). That said, MnemoPay's architecture intentionally avoids this by keeping signing authority with the agent. If a deployment requires managed custody for regulatory or operational reasons, the reputation layer could still work as long as the facilitator can map the custodian's signature back to the originating agent — but that mapping would need to live in the x402 spec, not in MnemoPay.

Happy to dig deeper on any of this.

Hey — thanks for the context on the issue thread. Building the financial infrastructure layer for agent deployers — custody, yield routing, and ERC-8004 reputation signals as a managed service. The x402 + ERC-8004 combination is exactly the rail we're building on. Would love 20 minutes at some point — specifically interested in who in the Coinbase ecosystem you think is doing the most serious infrastructure work on x402 right now. Happy to share what we're building in exchange.

@t49qnsx7qt-kpanks
Copy link
Copy Markdown
Author

t49qnsx7qt-kpanks commented Apr 3, 2026

@postmode — custody + yield routing + ERC-8004 reputation as a managed service is a compelling stack. That's essentially the infrastructure layer that makes agent-local signing practical at scale, which is the exact gap between "works in a demo" and "works in production."

Would love to do the 20 minutes. I'm flexible on timing — drop a Calendly link or propose a couple of slots and I'll lock one in.

On the Coinbase ecosystem question — happy to share what I've seen from working through this PR and the x402 spec. There are a few teams doing interesting things on the facilitator side that would be worth discussing live rather than in a comment thread.

Likewise keen to hear how you're thinking about the custody-to-reputation mapping. Your original question about the attribution gap when a custodian signs on behalf of an agent is the right problem — if you're building the managed custody layer, you're in the best position to define how that delegation gets expressed in the payment header. That could be a useful input to the x402 spec itself.

Looking forward to it.

@postmode
Copy link
Copy Markdown

postmode commented Apr 4, 2026 via email

@t49qnsx7qt-kpanks
Copy link
Copy Markdown
Author

Hey @postmode -- following up on your note about custodial signing, ERC-8004 reputation signals, and MnemoPay integration. Really interested in exploring how ERC-8004's reputation framework could complement MnemoPay's trust scoring on the payment side.

Happy to do that 20-minute call today (April 4) if your schedule allows. Feel free to DM me on X (@jerryomiagbo) or shoot me an email at jerry@mnemopay.com and we can lock in a time that works for you.

Looking forward to it!

-- Jerry Omiagbo, MnemoPay

@t49qnsx7qt-kpanks
Copy link
Copy Markdown
Author

Quick correction on my contact info above — best way to reach me is jeremiah@getbizsuite.com. Looking forward to connecting today, @postmode.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

sdk Changes to core v2 packages typescript

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants