2

I'm a beginner contract writer. How can I ensure that a payment (in a payable function) is only done with a fixed amount?

My first attempt (which doesn't work) looks like this:

  function getIn() public payable returns (uint256)  {

    uint256 _amount = 30000000000000000;
    require( msg.sender.balance >= _amount);
    balanceOf[ msg.sender ] -= _amount;
    ...

Is the only way to do this to create a payable function that then returns the diff? Something like this:

  function getIn() public payable returns (uint256)  {

    uint256 _amount = 30000000000000000;
    require( msg.value >= _amount);
    require( msg.sender.balance >= _amount);

    balanceOf[ msg.sender ] -= _amount;
    msg.sender.transfer( msg.value - _amount);

1 Answer 1

2

The functions seem weird... If this is a function that takes money from a user (they are calling payable function and sending your contract money), then why are you subtracting money from their internal balance?

They are depositing money, their balance should increment.

As for accepting a fixed amount of eth, what do you mean? You want the function to be executed only if the amount sent to it is = to certain value? If so:

// This function will fail if the buyer doesn't send the exact amount of money.

function buySomething() payable{
  uint exactAmount = 3000;
  require (msg.value == exactAmount);
  boughtSomething = true;
}

If you want to accept any amount and return the difference:

function buySomethingAndReturnChange() payable{
  uint minAmount = 3000;
  require (msg.value >= minAmount);
  uint moneyToReturn = msg.value - minAmount; 

  boughtSomething = true;
  if(moneyToReturn > 0)
    msg.sender.transfer(moneyToReturn);
}
4
  • Hi pabloruiz55, thanks for answering my question. I want to accept only a fixed amount of Ether say, if someone wants to purchase something of a fixed price ... give them back the Ether they sent too much of. I assume this is how things are done ... or is it always assumed that the sender will use the right amount and if they send too much then that's fine?
    – Etienne
    Nov 8, 2017 at 1:56
  • Or is the fixed amount usually managed in a GUI? Or would the contract just do: require (msg.value == minDeposit);? (I guess that makes most sense)
    – Etienne
    Nov 8, 2017 at 2:03
  • Just updated my answer to account for both scenarios, accepting the exact amount of money or anything above the minimum and return the change. Nov 8, 2017 at 2:13
  • @pabloruiz55 Don't you mean payable(msg.sender).transfer(moneyToReturn);? You're missing the payable for v.0.8.0.
    – enchance
    Mar 26 at 10:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.