智能合约怎么进行打赏功能?在互联网和开源平台上分享经验或者代码后,网站通常有一个打赏功能,用于对阅读者对分享者的感谢,使用solidity编写一个智能合约打赏功能:
1.任何人可以像合约账号打赏捐赠
2.任何人可以查看历史捐赠总额
3.合约拥有者可以设置余额提醒金额
4.合约拥有者可以进行提现
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract Donator {
// 事件,用于记录打赏行为
event Donated(address indexed donator, uint256 amount);
// 事件,用于记录提现行为
event Withdrawn(address indexed withdrawer, uint256 amount);
// 事件,用于记录提醒金额设置
event AlertAmountSet(uint256 alertAmount);
// 事件,用于触发余额超过提醒金额的提醒
event AlertTriggered(uint256 balance);
// 合约拥有者地址
address private owner;
// 提醒金额
uint256 private alertAmount;
// 捐赠总额
uint256 private totalDonations;
// 构造函数,设置合约的拥有者
constructor() {
owner = msg.sender;
}
// 打赏函数,任何人都可以调用,向合约发送ETH
function donate() public payable {
require(msg.value > 0, "Donation amount must be greater than 0");
totalDonations += msg.value;
emit Donated(msg.sender, msg.value);
_checkAlert();
}
// 设置提醒金额,只有合约的拥有者可以调用
function setAlertAmount(uint256 _alertAmount) public {
require(msg.sender == owner, "Only the owner can set alert amount");
require(_alertAmount > 0, "Alert amount must be greater than 0");
alertAmount = _alertAmount;
emit AlertAmountSet(alertAmount);
}
// 提现函数,只有合约的拥有者可以调用
function withdraw() public {
require(msg.sender == owner, "Only the owner can withdraw");
uint256 amount = address(this).balance;
emit Withdrawn(msg.sender, amount);
payable(msg.sender).transfer(amount);
}
// 获取所有捐赠总数的函数
function getTotalDonations() public view returns (uint256) {
return totalDonations;
}
// 获取合约余额的函数,只有合约的拥有者可以调用
function getBalance() public view returns (uint256) {
require(msg.sender == owner, "Only the owner can view the balance");
return address(this).balance;
}
// 检查是否达到提醒金额,如果达到则触发提醒事件
function _checkAlert() private {
if (address(this).balance >= alertAmount) {
emit AlertTriggered(address(this).balance);
}
}
}