Here's a detailed smart contract structure for the Cinema Booking System on Ethereum (Sepolia testnet). This contract includes:
- Movie and Showtime Management (Owner/Admin control)
- Ticket Booking and Payment (Users pay in Ether)
- Role-Based Access Control (Owner, Admin, User)
- Event Emission for transparency (e.g., ticket purchased, movie added)
- Security Checks (e.g., prevent double booking, validate payments)
CinemaBooking.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
contract CinemaBooking is AccessControl, ReentrancyGuard {
// Roles Definition
bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE");
// Structs
struct Movie {
uint256 id;
string title;
uint256 price; // Price in Wei
}
struct Showtime {
uint256 movieId;
uint256 time; // Unix timestamp
uint256 seatsAvailable;
uint256 totalSeats;
}
struct Ticket {
uint256 showtimeId;
address buyer;
uint256 purchaseTime;
}
// State Variables
uint256 public movieCount;
uint256 public showtimeCount;
uint256 public ticketCount;
mapping(uint256 => Movie) public movies;
mapping(uint256 => Showtime) public showtimes;
mapping(uint256 => Ticket) public tickets;
mapping(address => uint256[]) public userTickets; // User's booked tickets
// Events
event MovieAdded(uint256 indexed movieId, string title, uint256 price);
event ShowtimeAdded(uint256 indexed showtimeId, uint256 movieId, uint256 time);
event TicketPurchased(uint256 indexed ticketId, uint256 showtimeId, address buyer);
event FundsWithdrawn(address indexed owner, uint256 amount);
// Constructor
constructor() {
// Grant owner all roles
_grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
_grantRole(ADMIN_ROLE, msg.sender);
}
// Modifiers
modifier onlyOwner() {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "Only owner can call this");
_;
}
modifier onlyAdmin() {
require(hasRole(ADMIN_ROLE, msg.sender) || hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "Only admin/owner can call this");
_;
}
// Movie Management (Owner/Admin)
function addMovie(string memory _title, uint256 _price) external onlyAdmin {
movieCount++;
movies[movieCount] = Movie(movieCount, _title, _price);
emit MovieAdded(movieCount, _title, _price);
}
function updateMoviePrice(uint256 _movieId, uint256 _newPrice) external onlyAdmin {
require(_movieId > 0 && _movieId <= movieCount, "Invalid movie ID");
movies[_movieId].price = _newPrice;
}
// Showtime Management (Owner/Admin)
function addShowtime(uint256 _movieId, uint256 _time, uint256 _totalSeats) external onlyAdmin {
require(_movieId > 0 && _movieId <= movieCount, "Invalid movie ID");
require(_time > block.timestamp, "Showtime must be in the future");
require(_totalSeats > 0, "Seats must be greater than 0");
showtimeCount++;
showtimes[showtimeCount] = Showtime(_movieId, _time, _totalSeats, _totalSeats);
emit ShowtimeAdded(showtimeCount, _movieId, _time);
}
// Ticket Booking (Users)
function buyTicket(uint256 _showtimeId) external payable nonReentrant {
require(_showtimeId > 0 && _showtimeId <= showtimeCount, "Invalid showtime ID");
Showtime storage showtime = showtimes[_showtimeId];
Movie storage movie = movies[showtime.movieId];
require(showtime.seatsAvailable > 0, "No seats available");
require(msg.value == movie.price, "Incorrect Ether sent");
require(showtime.time > block.timestamp, "Showtime has passed");
// Issue ticket
ticketCount++;
tickets[ticketCount] = Ticket(_showtimeId, msg.sender, block.timestamp);
userTickets[msg.sender].push(ticketCount);
// Update seats
showtimes[_showtimeId].seatsAvailable--;
emit TicketPurchased(ticketCount, _showtimeId, msg.sender);
}
// Admin/Owner Views
function getTotalTicketsSold() external view onlyAdmin returns (uint256) {
return ticketCount;
}
function getRevenue() external view onlyAdmin returns (uint256) {
return address(this).balance;
}
function getUserTickets(address _user) external view onlyAdmin returns (uint256[] memory) {
return userTickets[_user];
}
function getMovieDetails(uint256 _movieId) external view onlyAdmin returns (string memory, uint256) {
require(_movieId > 0 && _movieId <= movieCount, "Invalid movie ID");
Movie storage movie = movies[_movieId];
return (movie.title, movie.price);
}
// Owner Functions
function withdrawFunds() external onlyOwner {
uint256 balance = address(this).balance;
require(balance > 0, "No funds to withdraw");
payable(msg.sender).transfer(balance);
emit FundsWithdrawn(msg.sender, balance);
}
function addAdmin(address _newAdmin) external onlyOwner {
_grantRole(ADMIN_ROLE, _newAdmin);
}
function removeAdmin(address _admin) external onlyOwner {
revokeRole(ADMIN_ROLE, _admin);
}
// Fallback function to receive Ether
receive() external payable {}
}
Contract Breakdown
-
Roles:
- Owner (
DEFAULT_ADMIN_ROLE): Full control (manage admins, withdraw funds).
- Admin (
ADMIN_ROLE): Manage movies/showtimes, view stats.
- User: Buy tickets.
-
Key Functions:
addMovie: Owner/Admin adds a movie (title, price).
addShowtime: Schedule a movie screening (movie ID, time, seats).
buyTicket: User buys a ticket (pays Ether, seat deducted).
getTotalTicketsSold: Admin/Owner views total tickets sold.
withdrawFunds: Owner withdraws contract balance.
-
Events:
MovieAdded
ShowtimeAdded
TicketPurchased
FundsWithdrawn
-
Security:
nonReentrant modifier (prevents reentrancy attacks).
AccessControl for role validation.
- Input validations (e.g., valid movie ID, sufficient Ether).
Deployment Steps (Sepolia Testnet)
-
Install dependencies:
npm install @openzeppelin/contracts hardhat dotenv
-
Create hardhat.config.js:
require("@nomiclabs/hardhat-ethers");
require("dotenv").config();
module.exports = {
solidity: "0.8.20",
networks: {
sepolia: {
url: process.env.SEPOLIA_RPC_URL,
accounts: [process.env.PRIVATE_KEY],
},
},
};
-
Deploy contract:
const hre = require("hardhat");
async function main() {
const CinemaBooking = await hre.ethers.getContractFactory("CinemaBooking");
const contract = await CinemaBooking.deploy();
await contract.deployed();
console.log("Contract deployed to:", contract.address);
}
main().catch((error) => console.error(error));
-
Run:
npx hardhat run scripts/deploy.js --network sepolia
Frontend Interaction (Example with Web3.js)
import Web3 from "web3";
import CinemaBookingABI from "./CinemaBookingABI.json";
const web3 = new Web3(window.ethereum);
const contractAddress = "YOUR_DEPLOYED_CONTRACT_ADDRESS";
const contract = new web3.eth.Contract(CinemaBookingABI, contractAddress);
// Buy ticket
async function buyTicket(showtimeId, price) {
const accounts = await web3.eth.getAccounts();
await contract.methods.buyTicket(showtimeId).send({
from: accounts[0],
value: web3.utils.toWei(price.toString(), "ether"),
});
}
// Get user tickets
async function getUserTickets(userAddress) {
const tickets = await contract.methods.getUserTickets(userAddress).call();
console.log("User Tickets:", tickets);
}
Testing (Hardhat)
Write tests in test/CinemaBooking.test.js:
const { expect } = require("chai");
const { ethers } = require("hardhat");
describe("CinemaBooking", function () {
let contract, owner, admin, user;
beforeEach(async () => {
[owner, admin, user] = await ethers.getSigners();
const CinemaBooking = await ethers.getContractFactory("CinemaBooking");
contract = await CinemaBooking.deploy();
});
it("Should add a movie", async () => {
await contract.addMovie("Inception", ethers.utils.parseEther("0.1"));
const movie = await contract.movies(1);
expect(movie.title).to.equal("Inception");
});
it("Should let user buy a ticket", async () => {
await contract.addMovie("Tenet", ethers.utils.parseEther("0.1"));
await contract.addShowtime(1, Math.floor(Date.now() / 1000) + 3600, 100);
await contract.connect(user).buyTicket(1, { value: ethers.utils.parseEther("0.1") });
expect(await contract.getTotalTicketsSold()).to.equal(1);
});
});
Run tests:
npx hardhat test
This structure covers all requirements:
- Role-based access (Owner/Admin/User).
- Ticket booking with Ether.
- Dynamic movie/showtime management.
- Events for transparency.
- Secure, tested, and ready for Sepolia deployment.
Next, do you want help with:
- Frontend React integration?
- Detailed testing strategy?
- IPFS hosting for frontend?
Let me know!