4

In the classic flipper ink! sc example I tried within a function

let dist2: f32 = f32::sqrt(4.0);

and got the error " function or associated item not found in f32 "

Bearing in mind this https://doc.rust-lang.org/std/primitive.f32.html#method.sqrt and failing that, after installing and trying this https://crates.io/crates/sp-arithmetic that I found here What's the best way to compute square root in Substrate? but creates conflicts and fails to compile flipper.

I am puzzled of how to proceed. Any suggestions please?

3 Answers 3

6

Issue is now resolved. As suggested by Phala team adding the following in the Cargo.toml

[dependencies] 
... 
sp-arithmetic = { version = "15", default-features = false }

[features] 
std = [ 
... 
"sp-arithmetic/std"
]

And

    [profile.release] 
    overflow-checks = false

And following this post Ink! smart contract struct field issues for necessary type conversions

Flipper now runs fine

   use scale::CompactAs; 
   use sp_arithmetic::FixedU128; 

   #[ink(message)] 
   pub fn get_squareroot(&self, num: u32) -> u128 {  
       let d1 = FixedU128::from_u32(num);  
       let d2 = FixedU128::sqrt(d1); 
       let d3 = *d2.encode_as();
       d3 
    }
1
  • i need to calculate percentage but having no support for float it is quite restrictive how to i solve it ?
    – rahul
    Commented Apr 6, 2023 at 11:41
2

ink! smart contract doesn't support f32 type. You can get more info from here

1
  • I am trying to calculate the distance of 2 point coordinates on the screen, something quite common for most game development Not knowing an alternative solution I am trying to use sp_arithmetic::fixed_point::FixedU64::sqrt from crates.io/crates/sp-arithmetic Even when I simply install the crate to a vanilla Flipper sc classic example the Flipper no longer compiles
    – Sokrates
    Commented Mar 31, 2023 at 6:25
-1

`use ink_lang::contract;

#[contract] mod sqrt_contract { #[ink(storage)] pub struct SqrtContract {}

impl SqrtContract {
    #[ink(constructor)]
    pub fn new() -> Self {
        Self {}
    }

    #[ink(message)]
    pub fn calculate_sqrt(&self, num: u64) -> u64 {
        ink_core::math::sqrt(num)
    }
}

}`

Keep in mind that Ink! is a statically-typed language, so you'll need to specify the data type of the input and output values. Also note that the sqrt function may not be available in all versions of Ink!, so make sure to check the documentation for your specific version.

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.