0

How can I convert Ethereum uint256 variables into Solana Rust?

Should I use u64 and 9 decimals in Solana Rust instead of 18 decimals in Ethereum?

According to Solana's doc, a lamport has a value of 0.000000001 SOL. That is 9 decimals.

So it seems 9 decimals is the standard in Solana, in contrast to 18 decimals in Ethereum.

u64 in Rust has the maximum value of 18,446,744,073,709,551,615...

u128 in Rust has the maximum value of 2^128 - 1

Somehow Rust Solana does not have u256! Strange

and if I use 9 decimals for all calculations, then I should make sure 18,446,744,073 is big enough for all my Solana Rust u64 variables' maximum values, right? Is this the correct strategy? Thank you!

Yilmaz
  • 35,338
  • 10
  • 157
  • 202
Russo
  • 2,186
  • 2
  • 26
  • 42
  • 1
    Can't you use additional crates in your contracts? E.g. https://docs.rs/spl-math/0.1.0/spl_math/uint/struct.U256.html - for incoming ETH u256 you could check the bits to see if it can be represented by u128 - or for your u64, do `U256::bits() <= u64::BITS`. – Martin Gallagher Nov 23 '21 at 15:10
  • Hi Martin, thank you for your suggestion. please see my answer below – Russo Dec 13 '21 at 03:48

1 Answers1

2

I think we do not need additional library like uint256, because the Solana Program Library(their token library) is using u64 for amount to transfer https://github.com/solana-labs/solana-program-library/blob/master/token/program/src/processor.rs#L203

Also anchor_spl uses u64 in reading token balances https://docs.rs/anchor-spl/0.19.0/anchor_spl/token/accessor/fn.amount.html

Function anchor_spl::token::accessor::amount
pub fn amount(account: &AccountInfo<'_>) -> Result<u64, ProgramError>

uint128 in Rust is actually large enough.

uint128 has a range of 0 to 2^128 - 1, that is 0 ~ 340,282,366,920,938,463,463,374,607,431,768,211,455

with 9 decimals, uint128 will be large enough.

Russo
  • 2,186
  • 2
  • 26
  • 42