1
contract A {
  function sendtoken() payable returns(bool) {
      require(msg.value!=0);
      balances[msg.sender]+= 1;
      balances[owner]-= 1;
      owner.transfer(msg.value);
      return true;
  }
}

Here if the owner.transfer(msg.value) function fails, then the token will definitely send to the sender, but the ether will not get to the owner. How can prevent this error? Is calling the function owner.transfer(msg.value) before the token transfer a better solution?

1

<address>.transfer will automatically throw, or in other words, trigger revertion of all state changes, and the tokens will not transfer.

|improve this answer|||||
  • So if the transfer fails then all the state changes that I made with this payable function will revert to its previous state? There are no worries about this? – Akash Feb 6 '18 at 10:38
  • Yes, any changes made within that call will be reverted. – hextet Feb 6 '18 at 10:41
0

.transfer() will throw error. If user don't have enough funds. Use revert it will revert back the changes to previous changes.

Or try below method.

contract A {
function sendtoken() payable returns(bool) {
      require(msg.value!=0);
      owner.transfer(msg.value);
      balances[msg.sender]+= 1;
      balances[owner]-= 1;
      return true;
 }
}

Or another way

contract A {
function sendtoken() payable returns(bool) {
      require(msg.value!=0);
      require(owner.send(msg.value));
      balances[msg.sender]+= 1;
      balances[owner]-= 1;
      return true;
 }
}

Roll back my code to fix race conditions. For more details refer below link https://consensys.github.io/smart-contract-best-practices/known_attacks/

|improve this answer|||||
  • 1
    Careful with this, in both example of the receiving address is a contract, it could trigger code execution thereby allowing possible exploitation of the contract implementing this. You should ALWAYS do your accounting first. – hextet Feb 6 '18 at 10:33
  • There will be a issue as race condition qus. So I am modifying the same. check below link consensys.github.io/smart-contract-best-practices/known_attacks – Jitendra Kumar. Balla Feb 8 '18 at 5:57

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.