NethermindEth / warp

Warp - Bringing Solidity to Starknet at warp speed. Warp is a Solidity to Cairo Compiler, this allows teams to write/migrate Solidity to Cairo for easy onboarding into the StarkNet ecosystem.
https://nethermind.io/warp/
Apache License 2.0
754 stars 70 forks source link

Unsafe operations in unchecked blocks #1037

Closed esdras-santos closed 1 year ago

esdras-santos commented 1 year ago

This PR do three things: 1 - deal with unsafe operations inside unchecked blocks. 2 - remove unnecessary warplib functions and replace it for their respective operations. 3 - remove input checks.

given the following function:

function add(uint x, uint y) external pure returns (uint) {
    unchecked {
        return x + y;
    }
}

old transpilation:

#[view]
fn add_771602f7(__warp_0_x : u256, __warp_1_y : u256)-> u256{
    let __warp_se_0 = warp_add_unsafe256(__warp_0_x, __warp_1_y);
    return __warp_se_0;
}

new transpilation:

#[view]
fn add_771602f7(__warp_0_x : u256, __warp_1_y : u256)-> u256{
        let (__warp_se_0, overflow) = u256_overflowing_add(__warp_0_x, __warp_1_y);
        assert(overflow == false, 'Overflow in unchecked block');
        return __warp_se_0;
}

new transpilation for when the operation is bellow than 256 bits

#[view]
fn add_feb99390(__warp_0_x : u128, __warp_1_y : u128)-> u128{
        let (__warp_se_0, overflow) = matchu128_overflowing_add(__warp_0_x, __warp_1_y){
            Result::Ok(__warp_se_0) => (__warp_se_0, false),
            Result::Err(__warp_se_0) => (__warp_se_0, true),
        };
        assert(overflow == false, 'Overflow in unchecked block');
        return __warp_se_0;
}

In the case of an operation outside an unchecked block like the following:

function add(uint8 x, uint8 y)public returns(uint8){
        return x + y;
}

old transpilation:

------------imports---------------
use warplib::maths::add::warp_add8;
use warplib::maths::external_input_check_ints::warp_external_input_check_int8;

--------------------------------------

#[external]
fn add_bb4e3f4d(__warp_0_x : felt252, __warp_1_y : felt252)-> felt252{

    warp_external_input_check_int8(__warp_1_y);

    warp_external_input_check_int8(__warp_0_x);

    let __warp_se_0 = warp_add8(__warp_0_x, __warp_1_y);

    return __warp_se_0;
}

new transpilation:

------------No warplib imports-------------------------

#[external]
fn add_bb4e3f4d(__warp_0_x : felt252, __warp_1_y : felt252)-> felt252{

    return __warp_0_x + __warp_1_y;
}
piwonskp commented 1 year ago

Please fix merge conflicts