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
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)
Phase 2: x402 Protocol Integration (Day 3)
Phase 3: Trading System (Days 4-5)
Phase 4: Smart Contracts (Days 6-7)
Phase 5: Security Hardening (Day 8)
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
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
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.
Background & Motivation
In the Sapient.X metaverse economy, each parcel agent needs:
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
ParcelWalletclass with x402 SDKParcelServiceAgreement.solto testnet (Base Sepolia)Technical Architecture
Wallet Architecture
x402 Payment Flow
Trade Execution Flow
Smart Contract Architecture
Implementation Plan
Phase 1: Wallet Core (Days 1-2)
ParcelWalletclass with key generation fromX402_PRIVATE_KEYenv varget_balance(token='USDC')using web3.py + USDC contract ABIsign_x402_payment(amount, pay_to, nonce)using EIP-712send_transaction(to, amount, token)with gas estimationtests/unit/test_wallet.pywith mocked web3 providerPhase 2: x402 Protocol Integration (Day 3)
X402Clientthat handles 402 → sign → retry flowX402Clientinto MCP server tool calls (see [FEATURE] Route.X MCP Server - Parcel Plugin Implementation #3)Phase 3: Trading System (Days 4-5)
OrderBookclass (in-memory + Redis-backed)TradeEnginewith maker/taker matching logicParcelServiceAgreement.solbroadcast_messageintegrationtests/unit/test_trading.pyPhase 4: Smart Contracts (Days 6-7)
ParcelServiceAgreement.solwith full dispute resolutionPhase 5: Security Hardening (Day 8)
ParcelServiceAgreement.sol(OpenZeppelin)Technical Requirements
web3eth-accountx402-pythonhardhat@openzeppelin/contracts@chainlink/contractsTarget Network: Base (mainnet) / Base Sepolia (testnet)
Supported Stablecoins:
Environment Variables
Security Requirements
ReentrancyGuardAcceptance Criteria
ParcelWalletcan generate wallet address from private key and query USDC balanceParcelServiceAgreement.solParcelServiceAgreement.soldeployed to Base Sepolia with verified sourceFiles to Create / Modify
Estimated Effort
Related Issues & Dependencies
ParcelAgent.execute_nodecallsinitiate_trade)initiate_tradetool to this module)WalletBalancecomponent reads wallet state)References