简体   繁体   中英

I want to make a time based transaction in smart contract

I am creating smart contract for lottery system and I want to make a time based transaction like a certain amount of players are added into the array then a time stamp should run and on specific time which I will declare should send the amount to the winner,

This is the part where I am stuck, I am trying to enter into the lottery from this this function and when conditions met I want to transfer the amount through the same function cause I want to automate the winner function:

function enter() public payable{
   require(msg.value > 1 wei);
   players.push(msg.sender);

 if(players.length==10){
     start = block.timestamp;
 }

 if(block.timestamp>= start+totalTime){
    uint index = random()% players.length;
    players[index].transfer(this.balance);
    dead[index].transfer((this.balance*2)/100);
    winner = players[index];
    players = new address[](0);
 }

This is my complete code:

pragma solidity ^0.4.26;

contract Lottery{
    address public manager;
    address[] public players;
    address [0x000000000000000000000000000000000000dead] private dead;
    address public winner;
    uint start;
     uint end;
    uint totalTime=50;
   
    constructor()public {
       manager = msg.sender;
    }

    function enter() public payable{
       require(msg.value > 1 wei);
       players.push(msg.sender);
    
     if(players.length==10){
         start = block.timestamp;
     }

     if(block.timestamp>= start+totalTime){
        uint index = random()% players.length;
        players[index].transfer(this.balance);
        dead[index].transfer((this.balance*2)/100);
        winner = players[index];
        players = new address[](0);
     }
    }
    function random() private view returns (uint){
        return uint(keccak256(block.difficulty,now,players));
    }
    function getBalance() public view returns(uint){
        return address(this).balance;
    }
    function getPlayers() public view returns (address[]){
        return players;
    }
    function getWinner() public view returns (address){
        return winner;
    }
     function getTime() public view returns (uint){
        return end-block.timestamp;
    }
}

You can't, someone has to call the function and pay the gas fees, what you can do is having an script that listen for events and every time someone "enters" in the lottery and check if already reached the desired amount and then calls the function to get the winner, also you can't have any logic outside a function in solidity, using block difficulty and timestamp as a source of randomness if you are planing to deploy to production is better to use chainlink

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM