智能合约彩票项目定制:为selectWinner函数添加1%管理费
定制后的彩票合约(含1%管理费机制)
以下是修改后的完整合约代码,已集成你要求的1%奖池管理费逻辑:
// SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.7.0 <0.9.0; contract Lottery{ address public manager; //global dynamic array for participants. address payable[] public participants; constructor() { //msg.sender is a global variable used to store contract address to manager. manager=msg.sender; } //receive function only creates once in a smart comtract. //this function help to transfer the ether. //always use with external keyword and payable. receive() external payable{ //require is used as a if statement. it check if ether value is 2 then only run below code. require(msg.value==0.02 ether); participants.push(payable(msg.sender)); } function getBalance() public view returns(uint){ //only manager check the total balance. require(msg.sender==manager); return address(this).balance; } //this random function will genrate random value and from participant array and then return to the winnerFunction. function random() public view returns(uint) { return uint(keccak256(abi.encodePacked(block.difficulty, block.timestamp, participants.length))); } //this function decide the winner randomly. function selectWinner() public{ require(msg.sender==manager); require(participants.length>=3); uint totalBalance = address(this).balance; uint managementFee = totalBalance / 100; // 提取1%管理费 uint prizeAmount = totalBalance - managementFee; // 剩余99%为奖金 uint r=random(); //call random function. uint index=r % participants.length; //for making random function value in array length range. address payable winner = participants[index]; // 先转管理费给合约所有者 payable(manager).transfer(managementFee); // 再转奖金给中奖者 winner.transfer(prizeAmount); // 重置参与者数组 participants=new address payable[](0); } }
关键改动说明
- 管理费计算与转账:在确定中奖者后,先从合约总余额中提取1%作为管理费,转账给合约所有者(需将
manager地址转换为payable类型,因为只有payable地址才能接收ETH转账) - 奖金发放:将扣除管理费后的剩余99%金额转账给中奖者
- 逻辑顺序:严格遵循「先扣管理费,再发奖金」的要求流程
注意事项
- Solidity整数除法会向下取整,因此1%管理费的计算会舍去小数部分,这部分极小的剩余ETH会留在合约中,可在后续开奖时计入奖池
- 确保合约部署者(即
manager)的地址是有效的ETH接收地址
内容的提问来源于stack exchange,提问作者ivan
相关产品推荐
相关产品推荐

