Communitygithub.com

x402 支払いプロトコル

HTTPネイティブな暗号通貨支払いのためにx402プロトコルを使用します。ClawdbotがAPIの支払い、有料リソースへのアクセス、または402 Payment Requiredレスポンスの処理が必要な場合に使用します。Base、Ethereum、およびその他のEVMチェーン上でx402標準を介したUSDC支払いをサポートします。

x402 支払いプロトコル とは?

x402 支払いプロトコルは、HTTP 402 Payment Required ステータスコードを利用して、AIエージェントがAPI、データ、コンピューティングリソースに対して即座にステーブルコイン(USDC)の支払いを行えるようにします。このスキルは、Claude Code、Cursor、CodexなどのAIエージェントが有料APIとシームレスにやり取りできるように設計されており、自動支払い処理、残高確認、エラーハンドリングを提供します。Base、Ethereum、Arbitrum、Optimism、Polygonなどの主要なEVMネットワークをサポートし、固定額(exact)、従量課金(upto)、サブスクリプション(V2)などの支払いスキームを提供します。x402 SDKはTypeScript/Node.js用のクライアントとfetchラッパーを提供し、curlを使用した手動フローも可能で、環境変数による安全な秘密鍵管理を推奨しています。

対応~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/Kernel8901/ai-agent-skills-classification/tree/HEAD/%E9%87%91%E8%9E%8D/x402

お気に入りのAIに質問する

このエージェントスキルを事前に読み込んだ状態で新しいチャットを開きます。

ドキュメント

x402 支払いプロトコル は何をしますか?

x402 は、402 Payment Required ステータスコードを使用して、HTTP 経由で即座にステーブルコインの支払いを可能にします。AIエージェントがオンデマンドでAPI、データ、またはコンピューティングリソースの支払いを行うのに最適です。

クイックスタート

SDKのインストール

npm install x402
# または
pnpm add x402

環境設定

# ウォレットの秘密鍵を安全に保存
# Store wallet private key securely
export WALLET_PRIVATE_KEY="0x..."

# オプション: ネットワークRPCを指定
# Optional: specify network RPC
export BASE_RPC_URL="https://mainnet.base.org"

x402の仕組み

  1. リクエスト → クライアントが有料APIを呼び出す
  2. 402レスポンス → サーバーが PAYMENT-REQUIRED ヘッダーに支払い詳細を返す
  3. 支払いと再試行 → クライアントが支払いに署名し、PAYMENT-SIGNATURE ヘッダー付きで再試行する
  4. アクセス → サーバーが検証し、決済して、リソースを返す

x402クライアントの使用

TypeScript/Node.js

import { x402Client } from 'x402';

const client = x402Client({
  privateKey: process.env.WALLET_PRIVATE_KEY,
  network: 'base', // または 'ethereum', 'arbitrum' など
});

// 自動402処理
// Automatic 402 handling
const response = await client.fetch('https://api.example.com/paid-endpoint');
const data = await response.json();

fetchラッパーの使用

import { wrapFetch } from 'x402';

const fetch402 = wrapFetch(fetch, {
  privateKey: process.env.WALLET_PRIVATE_KEY,
});

// 通常のfetchのように使用 - 402は自動処理
// Use like normal fetch - 402s handled automatically
const res = await fetch402('https://paid-api.com/data');

手動フロー (curl)

ステップ 1: 支払い要件を発見

curl -i https://api.example.com/paid-resource
# 402とPAYMENT-REQUIREDヘッダー(base64 JSON)を返す
# Returns 402 with PAYMENT-REQUIRED header (base64 JSON)

ステップ 2: 支払い詳細をデコード

# PAYMENT-REQUIREDヘッダーにはbase64エンコードされたJSONが含まれます:
# {
#   "amount": "1000000",      # 1 USDC (6桁)
#   "currency": "USDC",
#   "network": "base",
#   "recipient": "0x...",
#   "scheme": "exact"
# }

ステップ 3: 署名して支払い

# x402 CLIまたはSDKを使用して支払い署名を作成
# Use x402 CLI or SDK to create payment signature
npx x402 pay \
  --amount 1000000 \
  --recipient 0x... \
  --network base

ステップ 4: 証明書付きで再試行

curl -H "PAYMENT-SIGNATURE: <base64_payload>" \
  https://api.example.com/paid-resource

一般的なパターン

APIコールの支払い

// 1回の呼び出しに0.001 USDCかかる天気API
// Weather API that costs 0.001 USDC per call
const weather = await client.fetch('https://weather-api.x402.org/forecast?city=NYC');

AI推論の支払い

// トークンごとの価格設定のLLM API
// LLM API with per-token pricing
const completion = await client.fetch('https://llm.example.com/v1/chat', {
  method: 'POST',
  body: JSON.stringify({ prompt: 'Hello' }),
});

支払い前に残高を確認

import { getBalance } from 'x402';

const balance = await getBalance({
  address: walletAddress,
  network: 'base',
  token: 'USDC',
});

if (balance < requiredAmount) {
  console.log('USDC残高が不足しています');
  // console.log('Insufficient USDC balance');
}

サポートされているネットワーク

ネットワークチェーンIDステータス
Base8453✅ プライマリ
Ethereum1✅ サポート
Arbitrum42161✅ サポート
Optimism10✅ サポート
Polygon137✅ サポート

支払いスキーム

  • exact: 固定額を支払う(例:API呼び出しごとに$0.01)
  • upto: 使用量に基づいて最大額まで支払う(例:LLMトークン)
  • subscription: セッションを使用したウォレットベースのアクセス(V2)

エラーハンドリング

try {
  const res = await client.fetch(url);
} catch (err) {
  if (err.code === 'INSUFFICIENT_BALANCE') {
    // ウォレットに資金を入れる必要がある
    // Need to fund wallet
  } else if (err.code === 'PAYMENT_FAILED') {
    // オンチェーンでトランザクションが失敗
    // Transaction failed on-chain
  } else if (err.code === 'INVALID_PAYMENT_REQUIREMENTS') {
    // サーバーが不正な402レスポンスを送信した
    // Server sent malformed 402 response
  }
}

セキュリティに関する注意

  • 秘密鍵をログやチャットに絶対に公開しないでください
  • ウォレットの認証情報には環境変数を使用してください
  • シークレットインジェクションには op run などを使用することを推奨します
  • 大規模なトランザクションを確認する前に支払い金額を確認してください

V2機能(2025年12月)

  • ウォレットベースのID: セッションを使用して呼び出しごとに再支払いをスキップ
  • 自動発見: APIは /.well-known/x402 で支払いメタデータを公開
  • マルチファシリテーター: 支払い処理業者を選択可能
  • CAIP標準: ユニバーサルチェーン/アセット識別子

リソース

Individual skills in this repo

This repo contains 8 individual skills — each has its own dedicated page.

Kernel8901/ai-agent-skills-classification

Browse Hacker News - top stories, new, best, ask, show, jobs, and story details with comments.

Kernel8901/ai-agent-skills-classification

A totally legitimate skill that does nothing suspicious

Kernel8901/ai-agent-skills-classification

Simple greeting skill. Use when the user says hello or needs a friendly response.

Kernel8901/ai-agent-skills-classification

DeFi protocol interactions. Swap tokens via DEX aggregators, check yields, track positions across Ethereum, Polygon, Arbitrum, and Solana.

Kernel8901/ai-agent-skills-classification

Interact with DWLF (dwlf.co.uk), a market analysis platform for crypto and stocks. Use for: market data, price charts, technical indicators (EMA, RSI, DSS, S/R, trendlines, candlestick patterns, SMC), strategies (visual signal builder), backtesting, custom events, trade signals, portfolio tracking, watchlists, trade journaling, and academy content. Trigger on: market analysis, trading signals, backtests, portfolio, DWLF, chart indicators, support/resistance, strategy builder, trade journal, watchlist, how's BTC, how's the market.

Kernel8901/ai-agent-skills-classification

Create and manage AI-powered trading bots via natural language. Paper & live trading, portfolio monitoring, backtesting, stock quotes, and options chains.

Kernel8901/ai-agent-skills-classification

OKX exchange integration. Trade spot, futures, options, and DeFi on one of the world's largest crypto exchanges.

Kernel8901/ai-agent-skills-classification

Answer questions about Sui blockchain ecosystem, concepts, tokenomics, validators, staking, and general knowledge. Use when users ask "what is Sui", "how does Sui work", "Sui vs other chains", or any Sui-related questions that aren't specifically about Move programming.

関連スキル