- Solidity编译器版本0.5.0
- 玩家支付2以太币的固定价格加入
- 可以加入玩家的"n"个用户只能通过支付固定金额加入一次的限制
- 不允许业主/合同经理参加抽奖
- 智能合约必须随机选择赢家
- 获胜者获得所有奖金
- 当中奖者被选中时,新的抽奖开始
pragma solidity ^0.5.0;
contract LuckyDraw
{
address owner;
address[3] participants;
constructor() public
{
owner = msg.sender;
}
modifier onlyOwner()
{
require(msg.sender == owner);
_;
}
modifier notOwner()
{
_;
}
function joinLottery() payable public require notOwner()
{
require(msg.value == 2 ether);
}
function random() private view returns(uint)
{
return uint(keccak256(abi.encode(block.difficulty, now, participants)));
}
function pickwinner() external onlyOwner
{
uint win = random() % participants.length;
participants[index].transfer(address(this).balance);
participants = new address[](0);
}
}
如何设置号码?玩家数到n ?
不幸的是,我有一些未知的问题与固体0.5.0,所以我提供你一个更好的合同比你写在这里:
pragma solidity 0.6.0;
contract LuckyDraw {
uint private maxParticipantNumbers;
uint private participantNumbers;
uint private ticketPrice;
address private owner;
address payable[] participants;
constructor() public {
owner = msg.sender;
maxParticipantNumbers = 3;
ticketPrice = 2 ether;
}
modifier onlyOwner(){
require(msg.sender == owner, "Access denied!");
_;
}
modifier notOwner(){
require(msg.sender != owner, "Access denied");
_;
}
function setTicketPrice(uint _valueInEther) public onlyOwner{
ticketPrice = (_valueInEther * 1000000000000000000);
}
function setMaximmNumbers(uint _maxNumbers) public onlyOwner{
participantNumbers = _maxNumbers;
}
function viewTicketPrice() external view returns(uint){
return ticketPrice;
}
function joinLottery() payable public notOwner(){
require(msg.value == ticketPrice);
if (participantNumbers < maxParticipantNumbers){
participants.push(msg.sender);
participantNumbers++;
}
else if (participantNumbers == maxParticipantNumbers){
msg.sender.transfer(msg.value);
pickwinner();
}
}
function random() private view returns(uint){
return uint(keccak256(abi.encode(block.difficulty, now, participants, block.number)));
}
function pickwinner() internal{
uint win = random() % participants.length;
participants[win].transfer(address(this).balance);
delete participants;
participantNumbers = 0;
}
function endGame() external onlyowner{
uint win = random() % participants.length;
participants[win].transfer(address(this).balance);
delete participants;
participantNumbers = 0;
}
}
解释如下:
首先编译器是0.6.0!
maxParticipantNumbers
为最大参与数。
participantNumbers
计数。
ticketPrice
为机票价格。
后面是相同的
setTicketPrice()
是一个函数,只有合同的所有者可以调用它并更新票价,或者你可以离开它(请注意,你自动输入的数字是wei的度量,所以我在最后添加了10^18,你只需要设置数字,它是以太金额)!
setMaximmNumbers()
是一个只有合约所有者才能调用的函数,它可以改变可以参加彩票的最大玩家数量!
viewTicketPrice()
是一个外部视图函数,它返回票的价格(注意它返回的值是wei)。
joinLottery()
是一个出售彩票的函数,当最后一个参与者购买彩票时,自动调用pickwinner()
函数,彩票结束,自动转账并重新开始!
我还放了endGame()
功能,以防所有者想要在达到最大参与者数量之前结束游戏!
当然你可以自己改变,但我希望你喜欢它!