const { Wallet, utils } = require('ethers');
// Create a session wallet with limited allowance
const sessionWallet = Wallet.createRandom();
const spendingLimit = utils.parseUnits('10', 6); // 10 USDC tokens
// Implement smart contract logic to enforce spendingLimit (outside this snippet)
For more advanced identity and session key setups, check the erc-8004-agent-identity page.
Agent to Agent Payments: How It Works
Agent-to-agent payments generally operate by embedding micropayment data in request headers or payloads, validated via off-chain or on-chain mechanisms.
Basic flow:
- Agent A initiates payment: Signs a payment authorization to Agent B’s MCP endpoint.
- Agent B validates payment: Verifies the signature and associated funds.
- Service is rendered or data exchanged.
- Settlement occurs on-chain or through MCP server accounting.
The x402 protocol is a popular method for enforcing agent payments, supporting USDC-based micropayments. For a step-by-step build, see the x402 protocol tutorial.
In my experience, an easy-to-overlook gotcha is ensuring both agents agree on the payment currency and chain RPC endpoints. Otherwise, you’ll face validation failures that stall the payment flow.
Handling Agent Micropayments with USDC Stablecoin
USDC is preferred due to its stability and wide chain support, but it also introduces token approval and allowance management complexity.
When wiring USDC into on-chain payments:
- Approve only the required amount to your payment contract upfront (never unlimited approvals).
- Monitor allowance to avoid failed payments.
- Use testnets like Goerli or Polygon Mumbai before mainnet deployment.
Here’s how to check and approve USDC allowance in Solidity-compatible contracts:
IERC20 usdc = IERC20(USDC_ADDRESS);
function ensureAllowance(address spender, uint256 amount) public {
uint256 currentAllowance = usdc.allowance(msg.sender, spender);
if (currentAllowance < amount) {
usdc.approve(spender, amount);
}
}
The downside here: unrestricted approvals can cause wallet draining if the spender turns malicious. I always audit approval scopes carefully.
Apache 402 Payment Required Errors Explained
The HTTP 402 Payment Required status code is part of the x402 protocol specification to enforce payments before access is granted.
Why do these errors appear?
- No payment sent with the request.
- Invalid or expired payment signature.
- Insufficient funds in the paying agent's wallet.
- Mismatched expected payment amount or token.
Usually, the server responds with instructions on how much to pay and to what address in the error payload, helping clients correct payment.
Example Apache server logs:
[error] 402 Payment Required: Missing x402-payment-address header
[info] Payment signature verification failed: invalid signature
If you handle these programmatically, the client code should parse 402 responses to retry automatically after sending a proper payment header.
Slither vs Aderyn for Smart Contract Security
Both Slither and Aderyn are static analysis tools widely used to audit Solidity contracts, but they approach security checks differently.
| Feature |
Slither |
Aderyn |
| Language |
Solidity |
Solidity |
| Maturity |
Stable, widely adopted |
Emerging, evolving |
| Chain support |
EVM chains |
EVM chains |
| Security checks |
Broad vulnerability coverage |
Focused on reentrancy & gas |
| Integration |
CLI, CI/CD, plugins |
CLI, IDE support |
| Custom rule writing |
Yes |
Limited |
Slither flags many common patterns including reentrancy, tx.origin usage, and uninitialized storage. Aderyn’s strength lies in gas and reentrancy detection with some unique heuristics.
In my projects, I run both tools to catch a wider problem set. But watch out: false positives require manual triage.
Check out the troubleshooting-faq if you hit false positives or integration issues.
Troubleshooting Tips and Best Practices
If your agent payments or x402 integration aren't working:
- Enable verbose RPC and MCP logs: Look for signature mismatches or nonce problems.
- Check wallet balances and allowances on-chain to ensure funds are available.
- Validate payment headers are correctly formed and signed.
- Test with minimal amounts on testnets first before scaling your deployment.
- Use official SDKs or libraries where available, as rolling your own x402 implementation is error-prone.
- Avoid unlimited token approvals, and regularly audit agent wallet activity.
When running payment flows locally, a common error is clock skew causing signature expiration. Sync your environment clocks.
FAQs
How do I give an AI agent a wallet safely?
Create session keys with limited spending rights and avoid embedding private keys directly. Use account abstraction standards like ERC-4337 where feasible.
Why do I get "x402 error not working" when sending payments?
Usually an issue with malformed payment headers, insufficient wallet balance, or MCP server nonce conflict.
How does agent-to-agent payment work?
Agents sign off-chain payment authorizations verified by recipient servers before service delivery, often settling on-chain post-facto.
What’s better: Slither or Aderyn?
Both complement each other. Slither is more mature with broader checks; Aderyn specializes in reentrancy and gas issues.
How to deal with Apache 402 Payment Required errors?
Parse the response for payment instructions, then resend request with correct x402 payment headers attached.
Summary and Next Steps
Agent payments combined with AI agent wallets open exciting DeFAI possibilities—but integration challenges and security risks abound. Address "x402 error not working" by carefully verifying payment headers, wallet funds, and MCP server configs. Use session keys to give your agents wallets safely without risking main private keys. For micropayments, USDC is a pragmatic stablecoin choice; just watch your approvals.
If you want a hands-on guide, check my x402 protocol tutorial and practical setups like the NodeJS Express example or Python FastAPI setup.
I encourage you to also run both Slither and Aderyn side-by-side in audit pipelines—they catch complementary Solidity pitfalls.
Got a specific error or want to share a troubleshooting gotcha? Head over to the discussion or check the rest of the troubleshooting-faq cluster.
Happy coding!
Related: AWS x402 on CloudFront
Related: Best Stablecoin for AI Agents