Solidity – Send Value of Payable Function to Owner

addressespayablesolidity

Simple test/use case, there is a payable function that should send money directly to the owner. I get the error as in the title. Code:

address private owner;
    
    constructor() {
        owner = msg.sender;
    }

function makePay() public payable {
        owner.transfer(msg.value);
    } 

Now if I try declaring address private payable owner; I get error Expected identifier but got payable.

Also if I try address payable private owner; then in my constructor I get the error type address is not implicitly convertible to expected type address payable.

How can I fix this? And what's the underlying principle I'm missing here? New to this and learning, thanks.

Best Answer

The correct syntax for recent versions (>0.8.0) would be :

// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0 <0.9.0;

contract YourContract {
    address payable private owner;
    
    constructor() {
        owner = payable(msg.sender);
    }

    function makePay() public payable {
        owner.transfer(msg.value);
    } 
}

Also if I try address payable private owner; then in my constructor I get the error type address is not implicitly convertible to expected type address payable.

This is because msg.sender is of type address, and not address payable by default. You must explicitly mark an address as payable by design. As in the example, you cast the msg.sender variable to a type of address payable using payable(your_address).

You could also defer the cast to the moment where you actually need it :

// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0 <0.9.0;

contract YourContract {
    address private owner;

    constructor() {
        owner = msg.sender;
    }

    function makePay() public payable {
        payable(owner).transfer(msg.value);
    } 
}

The underlying principle is simply that since you are about to transfer valuable tokens, the language is defined in such a way that you must explicitly allow it to do so.

Related Topic