Metadata-Version: 2.4
Name: langchain-x402-nano
Version: 0.1.0
Summary: LangChain tool: pay x402 'exact' quotes on nano:mainnet (XNO) behind an offline-tested payment guard
Project-URL: Homepage, https://github.com/legalmoneyheist/langchain-nano-x402
Project-URL: Source, https://github.com/legalmoneyheist/langchain-nano-x402
Author: langchain-x402-nano contributors
License-Expression: MIT
License-File: LICENSE
Keywords: agents,langchain,langgraph,nano,payments,tool,x402,xno
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Internet :: WWW/HTTP
Classifier: Topic :: Office/Business :: Financial
Requires-Python: <3.14,>=3.11
Requires-Dist: langchain-core==1.7.2
Requires-Dist: langchain==1.4.7
Requires-Dist: langgraph-prebuilt==1.1.1
Requires-Dist: langgraph==1.2.18
Requires-Dist: nanopy==28.0.1.post26
Requires-Dist: requests==2.33.0
Requires-Dist: x402-nano-exact==0.1.2
Provides-Extra: test
Requires-Dist: pytest==9.2.0; extra == 'test'
Description-Content-Type: text/markdown

# langchain-x402-nano

A native [LangChain](https://pypi.org/project/langchain/) tool that lets an agent pay for HTTP
resources with **x402 `exact` on `nano:mainnet`** (XNO). A payment guard runs before anything is signed.

The tool is `nano_x402_pay`, a `langchain_core.tools.BaseTool` (`langchain_x402_nano.NanoX402PayTool`).
Give it to any LangChain agent: `create_agent(model, tools=[NanoX402PayTool()])`.

* Pinned: `langchain==1.4.7`, `langchain-core==1.7.2`, `langgraph==1.2.18`, `langgraph-prebuilt==1.1.1`,
  `nanopy==28.0.1.post26` (block building, blake2b, ed25519, CPU work), `x402-nano-exact==0.1.2`
  (scheme constants and address validation), `requests==2.33.0`. Python 3.11–3.13.
* Wire format: reads the base64 `PAYMENT-REQUIRED` header (or the body's `x402` field). It answers with
  `PAYMENT-SIGNATURE` = base64 `{x402Version: 2, resource, accepted, payload: {block}}` and decodes
  `PAYMENT-RESPONSE`.
* Signing: a real Nano state send block signed with ed25519 by `nanopy`, from the key in the environment
  (or a signer the operator injects). No placeholder signer.
* Proof of work: when `extra.workOptional` is not `true` (false or absent), work for the block's
  `previous` at `extra.workThreshold` is attached. The threshold is never easier than the send threshold.
  Work comes from `NANO_WORK_URL` (node-RPC `work_generate` shape) if set, else is computed locally.
  When `workOptional` is `true`, the placeholder `0000000000000000` is sent.

## Install (one command, no install scripts)

```sh
pip install --only-binary :all: "langchain-x402-nano[test]==0.1.0"
```

`--only-binary :all:` installs wheels only, so no package build or install script runs. Every
dependency ships a wheel. With uv: `uv pip install --no-build "langchain-x402-nano[test]==0.1.0"`.

## Configure (environment only; nothing secret is in the package)

| variable | meaning |
|---|---|
| `NANO_SEED` (+ `NANO_INDEX`, default 0) or `NANO_PRIVATE_KEY` | the paying account. Read lazily, never logged, printed or returned |
| `NANO_X402_ALLOWED_PAYTO` | comma list of `payTo` addresses that may be paid. **Empty = every payment refused** |
| `NANO_X402_MAX_PER_CALL_XNO` | per-call cap, default `0.001` |
| `NANO_X402_MAX_TOTAL_XNO` | cumulative cap for this process, default `0.01` |
| `NANO_X402_ALLOWED_ORIGINS` | optional comma list of origins that may be paid |
| `NANO_RPC` / `NANO_ACCOUNT_INFO_API` | where the confirmed frontier and balance are read: a node RPC, else `https://pursekeeper.dev/v1/account_info` |
| `NANO_WORK_URL` | optional work server; local CPU otherwise (`NANO_WORK_LOCAL=0` disables local work) |

You can inject a signer instead of using the environment: build `NanoX402Client(policy, signer=...)` with
any object that has `.address` and `.sign_send(state, pay_to, amount_raw, work)`, then use
`NanoX402PayTool(client=...)` (or `langchain_x402_nano.set_shared_client(...)`). Every `NanoX402PayTool()`
without a client shares one env-configured client per process, so the cumulative cap covers all of them.

A fresh account has to receive (open) before it can send. After funding the address, run
`langchain-x402-nano-receive` once. It publishes receive/open blocks only and never sends.

## Example: one paid call from LangChain's agent loop (Ӿ0.001 at pursekeeper.dev)

```sh
export NANO_SEED=...   # throwaway wallet, funded with ~Ӿ0.01 and opened
export NANO_X402_ALLOWED_PAYTO=nano_1xug1q5t7nxoj3ywwzokiea9jz8fq8qfgzp8pbyfr3co3e5xgj755uofu8ue
langchain-x402-nano-demo https://pursekeeper.dev/v1/hash --method POST --body hello
```

`langchain-x402-nano-demo` (source: `langchain_x402_nano/agent_example.py`) is, in short:

```python
from langchain.agents import create_agent
from langchain_x402_nano import NanoX402PayTool
from langchain_x402_nano.scripted_model import ScriptedToolCallModel

model = ScriptedToolCallModel(tool_args={"url": "https://pursekeeper.dev/v1/hash",
                                         "method": "POST", "body": "hello", "content_type": "text/plain"})
agent = create_agent(model, tools=[NanoX402PayTool()])
state = agent.invoke({"messages": [{"role": "user", "content": "Fetch https://pursekeeper.dev/v1/hash ..."}]})
print(state["messages"][-1].content)
```

LangChain's own `create_agent` loop (LangGraph) binds the tool to the model (`bind_tools`), runs the
model's tool call through its tool node and feeds the result back to the model for the final answer.
By default the model is `ScriptedToolCallModel`, a local `BaseChatModel` that supports `bind_tools`, so
no LLM key is needed: its first turn calls `nano_x402_pay` once, its second reports the result. To let
a real model decide, pass `--model provider:name` (e.g. `--model openai:gpt-4.1-mini`, with
`langchain-openai` installed and `OPENAI_API_KEY` set). The demo prints the status, amount, block hash
and body. It exits 0 only when the paid request returned 2xx.

Also free to try: `langchain-x402-nano-demo "https://pursekeeper.dev/v1/fetch?url=https://example.com" --method GET`.

## The guard (all before signing)

1. scheme `exact` on `nano:mainnet`, asset `XNO`; anything else → `wrong_network`
2. `payTo` must be in `NANO_X402_ALLOWED_PAYTO`; an empty allowlist fails closed → `pay_to_not_allowed`
3. amount ≤ per-call cap → `over_per_call_cap`
4. spent + reserved + amount ≤ cumulative cap (in memory, per process; a signed block always counts) → `over_total_cap`
5. a request already reserved or signed (same `request_id`, or same method + URL + body) is never signed again → `duplicate_request`
6. redirects: an unsigned probe follows same-origin redirects only; a cross-origin redirect stops the call unpaid
   (`cross_origin_redirect`); the signed request goes to the URL that answered 402 with redirects off; a quote whose
   `resource.url` names another origin is refused
7. malformed quotes (wrong `x402Version`, bad base64/JSON, missing or non-integer amount, bad `payTo`, bad
   `maxTimeoutSeconds`, `extra` or `workThreshold`) → `malformed_quote`
8. freshness: if the quote is older than `maxTimeoutSeconds` (less a 2 s margin) when it is time to sign, it is thrown
   away and re-fetched, and the new quote goes through the guard again; a quote is never re-used
9. one send block per call, built from the **confirmed** frontier (an unconfirmed frontier is refused), with
   `balance = balance − amount` and `link = payTo`
10. no automatic paid retry: a non-2xx (or a network error) after the payment is returned to the agent with the block hash.
    A 402 "not confirmed" answer is returned, not re-presented

## Offline tests

```sh
python -m pytest -p no:cacheprovider --pyargs langchain_x402_nano.tests
```

The tests ship inside the package (from a checkout, `python -m pytest` also works). They make no network
connections (any non-loopback `connect` fails the test) and use a mocked 402 seller. They cover every
guard rule above, block correctness (hash and signature), the PoW paths, the receive command, the tool's
LangChain schema, and full `create_agent` runs through the scripted model (the tool is called exactly once
and one block is signed). They also check that the seed and key appear in no tool output, log or captured stream.

## Licence

MIT
