Skip to content

feat(marketplace): x402 micro-payment flow for skill invocation - #442

Open
Peolite001 wants to merge 9 commits into
Bitcoindefi:mainfrom
Peolite001:feature/x402-skills-marketplace-flow
Open

feat(marketplace): x402 micro-payment flow for skill invocation#442
Peolite001 wants to merge 9 commits into
Bitcoindefi:mainfrom
Peolite001:feature/x402-skills-marketplace-flow

Conversation

@Peolite001

Copy link
Copy Markdown
Contributor

Closes #304

feat(marketplace): x402 micro-payment flow for skill invocation

Summary

Implements the x402 micro-payment flow for the skills marketplace. When an agent calls a skill from another agent, the x402 HTTP payment protocol handles the micro-payment automatically before the skill runs.

Changes

New Files

  • lib/marketplace/x402-middleware.ts — Core payment middleware

    • invokeSkillWithPayment(): Attempts skill call → captures 402 → generates Stellar payment → retries with X-Payment header
    • generateStellarPayment(): Builds and submits payment tx via existing /api/stellar/build-tx + /api/stellar/submit-tx
    • Integrates Agent Passport spend-cap gate
    • Supports MOCK_MODE for local development
  • lib/marketplace/invocation-ledger.ts — Payment ledger store

    • In-memory registry (globalThis-persisted across hot reloads)
    • Tracks: { agentId, skillId, amountXLM, txHash, invokedAt, status }
    • Queryable via listInvocations(), getInvocationStats()
  • lib/marketplace/skill-registry.ts — Bridge to PR#304 skill listings

    • registerSkill(), getSkill(), listSkills(), incrementSkillInvocation()
  • app/api/marketplace/skills/[skillId]/invoke/route.ts — Invoke endpoint

    • POST { agentId, payload, payerWallet? }
    • Validates skill exists and is active
    • Orchestrates payment + invocation via middleware
    • Returns { ok, data, paymentProof, invocationId } on success
    • Returns 402 { error: 'insufficient_balance' } on underfunded wallet
  • app/api/marketplace/invocations/route.ts — Ledger query endpoint

    • GET with filters: ?agentId=&skillId=&txHash=&status=&since=&limit=
    • Returns invocation list + aggregated stats
  • lib/marketplace/__tests__/x402-middleware.test.ts — Unit tests

    • Mocked x402 flow with vitest
    • Verifies 402→payment→200 chain
    • Verifies ledger entry matches returned txHash
    • Tests insufficient_balance propagation
    • Tests non-402 error passthrough

Architecture

Agent A ──POST /api/marketplace/skills/skill_123/invoke──┐
{ agentId: "A", payload: {...} } │

┌─────────────────────┐
│ x402-middleware.ts │
│ 1. attemptSkillRequest
│ 2. if 402 → create quote
│ 3. generateStellarPayment
│ 4. settleX402 on-chain
│ 5. retry w/ X-Payment header
└──────────┬──────────┘

┌──────────▼──────────┐
│ invocation-ledger │
│ record → update │
│ (txHash, amountXLM) │
└─────────────────────┘

Acceptance Criteria

  • Agent invokes skill → 402 received → payment sent → skill responds 200
  • Payment proof stored in invocation ledger with correct txHash
  • Insufficient balance → 402 returned to caller with { error: 'insufficient_balance' }
  • Unit test: mock x402 flow → invocation logged with correct txHash

Testing

# Unit tests
npx vitest run lib/marketplace/__tests__/x402-middleware.test.ts

# Local integration (mock mode)
NEXT_PUBLIC_MOCK_MODE=true npm run dev
curl -X POST http://localhost:3000/api/marketplace/skills/skill_123/invoke \
  -H "Content-Type: application/json" \
  -d '{"agentId":"agent_1","payload":{"text":"hello"}}'

- Add x402 payment middleware for agent-to-agent skill calls
- Implement POST /api/marketplace/skills/[skillId]/invoke with payment validation
- Add invocation ledger tracking txHash, amountXLM, agentId, skillId
- Handle 402 -> payment -> retry flow with Stellar settlement
- Support insufficient_balance error propagation
- Add unit tests with mocked x402 flow
Added invocation recording and status updating for payment processing.
Added mock restoration to ensure subsequent tests use mock path.
Restores mock-mode to true before each test and removes redundant mock-mode restoration after the insufficient balance test.
@sonarqubecloud

Copy link
Copy Markdown

Quality Gate Failed Quality Gate failed

Failed conditions
C Security Rating on New Code (required ≥ A)

See analysis details on SonarQube Cloud

💡 Need a hand with PR review? Try Gitar by Sonar!

@Peolite001

Copy link
Copy Markdown
Contributor Author

done, pls review

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant