DEV Community

Cover image for How to Make Your AI Agent Buy Onchain Ads with x402
sebayaki
sebayaki

Posted on

How to Make Your AI Agent Buy Onchain Ads with x402

Ever wished your AI agent could promote itself onchain — without any human clicking buttons?

With Signet and the x402 payment protocol, your agent can autonomously purchase spotlight ads on Base using USDC. No wallet UI, no browser extensions — just HTTP requests and crypto signatures.

What is x402?

x402 brings the HTTP 402 Payment Required status code to life. The flow is simple:

  1. Your agent makes a request to a paid endpoint
  2. Server responds with HTTP 402 and payment requirements (token, amount, recipient)
  3. Your agent signs an EIP-3009 USDC authorization (gasless — it's just a signature)
  4. Your agent resends the request with a X-PAYMENT header
  5. Server verifies the signature, settles the payment onchain, and processes the request

Think of it as Stripe for AI agents — but decentralized and permissionless.

What is Signet?

Signet is an onchain advertising platform on Base. The spotlight is the most visible ad position, and it's purchasable via USDC. With x402 integration, AI agents can buy spotlight ads autonomously.

Prerequisites

  • Node.js 18+
  • A wallet with USDC on Base
  • Your wallet's private key (for signing payments)

Option 1: Use the CLI (3 Commands)

The fastest way to get started:

# Check the current spotlight price
npx @signet-base/cli estimate

# Simulate a purchase (no real payment)
npx @signet-base/cli post --url https://your-agent.com --simulate

# Buy a spotlight ad for real
PRIVATE_KEY=0x... npx @signet-base/cli post --url https://your-agent.com
Enter fullscreen mode Exit fullscreen mode

That's it. Your agent has an onchain ad. 🎉


Option 2: Build It from Scratch

Let's build it step by step so you understand what's happening under the hood.

Install dependencies

npm install @x402/core @x402/evm viem
Enter fullscreen mode Exit fullscreen mode

Step 1: Estimate the Price

const SIGNET_API = 'https://signet.sebayaki.com';

const res = await fetch(`${SIGNET_API}/api/x402/estimate`);
const estimate = await res.json();

console.log(`Price: ~$${estimate.estimatedUSDC} USDC`);
console.log(`Available: ${estimate.spotlightAvailable}`);
Enter fullscreen mode Exit fullscreen mode

Step 2: Request the Endpoint → Get 402

const res = await fetch(`${SIGNET_API}/api/x402/spotlight`, {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ url: 'https://your-agent.com' }),
});

// Server responds with 402 and payment requirements
const paymentRequired402 = await res.json();
const accepts = paymentRequired402.accepts[0];
console.log(`Amount: $${accepts.amount} USDC`);
console.log(`Pay to: ${accepts.payTo}`);
Enter fullscreen mode Exit fullscreen mode

Step 3: Sign the USDC Authorization

This is where x402 shines. Your agent signs an EIP-3009 transferWithAuthorization — authorizing the server to pull USDC from your wallet. No gas needed for this step.

import { x402Client, x402HTTPClient } from '@x402/core/client';
import { registerExactEvmScheme } from '@x402/evm/exact/client';
import { privateKeyToAccount } from 'viem/accounts';

const account = privateKeyToAccount(process.env.PRIVATE_KEY);
const client = new x402Client();
registerExactEvmScheme(client, { signer: account });
const httpClient = new x402HTTPClient(client);

// Parse the 402 response into payment requirements
const paymentRequired = httpClient.getPaymentRequiredResponse(
  (name) => {
    if (name.toLowerCase() === 'x-402-version')
      return String(paymentRequired402.x402Version);
    return null;
  },
  paymentRequired402
);

// Create the signed payment payload
const paymentPayload = await httpClient.createPaymentPayload(
  paymentRequired
);
const paymentHeaders = httpClient.encodePaymentSignatureHeader(
  paymentPayload
);
Enter fullscreen mode Exit fullscreen mode

Step 4: Complete the Purchase

const finalRes = await fetch(`${SIGNET_API}/api/x402/spotlight`, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    ...paymentHeaders,
  },
  body: JSON.stringify({ url: 'https://your-agent.com' }),
});

const result = await finalRes.json();
console.log('✅ Ad placed!');
console.log(`TX: ${result.txHash}`);
console.log(`Block: ${result.blockNumber}`);
console.log(`Cost: $${result.usdcSpent} USDC`);
Enter fullscreen mode Exit fullscreen mode

The Full Script

Copy-paste ready. Save as spotlight.mjs and run with PRIVATE_KEY=0x... node spotlight.mjs <url>:

import { x402Client, x402HTTPClient } from '@x402/core/client';
import { registerExactEvmScheme } from '@x402/evm/exact/client';
import { privateKeyToAccount } from 'viem/accounts';

const SIGNET_API = 'https://signet.sebayaki.com';
const account = privateKeyToAccount(process.env.PRIVATE_KEY);
const targetUrl = process.argv[2] || 'https://example.com';

// 1. Estimate
const estimate = await fetch(`${SIGNET_API}/api/x402/estimate`)
  .then(r => r.json());
console.log(`Price: ~$${estimate.estimatedUSDC} USDC`);

// 2. Request → 402
const res = await fetch(`${SIGNET_API}/api/x402/spotlight`, {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ url: targetUrl }),
});

if (res.status !== 402) {
  console.error('Unexpected status:', res.status);
  process.exit(1);
}

const paymentRequired402 = await res.json();

// 3. Sign payment
const client = new x402Client();
registerExactEvmScheme(client, { signer: account });
const httpClient = new x402HTTPClient(client);

const paymentRequired = httpClient.getPaymentRequiredResponse(
  (name) => {
    if (name.toLowerCase() === 'x-402-version')
      return String(paymentRequired402.x402Version);
    return null;
  },
  paymentRequired402
);

const paymentPayload = await httpClient.createPaymentPayload(
  paymentRequired
);
const paymentHeaders = httpClient.encodePaymentSignatureHeader(
  paymentPayload
);

// 4. Submit with payment
const final = await fetch(`${SIGNET_API}/api/x402/spotlight`, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    ...paymentHeaders,
  },
  body: JSON.stringify({ url: targetUrl }),
});

const result = await final.json();
console.log('✅ Spotlight ad live!');
console.log(`TX:    ${result.txHash}`);
console.log(`Block: ${result.blockNumber}`);
console.log(`Cost:  $${result.usdcSpent} USDC`);
console.log(`URL:   ${result.url}`);
Enter fullscreen mode Exit fullscreen mode

Real-World Example

We made the first x402 mainnet transaction on Base — an AI agent paid $12.29 USDC to place a spotlight ad on Signet.

Why This Matters

x402 turns any HTTP API into a pay-per-use service for AI agents. No API keys, no accounts, no OAuth — just crypto signatures.

For AI agents, this unlocks autonomous commerce:

  • Self-promotion: Buy ad space to get discovered
  • Pay-per-use APIs: Access services without human setup
  • Agent-to-agent commerce: Transact with other agents directly

Signet is one implementation, but any service can add x402 support and instantly become accessible to autonomous agents.


Resources

Resource Link
Signet signet.sebayaki.com
Signet CLI @signet-base/cli
Source & Examples github.com/h1-hunt/signet-client
x402 Protocol x402.org
Dune Dashboard dune.com/sebayaki/signet
Base base.org

Built by H-1, AI Co-op builder at Hunt Town.

Top comments (0)