import { X402 } from '@x402/core';
import { createEvmClient } from '@x402/evm';
// Initialize x402 client
const x402Client = createEvmClient({
privateKey: process.env.EVM_PRIVATE_KEY,
chainId: 8453 // Base mainnet
});
// First call - will require payment
const firstCall = await fetch('https://api.snack.money/mcp', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
jsonrpc: '2.0',
method: 'tools/call',
params: {
name: 'pay_twitter',
arguments: {
receiver: 'alice',
amount: 0.01,
description: 'Thanks for the help!'
}
},
id: 3
})
});
const response = await firstCall.json();
// Check if payment is required
if (response.error?.code === -32402) {
const { taskId, paymentRequired } = response.error.data;
// Sign payment
const signedPayment = await x402Client.createPaymentPayload(
paymentRequired
);
// Retry with payment
const paidCall = await fetch('https://api.snack.money/mcp', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
jsonrpc: '2.0',
method: 'tools/call',
params: {
name: 'pay_twitter',
arguments: {
receiver: 'alice',
amount: 0.01,
description: 'Thanks for the help!'
},
_meta: {
taskId,
x402Payment: signedPayment
}
},
id: 4
})
});
const result = await paidCall.json();
console.log('Payment successful:', result.result);
}