-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpay-session.ts
More file actions
49 lines (42 loc) · 1.83 KB
/
Copy pathpay-session.ts
File metadata and controls
49 lines (42 loc) · 1.83 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
// Session-mode client: pay for an MPP-protected endpoint by signing
// an off-chain debit message. Requires an active session PDA on-chain
// owned by your wallet and authorizing this signer (see
// /Users/hiroyusai/src/mppsol-cpi/examples/open-session.ts to create one).
//
// Run: bun run examples/pay-session.ts
//
// Prerequisites:
// - A session opened on devnet (see mppsol-cpi/examples/open-session.ts)
// - The session's authorized_signer private key
// - The MPP server running at MPP_URL (default: http://localhost:3000/joke)
import { mppFetch, keypairSigner } from '@mppsol/agent';
import { readFileSync } from 'node:fs';
const URL = process.env.MPP_URL ?? 'http://localhost:3000/joke';
// Session PDA pubkey (output of open-session.ts).
const SESSION = process.env.MPPSOL_SESSION ?? 'YOUR_SESSION_PDA';
// Authorized-signer private key (32 bytes raw OR JSON array of 64 bytes).
// open-session.ts saves it to ./authorized-signer.json by default.
const SIGNER_PATH = process.env.SIGNER ?? './authorized-signer.json';
const raw = JSON.parse(readFileSync(SIGNER_PATH, 'utf8'));
const privateKey = Uint8Array.from(raw).slice(0, 32);
const signer = keypairSigner(privateKey);
// Persist sequence to disk so restarts don't reuse old sequences.
// In production: a Postgres `RETURNING`-incremented column or Redis INCR.
let nextSeq = 1n;
try { nextSeq = BigInt(readFileSync('.session-seq', 'utf8').trim()); } catch {}
const res = await mppFetch(URL, undefined, {
payer: {
kind: 'session',
session: SESSION,
signer,
nextSequence: () => {
const s = nextSeq++;
// Persist for next run.
require('node:fs').writeFileSync('.session-seq', String(nextSeq));
return s;
},
},
});
console.log('Status:', res.status);
console.log('Body:', await res.text());
console.log('Receipt:', res.headers.get('payment-receipt'));