Solidity语法基础学习
九、实战项目(一):
学以致用
UP主捐款合约
·合约要求:
·建立时,需将合约的建立者设定成owner(constructor,msg.sender)
·需记录每个观众的捐款总额(mapping)
·每次收到捐款时,需触发捐款事件:(event)
·列出捐款者、捐助金额(indexed)
·提供函数可以查询观众的捐款金额(returns)
·提供函数可以查询观众的VIP等级(string,if)
·没捐过款→”None”
·> 0ETH→”N”
·> 1ETH→”R”
·> 5ETH→”SR”
·>10ETH→”UR”
·提供函数让UP主可以提领金额,且触发提领事件(payable,address.balance,transfer)
·列出提款者、提领金额
Example:UP主捐款合约
//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判断要从范围大的条件到范围小的条件,否则满足小条件的会导致全部回传N 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(address(this).balance); emit Withdraw(receiver, value); } }