Solidity – How to Fix ‘Out of Gas’ Exception When Transferring Ether

ethersolidity

I try to transfer Ether from the contract to an address but it gives the error that the transaction is out of gas. I think it's a small problem but I can't find it. I have to specifically use solidity version 0.4.24.

The warning from Remix
The balance of the contract
The parameters I use
The error from MetaMask

I have tried different methods, like:

address.transfer(amount);
address.send(amount);
address.call.value(amount)( );

All methods will give the same out of gas exception. and the send and call method will also give a warning that it's outdated and that I should use the transfer method.

I also tried to adjust the gas and it didn't work, I also tried the needed 2,300 for the transfer listed on the docs.

The code:

pragma solidity 0.4.24;

contract TestContract {

    function() external payable { }

    function payContract() public payable {}

    function paySomeone(address _address, uint256 _amount) external {
         _address.transfer(_amount);
    }

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

}

Does anyone know what the problem is here?

Thank you for reading.

Best Answer

Not sure what you meant by

I have to specifically use solidity version 0.4.24

Assuming this is so (e.g. policy) ...

First, change ^0.4.24 to 0.4.24 without ^ to confirm you are not compiling with 0.5.x which would necessitate adding the keyword payable to the address declaration.

Second, confirm that contract has funds to send. The transfer draws from the contract's own balance so if the requested amount exceeds the funds on hand, the operation will fail. Your getBalance() function shows the current balance. It will initially be zero, so you have to send some ether to the contract in order to set up the test scenario.

Third, confirm the backing blockchain implementation is compatible with Solidity 0.4.24. The "backing" could be ganache, a private network with geth or a public testnet. In any case, the EVM version is a property of the network and you need a post-Byzantium EVM to run code compiled with 0.4.24 due to changes in the interface specification. A mismatch will cause this sort of trouble.

Hope it helps.

UPDATE (per comments below):

Your contract works fine, so I would be concentrate on testing methodology next.

You'll need more than 2,300 gas. Send much more to cover the rest of the operations (send itself forwards 2,300 gas to the receiver, the stipend, but this is not the budget for the whole shebang.)

In my test, the cost was 22,000 gas.

You generally don't have to specify gas but estimateGas() isn't 100%. Consider specifying 100,000 gas to rule it out.

Here is the contract working in Remix to show that the issue may be client-side, i.e. how are you forming the request and sending it.

enter image description here

Hope it helps.