0

I'm trying to use 0x to buy tokens with ETH. I'm following the sample at https://0x.org/docs/guides/swap-tokens-with-0x-api#swap-eth-for-1-dai.

I got the token address, and the decimals. let's say USDC and 6. And let's say I want to buy 1 USDC. How do I calculate the value I need to pass to buyAmount? I tried several things: passing '1', passing '1000000' (1 and 6 0s). I tried 5 0s. When it hits MetaMask it's always the wrong amount: 10 or 100 etc. And the fee is crazy ($39 in gas to buy 10 USDC?).

It's even worse with other tokens and amounts. Can anyone clue me into how to use the decimals to translate the amount I want to buy to the amount I need to send to the quote endpoint?

1

Let's call the decimals a token has d and the amount you want to buy a. Then the value you are looking for can be calculated by a * 10^d.

Example: You want to buy 50 USDC (a = 50) and USDC has 6 decimals (d = 6). The amount is 50 * 10^6 = 50000000.

4
  • Great! Does this hold for float values as well? If I want to buy 10.675 USDC, it's 10.675*10^6? – Traveling Tech Guy Sep 11 '20 at 17:28
  • Didn't work - still shows 10x the value I've been trying to buy (i.e 1 USDC is 0.02 ETH == $10 in MetaMask, before gas fees). – Traveling Tech Guy Sep 11 '20 at 17:50
  • Yes, the whole point of this conversion is to avoid floats. So 10.675 USDC would be 10675000. Unfortunately I'm not sure why there is a problem with 0x as I have never used it. But the conversion is definitely correct. – Bobface Sep 12 '20 at 7:37
  • Thanks for your help! Had it figured out after chatting with someone from 0x. For the record, it was the slippage parameter in their API that added to the total. – Traveling Tech Guy Sep 12 '20 at 16:05

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.