rezli
rezli

Reputation: 51

Send and transfer are only available for objects of type address payable , not address

function withdraw() public payable {
  msg.sender.transfer(address(this).balance);
}

I wrote this code and I got "ERROR send and transfer are only available for objects of type address payable , not address.".

Upvotes: 2

Views: 1814

Answers (3)

Yilmaz
Yilmaz

Reputation: 49182

   address payable private owner;

then set the owner in constructor as msg.sender:

constructor() {
    setOwner(msg.sender);
  }

this is setOwner:

function setOwner(address newOwner) private {
    owner = payable(newOwner);
  }

this is withdraw function:

 function withdraw() external onlyOwner {
     (bool success,)=owner.call{value:address(this).balance}("");
    // if it is not success, throw error
     require(success,"Transfer failed!");
   }

Make sure only owner can call this so write a modifier:

 modifier onlyOwner() {
    if (msg.sender != getContractOwner()) {
      revert OnlyOwner();
    }
    _;
  }

revert OnlyOwner is sending custom message with newer versions of solidity:

/// Only owner has an access!
  error OnlyOwner();

Upvotes: 0

Theo Dale
Theo Dale

Reputation: 195

From the docs:

The address type comes in two flavours, which are largely identical:

  • address: Holds a 20 byte value (size of an Ethereum address).
  • address payable: Same as address, but with the additional members > transfer and send.

You need to cast it to an address payable type to use the send and transfer methods. See https://docs.soliditylang.org/en/v0.8.11/types.html#address for more details.

Upvotes: 0

Dylan Kerler
Dylan Kerler

Reputation: 2187

Only the payable address type has the transfer method. msg.sender is the address type so you need to cast it to be payable:

payable(msg.sender).transfer(address(this).balance);

Upvotes: 3

Related Questions