Skip to main content

1. Install dependencies

npm install viem x402-fetch dotenv

2. Load your wallet

import { privateKeyToAccount } from 'viem/accounts';
import { wrapFetchWithPayment } from 'x402-fetch';
import dotenv from 'dotenv';

dotenv.config();

const account = privateKeyToAccount(process.env.PRIVATE_KEY!); // Keep this secret!

3. Wrap fetch with the EVM signer

const fetchWithPayment = wrapFetchWithPayment(fetch, account);
The account object from viem exposes signMessage, which x402 uses to replay invoices.

4. Call a Horizon endpoint

const baseUrl = process.env.HORIZON_BASE_URL ?? 'https://api.horizon.new/v1';

const response = await fetchWithPayment(`${baseUrl}/generate/audio`, {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    prompt: 'Warm, confident voice welcoming Horizon users.',
    metadata: { campaign: 'onboarding' },
  }),
});

const job = await response.json();
console.log(job.jobId, job.statusUrl);

5. Optional: handle job completion

const status = await fetchWithPayment(`${baseUrl}/jobs/${job.jobId}`).then((res) => res.json());

if (status.state === 'succeeded') {
  console.log(status.result);
}

Security reminders

  • Store the private key in a secure vault (e.g., HashiCorp Vault, AWS KMS) rather than plaintext env files in production.
  • Fund the wallet on the environment-specific chain (Base Sepolia for staging, Base mainnet for production).
  • Rotate keys periodically and restrict their usage to invoice replay only.