1

I have variable: TokenPriceWei = 2000 , that means I set 1 token price for 2000 Wei.

When I get msg.value , is it correct tokensAmount = (msg.value / TokenPriceWei) to get correct token Amount?

I'm wondering because i've seen some examples and none of them do that when calculating token /wei rate.

1

This is, in theory, correct, but remember that you cannot represent a decimal point in solidity.

if you send 3500wei the operation 3500/2000 = 1 and not 1.75. There are three solutions:

  1. Require this: require(msg.value%TokenPriceWei == 0), so people send the exact amount for an integer number of tokens. (not so friendly)

  2. Get the number of tokens as msg.value/TokenPriceWei and then return to the buyer this amount: msg.value % TokenPriceWei, which is the residual of the division in the example of 3500/2000 this is 1 token purchased and then 1500wei returned to the user.

  3. Use a multiplier to be able to represent decimal point indirectly.Include a variable decimals then:

    decimals = 10**3; // 3 is the number of decimal points, it can be anything you want, 18 is most used in tokens

    numberoftokens = (masg.value*decimals)/TokenPriceWei;

    Notice that this make a huge number of ERC20 tokens. Mist will use the variable decimals to correct the value when presenting it to the users.You need to remember this multiplier on anything that you do with the tokens, this is how most token contracts do it. For instance, in the example of 3500wei you will get: 3500*1000/2000 = 3500000/2000 = 1750 Mist will get that decimals is 1000 and will show that the user has 1.75 tokens.

Hope it helps.

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.