1.8 Modifier 修飾符

1.8 Modifier 修飾符

更新於 發佈於 閱讀時間約 3 分鐘
modifier

modifier

// SPDX-License-Identifier: MIT
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 函式用於兌換禮物,只有當學生擁有足夠的集點數時才能成功兌換。
avatar-img
Follow the Rainmaker 🌧️
5會員
91內容數
尋大神腳印, 亦步亦趨。
留言
avatar-img
留言分享你的想法!
0. 大綱Outline 以太坊交易 發起交易 與智能合約互動 receive & fallback function 1. 舊以太坊交易 Ethereum Gas Tracker - 7 Gwei - Etherscan //交易技術, 表示特定帳戶的交易數量,是計數器, 每發一筆交
Overview 1. Request Wallet Connection from Metamask get account function get account function 2. Set your smart contract address injected provide
在 Solidity 中,constant 變量用於定義不可變的常數值。這些常數在合約的生命週期內不會改變,並且它們的值必須在宣告時設定。使用 constant 關鍵字可以節省 gas,因為它們在編譯時就已經被嵌入到字節碼中,不需要在運行時讀取存儲。 用法 定義常數: 常數變量必須在宣告時初始
0. 大綱Outline 以太坊交易 發起交易 與智能合約互動 receive & fallback function 1. 舊以太坊交易 Ethereum Gas Tracker - 7 Gwei - Etherscan //交易技術, 表示特定帳戶的交易數量,是計數器, 每發一筆交
Overview 1. Request Wallet Connection from Metamask get account function get account function 2. Set your smart contract address injected provide
在 Solidity 中,constant 變量用於定義不可變的常數值。這些常數在合約的生命週期內不會改變,並且它們的值必須在宣告時設定。使用 constant 關鍵字可以節省 gas,因為它們在編譯時就已經被嵌入到字節碼中,不需要在運行時讀取存儲。 用法 定義常數: 常數變量必須在宣告時初始