#鐵人賽 #ethereum #solidity
鐵人賽至今已經過了一半,為了讓大家能更深刻地理解之前的內容與如何組合成一個完整功能性的合約,因此,今天就來示範一個完整的合約應該從無到有怎麼被寫出來!
本日影片: https://youtu.be/g8CAobvfF78
本日合約:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
contract Donation {
address public owner;
mapping(address => uint256) donationList;
event Donate(address indexed sender, uint256 value);
event Withdraw(address indexed owner, uint256 value);
modifier onlyOwner() {
require(msg.sender == owner, "Only owner can access this function");
_;
}
constructor() {
// 將合約的擁有者設定成建立合約的人
owner = msg.sender;
}
// 收受捐款的函式
function donate() public payable {
donationList[msg.sender] += msg.value;
emit Donate(msg.sender, msg.value);
}
// 查詢捐款總金額
function getHistory() public view returns (uint256) {
return donationList[msg.sender];
}
// 查詢 VIP 等級
function getRank() public view returns (string memory) {
if (donationList[msg.sender] > 10 ether) {
return "UR";
} else if (donationList[msg.sender] > 5 ether) {
return "SR";
} else if (donationList[msg.sender] > 1 ether) {
return "R";
} else if (donationList[msg.sender] > 0) {
return "N";
} else {
return "None";
}
}
// 提領餘額
function withdraw() onlyOwner public {
address payable receiver = payable(owner);
uint256 value = address(this).balance;
receiver.transfer(value);
emit Withdraw(receiver, value);
}
}
本影片提到的連結:
「Remix IDE」: https://remix.ethereum.org/
「在 2022 年,我們該如何寫智能合約」: https://ithelp.ithome.com.tw/users/20083367/ironman/5019
「那些關於 Ethereum 的事」: https://ithelp.ithome.com.tw/users/20083367/ironman/5136
「一本關於 Ethereum 與 Solidity 智能合約的書」: https://solidity.tw
「文章或主題許願池」: https://github.com/hydai/solidity-book/issues
「本系列播放清單」: https://www.youtube.com/playlist?list=PLHmOMPRfmOxQYDnXAc1hKY6ra4WDU8ZlM