1

This is my simple code for following along a tutorial. We are building a Lottery Smart Contract. However, I am failing to transfer the contract's balance to the winner. (see the last line inside of the contract.)

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

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

    constructor() {
        manager = msg.sender;
    }
    
    function enter() public payable {
        require(msg.value > .01 ether);

        players.push(msg.sender);
    }
    
    function random() private view returns (uint) {
        return uint(keccak256(abi.encodePacked(block.difficulty, block.timestamp, players)));
    }

    function pickWinner() public {
        uint index = random() % players.length;

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

I am getting the following error in remix:

TypeError: "send" and "transfer" are only available for objects of type "address payable"

I understand the error and tried changing the declaration of the players variable like this:

address payable[] public players;

But that gives me another error:

TypeError: Member "push" not found or not visible after argument-dependent lookup in address payable[] storage ref.

Can someone help me out?

0
1

You can use either this:

address[] public players;
...
players.push(msg.sender);
...
payable(players[index]).transfer(...);

Or this:

address payable[] public players;
...
players.push(payable(msg.sender));
...
players[index].transfer(...);
2
  • Thanks a lot! Works both ways. And a happy new year. :) Dec 31 '20 at 19:25
  • @Hyun-KyungYi: You're welcome. Happy New Year :) Dec 31 '20 at 19:27

Not the answer you're looking for? Browse other questions tagged or ask your own question.