Communitygithub.com

agent-payment-x402

AI 에이전트에 x402 결제 실행 기능을 추가합니다. 작업별 예산, 지출 제어 및 비수탁형 지갑을 지원합니다. Base(agentwallet-sdk)와 X Layer(OKX Payments / OKX Agent Payments Protocol)를 지원합니다. 에이전트가 스스로 비용을 지불해야 하고 작업별 예산, 지출 제어 및 비수탁형 지갑이 필요한 경우 사용하세요.

agent-payment-x402란 무엇인가요?

이 스킬은 AI 에이전트가 정책 기반 결제를 수행할 수 있도록 하는 x402 결제 실행 스킬입니다. 에이전트가 외부 API, 서비스 또는 다른 에이전트에게 비용을 지불해야 할 때 사용되며, 작업별 예산, 세션별 예산, 허용된 수신자 목록, 속도 제한 등의 지출 제어 기능을 내장하고 있습니다. Base 네트워크에서는 agentwallet-sdk를 MCP 결제 서버로 사용하고, X Layer에서는 OKX Agent Payments Protocol을 사용합니다. ERC-4337 스마트 계정을 기반으로 한 비수탁형 지갑을 사용하므로 에이전트가 정해진 범위 내에서만 지출할 수 있으며, 자금 풀링이나 수탁 위험이 없습니다. 오케스트레이터가 지출 정책을 설정하고 에이전트에게 위임하며, 에이전트는 정해진 한도 내에서만 결제를 실행할 수 있어 안전성과 통제력을 보장합니다.

지원 대상✓Claude Code~Codex CLI~Cursor
npx skills add https://github.com/affaan-m/ECC/tree/main/skills/agent-payment-x402

즐겨 사용하는 AI에게 물어보기

이 에이전트 스킬이 미리 로드된 새 채팅을 엽니다.

문서

에이전트 결제 실행 (x402)

AI 에이전트가 내장된 지출 제어 기능을 통해 정책 기반 결제를 할 수 있도록 합니다. x402 HTTP 결제 프로토콜과 MCP 도구를 사용하여 에이전트가 수탁 위험 없이 외부 서비스, API 또는 다른 에이전트에 비용을 지불할 수 있습니다.

사용 시기

다음과 같은 경우에 사용하세요: 에이전트가 API 호출 비용을 지불해야 하거나, 서비스를 구매해야 하거나, 다른 에이전트와 정산해야 하거나, 작업별 지출 한도를 적용해야 하거나, 비수탁형 지갑을 관리해야 하는 경우. cost-aware-llm-pipeline 및 security-review 스킬과 자연스럽게 함께 사용됩니다.

의사 결정 트리

에이전트가 유료 API에 접근하는지, 아니면 다른 사람에게 API 사용료를 청구하는지에 따라 통합 경로를 선택하세요.

필요 사항권장 경로
에이전트가 Base 또는 다른 agentwallet 지원 체인의 402 게이트 API에 비용을 지불엄격한 지출 정책과 함께 agentwallet-sdk를 MCP 결제 서버로 사용
에이전트가 X Layer의 402 게이트 API에 비용을 지불okx/onchainos-skills의 OKX Agent Payments Protocol 사용; okx-x402-payment는 더 이상 사용되지 않는 레거시 별칭
TypeScript API가 에이전트에게 청구Express, Hono, Fastify 또는 Next.js용 OKX Payments TypeScript 판매자 SDK 문서 사용
Go API가 에이전트에게 청구Gin, Echo 또는 net/http용 OKX Payments Go 판매자 SDK 문서 사용
Rust API가 에이전트에게 청구Axum용 OKX Payments Rust 판매자 SDK 문서 사용
Java API가 에이전트에게 청구Spring Boot 2/3, Java EE 또는 Jakarta용 OKX Payments Java 판매자 SDK 문서 사용
Python API가 에이전트에게 청구구현 전에 현재 OKX Payments 저장소 확인; Python 판매자 가이드는 없을 수 있음

지원 네트워크

  • agentwallet-sdk: 프로덕션 전에 패키지 문서를 사용하여 현재 네트워크 범위를 확인하세요. Base Sepolia가 가장 안전한 개발 기본값입니다. Base 메인넷은 원래 스킬에서 명시한 프로덕션 경로입니다.
  • OKX Payments / X Layer: 현재 판매자 문서는 X Layer (eip155:196) 및 USDT0 정산을 대상으로 합니다. 결제 패키지와 파사일레이터 동작이 빠르게 변경될 수 있으므로 프로덕션 코드를 생성하기 전에 최신 SDK 문서를 가져오세요.

작동 방식

x402 프로토콜

x402는 HTTP 402 (결제 필요)를 머신 협상 가능한 흐름으로 확장합니다. 서버가 402를 반환하면 에이전트의 결제 도구가 가격을 협상하고, 예산을 확인하며, 트랜잭션에 서명하고, 오케스트레이터가 설정한 정책 및 확인 경계 내에서만 재시도합니다.

지출 제어

모든 결제 도구 호출은 SpendingPolicy를 적용합니다:

  • 작업별 예산 — 단일 에이전트 작업에 대한 최대 지출
  • 세션별 예산 — 전체 세션에 걸친 누적 한도
  • 허용 수신자 목록 — 에이전트가 지불할 수 있는 주소/서비스 제한
  • 속도 제한 — 분/시간당 최대 트랜잭션 수

비수탁형 지갑

에이전트는 ERC-4337 스마트 계정을 통해 자체 키를 보유합니다. 오케스트레이터가 위임 전에 정책을 설정합니다. 에이전트는 범위 내에서만 지출할 수 있습니다. 풀링된 자금이나 수탁 위험이 없습니다.

MCP 통합

결제 계층은 모든 Claude Code 또는 에이전트 하네스 설정에 연결되는 표준 MCP 도구를 노출합니다.

보안 참고: 항상 패키지 버전을 고정하세요. 이 도구는 개인 키를 관리합니다. 고정되지 않은 npx 설치는 공급망 위험을 초래합니다.

옵션 A: agentwallet-sdk (Base / 멀티체인)

{
  "mcpServers": {
    "agentpay": {
      "command": "npx",
      "args": ["[email protected]"]
    }
  }
}

사용 가능한 도구 (에이전트 호출 가능)

도구목적
get_balance에이전트 지갑 잔액 확인
send_payment주소 또는 ENS로 결제 보내기
check_spending남은 예산 조회
list_transactions모든 결제의 감사 추적

참고: 지출 정책은 에이전트가 아닌 오케스트레이터가 에이전트에게 위임하기 전에 설정합니다. 이는 에이전트가 자체 지출 한도를 높이는 것을 방지합니다. 정책은 set_policy를 통해 오케스트레이션 계층이나 작업 전 훅에서 구성하고, 에이전트 호출 가능 도구로 절대 설정하지 마세요.

옵션 B: OKX Agent Payments Protocol (X Layer)

X Layer x402, 다자간 결제 (MPP), 세션 결제, 청구 및 A2A 청구 흐름에 이 경로를 사용하세요.

구매자 측 에이전트 흐름의 경우:

  1. 현재 okx/onchainos-skills 저장소를 설치하거나 참조하세요.
  2. skills/okx-agent-payments-protocol/SKILL.md를 디스패처로 사용하세요.
  3. skills/okx-x402-payment/SKILL.md는 더 이상 사용되지 않는 호환성 별칭으로 취급하고, 표준 스킬로 취급하지 마세요.
  4. 지갑 상태 확인이나 결제 작업 전에 명시적인 사용자 확인을 요구하세요. 결제 실행을 일반 도구 호출 뒤에 숨기지 마세요.

판매자 측 API 흐름의 경우, 코드를 생성하기 전에 최신 언어별 가이드를 가져오세요:

런타임현재 가이드
TypeScripthttps://raw.githubusercontent.com/okx/payments/main/typescript/SELLER.md
Gohttps://raw.githubusercontent.com/okx/payments/main/go/x402/SELLER.md
Rusthttps://raw.githubusercontent.com/okx/payments/main/rust/x402/SELLER.md
Javahttps://raw.githubusercontent.com/okx/payments/main/java/SELLER.md

현재 OKX 저장소를 확인하지 않고 이전 문서의 예제를 복사하지 마세요. 현재 OKX 지침은 okx-agent-payments-protocol을 디스패처로 사용하며, Java 판매자 문서도 이제 제공됩니다.

예제

MCP 클라이언트의 예산 적용

agentpay MCP 서버를 호출하는 오케스트레이터를 구축할 때는 유료 도구 호출을 디스패치하기 전에 예산을 적용하세요.

전제 조건: MCP 구성을 추가하기 전에 패키지를 설치하세요. -y 없이 npx를 사용하면 비대화형 환경에서 확인을 요청하여 서버가 중단될 수 있습니다: npm install -g [email protected]

import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";

async function main() {
  // 1. 트랜스포트를 구성하기 전에 자격 증명을 검증합니다.
  //    누락된 키는 즉시 실패해야 합니다. 인증 없이 하위 프로세스를 시작하지 마세요.
  const walletKey = process.env.WALLET_PRIVATE_KEY;
  if (!walletKey) {
    throw new Error("WALLET_PRIVATE_KEY가 설정되지 않았습니다 — 결제 서버 시작 거부");
  }

  // stdio 트랜스포트를 통해 agentpay MCP 서버에 연결합니다.
  // 서버가 필요한 환경 변수만 허용 목록에 추가하세요. 개인 키를 관리하는
  // 타사 하위 프로세스에 process.env 전체를 절대 전달하지 마세요.
  const transport = new StdioClientTransport({
    command: "npx",
    args: ["[email protected]"],
    env: {
      PATH: process.env.PATH ?? "",
      NODE_ENV: process.env.NODE_ENV ?? "production",
      WALLET_PRIVATE_KEY: walletKey,
    },
  });
  const agentpay = new Client({ name: "orchestrator", version: "1.0.0" });
  await agentpay.connect(transport);

  // 2. 에이전트에게 위임하기 전에 지출 정책을 설정합니다.
  //    항상 성공을 확인하세요. 무음 실패는 제어 기능이 비활성화되었음을 의미합니다.
  const policyResult = await agentpay.callTool({
    name: "set_policy",
    arguments: {
      per_task_budget: 0.50,
      per_session_budget: 5.00,
      allowlisted_recipients: ["api.example.com"],
    },
  });
  if (policyResult.isError) {
    throw new Error(
      `지출 정책 설정 실패 — 위임하지 마세요: ${JSON.stringify(policyResult.content)}`
    );
  }

  // 3. 유료 작업 전에 preToolCheck 사용
  await preToolCheck(agentpay, 0.01);
}

// 작업 전 훅: 네 가지 개별 오류 경로로 닫힘 실패 예산 적용.
async function preToolCheck(agentpay: Client, apiCost: number): Promise<void> {
  // 경로 1: 잘못된 입력 거부 (NaN/Infinity는 < 비교를 우회함)
  if (!Number.isFinite(apiCost) || apiCost < 0) {
    throw new Error(`잘못된 apiCost: ${apiCost} — 작업 차단됨`);
  }

  // 경로 2: 트랜스포트/연결 실패
  let result;
  try {
    result = await agentpay.callTool({ name: "check_spending" });
  } catch (err) {
    throw new Error(`결제 서비스에 연결할 수 없음 — 작업 차단됨: ${err}`);
  }

  // 경로 3: 도구가 오류 반환 (예: 인증 실패, 지갑 초기화 안 됨)
  if (result.isError) {
    throw new Error(
      `check_spending 실패 — 작업 차단됨: ${JSON.stringify(result.content)}`
    );
  }

  // 경로 4: 응답 형태 구문 분석 및 유효성 검사
  let remaining: number;
  try {
    const parsed = JSON.parse(
      (result.content as Array<{ text: string }>)[0].text
    );
    if (!Number.isFinite(parsed?.remaining)) {
      throw new TypeError("'remaining' 필드가 없거나 유한 숫자가 아님");
    }
    remaining = parsed.remaining;
  } catch (err) {
    throw new Error(
      `check_spending이 예상치 못한 형식 반환 — 작업 차단됨: ${err}`
    );
  }

  // 경로 5: 예산 초과
  if (remaining < apiCost) {
    throw new Error(
      `예산 초과: $${apiCost} 필요하지만 $${remaining}만 남음`
    );
  }
}

main().catch((err) => {
  console.error(err);
  process.exitCode = 1;
});

모범 사례

  • 위임 전에 예산 설정: 하위 에이전트를 생성할 때 오케스트레이션 계층을 통해 SpendingPolicy를 첨부하세요. 에이전트에게 무제한 지출 권한을 절대 부여하지 마세요.
  • 의존성 고정: MCP 구성에서 항상 정확한 버전을 지정하세요 (예: [email protected]). 프로덕션에 배포하기 전에 패키지 무결성을 확인하세요.
  • 감사 추적: 작업 후 훅에서 list_transactions를 사용하여 지출된 금액과 이유를 기록하세요.
  • 닫힘 실패: 결제 도구에 연결할 수 없으면 유료 작업을 차단하고, 측정되지 않은 접근으로 대체하지 마세요.
  • security-review와 함께 사용: 결제 도구는 높은 권한을 가집니다. 셸 접근과 동일한 수준의 검토를 적용하세요.
  • 먼저 테스트넷에서 테스트: 개발에는 Base Sepolia를 사용하고, 프로덕션에는 Base 메인넷으로 전환하세요.

프로덕션 참고 자료

Individual skills in this repo

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

accessibility

Design, implement, and audit inclusive digital products using WCAG 2.2 Level AA. Use when building or auditing UI that must meet WCAG 2.2 Level AA, or when reviewing a change for keyboard, contrast, or screen-reader support.

affaan-m/content-engine

Create platform-native content systems for X, LinkedIn, TikTok, YouTube, newsletters, and repurposed multi-platform campaigns. Use when the user wants social posts, threads, scripts, content calendars, or one source asset adapted cleanly across platforms.

affaan-m/ECC

Multi-platform content distribution across X, LinkedIn, Threads, and Bluesky. Adapts content per platform using content-engine patterns. Never posts identical content cross-platform. Use when the user wants to distribute content across social platforms.

affaan-m/fal-ai-media

Unified media generation via fal.ai MCP — image, video, and audio. Covers text-to-image (Nano Banana), text/image-to-video (Seedance, Kling, Veo 3), text-to-speech (CSM-1B), and video-to-audio (ThinkSound). Use when the user wants to generate images, videos, or audio with AI.

affaan-m/manim-video

日本語翻訳:このファイルは manim-video 用の日本語翻訳が必要です

affaan-m/remotion-video-creation

Remotion のベストプラクティス - React で動画を作成する。3D、アニメーション、音声、字幕、チャート、トランジションなどをカバーするドメイン固有の29のルール。

affaan-m/video-editing

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

agent-architecture-audit

Full-stack diagnostic for agent and LLM applications. Audits the 12-layer agent stack for wrapper regression, memory pollution, tool discipline failures, hidden repair loops, and rendering corruption. Produces severity-ranked findings with code-first fixes. Essential for developers building agent applications, autonomous loops, or any LLM-powered feature. Use when an agent or LLM feature misbehaves and the failing layer is unknown, or before shipping an agent stack.

agent-eval

Head-to-head comparison of coding agents (Claude Code, Aider, Codex, etc.) on custom tasks with pass rate, cost, time, and consistency metrics. Use when choosing between coding agents, or when a change to an agent setup needs measured pass rate, cost, and time rather than an impression.

agent-harness-construction

Design and optimize AI agent action spaces, tool definitions, and observation formatting for higher completion rates. Use when defining or revising an agent

agentic-engineering

Operate as an agentic engineer using eval-first execution, decomposition, and cost-aware model routing. Use when planning or executing engineering work that agents will carry out end to end.

agentic-os

Build persistent multi-agent operating systems on Claude Code. Covers kernel architecture, specialist agents, slash commands, file-based memory, scheduled automation, and state management without external databases. Use when building a persistent multi-agent system on Claude Code with its own memory, commands, and scheduling.

agent-introspection-debugging

Structured self-debugging workflow for AI agent failures using capture, diagnosis, contained recovery, and introspection reports. Use when an agent run fails and you need a reproducible diagnosis instead of a retry.

agent-self-evaluation

Use after completing any non-trivial task. The agent self-rates its output on 5 axes — accuracy, completeness, clarity, actionability, conciseness — with concrete evidence per criterion. Produces a structured 1-5 scorecard with specific improvement suggestions.

agent-sort

Build an evidence-backed ECC install plan for a specific repo by sorting skills, commands, rules, hooks, and extras into DAILY vs LIBRARY buckets using parallel repo-aware review passes. Use when ECC should be trimmed to what a project actually needs instead of loading the full bundle.

ai-first-engineering

Engineering operating model for teams where AI agents generate a large share of implementation output. Use when setting team process, review gates, or ownership rules for a codebase largely written by agents.

ai-regression-testing

Regression testing strategies for AI-assisted development. Sandbox-mode API testing without database dependencies, automated bug-check workflows, and patterns to catch AI blind spots where the same model writes and reviews code. Use when adding regression coverage to AI-assisted code, or when the same model both wrote and reviewed a change.

android-clean-architecture

Clean Architecture patterns for Android and Kotlin Multiplatform projects — module structure, dependency rules, UseCases, Repositories, and data layer patterns. Use when structuring modules, layers, or data flow in an Android or KMP project.

angular-developer

Generates Angular code and provides architectural guidance. Trigger when creating projects, components, or services, or for best practices on reactivity (signals, linkedSignal, resource), forms, dependency injection, routing, SSR, accessibility (ARIA), animations, styling (component styles, Tailwind CSS), testing, or CLI tooling.

api-connector-builder

Build a new API connector or provider by matching the target repo

관련 스킬