import AnchorBrowser from 'anchorbrowser';
import { Account } from 'eth-account';
import { x402Fetch } from 'x402';
(async () => {
const ENDPOINT = "https://api.anchorbrowser.io/v1/sessions";
const BODY = {};
const key = process.env.PRIVATE_KEY;
if (!key) {
console.error("Set PRIVATE_KEY=0x...");
process.exit(1);
}
try {
// Try to create session normally first
const anchor_client = new AnchorBrowser({apiKey: process.env.ANCHOR_API_KEY});
const session = await anchor_client.sessions.create();
console.log(JSON.stringify(session.data, null, 2));
} catch (error) {
// If we get a 402 error, handle payment
if (error.message.includes("402")) {
const pre = await fetch(ENDPOINT, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(BODY)
});
const preData = await pre.json();
const price = parseInt(preData.accepts[0].maxAmountRequired);
const account = Account.fromPrivateKey(key);
const res = await x402Fetch(account, ENDPOINT, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(BODY)
});
console.log(JSON.stringify(await res.json(), null, 2));
} else {
throw error;
}
}
})().catch(console.error);