Skip to content

xapi-labs/x402x-contracts

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

11 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

x402x Smart Contracts

x402x = EIP-7702 Extension for x402
Bringing Smart Contract Capabilities to EOAs for Signature-Based Payments

Solidity Foundry Tests License

📋 Overview

x402x is an EIP-7702 extension for the x402 payment protocol. While x402 enables frictionless HTTP-based payments with ERC-3009 settlement, x402x extends this capability by leveraging EIP-7702 to bring enhanced smart contract features to seller EOAs (Externally Owned Accounts).

By combining EIP-7702's set-code delegation with multiple signature-based payment standards (ERC-3009, ERC-2612 Permit, Permit2), x402x provides an enhanced settlement layer for x402 payments, enabling:

  • Minimal Trust - Payer's signature controls fund flow and only needs to trust the seller; no trust required for 3rd party facilitators or router contracts
  • Multiple Payment Standard Support - Supports ERC-3009, ERC-2612 Permit, and Permit2 for maximum flexibility (Currently, x402 supports ERC-3009 only)
  • Facilitator Reward - Permissionless facilitators tracked on-chain for future reward distribution (1% fee collected)
  • Zero Configuration - Works immediately with sensible defaults (lazy initialization)
  • Extensible Hooks - Execute custom business logic (e.g., minting NFTs) in the same transaction as payment, reducing settlement to a single atomic operation

🎯 The x402x Innovation: Extending x402 with EIP-7702

Why "x402x"?
The name x402x represents the x402 protocol (by Coinbase) extended with EIP-7702 capabilities. The "x" in x402x stands for "extension" - enhancing x402's settlement capabilities through EOA delegation.

What x402x Adds to x402:

Feature x402 (Original) x402x (Extension)
Payment Standards ERC-3009 only (USDC) ERC-3009, ERC-2612 Permit, Permit2
Settlement Method Direct transfer EIP-7702 delegated EOA
Facilitator Incentives ❌ No incentives ✅ 1% fee + on-chain tracking
Side Effects ❌ Separate transactions ✅ Same-transaction via hooks
Seller Account Any account EOA with EIP-7702 delegation

Key Innovations

  1. 🎯 Broader Token Support - Accept any ERC-20 with Permit/Permit2, not just USDC
  2. 💰 Facilitator Economy - 1% fee + on-chain tracking for reward distribution
  3. ⚡ Atomic Operations - Execute side effects (mint NFTs, update state) in same transaction
  4. 🔄 Reversible - Sellers can revoke EIP-7702 delegation anytime
  5. 🧩 Composable - Hooks integrate with DeFi, NFTs, and any on-chain logic

🏗️ Architecture

x402x_contracts/
├── src/
│   ├── x402xWallet.sol            # Main wallet contract (1020 lines)
│   │   ├── ISettleWithPermit      # ERC-2612 Permit interface
│   │   ├── ISettleWithERC3009     # ERC-3009 interface
│   │   └── ISettleWithPermit2     # Uniswap Permit2 interface
│   ├── ISettlementHooks.sol       # Hooks interface (181 lines)
│   ├── NFTRewardHook.sol          # NFT reward hook example (465 lines)
│   └── utils/
│       └── getTokenBalanceDiff.sol
└── test/
    ├── x402xWallet.t.sol          # 25 tests
    ├── NFTRewardHook.t.sol        # 24 tests
    └── TokenBalanceDiff.t.sol     # 9 tests

🚀 Quick Start

Prerequisites

  • Foundry
  • Solidity ^0.8.24
  • OpenZeppelin Contracts v5.0.2

Installation

# Clone and install
git clone https://github.com/WTFLabs-WTF/x402x-contracts.git
cd x402x_contracts
forge install

# Compile and test
forge build
forge test

Test Results

╭------------------------------+--------+--------+---------╮
| Test Suite                   | Passed | Failed | Skipped |
+================================================================+
| x402xWalletTest              | 25     | 0      | 0       |
| NFTRewardHookTest            | 24     | 0      | 0       |
| TokenBalanceDiffTest         | 9      | 0      | 0       |
+------------------------------+--------+--------+---------+
| TOTAL                        | 58     | 0      | 0       |
╰------------------------------+--------+--------+---------╯

💡 Usage

1. Deploy with EIP-7702

// Step 1: Deploy implementation (one-time)
x402xWalletMinimal implementation = new x402xWalletMinimal();

// Step 2: Seller signs EIP-7702 authorization (off-chain)
bytes memory auth = signEIP7702Authorization(
    sellerPrivateKey,
    address(implementation),
    chainId,
    nonce
);

// Step 3: Submit transaction with authorization
// Seller's EOA now has x402x payment capabilities!

2. Accept Payments

// Payer signs ERC-2612 Permit (off-chain)
bytes32 digest = getPermitDigest(...);
(uint8 v, bytes32 r, bytes32 s) = sign(payerPrivateKey, digest);

// Facilitator submits settlement (permissionless)
wallet.settleWithPermit(
    tokenAddress,    // USDC, DAI, etc.
    payerAddress,
    amount,
    deadline,
    v, r, s
);

// Result:
// ✅ Tokens transferred from payer
// ✅ Beneficiary receives (amount - 1% fee)
// ✅ Platform receives 1% fee
// ✅ Facilitator tracked for future rewards

3. Add NFT Rewards (Optional)

// 1. Deploy NFT Hook
NFTRewardHook hook = new NFTRewardHook(
    "Payment Receipt NFT",
    "PRNFT",
    ownerAddress
);

// 2. Set threshold: 1 USDC = mint NFT
hook.setThreshold(usdcAddress, 1_000_000, 6);
hook.addAuthorizedCaller(address(wallet));

// 3. Enable hook in wallet
wallet.updateConfig(
    beneficiaryAddress,
    address(hook),   // Use NFT Hook
    false,           // beforeSettle disabled
    true,            // afterSettle enabled ✅
    100              // 1% fee
);

// Users paying >= 1 USDC automatically get NFT!

🎁 Facilitator Incentives

x402x introduces a permissionless facilitator model with on-chain tracking and rewards:

// When facilitator submits settlement
wallet.settleWithPermit(token, payer, amount, deadline, v, r, s);

// Event emitted with facilitator tracking
event SettlementExecuted(
    address indexed token,
    address indexed payer,
    bytes32 indexed sigHash,      // For duplicate detection
    address facilitator,           // tx.origin (facilitator)
    uint256 amount,
    uint256 beneficiaryAmount,    // Amount - fee
    uint256 feeAmount,            // 1% default fee
    string method
);

Why tx.origin?

  • ✅ Multicall compatible
  • ✅ Simplified API (no extra parameters)
  • ✅ Safe for statistics tracking
  • ⚠️ Only affects tracking, not fund flow or access control

📖 Core Features

Payment Methods

Three signature-based payment methods:

// 1. ERC-2612 Permit
function settleWithPermit(
    address token, address payer, uint256 amount,
    uint256 deadline, uint8 v, bytes32 r, bytes32 s
) external;

// 2. ERC-3009 (x402 compatible)
function settleWithERC3009(
    address token, address payer, uint256 amount,
    uint256 validAfter, uint256 validBefore, bytes32 nonce,
    uint8 v, bytes32 r, bytes32 s
) external;

// 3. Permit2
function settleWithPermit2(
    IPermit2.PermitTransferFrom calldata permit,
    address payer, bytes calldata signature
) external;

Hooks System

Execute custom logic before/after settlements:

interface ISettlementHooks {
    function beforeSettle(
        address token, address payer,
        address facilitator, address seller, uint256 amount
    ) external returns (bytes4);

    function afterSettle(
        address token, address payer, address facilitator,
        address seller, uint256 amount,
        uint256 beneficiaryAmount, uint256 feeAmount
    ) external returns (bytes4);
}

Hook Use Cases:

  • 🎨 NFT Rewards - Mint NFTs for payments above threshold
  • 🎯 Loyalty Points - Track customer rewards
  • 🔐 Access Control - Whitelist/blacklist validation
  • 📊 Analytics - Custom event logging
  • 💸 Multi-party Settlement - Complex payment routing

🔒 Security

Built-in Protections

  • ReentrancyGuard - Prevents reentrancy attacks
  • SafeERC20 - Safe token operations
  • Access Control - onlyOwner modifier for config
  • Input Validation - Amount, address, fee range checks
  • Namespaced Storage - Prevents collision in EIP-7702 context

Security Design

// Namespaced storage (EIP-1967 style)
bytes32 private constant CONFIG_STORAGE_POSITION = 
    keccak256("x402.eip7702.sellerwallet.config") - 1;

// Input validation example
if (amount == 0) revert InvalidAmount();
if (feeBps != 0 && (feeBps < 100 || feeBps > 5000)) revert InvalidFee();

📊 Gas Costs

Operation Gas Cost Description
settleWithPermit ~152,000 Standard payment
settleWithERC3009 ~141,000 ERC-3009 payment
settleWithPermit2 ~157,000 Permit2 payment
settleWithPermit + NFT ~260,000 Payment + mint NFT
updateConfig ~86,000 Update configuration
Contract Deployment Size
x402xWallet ~2,600,000 ~12 KB
NFTRewardHook ~2,900,000 ~14.5 KB

🎯 Use Cases

  1. E-Commerce - Accept USDC/USDT, auto-mint membership NFTs
  2. SaaS Subscriptions - Token payments with NFT as proof
  3. Event Ticketing - NFT tickets from payments
  4. Charitable Donations - Donation certificates as NFTs
  5. Decentralized Marketplaces - P2P payments with reputation NFTs

🛠️ Development

Foundry Commands

forge build          # Compile
forge test           # Run tests
forge test -vvv      # Verbose output
forge test --gas-report  # Gas report
forge fmt            # Format code
forge snapshot       # Gas snapshot
forge coverage       # Code coverage
forge clean          # Clean artifacts

Cast Utilities

cast balance <address>                    # Query balance
cast call <contract> "balanceOf(address)" <address>
cast send <contract> "transfer(address,uint256)" <to> <amount>
cast block latest                         # Get latest block
cast chain-id                             # Get chain ID

🌐 Links

x402 Protocol (What We Extend)

Standards & Tech

Development

🤝 Contributing

  1. Fork the project
  2. Create feature branch (git checkout -b feature/AmazingFeature)
  3. Write tests ensuring coverage
  4. Commit changes (git commit -m 'Add AmazingFeature')
  5. Push to branch (git push origin feature/AmazingFeature)
  6. Open Pull Request

Code Standards:

  • Follow Solidity Style Guide
  • All features must include tests
  • Maintain test coverage
  • Use forge fmt to format

📄 License

MIT License - see LICENSE for details

📞 Contact

🙏 Acknowledgments


Built with ❤️ by the x402x team

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors