Pay & earn/ UTILITY 4Live

Agent-to-Agent Trade

An agent can be a buyer and a seller at the same time: it pays other agents for inputs and charges for what it makes from them. Nothing special is required. It is two x402 roles in one process.

On this page+

The pattern

lib/agent-wallet.ts
import { createKeyPairSignerFromBytes, getBase58Encoder } from "@solana/kit";
import { x402Client, wrapFetchWithPayment } from "@x402/fetch";
import { ExactSvmScheme } from "@x402/svm/exact/client";

const signer = await createKeyPairSignerFromBytes(
  getBase58Encoder().encode(process.env.AGENT_SECRET_KEY!),
);

export const paidFetch = wrapFetchWithPayment(
  fetch,
  new x402Client()
    .register("solana:*", new ExactSvmScheme(signer))
    .setSpendControls({ maxAmountPerPayment: "$0.02" }),
);
app/api/brief/route.ts
import { NextResponse } from "next/server";
import { withX402 } from "@x402/next";
import { server, SOLANA_MAINNET } from "@/lib/x402";
import { paidFetch } from "@/lib/agent-wallet";

const AXONPAY = "https://axonpay.fun";

export const GET = withX402(
  async () => {
    // Buy two inputs from Axonpay's own paid endpoints ($0.012 in total)...
    const [brief, xstocks] = await Promise.all([
      paidFetch(`${AXONPAY}/api/x402/brief`).then((r) => r.json()),
      paidFetch(`${AXONPAY}/api/x402/xstocks`).then((r) => r.json()),
    ]);
    // ...and sell what you make of them for $0.03.
    return NextResponse.json({ brief, xstocks, take: "your agent's analysis goes here" });
  },
  {
    accepts: { scheme: "exact", price: "$0.03", network: SOLANA_MAINNET, payTo: process.env.AXON_PAY_TO! },
    description: "Today's Solana brief plus xStocks premiums, with our take",
  },
  server,
);

The upstream sellers here are Axonpay’s own paid endpoints, so the example runs against real prices: the agent spends $0.012 and charges $0.03. All three payments are ordinary Solana transfers with their own signatures, so the whole supply chain can be audited on chain and in the receipts ledger.

Who pays first

With withX402, the buyer’s payment is verified before your handler runs and settled after it succeeds. Your agent therefore pays its suppliers before it has been paid. If the upstream calls succeed and your handler then fails, you have spent and earned nothing. Keep upstream spend per request small, under the per-call cap of the agent wallet.

Keep the two keys apart

  • The selling side only needs a payTo address. It can be a cold wallet that never signs anything.
  • The buying side uses an agent wallet under a mandate, so a buggy or prompt-injected agent can lose at most its daily budget.
  • Never reuse the payTo key as the agent key.

Composite calls