-
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathdemo.ts
More file actions
256 lines (232 loc) · 7.78 KB
/
Copy pathdemo.ts
File metadata and controls
256 lines (232 loc) · 7.78 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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
/**
* x402 + PEAC Integration Example
*
* Demonstrates the full x402 payment flow with PEAC receipts:
* 1. Client requests protected resource
* 2. Server returns 402 with x402 v2 payment requirements
* 3. Client pays via x402 (simulated)
* 4. Server issues PEAC receipt proving payment
* 5. Client verifies receipt offline
*
* This example simulates the flow locally - no external services required.
*
* For production, see: https://x402.peacprotocol.org
*/
import { issue, verifyLocal } from '@peac/protocol';
import { generateKeypair } from '@peac/crypto';
// x402 v2 network identifiers (CAIP-2 format)
const X402_NETWORKS = {
BASE_MAINNET: 'eip155:8453',
BASE_SEPOLIA: 'eip155:84532',
SOLANA_MAINNET: 'solana:mainnet',
} as const;
// Simulated server configuration
const CONFIG = {
resourceUrl: 'https://api.example.com/premium/data',
issuerUrl: 'https://payment.example.com',
priceUsd: 50, // $0.50 in cents
network: X402_NETWORKS.BASE_MAINNET,
asset: 'USDC',
};
interface X402PaymentRequest {
network: string;
asset: string;
amount: string;
recipient: string;
resource: string;
}
interface ServerResponse {
status: number;
headers: Record<string, string>;
body: unknown;
}
/**
* Simulated resource server implementing x402 v2 + PEAC.
*
* Returns 402 with x402 v2 headers when no receipt is present.
* Verifies receipt and returns resource when valid.
*/
async function resourceServer(
request: { headers: Record<string, string> },
verifyReceipt: (jws: string) => Promise<boolean>
): Promise<ServerResponse> {
const receipt = request.headers['peac-receipt'];
if (!receipt) {
// Return 402 with x402 v2 headers
// See: https://x402.org/specs for header format
return {
status: 402,
headers: {
'content-type': 'application/problem+json',
// x402 v2 canonical header (replaces X-PAYMENT in v1)
'payment-required': JSON.stringify({
network: CONFIG.network,
asset: CONFIG.asset,
amount: CONFIG.priceUsd.toString(),
recipient: '0x1234567890abcdef1234567890abcdef12345678',
resource: CONFIG.resourceUrl,
}),
// PEAC discovery
'peac-issuer': CONFIG.issuerUrl,
},
body: {
type: 'https://www.peacprotocol.org/errors/payment-required',
title: 'Payment Required',
status: 402,
detail: 'Pay via x402 to receive a PEAC receipt for this resource.',
x402: {
network: CONFIG.network,
asset: CONFIG.asset,
amount: CONFIG.priceUsd,
},
},
};
}
// Verify PEAC receipt
const valid = await verifyReceipt(receipt);
if (!valid) {
return {
status: 401,
headers: { 'content-type': 'application/problem+json' },
body: {
type: 'https://www.peacprotocol.org/errors/invalid-receipt',
title: 'Invalid Receipt',
status: 401,
detail: 'The provided PEAC receipt could not be verified.',
},
};
}
// Success - return the protected resource
return {
status: 200,
headers: {
'content-type': 'application/json',
'peac-receipt-verified': 'true',
},
body: {
data: 'Premium content unlocked via x402 payment',
accessedAt: new Date().toISOString(),
},
};
}
/**
* Simulates x402 payment and PEAC receipt issuance.
*
* In production:
* - Client pays via x402 SDK (Coinbase, etc.)
* - Server receives payment confirmation
* - Server issues PEAC receipt with x402 evidence
*/
async function simulateX402Payment(
paymentRequest: X402PaymentRequest,
keys: { privateKey: Uint8Array; publicKey: Uint8Array }
): Promise<string> {
// PEAC records normalized payment fields. The x402 chain context (network, tx hash,
// recipient address, x402 dialect) lives in the upstream x402 system; this demo
// simulates the payment locally and only carries normalized commerce fields in the
// signed record.
const result = await issue({
iss: CONFIG.issuerUrl,
kind: 'evidence',
type: 'org.peacprotocol/payment',
pillars: ['commerce'],
sub: paymentRequest.resource,
extensions: {
'org.peacprotocol/commerce': {
payment_rail: 'x402',
amount_minor: paymentRequest.amount,
currency: 'USD',
reference: `x402_${Date.now()}`,
asset: paymentRequest.asset,
env: 'live',
},
},
privateKey: keys.privateKey,
kid: 'x402-demo-2025',
});
return result.jws;
}
/**
* Client agent that handles the x402 + PEAC flow.
*/
async function agent(keys: {
privateKey: Uint8Array;
publicKey: Uint8Array;
verifyReceipt: (jws: string) => Promise<boolean>;
}): Promise<void> {
console.log('\n=== x402 + PEAC Integration Demo ===\n');
console.log(`Resource: ${CONFIG.resourceUrl}`);
console.log(`Network: ${CONFIG.network}`);
console.log(`Price: $${(CONFIG.priceUsd / 100).toFixed(2)} ${CONFIG.asset}\n`);
// Step 1: Request resource (no receipt)
console.log('1. Client requests protected resource...');
const response1 = await resourceServer({ headers: {} }, keys.verifyReceipt);
if (response1.status === 402) {
console.log(' -> 402 Payment Required');
// Parse x402 v2 payment requirements
const paymentRequired = JSON.parse(response1.headers['payment-required']) as X402PaymentRequest;
console.log(` -> Network: ${paymentRequired.network}`);
console.log(` -> Asset: ${paymentRequired.asset}`);
console.log(` -> Amount: ${paymentRequired.amount}`);
// Step 2: Pay via x402 and get PEAC receipt
console.log('\n2. Client pays via x402...');
const receipt = await simulateX402Payment(paymentRequired, keys);
console.log(` -> Payment confirmed`);
console.log(` -> PEAC receipt issued (${receipt.length} chars)`);
// Step 3: Retry with receipt
console.log('\n3. Client retries with PEAC-Receipt header...');
const response2 = await resourceServer(
{ headers: { 'peac-receipt': receipt } },
keys.verifyReceipt
);
if (response2.status === 200) {
console.log(' -> 200 OK - Access granted!');
console.log(` -> Data: ${JSON.stringify(response2.body)}`);
} else {
console.log(` -> Unexpected: ${response2.status}`);
}
// Step 4: Demonstrate offline verification
console.log('\n4. Verify record offline...');
const result = await verifyLocal(receipt, keys.publicKey, { issuer: CONFIG.issuerUrl });
if (result.valid) {
const commerce = (
result.claims.extensions as
| {
'org.peacprotocol/commerce'?: {
payment_rail?: string;
amount_minor?: string;
currency?: string;
asset?: string;
};
}
| undefined
)?.['org.peacprotocol/commerce'];
console.log(' -> Verified claims:');
console.log(` iss: ${result.claims.iss}`);
console.log(` sub: ${result.claims.sub ?? '(none)'}`);
console.log(
` amount_minor: ${commerce?.amount_minor ?? '?'} ${commerce?.currency ?? '?'}`
);
console.log(` payment_rail: ${commerce?.payment_rail ?? '?'}`);
console.log(` asset: ${commerce?.asset ?? '?'}`);
console.log(' -> x402 chain context (network, tx_hash, recipient) lives upstream.');
} else {
console.error(` -> Verification failed: ${result.code}`);
}
}
console.log('\n=== Demo Complete ===\n');
}
// Main execution
async function main() {
const { privateKey, publicKey } = await generateKeypair();
const verifyReceipt = async (jws: string): Promise<boolean> => {
try {
const result = await verifyLocal(jws, publicKey, { issuer: CONFIG.issuerUrl });
return result.valid;
} catch {
return false;
}
};
await agent({ privateKey, publicKey, verifyReceipt });
}
main().catch(console.error);