>_ P402 Documentation / Coinbase AgentKit

Coinbase AgentKit.

Plug CDP-managed autonomous wallets into P402 multi-provider AI routing. Agents spend USDC automatically — no private keys, no gas management.

What This Enables

Programmable Wallets

CDP provisions an MPC wallet per agent. No seed phrase exposure, TEE-grade key management.

Spending Policies

Set per-agent limits at wallet creation. Policy enforcement is on-chain — P402 can't override it.

Gasless Payments

x402 EIP-3009 transfers. Agent signs; P402 facilitator pays gas. USDC only moves when AI work completes.

Installation

# Install both SDKs
npm install @coinbase/agentkit @p402/sdk

# Required env vars
CDP_API_KEY_NAME=organizations/…
CDP_API_KEY_PRIVATE_KEY="-----BEGIN EC PRIVATE KEY-----…"
P402_API_KEY=p402_live_…

Get your P402 API key from Dashboard → Settings. CDP credentials from portal.cdp.coinbase.com ↗.

Quickstart

Provision a wallet, attach a spending policy, and route your first AI call in under 30 lines:

import { CdpClient } from '@coinbase/agentkit';
import { P402Client } from '@p402/sdk';

// 1. Provision an agent wallet (runs once per agent)
const cdp = new CdpClient();
const wallet = await cdp.evm.createSmartWallet({ networkId: 'base' });

// 2. Attach a $10/day spending policy
await cdp.policies.createPolicy({
  policy: {
    scope: 'account',
    rules: [{
      action: 'reject',
      operation: 'signEvmTransaction',
      criteria: [{
        type: 'ethValue',
        operator: '>',
        // ~10 USD in ETH at $2500/ETH
        value: '4000000000000000',
      }]
    }]
  }
});

// 3. Route an AI call through P402
const p402 = new P402Client({ apiKey: process.env.P402_API_KEY });

const response = await p402.chat({
  messages: [{ role: 'user', content: 'Summarize the latest Base L2 activity.' }],
  p402: { mode: 'cost', cache: true }
});

console.log(response.choices[0].message.content);
// p402_metadata.cost_usd — actual USDC deducted
console.log(response.p402_metadata?.cost_usd);

Session-Based Budget Control

For long-running agents, create a P402 session that tracks spend across multiple calls:

// Create a session with a $5 USDC budget, 24h expiry
const session = await p402.createSession({
  budget_usd: 5.0,
  expires_in_hours: 24,
  wallet_address: wallet.address,
});

// Attach session to all calls in this agent run
const p402WithSession = new P402Client({
  apiKey: process.env.P402_API_KEY,
  // Session ID scopes billing to this run
});

// Session stats — check remaining budget any time
const stats = await fetch(
  `https://p402.io/api/v2/sessions/${session.id}/stats`,
  { headers: { 'X-P402-Session': session.session_token } }
).then(r => r.json());

console.log(`Remaining: $${stats.budget_remaining_usd}`);

AP2 Spending Mandates

Mandates let a human authorize an agent to spend up to a limit — without handing over wallet keys:

// Human issues a mandate to the CDP wallet
const mandate = await fetch('https://p402.io/api/v2/governance/mandates', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${P402_API_KEY}`,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    type: 'payment',
    user_did: 'did:p402:tenant:usr_abc123',
    agent_did: `did:p402:agent:cdp:${wallet.address}`,
    constraints: {
      max_amount_usd: 50,
      allowed_categories: ['ai', 'data'],
      valid_until: new Date(Date.now() + 7 * 86400_000).toISOString(),
    },
  }),
}).then(r => r.json());

console.log(`Mandate issued: ${mandate.id}`);
// Mandate enforcement is automatic — P402 checks before every settlement

Error Handling

Error CodeHTTPMeaningAction
CDP_POLICY_DENIED403Wallet spending policy exceededIncrease CDP policy limit or reduce request cost
MANDATE_BUDGET_EXCEEDED403AP2 mandate budget exhaustedIssue a new mandate or increase max_amount_usd
RATE_LIMIT_EXCEEDED429P402 rate limit hitRetry after Retry-After header duration
INSUFFICIENT_FUNDS402USDC balance too lowFund wallet via cdp.evm.transfer() or Coinbase
REPLAY_DETECTED400EIP-3009 nonce already usedRetry with a fresh nonce (auto-handled by SDK)

Further Reading