Search code examples
blockchainethereumsoliditysmartcontractsweb3js

cannot send entire contract amount to account in solidity


I have created a lottery contract where I have stored all participated players in an address array I am getting errors while transferring my contract money to the winner i.e in function winner another error is while converting hash value to uint

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.11;

contract lottery
{
  address manager;
  address[] public players;

  function setManager() public{
      manager = msg.sender;
  }
  function enterLottery () public payable{
    require(msg.value > 0.9 ether);
    players.push(msg.sender); 
  }
function random() private view returns(uint){
     return uint(keccak256(block.difficulty,block.timestamp,players));
  }
  function winner() public payable{
      uint index = random() % players.length;
      players[index].send(address(this).balance);
      players = new address[](0);
  }
}

Solution

  • I run your code on remix and commented the errors on the line. It compiles successfully now:

    // SPDX-License-Identifier: GPL-3.0
    pragma solidity ^0.8.11;
    
    contract lottery
    {
      address manager;
      // send and transfer are only available for objects of type "address payable"
    //   address[] public players;
        address payable[]  public players;
    
    
      function setManager() public{
          manager = msg.sender;
      }
      function enterLottery () public payable{
        require(msg.value > 0.9 ether);
        // msg.sender was payable before version 8. we have to explicitly set it as payable
        players.push(payable(msg.sender)); 
      }
    function random() private view returns(uint){
        // Wrong argument count for function call:3 arguments given but expected 1. this function requires a single byte argument
        //  return uint(keccak256(block.difficulty,block.timestamp,players));
        return uint(keccak256(abi.encodePacked(block.difficulty,block.timestamp)));   
      }
    
      function winner() public payable{
          uint index = random() % players.length;
          // Failurer condition of 'send' is ignored. Consider using 'transfer' instead
        //   players[index].send(address(this).balance);
        players[index].transfer(address(this).balance);
        // type address[] memory is not implicitly convertible to expected type address payable[] storage ref
        //   players = new address[](0);
        players = new address payable[](0);
    
      }
    }