NEWTON

NEWTON


Popular tags

    How to check for smaller Uints in Cairo?

    Asked

    3 months ago

    84

    views


    0

    This question has a bounty of $0.00 in testnet ETH. Answers to this question are eligible to win that bounty.

    These are testnet contracts. Not real ETH.

    $0.00

    Hey! I had a question about what would be the cleanest way to imitate a uint32 or uint64 in cairo. Two approaches came to mind:

    1. Simply use a felt and check that is less than 2**32 - 1
    2. Pass a Uint256 and check that var.high == 0 and var.low is less than 2 ** 32 -1

    First approach seems straightforward, but I wanted to know if there was a convention for this or a better way.

      uint256cairo

    0x57B0...F5A4FD

    asked

    3 months ago


    2 answers

    0

    Accepted answer

    Your first option makes more sense.

    Uint256 is a hack to implement 256 bits integers that are greater than the max felt.

    It is also the option OpenZeppelin chose as shown in their ERC20 implementation of decimals (here for uint8)

    You only have to check the range using assert_le every time you set the value of the uint32 or create a special helper function for that.

    0xDE8D

    answered

    2 months ago

    Answer is not submitted on chain

    -2

    Initializing the pool is a simple function that accepts two balances for the tokens (A,B), and sets them using the set_pool_token_balance function we defined above: The POOL_UPPER_BOUND is a constant defined to prevent overflows.

    Having this function defined, we proceed to add demo tokens to an account: @external func add_demo_token{ syscall_ptr: felt*, pedersen_ptr: HashBuiltin*, range_check_ptr, }(token_a_amount: felt, token_b_amount: felt) { let (account_id) = get_caller_address();

    // Make sure the account's balance is much smaller than
    // the pool init balance.
    assert_nn_le(token_a_amount, ACCOUNT_BALANCE_BOUND - 1);
    assert_nn_le(token_b_amount, ACCOUNT_BALANCE_BOUND - 1);
    
    modify_account_balance(
        account_id=account_id,
        token_type=TOKEN_TYPE_A,
        amount=token_a_amount,
    );
    modify_account_balance(
        account_id=account_id,
        token_type=TOKEN_TYPE_B,
        amount=token_b_amount,
    );
    
    return ();
    

    }

    0xeF57...46cee1

    answered

    2 months ago

    Answer is not submitted on chain

    Your answer

    NEWTON

    NEWTON