Skip to content

docs(sdk): add D402 agent-payment cookbook (HTTP-402 settlement loop)#8

Open
cX3po wants to merge 2 commits into
kynesyslabs:mainfrom
cX3po:add-d402-cookbook
Open

docs(sdk): add D402 agent-payment cookbook (HTTP-402 settlement loop)#8
cX3po wants to merge 2 commits into
kynesyslabs:mainfrom
cX3po:add-d402-cookbook

Conversation

@cX3po

@cX3po cX3po commented Jun 1, 2026

Copy link
Copy Markdown

Why. D402 ships as a public SDK export (@kynesyslabs/demosdk/d402, /d402/server, /d402/client) but has no docs page — builders have no guide to the 402 → pay → X-Payment-Proof → verify loop. This adds a complete cookbook page: server d402Required middleware (all options), client D402Client flow, the round-trip + on-chain verification, error handling, and a denomination <Note> (OS_PER_DEM = 10^9 — the page deliberately avoids the 10^18 trap that's currently in the middleware JSDoc, see sdks#92).

Section & path. new sdk/cookbook/d402.mdx + nav entry in docs.json (Code Examples group). Verified line-by-line against the live SDK source.

One implementer's contribution from the PATH-OS Labs review pass — happy to adjust tone/placement.

Summary by CodeRabbit

  • Documentation
    • Added comprehensive guide for D402 (Agent Payments over HTTP 402) flow, covering server middleware configuration, client-side payment handling, and transaction verification process.
    • Updated SDK documentation navigation to reflect new payment flow documentation.

@coderabbitai

coderabbitai Bot commented Jun 1, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@cX3po, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 41 minutes and 36 seconds. Learn how PR review limits work.

Your organization has run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 7b792fa3-9281-4657-bf20-79d43103d837

📥 Commits

Reviewing files that changed from the base of the PR and between 4e1ab76 and 1c03ec9.

📒 Files selected for processing (1)
  • sdk/cookbook/d402.mdx

Walkthrough

This PR introduces comprehensive documentation for D402 Agent Payments over HTTP 402. It adds a new documentation page describing the server-side middleware for gating routes with payment requirements and the client-side flow for handling and fulfilling those payments, along with verification logic and error cases. The navigation configuration is updated to surface the new page.

Changes

D402 HTTP 402 Payment Documentation

Layer / File(s) Summary
Navigation and D402 Introduction
docs.json, sdk/cookbook/d402.mdx
Navigation updated to include the D402 page. Documentation frontmatter, concept overview, use-case guidance, installation, and denomination/unit-conversion notes introduced.
Server-Side D402 Integration
sdk/cookbook/d402.mdx
Middleware d402Required documented with options table, basic route-gating example, dynamic per-request recipient configuration, and misconfiguration error handling.
Client-Side D402 Integration
sdk/cookbook/d402.mdx
Client D402Client documented with wallet setup, 402 response parsing, handlePaymentRequired flow, and internal three-step transaction creation, signing, and broadcast process.
Verification Logic, Error Handling, and API Reference
sdk/cookbook/d402.mdx
X-Payment-Proof header format, server-side transaction verification and recipient/amount/memo resource binding, cached/idempotent retry behavior, HTTP error responses, client defensive patterns, and API reference with links to denomination utilities.

🎯 1 (Trivial) | ⏱️ ~5 minutes

🐰 A protocol hops into view,
D402 requests payment true—
Server gates the route with care,
Client settles debts in mid-air,
Verification round-trips through!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title directly and clearly summarizes the main change: adding D402 agent-payment documentation to the SDK cookbook, with HTTP-402 settlement loop context.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@qodo-code-review

Copy link
Copy Markdown

Review Summary by Qodo

Add D402 agent-payment cookbook with HTTP 402 settlement guide

📝 Documentation

Grey Divider

Walkthroughs

Description
• Adds comprehensive D402 cookbook documentation page
• Covers server-side d402Required middleware with all configuration options
• Covers client-side D402Client payment flow and round-trip verification
• Includes denomination guide (OS_PER_DEM = 10^9) to prevent overcharging errors
• Documents error handling, edge cases, and defensive client patterns
• Registers new page in navigation under Code Examples group
Diagram
flowchart LR
  A["D402 Cookbook Page"] --> B["Server: d402Required Middleware"]
  A --> C["Client: D402Client Flow"]
  B --> D["Payment Requirement Challenge"]
  C --> E["Create & Settle Payment"]
  E --> F["Retry with X-Payment-Proof"]
  F --> G["On-Chain Verification"]
  G --> H["Resource Access"]
  A --> I["Denomination Guide: 10^9 OS per DEM"]
  A --> J["Error Handling & Edge Cases"]

Loading

Grey Divider

File Changes

1. docs.json 📝 Documentation +2/-1

Register D402 cookbook page in navigation

• Adds sdk/cookbook/d402 entry to navigation under Code Examples group
• Maintains existing cookbook structure with new D402 page reference

docs.json


2. sdk/cookbook/d402.mdx 📝 Documentation +301/-0

Complete D402 agent-payment cookbook with settlement guide

• New comprehensive cookbook page explaining D402 HTTP 402 payment settlement loop
• Server section: d402Required middleware options, configuration, dynamic recipients, and 402
 challenge format
• Client section: D402Client usage, payment creation, settlement, and lower-level API steps
• Round-trip verification: transaction fetching, on-chain verification, requirement matching, and
 caching
• Critical denomination note: OS_PER_DEM = 10^9 with examples to prevent billion-unit overcharging
• Error handling table covering all HTTP statuses and edge cases with defensive client pattern
• API reference listing server and client exports, types, and related documentation links

sdk/cookbook/d402.mdx


Grey Divider

Qodo Logo

@qodo-code-review

qodo-code-review Bot commented Jun 1, 2026

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (1) 📘 Rule violations (0) 📎 Requirement gaps (0)

Grey Divider


Remediation recommended

1. Amount rule contradicts itself ✓ Resolved 🐞 Bug ≡ Correctness
Description
The D402 cookbook states that the server only calls next() when the payment "matches the
requirement exactly", but later states the amount check is >= and that overpayment is accepted.
This contradiction can mislead integrators about whether overpayment is valid and whether “exact
payment” is required.
Code

sdk/cookbook/d402.mdx[62]

Evidence
Line 62 claims an exact match is required, while later sections explicitly document >= semantics
and acceptance of overpayment, which is logically inconsistent within the same page.

sdk/cookbook/d402.mdx[60-63]
sdk/cookbook/d402.mdx[232-237]
sdk/cookbook/d402.mdx[282-284]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`sdk/cookbook/d402.mdx` contradicts itself about the payment amount rule:
- Early text says the middleware proceeds only when payment “matches … exactly”.
- Later sections describe the rule as `payment >= required` and explicitly say overpayment is accepted.
This inconsistency can cause users to implement incorrect client-side assumptions and can lead to confusion when overpayments are accepted.
### Issue Context
The more detailed verification section and the warning box consistently describe `>=` semantics, so the “exactly” phrasing is the outlier and should be updated (or, if the SDK truly enforces exact-match, then the later `>=` statements should be changed).
### Fix Focus Areas
- sdk/cookbook/d402.mdx[62-62]
- sdk/cookbook/d402.mdx[235-237]
- sdk/cookbook/d402.mdx[282-284]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Advisory comments

2. Missing trailing newline 🐞 Bug ⚙ Maintainability
Description
The newly added sdk/cookbook/d402.mdx does not end with a newline, which commonly creates noisy
diffs and can fail style checks in some tooling.
Code

sdk/cookbook/d402.mdx[R299-301]

Evidence
This is the end of the file; the PR diff flags it as lacking an ending newline.

sdk/cookbook/d402.mdx[299-301]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`sdk/cookbook/d402.mdx` is missing a trailing newline at end-of-file.
### Issue Context
Git marks this as `\ No newline at end of file`, and some formatters/linters enforce POSIX-style trailing newlines.
### Fix Focus Areas
- sdk/cookbook/d402.mdx[299-301]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

Qodo Logo

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
docs.json (1)

220-221: 💤 Low value

Consider grouping standalone cookbook pages for consistency.

The d402 and evm-contract-write-transactions entries are placed at the root level of "Code Examples" alongside group objects like SWAP and Transactions. While valid, this creates a mixed navigation structure. Consider grouping these under a "Recipes" or "Additional Examples" group for consistency, or moving d402 into a "Payments" or "Commerce" group if more payment-related docs are planned.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@docs.json` around lines 220 - 221, The docs.json navigation mixes standalone
entries "sdk/cookbook/d402" and "sdk/cookbook/evm-contract-write-transactions"
with grouped objects under "Code Examples"; to fix, move these two strings into
a new group object (e.g., title "Recipes" or "Additional Examples") or place
"sdk/cookbook/d402" into an existing "Payments"/"Commerce" group so all cookbook
pages follow the same grouped structure; update the "Code Examples" array to
replace the raw strings with the new group object containing these slugs.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@docs.json`:
- Around line 220-221: The docs.json navigation mixes standalone entries
"sdk/cookbook/d402" and "sdk/cookbook/evm-contract-write-transactions" with
grouped objects under "Code Examples"; to fix, move these two strings into a new
group object (e.g., title "Recipes" or "Additional Examples") or place
"sdk/cookbook/d402" into an existing "Payments"/"Commerce" group so all cookbook
pages follow the same grouped structure; update the "Code Examples" array to
replace the raw strings with the new group object containing these slugs.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 3714f55b-83c6-4164-bb4a-e3ff82d2a6f3

📥 Commits

Reviewing files that changed from the base of the PR and between bdee958 and 4e1ab76.

📒 Files selected for processing (2)
  • docs.json
  • sdk/cookbook/d402.mdx

Addresses Qodo review: line 62 said "matches exactly" but validatePayment enforces >= (overpayment accepted). Aligned the intro to the >= semantics documented in the verification section + Warning.
@cX3po

cX3po commented Jun 1, 2026

Copy link
Copy Markdown
Author

Thanks — fixed the contradiction. The intro now matches the >= semantics that validatePayment actually enforces (overpayment accepted, not refunded), consistent with the verification step and the Warning box.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant