Basic Smart Contract: Lottery Application

This smart contract enables users to enter a lottery with a fixed entry of 0.1 Ether. A minimum of three participants must join before a winner can be selected. Only the account that initiates the contract has the authority to choose the winner.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract lottery{

    address public admin;
    address payable[] public participants;
    
    event participantAdded(address sender);
    event WinnerSelected(address winner);

    constructor(){
        admin= msg.sender;
    }

    function addParticipent() external payable {
        require(msg.value==0.1 ether,"The value should be exactly 0.1 ETH");
        participants.push(payable(msg.sender));
        emit participantAdded(msg.sender);
     }

     function getBalance() public view returns (uint){
        require(msg.sender ==admin,"Only admin can call this function");
        return address(this).balance;
     }

     function random() internal view returns (uint){
        return uint(keccak256(abi.encodePacked(block.prevrandao, block.timestamp, participants.length)));
     }

     function Winner() public {
        require(msg.sender ==admin,"Only admin can call this function");
        require(participants.length>=3, "Add atleast 3 participants");

        address payable winner;

        uint r = random();
        uint index = r % participants.length;
        winner = participants[index];
        winner.transfer(getBalance());
        emit WinnerSelected(winner);
     }
}

Testing with Remix

Open the https://remix.ethereum.org/. Create ‘Lottery.sol’ file and paste the code inside.

  • Deploy the Contract on Remix
  • Adding Participants to the Lottery

Select various accounts on Remix to participate in the lottery.

At least three accounts must participate to select the winner.

The value of Ether should be exactly “0.1”.

Remix only supports decimal values, therefore, use the Unit Converter | Etherscan to convert 0.1 Ether to Wei, which equals “100000000000000000”.

Click the ‘addParticipant’ button.

  • Select the Winner

Choose the first account that deployed the Lottery Contract.

Click the ‘Winner’ button to select a winner at random.

If a minimum of three participants are present, a winner will be chosen at random, and Ether will be transferred to the winner’s account.