Featured Tutorial
Autonomous AI Agent Payments
Enable your AI agents to pay for APIs automatically using the x402 protocol. No human intervention required.
The Agentic Economy: As AI agents become more autonomous, they need to pay for services without human approval for each transaction. Apiosk enables machine-to-machine commerce with automatic micropayments.
Step 1: Set Up Agent Wallet
Create a dedicated wallet for your agent. Never use your personal wallet.
import { generatePrivateKey, privateKeyToAccount } from 'viem/accounts'
// Generate a new wallet for your agent
const privateKey = generatePrivateKey()
const account = privateKeyToAccount(privateKey)
console.log('Agent wallet address:', account.address)
console.log('Private key (save securely!):', privateKey)
// Fund this wallet with USDC on Base (testnet or mainnet)Step 2: Configure Environment
Set up your environment variables:
# .env AGENT_PRIVATE_KEY=0x...your-agent-private-key... GATEWAY_URL=https://gateway.apiosk.com NETWORK=base-sepolia # Use 'base' for production
Step 3: Initialize Agent Client
Use the Apiosk agent client to handle payments automatically:
import { createAgent } from './agent-client'
const agent = createAgent({
gatewayUrl: process.env.GATEWAY_URL!,
privateKey: process.env.AGENT_PRIVATE_KEY!,
network: 'base-sepolia'
})
console.log('Agent initialized:', agent.getAddress())Step 4: Make Autonomous API Calls
The agent handles 402 responses and payment signing automatically:
// Example: Call an AI inference API
const response = await agent.callApi('/openai/gpt4/completion', {
method: 'POST',
body: {
prompt: 'Explain quantum computing in simple terms',
max_tokens: 100
}
})
console.log('AI Response:', response.data)
console.log('Amount paid:', response.paymentInfo.amount, 'USDC')
// Example: Call multiple APIs in sequence
const searchResult = await agent.callApi('/search/web/query', {
method: 'POST',
body: { query: 'latest AI research papers' }
})
const summary = await agent.callApi('/ai/summarize', {
method: 'POST',
body: { text: searchResult.data.results }
})Step 5: Monitor Agent Spending
Track your agent's transactions:
// Track spending in your agent
let totalSpent = 0
async function trackedApiCall(endpoint, options) {
const result = await agent.callApi(endpoint, options)
totalSpent += parseFloat(result.paymentInfo.amount)
console.log(`Total spent: $${totalSpent.toFixed(4)} USDC`)
// Optional: Set spending limit
if (totalSpent > 10.00) {
throw new Error('Agent spending limit exceeded')
}
return result
}Security Best Practices
Wallet Isolation
Use dedicated wallets per agent. Never share wallets between agents or with personal funds.
Spending Limits
Fund agents with only what they need. Implement soft limits in code.
Key Management
Store keys in environment variables or secrets manager. Rotate periodically.
Testnet First
Always develop and test on Base Sepolia before using real USDC on mainnet.