make_post_sell/docs/MONERO.rst
Russell Ballestrini c4d9192540 Improve crypto payment handling and out-of-stock refunds
- Add proper inventory checking before crypto payment completion
- Implement sequential (FIFO) crypto payment processing to prevent race conditions
- Add comprehensive out-of-stock refund handling with two statuses:
  - STATUS_OUT_OF_STOCK_REFUNDED: Full refund to customer (no restocking fee)
  - STATUS_OUT_OF_STOCK_NO_REFUND: Sweep to shop when no refund address
- Use sweep_all with subaddr_indices for Monero to ensure complete fund recovery
- Use sendtoaddress with subtractfeefromamount for Dogecoin fee handling
- Add refund tracking fields (refund_reason, refund_tx_hash, refund_amount)
- Update MONERO.rst with subaddress isolation and refund processing documentation
- Ensure action buttons are removed for non-pending crypto quotes to prevent double payments
2025-09-24 09:35:07 -04:00

282 lines
No EOL
12 KiB
ReStructuredText

=====================================
Make Post Sell Monero Cash Register
=====================================
**The Ultimate Multi-Tenant Cryptocurrency Payment System**
Overview
========
Make Post Sell's Monero integration provides a **revolutionary multi-tenant cryptocurrency cash register** that enables any shop to accept Monero payments with enterprise-grade security, automatic fund management, and real-time payment tracking.
Our system is **truly amazing** because it solves the complex challenges of cryptocurrency commerce:
-**Zero-configuration setup** - Shops enable Monero payments with one click
-**Automatic account isolation** - Each shop gets its own dedicated Monero account
-**Real-time payment tracking** - Live confirmation monitoring with risk-based thresholds
-**Automatic fund sweeping** - Hot wallet funds automatically swept to cold storage
-**Multi-tenant security** - Complete financial isolation between shops
-**Production-ready scaling** - Handle unlimited shops and payments
Architecture Overview
=====================
Our Monero payment system consists of four key components:
**1. Hot Wallet Infrastructure**
- Single `monero-wallet-rpc` service manages all shops
- Each shop gets a dedicated Monero account (isolated finances)
- Remote node connectivity (no 150GB+ blockchain storage required)
- Secure RPC communication with authentication disabled for internal use
**2. Multi-Tenant Account Management**
- **Account Creation**: Automatic Monero account creation per shop
- **Labeling System**: Clean UUID-based labels for machine identification
- **Tagging System**: Human-readable shop names for easy management
- **Database Tracking**: Account indices stored in `mps_crypto_processor` table
**3. Payment Processing Pipeline**
- **Quote Generation**: Real-time XMR/USD exchange rates with time-limited quotes
- **Payment Monitoring**: 20-second polling cycle checking for incoming payments
- **Confirmation Tracking**: Risk-based confirmation requirements (petty/mid/high tiers)
- **Invoice Finalization**: Automatic product unlocking and email notifications
**4. Auto-Sweep Security**
- **Pooled Sweeping**: Multiple payments swept together for efficiency
- **Account Isolation**: Funds never mix between shops (dedicated accounts)
- **Cold Storage**: Automatic transfer to shop-configured cold wallet addresses
- **Network Fee Tracking**: Comprehensive fee monitoring for accounting
Multi-Tenant Magic
==================
What makes our system **truly amazing** is the multi-tenant architecture:
**Account Isolation**
---------------------
Each shop operates in complete financial isolation:
.. code-block:: text
Wallet Structure:
├── Account 0: Primary (system)
├── Account 1: Shop A (media.unturf.com)
├── Account 2: Shop B (example-store.com)
├── Account 3: Shop C (crypto-shop.net)
└── Account N: Shop N...
**Database Schema**
-------------------
.. code-block:: sql
-- Shop crypto processor configuration
CREATE TABLE mps_crypto_processor (
id UUID PRIMARY KEY,
shop_id UUID NOT NULL,
coin_type VARCHAR(32) NOT NULL, -- 'XMR'
wallet_label VARCHAR(128) NOT NULL, -- Account index: "1", "2", "3"...
sweep_to_address VARCHAR(256) NOT NULL, -- Cold wallet address
enabled BOOLEAN DEFAULT TRUE
);
-- Individual payment tracking
CREATE TABLE mps_crypto_payment (
id UUID PRIMARY KEY,
invoice_id UUID NOT NULL,
account_index INTEGER NOT NULL, -- Links to wallet account
expected_amount BIGINT NOT NULL, -- Atomic units (piconero)
received_amount BIGINT DEFAULT 0,
current_confirmations INTEGER DEFAULT 0,
status VARCHAR(32), -- pending/received/confirmed
swept_amount BIGINT, -- Amount swept to cold storage
swept_tx_hash VARCHAR(128) -- Sweep transaction hash
);
**Payment Flow**
================
The complete payment lifecycle demonstrates the system's sophistication:
**1. Shop Setup (One-Time)**
- Shop owner enters cold wallet address
- System creates dedicated Monero account automatically
- Account tagged with shop domain for identification
**2. Customer Checkout**
- Real-time XMR/USD rate fetched from CoinGecko
- Quote generated with 60-minute expiration
- Unique subaddress created for this specific payment
- Customer sees payment address + amount details
**3. Payment Monitoring**
- Crypto watcher polls every 20 seconds
- Checks all pending payments across all shops
- Updates confirmation counts as blocks are found
- Applies risk-based confirmation requirements:
- **Petty** (< $10): 2 confirmations
- **Mid** ($10-$100): 10 confirmations
- **High** (> $100): 20 confirmations
**4. Payment Confirmation**
- Payment status: ``pending````received````confirmed``
- Invoice automatically finalized when confirmed
- Digital products unlocked instantly
- Physical products trigger inventory deduction
- Purchase and sale emails sent automatically
**5. Auto-Sweep to Cold Storage**
- Unlocked funds trigger automatic sweep (funds unlock ~10 blocks after confirmation)
- All unlocked funds in shop's account swept together
- Efficient: Not 1:1 payment-to-sweep mapping
- Secure: Funds immediately moved to shop's cold wallet
- Trackable: Sweep transaction hash recorded
Risk Management
===============
Our system implements sophisticated risk management:
**Confirmation Tiers**
----------------------
Shop-configurable thresholds determine confirmation requirements:
.. code-block:: ini
# Shop settings (per-shop configuration)
payment_risk_threshold_mid_cents = 1000 # $10.00
payment_risk_threshold_high_cents = 10000 # $100.00
# Global Monero confirmation requirements
monero.confirmations.petty = 2 # < $10: Fast confirmation
monero.confirmations.mid = 10 # $10-$100: Standard security
monero.confirmations.high = 20 # > $100: Maximum security
**Overpayment Handling**
------------------------
- Automatic overpayment detection
- Optional refund to customer-provided address
- Graceful handling when no refund address provided
- Status tracking: ``confirmed_overpaid`` for accounting
**Quote Expiration**
--------------------
- Time-limited quotes prevent rate manipulation
- Configurable expiration (default: 60 minutes)
- Quotes expire and require new checkout if time limit exceeded
- Expired payment refund system (when refund address available)
Why This Is Amazing
===================
**For Shop Owners**
- **Zero Crypto Knowledge Required**: Enable Monero payments with one click
- **Complete Financial Control**: Direct payments to your cold wallet
- **Instant Setup**: No wallet management or blockchain syncing
- **Enterprise Security**: Bank-grade isolation and automatic fund management
- **Global Reach**: Accept payments from anywhere, anytime
**For Customers**
- **True Privacy**: Monero's built-in privacy features
- **Low Fees**: Minimal network fees compared to traditional payments
- **Fast Confirmation**: Risk-based confirmation for quick small purchases
- **Global Access**: No geographic restrictions or banking requirements
**For Developers**
- **Production Ready**: Handle unlimited shops and payment volume
- **Clean Architecture**: Well-separated concerns and modular design
- **Comprehensive APIs**: Full payment lifecycle management
- **Monitoring Built-in**: Real-time payment tracking and status updates
- **Extensible Design**: Easy to add new cryptocurrencies
**For Platform Operators**
- **Single Infrastructure**: One wallet serves unlimited shops
- **Automatic Scaling**: No per-shop setup or maintenance required
- **Security by Design**: Account isolation prevents fund mixing
- **Operational Excellence**: Automated deployment and monitoring
Subaddress Isolation and Refund Processing
===========================================
Our Monero implementation uses **subaddress isolation** to ensure complete security between customer payments and enable safe refund processing without affecting other transactions.
**Account and Subaddress Hierarchy**
------------------------------------
Each payment operates within a strict isolation model:
.. code-block:: text
Monero Wallet Structure:
├── Account 0: System (unused)
├── Account 1: Shop A
│ ├── Subaddress 0: Shop's primary address
│ ├── Subaddress 1: Customer Payment #1
│ ├── Subaddress 2: Customer Payment #2
│ └── Subaddress N: Customer Payment #N
├── Account 2: Shop B
│ ├── Subaddress 0: Shop's primary address
│ ├── Subaddress 1: Customer Payment #1
│ └── ...
└── Account N: Shop N...
**Payment Isolation Security**
------------------------------
Each crypto payment receives a unique subaddress within the shop's account, ensuring:
- **Complete Financial Isolation**: Funds from different customers never mix
- **Targeted Refunds**: Specific payments can be refunded without affecting others
- **Safe Sweep Operations**: Only intended funds are moved during sweeps
- **Audit Trail**: Each payment's funds are traceable throughout the lifecycle
**Refund Processing Flow**
--------------------------
When refunds are required (expired quotes, out-of-stock items, overpayments):
1. **Customer Refund**: Uses ``sweep_single`` to transfer customer's funds to their refund address
2. **Restocking Fee Sweep**: Uses ``sweep_all`` with specific ``subaddr_indices`` to collect restocking fees
3. **Transaction Ordering**: Refunds are always processed BEFORE restocking fee sweeps
.. code-block:: python
# Safe refund processing with subaddress isolation
# Step 1: Refund customer (specific subaddress)
refund_result = monero_rpc.sweep_single(
address=crypto_payment.refund_address,
account_index=crypto_payment.account_index,
subaddr_indices=[crypto_payment.subaddress_index]
)
# Step 2: Sweep restocking fee (same subaddress)
restocking_result = monero_rpc.sweep_all(
address=shop_cold_wallet,
account_index=crypto_payment.account_index,
subaddr_indices=[crypto_payment.subaddress_index]
)
**Why sweep_all is Safe**
-------------------------
The ``sweep_all`` operation with ``subaddr_indices`` parameter ensures security:
- **Without subaddr_indices**: Would sweep ALL funds in the account (DANGEROUS)
- **With subaddr_indices**: Only sweeps funds from specified subaddresses (SAFE)
This allows us to:
- Collect restocking fees from specific failed payments
- Leave other customers' payments untouched
- Maintain complete isolation between transactions
**Network Fee Considerations**
------------------------------
Monero network fees are automatically calculated and deducted:
- **Standard Fee**: ~0.0001 XMR for most transactions
- **Automatic Deduction**: Fees are subtracted from the swept amount
- **Fee Tracking**: All network fees are recorded for accounting
- **Confirmation Requirements**: Funds must be unlocked (~10 confirmations) before sweeping
This subaddress isolation architecture ensures that our multi-tenant Monero system maintains enterprise-grade security while providing the flexibility needed for complex refund scenarios.
The Result: A truly **amazing** multi-tenant cryptocurrency cash register that makes Monero payments as easy as traditional payment processing, while maintaining the privacy, security, and decentralization that makes cryptocurrency revolutionary.
**Welcome to the future of commerce.** 🚀