Skip to content

Commit cfcc76e

Browse files
committed
updates code after hackathon
1 parent abcef68 commit cfcc76e

File tree

3 files changed

+98
-37
lines changed

3 files changed

+98
-37
lines changed

docs/pos/payments/x402/quickstart-buyers.md

Lines changed: 59 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -34,45 +34,88 @@ Create a wallet client using a tool like [viem](https://viem.sh/):
3434
npm install viem
3535
```
3636

37-
Then, instantiate the wallet account:
37+
Then, instantiate the wallet account and client:
3838

3939
```typescript
40-
import { createWalletClient, http } from "viem";
41-
import { privateKeyToAccount } from "viem/accounts";
42-
import { polygonAmoy } from "viem/chains";
43-
44-
// Create a wallet client (using your private key)
45-
const account = privateKeyToAccount("0xYourPrivateKey"); // we recommend using an environment variable for this
40+
import { wrapFetchWithPayment, decodeXPaymentResponse } from "x402-fetch";
41+
import { createWalletClient, http } from 'viem';
42+
import { privateKeyToAccount } from 'viem/accounts';
43+
import { polygonAmoy } from 'viem/chains';
44+
import 'dotenv/config';
45+
46+
const privateKey = process.env.PRIVATE_KEY;
47+
if (!privateKey) {
48+
throw new Error("PRIVATE_KEY not set in .env file");
49+
}
50+
51+
const account = privateKeyToAccount(`0x${privateKey}`);
52+
const client = createWalletClient({
53+
account,
54+
chain: polygonAmoy,
55+
transport: http()
56+
});
57+
58+
console.log("Using wallet address:", account.address);
4659
```
4760

4861
## 3. Make Paid Requests Automatically
4962

5063
You can use either `x402-fetch` or `x402-axios` to automatically handle 402 Payment Required responses and complete payment flows.
5164

5265
!!! info x402-fetch
53-
**x402-fetch** extends the native `fetch` API to handle 402 responses and payment headers for you. [Full example from Coinbase here](https://github.com/coinbase/x402/tree/main/examples/typescript/clients/fetch)
66+
**x402-fetch** extends the native `fetch` API to handle 402 responses and payment headers for you. [Full example here](https://github.com/AkshatGada/x402_Polygon/blob/feature/facilitator-amoy/demo/quickstart-local/buyer_x402.js)
5467

5568
```typescript
5669
import { wrapFetchWithPayment, decodeXPaymentResponse } from "x402-fetch";
5770
// other imports...
5871

5972
// wallet creation logic...
6073

61-
const fetchWithPayment = wrapFetchWithPayment(fetch, account);
74+
const FACILITATOR_URL = process.env.FACILITATOR_URL || "https://facilitator.x402.rs";
75+
76+
const fetchWithPayment = wrapFetchWithPayment(fetch, client);
77+
78+
const url = process.env.QUICKSTART_RESOURCE_URL || 'http://127.0.0.1:4021/weather';
6279

6380
fetchWithPayment(url, { //url should be something like https://api.example.com/paid-endpoint
6481
method: "GET",
6582
})
6683
.then(async response => {
6784
const body = await response.json();
68-
console.log(body);
69-
70-
const paymentResponse = decodeXPaymentResponse(response.headers.get("x-payment-response")!);
71-
console.log(paymentResponse);
85+
console.log('Response body:', body);
86+
87+
// Only try to decode payment response if we got the weather data (not the 402 response)
88+
if (body.report) {
89+
console.log('All response headers:', Object.fromEntries(response.headers.entries()));
90+
const rawPaymentResponse = response.headers.get("x-payment-response");
91+
console.log('Raw x-payment-response:', rawPaymentResponse);
92+
93+
try {
94+
const paymentResponse = decodeXPaymentResponse(rawPaymentResponse);
95+
console.log('Decoded payment response:', paymentResponse);
96+
} catch (e) {
97+
console.error('Error decoding payment response:', e);
98+
console.error('Failed to decode response:', rawPaymentResponse);
99+
throw e;
100+
}
101+
}
72102
})
73-
.catch(error => {
74-
console.error(error.response?.data?.error);
75-
});
103+
.catch(async error => {
104+
console.error('Error:', error.message);
105+
if (error.response) {
106+
try {
107+
const text = await error.response.text();
108+
console.error('Response text:', text);
109+
console.error('Response status:', error.response.status);
110+
console.error('Response headers:', error.response.headers);
111+
} catch (e) {
112+
console.error('Error reading response:', e);
113+
console.error('Raw error:', error);
114+
}
115+
} else {
116+
console.error('Raw error:', error);
117+
}
118+
});
76119
```
77120

78121
## 4. Error Handling

docs/pos/payments/x402/quickstart-sellers.md

Lines changed: 37 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,12 @@ Before you begin, ensure you have:
1212
* [Node.js](https://nodejs.org/en) and npm (or Python and pip) installed
1313
* An existing API or server
1414

15-
**Note**\
16-
There are pre-configured examples available in the Coinbase repo for both
17-
[Node.js](https://github.com/coinbase/x402/tree/main/examples/typescript/servers). We also have an [advanced example](https://github.com/coinbase/x402/tree/main/examples/typescript/servers/advanced)
18-
that shows how to use the x402 SDKs to build a more complex payment flow.
15+
**Note**
16+
17+
There are pre-configured examples available in the Coinbase repo for
18+
[Node.js](https://github.com/coinbase/x402/tree/main/examples/typescript/servers).
19+
There is also an [advanced example](https://github.com/coinbase/x402/tree/main/examples/typescript/servers/advanced)
20+
that shows how to use the x402 SDKs to build a more complex payment flow.
1921
The following example shows how to adapt these for Polygon.
2022

2123
## 1. Install Dependencies
@@ -33,8 +35,6 @@ Install the [x402 Next.js middleware package](https://www.npmjs.com/package/x402
3335
npm install x402-next
3436
```
3537

36-
Install the [x402 Hono middleware package](https://www.npmjs.com/package/x402-hono).
37-
3838
```bash
3939
npm install x402-hono
4040
```
@@ -54,10 +54,10 @@ Integrate the payment middleware into your application. You will need
5454
to provide:
5555

5656
* The Facilitator URL or facilitator object. For testing,
57-
use `https://x402.org/facilitator` which works on Base Sepolia.
57+
use `https://facilitator.x402.rs/` which works on Polygon Mainnet and Amoy.
5858
* For more information on running in production on mainnet, check
5959
out [CDP's Quickstart for Sellers](https://docs.cdp.coinbase.com/x402/docs/
60-
quickstart-sellers)
60+
quickstart-sellers). For a facilitator access on Polygon, please contact us [here.](https://t.me/PolygonHQ/32)
6161
* The routes you want to protect.
6262
* Your receiving wallet address.
6363

@@ -68,21 +68,39 @@ Please adapt for Polygon.
6868

6969
```javascript
7070
import express from "express";
71-
import { paymentMiddleware, Network } from "x402-express";
71+
import { paymentMiddleware } from "x402-express";
72+
// import { facilitator } from "@coinbase/x402"; // For mainnet
7273

7374
const app = express();
7475

7576
app.use(paymentMiddleware(
76-
"0xYourAddress", // your receiving wallet address
77+
"0xCA3953e536bDA86D1F152eEfA8aC7b0C82b6eC00", // receiving wallet address
7778
{ // Route configurations for protected endpoints
78-
"GET /weather": {
79-
// USDC amount in dollars
80-
price: "$0.001",
81-
network: "polygon-amoy",
82-
},
79+
"GET /weather": {
80+
// USDC amount in dollars
81+
price: "$0.001",
82+
network: "polygon-amoy",
83+
// Optional: Add metadata for better discovery in x402 Bazaar
84+
config: {
85+
description: "Get current weather data for any location",
86+
inputSchema: {
87+
type: "object",
88+
properties: {
89+
location: { type: "string", description: "City name" }
90+
}
91+
},
92+
outputSchema: {
93+
type: "object",
94+
properties: {
95+
weather: { type: "string" },
96+
temperature: { type: "number" }
97+
}
98+
}
99+
}
83100
},
101+
},
84102
{
85-
url: "https://facilitator.x402.rs/", // Facilitator URL for Polygon Amoy testnet.
103+
url: process.env.FACILITATOR_URL || "https://facilitator.x402.rs", // Polygon Amoy facilitator
86104
}
87105
));
88106

@@ -98,10 +116,10 @@ app.get("/weather", (req, res) => {
98116

99117
app.listen(4021, () => {
100118
console.log(`Server listening at http://localhost:4021`);
101-
});
119+
});
102120
```
103121

104-
Full example in the repo [here](https://github.com/coinbase/x402/tree/main/examples/typescript/fullstack/next).
122+
Full example in the repo [here](https://github.com/AkshatGada/x402_Polygon/blob/feature/facilitator-amoy/demo/quickstart-local/seller_x402.js).
105123
Since this is a fullstack example, we recommend using the example to build
106124
this yourself, and treat the code snippet below as a reference to adapt for
107125
Polygon.
@@ -115,7 +133,7 @@ export const middleware = paymentMiddleware(
115133
{ // Route configurations for protected endpoints
116134
'/protected': {
117135
price: '$0.01',
118-
network: "base-sepolia",
136+
network: "polygon-amoy",
119137
config: {
120138
description: 'Access to protected content'
121139
}

mkdocs.yml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -69,8 +69,8 @@ nav:
6969
- USDC: pos/transfers/transfer-usdc.md
7070
- x402:
7171
- Overview: pos/payments/x402/overview.md
72-
- Quickstart for Buyers: pos/payments/x402/buyers.md
73-
- Quickstart for Sellers: pos/payments/x402/sellers.md
72+
- Quickstart for Buyers: pos/payments/x402/quickstart-buyers.md
73+
- Quickstart for Sellers: pos/payments/x402/quickstart-sellers.md
7474
- Node how-tos:
7575
- Prerequisites: pos/how-to/prerequisites.md
7676
- Sync node using snapshots: pos/how-to/snapshots.md

0 commit comments

Comments
 (0)