pragma solidity ^0.8.0;
contract GiftShop {
mapping(address => uint) public loyaltyPoints;
mapping(string => uint) public gifts;
address public owner;
event GiftRedeemed(address user, string giftName);
modifier hasEnoughPoints(uint pointsNeeded) {
require(loyaltyPoints[msg.sender] >= pointsNeeded, "Insufficient loyalty points");
_;
}
modifier onlyOwner() {
require(msg.sender == owner, "Only owner can call this function");
_;
}
constructor() {
owner = msg.sender;
gifts["Coffee Mug"] = 10;
gifts["T-shirt"] = 20;
gifts["Smartwatch"] = 50;
}
function addPoints(address user, uint points) public onlyOwner {
loyaltyPoints[user] += points;
}
function redeemGift(string memory giftName) public hasEnoughPoints(gifts[giftName]) {
loyaltyPoints[msg.sender] -= gifts[giftName];
emit GiftRedeemed(msg.sender, giftName);
}
}
- 有一個智能合約
GiftShop
,用於管理學生的集點數和禮物的兌換。 - 每個學生可以根據他們的集點數來兌換禮物。我們希望僅當學生的集點數達到一定標準時才能兌換禮物。
GiftShop
合約用於管理學生的集點數和禮物的兌換。loyaltyPoints
映射用於存儲學生的集點數。gifts
映射用於存儲禮物的集點數需求。hasEnoughPoints
modifier 用於檢查學生是否擁有足夠的集點數來兌換禮物。onlyOwner
modifier 用於限制只有合約的擁有者才能調用的函式。- 在 modifier 中,首先檢查相應的條件。如果條件不滿足,則通過
require
函式拋出異常。 addPoints
函式用於為學生增加集點數,僅合約的擁有者可以調用。redeemGift
函式用於兌換禮物,只有當學生擁有足夠的集點數時才能成功兌換。