1

I have my contract and people can buy my tokens via web3 and MetaMask. Now when I try to execute sell() function throw an exception and always Etherscan says Failed.

I set to sell and buy prices on my contract.

Here is my sell function:

/// @notice Sell `amount` tokens to contract
/// @param amount amount of tokens to be sold
function sell(uint256 amount) public {
    require(address(this).balance >= amount * sellPrice);      // checks if the contract has enough ether to buy
    _transfer(msg.sender, this, amount);              // makes the transfers
    msg.sender.transfer(amount * sellPrice);          // sends ether to the seller. It's important to do this last to avoid recursion attacks
}

I don't know what more I have to do. Does someone have any idea to help me?

UPDATE: Full code: https://pastebin.com/eBYC77GV.

UPDATE2: Etherscan Report: https://etherscan.io/tx/0x1213ca9540b8b7c0bd34f09dac906906772416a31e3b01559d0c0a3c05582a19

Thanks.

2
  • What is the value of sellPrice? Apr 3 '18 at 19:47
  • With the little informations we have, I guess you maybe set a wrong sellPrice. 1000000000000000 * sellPrice being superior to the balance. Apr 3 '18 at 19:55
1

If your sell price value is scaled up ie amount * (sellPrice * (10**18)) then you'll have a massively large value, so you'll need to divide the result by 10**18. Say for example sellPrice is meant to be 100 tokens in units of wei, tha would be 100 * (10**18). If you pass in a value for amount that is also in units of wei, you'll have an even larger number:

(amount * (10**18)) * (sellPrice * (10**18))

You have a few options here, you can either set sellPrice to not be scaled up to units of wei 100, not 100 * (10**18). Or if you prefer to keep everything in units of wei, you can simply divide your final result by 10**18. Alternatively, you can keep sellPrice in units of wei, and what you pass in for amount don't convert to units of u

4
  • 1
    You say something like this?: amount * (sellPrice * 10 ** 18) / 10**18
    – Francisco
    Apr 3 '18 at 20:43
  • Yup you've got it!
    – hextet
    Apr 3 '18 at 20:52
  • Its working! Thank you! But I have a bug when I put 1 on the amount the contract discount from my account 0.001 and not 1 token. Any idea?
    – Francisco
    Apr 3 '18 at 22:50
  • No problem! Try passing in 100 I suspect that would fix that issue. However it sounds like you might be dividing an extra time since you end up with 0.001 instead of 1
    – hextet
    Apr 4 '18 at 2:33

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.