In this smartbook, we'll discuss how to create a lottery contract with other functionality like only 80% amount will sent to the winner address and the remaining amount 20% goes to the owner.
In this smart contract, we'll mainly focus on how to send 80% to the winner, not 100%.
If you don't see my " Basic lottery contract ". Please check it first because I'm forward to the same code. If you want to better understand please check it.
We create a function name transferAmount in this function we basic find 80% of our contract balance amount.
function transferAmount() public view returns(uint) {
uint amount = (getBalance() / 100) * 80;
return amount;
}
We're not using the payable function because the payable function consumes some gas cost. And it's used where we receive or send the ether values. And we're only find the value not send ether to any address.
pragma solidity >=0.4.5 <0.9.0;
contract Lottery {
address owner;
address payable[] participants;
constructor(){
owner = msg.sender;
}
modifier onlyOwner {
require ( msg.sender == owner );
_;
}
function Owner() public view returns(address){
return msg.sender;
}
function getBalance() onlyOwner public view returns(uint){
return address(this).balance;
}
receive() external payable {
require ( msg.sender != owner, "Owner not send" );
require ( msg.value == 1 ether, "Invalid amount" );
participants.push(payable(msg.sender));
}
function transferAmount() public view returns(uint) {
uint amount = (getBalance() / 100) * 80;
return amount;
}
function random() onlyOwner public view returns(uint){
return uint(keccak256(abi.encodePacked(block.difficulty, block.timestamp, participants.length)));
}
function Winner() onlyOwner public payable{
address payable winner;
uint index = random() % participants.length;
winner = participants[index];
winner.transfer(transferAmount());
participants = new address payable[](0);
}
}