Solidity – Why is the Method in receive() External Payable Not Called?

accountsaddressesbalancessoliditytransactions

I wrote a smart contract that, when receiving money to my address, should automatically transfer 50% to the 1st wallet address, 25% to the second, 25% to the third.
For some reason it doesn't do it automatically.

I am using Remix IDE. I clicked Compile in the left tab of the Solidity Compiler, then went to Deploy & Run transactions, deleted the deployed contracts, wrote at the top in value 1 (selected ether instead of wei on the side) and deployed this contract on the new one.

1 ether was debited from the selected wallet and transferred to the contract account (I found out using the getBalance function), but the money was not transferred to the required wallet addresses. In order for the money to be transferred, you have to click on the withdrawFunds button below (that is, you need to call this function).

I wrote receive() external payable{this.withdrawFunds();}, expecting that because of this line, the contract itself will transfer money when received.
But for some reason it doesn't work. I need the contract to transfer the money itself.

Contract:

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

contract Demo {
        constructor() payable{}
        receive() external payable{this.withdrawFunds();}

        function withdrawFunds() external payable{
            address addr1 = 0xAb8483F64d9C6d1EcF9b849Ae677dD3315835cb2;
            address addr2 = 0x4B20993Bc481177ec7E8f571ceCaE8A9e22C02db;
            address addr3 = 0x78731D3Ca6b7E34aC0F824c42a7cC18A495cabaB;

            address payable wallet1 = payable(addr1);
            address payable wallet2 = payable(addr2);
            address payable wallet3 = payable(addr3);

            uint _50 = address(this).balance*50/100; //50% of balance of contract
            uint _25 = address(this).balance*25/100; //25% of balance of contract
            uint s_25 = address(this).balance*25/100; //25% of balance of contract

            wallet1.transfer(_50);
            wallet2.transfer(_25);
            wallet3.transfer(s_25);
        }

        function getBalance() public view returns(uint){
            return address(this).balance;
        }

        function receiveFunds() external payable {}
}

Best Answer

Receive fallback function will be executed on plain Ether transfers

(e.g. via .send() or .transfer()). You receiveFunds() call will not trigger receive() which is why transfer never happens.

Related Topic