import { CdpClient } from "@coinbase/cdp-sdk";
import axios from "axios";
import { privateKeyToAccount } from "viem/accounts";
import { x402Client, wrapAxiosWithPayment, decodePaymentResponseHeader } from "@x402/axios";
import { registerExactEvmScheme } from "@x402/evm/exact/client";
const apiKeyId = process.env.CDP_API_KEY_ID as string;
const apiKeySecret = process.env.CDP_API_KEY_SECRET as string;
const walletSecret = process.env.CDP_WALLET_SECRET as string;
const walletAddress = process.env.WALLET_ADDRESS as string;
const receiver = process.env.RECEIVER as string;
const amount = parseFloat(process.env.AMOUNT || "0.01");
async function sendPayment() {
console.log("🚀 Starting Snack Money payment with CDP SDK (Base)\n");
// Initialize CDP client
const cdpClient = new CdpClient({
apiKeyId,
apiKeySecret,
walletSecret,
});
console.log("✅ Initialized CDP client\n");
// Export private key from CDP for x402 signing
console.log("🔐 Exporting private key from CDP...\n");
const privateKey = await cdpClient.evm.exportAccount({
address: walletAddress
});
// Create viem account from private key
const account = privateKeyToAccount(`0x${privateKey}`);
console.log(`✅ Base signer created: ${account.address}\n`);
// Create x402 client and register EVM scheme
const x402 = new x402Client();
registerExactEvmScheme(x402, { signer: account });
console.log("✅ Registered EVM payment scheme\n");
// Wrap axios with payment interceptor
const api = wrapAxiosWithPayment(
axios.create({ baseURL: "https://api.snack.money" }),
x402
);
console.log(`💸 Sending ${amount} USDC to @${receiver} on X via Base...\n`);
try {
const response = await api.post("/payments/x/pay", {
amount,
currency: "USDC",
receiver,
description: "Payment via CDP SDK (Base)"
});
console.log("✅ Payment successful!");
console.log("\n📊 Response:", JSON.stringify(response.data, null, 2));
const paymentResponseHeader = response.headers["payment-response"];
if (paymentResponseHeader) {
const paymentResponse = decodePaymentResponseHeader(paymentResponseHeader);
console.log("\n🔐 Payment Response Details:", JSON.stringify(paymentResponse, null, 2));
}
} catch (error) {
console.error("❌ Payment failed:", error);
throw error;
}
}
sendPayment();