-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpayment-test.js
More file actions
191 lines (171 loc) · 6.86 KB
/
payment-test.js
File metadata and controls
191 lines (171 loc) · 6.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
#!/usr/bin/env node
/**
* Live End-to-End Payment Test
*
* Uses a dedicated test buyer wallet to pay $0.001 USDC for access
* to /api/prices, proving the full x402 flow works on Base mainnet.
*
* Usage:
* BUYER_PRIVATE_KEY=0x... node scripts/payment-test.js
*/
import { createPublicClient, createWalletClient, http, formatUnits, parseUnits } from 'viem';
import { privateKeyToAccount } from 'viem/accounts';
import { base } from 'viem/chains';
const BASE_URL = process.env.BASE_URL || 'https://agentdata-api.com';
const RPC_URL = process.env.BASE_RPC_URL || 'https://mainnet.base.org';
const USDC = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913';
const publicClient = createPublicClient({ chain: base, transport: http(RPC_URL) });
// ERC-3009 TransferWithAuthorization typed-data signing
async function signTransferAuth(account, walletClient, to, value, validAfter, validBefore, nonce) {
return walletClient.signTypedData({
account,
domain: {
name: 'USD Coin',
version: '2',
chainId: 8453,
verifyingContract: USDC,
},
types: {
TransferWithAuthorization: [
{ name: 'from', type: 'address' },
{ name: 'to', type: 'address' },
{ name: 'value', type: 'uint256' },
{ name: 'validAfter', type: 'uint256' },
{ name: 'validBefore', type: 'uint256' },
{ name: 'nonce', type: 'bytes32' },
],
},
primaryType: 'TransferWithAuthorization',
message: {
from: account.address,
to,
value: BigInt(value),
validAfter: BigInt(validAfter),
validBefore: BigInt(validBefore),
nonce,
},
});
}
async function main() {
const keyEnv = process.env.BUYER_PRIVATE_KEY;
if (!keyEnv) {
console.error('Set BUYER_PRIVATE_KEY env var (0x-prefixed)');
process.exit(1);
}
const buyer = privateKeyToAccount(keyEnv);
const walletClient = createWalletClient({ account: buyer, chain: base, transport: http(RPC_URL) });
console.log('════════════════════════════════════════════════════════');
console.log(' x402 Live Payment Test (Base Mainnet)');
console.log('════════════════════════════════════════════════════════');
console.log(` Buyer: ${buyer.address}`);
console.log(` Target: ${BASE_URL}/api/prices`);
// Check buyer balances
const eth = await publicClient.getBalance({ address: buyer.address });
console.log(` ETH bal: ${(Number(eth) / 1e18).toFixed(6)} ETH`);
// USDC balance
try {
const usdc = await publicClient.readContract({
address: USDC,
abi: [{ name: 'balanceOf', type: 'function', inputs: [{ name: 'a', type: 'address' }], outputs: [{ type: 'uint256' }], stateMutability: 'view' }],
functionName: 'balanceOf',
args: [buyer.address],
});
console.log(` USDC bal: ${formatUnits(usdc, 6)} USDC`);
if (usdc < 1000n) {
console.error('\n❌ Buyer has less than 0.001 USDC. Send USDC on Base to the buyer address.');
process.exit(2);
}
} catch (e) {
console.error('Cannot read USDC balance:', e.message);
process.exit(3);
}
// 1. First request — expect 402
console.log('\n📤 Step 1: GET /api/prices (expecting 402)');
const r1 = await fetch(`${BASE_URL}/api/prices`);
console.log(` Status: ${r1.status}`);
if (r1.status !== 402) {
console.error('Expected 402, got', r1.status);
process.exit(4);
}
const headerValue = r1.headers.get('payment-required');
if (!headerValue) {
console.error('No PAYMENT-REQUIRED header');
process.exit(5);
}
const payload = JSON.parse(Buffer.from(headerValue, 'base64').toString('utf8'));
const accept = payload.accepts[0];
console.log(` Amount required: ${accept.maxAmountRequired} (${formatUnits(BigInt(accept.maxAmountRequired), 6)} USDC)`);
console.log(` Pay to: ${accept.payTo}`);
console.log(` Asset: ${accept.asset}`);
// 2. Sign ERC-3009 authorization
console.log('\n✍️ Step 2: Signing ERC-3009 TransferWithAuthorization');
const validAfter = 0;
const validBefore = Math.floor(Date.now() / 1000) + accept.maxTimeoutSeconds;
// Random 32-byte nonce
const nonce = '0x' + Array.from({length: 64}, () => Math.floor(Math.random() * 16).toString(16)).join('');
const signature = await signTransferAuth(
buyer, walletClient,
accept.payTo,
accept.maxAmountRequired,
validAfter,
validBefore,
nonce,
);
console.log(` Signature: ${signature.substring(0, 40)}...`);
// 3. Build x402 payment payload (v2 format: wrap acceptance in `accepted` field)
const paymentPayload = {
x402Version: 2,
resource: `${BASE_URL}/api/prices`,
accepted: {
scheme: accept.scheme,
network: accept.network,
amount: accept.amount || accept.maxAmountRequired,
asset: accept.asset,
payTo: accept.payTo,
maxTimeoutSeconds: accept.maxTimeoutSeconds,
extra: accept.extra,
},
payload: {
signature,
authorization: {
from: buyer.address,
to: accept.payTo,
value: accept.maxAmountRequired,
validAfter: String(validAfter),
validBefore: String(validBefore),
nonce,
},
},
};
const paymentHeader = Buffer.from(JSON.stringify(paymentPayload)).toString('base64');
console.log(` Header length: ${paymentHeader.length}`);
// 4. Retry request with payment
console.log('\n📤 Step 3: GET /api/prices with PAYMENT-SIGNATURE');
const r2 = await fetch(`${BASE_URL}/api/prices`, {
headers: {
'PAYMENT-SIGNATURE': paymentHeader,
'X-PAYMENT': paymentHeader, // both header conventions
},
});
console.log(` Status: ${r2.status}`);
if (r2.status !== 200) {
const body = await r2.text();
console.error('Payment failed. Body:', body.substring(0, 500));
process.exit(6);
}
const data = await r2.json();
console.log('\n✅ PAYMENT SUCCESSFUL! Received data:');
console.log(JSON.stringify(data, null, 2).substring(0, 500));
// Settlement response header
const settleHeader = r2.headers.get('payment-response');
if (settleHeader) {
try {
const settle = JSON.parse(Buffer.from(settleHeader, 'base64').toString('utf8'));
console.log('\n💰 Settlement details:', JSON.stringify(settle, null, 2).substring(0, 500));
} catch {}
}
console.log('\n════════════════════════════════════════════════════════');
console.log(' ✅ END-TO-END TEST PASSED');
console.log('════════════════════════════════════════════════════════');
}
main().catch(e => { console.error('\n❌ Test failed:', e); process.exit(99); });