Solidity – How to Write a Contract that Only Accepts Fixed Amount Payments

solidity

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);

Best Answer

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);
}
Related Topic