Ethereum Payments – Sending Ether to a Contract Using Remix

contract-developmentetherpayablepaymentsstate-transition

New to Solidity…

When deploying a contract on a private blockchain using Remix, I am unable to execute payable functions. When executing these functions, the following error message displays: gas required exceeds allowance or always failing transaction.

The code was obtained from here and modified for the purpose of study.

pragma solidity ^0.4.17;

contract depositTest {

    uint256 public fee = 2000000000000000000 wei;

    function depositUsingParameter(uint256 deposit) public payable {  //deposit ETH using a parameter
        require(msg.value == deposit);
        deposit = msg.value;
    }

    function depositUsingVariable() public payable { //deposit ETH using a variable
        require(msg.value == fee);
        fee = msg.value;
    }

    function getContractBalance() public view returns (uint256) { //view amount of ETH the contract contains
        return address(this).balance;
    }

    function withdraw() public { //withdraw all ETH previously sent to this contract
        msg.sender.transfer(address(this).balance);
    }

    function() public payable {
    // this function enables the contract to receive funds
    }
}

Best Answer

The code is correct but I lacked the understanding regarding the mechanics of how Ether is accessed and sent to contracts. I will explain to aid others in their advancement of knowledge...

The function depositUsingParameter establishes a required value that is provided by the Ether owner. Since contracts cannot automatically withdraw funds from an Ether owner's wallet, the Ether owner must agree to allow the function to execute by providing an amount in the 'Value' field. (This field is located in the Run tab of Remix).

If I want to execute the depositUsingParameter function...

  1. I must put the amount I want to deposit first in the 'Value' field.

Remix - Run tab interface - First add the amount of Ether you want to deposit 2. Next, add the same value in Wei in the depositUsingParameter field.

...add the same value in Wei in the depositUsingParameter field

This allows for the successful execution of the function.

For function depositUsingVariable, the value of Ether is predetermined. In this case, 2 ETH. The Ether owner is required to provide 2 ETH in the value field (as illustrated above) in order for the function to execute successfully.

Related Topic