Search code examples
hashblockchainethereumsoliditysmartcontracts

Solidity question on transfers and hashing


using solidity 8.16

from solidity: TypeError: Wrong argument count for function call: 3 arguments given but expected 1. This function requires a single bytes argument. Use abi.encodePacked(...) to obtain the pre-0.5.0 behaviour or abi.encode(...) to use ABI encoding. --> contract.sol:17:21:

function random() private view returns (uint) {
        return uint(keccak256(block.difficulty, block.timestamp, players)); // bad line, trying to generate a sudo-random number and return the results
    }

from solidity: TypeError: "send" and "transfer" are only available for objects of type "address payable", not "address". --> contract.sol:22:18:

function pickWinner() public restricted {
        uint index = random() % players.length;
        payable (players[index].transfer(this).balance); <-- bad line trying to transfer funds of the contract to a address.
        players = new address[](0);
    }

I have been trying to figure this out for hours and idk what I'm doing wrong every time I fix what it say's it give me another error on the same line.


Solution

  • For the first error, error message is clear. Use abi.encodePacked

      return uint(keccak256(abi.encodePacked(block.difficulty, block.timestamp, players,counter)));
    

    For the second error, looks like you have players data structure. Since you are accessing with index, it must be an array that stores payable addresses.

     address payable[]  public players;
    

    then to write the transfer logic:

    players[index].transfer(address(this).balance);