// Node.js 22+. By default this inspects a quote without signing or paying.
const url = 'https://toolrail.dev/cl/uf?monto=50&direccion=uf-clp';
const network = 'eip155:8453';
const asset = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913';
const payTo = '0xC6E6138dAAc78CeC93d491b4581Afa1a61B98a17';
const ceiling = 5000n; // 0.005 USDC, with 6 decimal places.
const quote = await fetch(url, { redirect: 'error' });
if (quote.status !== 402) throw new Error(`Expected a quote (402), received ${quote.status}`);
const header = quote.headers.get('payment-required');
if (!header) throw new Error('Missing PAYMENT-REQUIRED header');
const requirements = JSON.parse(Buffer.from(header, 'base64').toString('utf8'));
const select = (version, accepts) => {
  if (version !== 2) throw new Error('Only x402 v2 is supported in this example');
  const choice = accepts.find(r => r.scheme === 'exact' && r.network === network
    && r.asset.toLowerCase() === asset.toLowerCase()
    && r.payTo.toLowerCase() === payTo.toLowerCase()
    && /^\d+$/.test(r.amount) && BigInt(r.amount) > 0n && BigInt(r.amount) <= ceiling);
  if (!choice) throw new Error('Quote does not match the network, USDC, recipient or price limit');
  return choice;
};
const selected = select(requirements.x402Version, requirements.accepts);
console.log(JSON.stringify({ url, network, amountUSDC: Number(selected.amount) / 1e6, payTo }, null, 2));
if (process.env.TOOLRAIL_PAY !== '1') {
  console.log('Quote only. Set TOOLRAIL_PAY=1 to authorize one paid request.');
} else {
  const key = process.env.TOOLRAIL_PRIVATE_KEY;
  if (!/^0x[0-9a-fA-F]{64}$/.test(key || '')) throw new Error('Set TOOLRAIL_PRIVATE_KEY locally to an EVM private key');
  const [{ x402Client, wrapFetchWithPayment }, { registerExactEvmScheme }, { privateKeyToAccount }] = await Promise.all([
    import('@x402/fetch'), import('@x402/evm/exact/client'), import('viem/accounts'),
  ]);
  const client = new x402Client(select);
  registerExactEvmScheme(client, { signer: privateKeyToAccount(key), networks: [network] });
  const safeFetch = (input, init = {}) => {
    if (String(input) !== url) throw new Error('This example only permits the fixed Toolrail URL');
    return fetch(input, { ...init, redirect: 'error' });
  };
  const response = await wrapFetchWithPayment(safeFetch, client)(url);
  console.log(`HTTP ${response.status}`);
  console.log(await response.text());
  if (!response.ok) process.exitCode = 1;
}
