Skip to content

[FEATURE] x402 Wallet + USDC Stablecoin Trading System #2

@AGI-Corporation

Description

@AGI-Corporation

Summary

Implement the x402 payment protocol to give each Parcel Agent a sovereign, non-custodial wallet with USDC/USDT stablecoin trading capabilities. This enables the Sapient.X economy: agents autonomously pay for services, execute trades, sign on-chain service agreements, and settle transactions without human intervention.

Roadmap Position: Depends on #1 (ParcelAgent) and #3 (MCP Server). The execute_node in ParcelAgent calls initiate_trade which triggers wallet operations here.


Background & Motivation

In the Sapient.X metaverse economy, each parcel agent needs:

  • A sovereign wallet (private key managed by the agent, not a central server)
  • The ability to pay for MCP tool calls via x402 micropayments
  • USDC/USDT trading between agents to buy/sell parcel resources
  • Smart contract-backed service agreements that auto-execute when conditions are met

The x402 protocol is an HTTP-native payment protocol that allows agents to attach payment proofs to API requests, enabling pay-per-use services at the infrastructure level. Combined with Circle's USDC on Base/Ethereum, this creates a fully autonomous agent economy.


Objectives

  • Implement ParcelWallet class with x402 SDK
  • Set up USDC/USDT contract interfaces (Base network primary)
  • Build escrow-based trade execution
  • Deploy ParcelServiceAgreement.sol to testnet (Base Sepolia)
  • Create market order book system
  • Add price oracle integration (Chainlink or Pyth)
  • Write integration tests against Base Sepolia testnet

Technical Architecture

Wallet Architecture

ParcelWallet
├── Private key management (encrypted, env-var seeded)
├── x402 payment signing (EIP-712 typed signatures)
├── USDC/USDT balance queries (Base network)
├── Transaction broadcasting (ethers.py or web3.py)
└── Transaction history (indexed from chain events)

x402 Payment Flow

Agent wants to call MCP tool (e.g., get_market_price)
   ↓
MCP server returns HTTP 402 Payment Required
   ↓  {"amount": "0.001 USDC", "payTo": "0x...", "nonce": "..."}
   ↓
ParcelWallet signs payment (EIP-712)
   ↓
Agent retries request with X-Payment header
   ↓
MCP server verifies payment, returns data

Trade Execution Flow

Agent A wants to buy resource from Agent B
   ↓
initiate_trade(buyer=A, seller=B, amount=100_USDC, resource="land_parcel")
   ↓
Escrow: Lock Agent A's USDC in ParcelServiceAgreement.sol
   ↓
Agent B confirms delivery
   ↓
Smart contract releases USDC to Agent B
   ↓
Trade recorded on-chain + emitted as MCP event

Smart Contract Architecture

// ParcelServiceAgreement.sol
contract ParcelServiceAgreement {
    struct Agreement {
        address buyer;       // Agent A wallet
        address seller;      // Agent B wallet
        uint256 amount;      // USDC amount (6 decimals)
        bytes32 resourceId;  // Parcel/resource identifier
        AgreementStatus status;
        uint256 expiresAt;
    }
    
    // Core functions
    function createAgreement(address seller, uint256 amount, bytes32 resourceId) external;
    function confirmDelivery(bytes32 agreementId) external;
    function disputeAgreement(bytes32 agreementId) external;
    function cancelAgreement(bytes32 agreementId) external;
    
    // Oracle integration for price validation
    function getOraclePrice(bytes32 assetId) external view returns (uint256);
}

Implementation Plan

Phase 1: Wallet Core (Days 1-2)

  • Create ParcelWallet class with key generation from X402_PRIVATE_KEY env var
  • Implement get_balance(token='USDC') using web3.py + USDC contract ABI
  • Implement sign_x402_payment(amount, pay_to, nonce) using EIP-712
  • Add send_transaction(to, amount, token) with gas estimation
  • Write tests/unit/test_wallet.py with mocked web3 provider

Phase 2: x402 Protocol Integration (Day 3)

Phase 3: Trading System (Days 4-5)

  • Implement OrderBook class (in-memory + Redis-backed)
  • Create TradeEngine with maker/taker matching logic
  • Implement escrow locking via ParcelServiceAgreement.sol
  • Add trade event emission and MCP broadcast_message integration
  • Write tests/unit/test_trading.py

Phase 4: Smart Contracts (Days 6-7)

  • Finalize ParcelServiceAgreement.sol with full dispute resolution
  • Write Hardhat tests for all contract functions
  • Deploy to Base Sepolia testnet
  • Add Etherscan/Basescan verification script
  • Add Chainlink price oracle integration for fair pricing

Phase 5: Security Hardening (Day 8)

  • Implement transaction signing verification (prevent replay attacks)
  • Add rate limiting on trade endpoints (max 100 trades/min per agent)
  • Re-entrancy guard on ParcelServiceAgreement.sol (OpenZeppelin)
  • Add EIP-712 signature replay protection (nonce tracking)
  • Smart contract audit checklist (slither static analysis)

Technical Requirements

Dependency Version Purpose
web3 >=6.0.0 Ethereum/Base interaction
eth-account >=0.9.0 Wallet signing
x402-python latest x402 payment protocol
hardhat >=2.19.0 Smart contract dev/testing
@openzeppelin/contracts >=5.0.0 Re-entrancy guards, ERC20
@chainlink/contracts >=0.8.0 Price oracle

Target Network: Base (mainnet) / Base Sepolia (testnet)

Supported Stablecoins:

  • USDC (Circle) — Primary settlement currency
  • USDT (Tether) — Secondary support

Environment Variables

# Wallet
X402_PRIVATE_KEY=           # Agent's private key (hex, 0x-prefixed)
X402_GATEWAY=               # x402 payment gateway URL

# Network
ETH_RPC_URL=                # Base Sepolia: https://sepolia.base.org
CHAIN_ID=84532              # Base Sepolia chain ID

# Contracts
USCD_CONTRACT_ADDRESS=      # USDC on Base Sepolia
SERVICE_AGREEMENT_ADDRESS=  # Deployed ParcelServiceAgreement.sol

# Oracle
CHAINLINK_PRICE_FEED=       # Price feed address for USDC/USD

Security Requirements

Requirement Implementation
Transaction signing verification EIP-712 typed data + signature recovery
Rate limiting on trade endpoints Redis sliding window counter
Re-entrancy protection OpenZeppelin ReentrancyGuard
Signature replay protection On-chain nonce mapping per address
Private key security Never stored in DB; loaded from env at runtime only
Smart contract audit Slither + manual review before mainnet

Acceptance Criteria

  • ParcelWallet can generate wallet address from private key and query USDC balance
  • x402 payment flow works end-to-end (402 response → signed payment → retry succeeds)
  • Trade execution creates on-chain escrow in ParcelServiceAgreement.sol
  • ParcelServiceAgreement.sol deployed to Base Sepolia with verified source
  • Order book matches buy/sell orders and settles via smart contract
  • Chainlink price oracle integrated for real-time USDC/USD pricing
  • All security requirements implemented and tested
  • Integration tests pass against Base Sepolia testnet
  • Hardhat test coverage > 95% for smart contract functions

Files to Create / Modify

src/blockchain/
├── __init__.py
├── wallet.py                    # ParcelWallet class
├── stablecoin.py                # USDC/USDT contract interfaces
├── x402_client.py               # x402 payment protocol client
└── oracle.py                    # NEW: Chainlink price oracle integration

src/agents/
└── trading.py                   # TradeEngine + OrderBook

contracts/
├── ParcelServiceAgreement.sol   # Main service agreement contract
├── interfaces/
│   ├── IERC20.sol               # Standard ERC20 interface
│   └── IPriceFeed.sol           # Chainlink price feed interface
└── scripts/
    ├── deploy.js                # Hardhat deployment script
    └── verify.js                # Etherscan verification

tests/unit/
├── test_wallet.py               # Wallet operations (mocked web3)
└── test_trading.py              # Trade execution logic

tests/integration/
└── test_trading_flow.py         # Full trade cycle (Base Sepolia)

tests/contracts/
├── test_ParcelServiceAgreement.js  # Hardhat tests
└── test_escrow_flow.js

Estimated Effort

Task Estimate
Wallet core + x402 client 2 days
Trading engine + order book 2 days
Smart contract development 2 days
Security hardening 1 day
Tests (unit + integration) 1 day
Total ~8 days

Related Issues & Dependencies


References

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    Status

    Todo

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions