This guide shows you how to enable AI agents to programmatically create and complete USDC transactions for goods or services on Base using Coinbase Commerce and AgentKit.

Overview

With this guide, you’ll learn how to:

  • Integrate Coinbase Commerce: Create orders and enable USDC payments on Base. Coinbase Commerce offers order tracking, reporting, webhook notifications, and built-in business tools that streamline payment management.
  • Add AgentKit Tools: Extend agents with the ability to handle charges and payments programmatically.

Step 1. Prerequisites

Before getting started:

  1. Install AgentKit and its dependencies.
  2. Sign up for Coinbase Commerce.
  3. Obtain a Commerce API key and set it as an environment variable (COINBASE_COMMERCE_KEY).
  4. Ensure the wallet linked to your agent is connected to Base Mainnet.

Note: The AgentKit Quickstart provides a more detailed getting-started flow.

Step 2. Add AgentKit and Agentic Commerce SDK

Install Required Packages

npm install @agentkit/core @cdp/agentic-commerce-sdk

Update Your Chatbot File

Integrate the Agentic Commerce SDK with AgentKit by adding the following components.

Step 3: Enable Coinbase Commerce Interactions

Define Constants

Add these constants to define Coinbase Commerce endpoints and your project ID:

const COMMERCE_API_URL = "https://api.commerce.coinbase.com/charges";
const ONRAMP_BASE_URL = "https://pay.coinbase.com/buy/select-asset";
const PROJECT_ID = "YOUR-PROJECT-ID";

Create Charge Schema

Define a schema for charge requests:

interface ChargeRequest {
  name: string;
  description: string;
  pricing_type: string;
  local_price: {
    amount: string;
    currency: string;
  };
}

Implement createCharge Function

Add the following function to enable charge creation:

async function createCharge(
  wallet: Wallet,
  args: {
    name: string;
    description: string;
    amount: string;
    currency: string;
    pricing_type: "fixed_price" | "no_price";
  },

): Promise<string> {
  const params: ChargeRequest = {
    name: args.name,
    description: args.description,
    pricing_type: args.pricing_type,
    local_price: {
      amount: args.amount,
      currency: args.currency,
    },
  };

  const response = await fetch(COMMERCE_API_URL, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "X-CC-Api-Key": process.env.COINBASE_COMMERCE_KEY || "",
    },
    body: JSON.stringify(params),
  });

  if (!response.ok) {
    throw new Error(`Failed to create charge: \${response.statusText}`);
  }

  const data = await response.json();
  return `Successfully created charge:
    Name: \${data.data.name}
    Description: \${data.data.description}
    Amount: \${data.data.pricing.local.amount} \${data.data.pricing.local.currency}
    Hosted URL: \${data.data.hosted_url}`;
}

Add a function to generate Coinbase Onramp links for purchasing crypto:

async function createOnrampLink(
  wallet: Wallet,
  args: { blockchain: string },
): Promise<string> {
  const address = (await wallet.getDefaultAddress()).getId();

  if (wallet.getNetworkId() == "base-sepolia") {
    return "Error: Wallet is not on Base Mainnet, use a faucet instead.";
  }

  const addressesObj = { [address.toString()]: [args.blockchain] };

  const onrampUrl = new URL(ONRAMP_BASE_URL);
  onrampUrl.searchParams.append("appId", PROJECT_ID);
  onrampUrl.searchParams.append("addresses", JSON.stringify(addressesObj));

  return `Generated Coinbase Onramp Link:
    URL: \${onrampUrl.toString()}
    Wallet Address: \${address}
    Blockchain: \${args.blockchain}`;
}

Step 5: Add Tools to AgentKit

Define Tool Prompts

const CREATE_CHARGE_PROMPT = `
This tool creates a new charge using the Coinbase Commerce API.
Use this to create a payment request or invoice.
`;
const CREATE_ONRAMP_LINK_PROMPT = `
This tool generates a Coinbase Onramp link for crypto purchases sent to a wallet.
`;

Add Tools to AgentKit

const createChargeTool = new CdpTool(
  {
    name: "create_charge",
    description: CREATE_CHARGE_PROMPT,
    argsSchema: CreateChargeInput,
    func: createCharge,
  },
  agentkit,
);

const createOnrampLinkTool = new CdpTool(
  {
    name: "create_onramp_link",
    description: CREATE_ONRAMP_LINK_PROMPT,
    argsSchema: CreateOnrampLinkInput,
    func: createOnrampLink,
  },
  agentkit,
);

tools.push(createChargeTool, createOnrampLinkTool);

Step 6: Create an Order API

Define an API endpoint for order creation:

app.post('/create-order', async (req, res) => {
  const { items, deliveryAddress, totalAmount } = req.body;

  if (!items || !deliveryAddress || !totalAmount) {
    return res.status(400).json({ error: "Missing order details" });
  }

  const orderId = `order-\${Date.now()}`;
  // Save order to the database (implementation not shown)
  
  res.json({ success: true, orderId, totalAmount });
});

Step 7: Integrate and Test

  1. Start your application.
  2. Use the agent to:
    • Create an order.
    • Generate a Coinbase Commerce charge using createCharge.
    • Pay the charge programmatically or share the checkout link.

See Also: