Skip to content

Commit cc79b72

Browse files
authored
v2: docs (#726)
* ts example docs * improve ts package docs
1 parent 605019f commit cc79b72

File tree

32 files changed

+2328
-1206
lines changed

32 files changed

+2328
-1206
lines changed
Lines changed: 88 additions & 109 deletions
Original file line numberDiff line numberDiff line change
@@ -1,79 +1,73 @@
11
# Advanced x402 Client Examples
22

3-
This directory contains advanced, production-ready patterns for x402 TypeScript clients using fetch. These examples go beyond the basics to demonstrate sophisticated techniques for building robust, scalable payment-enabled applications.
3+
Advanced patterns for x402 TypeScript clients demonstrating payment lifecycle hooks and network preferences.
44

5-
## What This Shows
6-
7-
Advanced patterns for production environments:
8-
9-
- **Payment Lifecycle Hooks**: Custom logic at different payment stages
5+
## Prerequisites
106

11-
## Examples
7+
- Node.js v20+ (install via [nvm](https://github.com/nvm-sh/nvm))
8+
- pnpm v10 (install via [pnpm.io/installation](https://pnpm.io/installation))
9+
- Valid EVM and/or SVM private keys for making payments
10+
- A running x402 server (see [server examples](../../servers/))
11+
- Familiarity with the [basic fetch client](../fetch/)
1212

13-
### 1. Payment Lifecycle Hooks (`hooks`)
13+
## Setup
1414

15-
**Production Pattern**: Register hooks for payment creation lifecycle events
15+
1. Copy `.env-local` to `.env`:
1616

1717
```bash
18-
npm start hooks
18+
cp .env-local .env
1919
```
2020

21-
**Demonstrates:**
21+
and fill required environment variables:
2222

23-
- onBeforePaymentCreation: Custom validation before payment
24-
- onAfterPaymentCreation: Logging and metrics after payment
25-
- onPaymentCreationFailure: Error recovery strategies
26-
- Payment event lifecycle management
23+
- `EVM_PRIVATE_KEY` - Ethereum private key for EVM payments
24+
- `SVM_PRIVATE_KEY` - Solana private key for SVM payments (required for preferred-network)
2725

28-
**Use When:**
26+
2. Install and build all packages from the typescript examples root:
2927

30-
- Need to log payment events for debugging/monitoring
31-
- Want custom validation before allowing payments
32-
- Require error recovery from payment failures
33-
- Building observable payment systems
28+
```bash
29+
cd ../../
30+
pnpm install && pnpm build
31+
cd clients/advanced
32+
```
3433

35-
## Prerequisites
34+
3. Run the server
3635

37-
- Node.js v20+ (install via [nvm](https://github.com/nvm-sh/nvm))
38-
- pnpm v10 (install via [pnpm.io/installation](https://pnpm.io/installation))
39-
- An Ethereum private key (testnet recommended)
40-
- A running x402 server (see [server examples](../../servers/))
41-
- Understanding of [basic fetch client](../fetch/)
36+
```bash
37+
pnpm dev
38+
```
4239

43-
## Setup
40+
## Available Examples
4441

45-
1. Install and build all packages from the typescript examples root:
42+
Each example demonstrates a specific advanced pattern:
4643

47-
```bash
48-
cd ../../
49-
pnpm install
50-
pnpm build
51-
cd clients/advanced
52-
```
44+
| Example | Command | Description |
45+
| ------------------- | ---------------------------- | ------------------------------- |
46+
| `hooks` | `pnpm dev:hooks` | Payment lifecycle hooks |
47+
| `preferred-network` | `pnpm dev:preferred-network` | Client-side network preferences |
48+
49+
## Testing the Examples
5350

54-
2. Copy `.env-example` to `.env` and add your Ethereum private key:
51+
Start a server first:
5552

5653
```bash
57-
cp .env-example .env
54+
cd ../../servers/express
55+
pnpm dev
5856
```
5957

60-
## Running Examples
58+
Then run the examples:
6159

6260
```bash
63-
# Run specific advanced example
64-
npm start hooks
65-
# or
61+
cd ../../clients/advanced
6662
pnpm dev:hooks
6763
```
6864

69-
## Architecture Patterns
70-
71-
### Payment Lifecycle Hooks
65+
## Example: Payment Lifecycle Hooks
7266

73-
Register hooks for complete observability and control:
67+
Register custom logic at different payment stages for observability and control:
7468

7569
```typescript
76-
import { x402Client } from "@x402/fetch";
70+
import { x402Client, wrapFetchWithPayment } from "@x402/fetch";
7771
import { ExactEvmScheme } from "@x402/evm/exact/client";
7872
import { privateKeyToAccount } from "viem/accounts";
7973

@@ -82,91 +76,76 @@ const signer = privateKeyToAccount(process.env.EVM_PRIVATE_KEY);
8276
const client = new x402Client()
8377
.register("eip155:*", new ExactEvmScheme(signer))
8478
.onBeforePaymentCreation(async context => {
85-
// Custom validation logic
8679
console.log("Creating payment for:", context.selectedRequirements);
87-
// Optionally abort: return { abort: true, reason: "Not allowed" };
80+
// Abort payment by returning: { abort: true, reason: "Not allowed" }
8881
})
8982
.onAfterPaymentCreation(async context => {
90-
// Log successful payment creation
91-
console.log("Payment created:", context.version);
83+
console.log("Payment created:", context.paymentPayload.x402Version);
9284
// Send to analytics, database, etc.
9385
})
9486
.onPaymentCreationFailure(async context => {
95-
// Handle failures
9687
console.error("Payment failed:", context.error);
97-
// Optionally recover with alternative method
88+
// Recover by returning: { recovered: true, payload: alternativePayload }
9889
});
90+
91+
const fetchWithPayment = wrapFetchWithPayment(fetch, client);
92+
const response = await fetchWithPayment("http://localhost:4021/weather");
9993
```
10094

101-
## Production Considerations
95+
Available hooks:
96+
97+
- `onBeforePaymentCreation` — Run before payment creation (can abort)
98+
- `onAfterPaymentCreation` — Run after successful payment creation
99+
- `onPaymentCreationFailure` — Run when payment creation fails (can recover)
102100

103-
### Hook Best Practices
101+
**Use case:**
104102

105-
1. **Keep hooks fast**: Avoid blocking operations
106-
2. **Handle errors gracefully**: Don't throw in hooks
107-
3. **Log appropriately**: Use structured logging
108-
4. **Avoid side effects in before hooks**: Only use for validation
103+
- Log payment events for debugging and monitoring
104+
- Custom validation before allowing payments
105+
- Implement retry or recovery logic for failed payments
106+
- Metrics and analytics collection
109107

110-
### Error Recovery Strategy
108+
## Example: Preferred Network Selection
111109

112-
Implement intelligent error handling in failure hooks:
110+
Configure client-side network preferences with automatic fallback:
113111

114112
```typescript
115-
client.onPaymentCreationFailure(async context => {
116-
const errorType = classifyError(context.error);
117-
118-
switch (errorType) {
119-
case "network":
120-
// Retry logic handled by client
121-
return undefined;
122-
case "insufficient_balance":
123-
// Alert user, no recovery
124-
notifyUser("Insufficient balance");
125-
return undefined;
126-
case "signing_error":
127-
// Attempt recovery with different method
128-
return {
129-
recovered: true,
130-
payload: await createAlternativePayment(),
131-
};
113+
import { x402Client, wrapFetchWithPayment, type PaymentRequirements } from "@x402/fetch";
114+
import { ExactEvmScheme } from "@x402/evm/exact/client";
115+
import { ExactSvmScheme } from "@x402/svm/exact/client";
116+
117+
// Define network preference order (most preferred first)
118+
const networkPreferences = ["solana:", "eip155:"];
119+
120+
const preferredNetworkSelector = (
121+
_x402Version: number,
122+
options: PaymentRequirements[],
123+
): PaymentRequirements => {
124+
// Try each preference in order
125+
for (const preference of networkPreferences) {
126+
const match = options.find(opt => opt.network.startsWith(preference));
127+
if (match) return match;
132128
}
133-
});
134-
```
135-
136-
## Testing Against Local Server
129+
// Fallback to first mutually-supported option
130+
return options[0];
131+
};
137132

138-
1. Start server:
133+
const client = new x402Client(preferredNetworkSelector)
134+
.register("eip155:*", new ExactEvmScheme(evmSigner))
135+
.register("solana:*", new ExactSvmScheme(svmSigner));
139136

140-
```bash
141-
cd ../../servers/express
142-
pnpm dev
137+
const fetchWithPayment = wrapFetchWithPayment(fetch, client);
138+
const response = await fetchWithPayment("http://localhost:4021/weather");
143139
```
144140

145-
2. Run advanced examples:
146-
147-
```bash
148-
cd ../../clients/advanced
149-
pnpm dev:hooks
150-
```
151-
152-
## Comparison: Basic vs Advanced
153-
154-
| Feature | Basic Client | Advanced Client |
155-
| ---------------- | ------------ | --------------------------- |
156-
| Payment Hooks | None | ✅ Lifecycle event handling |
157-
| Observability | Minimal | ✅ Comprehensive logging |
158-
| Error Recovery | Basic | ✅ Intelligent strategies |
159-
| Production Ready | Basic | ✅ Battle-tested patterns |
160-
161-
## Next Steps
141+
**Use case:**
162142

163-
- **[Basic Fetch Client](../fetch/)**: Start here if you haven't already
164-
- **[Basic Axios Client](../axios/)**: Alternative HTTP client
165-
- **[Custom Client](../custom/)**: Learn the internals
166-
- **[Server Examples](../../servers/)**: Build complementary servers
143+
- Prefer payments on specific chains
144+
- User preference settings in wallet UIs
167145

168-
## Related Resources
146+
## Hook Best Practices
169147

170-
- [x402 Core Package Documentation](../../../../typescript/packages/core/)
171-
- [x402 Fetch Package Documentation](../../../../typescript/packages/x402-fetch/)
172-
- [Production Deployment Guide](../../../../docs/production.md)
148+
1. **Keep hooks fast** — Avoid blocking operations
149+
2. **Handle errors gracefully** — Don't throw in hooks
150+
3. **Log appropriately** — Use structured logging
151+
4. **Avoid side effects in before hooks** — Only use for validation
Lines changed: 22 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1,67 +1,55 @@
11
# x402-axios Example Client
22

3-
This is an example client that demonstrates how to use the `x402-axios` package to make HTTP requests to endpoints protected by the x402 payment protocol.
3+
Example client demonstrating how to use `@x402/axios` to make HTTP requests to endpoints protected by the x402 payment protocol.
44

55
## Prerequisites
66

77
- Node.js v20+ (install via [nvm](https://github.com/nvm-sh/nvm))
88
- pnpm v10 (install via [pnpm.io/installation](https://pnpm.io/installation))
9-
- A running x402 server (you can use the example express server at `examples/typescript/servers/express`)
10-
- A valid Ethereum private key for making payments
9+
- A running x402 server (see [express server example](../../servers/express))
10+
- Valid EVM and/or SVM private keys for making payments
1111

1212
## Setup
1313

1414
1. Install and build all packages from the typescript examples root:
1515
```bash
1616
cd ../../
17-
pnpm install
18-
pnpm build
17+
pnpm install && pnpm build
1918
cd clients/axios
2019
```
2120

22-
2. Copy `.env-local` to `.env` and add your Ethereum private key:
21+
2. Copy `.env-local` to `.env` and add your private keys:
2322
```bash
2423
cp .env-local .env
2524
```
2625

27-
3. Start the example client:
26+
Required environment variables:
27+
- `EVM_PRIVATE_KEY` - Ethereum private key for EVM payments
28+
- `SVM_PRIVATE_KEY` - Solana private key for SVM payments
2829

30+
3. Run the client:
2931
```bash
30-
# Run the default example (builder-pattern)
3132
pnpm start
32-
33-
# Or run a specific example:
34-
pnpm start builder-pattern
35-
pnpm start mechanism-helper-registration
36-
37-
# Or use the convenience scripts:
38-
pnpm dev # builder-pattern
39-
pnpm dev:mechanism-helper-registration # mechanism-helper-registration
4033
```
4134

4235
## Available Examples
4336

44-
This package contains two examples demonstrating different ways to configure the x402 client:
45-
4637
### 1. Builder Pattern (`builder-pattern`)
47-
Demonstrates the basic way to configure the client by chaining `registerScheme` calls to map scheme patterns to mechanism clients.
38+
Configure the client by chaining `.register()` calls to map scheme patterns to mechanism clients.
4839

49-
### 2. Mechanism Helper Registration (`mechanism-helper-registration`)
50-
Shows how to use convenience helper functions provided by `@x402/evm` and `@x402/svm` packages to register all supported networks with recommended defaults.
40+
```bash
41+
pnpm start builder-pattern
42+
```
5143

52-
## How It Works
44+
### 2. Mechanism Helper Registration (`mechanism-helper-registration`)
45+
Use convenience helper functions from `@x402/evm` and `@x402/svm` to register supported networks.
5346

54-
The examples demonstrate how to:
55-
1. Create and configure an x402Client with different patterns
56-
2. Register mechanism clients for different blockchain schemes (EVM, SVM)
57-
3. Wrap axios with x402 payment handling
58-
4. Make a request to a paid endpoint
59-
5. Handle the response and payment details
47+
```bash
48+
pnpm start mechanism-helper-registration
49+
```
6050

6151
## Example Code
6252

63-
Here's a simplified version of the builder pattern:
64-
6553
```typescript
6654
import { x402Client, wrapAxiosWithPayment } from "@x402/axios";
6755
import { ExactEvmScheme } from "@x402/evm/exact/client";
@@ -80,10 +68,9 @@ const api = wrapAxiosWithPayment(axios.create(), client);
8068

8169
// Make request to paid endpoint
8270
const response = await api.get("http://localhost:4021/weather");
83-
const body = response.data;
84-
console.log(body);
71+
console.log(response.data);
8572
```
8673

87-
See the individual example files for more detailed demonstrations:
88-
- `builder-pattern.ts` - Basic builder pattern
89-
- `mechanism-helper-registration.ts` - Using helper functions
74+
## Next Steps
75+
76+
See [Advanced Examples](../advanced/) for payment lifecycle hooks and setting network preferences.

examples/typescript/clients/axios/package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
{
2-
"name": "@x402/fetch-client-example",
2+
"name": "@x402/axios-client-example",
33
"private": true,
44
"type": "module",
55
"scripts": {

0 commit comments

Comments
 (0)