4

Let us suppose an item A costs 5 USD and I want to purchase this item with the equivalent SOL amount inside my solana program.

For robustness, I am fetching the price from within the program using an oracle, which e.g. gives me X.XX as f64.

  1. How would I go about safely computing the SOL item cost of dividing 5/X.XX inside my program?
  2. How many decimals do I have to worry about?

This is a bit tricky for me, since I would have use checked_div() but this function does not support f64.

1 Answer 1

4

Standard practice is to use a fix-pointed number with decimals. For example 5 USDC is usually expressed with 6 decimals, as 5,000,000. You would probably use a u64 to store this value. Note that oracles like Pyth have an "exponent" value that tells you how many decimals that asset uses. Most tokens use 6 or 8.

Another caveat is that when doing math like division, to preserve precision, you might cast both values to u128, then eventually convert back to u64 after your math is done. You should also generally do your multiplication before division, to avoid loss of precision.

On the front end, you simply divide by 10^decimals to get back your floating point value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.