Why can’t I transfer ether in contract

go-ethereumsolidity

I am deploying a contract to Ethereum EVM environment with Ropsten testing network. It sends 1 ether to another account which is passed from the method paratemter.

After deploy, I set the target account's address 0xAb8483F64d9C6d1EcF9b849Ae677dD3315835cb2 when call transfer method. But I see below error:

transact to Leger.transfer errored: VM error: revert.
    The transaction has been reverted to the initial state.
Reason provided by the contract: "Transfer failed.".
Debug the transaction to get more information.

My account has 99 ethers and why I got above error?

// SPDX-License-Identifier: MIT
pragma solidity 0.7.4;
pragma experimental ABIEncoderV2;

contract Leger {

    address payable owner;

    constructor(){
        owner = msg.sender;
    }

    function transfer(address payable _recipient) public payable {
        
        bool success = _recipient.send(1);
        require(success, "Transfer failed.");
    }


    function getBalance() public view returns (uint256) {
        return owner.balance;
    }
    

}

I tired to fund first by setting up the 4th parameter when deploy (10 ether) but I got this error on deploying:

enter image description here

enter image description here

Best Answer

The problem is that your smart contract is not funded. You can verify this by changing the code of your getBalance function like this:

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

Now, if you call getBalance it will return 0.

If you want to transfer ether from your smart contract you have to fund it first. If you are using remix you can do this by setting a value (4th input field from the top in the "DEPLOY & RUN TRANSACTIONS" tab) and then call the transfer function.

Related Topic