Blockchain Based Ticketing Platform
Fintech Summit Hackathon Submission
A decentralized ticketing platform built on the XRP Ledger (XRPL) that eliminates ticket fraud and prevents scalping through blockchain technology.
Inspiration
Ticket fraud and scalping have plagued the event industry for decades. Traditional centralized ticketing systems are vulnerable to:
- Counterfeit tickets created through database manipulation
- Scalping where tickets are resold at exorbitant prices (often 5-10x face value)
- Lack of transparency in ticket ownership and transfer history
- Centralized control that can be compromised or manipulated
We were inspired to solve these problems by leveraging blockchain technology, specifically the XRP Ledger, which offers:
- Native NFT functionality without requiring complex smart contracts
- Sub-second transaction finality for fast user experience
- Low transaction fees (fractions of a cent)
- Built-in security through XRPL's battle-tested infrastructure
Our vision: Create a fair, transparent, and secure ticketing platform where:
- Every ticket is a unique, verifiable NFT on the blockchain
- Price caps prevent scalping (maximum 1.1x original price)
- Purchase limits stop hoarding (5 tickets per performance per wallet)
- Complete transaction history is visible and verifiable on-chain
What it does
Our platform is a comprehensive blockchain-based ticketing marketplace with two main components:
Primary Ticket Sales
- Official venues mint tickets as NFTs directly on XRPL
- Ticket metadata (performance name, date, venue, seat) stored on IPFS for decentralized access
- Purchase limits: 5 tickets per performance per wallet to prevent hoarding
- Real-time inventory tracking (100-200 tickets per performance)
- Automatic NFT transfer to buyers upon purchase
Secondary Resale Market
- Secure peer-to-peer ticket resales using XRPL's native offer system
- Price protection: Maximum 1.1x original price to prevent scalping
- Platform fees: Automated 5% fee on resales (seller receives 95%)
- Complete transaction history from minting to every resale
- Real-time ownership verification before transactions
User Experience
- Dual-tab interface: Separate views for "Official Primary Sale" and "Resale Market"
- My Tickets view: Display all owned NFTs with expandable transaction history
- Transaction verification: All transaction hashes link to XRPL Explorer for on-chain verification
- Optimistic UI updates: Fast response times with background blockchain verification
- Balance checks: Pre-purchase validation to prevent failed transactions
How we built it
Backend Architecture
Technology Stack:
- FastAPI (Python 3.9+) for RESTful API endpoints
- XRPL-Py SDK (v2.1.0+) for blockchain interactions
- SQLite database for local caching and transaction history
- IPFS (Pinata API) for decentralized metadata storage
- Session-based authentication using
itsdangerous
Core Blockchain Operations: thon
Primary ticket purchase flow
- Check purchase limit (5 tickets per performance)
- Mint NFT on XRPL: NFTokenMint transaction
- Upload ticket metadata to IPFS
- Create sell offer: NFTokenCreateOffer (platform → buyer)
- Buyer accepts offer: NFTokenAcceptOffer (automatic transfer)
- Record all transactions in database
- Update inventory and user balance*Key Services:*
XRPLClient: Singleton wrapper for XRPL SDK operationsPrimaryTicketService: Handles official ticket minting and salesNFTService: Manages resale market offers and acceptancesIPFSService: Handles metadata uploads to IPFS
Frontend
- Vanilla JavaScript (ES6+) - No framework dependencies
- Responsive HTML/CSS with modern dark theme
- Optimistic UI updates for instant user feedback
- Real-time balance and inventory updates
Database Models
Core models
- NFT: Tracks NFT ownership and metadata
- PrimaryTicket: Template for official ticket sales
- PurchaseRecord: Enforces purchase limits per performance
- Transaction: Complete audit trail of all blockchain transactions
TicketInfo: Performance details (name, date, venue, seat)### API Endpoints
POST /api/auth/login- User authenticationGET /api/primary-tickets- List available primary ticketsPOST /api/primary-tickets/purchase- Purchase primary ticketGET /api/offers- List resale market offersPOST /api/offers/create- Create resale offerPOST /api/offers/accept- Accept resale offerGET /api/nfts/{nft_id}/transactions- Get transaction history
Challenges we ran into
1. Asynchronous XRPL Operations
Problem: XRPL-Py SDK uses synchronous calls, but FastAPI is async. We needed to integrate them without blocking the event loop.
Solution: Used ThreadPoolExecutor with asyncio.run_in_executor() to run synchronous XRPL calls in background threads. Added proper error handling for asyncio.CancelledError to prevent server crashes.
hon
Example solution
mint_result = await asyncio.get_event_loop().run_in_executor( executor, self.xrpl_client.mint_nft, platform_wallet, ipfs_uri )### 2. Transaction Timing Issues
Problem: Encountered tefPAST_SEQ errors when creating sell offers immediately after minting NFTs. XRPL transactions need time to be validated in a ledger.
Solution: Added strategic delays (await asyncio.sleep(1)) between transactions to allow ledger closing. Also improved error messages to guide users when transactions fail.
3. ID Collisions in Frontend
Problem: Initially used truncated NFT IDs (first 8 characters) for HTML element IDs, causing multiple tickets to share the same ID. Clicking "View History" on one ticket would open another ticket's history.
Solution: Changed to use full NFT IDs for all HTML element IDs, ensuring uniqueness:cript
// Before: ticket-${nft.nft_id.substring(0, 8)}
// After: ticket-${nft.nft_id}
const ticketId = ticket-${nft.nft_id};### 4. Data Consistency Between XRPL and Database
Problem: NFTs could exist on XRPL but not in local database (or vice versa), causing "NFT not found" errors.
Solution: Created reconciliation scripts (fix_nft_not_found.py, fix_seller_tickets.py) to sync XRPL state with local database. Added checks to verify NFT existence before operations.
5. Purchase Limit Enforcement
Problem: Initially tracked purchase limits globally, but needed per-performance limits (5 tickets per show, not total).
Solution: Modified PurchaseRecord model to link purchases to specific PrimaryTicket IDs. Updated check_purchase_limit() to filter by primary_ticket_id:
def check_purchase_limit(self, db, wallet_address, primary_ticket_id): query = db.query(PurchaseRecord).filter( PurchaseRecord.wallet_address == wallet_address, PurchaseRecord.purchase_type == 'primary', PurchaseRecord.primary_ticket_id == primary_ticket_id ) return query.count() < MAX_TICKETS_PER_PERFORMANCE### 6. Balance Update Delays
Problem: Frontend balance didn't refresh immediately after purchases, causing confusion.
Solution: Implemented optimistic UI updates - immediately update balance in UI, then refresh from blockchain in background:
cript
// Optimistic update
currentUser.balance_xrp -= ticketPrice;
balanceElement.textContent = ${newBalance.toFixed(2)} XRP;
// Background refresh refreshBalance();### 7. Transaction History Display
Problem: Primary tickets purchased from official platform didn't show transaction history.
Solution: Record all transaction types (NFTokenMint, NFTokenCreateOffer, NFTokenAcceptOffer) in Transaction model during primary ticket purchase. Added proper labeling ("Official Platform" vs "Resale Seller") for clarity.
Accomplishments that we're proud of
Complete Primary + Secondary Market: Successfully implemented both official ticket sales and peer-to-peer resale in a single, unified platform
Anti-Scalping Mechanisms: Price caps (1.1x) and purchase limits (5 per performance) effectively prevent ticket hoarding and price gouging
Full Transaction Transparency: Every transaction from minting to resale is recorded on-chain and verifiable via XRPL Explorer - users can click any transaction hash to verify on blockchain
IPFS Integration: Decentralized metadata storage ensures ticket information persists even if the platform goes offline
User-Friendly Interface: Clean, modern UI with dual-tab navigation, real-time updates, and comprehensive transaction history with expandable views
Robust Error Handling: Graceful handling of blockchain timeouts, insufficient balances, and network errors with clear user feedback and pop-up alerts
Production-Ready Architecture: Modular service layer, proper database models, comprehensive API design, and proper separation of concerns
Optimistic UI Updates: Fast user experience with immediate feedback while maintaining data integrity through background verification
What we learned
Technical Learnings
XRPL's Native NFT Capabilities: XRPL's built-in NFT functionality eliminates the need for complex smart contracts, making development simpler and more secure. We learned to use
NFTokenMint,NFTokenCreateOffer, andNFTokenAcceptOffertransactions effectively.Blockchain Transaction Lifecycle: Understanding transaction validation, ledger closing (every 3-5 seconds), and the importance of proper sequencing in blockchain operations. We learned to handle
tefPAST_SEQerrors and implement retry logic.Asynchronous Programming: Deep dive into Python's
asyncio,ThreadPoolExecutor, and handling concurrent operations in web applications. We learned to bridge synchronous blockchain SDK calls with async FastAPI endpoints.IPFS for Decentralized Storage: Learning how to use Pinata API for IPFS uploads and understanding the benefits of decentralized metadata storage. We implemented fallback to mock hashes when IPFS credentials aren't available.
Optimistic UI Updates: Implementing fast user feedback while maintaining data integrity through background verification. This significantly improved perceived performance.
Database Design for Blockchain Apps: Balancing on-chain data (source of truth) with off-chain caching for performance and user experience. We learned when to trust blockchain state vs. local database.
Price Protection Mechanisms: Designing fair resale markets that protect consumers while allowing legitimate transfers. The 1.1x price cap strikes a balance between preventing scalping and allowing reasonable resale.
Domain Knowledge
- Ticketing Industry Pain Points: Understanding the real-world problems of ticket fraud, scalping, and lack of transparency
- Blockchain Use Cases: Learning when blockchain adds value (verification, transparency) vs. when it's overkill
- User Experience in Web3: Balancing blockchain transparency with user-friendly interfaces
Development Process
- Iterative Problem Solving: Each challenge required multiple iterations and debugging
- Testing on Testnet: Importance of thorough testing before mainnet deployment
- Error Handling: Comprehensive error handling is crucial for blockchain applications where transactions can fail for various reasons
Setup Instructions
Prerequisites
- Python 3.9 or 3.10
- Git
- XRPL Testnet accounts with XRP (get free XRP from XRPL Faucet)
🚀 Getting Started
Step 1: Clone the Repository
ash git clone https://github.com/Yanrong-Wang/FintechSummit.git cd FintechSummit### Step 2: Create Virtual Environment
Linux/macOS: h python3 -m venv venv source venv/bin/activate*Windows:*
python -m venv venv venv\Scripts\activate### Step 3: Install Dependencies
pip install --upgrade pip pip install -r requirements.txt### Step 4: Configure Environment Variables
Create a .env file in the root directory:
Copy example file
cp .env.example .envEdit .env with your XRPL Testnet credentials:
XRPL Testnet Configuration
XRPL_TESTNET_URL=https://s.altnet.rippletest.net:51234
Demo Wallet Configuration (for testing)
SELLER_SEED=your_seller_seed_here SELLER_ADDRESS=your_seller_address_here BUYER_SEED=your_buyer_seed_here BUYER_ADDRESS=your_buyer_address_here
Platform Official Wallet (for primary ticket sales)
PLATFORM_SEED=your_platform_seed_here PLATFORM_ADDRESS=your_platform_address_here
IPFS Configuration (optional - uses mock hash if not configured)
PINATA_JWT=your_jwt_token_here
OR use API key/secret instead:
PINATA_API_KEY=your_api_key
PINATA_SECRET_KEY=your_secret_key
Session Secret (for demo only - change in production)
SESSION_SECRET=your-secret-key-change-in-production*Getting XRPL Testnet Wallets:*
- Visit XRPL Testnet Faucet
- Generate testnet wallets (you'll need at least 3: seller, buyer, platform)
- Fund them with testnet XRP from the faucet
- Copy the seed and address into your
.envfile
Step 5: Initialize Database and Add Sample Tickets
sh
Add primary ticket templates (creates sample performances)
python add_primary_tickets.pyThis creates 4 sample performances:
- Phantom of the Opera Musical
- Swan Lake Ballet
- Hamilton Live Concert
- The Lion King Musical
Each performance has 100-200 tickets available.
Step 6: Run the Application
Option 1: Using the run script (Linux/macOS)
chmod +x run.sh ./run.sh*Option 2: Manual start*
python -m src.mainThe application will start on http://localhost:8000
Step 7: Access the Platform
- Open your browser and navigate to:
http://localhost:8000 - Login with a username and one of your configured wallet addresses (buyer or seller)
- Start exploring:
- Buy Tickets → Browse primary sales or resale market
- Sell → List your tickets for resale
- Me → View your tickets and transaction history
Troubleshooting
Port already in use:sh
Change port in src/config.py or use:
uvicorn src.main:app --port 8001*Database errors:*
Delete existing database and reinitialize
rm data/ticket_resale.db python -m src.main # Will auto-create new database python add_primary_tickets.py*XRPL connection issues:*
- Verify
XRPL_TESTNET_URLin.env - Check your internet connection
- Ensure testnet wallets are funded with XRP
Import errors:
Ensure virtual environment is activated
source venv/bin/activate # Linux/macOS venv\Scripts\activate # Windows
Reinstall dependencies
pip install -r requirements.txt---
What's next for Blockchain Based Ticketing Platform
Short-term Improvements
- Mobile App: Native iOS/Android apps for better mobile experience
- Email Notifications: Alert users about new tickets, price changes, and purchase confirmations
- Advanced Search: Filter tickets by performance, date, price range, and venue
- Favorites/Watchlist: Allow users to save tickets for later purchase
Enhanced Features
- QR Code Generation: Generate QR codes for ticket verification at venues
- Transfer to Friends: Direct NFT transfer functionality without going through resale market
- Refund System: Implement refund policies for cancelled events
- Multi-Currency Support: Accept payments in multiple cryptocurrencies
Scalability & Production
- Mainnet Deployment: Migrate from Testnet to XRPL Mainnet
- Key Management: Implement secure key management using HSMs or key vaults
- KYC/AML Compliance: Add identity verification for regulatory compliance
- Analytics Dashboard: Real-time analytics for venue owners and platform administrators
Advanced Blockchain Features
- Smart Contract Integration: Explore XRPL's Hooks for more complex business logic
- Cross-Chain Support: Enable ticket sales across multiple blockchains
- NFT Metadata Updates: Allow venues to update event details post-mint
- Royalty System: Implement automatic royalty payments to artists/venues on resales
Community & Ecosystem
- API for Third-Party Integrations: Open API for event management systems
- White-Label Solution: Allow venues to deploy their own branded ticketing platforms
- Decentralized Governance: DAO structure for platform decision-making
- Partnership Program: Collaborate with major venues and event organizers
Tech Stack
- Backend: Python 3.9+, FastAPI, SQLAlchemy, Pydantic
- Blockchain: XRP Ledger (XRPL) Testnet, xrpl-py SDK
- Storage: IPFS (Pinata API), SQLite
- Frontend: Vanilla JavaScript, HTML5, CSS3
- Testing: pytest, pytest-asyncio
All transactions verified on XRPL Testnet Explorer
Built With
- ipfs
- javascript
- python
- xrpl
Log in or sign up for Devpost to join the conversation.