SDK v0.1 · Base Mainnet

AgentPay SDK

Banking infrastructure for AI agent fleets. Give every agent its own on-chain wallet, budget, and spending rules — in a single API call.

Installation

Install the AgentPay SDK via npm, yarn, or pnpm.

bash
npm install @agentpay/sdk
# or
yarn add @agentpay/sdk
# or
pnpm add @agentpay/sdk

Requirements: Node.js ≥ 18, TypeScript ≥ 5.0 (recommended). The SDK is ESM-first and ships with full type definitions.

Quickstart

Create your first agent wallet and execute a payment in under 5 minutes.

typescript
import { AgentPay } from '@agentpay/sdk'

const pay = new AgentPay({
  apiKey: process.env.AGENTPAY_KEY!,
  network: 'base-mainnet', // or 'base-sepolia' for testnet
})

// 1. Create a wallet for your agent
const agent = await pay.createAgent('research-001', {
  label: 'Research Agent',
  dailyLimitUSDC: 50,
})

console.log(agent.address) // 0x1a2b3c...

// 2. Fund it (send USDC to agent.address from your treasury)

// 3. Agent pays for an API call
const tx = await pay.pay({
  fromAgentId: 'research-001',
  toAddress: '0xYourServiceAddress',
  amountUSDC: 0.04,
  memo: 'GPT-4o call · 1k tokens',
})

console.log(tx.hash) // 0xabc...

// 4. Check remaining budget
const balance = await pay.getBalance('research-001')
// { usdc: 49.96, spentToday: 0.04, remainingToday: 49.96, limit: 50 }

Authentication

All SDK methods are authenticated with an API key. Generate your key from the dashboard.

typescript
import { AgentPay } from '@agentpay/sdk'

const pay = new AgentPay({
  apiKey: process.env.AGENTPAY_KEY!, // Keep this secret
  network: 'base-mainnet',
})

Constructor options

apiKeyrequired
string

Your AgentPay API key. Never expose this client-side.

network
string

"base-mainnet" (default) or "base-sepolia" for testnet

rpcUrl
string

Optional custom RPC URL. Defaults to Alchemy's Base endpoint.

timeout
number

Request timeout in milliseconds. Default: 30000.

createAgent()

Provisions a new smart wallet on Base for an agent. The wallet is a minimal ERC-4337 account — fully on-chain, non-custodial.

typescript
const agent = await pay.createAgent(agentId: string, options: {
  label?: string
  dailyLimitUSDC?: number
  allowedRecipients?: string[] // whitelist of to-addresses
})

// Returns:
// {
//   agentId: string
//   address: string       // on-chain wallet address
//   label: string
//   dailyLimit: number
//   createdAt: string
// }

Parameters

agentIdrequired
string

Your internal identifier for this agent. Must be unique within your account.

label
string

Human-readable name shown in the dashboard.

dailyLimitUSDC
number

Maximum USDC the agent can spend per 24h window. Enforced on-chain.

allowedRecipients
string[]

If set, the agent can only send to these addresses. Empty = unrestricted.

typescript
// Example: Orchestrator creating sub-agents
const agents = await Promise.all([
  pay.createAgent('scraper-001', { label: 'Web Scraper', dailyLimitUSDC: 10 }),
  pay.createAgent('analyst-001', { label: 'Data Analyst', dailyLimitUSDC: 25 }),
  pay.createAgent('writer-001', { label: 'Content Writer', dailyLimitUSDC: 15 }),
])

console.log(agents.map(a => a.address))
// ['0x1a2b...', '0x3c4d...', '0x5e6f...']

pay()

Executes a USDC transfer from an agent wallet. Checks daily limit before sending; throws LimitExceededError if the spend would exceed the cap.

typescript
const tx = await pay.pay({
  fromAgentId: string
  toAddress: string      // recipient on Base
  amountUSDC: number
  memo?: string          // stored on-chain as calldata
})

// Returns:
// {
//   hash: string         // transaction hash
//   blockNumber: number
//   status: 'confirmed' | 'pending'
//   fee: number          // gas fee in USDC equivalent
// }

Parameters

fromAgentIdrequired
string

ID of the paying agent. Must have been created with createAgent().

toAddressrequired
string

Recipient address. Must be in allowedRecipients if that whitelist is set.

amountUSDCrequired
number

Amount to transfer. Minimum 0.001 USDC.

memo
string

Optional memo stored as hex calldata on-chain. Useful for billing/audit trails.

Latency: Transactions confirm in ~2s on Base Mainnet. The SDK waits for 1 confirmation before returning. Use pay.payAndWait() to wait for finality (12 blocks, ~24s).

getBalance()

Returns the current balance and spend status of an agent wallet.

typescript
const balance = await pay.getBalance(agentId: string)

// Returns:
// {
//   usdc: number           // current USDC balance
//   spentToday: number     // USDC spent in rolling 24h window
//   remainingToday: number // dailyLimit - spentToday
//   limit: number          // configured daily limit
//   updatedAt: string      // last on-chain update
// }
typescript
// Monitor a fleet
const fleet = await pay.listAgents()
const overBudget = fleet.filter(a =>
  a.spentToday / a.dailyLimit > 0.9
)

if (overBudget.length > 0) {
  console.warn('Agents near daily limit:', overBudget.map(a => a.label))
}

setDailyLimit()

Updates the daily spend cap for an agent. Takes effect immediately — if the new limit is lower than today's spend, further payments are blocked until the 24h window resets.

typescript
await pay.setDailyLimit(agentId: string, limitUSDC: number)

// Example: emergency cap a runaway agent
await pay.setDailyLimit('scraper-001', 0)
// → agent is now fully blocked

listAgents()

Returns all agents in your account with their current balances and spend status.

typescript
const agents = await pay.listAgents(options?: {
  includeInactive?: boolean // default: false
})

// Returns Agent[] where each Agent is:
// {
//   agentId: string
//   address: string
//   label: string
//   dailyLimit: number
//   spentToday: number
//   balance: number
//   txCount: number
//   createdAt: string
//   active: boolean
// }

getTransactions()

Fetches transaction history for an agent or the entire fleet.

typescript
const txs = await pay.getTransactions(options?: {
  agentId?: string     // filter by agent (omit for all)
  limit?: number       // default: 50, max: 500
  before?: string      // cursor for pagination
  after?: string       // ISO date filter
})

// Returns:
// {
//   transactions: Transaction[]
//   nextCursor?: string     // for pagination
//   total: number
// }
typescript
// Example: audit trail for billing
const txs = await pay.getTransactions({
  agentId: 'analyst-001',
  after: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString(),
  limit: 500,
})

const totalSpent = txs.transactions
  .reduce((sum, tx) => sum + tx.amountUSDC, 0)

console.log(`analyst-001 spent $${totalSpent.toFixed(2)} last 30 days`)

Webhooks

AgentPay can POST events to your endpoint in real time. Configure your webhook URL in the dashboard.

Event types

payment.confirmed

A pay() transaction confirmed on-chain.

payment.failed

A transaction failed (reverted or gas issue).

limit.exceeded

Agent tried to exceed its daily limit.

limit.warning

Agent has spent 80% of its daily limit.

balance.low

Agent USDC balance below 10 USDC.

agent.created

New agent wallet deployed.

typescript
// Webhook payload shape
interface WebhookEvent {
  id: string
  type: string            // e.g. 'payment.confirmed'
  timestamp: string
  agentId: string
  data: {
    hash?: string         // tx hash (payment events)
    amountUSDC?: number
    toAddress?: string
    spentToday?: number
    limit?: number
    balance?: number
  }
}

// Verify the webhook signature (HMAC-SHA256)
import crypto from 'crypto'

function verifyWebhook(payload: string, signature: string, secret: string) {
  const expected = crypto
    .createHmac('sha256', secret)
    .update(payload)
    .digest('hex')
  return crypto.timingSafeEqual(
    Buffer.from(signature),
    Buffer.from(`sha256=${expected}`)
  )
}

Error Handling

All SDK methods throw typed errors. Import them to catch specific cases.

typescript
import {
  AgentPayError,
  LimitExceededError,
  InsufficientBalanceError,
  AgentNotFoundError,
  UnauthorizedRecipientError,
} from '@agentpay/sdk'

try {
  await pay.pay({
    fromAgentId: 'research-001',
    toAddress: '0xSomeAddress',
    amountUSDC: 100,
  })
} catch (err) {
  if (err instanceof LimitExceededError) {
    // Agent hit its daily cap
    console.log(`Limit: $${err.limit}, Spent: $${err.spentToday}`)
  } else if (err instanceof InsufficientBalanceError) {
    // Not enough USDC in the wallet
    console.log(`Balance: $${err.balance}, Needed: $${err.required}`)
  } else if (err instanceof UnauthorizedRecipientError) {
    // toAddress not in allowedRecipients
    console.log('Recipient not whitelisted:', err.address)
  } else {
    throw err
  }
}

Error classes

LimitExceededError

Daily spend limit would be exceeded. Has .limit and .spentToday.

InsufficientBalanceError

Agent wallet has insufficient USDC. Has .balance and .required.

AgentNotFoundError

No agent found for the given agentId.

UnauthorizedRecipientError

toAddress is not in the agent's allowedRecipients list.

NetworkError

RPC or network timeout. Safe to retry.

Ready to ship?

10 agent wallets and 1,000 transactions/month — free forever.

Open Dashboard →