Search code examples
motoko

operator may trap for inferred type. Motoko Nat


I have written this simple Motoko code but when I deploy my canister I get a warning stating operator may trap for inferred type. Motoko Nat


    import Debug "mo:base/Debug";
    actor DBank {
      var currentValue = 300;
      currentValue := 100;
    
      public func topUp(amount: Nat) {
        currentValue += amount;
        Debug.print(debug_show(currentValue));
      };
    
      public func withdraw(amount:Nat) {
        let tempValue = currentValue - amount;
        if(tempValue>=0) {
          currentValue -= amount;
        Debug.print(debug_show(currentValue));
        } else {
          Debug.print("amount too large, not enough balance")
        }
        
      };
    }

I'm using the candid UI to call my function, my code is working fine but I can't get rid of the warning, can anyone help me, with how to remove the warning

in the image below the error is referring to the line :

let tempValue = currentValue - amount;

enter image description here


Solution

  • Since both operands to the subtraction currentValue - amount are of type Nat, the subtraction is performed at type Nat. That implies that the result would be out of bounds if it became negative, and you'd get a trap. The test on the next line would never be reached. So the warning is there for a reason. :)

    (Edit: FWIW, the warning actually reads "operator may trap for inferred type Nat", it's just wrapped around oddly in Candid UI.)

    I'd suggest changing the function to:

          public func withdraw(amount : Nat) {
            if (amount <= currentValue) {
              currentValue -= amount;
              Debug.print(debug_show(currentValue));
            } else {
              Debug.print("amount too large, not enough balance");
            }
          };
    

    Edit 2: The other solution would be to force the subtraction to be be performed at type Int by adding a type annotation:

    let tempValue : Int = currentValue - amount;