Skip to content

Commit 8be80a2

Browse files
Add @sei-js/x402 docs (#278)
* Add @sei-js/x402 docs - Copied over the docs from the main x402 repo, added pages for each facilitator, and improved the flow of the files. * Fixed issues in quickstart - Added dotenv as a parameter - Fixed incorrect port - Fixed unclosed object * Update docs/x402/packages/x402-express.mdx Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update docs/x402/quickstart.mdx Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Added Environment variables to prerequisites on quickstart * Fixed network names --------- Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
1 parent 0707a2e commit 8be80a2

13 files changed

Lines changed: 1527 additions & 0 deletions

File tree

docs/docs.json

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,36 @@
130130
"description": "Hardware wallet connection",
131131
"icon": "shield",
132132
"pages": ["ledger/introduction"]
133+
},
134+
{
135+
"dropdown": "@sei-js/x402",
136+
"description": "HTTP micro payments",
137+
"icon": "credit-card",
138+
"pages": [
139+
{
140+
"group": "Introduction",
141+
"pages": ["x402/introduction", "x402/overview", "x402/quickstart"]
142+
},
143+
{
144+
"group": "Facilitators",
145+
"pages": ["x402/facilitators/introduction", "x402/facilitators/example"]
146+
},
147+
{
148+
"group": "Client Integration",
149+
"pages": ["x402/clients/fetch"]
150+
},
151+
{
152+
"group": "Packages",
153+
"pages": [
154+
"x402/packages/x402",
155+
"x402/packages/x402-fetch",
156+
"x402/packages/x402-axios",
157+
"x402/packages/x402-express",
158+
"x402/packages/x402-hono",
159+
"x402/packages/x402-next"
160+
]
161+
}
162+
]
133163
}
134164
]
135165
},

docs/x402/clients/fetch.mdx

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
---
2+
title: "Fetch Client"
3+
description: "Make paid HTTP requests with the native Fetch API and x402"
4+
icon: "desktop"
5+
---
6+
7+
## Fetch Client Integration
8+
9+
Use x402 with the standard Fetch API to make paid HTTP requests. Perfect for both browser and Node.js environments.
10+
11+
## Installation
12+
13+
```bash
14+
npm install @sei-js/x402-fetch viem dotenv
15+
```
16+
17+
## Basic Usage
18+
19+
```typescript
20+
import { config } from "dotenv";
21+
import { Hex } from "viem";
22+
import { privateKeyToAccount } from "viem/accounts";
23+
import {
24+
wrapFetchWithPayment,
25+
decodeXPaymentResponse,
26+
} from "@sei-js/x402-fetch";
27+
28+
config();
29+
30+
const privateKey = process.env.PRIVATE_KEY as Hex;
31+
const baseURL = process.env.RESOURCE_SERVER_URL as string; // e.g. http://localhost:4021
32+
const endpointPath = process.env.ENDPOINT_PATH as string; // e.g. /weather
33+
const url = `${baseURL}${endpointPath}`;
34+
35+
if (!baseURL || !privateKey || !endpointPath) {
36+
console.error("Missing required environment variables");
37+
process.exit(1);
38+
}
39+
40+
// Create account from private key
41+
const account = privateKeyToAccount(privateKey);
42+
43+
// Wrap fetch with payment handling
44+
const fetchWithPayment = wrapFetchWithPayment(fetch, account);
45+
46+
// Make a paid request
47+
fetchWithPayment(url, {
48+
method: "GET",
49+
})
50+
.then(async (response) => {
51+
const body = await response.json();
52+
console.log("Response:", body);
53+
54+
// Decode the payment response
55+
const paymentResponse = decodeXPaymentResponse(
56+
response.headers.get("x-payment-response")!
57+
);
58+
console.log("Payment details:", paymentResponse);
59+
})
60+
.catch((error) => {
61+
console.error("Error:", error.response?.data?.error);
62+
});
63+
```
64+
65+
## Environment Setup
66+
67+
Create a `.env` file with the required configuration:
68+
69+
```env
70+
# Required: Your private key for making payments
71+
PRIVATE_KEY=0xYourPrivateKeyHere
72+
73+
# Required: The server URL hosting the paid API
74+
RESOURCE_SERVER_URL=http://localhost:4021
75+
76+
# Required: The endpoint path to access
77+
ENDPOINT_PATH=/weather
78+
```
79+
80+
<Warning>
81+
**Security Note**: Never commit private keys to version control. Use
82+
environment variables or secure key management services in production.
83+
</Warning>

docs/x402/facilitators/example.mdx

Lines changed: 211 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,211 @@
1+
---
2+
title: "Example"
3+
description: "Complete setup guide for x402 facilitators"
4+
icon: "code"
5+
---
6+
7+
<Warning>
8+
This example is for learning purposes only. Do not use it for production.
9+
</Warning>
10+
## Prerequisites
11+
12+
Before setting up a facilitator, ensure you have:
13+
14+
- **Node.js 18+** installed
15+
- **Sei wallet** with some SEI for gas fees
16+
- **Private key** for your facilitator wallet (testnet recommended for development)
17+
18+
## Quick Setup
19+
20+
### 1. Install Dependencies
21+
22+
```bash
23+
npm install @sei-js/x402 express dotenv
24+
```
25+
26+
### 2. Environment Configuration
27+
28+
Create a `.env` file:
29+
30+
```env
31+
# Required: Your facilitator private key
32+
PRIVATE_KEY=0xYourPrivateKeyHere
33+
34+
# Optional: Server port (defaults to 3000)
35+
PORT=3002
36+
```
37+
38+
<Warning>
39+
**Security Note**: Never commit private keys to version control. Use
40+
environment variables or secure key management services in production.
41+
</Warning>
42+
43+
### 3. Basic Facilitator Implementation
44+
45+
Create `index.ts` with the following structure:
46+
47+
```typescript
48+
import { config } from "dotenv";
49+
import express from "express";
50+
import { verify, settle } from "@sei-js/x402/facilitator";
51+
import {
52+
PaymentRequirementsSchema,
53+
PaymentRequirements,
54+
evm,
55+
PaymentPayload,
56+
PaymentPayloadSchema,
57+
} from "@sei-js/x402/types";
58+
59+
config();
60+
61+
const PRIVATE_KEY = process.env.PRIVATE_KEY;
62+
63+
if (!PRIVATE_KEY) {
64+
console.error("Missing required environment variables");
65+
process.exit(1);
66+
}
67+
68+
const { createConnectedClient, createSigner } = evm;
69+
70+
const app = express();
71+
app.use(express.json());
72+
73+
type VerifyRequest = {
74+
paymentPayload: PaymentPayload;
75+
paymentRequirements: PaymentRequirements;
76+
};
77+
78+
type SettleRequest = {
79+
paymentPayload: PaymentPayload;
80+
paymentRequirements: PaymentRequirements;
81+
};
82+
83+
const client = createConnectedClient("sei-testnet");
84+
85+
// Verification endpoint
86+
app.post("/verify", async (req, res) => {
87+
try {
88+
const body: VerifyRequest = req.body;
89+
const paymentRequirements = PaymentRequirementsSchema.parse(
90+
body.paymentRequirements
91+
);
92+
const paymentPayload = PaymentPayloadSchema.parse(body.paymentPayload);
93+
const valid = await verify(client, paymentPayload, paymentRequirements);
94+
res.json(valid);
95+
} catch {
96+
res.status(400).json({ error: "Invalid request" });
97+
}
98+
});
99+
100+
// Settlement endpoint
101+
app.post("/settle", async (req, res) => {
102+
try {
103+
const signer = createSigner("sei-testnet", PRIVATE_KEY as `0x${string}`);
104+
const body: SettleRequest = req.body;
105+
const paymentRequirements = PaymentRequirementsSchema.parse(
106+
body.paymentRequirements
107+
);
108+
const paymentPayload = PaymentPayloadSchema.parse(body.paymentPayload);
109+
const response = await settle(signer, paymentPayload, paymentRequirements);
110+
res.json(response);
111+
} catch (error) {
112+
res.status(400).json({ error: `Invalid request: ${error}` });
113+
}
114+
});
115+
116+
// Supported schemes endpoint
117+
app.get("/supported", (req, res) => {
118+
res.json({
119+
kinds: [
120+
{
121+
x402Version: 1,
122+
scheme: "exact",
123+
network: "sei-testnet",
124+
},
125+
],
126+
});
127+
});
128+
129+
app.listen(process.env.PORT || 3000, () => {
130+
console.log(
131+
`Server listening at http://localhost:${process.env.PORT || 3000}`
132+
);
133+
});
134+
```
135+
136+
### 4. Run Your Facilitator
137+
138+
```bash
139+
npx tsx index.ts
140+
```
141+
142+
<Check>
143+
Your facilitator server should start and display: `Server listening at
144+
http://localhost:3002`
145+
</Check>
146+
147+
## API Endpoints
148+
149+
Your facilitator exposes three main endpoints:
150+
151+
### POST /verify
152+
153+
Verifies x402 payment payloads without executing transactions.
154+
155+
**Request Body:**
156+
157+
```typescript
158+
{
159+
paymentPayload: PaymentPayload; // x402 payment data
160+
paymentRequirements: PaymentRequirements; // Payment requirements
161+
}
162+
```
163+
164+
**Response:**
165+
166+
```json
167+
{
168+
"valid": true,
169+
"reason": "Payment payload is valid"
170+
}
171+
```
172+
173+
### POST /settle
174+
175+
Settles verified payments by signing and broadcasting transactions to Sei testnet.
176+
177+
**Request Body:**
178+
179+
```typescript
180+
{
181+
paymentPayload: PaymentPayload; // x402 payment data
182+
paymentRequirements: PaymentRequirements; // Payment requirements
183+
}
184+
```
185+
186+
**Response:**
187+
188+
```json
189+
{
190+
"transactionHash": "0x...",
191+
"status": "success"
192+
}
193+
```
194+
195+
### GET /supported
196+
197+
Returns supported payment schemes and networks.
198+
199+
**Response:**
200+
201+
```json
202+
{
203+
"kinds": [
204+
{
205+
"x402Version": 1,
206+
"scheme": "exact",
207+
"network": "sei-testnet"
208+
}
209+
]
210+
}
211+
```

0 commit comments

Comments
 (0)